blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 4
410
| content_id
stringlengths 40
40
| detected_licenses
sequencelengths 0
51
| license_type
stringclasses 2
values | repo_name
stringlengths 5
132
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringlengths 4
80
| visit_date
timestamp[us] | revision_date
timestamp[us] | committer_date
timestamp[us] | github_id
int64 5.85k
689M
⌀ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 22
values | gha_event_created_at
timestamp[us] | gha_created_at
timestamp[us] | gha_language
stringclasses 131
values | src_encoding
stringclasses 34
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 2
classes | length_bytes
int64 3
9.45M
| extension
stringclasses 32
values | content
stringlengths 3
9.45M
| authors
sequencelengths 1
1
| author_id
stringlengths 0
313
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ced8f2060050a4eac387b3b19be68c0c6cf4c8e7 | cc53f7685325c016cc07ca2d1997a0fd302a146a | /src/test/java/AlbumTest.java | 4af8e79d9321625559f70e05a16312de5971e12d | [] | no_license | slbrtg/rotten-peaches-spark | 107bc6f3da5a3f1fc0bf6b70e22f990ff51adaff | 0a47e95c0f36cccd9c993465e61f383e37106a0f | refs/heads/master | 2020-06-27T13:15:45.379911 | 2017-07-13T23:44:47 | 2017-07-13T23:44:47 | 97,059,262 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,297 | java | import org.sql2o.*;
import org.junit.*;
import static org.junit.Assert.*;
import java.util.*;
public class AlbumTest {
@Rule
public DatabaseRule database = new DatabaseRule();
@Test
public void Album_instantiatesCorrectly_true() {
Album testAlbum = new Album("OK Computer", 1997, "indie rock", 1);
assertEquals(true, testAlbum instanceof Album);
}
@Test
public void getName_retrievesAlbumName_OKComputer() {
Album testAlbum = new Album("OK Computer", 1997, "indie rock", 1);
assertEquals("OK Computer", testAlbum.getName());
}
@Test
public void getId_instantiatesWithAnId_true() {
Album testAlbum = new Album("OK Computer", 1997, "indie rock", 1);
testAlbum.save();
assertTrue(testAlbum.getId() > 0);
}
@Test
public void all_retrievesAllInstancesOfAlbum_true() {
Album testAlbum = new Album("King Of Limbs", 1997, "indie rock", 1);
testAlbum.save();
Album testAlbum2 = new Album("In Rainbows", 1997, "indie rock", 2);
testAlbum2.save();
assertEquals(true, Album.all().get(0).equals(testAlbum));
assertEquals(true, Album.all().get(1).equals(testAlbum2));
}
@Test
public void find_returnAlbumWIthSameId_testAlbum2() {
Album testAlbum = new Album("King Of Limbs", 1997, "indie rock", 1);
testAlbum.save();
Album testAlbum2 = new Album("In Rainbows", 1997, "indie rock", 2);
testAlbum2.save();
assertEquals(Album.find(testAlbum2.getId()), testAlbum2);
}
@Test
public void updateName_updatesAlbumName_PabloHoney() {
Album testAlbum = new Album("King Of Limbs", 1997, "indie rock", 1);
testAlbum.save();
testAlbum.updateName("Pablo Honey");
assertEquals("Pablo Honey", Album.find(testAlbum.getId()).getName());
}
@Test
public void updateReleaseYear_updatesAlbumReleaseYear_1993() {
Album testAlbum = new Album("King Of Limbs", 1997, "indie rock", 1);
testAlbum.save();
testAlbum.updateReleaseYear(1993);
assertEquals(1993, Album.find(testAlbum.getId()).getReleaseYear());
}
@Test
public void delete_deletesAnAlbum_true() {
Album testAlbum2 = new Album("In Rainbows", 1997, "indie rock", 2);
testAlbum2.save();
int testAlbumId = testAlbum2.getId();
testAlbum2.delete();
assertEquals(null, Album.find(testAlbumId));
}
}
| [
"sowmya@"
] | sowmya@ |
b7ff8a9b8acd3a0abda0cc6e97ad9d353d8a7e44 | 99c03face59ec13af5da080568d793e8aad8af81 | /hom_classifier/2om_classifier/scratch/AOIS90AOIS9/Pawn.java | 0eaaa9bf50b6b060b92da2ca1cdcb7656e14cf5a | [] | no_license | fouticus/HOMClassifier | 62e5628e4179e83e5df6ef350a907dbf69f85d4b | 13b9b432e98acd32ae962cbc45d2f28be9711a68 | refs/heads/master | 2021-01-23T11:33:48.114621 | 2020-05-13T18:46:44 | 2020-05-13T18:46:44 | 93,126,040 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,761 | java | // This is a mutant program.
// Author : ysma
import java.util.ArrayList;
public class Pawn extends ChessPiece
{
public Pawn( ChessBoard board, ChessPiece.Color color )
{
super( board, color );
}
public java.lang.String toString()
{
if (color == ChessPiece.Color.WHITE) {
return "♙";
} else {
return "♟";
}
}
public java.util.ArrayList<String> legalMoves()
{
java.util.ArrayList<String> returnList = new java.util.ArrayList<String>();
if (this.getColor().equals( ChessPiece.Color.WHITE )) {
int currentCol = this.getColumn();
int nextRow = this.getRow() + 1;
if (nextRow <= 7) {
if (board.getPiece( onePossibleMove( nextRow, ++currentCol ) ) == null) {
returnList.add( onePossibleMove( nextRow, currentCol ) );
}
}
if (this.getRow() == 1) {
int nextNextRow = this.getRow() + 2;
if (board.getPiece( onePossibleMove( nextRow, currentCol ) ) == null && board.getPiece( onePossibleMove( nextNextRow, currentCol ) ) == null) {
returnList.add( onePossibleMove( nextNextRow, currentCol ) );
}
}
int leftColumn = currentCol - 1;
int rightColumn = currentCol + 1;
if (leftColumn >= 0) {
if (board.getPiece( onePossibleMove( nextRow, leftColumn ) ) != null) {
if (!board.getPiece( onePossibleMove( nextRow, leftColumn ) ).getColor().equals( this.getColor() )) {
returnList.add( onePossibleMove( nextRow, leftColumn ) );
}
}
}
if (rightColumn <= 7) {
if (board.getPiece( onePossibleMove( nextRow, rightColumn ) ) != null) {
if (!board.getPiece( onePossibleMove( nextRow, rightColumn ) ).getColor().equals( this.getColor() )) {
returnList.add( onePossibleMove( nextRow, rightColumn ) );
}
}
}
} else {
int currentCol = this.getColumn();
int nextRow = this.getRow() - 1;
if (nextRow >= 0) {
if (board.getPiece( onePossibleMove( nextRow, currentCol ) ) == null) {
returnList.add( onePossibleMove( nextRow--, currentCol ) );
}
}
if (this.getRow() == 6) {
int nextNextRow = this.getRow() - 2;
if (board.getPiece( onePossibleMove( nextRow, currentCol ) ) == null && board.getPiece( onePossibleMove( nextNextRow, currentCol ) ) == null) {
returnList.add( onePossibleMove( nextNextRow, currentCol ) );
}
}
int leftColumn = currentCol - 1;
int rightColumn = currentCol + 1;
if (leftColumn >= 0) {
if (board.getPiece( onePossibleMove( nextRow, leftColumn ) ) != null) {
if (!board.getPiece( onePossibleMove( nextRow, leftColumn ) ).getColor().equals( this.getColor() )) {
returnList.add( onePossibleMove( nextRow, leftColumn ) );
}
}
}
if (rightColumn <= 7) {
if (board.getPiece( onePossibleMove( nextRow, rightColumn ) ) != null) {
if (!board.getPiece( onePossibleMove( nextRow, rightColumn ) ).getColor().equals( this.getColor() )) {
returnList.add( onePossibleMove( nextRow, rightColumn ) );
}
}
}
}
return returnList;
}
} | [
"[email protected]"
] | |
fb64b815d5766bb477bdb7c395b966464176326b | 51e0883ba6ba3faed7dad80fb7c8826051b2b251 | /src/main/java/org/example/simplehttpserver/config/Configuration.java | 886c06abbf57edc6465f69826f72dee981431e0e | [] | no_license | samyum918/simplehttpserver | f480325b983da44d8f9ef298f60526606c6673c4 | d2bbb5f24437d3196f4862c7024614fa1687e671 | refs/heads/master | 2023-01-19T12:55:52.110420 | 2020-11-29T15:20:22 | 2020-11-29T15:20:22 | 316,453,120 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 192 | java | package org.example.simplehttpserver.config;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class Configuration {
private Integer port;
private String webroot;
}
| [
"[email protected]"
] | |
75e1ecdb3fea83d12cf535c6ec8b86e51eab8257 | 83a5dd42ec8ab543d0d9e588d15d6d88df8e8aab | /CineOnline/CineOnline-ejb/src/java/model/factories/AwardFacadeLocal.java | d3b349dbe26989e1fb2a04444b05bb4f53292bcc | [] | no_license | AleKrabbe/CineOnline | 8e8374b24d28ed92907d7d0daeab1c00064becc4 | b4c718a5a173e27a63b074b172b6ec2e787f937f | refs/heads/master | 2020-04-07T00:33:59.743600 | 2018-12-06T04:23:59 | 2018-12-06T04:23:59 | 157,909,083 | 1 | 0 | null | 2018-11-20T20:32:00 | 2018-11-16T18:55:41 | Java | UTF-8 | Java | false | false | 583 | java | /*
* 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 model.factories;
import java.util.List;
import javax.ejb.Local;
import model.entities.Award;
/**
*
* @author Alexandre Krabbe
*/
@Local
public interface AwardFacadeLocal {
void create(Award award);
void edit(Award award);
void remove(Award award);
Award find(Object id);
List<Award> findAll();
List<Award> findRange(int[] range);
int count();
}
| [
"[email protected]"
] | |
9e633f2684b6043a9483ed6894f897a99b218a0a | 94e10d222730dbc7925fe44c38d2eba8f1f19eea | /app/src/main/java/com/txunda/construction_worker/utils/ShareForApp.java | a6838e9c09318b1ce5a84b99bbd0dfe18f58919f | [] | no_license | Qsrx/construction_worker | 3293cfb6322e3052c941b0d2411ac7c17f69d796 | 7f2103cbc35bec551f87f7dc5266d46dc7991f5a | refs/heads/master | 2020-04-29T01:36:26.626064 | 2019-03-26T03:27:34 | 2019-03-26T03:27:34 | 175,736,253 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 15,247 | java | package com.txunda.construction_worker.utils;
import android.graphics.Bitmap;
import android.util.Log;
import com.zhy.http.okhttp.utils.L;
import java.util.HashMap;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.tencent.qq.QQ;
import cn.sharesdk.wechat.friends.Wechat;
import cn.sharesdk.wechat.moments.WechatMoments;
/**
* ===============Txunda===============
* 作者:DUKE_HwangZj
* 日期:2017/6/30 0030
* 时间:下午 4:49
* 描述:分享
* ===============Txunda===============
*/
public class ShareForApp implements PlatformActionListener {
// /**
// * 分享平台
// */
// public enum PlatformForShare {
// QQ, Qzon, Sine, Wechat, WechatMoments, FACEBOOK, WHATSAPP, INSRAGRAM, SinaWeibo
// }
//
// /**
// * 分享之后的状态
// */
// public enum StatusForShare {
// Success, Error, Cancel
// }
//
// /**
// * 分享平台的名称
// */
// private String platFormName;
// /**
// * 分享的图片
// */
// private Bitmap bitmap;
// /**
// * 图片链接
// */
// private String picUrl;
//
// /**
// * 标题
// */
// private String title;
// /**
// * 分享文本
// */
// private String text;
// /**
// * 标题链接
// */
// private String titleUrl;
//
// private ShareBeBackListener shareBeBackListener;
//
// /**
// * 够造函数
// *
// * @param platFormName 平台名称
// * @param bitmap 分享的图片
// * @param title 标题
// * @param text 文本
// * @param titleUrl 标题连接
// */
// public ShareForApp(String platFormName, Bitmap bitmap, String title, String text, String titleUrl,
// ShareBeBackListener shareBeBackListener) {
// this.platFormName = platFormName;
// this.bitmap = bitmap;
// this.title = title;
// this.text = text;
// this.titleUrl = titleUrl;
// this.shareBeBackListener = shareBeBackListener;
// }
//
// public ShareForApp(String platFormName, String picUrl, String title, String text, String titleUrl,
// ShareBeBackListener shareBeBackListener) {
// this.platFormName = platFormName;
// this.picUrl = picUrl;
// this.title = title;
// this.text = text;
// this.titleUrl = titleUrl;
// this.shareBeBackListener = shareBeBackListener;
// }
//
//
// public void toShare() {
// Platform.ShareParams sp = new Platform.ShareParams();
// sp.setTitle(title);
// sp.setText(text);// 分享文本
//
// if (platFormName.equals(Wechat.NAME)) {
// sp.setUrl(titleUrl);
// }
//// else if (platFormName.equals(SinaWeibo.NAME) || platFormName.equals(QQ.NAME)) {
//// sp.setTitleUrl(titleUrl);
//// }
// sp.setImageData(bitmap);
// // 3、非常重要:获取平台对象
// Platform wechathy = ShareSDK.getPlatform(platFormName);
// wechathy.setPlatformActionListener(this); // 设置分享事件回调
// // 执行分享
// wechathy.share(sp);
// Log.d("zdl", "toShare: 分享");
// }
//
// // SHARE_WEBPAGE 分享网页
//// SHARE_TEXT 分享文本
//// SHARE_IMAGE 分享图片
// public void toShareWithPicUrl() {
// Platform.ShareParams sp = new Platform.ShareParams();
// if (platFormName.equals(Wechat.NAME)) {// 微信
//// if (type == 1) {
//// sp.setShareType(Platform.SHARE_WEBPAGE);//分享网页
//// sp.setImageUrl(picUrl);
//// sp.setUrl(titleUrl);
//// }else if (type == 3){
////
//// } else if (type == 4){
//// sp.setShareType(Platform.SHARE_IMAGE);//分享图片
//// sp.setImagePath(picUrl);
//// }
//// sp.setShareType(Platform.SHARE_IMAGE);//分享图片
//// sp.setImageData(bitmap);
// sp.setShareType(Platform.SHARE_WEBPAGE);//分享网页
// sp.setImageUrl(picUrl);
//// sp.setShareType(Platform.SHARE_IMAGE);//分享图片
//// sp.setImageData(bitmap);
// sp.setTitleUrl(titleUrl);
// }
// else if (platFormName.equals(QQ.NAME)) {// QQ
//// if (type == 1) {
// sp.setShareType(Platform.SHARE_WEBPAGE);//分享网页
// sp.setImageUrl(picUrl);
//// } else if (type == 3){
////
//// sp.setImageUrl(picUrl);
//// } else if (type == 4){
//// sp.setShareType(Platform.SHARE_IMAGE);//分享图片
//// sp.setImagePath(picUrl);
//// }
//// sp.setShareType(Platform.SHARE_IMAGE);//分享图片
//// sp.setImageData(bitmap);
// sp.setTitleUrl(titleUrl);
// } else if (platFormName.equals(WechatMoments.NAME)) {//朋友圈
// sp.setShareType(Platform.SHARE_WEBPAGE);//分享网页
// sp.setImageUrl(picUrl);
//// sp.setShareType(Platform.SHARE_IMAGE);//分享图片
//// sp.setImageData(bitmap);
// sp.setTitleUrl(titleUrl);
// }
// sp.setTitle(title);
// sp.setText(text);// 分享文本
// // 3、非常重要:获取平台对象
// Platform wechathy = ShareSDK.getPlatform(platFormName);
// wechathy.setPlatformActionListener(this); // 设置分享事件回调
// // 执行分享
// wechathy.share(sp);
// L.e("分享");
// }
//
// @Override
// public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
// Log.e("=====成功=====", hashMap.toString());
//// if (platform.getName().equals(SinaWeibo.NAME)) {// 微博
//// shareBeBackListener.beBack(SinaWeibo, StatusForShare.Success, i);
//// } else
// if (platform.getName().equals(Wechat.NAME)) {// 微信
// shareBeBackListener.beBack(PlatformForShare.Wechat, StatusForShare.Success, i);
// } else if (platform.getName().equals(QQ.NAME)) {// QQ
// shareBeBackListener.beBack(PlatformForShare.QQ, StatusForShare.Success, i);
// } else if (platform.getName().equals(WechatMoments.NAME)) {
// shareBeBackListener.beBack(PlatformForShare.WechatMoments, StatusForShare.Success, i);
// }
// }
//
// @Override
// public void onError(Platform platform, int i, Throwable throwable) {
// Log.e("=====失败====", String.valueOf(i) + "=====" + throwable.getMessage());
//// if (platform.getName().equals(SinaWeibo.NAME)) {// 微博
//// shareBeBackListener.beBack(SinaWeibo, StatusForShare.Error, i);
//// } else
// if (platform.getName().equals(Wechat.NAME)) {// 微信
// shareBeBackListener.beBack(PlatformForShare.Wechat, StatusForShare.Error, i);
// } else if (platform.getName().equals(QQ.NAME)) {// QQ
// shareBeBackListener.beBack(PlatformForShare.QQ, StatusForShare.Error, i);
// } else if (platform.getName().equals(WechatMoments.NAME)) {
// shareBeBackListener.beBack(PlatformForShare.WechatMoments, StatusForShare.Error, i);
// }
// }
//
// @Override
// public void onCancel(Platform platform, int i) {
// Log.e("=====取消====", String.valueOf(i));
//// if (platform.getName().equals(SinaWeibo.NAME)) {// 微博
//// shareBeBackListener.beBack(SinaWeibo, StatusForShare.Cancel, i);
//// } else
// if (platform.getName().equals(Wechat.NAME)) {// 微信
// shareBeBackListener.beBack(PlatformForShare.Wechat, StatusForShare.Cancel, i);
// } else if (platform.getName().equals(QQ.NAME)) {// QQ
// shareBeBackListener.beBack(PlatformForShare.QQ, StatusForShare.Cancel, i);
// } else if (platform.getName().equals(WechatMoments.NAME)) {//微信朋友圈
// shareBeBackListener.beBack(PlatformForShare.WechatMoments, StatusForShare.Cancel, i);
// }
// }
/**
* 分享平台
*/
public enum PlatformForShare {
QQ, Qzon, Sine, Wechat, WechatMoments, FACEBOOK, WHATSAPP, INSRAGRAM, SinaWeibo
}
/**
* 分享之后的状态
*/
public enum StatusForShare {
Success, Error, Cancel
}
/**
* 分享平台的名称
*/
private String platFormName;
/**
* 分享的图片
*/
private Bitmap bitmap;
/**
* 图片链接
*/
private String picUrl;
/**
* 标题
*/
private String title;
/**
* 分享文本
*/
private String text;
/**
* 标题链接
*/
private String titleUrl;
private ShareBeBackListener shareBeBackListener;
/**
* 够造函数
*
* @param platFormName 平台名称
* @param bitmap 分享的图片
* @param title 标题
* @param text 文本
* @param titleUrl 标题连接
*/
public ShareForApp(String platFormName, Bitmap bitmap, String title, String text, String titleUrl,
ShareBeBackListener shareBeBackListener) {
this.platFormName = platFormName;
this.bitmap = bitmap;
this.title = title;
this.text = text;
this.titleUrl = titleUrl;
this.shareBeBackListener = shareBeBackListener;
}
public ShareForApp(String platFormName, String picUrl, String title, String text, String titleUrl,
ShareBeBackListener shareBeBackListener) {
this.platFormName = platFormName;
this.picUrl = picUrl;
this.title = title;
this.text = text;
this.titleUrl = titleUrl;
this.shareBeBackListener = shareBeBackListener;
}
public void toShare() {
Platform.ShareParams sp = new Platform.ShareParams();
sp.setTitle(title);
sp.setText(text);// 分享文本
if (platFormName.equals(Wechat.NAME)) {
sp.setUrl(titleUrl);
} else if (platFormName.equals(QQ.NAME)) {
sp.setTitleUrl(titleUrl);
}
sp.setImageData(bitmap);
// 3、非常重要:获取平台对象
Platform wechathy = ShareSDK.getPlatform(platFormName);
wechathy.setPlatformActionListener(this); // 设置分享事件回调
// 执行分享
wechathy.share(sp);
Log.d("zdl", "toShare: 分享");
}
// SHARE_WEBPAGE 分享网页
// SHARE_TEXT 分享文本
// SHARE_IMAGE 分享图片
public void toShareWithPicUrl(int type) {
Platform.ShareParams sp = new Platform.ShareParams();
if (platFormName.equals(Wechat.NAME)) {// 微信
if (type == 1) {
sp.setShareType(Platform.SHARE_WEBPAGE);//分享网页
sp.setImageUrl(picUrl);
sp.setUrl(titleUrl);
}else if (type == 3){
sp.setShareType(Platform.SHARE_IMAGE);//分享图片
sp.setImageUrl(picUrl);
} else if (type == 4){
sp.setShareType(Platform.SHARE_IMAGE);//分享图片
sp.setImagePath(picUrl);
}
} else if (platFormName.equals(QQ.NAME)) {// QQ
if (type == 1) {
sp.setShareType(Platform.SHARE_WEBPAGE);//分享网页
sp.setImageUrl(picUrl);
} else if (type == 3){
sp.setShareType(Platform.SHARE_IMAGE);//分享图片
sp.setImageUrl(picUrl);
} else if (type == 4){
sp.setShareType(Platform.SHARE_IMAGE);//分享图片
sp.setImagePath(picUrl);
}
sp.setTitleUrl(titleUrl);
} else if (platFormName.equals(WechatMoments.NAME)) {//朋友圈
if (type == 1) {
sp.setShareType(Platform.SHARE_WEBPAGE);//分享网页
sp.setImageUrl(picUrl);
} else if (type == 3){
sp.setShareType(Platform.SHARE_IMAGE);//分享图片
sp.setImageUrl(picUrl);
} else if (type == 4){
sp.setShareType(Platform.SHARE_IMAGE);//分享图片
sp.setImagePath(picUrl);
}
sp.setTitleUrl(titleUrl);
} else {
if (type == 1) {
sp.setShareType(Platform.SHARE_WEBPAGE);//分享网页
sp.setImageUrl(picUrl);
} else if (type == 3){
sp.setShareType(Platform.SHARE_IMAGE);//分享图片
sp.setImageUrl(picUrl);
} else if (type == 4){
sp.setShareType(Platform.SHARE_IMAGE);//分享图片
sp.setImagePath(picUrl);
}
sp.setTitleUrl(titleUrl);
}
sp.setTitle(title);
sp.setText(text);// 分享文本
// 3、非常重要:获取平台对象
Platform wechathy = ShareSDK.getPlatform(platFormName);
wechathy.setPlatformActionListener(this); // 设置分享事件回调
// 执行分享
wechathy.share(sp);
L.e("分享");
}
@Override
public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
Log.e("=====成功=====", hashMap.toString());
if (platform.getName().equals(Wechat.NAME)) {// 微信
shareBeBackListener.beBack(PlatformForShare.Wechat, StatusForShare.Success, i);
} else if (platform.getName().equals(QQ.NAME)) {// QQ
shareBeBackListener.beBack(PlatformForShare.QQ, StatusForShare.Success, i);
} else if (platform.getName().equals(WechatMoments.NAME)) {
shareBeBackListener.beBack(PlatformForShare.WechatMoments, StatusForShare.Success, i);
}
}
@Override
public void onError(Platform platform, int i, Throwable throwable) {
Log.e("=====失败====", String.valueOf(i) + "=====" + throwable.getMessage());
if (platform.getName().equals(Wechat.NAME)) {// 微信
shareBeBackListener.beBack(PlatformForShare.Wechat, StatusForShare.Error, i);
} else if (platform.getName().equals(QQ.NAME)) {// QQ
shareBeBackListener.beBack(PlatformForShare.QQ, StatusForShare.Error, i);
} else if (platform.getName().equals(WechatMoments.NAME)) {
shareBeBackListener.beBack(PlatformForShare.WechatMoments, StatusForShare.Error, i);
}
}
@Override
public void onCancel(Platform platform, int i) {
Log.e("=====取消====", String.valueOf(i));
if (platform.getName().equals(Wechat.NAME)) {// 微信
shareBeBackListener.beBack(PlatformForShare.Wechat, StatusForShare.Cancel, i);
} else if (platform.getName().equals(QQ.NAME)) {// QQ
shareBeBackListener.beBack(PlatformForShare.QQ, StatusForShare.Cancel, i);
} else if (platform.getName().equals(WechatMoments.NAME)) {//微信朋友圈
shareBeBackListener.beBack(PlatformForShare.WechatMoments, StatusForShare.Cancel, i);
}
}
} | [
"””浮“[email protected]"
] | |
a8c4ef49ecd85ad69cf44b31b9b203dc9bcaacbf | 25ac334bb00a50245223eaa1bd3d6ca2968ae182 | /android/app/src/main/java/com/jinjerkeihi/nfcfelica/transit/Station.java | dc53b2eb8c4ea46650ecff84d127ae5221d929b9 | [] | no_license | buixuanthe2212/reduxThunk | 2e3c66bfb15f6d883ced6eebab673c04f3f207bb | 7fa8793c027a21815bd37e6f19195b71aab21168 | refs/heads/master | 2020-03-18T14:13:22.646564 | 2018-05-25T09:53:54 | 2018-05-25T09:53:54 | 134,836,725 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,987 | java | /*
* Station.java
*
* Copyright (C) 2011 Eric Butler <[email protected]>
*
* 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.jinjerkeihi.nfcfelica.transit;
import android.os.Parcel;
import android.os.Parcelable;
public class Station implements Parcelable {
public static final Creator<Station> CREATOR = new Creator<Station>() {
public Station createFromParcel(Parcel parcel) {
return new Station(parcel);
}
public Station[] newArray(int size) {
return new Station[size];
}
};
protected final String mCompanyName, mLineName, mStationName, mShortStationName, mLatitude, mLongitude, mLanguage;
public Station(String stationName, String latitude, String longitude) {
this(stationName, null, latitude, longitude);
}
public Station(String stationName, String shortStationName, String latitude, String longitude) {
this(null, null, stationName, shortStationName, latitude, longitude);
}
public Station(String companyName, String lineName, String stationName, String shortStationName, String latitude, String longitude) {
this(companyName, lineName, stationName, shortStationName, latitude, longitude, null);
}
public Station(String companyName, String lineName, String stationName, String shortStationName, String latitude, String longitude, String language) {
mCompanyName = companyName;
mLineName = lineName;
mStationName = stationName;
mShortStationName = shortStationName;
mLatitude = latitude;
mLongitude = longitude;
mLanguage = language;
}
protected Station(Parcel parcel) {
mCompanyName = parcel.readString();
mLineName = parcel.readString();
mStationName = parcel.readString();
mShortStationName = parcel.readString();
mLatitude = parcel.readString();
mLongitude = parcel.readString();
mLanguage = parcel.readString();
}
public String getStationName() {
return mStationName;
}
public String getShortStationName() {
return (mShortStationName != null) ? mShortStationName : mStationName;
}
public String getCompanyName() {
return mCompanyName;
}
public String getLineName() {
return mLineName;
}
public String getLatitude() {
return mLatitude;
}
public String getLongitude() {
return mLongitude;
}
/**
* Language that the station line name and station name are written in. If null, then use
* the system locale instead.
*
* https://developer.android.com/reference/java/util/Locale.html#forLanguageTag(java.lang.String)
*/
public String getLanguage() {
return mLanguage;
}
public boolean hasLocation() {
return getLatitude() != null && !getLatitude().isEmpty()
&& getLongitude() != null && !getLongitude().isEmpty();
}
public int describeContents() {
return 0;
}
public void writeToParcel(Parcel parcel, int flags) {
parcel.writeString(mCompanyName);
parcel.writeString(mLineName);
parcel.writeString(mStationName);
parcel.writeString(mShortStationName);
parcel.writeString(mLatitude);
parcel.writeString(mLongitude);
parcel.writeString(mLanguage);
}
}
| [
"[email protected]"
] | |
7674dd0c711fa9aedce42c32d7f59c933350214e | d179c3a428566e4dccf5f55bdd2d812f7d5bc833 | /src/main/java/org/sejda/sambox/rendering/RenderDestination.java | 9e6b63b691b79316d580d4535755bf8441f154c3 | [
"Apache-2.0",
"LicenseRef-scancode-apple-excl",
"BSD-3-Clause",
"APAFML"
] | permissive | torakiki/sambox | ea82fb22583f7e5f316c740a632d5c1891e5d067 | c8a6d26aa0b133130a90df104e3bb267ff13a19f | refs/heads/master | 2023-08-10T12:17:25.490810 | 2023-08-01T15:30:51 | 2023-08-01T15:30:51 | 30,909,947 | 48 | 16 | Apache-2.0 | 2023-08-01T15:08:27 | 2015-02-17T09:14:01 | Java | UTF-8 | Java | false | false | 1,053 | java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.sejda.sambox.rendering;
/**
* Optional content groups are visible depending on the render purpose.
*/
public enum RenderDestination
{
/** graphics export */
EXPORT,
/** viewing */
VIEW,
/** printing */
PRINT
}
| [
"[email protected]"
] | |
9b51c7df25e53508c790dbdd7fe2454d4647dcd6 | aba1234b5e243116bf5e7433c9e428ede1a0c924 | /src/main/java/com/brandongossen/bodg/clientmanager/controllers/UsersController.java | adef600177524828e119af5b3d8e30f1ade8b004 | [] | no_license | Brandon-Travis-BodG/bod-g-client-relationships | dbc3d7a039ee56ccefbf9e90373d271fe1819df9 | 1d9ec15202c642a3422d9ef4a6551c494f92cbc7 | refs/heads/master | 2021-09-15T08:13:39.758940 | 2018-05-22T06:18:13 | 2018-05-22T06:18:13 | 116,068,346 | 0 | 0 | null | 2018-05-29T00:41:02 | 2018-01-02T23:32:48 | Java | UTF-8 | Java | false | false | 3,150 | java | package com.brandongossen.bodg.clientmanager.controllers;
import com.brandongossen.bodg.clientmanager.models.Gender;
import com.brandongossen.bodg.clientmanager.models.GenderConverter;
import com.brandongossen.bodg.clientmanager.models.User;
import com.brandongossen.bodg.clientmanager.repositories.UsersRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.Errors;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import javax.validation.Valid;
@Controller
public class UsersController {
private UsersRepository usersDao;
private PasswordEncoder passwordEncoder;
public UsersController(UsersRepository usersDao, PasswordEncoder passwordEncoder) {
this.usersDao = usersDao;this.passwordEncoder = passwordEncoder;
}
@GetMapping("/register")
public String showRegistrationForm(Model viewModel) {
viewModel.addAttribute("user", new User());
return "users/registration";
}
@PostMapping("/register")
public String registerUser(@Valid User user, Errors validation, Model viewModel) {
User existingUser = usersDao.findByUsername(user.getUsername());
User existingEmail = usersDao.findByEmail(user.getEmail());
User existingPhoneNumber = usersDao.findByPhoneNumber(user.getPhoneNumber());
if (existingUser != null) {
validation.rejectValue(
"username",
"user.username",
"Username already taken!"
);
}
if (existingEmail != null) {
validation.rejectValue(
"email",
"user.email",
"Email already taken!"
);
}
if (existingPhoneNumber != null) {
validation.rejectValue(
"user.phoneNumber",
"user.phoneNumber",
"Phone number is already taken!"
);
}
if (validation.hasErrors()) {
viewModel.addAttribute("errors", validation);
viewModel.addAttribute("user", user);
return "users/registration";
}
//user.setPassword(passwordEncoder.encode(user.getPassword()));
//place the hashing encoder to storing password in a variable
String hashPassword = passwordEncoder.encode(user.getPassword());
user.setPassword(hashPassword);
usersDao.save(user);
return "redirect:/login";
}
@InitBinder
public void initBinder(final WebDataBinder binder) {
binder.registerCustomEditor(Gender.class, new GenderConverter());
//Gender Converter is changing from a string to a gender object
}
}
| [
"[email protected]"
] | |
ea5c4eb86da0047497dbc77ee53c601138b960b9 | 300947e343fbe069ff64a49b4151b7fa81ab2c30 | /Timber-master/Timber-master/app/src/main/java/naman14/timber/StreamYoutubecrome.java | 95f441b1275fe97ca2180ed049c0df6fac215fcc | [] | no_license | Sripathm2/Timber | 342dadc81f2f8872e5d87cd145bc8dfef3fddda4 | ff1f79f08752b76307cb3957a40336577cdd39c3 | refs/heads/master | 2021-06-10T04:49:09.223490 | 2017-01-23T20:22:26 | 2017-01-23T20:22:26 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 883 | java | package naman14.timber;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.customtabs.CustomTabsIntent;
import android.support.v7.app.AppCompatActivity;
import com.naman14.timber.R;
public class StreamYoutubecrome extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_stream_youtubecrome);
Intent intent = getIntent();
String output=intent.getStringExtra("check");
output.replaceAll(" ","+");
String url="https://www.youtube.com/results?search_query=+"+output;
CustomTabsIntent.Builder builder = new CustomTabsIntent.Builder();
CustomTabsIntent customTabsIntent = builder.build();
customTabsIntent.launchUrl(this, Uri.parse(url));
}
}
| [
"[email protected]"
] | |
465973d5e0e14b135b293e90611da2f1f927053a | 1f19aec2ecfd756934898cf0ad2758ee18d9eca2 | /u-1/u-1-f358.java | 49c23582263b09add8527098aa5a8f6b86b876e3 | [] | no_license | apertureatf/perftest | f6c6e69efad59265197f43af5072aa7af8393a34 | 584257a0c1ada22e5486052c11395858a87b20d5 | refs/heads/master | 2020-06-07T17:52:51.172890 | 2019-06-21T18:53:01 | 2019-06-21T18:53:01 | 193,039,805 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 106 | java | mastercard 5555555555554444 4012888888881881 4222222222222 378282246310005 6011111111111117
7304672759536 | [
"[email protected]"
] | |
5c2b7cb0b131bde0090495a684bd0d9b49a79266 | 7dca9d068fe6d18803cb568f3792363d652c5570 | /httpclientandroidlib/src/ch/boye/httpclientandroidlib/impl/client/cache/CachingHttpClient.java | 10defcf3829e116383c05b8c80a5cec467ecf29f | [] | no_license | biafra23/AmDroid | 2c0d68dc9bd559c5a811123681261ef10d9e5700 | 3aad88fff8a6d8c0eb9e3be22b23a60c25916285 | refs/heads/master | 2016-09-06T17:22:56.390353 | 2012-07-31T20:09:24 | 2012-07-31T20:09:24 | 2,485,574 | 16 | 2 | null | null | null | null | UTF-8 | Java | false | false | 39,008 | java | /*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package ch.boye.httpclientandroidlib.impl.client.cache;
import java.io.IOException;
import java.lang.reflect.UndeclaredThrowableException;
import java.net.URI;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicLong;
import ch.boye.httpclientandroidlib.androidextra.HttpClientAndroidLog;
/* LogFactory removed by HttpClient for Android script. */
import ch.boye.httpclientandroidlib.Header;
import ch.boye.httpclientandroidlib.HeaderElement;
import ch.boye.httpclientandroidlib.HttpEntity;
import ch.boye.httpclientandroidlib.HttpHost;
import ch.boye.httpclientandroidlib.HttpMessage;
import ch.boye.httpclientandroidlib.HttpRequest;
import ch.boye.httpclientandroidlib.HttpResponse;
import ch.boye.httpclientandroidlib.HttpStatus;
import ch.boye.httpclientandroidlib.HttpVersion;
import ch.boye.httpclientandroidlib.ProtocolException;
import ch.boye.httpclientandroidlib.ProtocolVersion;
import ch.boye.httpclientandroidlib.RequestLine;
import ch.boye.httpclientandroidlib.annotation.ThreadSafe;
import ch.boye.httpclientandroidlib.client.ClientProtocolException;
import ch.boye.httpclientandroidlib.client.HttpClient;
import ch.boye.httpclientandroidlib.client.ResponseHandler;
import ch.boye.httpclientandroidlib.client.cache.CacheResponseStatus;
import ch.boye.httpclientandroidlib.client.cache.HeaderConstants;
import ch.boye.httpclientandroidlib.client.cache.HttpCacheEntry;
import ch.boye.httpclientandroidlib.client.cache.HttpCacheStorage;
import ch.boye.httpclientandroidlib.client.cache.ResourceFactory;
import ch.boye.httpclientandroidlib.client.methods.HttpUriRequest;
import ch.boye.httpclientandroidlib.conn.ClientConnectionManager;
import ch.boye.httpclientandroidlib.impl.client.DefaultHttpClient;
import ch.boye.httpclientandroidlib.impl.cookie.DateParseException;
import ch.boye.httpclientandroidlib.impl.cookie.DateUtils;
import ch.boye.httpclientandroidlib.message.BasicHttpResponse;
import ch.boye.httpclientandroidlib.params.HttpParams;
import ch.boye.httpclientandroidlib.protocol.HttpContext;
import ch.boye.httpclientandroidlib.util.EntityUtils;
import ch.boye.httpclientandroidlib.util.VersionInfo;
/**
* <p>The {@link CachingHttpClient} is meant to be a drop-in replacement for
* a {@link DefaultHttpClient} that transparently adds client-side caching.
* The current implementation is conditionally compliant with HTTP/1.1
* (meaning all the MUST and MUST NOTs are obeyed), although quite a lot,
* though not all, of the SHOULDs and SHOULD NOTs are obeyed too. Generally
* speaking, you construct a {@code CachingHttpClient} by providing a
* "backend" {@link HttpClient} used for making actual network requests and
* provide an {@link HttpCacheStorage} instance to use for holding onto
* cached responses. Additional configuration options can be provided by
* passing in a {@link CacheConfig}. Note that all of the usual client
* related configuration you want to do vis-a-vis timeouts and connection
* pools should be done on this backend client before constructing a {@code
* CachingHttpClient} from it.</p>
*
* <p>Generally speaking, the {@code CachingHttpClient} is implemented as a
* <a href="http://en.wikipedia.org/wiki/Decorator_pattern">Decorator</a>
* of the backend client; for any incoming request it attempts to satisfy
* it from the cache, but if it can't, or if it needs to revalidate a stale
* cache entry, it will use the backend client to make an actual request.
* However, a proper HTTP/1.1 cache won't change the semantics of a request
* and response; in particular, if you issue an unconditional request you
* will get a full response (although it may be served to you from the cache,
* or the cache may make a conditional request on your behalf to the origin).
* This notion of "semantic transparency" means you should be able to drop
* a {@link CachingHttpClient} into an existing application without breaking
* anything.</p>
*
* <p>Folks that would like to experiment with alternative storage backends
* should look at the {@link HttpCacheStorage} interface and the related
* package documentation there. You may also be interested in the provided
* {@link ch.boye.httpclientandroidlib.impl.client.cache.ehcache.EhcacheHttpCacheStorage
* EhCache} and {@link
* ch.boye.httpclientandroidlib.impl.client.cache.memcached.MemcachedHttpCacheStorage
* memcached} storage backends.</p>
* </p>
* @since 4.1
*/
@ThreadSafe // So long as the responseCache implementation is threadsafe
public class CachingHttpClient implements HttpClient {
/**
* This is the name under which the {@link
* ch.boye.httpclientandroidlib.client.cache.CacheResponseStatus} of a request
* (for example, whether it resulted in a cache hit) will be recorded if an
* {@link HttpContext} is provided during execution.
*/
public static final String CACHE_RESPONSE_STATUS = "http.cache.response.status";
private final static boolean SUPPORTS_RANGE_AND_CONTENT_RANGE_HEADERS = false;
private final AtomicLong cacheHits = new AtomicLong();
private final AtomicLong cacheMisses = new AtomicLong();
private final AtomicLong cacheUpdates = new AtomicLong();
private final HttpClient backend;
private final HttpCache responseCache;
private final CacheValidityPolicy validityPolicy;
private final ResponseCachingPolicy responseCachingPolicy;
private final CachedHttpResponseGenerator responseGenerator;
private final CacheableRequestPolicy cacheableRequestPolicy;
private final CachedResponseSuitabilityChecker suitabilityChecker;
private final ConditionalRequestBuilder conditionalRequestBuilder;
private final int maxObjectSizeBytes;
private final boolean sharedCache;
private final ResponseProtocolCompliance responseCompliance;
private final RequestProtocolCompliance requestCompliance;
private final AsynchronousValidator asynchRevalidator;
public HttpClientAndroidLog log = new HttpClientAndroidLog(getClass());
CachingHttpClient(
HttpClient client,
HttpCache cache,
CacheConfig config) {
super();
if (client == null) {
throw new IllegalArgumentException("HttpClient may not be null");
}
if (cache == null) {
throw new IllegalArgumentException("HttpCache may not be null");
}
if (config == null) {
throw new IllegalArgumentException("CacheConfig may not be null");
}
this.maxObjectSizeBytes = config.getMaxObjectSizeBytes();
this.sharedCache = config.isSharedCache();
this.backend = client;
this.responseCache = cache;
this.validityPolicy = new CacheValidityPolicy();
this.responseCachingPolicy = new ResponseCachingPolicy(maxObjectSizeBytes, sharedCache);
this.responseGenerator = new CachedHttpResponseGenerator(this.validityPolicy);
this.cacheableRequestPolicy = new CacheableRequestPolicy();
this.suitabilityChecker = new CachedResponseSuitabilityChecker(this.validityPolicy, config);
this.conditionalRequestBuilder = new ConditionalRequestBuilder();
this.responseCompliance = new ResponseProtocolCompliance();
this.requestCompliance = new RequestProtocolCompliance();
this.asynchRevalidator = makeAsynchronousValidator(config);
}
/**
* Constructs a {@code CachingHttpClient} with default caching settings that
* stores cache entries in memory and uses a vanilla {@link DefaultHttpClient}
* for backend requests.
*/
public CachingHttpClient() {
this(new DefaultHttpClient(),
new BasicHttpCache(),
new CacheConfig());
}
/**
* Constructs a {@code CachingHttpClient} with the given caching options that
* stores cache entries in memory and uses a vanilla {@link DefaultHttpClient}
* for backend requests.
* @param config cache module options
*/
public CachingHttpClient(CacheConfig config) {
this(new DefaultHttpClient(),
new BasicHttpCache(config),
config);
}
/**
* Constructs a {@code CachingHttpClient} with default caching settings that
* stores cache entries in memory and uses the given {@link HttpClient}
* for backend requests.
* @param client used to make origin requests
*/
public CachingHttpClient(HttpClient client) {
this(client,
new BasicHttpCache(),
new CacheConfig());
}
/**
* Constructs a {@code CachingHttpClient} with the given caching options that
* stores cache entries in memory and uses the given {@link HttpClient}
* for backend requests.
* @param config cache module options
* @param client used to make origin requests
*/
public CachingHttpClient(HttpClient client, CacheConfig config) {
this(client,
new BasicHttpCache(config),
config);
}
/**
* Constructs a {@code CachingHttpClient} with the given caching options
* that stores cache entries in the provided storage backend and uses
* the given {@link HttpClient} for backend requests. However, cached
* response bodies are managed using the given {@link ResourceFactory}.
* @param client used to make origin requests
* @param resourceFactory how to manage cached response bodies
* @param storage where to store cache entries
* @param config cache module options
*/
public CachingHttpClient(
HttpClient client,
ResourceFactory resourceFactory,
HttpCacheStorage storage,
CacheConfig config) {
this(client,
new BasicHttpCache(resourceFactory, storage, config),
config);
}
/**
* Constructs a {@code CachingHttpClient} with the given caching options
* that stores cache entries in the provided storage backend and uses
* the given {@link HttpClient} for backend requests.
* @param client used to make origin requests
* @param storage where to store cache entries
* @param config cache module options
*/
public CachingHttpClient(
HttpClient client,
HttpCacheStorage storage,
CacheConfig config) {
this(client,
new BasicHttpCache(new HeapResourceFactory(), storage, config),
config);
}
CachingHttpClient(
HttpClient backend,
CacheValidityPolicy validityPolicy,
ResponseCachingPolicy responseCachingPolicy,
HttpCache responseCache,
CachedHttpResponseGenerator responseGenerator,
CacheableRequestPolicy cacheableRequestPolicy,
CachedResponseSuitabilityChecker suitabilityChecker,
ConditionalRequestBuilder conditionalRequestBuilder,
ResponseProtocolCompliance responseCompliance,
RequestProtocolCompliance requestCompliance) {
CacheConfig config = new CacheConfig();
this.maxObjectSizeBytes = config.getMaxObjectSizeBytes();
this.sharedCache = config.isSharedCache();
this.backend = backend;
this.validityPolicy = validityPolicy;
this.responseCachingPolicy = responseCachingPolicy;
this.responseCache = responseCache;
this.responseGenerator = responseGenerator;
this.cacheableRequestPolicy = cacheableRequestPolicy;
this.suitabilityChecker = suitabilityChecker;
this.conditionalRequestBuilder = conditionalRequestBuilder;
this.responseCompliance = responseCompliance;
this.requestCompliance = requestCompliance;
this.asynchRevalidator = makeAsynchronousValidator(config);
}
private AsynchronousValidator makeAsynchronousValidator(
CacheConfig config) {
if (config.getAsynchronousWorkersMax() > 0) {
return new AsynchronousValidator(this, config);
}
return null;
}
/**
* Reports the number of times that the cache successfully responded
* to an {@link HttpRequest} without contacting the origin server.
* @return the number of cache hits
*/
public long getCacheHits() {
return cacheHits.get();
}
/**
* Reports the number of times that the cache contacted the origin
* server because it had no appropriate response cached.
* @return the number of cache misses
*/
public long getCacheMisses() {
return cacheMisses.get();
}
/**
* Reports the number of times that the cache was able to satisfy
* a response by revalidating an existing but stale cache entry.
* @return the number of cache revalidations
*/
public long getCacheUpdates() {
return cacheUpdates.get();
}
public HttpResponse execute(HttpHost target, HttpRequest request) throws IOException {
HttpContext defaultContext = null;
return execute(target, request, defaultContext);
}
public <T> T execute(HttpHost target, HttpRequest request,
ResponseHandler<? extends T> responseHandler) throws IOException {
return execute(target, request, responseHandler, null);
}
public <T> T execute(HttpHost target, HttpRequest request,
ResponseHandler<? extends T> responseHandler, HttpContext context) throws IOException {
HttpResponse resp = execute(target, request, context);
return handleAndConsume(responseHandler,resp);
}
public HttpResponse execute(HttpUriRequest request) throws IOException {
HttpContext context = null;
return execute(request, context);
}
public HttpResponse execute(HttpUriRequest request, HttpContext context) throws IOException {
URI uri = request.getURI();
HttpHost httpHost = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme());
return execute(httpHost, request, context);
}
public <T> T execute(HttpUriRequest request, ResponseHandler<? extends T> responseHandler)
throws IOException {
return execute(request, responseHandler, null);
}
public <T> T execute(HttpUriRequest request, ResponseHandler<? extends T> responseHandler,
HttpContext context) throws IOException {
HttpResponse resp = execute(request, context);
return handleAndConsume(responseHandler, resp);
}
private <T> T handleAndConsume(
final ResponseHandler<? extends T> responseHandler,
HttpResponse response) throws Error, IOException {
T result;
try {
result = responseHandler.handleResponse(response);
} catch (Exception t) {
HttpEntity entity = response.getEntity();
try {
EntityUtils.consume(entity);
} catch (Exception t2) {
// Log this exception. The original exception is more
// important and will be thrown to the caller.
this.log.warn("Error consuming content after an exception.", t2);
}
if (t instanceof RuntimeException) {
throw (RuntimeException) t;
}
if (t instanceof IOException) {
throw (IOException) t;
}
throw new UndeclaredThrowableException(t);
}
// Handling the response was successful. Ensure that the content has
// been fully consumed.
HttpEntity entity = response.getEntity();
EntityUtils.consume(entity);
return result;
}
public ClientConnectionManager getConnectionManager() {
return backend.getConnectionManager();
}
public HttpParams getParams() {
return backend.getParams();
}
public HttpResponse execute(HttpHost target, HttpRequest request, HttpContext context)
throws IOException {
// default response context
setResponseStatus(context, CacheResponseStatus.CACHE_MISS);
String via = generateViaHeader(request);
if (clientRequestsOurOptions(request)) {
setResponseStatus(context, CacheResponseStatus.CACHE_MODULE_RESPONSE);
return new OptionsHttp11Response();
}
HttpResponse fatalErrorResponse = getFatallyNoncompliantResponse(
request, context);
if (fatalErrorResponse != null) return fatalErrorResponse;
request = requestCompliance.makeRequestCompliant(request);
request.addHeader("Via",via);
flushEntriesInvalidatedByRequest(target, request);
if (!cacheableRequestPolicy.isServableFromCache(request)) {
return callBackend(target, request, context);
}
HttpCacheEntry entry = satisfyFromCache(target, request);
if (entry == null) {
return handleCacheMiss(target, request, context);
}
return handleCacheHit(target, request, context, entry);
}
private HttpResponse handleCacheHit(HttpHost target, HttpRequest request,
HttpContext context, HttpCacheEntry entry)
throws ClientProtocolException, IOException {
recordCacheHit(target, request);
Date now = getCurrentDate();
if (suitabilityChecker.canCachedResponseBeUsed(target, request, entry, now)) {
return generateCachedResponse(request, context, entry, now);
}
if (!mayCallBackend(request)) {
return generateGatewayTimeout(context);
}
if (validityPolicy.isRevalidatable(entry)) {
return revalidateCacheEntry(target, request, context, entry, now);
}
return callBackend(target, request, context);
}
private HttpResponse revalidateCacheEntry(HttpHost target,
HttpRequest request, HttpContext context, HttpCacheEntry entry,
Date now) throws ClientProtocolException {
log.trace("Revalidating the cache entry");
try {
if (asynchRevalidator != null
&& !staleResponseNotAllowed(request, entry, now)
&& validityPolicy.mayReturnStaleWhileRevalidating(entry, now)) {
final HttpResponse resp = generateCachedResponse(request, context, entry, now);
asynchRevalidator.revalidateCacheEntry(target, request, context, entry);
return resp;
}
return revalidateCacheEntry(target, request, context, entry);
} catch (IOException ioex) {
return handleRevalidationFailure(request, context, entry, now);
} catch (ProtocolException e) {
throw new ClientProtocolException(e);
}
}
private HttpResponse handleCacheMiss(HttpHost target, HttpRequest request,
HttpContext context) throws IOException {
recordCacheMiss(target, request);
if (!mayCallBackend(request)) {
return new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_GATEWAY_TIMEOUT,
"Gateway Timeout");
}
Map<String, Variant> variants =
getExistingCacheVariants(target, request);
if (variants != null && variants.size() > 0) {
return negotiateResponseFromVariants(target, request, context, variants);
}
return callBackend(target, request, context);
}
private HttpCacheEntry satisfyFromCache(HttpHost target, HttpRequest request) {
HttpCacheEntry entry = null;
try {
entry = responseCache.getCacheEntry(target, request);
} catch (IOException ioe) {
log.warn("Unable to retrieve entries from cache", ioe);
}
return entry;
}
private HttpResponse getFatallyNoncompliantResponse(HttpRequest request,
HttpContext context) {
HttpResponse fatalErrorResponse = null;
List<RequestProtocolError> fatalError = requestCompliance.requestIsFatallyNonCompliant(request);
for (RequestProtocolError error : fatalError) {
setResponseStatus(context, CacheResponseStatus.CACHE_MODULE_RESPONSE);
fatalErrorResponse = requestCompliance.getErrorForRequest(error);
}
return fatalErrorResponse;
}
private Map<String, Variant> getExistingCacheVariants(HttpHost target,
HttpRequest request) {
Map<String,Variant> variants = null;
try {
variants = responseCache.getVariantCacheEntriesWithEtags(target, request);
} catch (IOException ioe) {
log.warn("Unable to retrieve variant entries from cache", ioe);
}
return variants;
}
private void recordCacheMiss(HttpHost target, HttpRequest request) {
cacheMisses.getAndIncrement();
if (log.isTraceEnabled()) {
RequestLine rl = request.getRequestLine();
log.trace("Cache miss [host: " + target + "; uri: " + rl.getUri() + "]");
}
}
private void recordCacheHit(HttpHost target, HttpRequest request) {
cacheHits.getAndIncrement();
if (log.isTraceEnabled()) {
RequestLine rl = request.getRequestLine();
log.trace("Cache hit [host: " + target + "; uri: " + rl.getUri() + "]");
}
}
private void recordCacheUpdate(HttpContext context) {
cacheUpdates.getAndIncrement();
setResponseStatus(context, CacheResponseStatus.VALIDATED);
}
private void flushEntriesInvalidatedByRequest(HttpHost target,
HttpRequest request) {
try {
responseCache.flushInvalidatedCacheEntriesFor(target, request);
} catch (IOException ioe) {
log.warn("Unable to flush invalidated entries from cache", ioe);
}
}
private HttpResponse generateCachedResponse(HttpRequest request,
HttpContext context, HttpCacheEntry entry, Date now) {
final HttpResponse cachedResponse;
if (request.containsHeader(HeaderConstants.IF_NONE_MATCH)
|| request.containsHeader(HeaderConstants.IF_MODIFIED_SINCE)) {
cachedResponse = responseGenerator.generateNotModifiedResponse(entry);
} else {
cachedResponse = responseGenerator.generateResponse(entry);
}
setResponseStatus(context, CacheResponseStatus.CACHE_HIT);
if (validityPolicy.getStalenessSecs(entry, now) > 0L) {
cachedResponse.addHeader("Warning","110 localhost \"Response is stale\"");
}
return cachedResponse;
}
private HttpResponse handleRevalidationFailure(HttpRequest request,
HttpContext context, HttpCacheEntry entry, Date now) {
if (staleResponseNotAllowed(request, entry, now)) {
return generateGatewayTimeout(context);
} else {
return unvalidatedCacheHit(context, entry);
}
}
private HttpResponse generateGatewayTimeout(HttpContext context) {
setResponseStatus(context, CacheResponseStatus.CACHE_MODULE_RESPONSE);
return new BasicHttpResponse(HttpVersion.HTTP_1_1,
HttpStatus.SC_GATEWAY_TIMEOUT, "Gateway Timeout");
}
private HttpResponse unvalidatedCacheHit(HttpContext context,
HttpCacheEntry entry) {
final HttpResponse cachedResponse = responseGenerator.generateResponse(entry);
setResponseStatus(context, CacheResponseStatus.CACHE_HIT);
cachedResponse.addHeader(HeaderConstants.WARNING, "111 localhost \"Revalidation failed\"");
return cachedResponse;
}
private boolean staleResponseNotAllowed(HttpRequest request,
HttpCacheEntry entry, Date now) {
return validityPolicy.mustRevalidate(entry)
|| (isSharedCache() && validityPolicy.proxyRevalidate(entry))
|| explicitFreshnessRequest(request, entry, now);
}
private boolean mayCallBackend(HttpRequest request) {
for (Header h: request.getHeaders("Cache-Control")) {
for (HeaderElement elt : h.getElements()) {
if ("only-if-cached".equals(elt.getName())) {
return false;
}
}
}
return true;
}
private boolean explicitFreshnessRequest(HttpRequest request, HttpCacheEntry entry, Date now) {
for(Header h : request.getHeaders("Cache-Control")) {
for(HeaderElement elt : h.getElements()) {
if ("max-stale".equals(elt.getName())) {
try {
int maxstale = Integer.parseInt(elt.getValue());
long age = validityPolicy.getCurrentAgeSecs(entry, now);
long lifetime = validityPolicy.getFreshnessLifetimeSecs(entry);
if (age - lifetime > maxstale) return true;
} catch (NumberFormatException nfe) {
return true;
}
} else if ("min-fresh".equals(elt.getName())
|| "max-age".equals(elt.getName())) {
return true;
}
}
}
return false;
}
private String generateViaHeader(HttpMessage msg) {
final VersionInfo vi = VersionInfo.loadVersionInfo("ch.boye.httpclientandroidlib.client", getClass().getClassLoader());
final String release = (vi != null) ? vi.getRelease() : VersionInfo.UNAVAILABLE;
final ProtocolVersion pv = msg.getProtocolVersion();
if ("http".equalsIgnoreCase(pv.getProtocol())) {
return String.format("%d.%d localhost (Apache-HttpClient/%s (cache))",
pv.getMajor(), pv.getMinor(), release);
} else {
return String.format("%s/%d.%d localhost (Apache-HttpClient/%s (cache))",
pv.getProtocol(), pv.getMajor(), pv.getMinor(), release);
}
}
private void setResponseStatus(final HttpContext context, final CacheResponseStatus value) {
if (context != null) {
context.setAttribute(CACHE_RESPONSE_STATUS, value);
}
}
/**
* Reports whether this {@code CachingHttpClient} implementation
* supports byte-range requests as specified by the {@code Range}
* and {@code Content-Range} headers.
* @return {@code true} if byte-range requests are supported
*/
public boolean supportsRangeAndContentRangeHeaders() {
return SUPPORTS_RANGE_AND_CONTENT_RANGE_HEADERS;
}
/**
* Reports whether this {@code CachingHttpClient} is configured as
* a shared (public) or non-shared (private) cache. See {@link
* CacheConfig#setSharedCache(boolean)}.
* @return {@code true} if we are behaving as a shared (public)
* cache
*/
public boolean isSharedCache() {
return sharedCache;
}
Date getCurrentDate() {
return new Date();
}
boolean clientRequestsOurOptions(HttpRequest request) {
RequestLine line = request.getRequestLine();
if (!HeaderConstants.OPTIONS_METHOD.equals(line.getMethod()))
return false;
if (!"*".equals(line.getUri()))
return false;
if (!"0".equals(request.getFirstHeader(HeaderConstants.MAX_FORWARDS).getValue()))
return false;
return true;
}
HttpResponse callBackend(HttpHost target, HttpRequest request, HttpContext context)
throws IOException {
Date requestDate = getCurrentDate();
log.trace("Calling the backend");
HttpResponse backendResponse = backend.execute(target, request, context);
backendResponse.addHeader("Via", generateViaHeader(backendResponse));
return handleBackendResponse(target, request, requestDate, getCurrentDate(),
backendResponse);
}
private boolean revalidationResponseIsTooOld(HttpResponse backendResponse,
HttpCacheEntry cacheEntry) {
final Header entryDateHeader = cacheEntry.getFirstHeader("Date");
final Header responseDateHeader = backendResponse.getFirstHeader("Date");
if (entryDateHeader != null && responseDateHeader != null) {
try {
Date entryDate = DateUtils.parseDate(entryDateHeader.getValue());
Date respDate = DateUtils.parseDate(responseDateHeader.getValue());
if (respDate.before(entryDate)) return true;
} catch (DateParseException e) {
// either backend response or cached entry did not have a valid
// Date header, so we can't tell if they are out of order
// according to the origin clock; thus we can skip the
// unconditional retry recommended in 13.2.6 of RFC 2616.
}
}
return false;
}
HttpResponse negotiateResponseFromVariants(HttpHost target,
HttpRequest request, HttpContext context,
Map<String, Variant> variants) throws IOException {
HttpRequest conditionalRequest = conditionalRequestBuilder.buildConditionalRequestFromVariants(request, variants);
Date requestDate = getCurrentDate();
HttpResponse backendResponse = backend.execute(target, conditionalRequest, context);
Date responseDate = getCurrentDate();
backendResponse.addHeader("Via", generateViaHeader(backendResponse));
if (backendResponse.getStatusLine().getStatusCode() != HttpStatus.SC_NOT_MODIFIED) {
return handleBackendResponse(target, request, requestDate, responseDate, backendResponse);
}
Header resultEtagHeader = backendResponse.getFirstHeader(HeaderConstants.ETAG);
if (resultEtagHeader == null) {
log.warn("304 response did not contain ETag");
return callBackend(target, request, context);
}
String resultEtag = resultEtagHeader.getValue();
Variant matchingVariant = variants.get(resultEtag);
if (matchingVariant == null) {
log.debug("304 response did not contain ETag matching one sent in If-None-Match");
return callBackend(target, request, context);
}
HttpCacheEntry matchedEntry = matchingVariant.getEntry();
if (revalidationResponseIsTooOld(backendResponse, matchedEntry)) {
return retryRequestUnconditionally(target, request, context,
matchedEntry);
}
recordCacheUpdate(context);
HttpCacheEntry responseEntry = getUpdatedVariantEntry(target,
conditionalRequest, requestDate, responseDate, backendResponse,
matchingVariant, matchedEntry);
HttpResponse resp = responseGenerator.generateResponse(responseEntry);
tryToUpdateVariantMap(target, request, matchingVariant);
if (shouldSendNotModifiedResponse(request, responseEntry)) {
return responseGenerator.generateNotModifiedResponse(responseEntry);
}
return resp;
}
private HttpResponse retryRequestUnconditionally(HttpHost target,
HttpRequest request, HttpContext context,
HttpCacheEntry matchedEntry) throws IOException {
HttpRequest unconditional = conditionalRequestBuilder
.buildUnconditionalRequest(request, matchedEntry);
return callBackend(target, unconditional, context);
}
private HttpCacheEntry getUpdatedVariantEntry(HttpHost target,
HttpRequest conditionalRequest, Date requestDate,
Date responseDate, HttpResponse backendResponse,
Variant matchingVariant, HttpCacheEntry matchedEntry) {
HttpCacheEntry responseEntry = matchedEntry;
try {
responseEntry = responseCache.updateVariantCacheEntry(target, conditionalRequest,
matchedEntry, backendResponse, requestDate, responseDate, matchingVariant.getCacheKey());
} catch (IOException ioe) {
log.warn("Could not update cache entry", ioe);
}
return responseEntry;
}
private void tryToUpdateVariantMap(HttpHost target, HttpRequest request,
Variant matchingVariant) {
try {
responseCache.reuseVariantEntryFor(target, request, matchingVariant);
} catch (IOException ioe) {
log.warn("Could not update cache entry to reuse variant", ioe);
}
}
private boolean shouldSendNotModifiedResponse(HttpRequest request,
HttpCacheEntry responseEntry) {
return (suitabilityChecker.isConditional(request)
&& suitabilityChecker.allConditionalsMatch(request, responseEntry, new Date()));
}
HttpResponse revalidateCacheEntry(
HttpHost target,
HttpRequest request,
HttpContext context,
HttpCacheEntry cacheEntry) throws IOException, ProtocolException {
HttpRequest conditionalRequest = conditionalRequestBuilder.buildConditionalRequest(request, cacheEntry);
Date requestDate = getCurrentDate();
HttpResponse backendResponse = backend.execute(target, conditionalRequest, context);
Date responseDate = getCurrentDate();
if (revalidationResponseIsTooOld(backendResponse, cacheEntry)) {
HttpRequest unconditional = conditionalRequestBuilder
.buildUnconditionalRequest(request, cacheEntry);
requestDate = getCurrentDate();
backendResponse = backend.execute(target, unconditional, context);
responseDate = getCurrentDate();
}
backendResponse.addHeader("Via", generateViaHeader(backendResponse));
int statusCode = backendResponse.getStatusLine().getStatusCode();
if (statusCode == HttpStatus.SC_NOT_MODIFIED || statusCode == HttpStatus.SC_OK) {
recordCacheUpdate(context);
}
if (statusCode == HttpStatus.SC_NOT_MODIFIED) {
HttpCacheEntry updatedEntry = responseCache.updateCacheEntry(target, request, cacheEntry,
backendResponse, requestDate, responseDate);
if (suitabilityChecker.isConditional(request)
&& suitabilityChecker.allConditionalsMatch(request, updatedEntry, new Date())) {
return responseGenerator.generateNotModifiedResponse(updatedEntry);
}
return responseGenerator.generateResponse(updatedEntry);
}
if (staleIfErrorAppliesTo(statusCode)
&& !staleResponseNotAllowed(request, cacheEntry, getCurrentDate())
&& validityPolicy.mayReturnStaleIfError(request, cacheEntry, responseDate)) {
final HttpResponse cachedResponse = responseGenerator.generateResponse(cacheEntry);
cachedResponse.addHeader(HeaderConstants.WARNING, "110 localhost \"Response is stale\"");
HttpEntity errorBody = backendResponse.getEntity();
if (errorBody != null) EntityUtils.consume(errorBody);
return cachedResponse;
}
return handleBackendResponse(target, conditionalRequest, requestDate, responseDate,
backendResponse);
}
private boolean staleIfErrorAppliesTo(int statusCode) {
return statusCode == HttpStatus.SC_INTERNAL_SERVER_ERROR
|| statusCode == HttpStatus.SC_BAD_GATEWAY
|| statusCode == HttpStatus.SC_SERVICE_UNAVAILABLE
|| statusCode == HttpStatus.SC_GATEWAY_TIMEOUT;
}
HttpResponse handleBackendResponse(
HttpHost target,
HttpRequest request,
Date requestDate,
Date responseDate,
HttpResponse backendResponse) throws IOException {
log.trace("Handling Backend response");
responseCompliance.ensureProtocolCompliance(request, backendResponse);
boolean cacheable = responseCachingPolicy.isResponseCacheable(request, backendResponse);
responseCache.flushInvalidatedCacheEntriesFor(target, request, backendResponse);
if (cacheable &&
!alreadyHaveNewerCacheEntry(target, request, backendResponse)) {
try {
return responseCache.cacheAndReturnResponse(target, request, backendResponse, requestDate,
responseDate);
} catch (IOException ioe) {
log.warn("Unable to store entries in cache", ioe);
}
}
if (!cacheable) {
try {
responseCache.flushCacheEntriesFor(target, request);
} catch (IOException ioe) {
log.warn("Unable to flush invalid cache entries", ioe);
}
}
return backendResponse;
}
private boolean alreadyHaveNewerCacheEntry(HttpHost target, HttpRequest request,
HttpResponse backendResponse) {
HttpCacheEntry existing = null;
try {
existing = responseCache.getCacheEntry(target, request);
} catch (IOException ioe) {
// nop
}
if (existing == null) return false;
Header entryDateHeader = existing.getFirstHeader("Date");
if (entryDateHeader == null) return false;
Header responseDateHeader = backendResponse.getFirstHeader("Date");
if (responseDateHeader == null) return false;
try {
Date entryDate = DateUtils.parseDate(entryDateHeader.getValue());
Date responseDate = DateUtils.parseDate(responseDateHeader.getValue());
return responseDate.before(entryDate);
} catch (DateParseException e) {
}
return false;
}
}
| [
"[email protected]"
] | |
bc1cd170315f1090182d952d663abad30fa0e7fc | 917372f7a06e20f694c8577d39ef3c552819d78d | /app/src/main/java/com/example/android/sunshine/data/SunshinePreferences.java | 9a88c5f17514d52481792e81dea0e8036a55bc4a | [] | no_license | augustmary/SunshineApp | cce610aa7fc5c361f697342ca906327decdb1a43 | ee1dd8aa9fc9961d3872290304ebb25f8bc79e80 | refs/heads/master | 2021-06-15T19:50:50.131981 | 2017-03-10T15:45:39 | 2017-03-10T15:45:39 | 81,199,350 | 0 | 0 | null | 2017-03-10T15:53:58 | 2017-02-07T11:07:58 | Java | UTF-8 | Java | false | false | 6,176 | java | /*
* Copyright (C) 2016 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.sunshine.data;
import android.content.Context;
import android.content.SharedPreferences;
import android.support.v7.preference.PreferenceManager;
import com.example.android.sunshine.R;
public class SunshinePreferences {
/*
* Human readable location string, provided by the API. Because for styling,
* "Mountain View" is more recognizable than 94043.
*/
public static final String PREF_CITY_NAME = "city_name";
/*
* In order to uniquely pinpoint the location on the map when we launch the
* map intent, we store the latitude and longitude.
*/
public static final String PREF_COORD_LAT = "coord_lat";
public static final String PREF_COORD_LONG = "coord_long";
/*
* Before you implement methods to return your REAL preference for location,
* we provide some default values to work with.
*/
private static final String DEFAULT_WEATHER_LOCATION = "94043,USA";
private static final double[] DEFAULT_WEATHER_COORDINATES = {37.4284, 122.0724};
private static final String DEFAULT_MAP_LOCATION =
"1600 Amphitheatre Parkway, Mountain View, CA 94043";
/**
* Helper method to handle setting location details in Preferences (City Name, Latitude,
* Longitude)
*
* @param c Context used to get the SharedPreferences
* @param cityName A human-readable city name, e.g "Mountain View"
* @param lat The latitude of the city
* @param lon The longitude of the city
*/
static public void setLocationDetails(Context c, String cityName, double lat, double lon) {
/** This will be implemented in a future lesson **/
}
/**
* Helper method to handle setting a new location in preferences. When this happens
* the database may need to be cleared.
*
* @param c Context used to get the SharedPreferences
* @param locationSetting The location string used to request updates from the server.
* @param lat The latitude of the city
* @param lon The longitude of the city
*/
static public void setLocation(Context c, String locationSetting, double lat, double lon) {
/** This will be implemented in a future lesson **/
}
/**
* Resets the stored location coordinates.
*
* @param c Context used to get the SharedPreferences
*/
static public void resetLocationCoordinates(Context c) {
/** This will be implemented in a future lesson **/
}
/**
* Returns the location currently set in Preferences. The default location this method
* will return is "94043,USA", which is Mountain View, California. Mountain View is the
* home of the headquarters of the Googleplex!
*
* @param context Context used to get the SharedPreferences
* @return Location The current user has set in SharedPreferences. Will default to
* "94043,USA" if SharedPreferences have not been implemented yet.
*/
public static String getPreferredWeatherLocation(Context context) {
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(context);
String keyForLocation = context.getString(R.string.pref_location_key);
String defaultLocation = context.getString(R.string.pref_location_default);
return prefs.getString(keyForLocation, defaultLocation);
}
/**
* Returns true if the user has selected metric temperature display.
*
* @param context Context used to get the SharedPreferences
* @return true If metric display should be used
*/
public static boolean isMetric(Context context) {
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(context);
String keyForUnits = context.getString(R.string.pref_units_key);
String defaultUnits = context.getString(R.string.pref_units_metric);
String preferredUnits = prefs.getString(keyForUnits, defaultUnits);
String metric = context.getString(R.string.pref_units_metric);
boolean userPrefersMetric;
userPrefersMetric = metric.equals(preferredUnits);
return userPrefersMetric;
}
/**
* Returns the location coordinates associated with the location. Note that these coordinates
* may not be set, which results in (0,0) being returned. (conveniently, 0,0 is in the middle
* of the ocean off the west coast of Africa)
*
* @param context Used to get the SharedPreferences
* @return An array containing the two coordinate values.
*/
public static double[] getLocationCoordinates(Context context) {
return getDefaultWeatherCoordinates();
}
/**
* Returns true if the latitude and longitude values are available. The latitude and
* longitude will not be available until the lesson where the PlacePicker API is taught.
*
* @param context used to get the SharedPreferences
* @return true if lat/long are set
*/
public static boolean isLocationLatLonAvailable(Context context) {
/** This will be implemented in a future lesson **/
return false;
}
private static String getDefaultWeatherLocation() {
/** This will be implemented in a future lesson **/
return DEFAULT_WEATHER_LOCATION;
}
public static double[] getDefaultWeatherCoordinates() {
/** This will be implemented in a future lesson **/
return DEFAULT_WEATHER_COORDINATES;
}
} | [
"[email protected]"
] | |
305820bc3039753328eb71f7846ae6608184f5b2 | 4bd2ddf7cd2b0e3e87c78d7d81d6df1c5bdc1cda | /xh5/x5-bpmx-root/modules/x5-bpmx-core/src/main/java/com/hotent/bpmx/core/defxml/entity/CallConversation.java | 132fccccde3f5a6d8a769dbbd96b7ea4d71ebd9c | [] | no_license | codingOnGithub/hx | 27a873a308528eb968632bbf97e6e25107f92a9f | c93d6c23032ff798d460ee9a0efaba214594a6b9 | refs/heads/master | 2021-05-27T14:40:05.776605 | 2014-10-22T16:52:34 | 2014-10-22T16:52:34 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,269 | java | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2013.12.11 at 10:08:02 AM CST
//
package com.hotent.bpmx.core.defxml.entity;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlType;
import javax.xml.namespace.QName;
/**
* <p>Java class for tCallConversation complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="tCallConversation">
* <complexContent>
* <extension base="{http://www.omg.org/spec/BPMN/20100524/MODEL}tConversationNode">
* <sequence>
* <element ref="{http://www.omg.org/spec/BPMN/20100524/MODEL}participantAssociation" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* <attribute name="calledCollaborationRef" type="{http://www.w3.org/2001/XMLSchema}QName" />
* <anyAttribute processContents='lax' namespace='##other'/>
* </extension>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "tCallConversation", propOrder = {
"participantAssociation"
})
public class CallConversation
extends ConversationNode
{
protected List<ParticipantAssociation> participantAssociation;
@XmlAttribute(name = "calledCollaborationRef")
protected QName calledCollaborationRef;
/**
* Gets the value of the participantAssociation property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the participantAssociation property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getParticipantAssociation().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link ParticipantAssociation }
*
*
*/
public List<ParticipantAssociation> getParticipantAssociation() {
if (participantAssociation == null) {
participantAssociation = new ArrayList<ParticipantAssociation>();
}
return this.participantAssociation;
}
/**
* Gets the value of the calledCollaborationRef property.
*
* @return
* possible object is
* {@link QName }
*
*/
public QName getCalledCollaborationRef() {
return calledCollaborationRef;
}
/**
* Sets the value of the calledCollaborationRef property.
*
* @param value
* allowed object is
* {@link QName }
*
*/
public void setCalledCollaborationRef(QName value) {
this.calledCollaborationRef = value;
}
}
| [
"[email protected]"
] | |
35d979a8e9826f1637149796dc7399819235187b | 47bbc55408588dcab1daf64a4d67f5a2e54bf9ad | /FailureDetection/src/DCMS_FrontEnd/_FrontEndStub.java | 7442913ca3aa5b0013a015412bb05a6870afef9b | [] | no_license | Aakaash897/Distributed-Computing | 2d03747209468b4aba5d58cfa8a95cfd8a2214bf | 0b5f407be04fea90193cd243999ed679a604c8cc | refs/heads/master | 2020-05-18T14:58:51.912112 | 2019-05-01T21:38:49 | 2019-05-01T21:38:49 | 184,484,587 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 6,960 | java | package DCMS_FrontEnd;
/**
* DCMS_FrontEnd/_FrontEndStub.java .
* Generated by the IDL-to-Java compiler (portable), version "3.2"
* from FrontEnd.idl
* Friday, August 4, 2017 10:55:50 PM EDT
*/
public class _FrontEndStub extends org.omg.CORBA.portable.ObjectImpl implements DCMS_FrontEnd.FrontEnd
{
public String createTRecord (String managerID, String firstName, String lastName, String address, String phoneNumber, String specialization, String location)
{
org.omg.CORBA.portable.InputStream $in = null;
try {
org.omg.CORBA.portable.OutputStream $out = _request ("createTRecord", true);
$out.write_string (managerID);
$out.write_string (firstName);
$out.write_string (lastName);
$out.write_string (address);
$out.write_string (phoneNumber);
$out.write_string (specialization);
$out.write_string (location);
$in = _invoke ($out);
String $result = $in.read_string ();
return $result;
} catch (org.omg.CORBA.portable.ApplicationException $ex) {
$in = $ex.getInputStream ();
String _id = $ex.getId ();
throw new org.omg.CORBA.MARSHAL (_id);
} catch (org.omg.CORBA.portable.RemarshalException $rm) {
return createTRecord (managerID, firstName, lastName, address, phoneNumber, specialization, location );
} finally {
_releaseReply ($in);
}
} // createTRecord
public String createSRecord (String managerID, String firstName, String lastName, String courseRegistered, String status, String statusDate)
{
org.omg.CORBA.portable.InputStream $in = null;
try {
org.omg.CORBA.portable.OutputStream $out = _request ("createSRecord", true);
$out.write_string (managerID);
$out.write_string (firstName);
$out.write_string (lastName);
$out.write_string (courseRegistered);
$out.write_string (status);
$out.write_string (statusDate);
$in = _invoke ($out);
String $result = $in.read_string ();
return $result;
} catch (org.omg.CORBA.portable.ApplicationException $ex) {
$in = $ex.getInputStream ();
String _id = $ex.getId ();
throw new org.omg.CORBA.MARSHAL (_id);
} catch (org.omg.CORBA.portable.RemarshalException $rm) {
return createSRecord (managerID, firstName, lastName, courseRegistered, status, statusDate );
} finally {
_releaseReply ($in);
}
} // createSRecord
public String recordCounts (String managerID)
{
org.omg.CORBA.portable.InputStream $in = null;
try {
org.omg.CORBA.portable.OutputStream $out = _request ("recordCounts", true);
$out.write_string (managerID);
$in = _invoke ($out);
String $result = $in.read_string ();
return $result;
} catch (org.omg.CORBA.portable.ApplicationException $ex) {
$in = $ex.getInputStream ();
String _id = $ex.getId ();
throw new org.omg.CORBA.MARSHAL (_id);
} catch (org.omg.CORBA.portable.RemarshalException $rm) {
return recordCounts (managerID );
} finally {
_releaseReply ($in);
}
} // recordCounts
public String editRecord (String managerID, String recordID, String fieldName, String newValue)
{
org.omg.CORBA.portable.InputStream $in = null;
try {
org.omg.CORBA.portable.OutputStream $out = _request ("editRecord", true);
$out.write_string (managerID);
$out.write_string (recordID);
$out.write_string (fieldName);
$out.write_string (newValue);
$in = _invoke ($out);
String $result = $in.read_string ();
return $result;
} catch (org.omg.CORBA.portable.ApplicationException $ex) {
$in = $ex.getInputStream ();
String _id = $ex.getId ();
throw new org.omg.CORBA.MARSHAL (_id);
} catch (org.omg.CORBA.portable.RemarshalException $rm) {
return editRecord (managerID, recordID, fieldName, newValue );
} finally {
_releaseReply ($in);
}
} // editRecord
public String transferRecord (String managerID, String recordID, String remoteCenterServerName)
{
org.omg.CORBA.portable.InputStream $in = null;
try {
org.omg.CORBA.portable.OutputStream $out = _request ("transferRecord", true);
$out.write_string (managerID);
$out.write_string (recordID);
$out.write_string (remoteCenterServerName);
$in = _invoke ($out);
String $result = $in.read_string ();
return $result;
} catch (org.omg.CORBA.portable.ApplicationException $ex) {
$in = $ex.getInputStream ();
String _id = $ex.getId ();
throw new org.omg.CORBA.MARSHAL (_id);
} catch (org.omg.CORBA.portable.RemarshalException $rm) {
return transferRecord (managerID, recordID, remoteCenterServerName );
} finally {
_releaseReply ($in);
}
} // transferRecord
// Type-specific CORBA::Object operations
private static String[] __ids = {
"IDL:DCMS_FrontEnd/FrontEnd:1.0"};
public String[] _ids ()
{
return (String[])__ids.clone ();
}
private void readObject (java.io.ObjectInputStream s) throws java.io.IOException
{
String str = s.readUTF ();
String[] args = null;
java.util.Properties props = null;
org.omg.CORBA.ORB orb = org.omg.CORBA.ORB.init (args, props);
try {
org.omg.CORBA.Object obj = orb.string_to_object (str);
org.omg.CORBA.portable.Delegate delegate = ((org.omg.CORBA.portable.ObjectImpl) obj)._get_delegate ();
_set_delegate (delegate);
} finally {
orb.destroy() ;
}
}
private void writeObject (java.io.ObjectOutputStream s) throws java.io.IOException
{
String[] args = null;
java.util.Properties props = null;
org.omg.CORBA.ORB orb = org.omg.CORBA.ORB.init (args, props);
try {
String str = orb.object_to_string (this);
s.writeUTF (str);
} finally {
orb.destroy() ;
}
}
} // class _FrontEndStub
| [
"[email protected]"
] | |
9b419ac9e57cc461b10bde501edbdcf71c3a148a | faac256e67bdcb268054939c5f841d8b706f52e1 | /app/src/main/java/zw/co/vokers/zoledge/reader/camera/GraphicOverlay.java | c408e58373d69e2ac302d4f1d2a8aa1cec34316d | [] | no_license | VinceGee/ZOLEdge | 9b425e3f588277c344921bf13e81d6441c8f74ce | 6dd48be95b22ac20fce4e95ca04b054f6f2b3e68 | refs/heads/master | 2020-03-22T05:40:06.390930 | 2018-07-03T12:46:12 | 2018-07-03T12:46:12 | 139,582,319 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 7,141 | java | /*
* Copyright (C) The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package zw.co.vokers.zoledge.reader.camera;
import android.content.Context;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.view.View;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.Vector;
/**
* A view which renders a series of custom graphics to be overlayed on top of an associated preview
* (i.e., the camera preview). The creator can add graphics objects, update the objects, and remove
* them, triggering the appropriate drawing and invalidation within the view.<p>
*
* Supports scaling and mirroring of the graphics relative the camera's preview properties. The
* idea is that detection items are expressed in terms of a preview size, but need to be scaled up
* to the full view size, and also mirrored in the case of the front-facing camera.<p>
*
* Associated {@link Graphic} items should use the following methods to convert to view coordinates
* for the graphics that are drawn:
* <ol>
* <li>{@link Graphic#scaleX(float)} and {@link Graphic#scaleY(float)} adjust the size of the
* supplied value from the preview scale to the view scale.</li>
* <li>{@link Graphic#translateX(float)} and {@link Graphic#translateY(float)} adjust the coordinate
* from the preview's coordinate system to the view coordinate system.</li>
* </ol>
*/
public class GraphicOverlay<T extends GraphicOverlay.Graphic> extends View {
private final Object mLock = new Object();
private int mPreviewWidth;
private float mWidthScaleFactor = 1.0f;
private int mPreviewHeight;
private float mHeightScaleFactor = 1.0f;
private int mFacing = CameraSource.CAMERA_FACING_BACK;
private Set<T> mGraphics = new HashSet<>();
/**
* Base class for a custom graphics object to be rendered within the graphic overlay. Subclass
* this and implement the {@link Graphic#draw(Canvas)} method to define the
* graphics element. Add instances to the overlay using {@link GraphicOverlay#add(Graphic)}.
*/
public static abstract class Graphic {
private GraphicOverlay mOverlay;
public Graphic(GraphicOverlay overlay) {
mOverlay = overlay;
}
/**
* Draw the graphic on the supplied canvas. Drawing should use the following methods to
* convert to view coordinates for the graphics that are drawn:
* <ol>
* <li>{@link Graphic#scaleX(float)} and {@link Graphic#scaleY(float)} adjust the size of
* the supplied value from the preview scale to the view scale.</li>
* <li>{@link Graphic#translateX(float)} and {@link Graphic#translateY(float)} adjust the
* coordinate from the preview's coordinate system to the view coordinate system.</li>
* </ol>
*
* @param canvas drawing canvas
*/
public abstract void draw(Canvas canvas);
/**
* Adjusts a horizontal value of the supplied value from the preview scale to the view
* scale.
*/
public float scaleX(float horizontal) {
return horizontal * mOverlay.mWidthScaleFactor;
}
/**
* Adjusts a vertical value of the supplied value from the preview scale to the view scale.
*/
public float scaleY(float vertical) {
return vertical * mOverlay.mHeightScaleFactor;
}
/**
* Adjusts the x coordinate from the preview's coordinate system to the view coordinate
* system.
*/
public float translateX(float x) {
if (mOverlay.mFacing == CameraSource.CAMERA_FACING_FRONT) {
return mOverlay.getWidth() - scaleX(x);
} else {
return scaleX(x);
}
}
/**
* Adjusts the y coordinate from the preview's coordinate system to the view coordinate
* system.
*/
public float translateY(float y) {
return scaleY(y);
}
public void postInvalidate() {
mOverlay.postInvalidate();
}
}
public GraphicOverlay(Context context, AttributeSet attrs) {
super(context, attrs);
}
/**
* Removes all graphics from the overlay.
*/
public void clear() {
synchronized (mLock) {
mGraphics.clear();
}
postInvalidate();
}
/**
* Adds a graphic to the overlay.
*/
public void add(T graphic) {
synchronized (mLock) {
mGraphics.add(graphic);
}
postInvalidate();
}
/**
* Removes a graphic from the overlay.
*/
public void remove(T graphic) {
synchronized (mLock) {
mGraphics.remove(graphic);
}
postInvalidate();
}
/**
* Returns a copy (as a list) of the set of all active graphics.
* @return list of all active graphics.
*/
public List<T> getGraphics() {
synchronized (mLock) {
return new Vector(mGraphics);
}
}
/**
* Returns the horizontal scale factor.
*/
public float getWidthScaleFactor() {
return mWidthScaleFactor;
}
/**
* Returns the vertical scale factor.
*/
public float getHeightScaleFactor() {
return mHeightScaleFactor;
}
/**
* Sets the camera attributes for size and facing direction, which informs how to transform
* image coordinates later.
*/
public void setCameraInfo(int previewWidth, int previewHeight, int facing) {
synchronized (mLock) {
mPreviewWidth = previewWidth;
mPreviewHeight = previewHeight;
mFacing = facing;
}
postInvalidate();
}
/**
* Draws the overlay with its associated graphic objects.
*/
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
synchronized (mLock) {
if ((mPreviewWidth != 0) && (mPreviewHeight != 0)) {
mWidthScaleFactor = (float) canvas.getWidth() / (float) mPreviewWidth;
mHeightScaleFactor = (float) canvas.getHeight() / (float) mPreviewHeight;
}
for (Graphic graphic : mGraphics) {
graphic.draw(canvas);
}
}
}
}
| [
"[email protected]"
] | |
d6633bdaa2723b91b29e4cd81fd8f691905c240e | 7be4ab4e0dd5e26c17373bca27b8b811dc116b31 | /app/src/main/java/larryherb/weathernow/GSON/WindObject.java | 8a3c1b5ce4f49d00cb7757776067271d20d1e75a | [
"MIT"
] | permissive | lherb3/WeatherNow-AndroidApp | 1cc5a7ae86b77b9e5c1f589a096219d6c77dedfc | a471b5d0faa7b284b20dff5e14722a96a2999bb4 | refs/heads/master | 2021-08-19T12:19:41.213602 | 2017-11-26T07:23:51 | 2017-11-26T07:23:51 | 110,650,549 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 333 | java | package larryherb.weathernow.GSON;
import com.google.gson.annotations.SerializedName;
/**
* Created by lherb3 on 11/13/17.
*/
public class WindObject {
@SerializedName("speed")
public double speed;
@SerializedName("deg")
public double
degrees;
@SerializedName("gust")
public double gust;
}
| [
"[email protected]"
] | |
697228fa9e44a5f204e0aa8b7118cba717a797e3 | 17f00d0aecce8af1979f787709c3313a082b384b | /fm-workbench/trusted-build/edu.umn.cs.crisys.smaccm.aadl2camkes/src/edu/umn/cs/crisys/smaccm/aadl2camkes/ast/IdType.java | ffbf4dc65ea34dbb32437c4ec30dc059bb7f2369 | [] | no_license | three-jeeps/smaccm | 490100fc55bc765ea06a08323622520d0457b58f | cfcd09ffb485683c7e59a6674df40e5bd0dcab0a | refs/heads/master | 2021-01-15T14:46:48.785880 | 2015-01-08T02:32:52 | 2015-01-08T02:32:52 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,985 | java | /*
Copyright (c) 2011,2013 Rockwell Collins and the University of Minnesota.
Developed with the sponsorship of the Defense Advanced Research Projects Agency (DARPA).
Permission is hereby granted, free of charge, to any person obtaining a copy of this data,
including any software or models in source or binary form, as well as any drawings, specifications,
and documentation (collectively "the Data"), to deal in the Data without restriction, including
without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Data, and to permit persons to whom the Data is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or
substantial portions of the Data.
THE DATA IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS, SPONSORS, DEVELOPERS, CONTRIBUTORS, OR COPYRIGHT HOLDERS BE LIABLE
FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE DATA OR THE USE OR OTHER DEALINGS IN THE DATA.
*/
package edu.umn.cs.crisys.smaccm.aadl2camkes.ast;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import edu.umn.cs.crisys.smaccm.aadl2camkes.Aadl2CamkesException;
import edu.umn.cs.crisys.smaccm.aadl2camkes.Aadl2CamkesFailure;
public class IdType extends Type {
private final String typeId;
private Type typeRef = null;
public IdType(String tid) {
typeId = tid;
}
public String getTypeId() {
return typeId;
}
// TODO: this may be problematic for type aliases.
// Type aliases are not supported in CORBA IDL.
public boolean isBaseType() { return false ; }
public Type getTypeRef() { return typeRef; }
private Type getRootTypeInt(Set<Type> visited) {
if (visited.contains(this)) {
throw new Aadl2CamkesException("Circular reference in ids for type " + typeId);
}
else if (typeRef instanceof IdType) {
visited.add(this);
return ((IdType)typeRef).getRootTypeInt(visited);
}
else {
return typeRef;
}
}
@Override
public Type getRootType() throws Aadl2CamkesFailure {
Set<Type> visited = new HashSet<Type>();
try {
return getRootTypeInt(visited);
} catch (Aadl2CamkesException e) {
Aadl2CamkesFailure f = new Aadl2CamkesFailure();
f.addMessage(e.toString());
f.addMessage("Circular reference in ids for type " + typeId);
throw f;
}
}
@Override
public void init(Map<String, Type> types) {
assert(types != null);
Type ty = types.get(typeId);
if (ty == null) {
throw new Aadl2CamkesException("Unable to find type " + typeId + " (last lookup: " + typeId + ")");
}
else {
typeRef = ty;
}
}
@Override
public String toString() {
return typeId;
}
}
| [
"[email protected]"
] | |
61c455ea1cb69c5b2d8e3b54ea7c75e55cc70bc0 | fd55f9688db9e059f170bbd270df5f628feb9c4b | /app/src/main/java/com/example/sierzega/projectforclasses/MainActivity.java | d896ff644d13300772df60526c93d078c26f3d16 | [] | no_license | Swierscz/Projectforclasses | b7963b86d9ba2229e1ca169a88ee5dc664005014 | 7b3ba0bf906ba215f95da13ce99d7b8a0d64c73e | refs/heads/master | 2020-03-18T11:46:28.671498 | 2018-05-24T09:10:58 | 2018-05-24T09:10:58 | 134,690,585 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 5,115 | java | package com.example.sierzega.projectforclasses;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class MainActivity extends AppCompatActivity {
private static final String TAG = MainActivity.class.getSimpleName();
private NumberHolder numberHolder;
private ArrayAdapter<String> arrayAdapter;
public static final String BASE_URL = "http://192.168.42.229:8080/";
Retrofit retrofit;
MyApiEndpointInterface apiService;
EditText amountOfNumbersToGenerate, edtTxtAvgValue;
Button btnGenerateNumbers, btnCalculateAvgValue;
ListView listView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
retrofit = new Retrofit.Builder().baseUrl(BASE_URL).addConverterFactory(GsonConverterFactory.create()).build();
apiService = retrofit.create(MyApiEndpointInterface.class);
numberHolder = NumberHolder.getInstance();
initializeViewComponents();
btnGenerateNumbers.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
numberHolder.fillListWithData(getRandomNumbersFromServer());
updateListOfNumbersWithGeneratedValues();
}
});
thread.start();
}
});
btnCalculateAvgValue.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
apiService.sendNumbersValues(numberHolder.getListOfIntegers()).enqueue(new Callback<List<Integer>>() {
@Override
public void onResponse(Call<List<Integer>> call, Response<List<Integer>> response) {
getAvgValueFromServerAndUpdateTextField();
}
@Override
public void onFailure(Call<List<Integer>> call, Throwable t) {
Log.i(TAG, "Sending numbers failed");
}
});
}
});
thread.start();
}
});
}
private void updateListOfNumbersWithGeneratedValues() {
arrayAdapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, ListConversionUtils.convertIntegersToStringsInList(numberHolder.getListOfIntegers()));
runOnUiThread(new Runnable() {
@Override
public void run() {
listView.setAdapter(arrayAdapter);
}
});
}
private void initializeViewComponents() {
btnGenerateNumbers = (Button) findViewById(R.id.btnGenerateNumbers);
btnCalculateAvgValue = (Button) findViewById(R.id.btnCalculateAvgValue);
listView = (ListView) findViewById(R.id.lvListOfNumbers);
amountOfNumbersToGenerate = (EditText) findViewById(R.id.edtTxtAmountOfNumbersToGenerate);
edtTxtAvgValue = (EditText) findViewById(R.id.edtTxtAvgValue);
}
public List<Integer> getRandomNumbersFromServer() {
Call<List<Integer>> callWithListOfNumbers = apiService.getRandomNumbers(Integer.parseInt(amountOfNumbersToGenerate.getText().toString()));
List<Integer> tempList;
try {
tempList = callWithListOfNumbers.execute().body();
return tempList;
} catch (IOException e) {
e.printStackTrace();
}
return new ArrayList<>();
}
public void getAvgValueFromServerAndUpdateTextField() {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
final Call<Integer> callValue = apiService.getAvgValue();
int i = 0;
try {
i = callValue.execute().body();
} catch (IOException e) {
e.printStackTrace();
}
final int finalI = i;
runOnUiThread(new Runnable() {
@Override
public void run() {
edtTxtAvgValue.setText("" + finalI);
}
});
}
});
thread.start();
}
}
| [
"[email protected]"
] | |
20a7fa62ab28dab7fe1434e3b9d4f28a1d815e4c | e2837676303164d27f42dbcfbcf8cbbf6659ed02 | /microservice-course-management/src/main/java/com/sha/microservicecoursemanagement/repository/CourseRepository.java | e7e946f69c34efeca12f21922ba49cab2b867850 | [] | no_license | erkan4534/microservices | 2860e135bfa9c37421536844cb58247a5e2fca92 | ad5d428f0f56b5e15ebe6e3f8a4d9d82cbd4a836 | refs/heads/main | 2023-04-24T10:10:06.697476 | 2021-05-16T18:57:20 | 2021-05-16T18:57:20 | 358,974,175 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 252 | java | package com.sha.microservicecoursemanagement.repository;
import com.sha.microservicecoursemanagement.model.Course;
import org.springframework.data.jpa.repository.JpaRepository;
public interface CourseRepository extends JpaRepository<Course,Long> {
}
| [
"[email protected]"
] | |
a94a67b2223b07c2b730132a93f0a5869353712b | d785d788a3f4765ad998795a7dfb3607acbca81a | /ACSL_base/src/org/dalton/acsl3/abc15/ACSL3_ABC15_c16mn.java | de39bed478ee37504de8ad76be9675011348de7b | [] | no_license | daltonschool/ACSL_base | 6f77c6dd39e16061ee96b0abd50946206e1a7cbe | c021472f4cb4f0476652eb4e3f96039dd5150861 | refs/heads/master | 2021-05-04T11:18:51.860150 | 2017-01-03T03:42:14 | 2017-01-03T03:42:14 | 46,642,526 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 6,301 | java | package org.dalton.acsl3.abc15;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
public class ACSL3_ABC15_c16mn {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
while(true){
String[][] grid = new String[6][6];
gridSetter(grid);
String[] input = scan.nextLine().split(", ");
for (int i = 0; i < 4; i++) {
//parsing double array values from grid position
grid[Integer.valueOf(input[i])/6][Integer.valueOf(input[i])%6 - 1] = "X";
}
//placing initial letters on grid
int counter = 0;
for (int i = 6; i < input.length; i+=2) {
if(Integer.valueOf(input[i]) < 7){
int row = 1;
if(grid[row][Integer.valueOf(input[i])-1].equals("X")) row++;
grid[row][Integer.valueOf(input[i])-1] = input[i-1];
}else if(Integer.valueOf(input[i])%6 == 1){
int column = 1;
if(grid[Integer.valueOf(input[i])/6][column].equals("X")) column++;
grid[Integer.valueOf(input[i])/6][column] = input[i-1];
}else if(Integer.valueOf(input[i])%6 == 0){
int column = 4;
if(grid[(Integer.valueOf(input[i])/6)-1][column].equals("X")) column--;
grid[Integer.valueOf(input[i])/6-1][column] = input[i-1];
}else if(Integer.valueOf(input[i]) > 30){
int row = 4;
if(grid[row][(Integer.valueOf(input[i])%6)-1].equals("X")) row--;
grid[row][(Integer.valueOf(input[i])%6)-1] = input[i-1];
}
}
// gridPrinter(gridConverter(grid));
// System.out.println();
grid = gridSolver(gridConverter(grid));
// gridPrinter(grid);
// System.out.println();
System.out.println(gridToString(grid));
}
}
public static String gridToString(String[][] grid){
String result = "";
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[i].length; j++) {
if(!grid[i][j].equals("X") && !grid[i][j].equals("0")) result += grid[i][j];
}
}
return result;
}
public static String[][] gridSolver(String[][] grid){
if(gridChecker(grid)) return grid;
for (int i = 0; i < grid.length; i++) {
grid[i] = missingChecker(grid[i]);
}
String[] column = new String[grid.length];
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < column.length; j++) {
column[j] = grid[j][i];
}
column = missingChecker(column);
for (int j = 0; j < column.length; j++) {
grid[j][i] = column[j];
}
}
// gridPrinter(grid);
// System.out.println();
grid = overlap(grid);
return gridSolver(grid);
}
public static String[][] overlap(String[][] grid){
String[][] columns = new String[grid.length][grid.length];
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[i].length; j++) {
columns[i][j] = grid[j][i];
}
}
for (int i = 0; i < grid.length; i++) {
List<Integer> numzeros = new ArrayList<Integer>();
String letter = "";
for (int j = 0; j < grid[i].length; j++) {
if(grid[i][j] == "0"){
numzeros.add(j);
}
if(!grid[i][j].equals("X") && !grid[i][j].equals("0")) letter = grid[i][j];
}
if(numzeros.size() == 2){
for (int j = 0; j < numzeros.size(); j++) {
if(Arrays.asList(columns[numzeros.get((j+1)%2)]).contains("A") && !Arrays.asList(columns[numzeros.get(j)]).contains("A") && !letter.equals("A")){
grid[i][numzeros.get(j)] = "A";
break;
}else if(Arrays.asList(columns[numzeros.get((j+1)%2)]).contains("B") && !Arrays.asList(columns[numzeros.get(j)]).contains("B") && !letter.equals("B")){
grid[i][numzeros.get(j)] = "B";
break;
}else if(Arrays.asList(columns[numzeros.get((j+1)%2)]).contains("C") && !Arrays.asList(columns[numzeros.get(j)]).contains("C") && !letter.equals("C")){
grid[i][numzeros.get(j)] = "C";
break;
}
}
// System.out.println("row overlap");
// gridPrinter(grid);
// System.out.println();
}
}
for (int i = 0; i < grid.length; i++) {
List<Integer> numzeros = new ArrayList<Integer>();
String letter = "";
for (int j = 0; j < grid[i].length; j++) {
if(grid[j][i] == "0") numzeros.add(j);
letter = grid[j][i];
}
if(numzeros.size() == 2){
for (int j = 0; j < numzeros.size(); j++) {
if(Arrays.asList(grid[numzeros.get((j+1)%2)]).contains("A") && !Arrays.asList(grid[numzeros.get(j)]).contains("A") && !letter.equals("A")){
grid[numzeros.get(j)][i] = "A";
break;
}else if(Arrays.asList(grid[numzeros.get((j+1)%2)]).contains("B") && !Arrays.asList(grid[numzeros.get(j)]).contains("B") && !letter.equals("B")){
grid[numzeros.get(j)][i] = "B";
break;
}else if(Arrays.asList(grid[numzeros.get((j+1)%2)]).contains("C") && !Arrays.asList(grid[numzeros.get(j)]).contains("C") && !letter.equals("C")){
grid[numzeros.get(j)][i] = "C";
break;
}
}
// System.out.println("column overlap");
// gridPrinter(grid);
// System.out.println();
}
}
return grid;
}
public static String[] missingChecker(String[] input){
int letters = 'A' + 'B' + 'C' + 'X';
int zerocount = 0;
int place = 0;
for (int i = 0; i < input.length; i++) {
if(input[i] == "0"){
zerocount ++;
place = i;
}
else letters = letters - input[i].charAt(0);
}
if(zerocount == 1){
char letter = (char) letters;
input[place] = "" + letter;
return input;
}
else return input;
}
public static boolean gridChecker(String[][] grid){
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[i].length; j++) {
if(grid[i][j].equals("0")) return false;
}
}
return true;
}
public static String[][] gridConverter(String[][] grid){
String[][] result = new String[4][4];
int k = 0;
for (int i = 1; i < grid.length; i++) {
int l = 0;
if(i == grid.length - 1) break;
for (int j = 1; j < grid[i].length; j++) {
if(j == grid[i].length - 1) break;
result[k][l] = grid[i][j];
l++;
}
k++;
}
return result;
}
public static void gridSetter(String[][] grid){
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[i].length; j++) {
grid[i][j] = "0";
}
}
}
public static void gridPrinter(String[][] grid){
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[i].length; j++) {
System.out.print(" " + grid[i][j] + " ");
}
System.out.println();
}
}
}
| [
"[email protected]"
] | |
bfd56f800e9e01f8b898cefe8dbefa863d078447 | 7fa9c6b0fa1d0726ae1cda0199716c811a1ea01b | /Crawler/data/BillAction.java | fb6c3939f83e2e11b2dd60c398424fd3fd6e612a | [] | no_license | NayrozD/DD2476-Project | b0ca75799793d8ced8d4d3ba3c43c79bb84a72c0 | 94dfb3c0a470527b069e2e0fd9ee375787ee5532 | refs/heads/master | 2023-03-18T04:04:59.111664 | 2021-03-10T15:03:07 | 2021-03-10T15:03:07 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 6,470 | java | 12
https://raw.githubusercontent.com/Pingvin235/bgerp/master/src/ru/bgcrm/plugin/bgbilling/proto/struts/action/BillAction.java
package ru.bgcrm.plugin.bgbilling.proto.struts.action;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import ru.bgcrm.model.BGException;
import ru.bgcrm.model.SearchResult;
import ru.bgcrm.plugin.bgbilling.proto.dao.BillDAO;
import ru.bgcrm.plugin.bgbilling.proto.model.bill.Bill;
import ru.bgcrm.plugin.bgbilling.proto.model.bill.Invoice;
import ru.bgcrm.plugin.bgbilling.struts.action.BaseAction;
import ru.bgcrm.struts.form.DynActionForm;
import ru.bgcrm.util.Utils;
import ru.bgcrm.util.sql.ConnectionSet;
public class BillAction
extends BaseAction
{
public ActionForward attributeList( ActionMapping mapping,
DynActionForm form,
HttpServletRequest request,
HttpServletResponse response,
ConnectionSet conSet )
throws BGException
{
String billingId = form.getParam( "billingId" );
int contractId = form.getParamInt( "contractId" );
int moduleId = form.getParamInt( "moduleId" );
form.getResponse().setData( "list", new BillDAO( form.getUser(), billingId, moduleId ).getAttributeList( contractId ) );
return processUserTypedForward( conSet, mapping, form, response, "attributeList" );
}
public ActionForward docTypeList( ActionMapping mapping,
DynActionForm form,
HttpServletRequest request,
HttpServletResponse response,
ConnectionSet conSet )
throws BGException
{
String billingId = form.getParam( "billingId" );
int contractId = form.getParamInt( "contractId" );
int moduleId = form.getParamInt( "moduleId" );
BillDAO billDao = new BillDAO( form.getUser(), billingId, moduleId );
form.getResponse().setData( "billTypeList", billDao.getContractDocTypeList( contractId, "bill" ) );
form.getResponse().setData( "invoiceTypeList", billDao.getContractDocTypeList( contractId, "invoice" ) );
return processUserTypedForward( conSet, mapping, form, response, "docTypeList" );
}
public ActionForward docTypeAdd( ActionMapping mapping,
DynActionForm form,
HttpServletRequest request,
HttpServletResponse response,
ConnectionSet conSet )
throws BGException
{
String billingId = form.getParam( "billingId" );
int contractId = form.getParamInt( "contractId" );
int moduleId = form.getParamInt( "moduleId" );
new BillDAO( form.getUser(), billingId, moduleId ).contractDocTypeAdd( contractId, form.getParam( "typeIds" ) );
return processJsonForward( conSet, form, response );
}
public ActionForward docTypeDelete( ActionMapping mapping,
DynActionForm form,
HttpServletRequest request,
HttpServletResponse response,
ConnectionSet conSet )
throws BGException
{
String billingId = form.getParam( "billingId" );
int contractId = form.getParamInt( "contractId" );
int moduleId = form.getParamInt( "moduleId" );
new BillDAO( form.getUser(), billingId, moduleId ).contractDocTypeDelete( contractId, form.getParam( "typeIds" ) );
return processJsonForward( conSet, form, response );
}
public ActionForward documentList( ActionMapping mapping,
DynActionForm form,
HttpServletRequest request,
HttpServletResponse response,
ConnectionSet conSet )
throws BGException
{
String billingId = form.getParam( "billingId" );
int contractId = form.getParamInt( "contractId" );
int moduleId = form.getParamInt( "moduleId" );
String mode = form.getParam( "mode", "bill" );
form.setParam( "mode", mode );
BillDAO billDao = new BillDAO( form.getUser(), billingId, moduleId );
if( "bill".equals( mode ) )
{
billDao.searchBillList( contractId, new SearchResult<Bill>( form ) );
}
else
{
billDao.searchInvoiceList( contractId, new SearchResult<Invoice>( form ) );
}
return processUserTypedForward( conSet, mapping, form, response, "documentList" );
}
public ActionForward getDocument( ActionMapping mapping,
DynActionForm form,
HttpServletRequest request,
HttpServletResponse response,
ConnectionSet conSet )
throws BGException
{
String billingId = form.getParam( "billingId" );
int moduleId = form.getParamInt( "moduleId" );
String type = form.getParam( "type" );
String ids = form.getParam( "ids" );
try
{
OutputStream out = response.getOutputStream();
Utils.setFileNameHeades( response, type + ".pdf" );
out.write( new BillDAO( form.getUser(), billingId, moduleId ).getDocumentsPdf( ids, type ) );
}
catch( Exception ex )
{
throw new BGException( ex );
}
return null;
}
public ActionForward setPayed( ActionMapping mapping,
DynActionForm form,
HttpServletRequest request,
HttpServletResponse response,
ConnectionSet conSet )
throws BGException
{
String billingId = form.getParam( "billingId" );
int moduleId = form.getParamInt( "moduleId" );
String ids = form.getParam( "ids" );
Date date = form.getParamDate( "date" );
BigDecimal summa = Utils.parseBigDecimal( form.getParam( "summa" ) );
String comment = form.getParam( "comment" );
BillDAO billDao = new BillDAO( form.getUser(), billingId, moduleId );
if( date != null )
{
billDao.setPayed( ids, true, date, summa, comment );
}
else
{
billDao.setPayed( ids, false, null, null, null );
}
return processJsonForward( conSet, form, response );
}
} | [
"[email protected]"
] | |
fc6973d79bbdb96d33753f38df9c5917a1e88a34 | 54d572858271c6ef357daebeabc4d0e0967a4163 | /src/LeetCode076.java | 2b7a2fa09d71939724222be885c2cfaf905af462 | [] | no_license | WHJ1101/leetcode | 6dba763d1467e3207b3749d723c5a871d1836e67 | feeed099e7104a497e0f6c4d4b8a11e32881d0e6 | refs/heads/master | 2022-11-20T10:08:56.253456 | 2020-07-19T18:39:45 | 2020-07-19T18:39:45 | 263,327,418 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,636 | java | import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
class LeetCode076 {
Map<Character, Integer> ori = new HashMap<Character, Integer>();
Map<Character, Integer> cnt = new HashMap<Character, Integer>();
public String minWindow(String s, String t) {
int tLen = t.length();
for (int i = 0; i < tLen; i++) {
char c = t.charAt(i);
ori.put(c, ori.getOrDefault(c, 0) + 1);
}
int l = 0, r = -1;
int len = Integer.MAX_VALUE, ansL = -1, ansR = -1;
int sLen = s.length();
while (r < sLen) {
++r;
if (r < sLen && ori.containsKey(s.charAt(r))) {
cnt.put(s.charAt(r), cnt.getOrDefault(s.charAt(r), 0) + 1);
}
while (check() && l <= r) {
if (r - l + 1 < len) {
len = r - l + 1;
ansL = l;
ansR = l + len;
}
if (ori.containsKey(s.charAt(l))) {
cnt.put(s.charAt(l), cnt.getOrDefault(s.charAt(l), 0) - 1);
}
++l;
}
}
return ansL == -1 ? "" : s.substring(ansL, ansR);
}
public boolean check() {
Iterator iter = ori.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry entry = (Map.Entry) iter.next();
Character key = (Character) entry.getKey();
Integer val = (Integer) entry.getValue();
if (cnt.getOrDefault(key, 0) < val) {
return false;
}
}
return true;
}
}
| [
"[email protected]"
] | |
eb6fa10f5235e4366e48c781160a1eb06e5e701c | 947edc58e161933b70d595242d4663a6d0e68623 | /pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/service/CtcdMantissaService.java | a56df4b12d388aa5d94897b207d7a97a2743c940 | [] | no_license | jieke360/pig6 | 5a5de28b0e4785ff8872e7259fc46d1f5286d4d9 | 8413feed8339fab804b11af8d3fbab406eb80b68 | refs/heads/master | 2023-02-04T12:39:34.279157 | 2020-12-31T03:57:43 | 2020-12-31T03:57:43 | 325,705,631 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,118 | java | /*
* Copyright (c) 2018-2025, lengleng All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* Neither the name of the pig4cloud.com developer nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
* Author: lengleng ([email protected])
*/
package com.pig4cloud.pigx.admin.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.pig4cloud.pigx.admin.entity.CtcdMantissa;
/**
* 进位类型
*
* @author gaoxiao
* @date 2020-08-12 11:37:07
*/
public interface CtcdMantissaService extends IService<CtcdMantissa> {
}
| [
"[email protected]"
] | |
6dc52096d920e5d26d895b2c54fbf6a815953e69 | 6bfc5a1efdbbe337dca4a71c3ed53054bf662a82 | /src/grimonium/set/GrimoniumSet.java | ac144c367c19765c2d291ce920b6c2003d67c4dc | [] | no_license | michaelforrest/grimonium | d99945779edbc08654eea97c687d8ffb0ecf21fd | 1f582d8f59e262ee84a28ddebf0e5741392fa78e | refs/heads/master | 2021-01-16T19:33:29.737744 | 2009-02-12T17:44:47 | 2009-02-12T17:44:47 | 97,209 | 2 | 1 | null | null | null | null | UTF-8 | Java | false | false | 3,191 | java | package grimonium.set;
import grimonium.Ableton;
import grimonium.GrimoniumOutput;
import grimonium.Ableton.MidiTrack;
import grimonium.gui.Colours;
import grimonium.gui.MixerSource;
import grimonium.maps.ElementFactory;
import grimonium.maps.EncoderMap;
import grimonium.maps.FaderMap;
import grimonium.maps.MapBase;
import java.util.ArrayList;
import microkontrol.MicroKontrol;
import microkontrol.controls.Button;
import microkontrol.controls.EncoderListener;
import processing.xml.XMLElement;
public class GrimoniumSet extends CollectionWithSingleSelectedItem implements EncoderListener, MixerSource{
public Song[] songs;
private MicroKontrol mk;
private MapBase[] commonElements;
private Song beforeShiftPressed;
public GrimoniumSet(XMLElement child) {
if(!child.getName().equals("set")) return;
mk = MicroKontrol.getInstance();
addCommon(child.getChild("common"));
addSongs(child.getChildren("songs/song"));
setCollection(songs);
activateSong(0);
mk.encoders[8].listen(this);
mk.buttons.get("HEX LOCK").listen(Button.PRESSED,this,"onShiftPressed" );
mk.buttons.get("HEX LOCK").listen(Button.RELEASED,this,"onShiftReleased" );
}
public void onShiftPressed(){
beforeShiftPressed = current();
select(songs[songs.length-1]);
GuiController.update();
}
public void onShiftReleased(){
select(beforeShiftPressed);
GuiController.update();
}
private void addCommon(XMLElement child) {
commonElements = new MapBase[child.getChildren().length];
for (int i = 0; i < child.getChildren().length; i++) {
XMLElement element = child.getChildren()[i];
MapBase control = ElementFactory.create(element);
control.activate();
commonElements[i] = control;
}
}
private void activateSong(int index) {
select(songs[index]);
}
@Override
public void select(Object object) {
if(current() != null) current().deactivate();
super.select(object);
current().activate();
GrimoniumOutput.visualsChanged(current().visuals);
}
public Song current() {
return (Song) super.current();
}
private void addSongs(XMLElement[] children) {
songs = new Song[children.length];
for (int i = 0; i < children.length; i++) {
XMLElement element = children[i];
Song song = new Song(element);
songs[i] = song;
}
}
public void moved(Integer delta) {
changeSelectionByOffset(delta);
}
public Song currentSong() {
return current();
}
public ArrayList<EncoderMap> getEncoders() {
return MapBase.collectEncoders(commonElements);
}
public ArrayList<FaderMap> getFaders() {
return MapBase.collectFaders(commonElements);
}
public int getColour() {
return 0x22000000 + Colours.get("blue");
}
public void previousSong() {
changeSelectionByOffset(-1);
}
public void nextSong() {
changeSelectionByOffset(1);
}
public int getAlpha() {
return 0xFF;
}
public float getTint() {
return 255;
}
public void stopClipsFromOtherSongs() {
for(MidiTrack track : Ableton.midiTracks){
stopTrackUnlessInGroup(track);
}
}
private void stopTrackUnlessInGroup(MidiTrack track) {
for(ClipGroup group : current().groups){
if(group.track == track.channel) return;
}
if(track.stop!=null) track.stop.trigger();
}
}
| [
"[email protected]"
] | |
ef7753dcd8ada2ffe82f87e0e75ecd038cad0157 | df3da3c9dfec9dd15f7ee7159eb833e97c3cbf6a | /src/main/java/com/superapp/firstdemo/ServletInitializer.java | ac3ed64bc9e9e54e28cc4e29d0d675d1e5b550d2 | [] | no_license | alexjcm/vaccination-inventory | ccd4d948a59c68f218b92c7dd81b342976d708d6 | 6775d4b40023ca93299bcec100f8b4db50fac431 | refs/heads/main | 2023-08-28T00:21:42.163532 | 2021-10-13T02:41:37 | 2021-10-13T02:41:37 | 407,659,686 | 0 | 0 | null | 2021-10-13T02:41:37 | 2021-09-17T19:37:19 | Java | UTF-8 | Java | false | false | 429 | java | package com.superapp.firstdemo;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
public class ServletInitializer extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(SuperappApplication.class);
}
}
| [
"[email protected]"
] | |
0fa7cf821791298b2e9b73b63cffe62701d56bdb | 304afb759a91f00809ff49cfc2fbf7606a78d80f | /project_game/src/br/com/casadocodigo/bis/game/scenes/TitleScreen.java | 80b314527722a1f23a2cbf4491338a88890c0780 | [] | no_license | edmatamoros/ProjectGame | 8c1c065733ed532eccef43b37afc60c9d06999ec | 0ae0da2c02d4a652253558a851bcac391e3f07cd | refs/heads/master | 2021-01-19T14:34:34.426315 | 2014-04-05T19:19:47 | 2014-04-05T19:19:47 | null | 0 | 0 | null | null | null | null | ISO-8859-1 | Java | false | false | 1,381 | java | package br.com.casadocodigo.bis.game.scenes;
import static br.com.casadocodigo.bis.config.DeviceSettings.screenHeight;
import static br.com.casadocodigo.bis.config.DeviceSettings.screenResolution;
import static br.com.casadocodigo.bis.config.DeviceSettings.screenWidth;
import org.cocos2d.layers.CCLayer;
import org.cocos2d.layers.CCScene;
import org.cocos2d.nodes.CCSprite;
import org.cocos2d.types.CGPoint;
import br.com.casadocodigo.bis.config.Assets;
import br.com.casadocodigo.bis.game.control.MenuButtons;
import br.com.casadocodigo.bis.screens.ScreenBackground;
public class TitleScreen extends CCLayer {
private ScreenBackground background;
public CCScene scene() {
CCScene scene = CCScene.node();
scene.addChild(this);
return scene;
}
public TitleScreen() {
// background
//Adiciona a imagem Background.png que está
//no diretório assets
this.background = new ScreenBackground(Assets.BACKGROUND);
this.background.setPosition(screenResolution(CGPoint.ccp(screenWidth() / 2.0f, screenHeight() / 2.0f)));
this.addChild(this.background);
// logo
CCSprite title = CCSprite.sprite(Assets.LOGO);
title.setPosition(screenResolution(CGPoint.ccp( screenWidth() /2 , screenHeight() - 130 ))) ;
this.addChild(title);
// Adiciona os botões de opção
MenuButtons menuLayer = new MenuButtons();
this.addChild(menuLayer);
}
}
| [
"[email protected]"
] | |
167aa72e7119a3c3eb83753131e75db87c94ab16 | 07fafdaf3ac44da373434ddda2fb96859247cf4f | /Actividad2Musico.java/src/excepciones/ito/poo/Solicitante.java | 109fd2c6edc4a6304824897c7a5122694931264a | [] | no_license | GerardoGutierrezFeria/PracticaComplementaria | 38311501b67d051cb78238670af8d4681bda2328 | 787543b24d181f4b05fe9a532f7e3b7d59ad618d | refs/heads/master | 2023-06-08T21:40:21.933869 | 2021-06-14T22:25:50 | 2021-06-14T22:25:50 | 376,970,839 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 174 | java | package excepciones.ito.poo;
@SuppressWarnings("serial")
public class Solicitante extends Exception {
public Solicitante(String message) {
super(message);
}
} | [
"Gelexis@LAPTOP-7BJ6TSE7"
] | Gelexis@LAPTOP-7BJ6TSE7 |
46c39f350c077bdf38cf6736fe68fa12a71cd66c | 3f920aaa8826d1aabfe2ee12c3eb1fddda5b6591 | /src/com/pan/Concurrent/SynLockIn_1/Run1.java | 09c915b2026837edc1c2bce9335ca682dd734da4 | [] | no_license | Pan1206/commitMQ | fddf57b3ff8e6f2558b39a590f0b21d7b5c31088 | de45ac8837f345a761aa1b2cf0c0a2b7112dd895 | refs/heads/master | 2020-12-28T15:55:21.356559 | 2020-02-06T09:57:48 | 2020-02-06T09:57:48 | 238,395,740 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,046 | java | package com.pan.Concurrent.SynLockIn_1;
/**
* 1)当存在父子类继承关系时,子类是完全可以通过"可重入锁”调用父类的同步方法的;
* 2)虽然可以使用synchronized来定义方法,但synchronized并不属于方法定义的一部分,
* 因此,synchronized关键字不能被继承。如果在父类中的某个方法使用了synchronized关键字,
* 而在子类中覆盖了这个方法,在子类中的这个方法默认情况下并不是同步的,
* 而必须显式地在子类的这个方法中加上synchronized关键字才可以。
* 当然,还可以在子类方法中调用父类中相应的方法,这样虽然子类中的方法不是同步的,
* 但子类调用了父类的同步方法,因此,子类的方法也就相当于同步了。这两种方式的例子代码如下:
* 在子类方法中加上synchronized关键字
*/
public class Run1 {
public static void main(String[] args) {
MyThread1 myThread1=new MyThread1();
myThread1.start();
}
}
| [
"[email protected]"
] | |
cb9c6d40a2144442aba4ed4a6b22dc421ada380d | 98c049efdfebfafc5373897d491271b4370ab9b4 | /src/main/java/lapr/project/data/PharmacyDB.java | 13e4ba5a59d1a42e2a7a219fb038b76bfd504b30 | [] | no_license | antoniodanielbf-isep/LAPR3-2020 | 3a4f4cc608804f70cc87a3ccb29cbc05f5edf0f3 | 7ee16e8c995aea31c30c858f93e8ebdf1de7617f | refs/heads/main | 2023-05-27T14:42:05.442427 | 2021-06-20T18:09:59 | 2021-06-20T18:09:59 | 378,709,095 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,568 | java | package lapr.project.data;
import lapr.project.model.*;
import oracle.jdbc.OracleTypes;
import java.sql.CallableStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
/**
* The type Pharmacy db.
*/
public class PharmacyDB extends DataHandler {
/**
* Gets all pharmacies.
*
* @return the all pharmacies
*/
public List<Pharmacy> getAllPharmacies() {
List<Pharmacy> pharmacys = new ArrayList<>();
try (CallableStatement callStmt =
getConnection().prepareCall("{ ? = call getAllPharmacys() }")) {
callStmt.registerOutParameter(1, OracleTypes.CURSOR);
callStmt.execute();
ResultSet rSet = (ResultSet) callStmt.getObject(1);
while (rSet.next()) {
int id = rSet.getInt(1);
String designation = rSet.getString(2);
String address = rSet.getString(3);
String pharmacyOwner = rSet.getString(4);
pharmacys.add(new Pharmacy(id, designation, address, pharmacyOwner));
}
return pharmacys;
} catch (SQLException e) {
e.printStackTrace();
}
throw new IllegalArgumentException("No Data Found");
}
/**
* Create pharmacy int.
*
* @param pharmacyOwner the pharmacy owner
* @param designation the designation
* @param address the address
* @return the int
*/
public int createPharmacy(String pharmacyOwner, String designation, Address address) {
Integer pharmacyID;
CallableStatement callStmt = null;
if (!pharmacyOwner.isEmpty() && !designation.isEmpty() && address != null) {
try {
callStmt = getConnection().prepareCall("{ ? = call createPharmacy(?,?,?) }");
callStmt.registerOutParameter(1, OracleTypes.INTEGER);
callStmt.setString(2, pharmacyOwner);
callStmt.setString(3, address.getCoordinates());
callStmt.setString(4, designation);
callStmt.execute();
pharmacyID = (Integer) callStmt.getObject(1);
return pharmacyID;
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
assert callStmt != null;
callStmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
return -1;
}
/**
* Update boolean.
*
* @param pharmacyOwner the pharmacy owner
* @param designation the designation
* @param address the address
* @return the boolean
*/
public boolean update(String pharmacyOwner, String designation, Address address) {
boolean isUpdated = false;
if (!pharmacyOwner.isEmpty() && !designation.isEmpty() && address != null) {
try (CallableStatement callStmt = getConnection().prepareCall("{ call updatePharmacy(?,?,?) }")) {
callStmt.setString(1, pharmacyOwner);
callStmt.setString(2, address.getCoordinates());
callStmt.setString(3, designation);
callStmt.execute();
isUpdated = true;
} catch (SQLException e) {
e.printStackTrace();
}
}
return isUpdated;
}
/**
* Gets pharmacy by user email.
*
* @param email the email
* @return the pharmacy by user email
*/
public Pharmacy getPharmacyByUserEmail(String email) {
CallableStatement callStmt;
Pharmacy pharmacy = null;
try {
callStmt = getConnection().prepareCall("{ ? = call getPharmacyByUserEmail(?) }");
callStmt.registerOutParameter(1, OracleTypes.CURSOR);
callStmt.setString(2, email);
callStmt.execute();
ResultSet rSet = (ResultSet) callStmt.getObject(1);
if (rSet.next()) {
int id = rSet.getInt(1);
String designation = rSet.getString(2);
String adress = rSet.getString(3);
String pharmacyOwner = rSet.getString(4);
closeAll();
pharmacy = new Pharmacy(id, designation, adress, pharmacyOwner);
}
} catch (SQLException e) {
e.printStackTrace();
}
return pharmacy;
}
}
| [
"[email protected]"
] | |
5b4fa101454b89d1ddc5c8cf2238b5bb354ae832 | e3ccc2fef19be175120b8d5073858aef0dce4bd2 | /cs315/util/Iterator.java | dbf6a904ae214d8ea0649ba378b054b6b2ffb50f | [] | no_license | michaeltheitking/Alphametic | c334594325eaf533403ba64a58ad85f978bec6dc | 2ccb8b9204940ec39e718ce04bf6fcee76fbee29 | refs/heads/master | 2021-05-27T19:36:56.066440 | 2014-06-11T17:05:13 | 2014-06-11T17:05:13 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 813 | java | package cs315.util;
/**
* Interface for iterating through all the permutations of a character array.
*
* @author michael king and michael fradkin
* @version 1.0
*/
public interface Iterator
{
/**
* method to determine if loops can be incremented again. <BR>
* post: returns true if iterator can be incremented at least once; otherwise false <BR>
* Complexity: ?? <BR>
* Memory Usage: ?? <BR>
* @return true if iterator can be incremented at least once; otherwise false
*/
boolean hasNext();
/**
* method to increment through the object <BR>
* pre: this.hasNext() == true <BR>
* post: iterator is incremented once <BR>
* Complexity: ??<BR>
* Memory Usage: ??<BR>
* @return the next iteration Object
*/
Object next();
}
| [
"[email protected]"
] | |
78092c6b080afb3e1d796f9fa72075780c6528ca | 11e613c4598c21e9e212413e6fc1fef59d6f2742 | /rxeasyhttp/src/main/java/com/zhouyou/http/cache/converter/GsonDiskConverter.java | f169e864dd8b358860e339da3c438b4e0f181521 | [
"Apache-2.0"
] | permissive | SunnyLy/RxEasyHttp | ed666d91487f90c2f60be1f66669ff34154138d0 | 613e9580a054a5979a6b5c8c7cc48953cb555cff | refs/heads/master | 2020-06-01T15:43:41.051183 | 2017-06-12T08:48:41 | 2017-06-12T08:48:41 | 94,078,502 | 1 | 0 | null | 2017-06-12T09:26:32 | 2017-06-12T09:26:32 | null | UTF-8 | Java | false | false | 3,278 | java | /*
* Copyright (C) 2017 zhouyou([email protected])
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.zhouyou.http.cache.converter;
import com.google.gson.Gson;
import com.google.gson.JsonIOException;
import com.google.gson.JsonSyntaxException;
import com.zhouyou.http.utils.HttpLog;
import com.zhouyou.http.utils.Utils;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.lang.reflect.Type;
/**
* <p>描述:GSON-数据转换器</p>
* 1.GSON-数据转换器其实就是存储字符串的操作<br>
* 2.如果你的Gson有特殊处理,可以自己创建一个,否则用默认。<br>
* <p>
* 优点:<br>
* 相对于SerializableDiskConverter转换器,存储的对象不需要进行序列化(Serializable),<br>
* 特别是一个对象中又包含很多其它对象,每个对象都需要Serializable,比较麻烦<br>
* </p>
* <p>
* <p>
* 缺点:<br>
* 就是存储和读取都要使用Gson进行转换,object->String->Object的给一个过程,相对来说<br>
* 每次都要转换性能略低,但是以现在的手机性能可以忽略不计了。<br>
* </p>
* <p>
* 《-------骚年,自己根据实际需求选择吧!!!------------》<br>
* 《--看到这里,顺便提下知道IDiskConverter的好处了吧,面向接口编程是不是很灵活(*^_^*)----------》<br>
* <p>
* 作者: zhouyou<br>
* 日期: 2016/12/24 17:35<br>
* 版本: v2.0<br>
*/
public class GsonDiskConverter implements IDiskConverter {
private Gson gson;
public GsonDiskConverter() {
this.gson = new Gson();
}
public GsonDiskConverter(Gson gson) {
this.gson = gson;
}
@Override
public <T> T load(InputStream source, Type type) {
T value = null;
try {
if (gson != null) gson = new Gson();
value = gson.fromJson(new InputStreamReader(source), type);
} catch (JsonIOException e) {
HttpLog.e(e.getMessage());
} catch (JsonSyntaxException e) {
HttpLog.e(e.getMessage());
} finally {
Utils.close(source);
}
return value;
}
@Override
public boolean writer(OutputStream sink, Object data) {
try {
String json = gson.toJson(data);
byte[] bytes = json.getBytes();
sink.write(bytes, 0, bytes.length);
sink.flush();
return true;
} catch (JsonIOException e) {
HttpLog.e(e.getMessage());
} catch (JsonSyntaxException e) {
HttpLog.e(e.getMessage());
} catch (IOException e) {
HttpLog.e(e.getMessage());
}
return false;
}
}
| [
"[email protected]"
] | |
2799826ef897ecc63d675b861ed277e69b7523ed | fcf485b7d02986bb294d5add269269276b773d62 | /src/main/java/com/hitesh/test/leetcode/array/AvoidFloodInTheCity.java | 1aa1e406e37ac81addfeab8c538e304fc3a38035 | [] | no_license | hiteshsethiya/codeshadow | 0e38cadb5abcfdb714a308796e1e7f0ab0f5eebb | b67a8177cff6614fff6e69014a0b42ac904af4fc | refs/heads/master | 2022-05-31T08:48:47.035099 | 2020-11-06T10:58:48 | 2020-11-06T10:58:48 | 244,311,764 | 1 | 0 | null | 2022-05-20T21:32:03 | 2020-03-02T07:54:17 | Java | UTF-8 | Java | false | false | 5,424 | java | package com.hitesh.test.leetcode.array;
import java.util.*;
public class AvoidFloodInTheCity {
/*
* Your country has an infinite number of lakes. Initially, all the lakes are empty,
* but when it rains over the nth lake, the nth lake becomes full of water.
* If it rains over a lake which is full of water, there will be a flood.
* Your goal is to avoid the flood in any lake.
*
* Given an integer array rains where:
*
* rains[i] > 0 means there will be rains over the rains[i] lake.
* rains[i] == 0 means there are no rains this day and you can choose one lake this day and dry it.
* Return an array ans where:
*
* ans.length == rains.length
* ans[i] == -1 if rains[i] > 0.
* ans[i] is the lake you choose to dry in the ith day if rains[i] == 0.
* If there are multiple valid answers return any of them. If it is impossible to avoid flood return an empty array.
*
* Notice that if you chose to dry a full lake, it becomes empty, but if you chose to dry an empty lake,
* nothing changes. (see example 4)
*
*
*
* Example 1:
*
* Input: rains = [1,2,3,4]
* Output: [-1,-1,-1,-1]
* Explanation: After the first day full lakes are [1]
* After the second day full lakes are [1,2]
* After the third day full lakes are [1,2,3]
* After the fourth day full lakes are [1,2,3,4]
* There's no day to dry any lake and there is no flood in any lake.
* Example 2:
*
* Input: rains = [1,2,0,0,2,1]
* Output: [-1,-1,2,1,-1,-1]
* Explanation: After the first day full lakes are [1]
* After the second day full lakes are [1,2]
* After the third day, we dry lake 2. Full lakes are [1]
* After the fourth day, we dry lake 1. There is no full lakes.
* After the fifth day, full lakes are [2].
* After the sixth day, full lakes are [1,2].
* It is easy that this scenario is flood-free. [-1,-1,1,2,-1,-1] is another acceptable scenario.
* Example 3:
*
* Input: rains = [1,2,0,1,2]
* Output: []
* Explanation: After the second day, full lakes are [1,2]. We have to dry one lake in the third day.
* After that, it will rain over lakes [1,2]. It's easy to prove that no matter which lake you choose
* to dry in the 3rd day, the other one will flood.
* Example 4:
*
* Input: rains = [69,0,0,0,69]
* Output: [-1,69,1,1,-1]
* Explanation: Any solution on one of the forms [-1,69,x,y,-1], [-1,x,69,y,-1] or [-1,x,y,69,-1]
* is acceptable where 1 <= x,y <= 10^9
* Example 5:
*
* Input: rains = [10,20,20]
* Output: []
* Explanation: It will rain over lake 20 two consecutive days. There is no chance to dry any lake.
*
*
* Constraints:
*
* 1 <= rains.length <= 10^5
* 0 <= rains[i] <= 10^9
*/
private static final int[] EMPTY = new int[0];
public int[] avoidFloodBF(int[] rains) {
int[] ans = new int[rains.length];
Set<Integer> full = new HashSet<>();
int n = rains.length;
for (int i = 0; i < n; ++i) {
int j = i + 1;
if (j < n && rains[i] > 0 && rains[i] == rains[j]) return EMPTY;
if (full.contains(rains[i])) return EMPTY;
if (rains[i] > 0) {
ans[i] = -1;
full.add(rains[i]);
} else if (rains[i] == 0) {
while (j < n && (rains[j] == 0 || !full.contains(rains[j]))) {
j++;
}
if (j < n) {
ans[i] = full.contains(rains[j]) ? rains[j] : 1;
full.remove(ans[i]);
} else {
ans[i] = 1;
}
}
}
return ans;
}
public int[] avoidFlood(int[] rains) {
int[] ans = new int[rains.length];
int n = rains.length;
Map<Integer, Integer> fullLakes = new HashMap<>();
TreeSet<Integer> noRains = new TreeSet<>();
for (int i = 0; i < n; ++i) {
if (rains[i] == 0) {
noRains.add(i);
ans[i] = 1;
} else if (rains[i] > 0) {
if (fullLakes.containsKey(rains[i])) {
Integer canDry = noRains.ceiling(fullLakes.get(rains[i]));
if (canDry == null) return EMPTY;
ans[canDry] = rains[i];
noRains.remove(canDry);
}
fullLakes.put(rains[i], i);
ans[i] = -1;
}
}
return ans;
}
public static void execute(int[] input, int[] ans) {
int[] o = new AvoidFloodInTheCity().avoidFlood(input);
System.out.println(Arrays.toString(o));
System.out.println(Arrays.equals(o, ans));
}
public static void main(String[] args) {
execute(new int[]{1, 2, 0, 2, 3, 0, 1}, new int[]{-1, -1, 2, -1, -1, 1, -1});
execute(new int[]{1, 0, 2, 0, 2, 1}, new int[]{-1, 1, -1, 2, -1, -1});
execute(new int[]{1, 2, 3, 4}, new int[]{-1, -1, -1, -1});
execute(new int[]{1, 2, 0, 0, 2, 1}, new int[]{-1, -1, 2, 1, -1, -1});
execute(new int[]{1, 2, 0, 1, 2}, new int[]{});
execute(new int[]{69, 0, 0, 0, 69}, new int[]{-1, 69, 1, 1, -1});
execute(new int[]{10, 20, 20}, new int[]{});
}
}
| [
"[email protected]"
] | |
09c83816c924837db9326db80308815bf73ad378 | 8fc81eec28b4f41984c78a5474f8925d2921f8d8 | /algorithms/src/main/java/exigentech/codility/practice/foresee/Problem.java | d8590038e7dae06dd94addf0fa1ce31d70f96ead | [] | no_license | anecula/cracking-the-coding-interview | 63db00bb85448522b5582dc427b166c68b1d8d40 | 9b1a72073448a92663488b8f71c9f9d6006bcc0b | refs/heads/master | 2020-03-29T23:43:17.754532 | 2018-06-18T13:20:29 | 2018-06-18T13:20:29 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,268 | java | package exigentech.codility.practice.foresee;
import java.util.Random;
enum RandomValueGenerator {
SOLUTION;
private static Random RANDOM = new Random();
/**
* @return Randomized integer such that {@code lowerBound < n < upperBound}
*/
int betweenBounds(int lowerBound, int upperBound) {
return RANDOM.nextInt(upperBound - lowerBound) + lowerBound;
}
}
final class Solution {
private static int UPPER_BOUND = Double.valueOf(Math.pow(10, 9)).intValue();
private static int MULTIPLE_OF = 10;
/**
* @return Randomized multiple of 10 (x) such that {@code n < x < 10^9}.
*/
int solution(int n) {
if (n == UPPER_BOUND - 1) {
// Since the return value must be greater than n and a multiple of 10,
// UPPER_BOUND is the only valid value.
return UPPER_BOUND;
}
if (n >= UPPER_BOUND) {
throw new IllegalArgumentException("Input n must be strictly < " + UPPER_BOUND);
}
final int boundedRandom = RandomValueGenerator.SOLUTION.betweenBounds(n + 1, UPPER_BOUND);
final int mod = boundedRandom % MULTIPLE_OF;
if (mod == 0) {
return boundedRandom;
}
if (boundedRandom - mod == n) {
return boundedRandom + (MULTIPLE_OF - mod);
}
return boundedRandom - mod;
}
}
| [
"[email protected]"
] | |
ac314f805506a3413e897d2324c98f875d776490 | ff0e2cd24bc598f2d40a1aef179f107c0b5986aa | /src/main/java/com/geekerstar/job/configure/ScheduleConfigure.java | 1d0c878d7b2752a0b9827084b84c86c5c6e39231 | [] | no_license | geekerstar/geek-fast | 8ecc7eabae4e3c35e9619d9f02876fb9d2484511 | 212ff294aaf5c04ac2cc2f6f0e5446db1932282a | refs/heads/master | 2022-09-17T09:59:59.340773 | 2020-08-06T08:37:14 | 2020-08-06T08:37:14 | 226,278,168 | 1 | 0 | null | 2022-09-01T23:17:27 | 2019-12-06T08:11:18 | Java | UTF-8 | Java | false | false | 2,268 | java | package com.geekerstar.job.configure;
import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import javax.sql.DataSource;
import java.util.Properties;
/**
* @author geekerstar
* @date 2020/2/2 12:39
* @description
*/
@Configuration
@RequiredArgsConstructor
public class ScheduleConfigure {
private final DynamicRoutingDataSource dynamicRoutingDataSource;
@Bean
public SchedulerFactoryBean schedulerFactoryBean() {
SchedulerFactoryBean factory = new SchedulerFactoryBean();
// 手动从多数据源中获取 quartz数据源
DataSource quartz = dynamicRoutingDataSource.getDataSource("quartz");
factory.setDataSource(quartz);
// quartz参数
Properties prop = new Properties();
prop.put("org.quartz.scheduler.instanceName", "MyScheduler");
prop.put("org.quartz.scheduler.instanceId", "AUTO");
// 线程池配置
prop.put("org.quartz.threadPool.class", "org.quartz.simpl.SimpleThreadPool");
prop.put("org.quartz.threadPool.threadCount", "20");
prop.put("org.quartz.threadPool.threadPriority", "5");
// JobStore配置
prop.put("org.quartz.jobStore.class", "org.quartz.impl.jdbcjobstore.JobStoreTX");
// 集群配置
prop.put("org.quartz.jobStore.isClustered", "true");
prop.put("org.quartz.jobStore.clusterCheckinInterval", "15000");
prop.put("org.quartz.jobStore.maxMisfiresToHandleAtATime", "1");
prop.put("org.quartz.jobStore.misfireThreshold", "12000");
prop.put("org.quartz.jobStore.tablePrefix", "QRTZ_");
factory.setQuartzProperties(prop);
factory.setSchedulerName("Geek_Scheduler");
// 延时启动
factory.setStartupDelay(1);
factory.setApplicationContextSchedulerContextKey("applicationContextKey");
// 启动时更新己存在的 Job
factory.setOverwriteExistingJobs(true);
// 设置自动启动,默认为 true
factory.setAutoStartup(true);
return factory;
}
}
| [
"[email protected]"
] | |
d9ab219428c327d63c0ffa1063dbb4ed504bdd06 | 0d8f6066839539aceaa2e0e01b666b37b8288ee6 | /src/main/java/com/stardust/easyassess/track/services/FormService.java | feb75dc1ee2e08341271845727cbfa5617bfc087 | [
"MIT"
] | permissive | EasyAssessSystem/track | 4d4dcdf37696b09082e8538ad4bf0fad5771780c | 3c3a6b358e5fb7531695ad7140a56b1ad6d36e7d | refs/heads/master | 2020-09-15T09:21:46.391690 | 2018-03-29T07:37:13 | 2018-03-29T07:37:13 | 66,845,229 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 196 | java | package com.stardust.easyassess.track.services;
import com.stardust.easyassess.track.models.form.Form;
public interface FormService extends EntityService<Form> {
Form submit(Form form);
}
| [
"[email protected]"
] | |
4746b6b544c6558cac029dac115bc3ae8ceb4253 | 717a2db8128c1a214a86de6acfcd51f64233c1b6 | /src/main/java/com/olympians/controllers/UserController.java | 4cade2d02df2c19f9ce82c75a8500e85c37d0132 | [] | no_license | java24july-ank-meh/Olympians | e300e1c8d32794d71b5ae82efdadd6535bef5161 | d561c04cef38db4c83889cced112e3d20bc7489f | refs/heads/master | 2021-01-22T14:21:02.671263 | 2017-09-12T19:09:54 | 2017-09-12T19:09:54 | 100,714,218 | 0 | 0 | null | 2017-08-25T19:20:10 | 2017-08-18T13:24:17 | HTML | UTF-8 | Java | false | false | 2,989 | java | package com.olympians.controllers;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import com.olympians.Dao.DaoInterface;
import com.olympians.beans.Person;
import com.olympians.beans.PersonImpl;
@Controller
@RequestMapping("/usercontroller")
public class UserController {
@Autowired
Person loggedIn;
@Autowired
DaoInterface dao;
public UserController() {
super();
// TODO Auto-generated constructor stub
}
public UserController(Person loggedIn, DaoInterface dao) {
super();
this.loggedIn = loggedIn;
this.dao = dao;
}
public Person getLoggedIn() {
return loggedIn;
}
public void setLoggedIn(Person loggedIn) {
this.loggedIn = loggedIn;
}
public DaoInterface getDao() {
return dao;
}
public void setDao(DaoInterface dao) {
this.dao = dao;
}
@RequestMapping("/all")
public ResponseEntity<Object> allUserFields(HttpServletRequest req){
List<Person> result = new ArrayList<>();
Person toReturn = null;
try{toReturn = dao.GetPersonbyUserName(loggedIn.getUsername());}
catch(Exception e) {e.printStackTrace();}
System.out.println("In allUserFields: " + toReturn);
result.add(toReturn);
return ResponseEntity.ok(result);
}
@RequestMapping("/edit")
public String editUserFields(HttpServletRequest req){
Person person = null;
try{person = dao.GetPersonbyUserName(loggedIn.getUsername());}
catch(Exception e ) {e.printStackTrace();}
String fname = req.getParameter("fname");
String lname = req.getParameter("lname");
String username = req.getParameter("uname");
String opword = req.getParameter("opword");
String npword = req.getParameter("npword");
String email = req.getParameter("email");
if(!opword.equals(person.getPassword()) || !(opword.equals(npword))) {
}
else {
dao.EditAccount(person, fname, lname, username, npword, email);
}
return "redirect:homepage";
}
@RequestMapping("/new")
public String newUser(HttpServletRequest req) {
//forward:url lets you forward request from one controller to another
String fname = req.getParameter("fname");
String lname = req.getParameter("lname");
String username = req.getParameter("user1");
String email = req.getParameter("email");
String password = req.getParameter("pass1");
loggedIn.setFname(fname);
loggedIn.setLname(lname);
loggedIn.setUsername(username);
loggedIn.setEmail(email);
loggedIn.setPassword(password);
try {dao.CreateUser(fname, lname, username, password, email);}
catch(Exception e) {return "redirect:/";}
return "redirect:/homepage";
}
}
| [
"chpalmour@gmail"
] | chpalmour@gmail |
f0c71db39a7497ee09f0e8e38f5df9dca8783d06 | 4aabb2b37e6a9d8248d59139db9e4b9a2e8213ea | /app/src/main/java/com/technextit/emergency/ContactListFragment.java | 90242f27289c8c4258b19e48a971b8924def60f7 | [] | no_license | Nebir/EmergencyBD | a2a835b0fb9b5d6702a5c5fa3255455d82806843 | 6693eac35f76e8be844b8281e8b3be3e76ee91ef | refs/heads/master | 2020-03-30T19:14:18.524232 | 2018-10-04T07:30:32 | 2018-10-04T07:30:32 | 151,528,057 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,051 | java | package com.technextit.emergency;
import android.app.ActionBar;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.Toast;
import com.android.volley.VolleyError;
import com.technextit.emergency.adapter.ContactListAdapter;
import com.technextit.emergency.app.AppController;
import com.technextit.emergency.http.Client;
import com.technextit.emergency.listener.VolleyResponseHandler;
import com.technextit.emergency.model.Contact;
import com.technextit.emergency.model.Contacts;
import com.technextit.emergency.model.Division;
import com.technextit.emergency.model.Service;
import com.technextit.emergency.utils.URLUtils;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/**
* A simple {@link Fragment} subclass.
*/
public class ContactListFragment extends Fragment implements ActionBar.TabListener{
private static final String ARG_SECTION_NUMBER = "section_number";
private static final String SELECTED_SERVICE_POS = "selected_service_pos";
public ContactListAdapter contactListAdapter;
public List<Contact> contacts;
public ListView listView;
public static ContactListFragment newInstance(int selectedDivision, int selectedService) {
ContactListFragment fragment = new ContactListFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, selectedDivision);
args.putInt(SELECTED_SERVICE_POS, selectedService);
fragment.setArguments(args);
return fragment;
}
public ContactListFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_contact_list, container, false);
// int servicePos = savedInstanceState.getInt(SELECTED_SERVICE_POS);
// int divisionPos = savedInstanceState.getInt(ARG_SECTION_NUMBER);
listView = (ListView) view.findViewById(R.id.contactListView);
contacts = new ArrayList<Contact>();
contactListAdapter = new ContactListAdapter(getActivity(), contacts);
listView.setAdapter(contactListAdapter);
HashMap<String, String> params = new HashMap<String, String>();
// Service service = AppController.getInstance().getServices().get(servicePos);
// Division division = AppController.getInstance().getDivisions().get(divisionPos);
//
// params.put("serviceId", ""+service.getId());
// params.put("divisionId", ""+division.getId());
Client.post(URLUtils.URL_CONTACTS, params, Contacts.class, null, new VolleyResponseHandler<Contacts>() {
@Override
public void onSuccess(Contacts response) {
if (response.contacts != null) {
contactListAdapter.setContacts(response.contacts);
}
Log.e("Key", "SIze of divisions-- " + response.contacts.size());
Toast.makeText(getActivity(), "Test--> " + response.contacts.size(), Toast.LENGTH_SHORT).show();
contactListAdapter.notifyDataSetChanged();
}
@Override
public void onError(VolleyError error) {
Toast.makeText(getActivity(), "Test--> " + error.getMessage(), Toast.LENGTH_SHORT).show();
Log.e("Key", "error-- " + error.getMessage());
}
});
return view;
}
@Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {
}
@Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction ft) {
}
@Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction ft) {
}
}
| [
"[email protected]"
] | |
adf875c74ce9337df923d37f915e073a3c4272e4 | 2855a6068ec8af1c39895d12cb12e13ce2ffc2df | /rxandroidjmdns/src/main/java/com/hoanglm/rxandroidjmdns/dagger/ServiceConnectorScope.java | a7befd09c5f66fe546eefe01bf47076fc4b37990 | [] | no_license | inpyokim/RxAndroidJmDNS | b3af6228d4cbf68398bb2425ce4f0d1d578463fe | 3651bb553541407e9f080c690fc2dec75c325d17 | refs/heads/master | 2020-07-07T08:14:47.012771 | 2018-05-30T04:32:15 | 2018-05-30T04:32:15 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 244 | java | package com.hoanglm.rxandroidjmdns.dagger;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import javax.inject.Scope;
@Scope
@Retention(RetentionPolicy.RUNTIME)
public @interface ServiceConnectorScope {
} | [
"[email protected]"
] | |
446730cf20197d5b9a4a0227c4ed55148a840a05 | 9276f9c42a4feb5e5e89bce9dd99511d7f029f6b | /src/main/java/com/evacipated/cardcrawl/mod/stslib/fields/cards/AbstractCard/SneckoField.java | 299facfbfb92c75b2a24b6d51d80ae1fa987aa4b | [
"MIT"
] | permissive | kiooeht/StSLib | b520d67aeb11bc40de391f3f806134b911d36b2c | 6d9b5e020ff7b608308ad1abb8f1f6b1682afecf | refs/heads/master | 2023-08-17T05:04:50.315903 | 2023-08-15T21:26:33 | 2023-08-15T21:26:33 | 140,659,888 | 84 | 52 | MIT | 2023-09-13T06:00:52 | 2018-07-12T04:13:35 | Java | UTF-8 | Java | false | false | 977 | java | package com.evacipated.cardcrawl.mod.stslib.fields.cards.AbstractCard;
import com.evacipated.cardcrawl.modthespire.lib.SpireField;
import com.evacipated.cardcrawl.modthespire.lib.SpirePatch;
import com.megacrit.cardcrawl.cards.AbstractCard;
@SpirePatch(
cls="com.megacrit.cardcrawl.cards.AbstractCard",
method=SpirePatch.CLASS
)
public class SneckoField
{
public static SpireField<Boolean> snecko = new SneckoFieldType(() -> false);
// This is done so card cost is automatically set to -1
private static class SneckoFieldType extends SpireField<Boolean>
{
SneckoFieldType(DefaultValue<Boolean> defaultValue)
{
super(defaultValue);
}
@Override
public void set(Object __intance, Boolean value)
{
super.set(__intance, value);
if (value && __intance instanceof AbstractCard) {
((AbstractCard)__intance).cost = -1;
}
}
}
} | [
"[email protected]"
] | |
ff98d444a76c9ed4adc51d22e5ffd2d31ae36c78 | fa91450deb625cda070e82d5c31770be5ca1dec6 | /Diff-Raw-Data/2/2_8b9964737428c70f8d86878f19a66348aa0e4bd5/OptionFrameV2/2_8b9964737428c70f8d86878f19a66348aa0e4bd5_OptionFrameV2_t.java | f6d0e7075e4a390727a9bdaa95fb5bb35ac2a70e | [] | no_license | zhongxingyu/Seer | 48e7e5197624d7afa94d23f849f8ea2075bcaec0 | c11a3109fdfca9be337e509ecb2c085b60076213 | refs/heads/master | 2023-07-06T12:48:55.516692 | 2023-06-22T07:55:56 | 2023-06-22T07:55:56 | 259,613,157 | 6 | 2 | null | 2023-06-22T07:55:57 | 2020-04-28T11:07:49 | null | UTF-8 | Java | false | false | 25,981 | java | /* OpenLogViewer
*
* Copyright 2011
*
* This file is part of the OpenLogViewer project.
*
* OpenLogViewer software 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.
*
* OpenLogViewer software 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 any OpenLogViewer software. If not, see http://www.gnu.org/licenses/
*
* I ask that if you make any changes to this file you fork the code on github.com!
*
*/
package org.diyefi.openlogviewer.optionpanel;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ContainerEvent;
import java.awt.event.ContainerListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionAdapter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import javax.swing.*;
import org.diyefi.openlogviewer.OpenLogViewerApp;
import org.diyefi.openlogviewer.genericlog.GenericDataElement;
import org.diyefi.openlogviewer.genericlog.GenericLog;
import org.diyefi.openlogviewer.propertypanel.SingleProperty;
/**
*
* @author Bryan Harris
*/
public class OptionFrameV2 extends JFrame {
private JFrame thisRef;
private JPanel inactiveHeaders;
private ModifyGraphPane infoPanel;
private JButton addDivisionButton;
private JButton remDivisionButton;
private JLayeredPane layeredPane;
private ArrayList<JPanel> activePanelList;
private static final int COMP_HEIGHT = 20;// every thing except panels are 20 px high; default 20
private static final int COMP_WIDTH = 200; // used for buttons and such that are in; default 200
private static final int PANEL_WIDTH = 140;// panels are 120 px wide buttons and labels are also; default 120
private static final int PANEL_HEIGHT = 120;// panels are 120 px high;default 120
@SuppressWarnings("LeakingThisInConstructor")
public OptionFrameV2() {
super("Graphing Option Pane");
this.setSize(1280, 480);
this.setPreferredSize(this.getSize());
this.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
thisRef = this;
activePanelList = new ArrayList<JPanel>();
layeredPane = new JLayeredPane();
layeredPane.setPreferredSize(new Dimension(1280, 420));
JScrollPane scroll = new JScrollPane(layeredPane);
inactiveHeaders = initHeaderPanel();
layeredPane.add(inactiveHeaders);
infoPanel = new ModifyGraphPane();
this.add(infoPanel);
this.add(scroll);
addActiveHeaderPanel();
}
private JInternalFrame initInfoPanel() {
JInternalFrame ip = new JInternalFrame();
return ip;
}
private JPanel initHeaderPanel() {
JPanel ih = new JPanel();
ih.setLayout(null);
ih.setName("Drop InactiveHeaderPanel");
this.addDivisionButton = new JButton("Add Division");
addDivisionButton.setBounds(0, 0, PANEL_WIDTH, COMP_HEIGHT);
addDivisionButton.addActionListener(addDivisionListener);
ih.add(addDivisionButton);
ih.setBounds(0, 0, 1280, 180);
return ih;
}
private ActionListener addDivisionListener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
addActiveHeaderPanel();
}
};
private ActionListener remDivisionListener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
remActiveHeaderPanel(e);
}
};
private ContainerListener addRemoveListener = new ContainerListener() {
@Override
public void componentAdded(ContainerEvent e) {
if (e.getChild() != null) {
if (e.getChild() instanceof ActiveHeaderLabel) {
((ActiveHeaderLabel) e.getChild()).setEnabled(true);
((ActiveHeaderLabel) e.getChild()).setSelected(true);
((ActiveHeaderLabel) e.getChild()).getGDE().setSplitNumber(
activePanelList.indexOf(
e.getChild().getParent()) + 1);
}
}
}
@Override
public void componentRemoved(ContainerEvent e) {
if (e.getChild() != null) {
if (e.getChild() instanceof ActiveHeaderLabel) {
((ActiveHeaderLabel) e.getChild()).setEnabled(false);
((ActiveHeaderLabel) e.getChild()).setSelected(false);
}
for (int i = 0; i < e.getContainer().getComponentCount(); i++) {
if (e.getContainer().getComponent(i) instanceof ActiveHeaderLabel) {
e.getContainer().getComponent(i).setLocation(0, i * COMP_HEIGHT);
}
}
}
}
};
private void addActiveHeaderPanel() {
if (activePanelList.size() < 8) {
int row = activePanelList.size() / 4;
int col = activePanelList.size() % 4;
JPanel activePanel = new JPanel();
activePanelList.add(activePanel);
if (OpenLogViewerApp.getInstance() != null) {
OpenLogViewerApp.getInstance().getLayeredGraph().setTotalSplits(activePanelList.size());
}
activePanel.setLayout(null);
activePanel.setName("Drop ActivePanel " + (activePanelList.indexOf(activePanel) + 1));
activePanel.addContainerListener(addRemoveListener);
activePanel.setBounds((col * PANEL_WIDTH), inactiveHeaders.getHeight() + PANEL_HEIGHT * row, PANEL_WIDTH, PANEL_HEIGHT);
activePanel.setBackground(Color.DARK_GRAY);
JButton removeButton = new JButton("Remove");
removeButton.setToolTipText("Click Here to remove this division and associated Graphs");
removeButton.setBounds(0, 0, PANEL_WIDTH, COMP_HEIGHT);
removeButton.addActionListener(remDivisionListener);
activePanel.add(removeButton);
layeredPane.add(activePanel);
if (activePanelList.size() == 8) {
addDivisionButton.setEnabled(false);
}
}
}
private void remActiveHeaderPanel(ActionEvent e) {
JPanel panel = (JPanel) ((JButton) e.getSource()).getParent();
activePanelList.remove(panel);
OpenLogViewerApp.getInstance().getLayeredGraph().setTotalSplits(activePanelList.size());
for (int i = 0; i < panel.getComponentCount();) {
if (panel.getComponent(i) instanceof ActiveHeaderLabel) {
ActiveHeaderLabel GCB = (ActiveHeaderLabel) panel.getComponent(i);
GCB.getInactivePanel().add(GCB);
GCB.setLocation(GCB.getInactiveLocation());
GCB.setSelected(false);
} else if (panel.getComponent(i) instanceof JButton) {
panel.remove(panel.getComponent(i));//removes the button
} else {
i++;
}
}
panel.getParent().remove(panel);
for (int i = 0; i < activePanelList.size(); i++) {
int row = i / 4;
int col = i % 4;
activePanelList.get(i).setLocation((col * PANEL_HEIGHT), inactiveHeaders.getHeight() + PANEL_WIDTH * row);
}
if (!addDivisionButton.isEnabled()) {
addDivisionButton.setEnabled(true);
}
////////////////////////////////////////////////////////////////////Move this to events eventually,
if (activePanelList.size() > 1) {
for (int i = 0; i < activePanelList.size(); i++) {
JPanel active = activePanelList.get(i);
if (active.getComponentCount() > 1) {
for (int j = 0; j < active.getComponentCount(); j++) {
if (active.getComponent(j) instanceof ActiveHeaderLabel) {
((ActiveHeaderLabel) active.getComponent(j)).getGDE().setSplitNumber(i + 1);
}
}
}
}
}
this.repaint();
}
private MouseMotionAdapter labelAdapter = new MouseMotionAdapter() {
@Override
public void mouseDragged(MouseEvent e) {
Component c = e.getComponent();
ActiveHeaderLabel GCB = (ActiveHeaderLabel) c;
GCB.setDragging(true);
if (c.getParent() != null && layeredPane.getMousePosition() != null && (e.getModifiers() == 16)) {// 4 == right mouse button
if (!c.getParent().contains(layeredPane.getMousePosition().x - c.getParent().getX(), layeredPane.getMousePosition().y - c.getParent().getY())) {
Component cn = c.getParent().getParent().getComponentAt(layeredPane.getMousePosition());
if (cn instanceof JPanel) {
JPanel j = (JPanel) cn;
if (j.getName().contains("Drop")) { // implement a better way to do this later
j.add(c);// components cannot share parents so it is automatically removed
c.setLocation( // reset the location to where the mouse is, otherwise first pixel when moving to the new jpanel
// will cause a location issue reflecting where the panel was in the PREVIOUS panel
layeredPane.getMousePosition().x - c.getParent().getX() - (c.getWidth() / 2),
layeredPane.getMousePosition().y - c.getParent().getY() - (c.getHeight() / 2));
}
}
} else {
c.setLocation(c.getX() + e.getX() - (c.getWidth() / 2), c.getY() + e.getY() - (c.getHeight() / 2));
}
thisRef.repaint();
}
}
};
private boolean place(ActiveHeaderLabel GCB) {
int x = 0;
int y = COMP_HEIGHT;
while (y < GCB.getParent().getHeight()) {
if (GCB.getParent().getComponentAt(x, y) == GCB.getParent() || GCB.getParent().getComponentAt(x, y) == GCB) {
GCB.setLocation(x, y);
return true;
}
y = y + COMP_HEIGHT;
}
return false;
}
public void updateFromLog(GenericLog gl) {
while (activePanelList.size() > 0) {
activePanelList.get(0).removeAll();
layeredPane.remove(activePanelList.get(0));
activePanelList.remove(activePanelList.get(0)); // only did it this way incase things are out of order at any point
}
addDivisionButton.setEnabled(true);
if (inactiveHeaders.getComponentCount() > 1) {
inactiveHeaders.removeAll();
inactiveHeaders.add(this.addDivisionButton);
}
this.addActiveHeaderPanel(); // will be based on highest number of divisions found when properties are applied
ArrayList<ActiveHeaderLabel> tmpList = new ArrayList<ActiveHeaderLabel>();
Iterator i = gl.keySet().iterator();
String head = "";
ActiveHeaderLabel toBeAdded = null;
while (i.hasNext()) {
head = (String) i.next();
GenericDataElement GDE = gl.get(head);
toBeAdded = new ActiveHeaderLabel();
toBeAdded.setName(head);
toBeAdded.setText(head);
toBeAdded.setRef(GDE);
toBeAdded.setEnabled(false);//you are unable to activate a graph in the inacivelist
toBeAdded.addMouseMotionListener(labelAdapter);
if (checkForProperties(toBeAdded, GDE)) {
toBeAdded.setBackground(GDE.getColor());
}
tmpList.add(toBeAdded);
}
Collections.sort(tmpList);
int j = 0;
int leftSide = 0;
for (int it = 0; it < tmpList.size(); it++) {
if (COMP_HEIGHT + (COMP_HEIGHT * (j + 1)) > inactiveHeaders.getHeight()) {
j = 0;
leftSide += PANEL_WIDTH;
}
tmpList.get(it).setBounds(leftSide, (COMP_HEIGHT + (COMP_HEIGHT * j)),
PANEL_WIDTH//(((COMP_HEIGHT + (head.length() * 8)) < 120) ? (32 + (head.length() * 7)) : 120)// this keeps the select boxes at a max of 120
, COMP_HEIGHT);
inactiveHeaders.add(tmpList.get(it));
j++;
}
this.repaint();
this.setDefaultCloseOperation(JFrame.ICONIFIED);
this.setVisible(true);
}
private boolean checkForProperties(ActiveHeaderLabel GCB, GenericDataElement GDE) {
for (int i = 0; i < OpenLogViewerApp.getInstance().getProperties().size(); i++) {
if (OpenLogViewerApp.getInstance().getProperties().get(i).getHeader().equals(GDE.getName())) {
GDE.setColor(OpenLogViewerApp.getInstance().getProperties().get(i).getColor());
GDE.setMaxValue(OpenLogViewerApp.getInstance().getProperties().get(i).getMax());
GDE.setMinValue(OpenLogViewerApp.getInstance().getProperties().get(i).getMin());
GDE.setSplitNumber(OpenLogViewerApp.getInstance().getProperties().get(i).getSplit());
if (OpenLogViewerApp.getInstance().getProperties().get(i).isActive()) {
//GCB.setSelected(true);
return true;
}
}
}
return false;
}
private class ModifyGraphPane extends JInternalFrame {
GenericDataElement GDE;
ActiveHeaderLabel AHL;
private JLabel minLabel;
private JLabel maxLabel;
private JTextField minField;
private JTextField maxField;
private JButton resetButton;
private JButton applyButton;
private JButton saveButton;
private JButton colorButton;
private ActionListener resetButtonListener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (GDE != null) {
GDE.reset();
minField.setText(Double.toString(GDE.getMinValue()));
maxField.setText(Double.toString(GDE.getMaxValue()));
}
}
};
private ActionListener applyButtonListener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (GDE != null) {
changeGDEValues();
}
}
};
private ActionListener saveButtonListener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (GDE != null) {
changeGDEValues();
OpenLogViewerApp.getInstance().getPropertyPane().addPropertyAndSave(new SingleProperty(GDE));
}
}
};
private ActionListener colorButtonListener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Color c = JColorChooser.showDialog(
new JFrame(),
"Choose Background Color",
colorButton.getForeground());
if (c != null) {
colorButton.setForeground(c);
}
}
};
public ModifyGraphPane() {
this.setName("InfoPanel");
minLabel = new JLabel("Min:");
maxLabel = new JLabel("Max:");
minField = new JTextField(10);
maxField = new JTextField(10);
resetButton = new JButton("Reset Min/Max");
resetButton.addActionListener(resetButtonListener);
applyButton = new JButton("Apply");
applyButton.addActionListener(applyButtonListener);
saveButton = new JButton("Save");
saveButton.addActionListener(saveButtonListener);
colorButton = new JButton("Color");
colorButton.addActionListener(colorButtonListener);
//X Y width height
minLabel.setBounds(0, 0, COMP_WIDTH/2, COMP_HEIGHT);
minField.setBounds(100, 0, COMP_WIDTH/2, COMP_HEIGHT);
maxLabel.setBounds(0, 20, COMP_WIDTH/2, COMP_HEIGHT);
maxField.setBounds(100, 20, COMP_WIDTH/2, COMP_HEIGHT);
colorButton.setBounds(0, 40, COMP_WIDTH, COMP_HEIGHT);
applyButton.setBounds(0, 60, COMP_WIDTH/2, COMP_HEIGHT);
saveButton.setBounds(100, 60, COMP_WIDTH/2, COMP_HEIGHT);
resetButton.setBounds(0, 80, COMP_WIDTH, COMP_HEIGHT);
this.setLayout(null);
///ip.add(headerLabel);
this.add(minLabel);
this.add(minField);
this.add(maxLabel);
this.add(maxField);
this.add(colorButton);
this.add(applyButton);
this.add(saveButton);
this.add(resetButton);
this.setBounds(500, 180, 210, 133);
this.setMaximizable(false);
this.setDefaultCloseOperation(JInternalFrame.HIDE_ON_CLOSE);
this.setClosable(true);
}
public void setGDE(GenericDataElement gde, ActiveHeaderLabel ahl) {
this.GDE = gde;
this.AHL = ahl;
this.setTitle(GDE.getName());
minField.setText(GDE.getMinValue().toString());
maxField.setText(GDE.getMaxValue().toString());
colorButton.setForeground(GDE.getColor());
}
private void changeGDEValues() {
try {
GDE.setMaxValue(Double.parseDouble(maxField.getText()));
} catch (Exception ex) {
//TO-DO: do something with Auto field
}
try {
GDE.setMinValue(Double.parseDouble(minField.getText()));
} catch (Exception ex) {
//TO-DO: do something with Auto field
}
if (!GDE.getColor().equals(colorButton.getForeground())) {
GDE.setColor(colorButton.getForeground());
AHL.setForeground(colorButton.getForeground());
}
}
}
private class ActiveHeaderLabel extends JLabel implements Comparable {
private GenericDataElement GDE;
private Point previousLocation;
private Point inactiveLocation;
private JPanel previousPanel;
private JPanel inactivePanel;
private boolean dragging;
private boolean selected;
private MouseListener selectedListener = new MouseListener() {
@Override
public void mouseClicked(MouseEvent e) {
if (e.getModifiers() == 16) {
setSelected(!selected);
} else if (e.getModifiers() == 18) {
infoPanel.setGDE(GDE,(ActiveHeaderLabel)e.getSource());
if (!infoPanel.isVisible()) {
infoPanel.setVisible(true);
}
}
// System.out.println(e.getModifiers());
}
@Override
public void mouseEntered(MouseEvent e) {
}
@Override
public void mouseExited(MouseEvent e) {
}
@Override
public void mousePressed(MouseEvent e) {
ActiveHeaderLabel GCB = (ActiveHeaderLabel) e.getSource();
GCB.setPreviousLocation(GCB.getLocation());
GCB.setPreviousPanel((JPanel) GCB.getParent());
}
@Override
public void mouseReleased(MouseEvent e) {
ActiveHeaderLabel GCB = (ActiveHeaderLabel) e.getSource();
if (GCB.isDragging()) {
if (GCB.getParent() == inactiveHeaders) { // moving back to inactive
GCB.setLocation(GCB.getInactiveLocation());
GCB.setSelected(false);
GCB.setEnabled(false);
} else { // moving to
if (!place(GCB)) {
if (GCB.getPreviousPanel() != GCB.getParent()) { // if it moved
GCB.getPreviousPanel().add(GCB);
place(GCB);
}
if (GCB.getPreviousPanel() == GCB.getInactivePanel()) {
GCB.setLocation(GCB.getInactiveLocation());
GCB.setEnabled(false);
GCB.setSelected(false);
} else {
place(GCB);
}
thisRef.repaint();
}
}
GCB.setDragging(false);
}
}
};
private ItemListener enabledListener = new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
throw new UnsupportedOperationException("Not supported yet.");
}
};
public ActiveHeaderLabel() {
super();
addMouseListener(selectedListener);
super.setOpaque(false);
inactivePanel = inactiveHeaders;
dragging = false;
selected = false;
super.setBorder(BorderFactory.createEtchedBorder(Color.lightGray, Color.white));
}
@Override
public void setBounds(int x, int y, int widht, int height) {
super.setBounds(x, y, widht, height);
if (inactiveLocation == null) {
inactiveLocation = new Point(x, y);
}
}
public void setRef(GenericDataElement GDE) {
this.GDE = GDE;
// this line is here because if the tool tip is never set no mouse events
// will ever be created for tool tips
this.setToolTipText();
}
@Override
public String getToolTipText(MouseEvent e) {
this.setToolTipText();
return getToolTipText();
}
public void setToolTipText() {
this.setToolTipText("<HTML>Min Value: <b>" + GDE.getMinValue()
+ "</b><br>Max Value: <b>" + GDE.getMaxValue()
+ "</b><br>Total Length: <b>" + GDE.size() + "</b> data points"
+ "<br>To modify Min and Max values for scaling purposes Ctrl+LeftClick</HTML>");
}
public GenericDataElement getGDE() {
return GDE;
}
public Point getPreviousLocation() {
return previousLocation;
}
public void setPreviousLocation(Point previousLocation) {
this.previousLocation = previousLocation;
}
public JPanel getPreviousPanel() {
return previousPanel;
}
public void setPreviousPanel(JPanel previousPanel) {
this.previousPanel = previousPanel;
}
public Point getInactiveLocation() {
return inactiveLocation;
}
public JPanel getInactivePanel() {
return inactivePanel;
}
public boolean isDragging() {
return dragging;
}
public void setDragging(boolean dragging) {
this.dragging = dragging;
}
public boolean isSelected() {
return selected;
}
public void setSelected(boolean selected) {
if (this.isEnabled()) {
this.selected = selected;
} else {
this.selected = false;
}
addRemGraph();
}
private void addRemGraph() {
if (selected) {
this.setForeground(GDE.getColor());
this.repaint();
OpenLogViewerApp.getInstance().getLayeredGraph().addGraph(this.getName());
} else {
this.setForeground(GDE.getColor().darker().darker());
if (OpenLogViewerApp.getInstance().getLayeredGraph().removeGraph(this.getName())) {
OpenLogViewerApp.getInstance().getLayeredGraph().repaint();
}
}
}
@Override
public int compareTo(Object o) {
if (o instanceof ActiveHeaderLabel) {
ActiveHeaderLabel GCB = (ActiveHeaderLabel) o;
return this.GDE.compareTo(GCB.getGDE());
} else {
return -1;
}
}
}
}
| [
"[email protected]"
] | |
9ac11fef1620ced044058e61cc5ece0764608236 | 8fe809808931203aa6913d130afb2f41ac58ef2c | /src/com/ai/aris/server/webservice/service/impl/AisServiceSVImpl.java | 00f271df13c5482f7fc627e95c40a42aba5610c9 | [] | no_license | yangsense/bpris | 08332632f39fa33584bdcb95f07e5d61b635a347 | 77bed9caebc4fd1a4b5a90e5de884ffc414fc5cc | refs/heads/master | 2020-06-05T16:54:31.536441 | 2019-06-18T09:49:47 | 2019-06-18T09:49:47 | 192,486,051 | 0 | 0 | null | 2019-06-18T07:46:34 | 2019-06-18T07:12:00 | null | UTF-8 | Java | false | false | 112,089 | java | package com.ai.aris.server.webservice.service.impl;
import static org.apache.commons.lang.StringUtils.isNotBlank;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URLDecoder;
import java.sql.Clob;
import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.Timestamp;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import net.sf.json.util.JSONUtils;
import com.ai.appframe2.bo.DataContainerFactory;
import com.ai.appframe2.bo.SysdateManager;
import com.ai.appframe2.common.AIConfigManager;
import com.ai.appframe2.common.DataContainerInterface;
import com.ai.appframe2.common.ServiceManager;
import com.ai.appframe2.service.ServiceFactory;
import com.ai.aris.server.basecode.bean.AisPatientInfoHisBean;
import com.ai.aris.server.basecode.bean.AisPatientInfoHisEngine;
import com.ai.aris.server.basecode.bean.AisPixInfoBean;
import com.ai.aris.server.basecode.bean.AisPixInfoEngine;
import com.ai.aris.server.basecode.bean.AisServiceLogBean;
import com.ai.aris.server.basecode.bean.AisServiceLogEngine;
import com.ai.aris.server.basecode.bean.AiscBodyPart2ItemBean;
import com.ai.aris.server.basecode.bean.AiscBodyPart2ItemEngine;
import com.ai.aris.server.basecode.bean.AiscBodyPartBean;
import com.ai.aris.server.basecode.bean.AiscBodyPartEngine;
import com.ai.aris.server.basecode.bean.AiscCareProvBean;
import com.ai.aris.server.basecode.bean.AiscCareProvEngine;
import com.ai.aris.server.basecode.bean.AiscConorganizationBean;
import com.ai.aris.server.basecode.bean.AiscEquipmentBean;
import com.ai.aris.server.basecode.bean.AiscEquipmentEngine;
import com.ai.aris.server.basecode.bean.AiscItemMastBean;
import com.ai.aris.server.basecode.bean.AiscItemMastEngine;
import com.ai.aris.server.basecode.bean.AiscLocBean;
import com.ai.aris.server.basecode.bean.AiscLocEngine;
import com.ai.aris.server.basecode.bean.AiscLoginLocBean;
import com.ai.aris.server.basecode.bean.AiscOrdCat2LocBean;
import com.ai.aris.server.basecode.bean.AiscOrdCat2LocEngine;
import com.ai.aris.server.basecode.bean.AiscOrdCategoryBean;
import com.ai.aris.server.basecode.bean.AiscOrdCategoryEngine;
import com.ai.aris.server.basecode.bean.AiscOrdSubCategoryBean;
import com.ai.aris.server.basecode.bean.AiscRoomBean;
import com.ai.aris.server.basecode.bean.AiscRoomEngine;
import com.ai.aris.server.basecode.bean.AiscServerInfoBean;
import com.ai.aris.server.basecode.bean.AiscServerInfoEngine;
import com.ai.aris.server.basecode.bean.AiscUser2CareProvBean;
import com.ai.aris.server.common.bean.CommonEngine;
import com.ai.aris.server.common.service.interfaces.ICommonSV;
import com.ai.aris.server.common.util.DBUtil;
import com.ai.aris.server.interfacereal.bean.AisPatientRealBean;
import com.ai.aris.server.interfacereal.bean.AisPatientRealEngine;
import com.ai.aris.server.interfacereal.bean.AisStudyinfoRealBean;
import com.ai.aris.server.interfacereal.bean.AisStudyinfoRealEngine;
import com.ai.aris.server.interfacereal.bean.AiscBodyPart2ItemRealBean;
import com.ai.aris.server.interfacereal.bean.AiscBodypartRealBean;
import com.ai.aris.server.interfacereal.bean.AiscBodypartRealEngine;
import com.ai.aris.server.interfacereal.bean.AiscCareprovRealBean;
import com.ai.aris.server.interfacereal.bean.AiscCareprovRealEngine;
import com.ai.aris.server.interfacereal.bean.AiscEquipmentRealBean;
import com.ai.aris.server.interfacereal.bean.AiscEquipmentRealEngine;
import com.ai.aris.server.interfacereal.bean.AiscItemmastRealBean;
import com.ai.aris.server.interfacereal.bean.AiscItemmastRealEngine;
import com.ai.aris.server.interfacereal.bean.AiscLocRealBean;
import com.ai.aris.server.interfacereal.bean.AiscLocRealEngine;
import com.ai.aris.server.interfacereal.bean.AiscOrdCat2LocRealBean;
import com.ai.aris.server.interfacereal.bean.AiscOrdcategoryRealBean;
import com.ai.aris.server.interfacereal.bean.AiscOrdcategoryRealEngine;
import com.ai.aris.server.interfacereal.bean.AiscOrdsubcategoryRealBean;
import com.ai.aris.server.interfacereal.bean.AiscOrdsubcategoryRealEngine;
import com.ai.aris.server.interfacereal.bean.AiscRoomRealBean;
import com.ai.aris.server.interfacereal.bean.AiscRoomRealEngine;
import com.ai.aris.server.interfacereal.bean.AiscSeverinfoRealBean;
import com.ai.aris.server.interfacereal.bean.AiscSeverinfoRealEngine;
import com.ai.aris.server.interfacereal.bean.QryStudyItemInterfaceBean;
import com.ai.aris.server.interfacereal.bean.QryordsubcateINFBean;
import com.ai.aris.server.interfacereal.bean.QryordsubcateINFEngine;
import com.ai.aris.server.webservice.BusiDataEnum;
import com.ai.aris.server.webservice.DataEnum;
import com.ai.aris.server.webservice.bean.AisPatientInfoData;
import com.ai.aris.server.webservice.bean.AisStudyReportData;
import com.ai.aris.server.webservice.service.interfaces.IAisServiceSV;
import com.ai.aris.server.workstation.bean.AisFilesInfoBean;
import com.ai.aris.server.workstation.bean.AisFilesInfoEngine;
import com.ai.aris.server.workstation.bean.AisPatientInfoBean;
import com.ai.aris.server.workstation.bean.AisPatientInfoEngine;
import com.ai.aris.server.workstation.bean.AisReportFilesBean;
import com.ai.aris.server.workstation.bean.AisReportFilesEngine;
import com.ai.aris.server.workstation.bean.AisStudyInfoBean;
import com.ai.aris.server.workstation.bean.AisStudyInfoEngine;
import com.ai.aris.server.workstation.bean.AisStudyItemInfoBean;
import com.ai.aris.server.workstation.bean.AisStudyItemInfoEngine;
import com.ai.aris.server.workstation.bean.AisStudyReportBean;
import com.ai.aris.server.workstation.bean.AisStudyReportEngine;
import com.ai.aris.server.workstation.bean.QryReportHBean;
import com.ai.aris.server.workstation.bean.QryReportHEngine;
import com.ai.aris.server.workstation.bean.QryServerMediumBean;
import com.ai.aris.server.workstation.bean.QryServerMediumEngine;
import com.ai.aris.server.workstation.model.AisFilesInfoModel;
import com.ai.aris.server.workstation.service.interfaces.IPatientRegSV;
import com.ai.common.json.TimestampMorpher;
import com.ai.common.util.DateUtils;
import com.ai.common.util.ServiceUtil;
public class AisServiceSVImpl implements IAisServiceSV {
IPatientRegSV patientSv = (IPatientRegSV) ServiceFactory.getService(IPatientRegSV.class);
ICommonSV commonSV = (ICommonSV) ServiceFactory.getService(ICommonSV.class);
public <T extends DataContainerInterface> void save(T aBean) throws Exception{
CommonEngine.save(aBean);
}
public void updateSynMark(List<AisStudyReportData> list)throws Exception{
if(list!=null&&list.size()>0){
for(AisStudyReportData bean :list){
try {
String delSql2 = "update ais_studyreport set REPORT_TOARCHIVE=1 where report_id="+bean.getReportId()+" and studyinfo_id="+bean.getStudyinfoId()+"";
commonSV.execute(delSql2,null);
}catch (Exception e){
e.printStackTrace();
}
}
}
}
@Override
public AisPixInfoBean[] getAisPixInfoBean(String patientId,String orgId) throws Exception{
StringBuffer condition = new StringBuffer();
condition.append(" 1=1");
if (isNotBlank(patientId)) {
condition.append(" AND PATIENT_ID = '" + patientId+"'" );
}
if (isNotBlank(orgId)) {
condition.append(" AND ORG_ID = '" + orgId+"'" );
}
AisPixInfoBean[] pixBean = AisPixInfoEngine.getBeans(condition.toString(), null);
if(pixBean.length > 0){
return pixBean;
}else{
return null;
}
}
@Override
public AisPatientInfoBean[] getAisPatientBean(String idNumber) throws Exception{
StringBuffer condition = new StringBuffer();
condition.append(" 1=1");
if (isNotBlank(idNumber)) {
condition.append(" AND PATIENT_IDNUMBER = '" + idNumber+"'" );
}
AisPatientInfoBean[] patientBean = AisPatientInfoEngine.getBeans(condition.toString(), null);
if(patientBean.length > 0){
return patientBean;
}else{
return null;
}
}
@Override
public boolean insertPatientBean(long id,String patientId,Map map) throws Exception{
try {
String patientDob = map.get("Patient_DOB").toString().equals("")?"":map.get("Patient_DOB").toString();
AisPatientInfoBean bean = new AisPatientInfoBean();
bean.setPatientGlobalid(id);
bean.setPatientId(patientId);
bean.setPatientName(map.get("Patient_Name").toString());
bean.setPatientNamepy(map.get("Patient_NamePy").toString());
bean.setPatientDob(Timestamp.valueOf(patientDob));
bean.setPatientAge(map.get("Patient_Age").toString());
bean.setPatientSex(map.get("Patient_Sex").toString());
bean.setPatientIdnumber(map.get("Patient_IDNumber").toString());
bean.setPatientCardid(map.get("Patient_CardID").toString());
bean.setPatientMedicareid(map.get("Patient_MedicareID").toString());
bean.setPatientMobile(map.get("Patient_Mobile").toString());
bean.setPatientPhone(map.get("Patient_Phone").toString());
bean.setPatientVocation(map.get("Patient_Vocation").toString());
bean.setPatientNation(map.get("Patient_Nation").toString());
bean.setPatientStation(map.get("Patient_Station").toString());
bean.setPatientRemark(map.get("Patient _Remark").toString());
bean.setPatientStatus(map.get("Patient_Status").toString());
bean.setPatientAddress(map.get("Patient_Address").toString());
AisPatientInfoEngine.save(bean);
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
@Override
public boolean insertPixBean(long id,Map map) throws Exception{
try {
AisPixInfoBean zbean = new AisPixInfoBean();
zbean.setPatientGlobalid(id);
zbean.setOrgId(map.get("Org_Id").toString());
zbean.setPatientId(map.get("Patient_HID").toString());
AisPixInfoEngine.save(zbean);
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
@Override
public boolean updatePatient(long id,Map map) throws Exception{
try {
String patientDob = map.get("Patient_DOB").toString().equals("")?"":map.get("Patient_DOB").toString();
//修改前保存原始记录
AisPatientInfoBean oldBean = AisPatientInfoEngine.getBean(id);
AisPatientInfoHisBean hisBean = new AisPatientInfoHisBean();
DataContainerFactory.copyNoClearData(oldBean, hisBean);
AisPatientInfoHisEngine.save(hisBean);
AisPatientInfoBean bean = new AisPatientInfoBean();
bean.setPatientGlobalid(id);
bean.setStsToOld();
bean.setPatientName(map.get("Patient_Name").toString());
bean.setPatientNamepy(map.get("Patient_NamePy").toString());
bean.setPatientDob(Timestamp.valueOf(patientDob));
bean.setPatientAge(map.get("Patient_Age").toString());
bean.setPatientSex(map.get("Patient_Sex").toString());
bean.setPatientIdnumber(map.get("Patient_IDNumber").toString());
bean.setPatientCardid(map.get("Patient_CardID").toString());
bean.setPatientMedicareid(map.get("Patient_MedicareID").toString());
bean.setPatientMobile(map.get("Patient_Mobile").toString());
bean.setPatientPhone(map.get("Patient_Phone").toString());
bean.setPatientVocation(map.get("Patient_Vocation").toString());
bean.setPatientNation(map.get("Patient_Nation").toString());
bean.setPatientStation(map.get("Patient_Station").toString());
bean.setPatientRemark(map.get("Patient _Remark").toString());
bean.setPatientStatus(map.get("Patient_Status").toString());
bean.setPatientAddress(map.get("Patient_Address").toString());
AisPatientInfoEngine.save(bean);
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
@Override
public boolean deleteBusiData(String orgId) throws Exception{
Statement stmt = null;
try {
stmt = ServiceManager.getSession().getConnection().createStatement();
String sql = "delete from ais_studyreport where studyinfo_id in (select studyinfo_id from ais_studyinfo where org_id='"+orgId+"' and studystatus_code='VERIFY')";
String sql1 = "delete from ais_studyiteminfo where studyinfo_id in (select studyinfo_id from ais_studyinfo where org_id='"+orgId+"' and studystatus_code='VERIFY')";
stmt.executeUpdate(sql);
stmt.executeUpdate(sql1);
return true;
}catch (Exception e){
e.printStackTrace();
return false;
}finally{
com.ai.aris.server.common.util.DBUtil.release(null, stmt, null);
}
}
@Override
public void deleteStudyinfoReal(String orgId) throws Exception{
StringBuffer condition = new StringBuffer();
condition.append(" 1=1");
if (isNotBlank(orgId)) {
condition.append(" AND org_id = '" + orgId+"'" );
}
AisStudyinfoRealBean[] realBeans = AisStudyinfoRealEngine.getBeans(condition.toString(), null);
if(realBeans.length > 0){
for(AisStudyinfoRealBean bean :realBeans){
bean.delete();
AisStudyinfoRealEngine.save(bean);
}
}
}
@Override
public boolean insertStudyInfo(Map map) throws Exception{
Statement stmt = null;
try {
stmt = ServiceManager.getSession().getConnection().createStatement();
long studyId = ServiceUtil.getSequence("SEQSTUDYINFOID");
String cloumn = "STUDYINFO_ID,ORG_ID,LOC_ID,PATIENT_OUTPATIENTID,PATIENT_INPATIENTID,STUDY_EPSODEID,PATIENTTYPE_CODE,"
+ "STUDY_APPLOCID,STUDY_APPDOC,STUDY_WARD,STUDY_BEDNO,STUDY_AIM,STUDY_CLINIC,STUDY_ITEMDESC,STUDY_APPDATE,STUDY_ACCNUMBER,STUDYSTATUS_CODE,PATIENT_GLOBALID";
String studyapptime = map.get("Study_AppDateTime").toString().equals("")?"":map.get("Study_AppDateTime").toString();
String cloumnValue = ""+studyId+",'"+map.get("ORG_ID")+"','"+map.get("Loc_code")+"','"+map.get("Patient_OutpatientID")+"'," +
"'"+map.get("Patient_InpatientID")+"','"+map.get("Study_EpsodeID")+"','"+map.get("PatientType_Code")+"','"+map.get("Study_AppLoc")+"','"+map.get("Study_AppDoc")+"'," +
"'"+map.get("Study_Ward")+"','"+map.get("Study_bedNo")+"','"+map.get("Study_Aim")+"','"+map.get("Study_Clinic")+"','"+map.get("Study_ItemDesc")+"' "
+ "to_date('"+studyapptime+"','yyyy-MM-dd hh24:mi:ss'),'"+map.get("Study_Accnumber")+"','"+map.get("StudyStatus_Code")+"',"+map.get("PATIENT_GLOBALID")+" ";
//
String sql = "insert into ais_studyinfo ("+cloumn+") values ("+cloumnValue+")";
stmt.executeUpdate(sql);
// Timestamp dateTime=new Timestamp(new Date().getTime());
String reportTime = map.get("Report_ReportDateTime").toString().equals("")?"":map.get("Report_ReportDateTime").toString();
long newReportId = ServiceUtil.getSequence("SEQREPORTID");
AisStudyReportBean reportBean = new AisStudyReportBean();
reportBean.setReportId(newReportId);
reportBean.setStudyinfoId(studyId);
reportBean.setReportDatetime(Timestamp.valueOf(reportTime));
reportBean.setReportDoctorid(map.get("Study_ReportDoctorCode").toString());
reportBean.setReportVerifydoctorid(map.get("Report_ReportDoctor").toString());
reportBean.setReportExammethod(map.get("Report_ExamMethod").toString());
reportBean.setReportIspositive(Integer.parseInt(map.get("Report_IsPositive").toString()));
reportBean.setReportRemark(map.get("Study_Remark").toString());
reportBean.setReportExam(map.get("Report_Exam").toString());
reportBean.setReportResult(map.get("Report_Result").toString());
AisStudyReportEngine.save(reportBean);
return true;
}catch (Exception e){
e.printStackTrace();
return false;
}finally{
com.ai.aris.server.common.util.DBUtil.release(null, stmt, null);
}
}
@Override
public String insertPatientBean(String orgId,AisPatientInfoData model) throws Exception{
Map seqs = patientSv.getSeq(orgId,"-999");
long id = Long.parseLong(seqs.get("patientGlobalid").toString());
String pacsPatientId = seqs.get("patientId").toString();
//pix保存医院的病人ID
AisPixInfoBean zbean = new AisPixInfoBean();
zbean.setPatientGlobalid(id);
zbean.setOrgId(orgId);
zbean.setPatientId(model.getPatientId());
AisPixInfoEngine.save(zbean);
//
AisPatientRealBean real = new AisPatientRealBean();
real.setPatientRealId(ServiceUtil.getSequence("SEQPATIENT_REAL"));
real.setGlobalId(id);
real.setOldGlobalId(model.getPatientGlobalid());
real.setOrgId(orgId);
AisPatientRealEngine.save(real);
//中心病人ID保存为中心规则病人ID
AisPatientInfoBean bean = new AisPatientInfoBean();
bean.setPatientId(pacsPatientId);
bean.setPatientGlobalid(id);
bean.setPatientName(model.getPatientName());
bean.setPatientNamepy(model.getPatientNamepy());
bean.setPatientDob(model.getPatientDob());
bean.setPatientAge(model.getPatientAge());
bean.setPatientSex(model.getPatientSex());
bean.setPatientIdnumber(model.getPatientIdnumber());
bean.setPatientCardid(model.getPatientCardid());
bean.setPatientMedicareid(model.getPatientMedicareid());
bean.setPatientMobile(model.getPatientMobile());
bean.setPatientPhone(model.getPatientPhone());
bean.setPatientVocation(model.getPatientVocation());
bean.setPatientNation(model.getPatientNation());
bean.setPatientStation(model.getPatientStation());
bean.setPatientStatus(model.getPatientStatus());
bean.setPatientRemark(model.getPatientRemark());
bean.setPatientAddress(model.getPatientAddress());
bean.setOrgId(orgId);
AisPatientInfoEngine.save(bean);
return String.valueOf(id);
}
@Override
public void insertPixBean(long id,String orgId,AisPatientInfoData model) throws Exception{
try {
//pix保存医院的病人ID
AisPixInfoBean zbean = new AisPixInfoBean();
zbean.setPatientGlobalid(id);
zbean.setOrgId(orgId);
zbean.setPatientId(model.getPatientId());
AisPixInfoEngine.save(zbean);
//
AisPatientRealBean real = new AisPatientRealBean();
real.setPatientRealId(ServiceUtil.getSequence("SEQPATIENT_REAL"));
real.setGlobalId(id);
real.setOldGlobalId(model.getPatientGlobalid());
real.setOrgId(orgId);
AisPatientRealEngine.save(real);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void updatePatient(long id,AisPatientInfoData model) throws Exception{
AisPatientInfoBean oldBean = AisPatientInfoEngine.getBean(id);
oldBean.setStsToOld();
oldBean.setPatientName(model.getPatientName());
oldBean.setPatientNamepy(model.getPatientNamepy());
oldBean.setPatientDob(model.getPatientDob());
oldBean.setPatientAge(model.getPatientAge());
oldBean.setPatientSex(model.getPatientSex());
oldBean.setPatientIdnumber(model.getPatientIdnumber());
oldBean.setPatientCardid(model.getPatientCardid());
oldBean.setPatientMedicareid(model.getPatientMedicareid());
oldBean.setPatientMobile(model.getPatientMobile());
oldBean.setPatientPhone(model.getPatientPhone());
oldBean.setPatientAddress(model.getPatientAddress());
AisPatientInfoEngine.save(oldBean);
}
@Override
public AiscLocRealBean getLocRealBean(long locId,String orgId) throws Exception{
StringBuffer condition = new StringBuffer();
condition.append(" ORG_ID = '" + orgId+"' and old_loc_id="+locId );
AiscLocRealBean[] realBean = AiscLocRealEngine.getBeans(condition.toString(), null);
if(realBean.length > 0){
return realBean[0];
}else{
return null;
}
}
@Override
public AisStudyItemInfoBean[] getStudyItem(long studyinfoId) throws Exception{
String sql = "SELECT * FROM AIS_STUDYITEMINFO WHERE STUDYINFO_ID = " + studyinfoId;
AisStudyItemInfoBean[] studyItemInfoBeans = AisStudyItemInfoEngine.getBeansFromSql(sql, null);
if(studyItemInfoBeans.length > 0){
return studyItemInfoBeans;
}else{
return null;
}
}
@Override
public AisPatientRealBean getRealGlobalId(long globalId,String orgId) throws Exception{
StringBuffer condition = new StringBuffer();
condition.append(" ORG_ID = '" + orgId+"' and OLD_GLOBAL_ID ="+globalId );
AisPatientRealBean[] realBean = AisPatientRealEngine.getBeans(condition.toString(), null);
if(realBean.length > 0){
return realBean[0];
}else{
return null;
}
}
@Override
public AiscItemmastRealBean getStudyItemRealBean(long oldmastId,String orgId) throws Exception{
StringBuffer condition = new StringBuffer();
condition.append(" ORG_ID = '" + orgId+"' and OLD_ITEMMAST_ID ="+oldmastId );
AiscItemmastRealBean[] realBean = AiscItemmastRealEngine.getBeans(condition.toString(), null);
if(realBean.length > 0){
return realBean[0];
}else{
return null;
}
}
@Override
public AiscBodypartRealBean getBodypartRealBean(long oldmastId,String orgId) throws Exception{
StringBuffer condition = new StringBuffer();
condition.append(" ORG_ID = '" + orgId+"' and OLD_BODYPART_CODE ="+oldmastId );
AiscBodypartRealBean[] realBean = AiscBodypartRealEngine.getBeans(condition.toString(), null);
if(realBean.length > 0){
return realBean[0];
}else{
return null;
}
}
@Override
public AisStudyinfoRealBean getStudyinfoRealBean(long studyinfoId,String orgId) throws Exception{
StringBuffer condition = new StringBuffer();
condition.append(" ORG_ID = '" + orgId+"' and OLD_STUDYINFO_ID ="+studyinfoId );
AisStudyinfoRealBean[] realBean = AisStudyinfoRealEngine.getBeans(condition.toString(), null);
if(realBean.length > 0){
return realBean[0];
}else{
return null;
}
}
@Override
public AiscCareprovRealBean getCareBean(long careId,String orgId) throws Exception{
StringBuffer condition = new StringBuffer();
condition.append(" ORG_ID = '" + orgId+"' and OLD_CAREPROV_ID ="+careId );
AiscCareprovRealBean[] realBean = AiscCareprovRealEngine.getBeans(condition.toString(), null);
if(realBean.length > 0){
return realBean[0];
}else{
return null;
}
}
@Override
public AiscEquipmentRealBean getEquipmentBean(long equipId,String orgId) throws Exception{
StringBuffer condition = new StringBuffer();
condition.append(" ORG_ID = '" + orgId+"' and OLD_EQUIPMENT_ID ="+equipId );
AiscEquipmentRealBean[] realBean = AiscEquipmentRealEngine.getBeans(condition.toString(), null);
if(realBean.length > 0){
return realBean[0];
}else{
return null;
}
}
@Override
public AiscRoomRealBean getRoomReal(long roomId,String orgId) throws Exception{
StringBuffer condition = new StringBuffer();
condition.append(" ORG_ID = '" + orgId+"' and OLD_ROOM_ID ="+roomId );
AiscRoomRealBean[] realBean = AiscRoomRealEngine.getBeans(condition.toString(), null);
if(realBean.length > 0){
return realBean[0];
}else{
return null;
}
}
@Override
public void insertStudyItem(QryStudyItemInterfaceBean bean)throws Exception{
AisStudyItemInfoBean sbean = new AisStudyItemInfoBean();
sbean.setStudyinfoId(bean.getStudyinfoId());
sbean.setStudyitemId(ServiceUtil.getSequence("SEQSTUDYITEMID"));
sbean.setStudyitemHisid(bean.getStudyitemHisid());
sbean.setStudyitemCode(bean.getStudyitemCode());
sbean.setStudyitemDesc(bean.getStudyitemDesc());
sbean.setStudyitemEndesc(bean.getStudyitemEndesc());
sbean.setStudyitemBodyinfo(bean.getStudyitemBodyinfo());
sbean.setStudyitemPrice(bean.getStudyitemPrice());
sbean.setStudyitemNumber(Integer.parseInt(String.valueOf(bean.getStudyitemNumber())));
sbean.setStudyitemStatus(bean.getStudyitemStatus());
sbean.setStudyitemItemno(bean.getStudyitemItemno());
sbean.setStudyitemBodypart(bean.getStudyitemBodypart());
AisStudyItemInfoEngine.save(sbean);
}
@Override
public void insertStudyinfoReal(long newStudyInfoId,AisStudyInfoBean bean)throws Exception{
AisStudyinfoRealBean realbean = new AisStudyinfoRealBean();
realbean.setStudyinfoRealId(ServiceUtil.getSequence("SEQSTUDYTEMPID"));
realbean.setStudyinfoId(newStudyInfoId);
realbean.setOldStudyinfoId(bean.getStudyinfoId());
realbean.setOrgId(bean.getOrgId());
AisStudyinfoRealEngine.save(realbean);
}
@Override
public AiscServerInfoBean getServerInfo(AiscServerInfoBean bean) throws Exception{
StringBuffer condition = new StringBuffer();
condition.append(" 1=1");
condition.append(" and server_ip='"+bean.getServerIp()+"'");
condition.append(" and server_type = '"+bean.getServerType()+"' ");
AiscServerInfoBean[] oldBean = AiscServerInfoEngine.getBeans(condition.toString(), null);
if(oldBean!=null&&oldBean.length>0){
return oldBean[0];
}else{
return null;
}
}
@Override
public AiscLocBean getLocInfo(AiscLocBean bean) throws Exception{
StringBuffer condition = new StringBuffer();
condition.append(" 1=1");
condition.append(" and loc_code='"+bean.getLocCode()+"'");
condition.append(" and org_id = '"+bean.getOrgId()+"' ");
AiscLocBean[] oldBean = AiscLocEngine.getBeans(condition.toString(), null);
if(oldBean!=null&&oldBean.length>0){
return oldBean[0];
}else{
return null;
}
}
public AiscRoomBean getRoomInfo(AiscRoomBean bean) throws Exception{
StringBuffer condition = new StringBuffer();
condition.append(" 1=1");
AiscLocRealBean[] realBeen = commonSV.getBeans(" ORG_ID = "+bean.getOrgId()+" and old_loc_id="+bean.getLocId(),null,AiscLocRealBean.class);
if(realBeen!=null&&realBeen.length>0){
condition.append(" and loc_id="+realBeen[0].getLocId()+"");
}else{
condition.append(" and loc_id="+bean.getLocId()+"");
}
condition.append(" and room_desc='"+bean.getRoomDesc()+"'");
condition.append(" and org_id = '"+bean.getOrgId()+"' ");
AiscRoomBean[] oldBean = AiscRoomEngine.getBeans(condition.toString(), null);
if(oldBean!=null&&oldBean.length>0){
return oldBean[0];
}else{
return null;
}
}
public AiscEquipmentBean getEquipment(AiscEquipmentBean bean) throws Exception{
StringBuffer condition = new StringBuffer();
condition.append(" 1=1");
condition.append(" and equipment_code='"+bean.getEquipmentCode()+"'");
condition.append(" and org_id = '"+bean.getOrgId()+"' ");
AiscEquipmentBean[] oldBean = AiscEquipmentEngine.getBeans(condition.toString(), null);
if(oldBean!=null&&oldBean.length>0){
return oldBean[0];
}else{
return null;
}
}
public AiscOrdCategoryBean getCategory(AiscOrdCategoryBean bean) throws Exception{
StringBuffer condition = new StringBuffer();
condition.append(" 1=1");
condition.append(" and ordcategory_code='"+bean.getOrdcategoryCode()+"'");
condition.append(" and org_id='"+bean.getOrgId()+"'");
AiscOrdCategoryBean[] oldBean = AiscOrdCategoryEngine.getBeans(condition.toString(), null);
if(oldBean!=null&&oldBean.length>0){
return oldBean[0];
}else{
return null;
}
}
public QryordsubcateINFBean getAiscOrdSubCategory(AiscOrdSubCategoryBean bean,String orgId) throws Exception{
StringBuffer condition = new StringBuffer();
condition.append(" 1=1");
condition.append(" and ordsubcategory_code='"+bean.getOrdsubcategoryCode()+"'");
condition.append(" and org_id='"+orgId+"'");
QryordsubcateINFBean[] oldBean = QryordsubcateINFEngine.getBeans(condition.toString(), null);
if(oldBean!=null&&oldBean.length>0){
return oldBean[0];
}else{
return null;
}
}
public long getRealOrdcategoryId(long id,String orgId) throws Exception{
StringBuffer condition = new StringBuffer();
condition.append(" 1=1");
condition.append(" and old_ordcategory_id="+id);
condition.append(" and org_id='"+orgId+"'");
AiscOrdcategoryRealBean[] oldBean = AiscOrdcategoryRealEngine.getBeans(condition.toString(), null);
if(oldBean!=null&&oldBean.length>0){
return oldBean[0].getOrdcategoryId();
}else{
return id;
}
}
public long getItemmastId(long id,String orgId) throws Exception{
StringBuffer condition = new StringBuffer();
condition.append(" 1=1");
condition.append(" and old_itemmast_id="+id);
condition.append(" and org_id='"+orgId+"'");
AiscItemmastRealBean[] oldBean = AiscItemmastRealEngine.getBeans(condition.toString(), null);
if(oldBean!=null&&oldBean.length>0){
return oldBean[0].getItemmastId();
}else{
return id;
}
}
public long getLocId(long id,String orgId) throws Exception{
StringBuffer condition = new StringBuffer();
condition.append(" 1=1");
condition.append(" and old_loc_id="+id);
condition.append(" and org_id='"+orgId+"'");
AiscLocRealBean[] oldBean = AiscLocRealEngine.getBeans(condition.toString(), null);
if(oldBean!=null&&oldBean.length>0){
return oldBean[0].getLocId();
}else{
return id;
}
}
public long getRoomId(long id,String orgId) throws Exception{
StringBuffer condition = new StringBuffer();
condition.append(" 1=1");
condition.append(" and old_room_id="+id);
condition.append(" and org_id='"+orgId+"'");
AiscRoomRealBean[] oldBean = AiscRoomRealEngine.getBeans(condition.toString(), null);
if(oldBean!=null&&oldBean.length>0){
return oldBean[0].getRoomId();
}else{
return id;
}
}
public long getServerId(long id) throws Exception{
StringBuffer condition = new StringBuffer();
condition.append(" 1=1");
condition.append(" and old_server_id="+id);
AiscSeverinfoRealBean[] oldBean = AiscSeverinfoRealEngine.getBeans(condition.toString(), null);
if(oldBean!=null&&oldBean.length>0){
return oldBean[0].getServerId();
}else{
return id;
}
}
public long getBodyCode(long id,String orgId) throws Exception{
StringBuffer condition = new StringBuffer();
condition.append(" 1=1");
condition.append(" and old_bodypart_code="+id);
condition.append(" and org_id='"+orgId+"'");
AiscBodypartRealBean[] oldBean = AiscBodypartRealEngine.getBeans(condition.toString(), null);
if(oldBean!=null&&oldBean.length>0){
return oldBean[0].getBodypartCode();
}else{
return id;
}
}
public long getRealOrdSubcategoryId(long id,String orgId) throws Exception{
StringBuffer condition = new StringBuffer();
condition.append(" 1=1");
condition.append(" and old_subcate_id="+id);
condition.append(" and org_id='"+orgId+"'");
AiscOrdsubcategoryRealBean[] oldBean = AiscOrdsubcategoryRealEngine.getBeans(condition.toString(), null);
if(oldBean!=null&&oldBean.length>0){
return oldBean[0].getSubcateId();
}else{
return id;
}
}
public AiscItemMastBean getAiscItemMast(AiscItemMastBean bean) throws Exception{
StringBuffer condition = new StringBuffer();
condition.append(" 1=1");
condition.append(" and itemmast_code='"+bean.getItemmastCode()+"'");
condition.append(" and itemmast_desc='"+bean.getItemmastDesc()+"'");
condition.append(" and org_id='"+bean.getOrgId()+"'");
AiscItemMastBean[] oldBean = AiscItemMastEngine.getBeans(condition.toString(), null);
if(oldBean!=null&&oldBean.length>0){
return oldBean[0];
}else{
return null;
}
}
public AiscBodyPartBean getAiscBodyPart(AiscBodyPartBean bean) throws Exception{
StringBuffer condition = new StringBuffer();
condition.append(" 1=1");
condition.append(" and bodypart_desc='"+bean.getBodypartDesc()+"'");
condition.append(" and org_id='"+bean.getOrgId()+"'");
condition.append(" and bodypart_type='"+bean.getBodypartType()+"'");
AiscBodyPartBean[] oldBean = AiscBodyPartEngine.getBeans(condition.toString(), null);
if(oldBean!=null&&oldBean.length>0){
return oldBean[0];
}else{
return null;
}
}
public AiscBodyPart2ItemBean getAiscBodyPartItem(AiscBodyPart2ItemBean bean) throws Exception{
StringBuffer condition = new StringBuffer();
condition.append(" 1=1");
AiscItemmastRealBean[] realBeen = commonSV.getBeans(" ORG_ID = "+bean.getOrgId()+" and old_itemmast_id="+bean.getItemmastId(),null,AiscItemmastRealBean.class);
if(realBeen!=null&&realBeen.length>0){
condition.append(" and itemmast_id="+realBeen[0].getItemmastId()+"");
}else{
condition.append(" and itemmast_id="+bean.getItemmastId()+"");
}
condition.append(" and org_id = '"+bean.getOrgId()+"' ");
AiscBodypartRealBean[] partBeen = commonSV.getBeans(" ORG_ID = "+bean.getOrgId()+" and old_bodypart_code="+bean.getBodypartCode(),null,AiscBodypartRealBean.class);
if(partBeen!=null&&partBeen.length>0){
condition.append(" and bodypart_code="+partBeen[0].getBodypartCode()+"");
}else{
condition.append(" and bodypart_code="+bean.getBodypartCode()+"");
}
condition.append(" and org_id='"+bean.getOrgId()+"'");
AiscBodyPart2ItemBean[] oldBean = AiscBodyPart2ItemEngine.getBeans(condition.toString(), null);
if(oldBean!=null&&oldBean.length>0){
return oldBean[0];
}else{
return null;
}
}
public AiscOrdCat2LocBean getAiscOrdcat2loc(AiscOrdCat2LocBean bean) throws Exception{
StringBuffer condition = new StringBuffer();
condition.append(" 1=1");
AiscOrdcategoryRealBean[] ordcat = commonSV.getBeans(" ORG_ID = "+bean.getOrgId()+" and old_ordcategory_id="+bean.getOrdcatId(),null,AiscOrdcategoryRealBean.class);
if(ordcat!=null&&ordcat.length>0){
condition.append(" and ordcat_id="+ordcat[0].getOrdcategoryId()+"");
}else{
condition.append(" and ordcat_id="+bean.getOrdcatId()+"");
}
AiscLocRealBean[] realBeen = commonSV.getBeans(" ORG_ID = "+bean.getOrgId()+" and old_loc_id="+bean.getLocId(),null,AiscLocRealBean.class);
if(realBeen!=null&&realBeen.length>0){
condition.append(" and loc_id="+realBeen[0].getLocId()+"");
}else{
condition.append(" and loc_id="+bean.getLocId()+"");
}
condition.append(" and org_id = '"+bean.getOrgId()+"' ");
AiscOrdCat2LocBean[] oldBean = AiscOrdCat2LocEngine.getBeans(condition.toString(), null);
if(oldBean!=null&&oldBean.length>0){
return oldBean[0];
}else{
return null;
}
}
public AiscCareProvBean getAiscCareprov(AiscCareProvBean bean) throws Exception{
StringBuffer condition = new StringBuffer();
condition.append(" 1=1");
condition.append(" and careprov_code='"+bean.getCareprovCode()+"'");
condition.append(" and org_id = '"+bean.getOrgId()+"' ");
AiscCareProvBean[] oldBean = AiscCareProvEngine.getBeans(condition.toString(), null);
if(oldBean!=null&&oldBean.length>0){
return oldBean[0];
}else{
return null;
}
}
public String sendData(String body,String orgId) throws Exception{
Date currentTime = SysdateManager.getSysDate();
JSONObject jsonbody = JSONObject.fromObject(body);
String result = "success";
// try{
for (DataEnum c : DataEnum.values()) {
if("SEVERINFO".equals(c.getInterfaceName())){
JSONArray jsonArray = JSONArray.fromObject(jsonbody.getString("SEVERINFO"));
List<AiscServerInfoBean> list = (List<AiscServerInfoBean>) JSONArray.toCollection(jsonArray,AiscServerInfoBean.class);
for(AiscServerInfoBean serverBean :list){
AiscServerInfoBean yBean = getServerInfo(serverBean);
if(yBean==null){
AiscSeverinfoRealBean newBean =new AiscSeverinfoRealBean();
//插入新服务器ID与源服务器ID对应关系
newBean.setServerRealId(commonSV.getSequence("SEQ_AISC_SEVERINFO_REAL"));
newBean.setOldServerId(serverBean.getServerId());
newBean.setOrgId(orgId);
serverBean.setServerId(commonSV.getSequence("SEQSERVERINFOID"));
newBean.setServerId(serverBean.getServerId());
commonSV.save(serverBean);
commonSV.save(newBean);
}else{
AiscSeverinfoRealBean qryBean = commonSV.getBean(" OLD_SERVER_ID = "+serverBean.getServerId()+" and org_id='"+orgId+"'",null,AiscSeverinfoRealBean.class);
if (qryBean!=null){
String upSql= " update AISC_SEVERINFO_REAL t set SERVER_ID= "+yBean.getServerId()+",CREATE_TIME =to_date( '"+currentTime+"', 'yyyy-mm-dd hh24:mi:ss')\n" +
" where t.OLD_SERVER_ID = "+serverBean.getServerId()+" and t.org_id= '"+orgId+"'" ;
commonSV.execute(upSql,null);
}else{
AiscSeverinfoRealBean realBean = new AiscSeverinfoRealBean();
realBean.setServerRealId(commonSV.getSequence("SEQ_AISC_SEVERINFO_REAL"));
realBean.setOldServerId(serverBean.getServerId());
realBean.setOrgId(orgId);
realBean.setServerId(yBean.getServerId());
commonSV.save(realBean);
}
}
}
}
if("ROOM".equals(c.getInterfaceName())){
JSONArray jsonArray = JSONArray.fromObject(jsonbody.getString("ROOM"));
List<AiscRoomBean> list = (List<AiscRoomBean>) JSONArray.toCollection(jsonArray,AiscRoomBean.class);
for(AiscRoomBean roomBean :list){
//判断房间是否存在
AiscRoomBean ybean = getRoomInfo(roomBean);
if(ybean==null){
AiscRoomRealBean realBean =new AiscRoomRealBean();
realBean.setRoomRealId(commonSV.getSequence("SEQ_AISC_ROOM_REAL"));
realBean.setOldRoomId(roomBean.getRoomId());
realBean.setOrgId(String.valueOf(roomBean.getOrgId()));
roomBean.setRoomId(commonSV.getSequence("SEQROOMID"));
long locId = getLocId(roomBean.getLocId(),orgId);
roomBean.setLocId(locId);
realBean.setRoomId(roomBean.getRoomId());
commonSV.save(roomBean);
commonSV.save(realBean);
}else{
AiscRoomRealBean qryBean = commonSV.getBean(" OLD_ROOM_ID = "+roomBean.getRoomId()+" and org_id='"+ybean.getOrgId()+"'",null,AiscRoomRealBean.class);
if (qryBean!=null){
String upSql= " update AISC_ROOM_REAL t set ROOM_ID= "+ybean.getRoomId()+",CREATE_TIME =sysdate" +
" where t.OLD_ROOM_ID = "+roomBean.getRoomId()+" and t.org_id= "+ybean.getOrgId() ;
commonSV.execute(upSql,null);
}else{
AiscRoomRealBean realBean =new AiscRoomRealBean();
realBean.setRoomRealId(commonSV.getSequence("SEQ_AISC_ROOM_REAL"));
realBean.setOldRoomId(roomBean.getRoomId());
realBean.setOrgId(String.valueOf(roomBean.getOrgId()));
realBean.setRoomId(ybean.getRoomId());
commonSV.save(realBean);
}
}
}
}
if("LOC".equals(c.getInterfaceName())){
JSONArray jsonArray = JSONArray.fromObject(jsonbody.getString("LOC"));
List<AiscLocBean> list = (List<AiscLocBean>) JSONArray.toCollection(jsonArray,AiscLocBean.class);
for(AiscLocBean locBeen :list){
AiscLocBean oldBean = getLocInfo(locBeen);
if(oldBean==null){
//插入新科室及关系对应
AiscLocRealBean realBean = new AiscLocRealBean();
realBean.setLocRealId(commonSV.getSequence("SEQ_AISC_LOC_REAL"));
realBean.setOrgId(locBeen.getOrgId());
realBean.setOldLocId(locBeen.getLocId());
locBeen.setLocId(commonSV.getSequence("SEQLOCID"));
long serverId = getServerId(locBeen.getServerId());
locBeen.setServerId(serverId);
realBean.setLocId(locBeen.getLocId());
commonSV.save(locBeen);
commonSV.save(realBean);
}else{
AiscLocRealBean qryBean = commonSV.getBean(" OLD_LOC_ID = "+locBeen.getLocId()+" and org_id='"+oldBean.getOrgId()+"'",null,AiscLocRealBean.class);
if (qryBean!=null){
String upSql= " update aisc_loc_real t set loc_id= "+oldBean.getLocId()+",CREATE_TIME =sysdate" +
" where t.OLD_LOC_ID = "+locBeen.getLocId()+" and t.org_id= "+oldBean.getOrgId() ;
commonSV.execute(upSql,null);
}else{
AiscLocRealBean realBean = new AiscLocRealBean();
realBean.setLocRealId(commonSV.getSequence("SEQ_AISC_LOC_REAL"));
realBean.setOrgId(locBeen.getOrgId());
realBean.setOldLocId(locBeen.getLocId());
realBean.setLocId(oldBean.getLocId());
commonSV.save(realBean);
}
}
}
}
if("EQUIPMENT".equals(c.getInterfaceName())){
JsonConfig jsonConfig = new JsonConfig();
String[] formats={"yyyy-MM-dd HH:mm:ss","yyyy-MM-dd"};
JSONUtils.getMorpherRegistry().registerMorpher(new TimestampMorpher(formats));
JSONArray jsonArray = JSONArray.fromObject(jsonbody.getString("EQUIPMENT"),jsonConfig);
List<AiscEquipmentBean> list = (List<AiscEquipmentBean>) JSONArray.toCollection(jsonArray,AiscEquipmentBean.class);
for(AiscEquipmentBean equipmentBeen:list){
AiscEquipmentBean oldBean = getEquipment(equipmentBeen);
if(oldBean==null){
AiscEquipmentRealBean realBean =new AiscEquipmentRealBean();
realBean.setEquipmentRealId(commonSV.getSequence("SEQ_AISC_EQUIPMENT_REAL"));
realBean.setOrgId(equipmentBeen.getOrgId());
realBean.setOldEquipmentId(equipmentBeen.getEquipmentId());
equipmentBeen.setEquipmentId(commonSV.getSequence("SEQEQUIPMENTID"));
long locId = getLocId(equipmentBeen.getLocId(),orgId);
equipmentBeen.setLocId(locId);
long roomId = getRoomId(equipmentBeen.getRoomId(),orgId);
equipmentBeen.setRoomId(roomId);
realBean.setEquipmentId(equipmentBeen.getEquipmentId());
// long ordsubcategoryId = getRealOrdSubcategoryId(equipmentBeen.getOrdsubcategoryId(),orgId);
// equipmentBeen.setOrdsubcategoryId(ordsubcategoryId);
commonSV.save(equipmentBeen);
commonSV.save(realBean);
}else{
AiscEquipmentRealBean qryBean = commonSV.getBean(" OLD_EQUIPMENT_ID = "+equipmentBeen.getEquipmentId()+" and org_id='"+oldBean.getOrgId()+"'",null,AiscEquipmentRealBean.class);
if (qryBean!=null){
String upSql= " update aisc_equipment_real t set EQUIPMENT_ID= "+oldBean.getEquipmentId()+",CREATE_TIME =sysdate" +
" where t.OLD_EQUIPMENT_ID = "+equipmentBeen.getEquipmentId()+" and t.org_id= "+oldBean.getOrgId() ;
commonSV.execute(upSql,null);
}else{
AiscEquipmentRealBean realBean = new AiscEquipmentRealBean();
realBean.setEquipmentRealId(commonSV.getSequence("SEQ_AISC_EQUIPMENT_REAL"));
realBean.setOrgId(equipmentBeen.getOrgId());
realBean.setOldEquipmentId(equipmentBeen.getEquipmentId());
realBean.setEquipmentId(oldBean.getEquipmentId());
commonSV.save(realBean);
}
}
}
}
if("ORDCATEGORY".equals(c.getInterfaceName())){
JSONArray jsonArray = JSONArray.fromObject(jsonbody.getString("ORDCATEGORY"));
List<AiscOrdCategoryBean> list = (List<AiscOrdCategoryBean>) JSONArray.toCollection(jsonArray,AiscOrdCategoryBean.class);
for (AiscOrdCategoryBean ordCategoryBeen:list){
AiscOrdCategoryBean oldBean = getCategory(ordCategoryBeen);
if(oldBean==null){
AiscOrdcategoryRealBean realBean =new AiscOrdcategoryRealBean();
realBean.setOrdcategoryRealId(commonSV.getSequence("SEQ_AISC_ORDCATEGORY_REAL"));
realBean.setOldOrdcategoryId(ordCategoryBeen.getOrdcategoryId());
realBean.setOrgId(orgId);
ordCategoryBeen.setOrdcategoryId(commonSV.getSequence("SEQ_ORDCATEGORY"));
realBean.setOrdcategoryId(ordCategoryBeen.getOrdcategoryId());
commonSV.save(ordCategoryBeen);
commonSV.save(realBean);
}else{
AiscOrdcategoryRealBean qryBean = commonSV.getBean(" OLD_ORDCATEGORY_ID = "+ordCategoryBeen.getOrdcategoryId()+" and org_id='"+orgId+"'",null,AiscOrdcategoryRealBean.class);
if (qryBean!=null){
String upSql= " update AISC_ORDCATEGORY_REAL t set ORDCATEGORY_ID= "+oldBean.getOrdcategoryId()+",CREATE_TIME =sysdate" +
" where t.OLD_ORDCATEGORY_ID = "+ordCategoryBeen.getOrdcategoryId()+" and t.org_id= '"+orgId+"'" ;
commonSV.execute(upSql,null);
}else{
AiscOrdcategoryRealBean realBean =new AiscOrdcategoryRealBean();
realBean.setOrdcategoryRealId(commonSV.getSequence("SEQ_AISC_ORDCATEGORY_REAL"));
realBean.setOldOrdcategoryId(ordCategoryBeen.getOrdcategoryId());
realBean.setOrgId(orgId);
realBean.setOrdcategoryId(oldBean.getOrdcategoryId());
commonSV.save(realBean);
}
}
}
}
if("ORDSUBCATEGORY".equals(c.getInterfaceName())){
JSONArray jsonArray = JSONArray.fromObject(jsonbody.getString("ORDSUBCATEGORY"));
List<AiscOrdSubCategoryBean> list = (List<AiscOrdSubCategoryBean>) JSONArray.toCollection(jsonArray,AiscOrdSubCategoryBean.class);
for (AiscOrdSubCategoryBean ordSubCategoryBeen:list){
QryordsubcateINFBean oldBean = getAiscOrdSubCategory(ordSubCategoryBeen,orgId);
if(oldBean==null){
AiscOrdsubcategoryRealBean realBean =new AiscOrdsubcategoryRealBean();
realBean.setSubcateRealId(commonSV.getSequence("SEQ_aisc_ordsubcategory_real"));
realBean.setOldSubcateId (ordSubCategoryBeen.getOrdsubcategoryId());
realBean.setOrgId(orgId);
ordSubCategoryBeen.setOrdsubcategoryId(commonSV.getSequence("SEQ_ORDSUBCATEGORY"));
realBean.setSubcateId(ordSubCategoryBeen.getOrdsubcategoryId());
long id = getRealOrdcategoryId(ordSubCategoryBeen.getOrdcategoryId(),orgId);
ordSubCategoryBeen.setOrdcategoryId(id);
commonSV.save(ordSubCategoryBeen);
commonSV.save(realBean);
}else{
AiscOrdsubcategoryRealBean qryBean = commonSV.getBean(" old_subcate_id = "+ordSubCategoryBeen.getOrdsubcategoryId()+" and org_id='"+orgId+"'",null,AiscOrdsubcategoryRealBean.class);
if (qryBean!=null){
String upSql= " update aisc_ordsubcategory_real t set subcate_id= "+oldBean.getOrdsubcategoryId()+",CREATE_TIME =sysdate" +
" where t.old_subcate_id = "+ordSubCategoryBeen.getOrdsubcategoryId()+" and t.org_id= '"+orgId+"'" ;
commonSV.execute(upSql,null);
}else{
AiscOrdsubcategoryRealBean realBean =new AiscOrdsubcategoryRealBean();
realBean.setSubcateRealId(commonSV.getSequence("SEQ_aisc_ordsubcategory_real"));
realBean.setOldSubcateId (ordSubCategoryBeen.getOrdsubcategoryId());
realBean.setOrgId(orgId);
realBean.setSubcateId(oldBean.getOrdsubcategoryId());
commonSV.save(realBean);
}
}
}
}
if("ITEMMAST".equals(c.getInterfaceName())){
JSONArray jsonArray = JSONArray.fromObject(jsonbody.getString("ITEMMAST"));
List<AiscItemMastBean> list = (List<AiscItemMastBean>) JSONArray.toCollection(jsonArray,AiscItemMastBean.class);
for (AiscItemMastBean itemMastBeen:list){
AiscItemMastBean oldBean = getAiscItemMast(itemMastBeen);
if(oldBean==null){
AiscItemmastRealBean newBean =new AiscItemmastRealBean();
newBean.setItemmastRealId(commonSV.getSequence("SEQ_AISC_ITEMMAST_REAL"));
newBean.setOldItemmastId(itemMastBeen.getItemmastId());
newBean.setOrgId(orgId);
itemMastBeen.setItemmastId(commonSV.getSequence("SEQ_ITEMMAST"));
newBean.setItemmastId(itemMastBeen.getItemmastId());
long id = getRealOrdcategoryId(itemMastBeen.getOrdcategoryId(),orgId);
itemMastBeen.setOrdcategoryId(id);
long subid = getRealOrdSubcategoryId(itemMastBeen.getOrdsubcategoryId(),orgId);
itemMastBeen.setOrdsubcategoryId(subid);
commonSV.save(itemMastBeen);
commonSV.save(newBean);
}else{
AiscItemmastRealBean qryBean = commonSV.getBean(" OLD_ITEMMAST_ID = "+itemMastBeen.getItemmastId()+" and org_id='"+orgId+"'",null,AiscItemmastRealBean.class);
if (qryBean!=null){
String upSql= " update aisc_itemmast_real t set ITEMMAST_ID= "+oldBean.getItemmastId()+",CREATE_TIME =sysdate" +
" where t.OLD_ITEMMAST_ID = "+itemMastBeen.getItemmastId()+" and t.org_id= '"+orgId+"'";
commonSV.execute(upSql,null);
}else{
AiscItemmastRealBean newBean =new AiscItemmastRealBean();
newBean.setItemmastRealId(commonSV.getSequence("SEQ_AISC_ITEMMAST_REAL"));
newBean.setOldItemmastId(itemMastBeen.getItemmastId());
newBean.setOrgId(orgId);
newBean.setItemmastId(oldBean.getItemmastId());
commonSV.save(newBean);
}
}
}
}
if("BODYPART".equals(c.getInterfaceName())){
JSONArray jsonArray = JSONArray.fromObject(jsonbody.getString("BODYPART"));
List<AiscBodyPartBean> list = (List<AiscBodyPartBean>) JSONArray.toCollection(jsonArray,AiscBodyPartBean.class);
for (AiscBodyPartBean bodyPartBeen:list){
AiscBodyPartBean oldBean = getAiscBodyPart(bodyPartBeen);
if(oldBean==null){
AiscBodypartRealBean newBean =new AiscBodypartRealBean();
newBean.setBodypartRealId(commonSV.getSequence("SEQ_AISC_BODYPART_REAL"));
newBean.setOldBodypartCode(Long.parseLong(bodyPartBeen.getBodypartCode()));
newBean.setOrgId(orgId);
bodyPartBeen.setBodypartCode(String.valueOf(commonSV.getSequence("SEQBODYPARTID")));
if(bodyPartBeen.getBodypartPid()!=-1){
long id = getBodyCode(bodyPartBeen.getBodypartPid(),orgId);
bodyPartBeen.setBodypartPid(id);
}
newBean.setBodypartCode(Long.parseLong(bodyPartBeen.getBodypartCode()));
commonSV.save(bodyPartBeen);
commonSV.save(newBean);
}else{
AiscBodypartRealBean qryBean = commonSV.getBean(" OLD_BODYPART_CODE = "+bodyPartBeen.getBodypartCode()+" and org_id='"+orgId+"'",null,AiscBodypartRealBean.class);
if (qryBean!=null){
String upSql= " update AISC_BODYPART_REAL t set BODYPART_CODE= "+oldBean.getBodypartCode()+",CREATE_TIME =sysdate" +
" where t.OLD_BODYPART_CODE = "+bodyPartBeen.getBodypartCode()+" and t.org_id= '"+orgId+"'" ;
commonSV.execute(upSql,null);
}else{
AiscBodypartRealBean newBean =new AiscBodypartRealBean();
newBean.setBodypartRealId(commonSV.getSequence("SEQ_AISC_BODYPART_REAL"));
newBean.setOldBodypartCode(Long.parseLong(bodyPartBeen.getBodypartCode()));
newBean.setOrgId(orgId);
newBean.setBodypartCode(Long.parseLong(oldBean.getBodypartCode()));
commonSV.save(newBean);
}
}
}
}
if("BODYPART2ITEM".equals(c.getInterfaceName())){
JSONArray jsonArray = JSONArray.fromObject(jsonbody.getString("BODYPART2ITEM"));
List<AiscBodyPart2ItemBean> list = (List<AiscBodyPart2ItemBean>) JSONArray.toCollection(jsonArray,AiscBodyPart2ItemBean.class);
for (AiscBodyPart2ItemBean bodyPart2ItemBeen:list){
AiscBodyPart2ItemBean oldBean = getAiscBodyPartItem(bodyPart2ItemBeen);
if(oldBean==null){
AiscBodyPart2ItemRealBean realBean =new AiscBodyPart2ItemRealBean();
realBean.setItemRealId(commonSV.getSequence("SEQ_AISC_BODYPART2ITEM_REAL"));
realBean.setOldItemId(bodyPart2ItemBeen.getBodypart2Id());
realBean.setOrgId(String.valueOf(bodyPart2ItemBeen.getOrgId()));
bodyPart2ItemBeen.setBodypart2Id(commonSV.getSequence("SEQBODYPARTITEMID"));
realBean.setItemId(bodyPart2ItemBeen.getBodypart2Id());
long mastid = getItemmastId(bodyPart2ItemBeen.getItemmastId(),orgId);
bodyPart2ItemBeen.setItemmastId(mastid);
long bodyCode = getBodyCode(Long.parseLong(bodyPart2ItemBeen.getBodypartCode()),orgId);
bodyPart2ItemBeen.setBodypartCode(String.valueOf(bodyCode));
commonSV.save(bodyPart2ItemBeen);
commonSV.save(realBean);
}else{
AiscBodyPart2ItemRealBean qryBean = commonSV.getBean(" OLD_ITEM_ID = "+bodyPart2ItemBeen.getBodypart2Id()+" and org_id='"+String.valueOf(bodyPart2ItemBeen.getOrgId())+"'",null,AiscBodyPart2ItemRealBean.class);
if (qryBean!=null){
String upSql= " update aisc_bodypart2item_real t set ITEM_ID= "+oldBean.getBodypart2Id()+",CREATE_TIME =sysdate" +
" where t.OLD_ITEM_ID = "+bodyPart2ItemBeen.getBodypart2Id()+" and t.org_id= '"+String.valueOf(bodyPart2ItemBeen.getOrgId())+"'" ;
commonSV.execute(upSql,null);
}else{
AiscBodyPart2ItemRealBean realBean =new AiscBodyPart2ItemRealBean();
realBean.setItemRealId(commonSV.getSequence("SEQ_AISC_BODYPART2ITEM_REAL"));
realBean.setOldItemId(bodyPart2ItemBeen.getBodypart2Id());
realBean.setOrgId(String.valueOf(bodyPart2ItemBeen.getOrgId()));
realBean.setItemId(oldBean.getBodypart2Id());
commonSV.save(realBean);
}
}
}
}
if("ORDCAT2LOC".equals(c.getInterfaceName())){
JSONArray jsonArray = JSONArray.fromObject(jsonbody.getString("ORDCAT2LOC"));
List<AiscOrdCat2LocBean> list = (List<AiscOrdCat2LocBean>) JSONArray.toCollection(jsonArray,AiscOrdCat2LocBean.class);
for (AiscOrdCat2LocBean ordCat2LocBeen:list){
AiscOrdCat2LocBean oldBean = getAiscOrdcat2loc(ordCat2LocBeen);
if(oldBean==null){
AiscOrdCat2LocRealBean realBean = new AiscOrdCat2LocRealBean();
realBean.setOrdcat2locRealId(commonSV.getSequence("SEQ_AISC_ORDCAT2LOC_REAL"));
realBean.setOldOrdcat2locId(ordCat2LocBeen.getOrdcat2locId());
realBean.setOrgId(String.valueOf(ordCat2LocBeen.getOrgId()));
ordCat2LocBeen.setOrdcat2locId(commonSV.getSequence("SEQORDCAT2LOC"));
long locId = getLocId(ordCat2LocBeen.getLocId(),orgId);
ordCat2LocBeen.setLocId(locId);
long id = getRealOrdcategoryId(ordCat2LocBeen.getOrdcatId(),orgId);
ordCat2LocBeen.setOrdcatId(id);;
realBean.setOrdcat2locId(ordCat2LocBeen.getOrdcat2locId());
commonSV.save(ordCat2LocBeen);
commonSV.save(realBean);
}else{
AiscOrdCat2LocRealBean qryBean = commonSV.getBean(" old_ORDCAT2LOC_id = "+ordCat2LocBeen.getOrdcat2locId()+" and org_id='"+String.valueOf(ordCat2LocBeen.getOrgId())+"'",null,AiscOrdCat2LocRealBean.class);
if (qryBean!=null){
String upSql= " update AISC_ORDCAT2LOC_REAL t set ORDCAT2LOC_id= "+oldBean.getOrdcat2locId()+",CREATE_TIME =sysdate" +
" where t.old_ORDCAT2LOC_id = "+ordCat2LocBeen.getOrdcat2locId()+" and t.org_id= '"+String.valueOf(ordCat2LocBeen.getOrgId())+"'" ;
commonSV.execute(upSql,null);
}else{
AiscOrdCat2LocRealBean realBean = new AiscOrdCat2LocRealBean();
realBean.setOrdcat2locRealId(commonSV.getSequence("SEQ_AISC_ORDCAT2LOC_REAL"));
realBean.setOldOrdcat2locId(ordCat2LocBeen.getOrdcat2locId());
realBean.setOrgId(String.valueOf(ordCat2LocBeen.getOrgId()));
realBean.setOrdcat2locId(oldBean.getOrdcat2locId());
commonSV.save(realBean);
}
}
}
}
if("CAREPROV".equals(c.getInterfaceName())){
JSONArray jsonArray = JSONArray.fromObject(jsonbody.getString("CAREPROV"));
List<AiscCareProvBean> list = (List<AiscCareProvBean>) JSONArray.toCollection(jsonArray,AiscCareProvBean.class);
for (AiscCareProvBean careProvBeen:list){
AiscCareProvBean oldBean = getAiscCareprov(careProvBeen);
if(oldBean==null){
AiscCareprovRealBean realBean =new AiscCareprovRealBean();
realBean.setCareprovRealId(commonSV.getSequence("SEQ_AISC_CAREPROV_REAL"));
realBean.setOldCareprovId(careProvBeen.getCareprovId());
realBean.setOrgId(String.valueOf(careProvBeen.getOrgId()));
careProvBeen.setCareprovId(commonSV.getSequence("SEQ_AISC_CAREPROV"));
realBean.setCareprovId(careProvBeen.getCareprovId());
long locId = getLocId(careProvBeen.getLocId(),orgId);
careProvBeen.setLocId(locId);
commonSV.save(careProvBeen);
commonSV.save(realBean);
}else{
AiscCareprovRealBean qryBean = commonSV.getBean(" OLD_CAREPROV_ID = "+careProvBeen.getCareprovId()+" and org_id='"+String.valueOf(careProvBeen.getOrgId())+"'",null,AiscCareprovRealBean.class);
if (qryBean!=null){
String upSql= " update AISC_CAREPROV_REAL t set CAREPROV_ID= "+oldBean.getCareprovId()+",CREATE_TIME =sysdate" +
" where t.OLD_CAREPROV_ID = "+careProvBeen.getCareprovId()+" and t.org_id= '"+String.valueOf(careProvBeen.getOrgId())+"'" ;
commonSV.execute(upSql,null);
}else{
AiscCareprovRealBean realBean =new AiscCareprovRealBean();
realBean.setCareprovRealId(commonSV.getSequence("SEQ_AISC_CAREPROV_REAL"));
realBean.setOldCareprovId(careProvBeen.getCareprovId());
realBean.setOrgId(String.valueOf(careProvBeen.getOrgId()));
realBean.setCareprovId(oldBean.getCareprovId());
commonSV.save(realBean);
}
}
}
}
}
translateBatch(orgId);
// }catch(Exception e){
// result = "faild";
// e.printStackTrace();
// }
return result;
}
public String sendBusiData(String body,String orgId) throws Exception{
Date currentTime = SysdateManager.getSysDate();
JSONObject jsonbody = JSONObject.fromObject(body);
String result = "success";
for (BusiDataEnum c : BusiDataEnum.values()) {
if("PATIENTINFO".equals(c.getInterfaceName())){
JSONArray jsonArray = JSONArray.fromObject(jsonbody.getString("PATIENTINFO"));
List<AisPatientInfoData> list = (List<AisPatientInfoData>) JSONArray.toCollection(jsonArray,AisPatientInfoData.class);
//首先根据身份证号判断
for(AisPatientInfoData model:list){
AisPatientInfoBean[] patientBean = null;
if(isNotBlank(model.getPatientIdnumber())){
patientBean = getAisPatientBean(model.getPatientIdnumber());
}
//查询ais_pixinfo表中是否有记录
AisPixInfoBean[] pixBean = getAisPixInfoBean(model.getPatientId(),orgId);
//该情况只有人为修改数据的时候才会出现
if(pixBean!=null&&patientBean==null){
//pixBean 更新
//patient 插入
}else if(pixBean==null&&patientBean==null){
//patient 插入&pixBean 插入
insertPatientBean(orgId,model);
}else if(pixBean==null&&patientBean!=null){
//查询pacs已有病人信息
if(patientBean!=null&&patientBean.length>0){
for(int hh=0;hh<patientBean.length;hh++){
//插入pixBean
if(isFlag(patientBean[0].getPatientGlobalid(),orgId)){
insertPixBean(patientBean[hh].getPatientGlobalid(),orgId,model);
}
//更新中心pacs已有病人信息
updatePatient(patientBean[hh].getPatientGlobalid(),model);
}
}
}else{
//若pix和中心patient都有信息,则只更新病人信息
if(pixBean!=null&&pixBean.length>0){
for(int hh=0;hh<pixBean.length;hh++){
//更新中心pacs已有病人信息
updatePatient(pixBean[hh].getPatientGlobalid(),model);
}
}
}
}
}
if("STUDYINFO".equals(c.getInterfaceName())){
JsonConfig jsonConfig = new JsonConfig();
String[] formats={"yyyy-MM-dd HH:mm:ss","yyyy-MM-dd"};
JSONUtils.getMorpherRegistry().registerMorpher(new TimestampMorpher(formats));
JSONArray jsonArray = JSONArray.fromObject(jsonbody.getString("STUDYINFO"),jsonConfig);
List<AisStudyInfoBean> list = (List<AisStudyInfoBean>) JSONArray.toCollection(jsonArray,AisStudyInfoBean.class);
for (AisStudyInfoBean bean : list){
long studyinfoId= Long.parseLong(orgId+bean.getStudyinfoId());
AisStudyinfoRealBean oldBean = getStudyinfoRealBean(studyinfoId,bean.getOrgId());
if(oldBean==null){
AisStudyinfoRealBean realBean =new AisStudyinfoRealBean();
realBean.setStudyinfoRealId(commonSV.getSequence("SEQSTUDYTEMPID"));
realBean.setOldStudyinfoId(studyinfoId);
realBean.setOrgId(String.valueOf(bean.getOrgId()));
bean.setStudyinfoId(Long.parseLong(orgId+commonSV.getSequence("SEQSTUDYINFOID")));
realBean.setStudyinfoId(bean.getStudyinfoId());
//转义
translateStudyinfo(bean);
//插入关系表及的登记记录
commonSV.save(bean);
commonSV.save(realBean);
}else{
//修改登记信息
AisStudyInfoBean oldstudyInfoBean = new AisStudyInfoBean();
oldstudyInfoBean.setStudyinfoId(oldBean.getStudyinfoId());
oldstudyInfoBean.setStsToOld();
bean.setStudyinfoId(oldBean.getStudyinfoId());
DataContainerFactory.copyNoClearData(bean, oldstudyInfoBean);
translateStudyinfo(oldstudyInfoBean);
AisStudyInfoEngine.save(oldstudyInfoBean);
}
}
}
if("STUDYITEMINFO".equals(c.getInterfaceName())){
JSONArray jsonArray = JSONArray.fromObject(jsonbody.getString("STUDYITEMINFO"));
List<AisStudyItemInfoBean> list = (List<AisStudyItemInfoBean>) JSONArray.toCollection(jsonArray,AisStudyItemInfoBean.class);
for (AisStudyItemInfoBean bean : list){
AisStudyItemInfoBean studyitemBeen = new AisStudyItemInfoBean();
AisStudyinfoRealBean oldBean = getStudyinfoRealBean(Long.parseLong(orgId+bean.getStudyinfoId()),orgId);
//studyinfoId转义
if(oldBean!=null){
deleteStudyIteminfo(oldBean.getStudyinfoId(),orgId);
studyitemBeen.setStudyinfoId(oldBean.getStudyinfoId());
}
//检查项目code转义
AiscItemmastRealBean studyitem = getStudyItemRealBean(Long.parseLong(bean.getStudyitemCode()),orgId);
if(studyitem!=null){
studyitemBeen.setStudyitemCode(String.valueOf(studyitem.getItemmastId()));
}
studyitemBeen.setStudyitemId(commonSV.getSequence("SEQSTUDYITEMID"));
studyitemBeen.setStudyitemHisid(bean.getStudyitemHisid());
studyitemBeen.setStudyitemCode(bean.getStudyitemCode());
studyitemBeen.setStudyitemDesc(bean.getStudyitemDesc());
studyitemBeen.setStudyitemEndesc(bean.getStudyitemEndesc());
studyitemBeen.setStudyitemBodyinfo(bean.getStudyitemBodyinfo());
studyitemBeen.setStudyitemPrice(bean.getStudyitemPrice());
studyitemBeen.setStudyitemNumber(Integer.parseInt(String.valueOf(bean.getStudyitemNumber())));
studyitemBeen.setStudyitemStatus(bean.getStudyitemStatus());
studyitemBeen.setStudyitemItemno(bean.getStudyitemItemno());
if(bean.getStudyitemBodypart()!=null&&!"".equals(bean.getStudyitemBodypart())){
String arr[] = bean.getStudyitemBodypart().split(",");
String parts = "";
boolean task = false;
for(int i=0;i<arr.length;i++){
AiscBodypartRealBean partBean = getBodypartRealBean(Long.parseLong(arr[i]),orgId);
if(partBean!=null){
parts+=partBean.getBodypartCode()+",";
}else{
parts = bean.getStudyitemBodypart();
task = true;
}
}
if(task){
studyitemBeen.setStudyitemBodypart(parts);
}else{
studyitemBeen.setStudyitemBodypart(parts.substring(0,parts.length()-1));
}
}
commonSV.save(studyitemBeen);
}
}
if("STUDYREPORT".equals(c.getInterfaceName())){
JSONArray jsonArray = JSONArray.fromObject(jsonbody.getString("STUDYREPORT"));
List<AisStudyReportBean> list = (List<AisStudyReportBean>) JSONArray.toCollection(jsonArray,AisStudyReportBean.class);
for (AisStudyReportBean bean : list){
AisStudyReportBean studyreport = new AisStudyReportBean();
//studyinfoId转义
AisStudyinfoRealBean realbean = getStudyinfoRealBean(Long.parseLong(orgId+bean.getStudyinfoId()),orgId);
if(realbean!=null){
deleteStudyReport(realbean.getStudyinfoId(),orgId);
studyreport.setStudyinfoId(realbean.getStudyinfoId());
}else{
studyreport.setStudyinfoId(Long.parseLong(orgId+bean.getStudyinfoId()));
}
studyreport.setReportId(commonSV.getSequence("SEQREPORTID"));
studyreport.setReportDatetime(bean.getReportDatetime());
if (isNotBlank(bean.getReportDoctorid())) {
AiscCareprovRealBean reportdoc = getCareBean(Long.parseLong(bean.getReportDoctorid()),orgId);
if(reportdoc!=null){
studyreport.setReportDoctorid(String.valueOf(reportdoc.getCareprovId()));
}else{
studyreport.setReportDoctorid(bean.getReportDoctorid());
}
}
studyreport.setReportVerifydatetime(bean.getReportVerifydatetime());
if (isNotBlank(bean.getReportVerifydoctorid())) {
AiscCareprovRealBean verifydoc = getCareBean(Long.parseLong(bean.getReportVerifydoctorid()),orgId);
if(verifydoc!=null){
studyreport.setReportVerifydoctorid(String.valueOf(verifydoc.getCareprovId()));
}else{
studyreport.setReportVerifydoctorid(bean.getReportVerifydoctorid());
}
}
studyreport.setReportFinaldatetime(bean.getReportFinaldatetime());
if (isNotBlank(bean.getReportFinaldoctorid())) {
AiscCareprovRealBean finaldoc = getCareBean(Long.parseLong(bean.getReportFinaldoctorid()),orgId);
if(finaldoc!=null){
studyreport.setReportFinaldoctorid(String.valueOf(finaldoc.getCareprovId()));
}else{
studyreport.setReportFinaldoctorid(bean.getReportFinaldoctorid());
}
}
if (isNotBlank(bean.getReportRecord())) {
AiscCareprovRealBean writedoc = getCareBean(Long.parseLong(bean.getReportRecord()),orgId);
if(writedoc!=null){
studyreport.setReportRecord(String.valueOf(writedoc.getCareprovId()));
}else{
studyreport.setReportRecord(bean.getReportRecord());
}
}
studyreport.setReportIscompleted(Integer.parseInt(String.valueOf(bean.getReportIscompleted())));
studyreport.setReportIspositive(Integer.parseInt(String.valueOf(bean.getReportIspositive())));
studyreport.setReportIsprinted(Integer.parseInt(String.valueOf(bean.getReportIsprinted())));
studyreport.setReportIssent(Integer.parseInt(String.valueOf(bean.getReportIssent())));
studyreport.setReportPrintcareprovid(bean.getReportPrintcareprovid());
studyreport.setReportPrintdatetime(bean.getReportPrintdatetime());
studyreport.setReportUncompletedreason(bean.getReportUncompletedreason());
studyreport.setReportExam(bean.getReportExam());
studyreport.setReportExammethod(bean.getReportExammethod());
studyreport.setReportResult(bean.getReportResult());
studyreport.setReportIcd10(bean.getReportIcd10());
studyreport.setReportAcrcode(bean.getReportAcrcode());
studyreport.setReportRemark(bean.getReportRemark());
studyreport.setReportLock(Integer.parseInt(String.valueOf(bean.getReportLock())));
commonSV.save(studyreport);
}
}
}
return result;
}
public void deleteStudyReport(long studyinfoId,String orgId){
try {
String delSql2 = "delete from ais_studyreport where report_id=(select "
+ " report_id from ais_studyreport a,ais_studyinfo b where a.studyinfo_id=b.studyinfo_id "
+ " and b.org_id=:ORG_ID and a.studyinfo_id=:studyinfoId and b.studystatus_code = 'VERIFY')";
Map delMap2 = new HashMap();
delMap2.put("ORG_ID",orgId);
delMap2.put("studyinfoId",studyinfoId);
commonSV.execute(delSql2,delMap2);
}catch (Exception e){
e.printStackTrace();
}
}
public void deleteStudyIteminfo(long studyinfoId,String orgId){
try {
String delSql2 = "delete from ais_studyiteminfo where studyitem_id=(select "
+ " studyitem_id from ais_studyiteminfo a,ais_studyinfo b where a.studyinfo_id=b.studyinfo_id "
+ " and b.org_id=:ORG_ID and a.studyinfo_id=:studyinfoId and b.studystatus_code='VERIFY') ";
Map delMap2 = new HashMap();
delMap2.put("ORG_ID",orgId);
delMap2.put("studyinfoId",studyinfoId);
commonSV.execute(delSql2,delMap2);
}catch (Exception e){
e.printStackTrace();
}
}
private AisStudyInfoBean translateStudyinfo(AisStudyInfoBean bean) throws Exception{
AiscLocRealBean realbean = getLocRealBean(bean.getLocId(),bean.getOrgId());
if(realbean!=null){
bean.setLocId(realbean.getLocId());
}
//申请科室转义
if (bean.getStudyApplocid()!=-1&&isNotBlank(String.valueOf(bean.getStudyApplocid()))) {
AiscLocRealBean applocbean = getLocRealBean(bean.getStudyApplocid(),bean.getOrgId());
if(applocbean!=null){
bean.setStudyApplocid(applocbean.getLocId());
}
}
//房间转义
if (bean.getRoomId()!=-1&&isNotBlank(String.valueOf(bean.getRoomId()))) {
AiscRoomRealBean roomreal = getRoomReal(bean.getRoomId(),bean.getOrgId());
if(roomreal!=null){
bean.setRoomId(roomreal.getRoomId());
}
}
//申请医生转义
if (isNotBlank(bean.getStudyAppdoc())) {
AiscCareprovRealBean carebean = getCareBean(Long.parseLong(bean.getStudyAppdoc()),bean.getOrgId());
if(carebean!=null){
bean.setStudyAppdoc(String.valueOf(carebean.getCareprovId()));
}
}
//设备转义
if (bean.getEquipmentId()!=-1&&isNotBlank(String.valueOf(bean.getEquipmentId()))) {
AiscEquipmentRealBean equipreal = getEquipmentBean(bean.getEquipmentId(),bean.getOrgId());
if(equipreal!=null){
bean.setEquipmentId(equipreal.getEquipmentId());
}
}
//操作员转义
if (isNotBlank(bean.getStudyOperationid())) {
// AiscCareprovRealBean operbean = getCareBean(Long.parseLong(bean.getStudyOperationid()),bean.getOrgId());
// bean.setStudyOperationid(String.valueOf(operbean.get));
}
//检查医生转义
if (isNotBlank(bean.getStudyDoctorid())) {
AiscCareprovRealBean docbean = getCareBean(Long.parseLong(bean.getStudyDoctorid()),bean.getOrgId());
if(docbean!=null){
bean.setStudyDoctorid(String.valueOf(docbean.getCareprovId()));
}
}
//辅助技师转义
if (isNotBlank(bean.getAidDoctorid())) {
AiscCareprovRealBean jsbean = getCareBean(Long.parseLong(bean.getAidDoctorid()),bean.getOrgId());
if(jsbean!=null){
bean.setStudyDoctorid(String.valueOf(jsbean.getCareprovId()));
}
}
//病人ID转义
AisPatientRealBean paBean = getRealGlobalId(bean.getPatientGlobalid(),bean.getOrgId());
if(paBean!=null){
bean.setPatientGlobalid(paBean.getGlobalId());
}
return bean;
}
private Boolean translateBatch(String orgId){
Boolean flag =false ;
try {
//---------科室关系表-----------------
AiscLocRealBean[] realBeen = commonSV.getBeans(" ORG_ID = "+orgId,null,AiscLocRealBean.class);
for (AiscLocRealBean realBean:realBeen){
//设备信息中科室转义
AiscEquipmentBean[] equipmentBeens = commonSV.getBeans(" LOC_ID = "+realBean.getOldLocId()+" and ORG_ID = "+orgId,null,AiscEquipmentBean.class);
for (AiscEquipmentBean bean:equipmentBeens) {
bean.setStsToOld();
bean.setLocId(realBean.getLocId());
commonSV.save(bean);
}
//房间信息中科室转义
AiscRoomBean[] roomBeen = commonSV.getBeans(" LOC_ID = "+realBean.getOldLocId()+" and ORG_ID = "+orgId,null,AiscRoomBean.class);
for (AiscRoomBean bean:roomBeen) {
bean.setStsToOld();
bean.setLocId(realBean.getLocId());
commonSV.save(bean);
}
//检查大类与科室关联中科室ID转义
AiscOrdCat2LocBean[] ordCat2LocBeen = commonSV.getBeans(" LOC_ID = "+realBean.getOldLocId()+" and ORG_ID = "+orgId,null,AiscOrdCat2LocBean.class);
for (AiscOrdCat2LocBean bean:ordCat2LocBeen) {
bean.setStsToOld();
bean.setLocId(realBean.getLocId());
commonSV.save(bean);
}
//医护人员维护中科室ID转义
AiscCareProvBean[] careProvBeen = commonSV.getBeans(" LOC_ID = "+realBean.getOldLocId()+" and ORG_ID = "+orgId,null,AiscCareProvBean.class);
for (AiscCareProvBean bean:careProvBeen) {
bean.setStsToOld();
bean.setLocId(realBean.getLocId());
commonSV.save(bean);
}
//操作员与登录科室登录中科室ID转义
AiscLoginLocBean[] loginLocBeen = commonSV.getBeans(" LOC_ID = "+realBean.getOldLocId()+" and ORG_ID = "+orgId,null,AiscLoginLocBean.class);
for (AiscLoginLocBean bean:loginLocBeen) {
bean.setStsToOld();
bean.setLocId(realBean.getLocId());
commonSV.save(bean);
}
}
//---------服务器关系表-----------------
AiscSeverinfoRealBean[] severinfoRealBeen = commonSV.getBeans(" ORG_ID = "+orgId,null,AiscSeverinfoRealBean.class);
for (AiscSeverinfoRealBean realBean :severinfoRealBeen){
//科室表中服务器ID转义
AiscLocBean[] loginLocBeen = commonSV.getBeans(" SERVER_ID = "+realBean.getOldServerId(),null,AiscLocBean.class);
for (AiscLocBean bean:loginLocBeen) {
bean.setStsToOld();
bean.setServerId(realBean.getServerId());
commonSV.save(bean);
}
}
//---------房间关系表-----------------
AiscRoomRealBean[] roomRealBeen = commonSV.getBeans(" ORG_ID = "+orgId,null,AiscRoomRealBean.class);
for (AiscRoomRealBean realBean :roomRealBeen){
//设备信息中房间转义
AiscEquipmentBean[] equipmentBeen = commonSV.getBeans(" ROOM_ID = "+realBean.getOldRoomId()+" and ORG_ID = "+orgId,null,AiscEquipmentBean.class);
for (AiscEquipmentBean bean:equipmentBeen) {
bean.setStsToOld();
bean.setRoomId(realBean.getRoomId());
commonSV.save(bean);
}
}
//---------检查项目关系表-----------------
AiscItemmastRealBean[] itemMastBeen = commonSV.getBeans(" ORG_ID = "+orgId,null,AiscItemmastRealBean.class);
for (AiscItemmastRealBean realBean :itemMastBeen){
//检查项目与部位关系中itemmast_id转义
AiscBodyPart2ItemBean[] bodypart2itemBeen = commonSV.getBeans(" ITEMMAST_ID = "+realBean.getOldItemmastId()+" and ORG_ID = "+orgId,null,AiscBodyPart2ItemBean.class);
for (AiscBodyPart2ItemBean bean:bodypart2itemBeen) {
bean.setStsToOld();
bean.setItemmastId(realBean.getItemmastId());
commonSV.save(bean);
}
}
//---------检查部位关系表-----------------
AiscBodypartRealBean[] bodyPartBeen = commonSV.getBeans(" ORG_ID = "+orgId,null,AiscBodypartRealBean.class);
for (AiscBodypartRealBean realBean :bodyPartBeen){
//检查项目与部位关系中bodypart_code转义
AiscBodyPart2ItemBean[] loginLocBeen = commonSV.getBeans(" BODYPART_CODE = "+realBean.getOldBodypartCode()+" and ORG_ID = "+orgId,null,AiscBodyPart2ItemBean.class);
for (AiscBodyPart2ItemBean bean:loginLocBeen) {
bean.setStsToOld();
bean.setBodypartCode(String.valueOf(realBean.getBodypartCode()));
commonSV.save(bean);
}
}
//---------检查大类关系表-----------------
AiscOrdcategoryRealBean[] ordcategoryRealBeen = commonSV.getBeans(" ORG_ID = "+orgId,null,AiscOrdcategoryRealBean.class);
for (AiscOrdcategoryRealBean realBean :ordcategoryRealBeen){
//检查大类与科室关联中检查大类转义
AiscOrdCat2LocBean[] ordCat2LocBeen = commonSV.getBeans(" ORDCAT_ID = "+realBean.getOldOrdcategoryId(),null,AiscOrdCat2LocBean.class);
for (AiscOrdCat2LocBean bean:ordCat2LocBeen) {
bean.setStsToOld();
bean.setOrdcatId(realBean.getOrdcategoryId());
commonSV.save(bean);
}
//检查子类中检查大类转义
AiscOrdSubCategoryBean[] ordSubCategoryBeen = commonSV.getBeans(" ORDCATEGORY_ID = "+realBean.getOldOrdcategoryId(),null,AiscOrdSubCategoryBean.class);
for (AiscOrdSubCategoryBean bean:ordSubCategoryBeen) {
bean.setStsToOld();
bean.setOrdcategoryId(realBean.getOrdcategoryId());
commonSV.save(bean);
}
//检查项目中检查大类转义
AiscItemMastBean[] itemmstBeen = commonSV.getBeans(" ORDCATEGORY_ID = "+realBean.getOldOrdcategoryId()+" and ORG_ID = "+orgId,null,AiscItemMastBean.class);
for (AiscItemMastBean bean:itemmstBeen) {
bean.setStsToOld();
bean.setOrdcategoryId(realBean.getOrdcategoryId());
commonSV.save(bean);
}
}
//---------检查子类关系表-----------------
AiscOrdsubcategoryRealBean[] ordsubcateRealBeen = commonSV.getBeans(" ORG_ID = "+orgId,null,AiscOrdsubcategoryRealBean.class);
for (AiscOrdsubcategoryRealBean realBean :ordsubcateRealBeen){
//设备中检查子类转义
AiscEquipmentBean[] equipBeen = commonSV.getBeans(" ordsubcategory_id = "+realBean.getOldSubcateId(),null,AiscEquipmentBean.class);
for(AiscEquipmentBean bean:equipBeen){
bean.setStsToOld();
bean.setOrdsubcategoryId(realBean.getSubcateId());
commonSV.save(bean);
}
}
//---------医护人员关系表-----------------
AiscCareprovRealBean[] careprovRealBeen = commonSV.getBeans(" ORG_ID = "+orgId,null,AiscCareprovRealBean.class);
for (AiscCareprovRealBean realBean :careprovRealBeen){
//操作员与医护人员关联中医护人员ID转义
AiscUser2CareProvBean[] user2CareProvBeen = commonSV.getBeans(" CAREPROV_ID = "+realBean.getOldCareprovId(),null,AiscUser2CareProvBean.class);
for (AiscUser2CareProvBean bean:user2CareProvBeen) {
bean.setStsToOld();
bean.setCareprovId(realBean.getCareprovId());
commonSV.save(bean);
}
}
} catch (Exception e) {
e.printStackTrace();
return flag ;
}
return flag ;
}
/**
* 写入接口日志表
* @param bean
* @return
* @throws Exception
*/
public void writeServiceLog(AisServiceLogBean bean) throws Exception{
long id =ServiceUtil.getSequence("SEQ_AIS_SERVICE_LOG");
bean.setServiceId(id);
AisServiceLogEngine.save(bean);
}
public String upPatientInfo(AisPatientInfoData patient,String orgId) throws Exception{
AisPatientInfoBean[] patientBean = null;
if(isNotBlank(patient.getPatientIdnumber())){
patientBean = getAisPatientBean(patient.getPatientIdnumber());
}
//查询ais_pixinfo表中是否有记录
AisPixInfoBean[] pixBean = getAisPixInfoBean(patient.getPatientId(),orgId);
//该情况只有人为修改数据的时候才会出现
if(pixBean!=null&&patientBean==null){
//pixBean 更新
return String.valueOf(pixBean[0].getPatientGlobalid());
//patient 插入
}else if(pixBean==null&&patientBean==null){
//patient 插入&pixBean 插入
return insertPatientBean(orgId,patient);
}else if(pixBean==null&&patientBean!=null){
//查询pacs已有病人信息
if(patientBean!=null&&patientBean.length>0){
//插入pixBean
if(isFlag(patientBean[0].getPatientGlobalid(),orgId)){
insertPixBean(patientBean[0].getPatientGlobalid(),orgId,patient);
}
//更新中心pacs已有病人信息
updatePatient(patientBean[0].getPatientGlobalid(),patient);
return String.valueOf(patientBean[0].getPatientGlobalid());
}
}else{
//若pix和中心patient都有信息,则只更新病人信息
if(pixBean!=null&&pixBean.length>0){
//更新中心pacs已有病人信息
updatePatient(pixBean[0].getPatientGlobalid(),patient);
return String.valueOf(pixBean[0].getPatientGlobalid());
}
}
return "";
}
public String upStudyInfo(AisStudyInfoBean bean,String orgId) throws Exception{
long studyinfoId= Long.parseLong(orgId+bean.getStudyinfoId());
AisStudyinfoRealBean oldBean = getStudyinfoRealBean(studyinfoId,bean.getOrgId());
if(oldBean==null){
long id = Long.parseLong(orgId+commonSV.getSequence("SEQSTUDYINFOID"));
AisStudyinfoRealBean realBean =new AisStudyinfoRealBean();
realBean.setStudyinfoRealId(commonSV.getSequence("SEQSTUDYTEMPID"));
realBean.setOldStudyinfoId(studyinfoId);
realBean.setOrgId(String.valueOf(bean.getOrgId()));
bean.setStudyinfoId(id);
realBean.setStudyinfoId(id);
//转义
translateStudyinfo(bean);
//插入关系表及的登记记录
commonSV.save(bean);
commonSV.save(realBean);
return String.valueOf(id);
}else{
//修改登记信息
AisStudyInfoBean oldstudyInfoBean = new AisStudyInfoBean();
oldstudyInfoBean.setStudyinfoId(oldBean.getStudyinfoId());
oldstudyInfoBean.setStsToOld();
bean.setStudyinfoId(oldBean.getStudyinfoId());
DataContainerFactory.copyNoClearData(bean, oldstudyInfoBean);
translateStudyinfo(oldstudyInfoBean);
AisStudyInfoEngine.save(oldstudyInfoBean);
return String.valueOf(oldstudyInfoBean.getStudyinfoId());
}
}
public void upStudyItemInfo(AisStudyItemInfoBean bean,String orgId) throws Exception{
AisStudyItemInfoBean studyitemBeen = new AisStudyItemInfoBean();
AisStudyinfoRealBean oldBean = getStudyinfoRealBean(Long.parseLong(orgId+bean.getStudyinfoId()),orgId);
//studyinfoId转义
if(oldBean!=null){
deleteStudyIteminfo(oldBean.getStudyinfoId(),orgId);
studyitemBeen.setStudyinfoId(oldBean.getStudyinfoId());
}
//检查项目code转义
AiscItemmastRealBean studyitem = getStudyItemRealBean(Long.parseLong(bean.getStudyitemCode()),orgId);
if(studyitem!=null){
studyitemBeen.setStudyitemCode(String.valueOf(studyitem.getItemmastId()));
}
studyitemBeen.setStudyitemId(commonSV.getSequence("SEQSTUDYITEMID"));
studyitemBeen.setStudyitemHisid(bean.getStudyitemHisid());
studyitemBeen.setStudyitemCode(bean.getStudyitemCode());
studyitemBeen.setStudyitemDesc(bean.getStudyitemDesc());
studyitemBeen.setStudyitemEndesc(bean.getStudyitemEndesc());
studyitemBeen.setStudyitemBodyinfo(bean.getStudyitemBodyinfo());
studyitemBeen.setStudyitemPrice(bean.getStudyitemPrice());
studyitemBeen.setStudyitemNumber(Integer.parseInt(String.valueOf(bean.getStudyitemNumber())));
studyitemBeen.setStudyitemStatus(bean.getStudyitemStatus());
studyitemBeen.setStudyitemItemno(bean.getStudyitemItemno());
if(bean.getStudyitemBodypart()!=null&&!"".equals(bean.getStudyitemBodypart())){
String arr[] = bean.getStudyitemBodypart().split(",");
String parts = "";
boolean task = false;
for(int i=0;i<arr.length;i++){
AiscBodypartRealBean partBean = getBodypartRealBean(Long.parseLong(arr[i]),orgId);
if(partBean!=null){
parts+=partBean.getBodypartCode()+",";
}else{
parts = bean.getStudyitemBodypart();
task = true;
}
}
if(task){
studyitemBeen.setStudyitemBodypart(parts);
}else{
studyitemBeen.setStudyitemBodypart(parts.substring(0,parts.length()-1));
}
}
commonSV.save(studyitemBeen);
}
public AiscLocBean getHzLocInfo(AiscLocBean bean) throws Exception{
StringBuffer condition = new StringBuffer();
condition.append(" 1=1");
condition.append(" and loc_code='"+bean.getLocCode()+"'");
condition.append(" and org_id = '"+bean.getOrgId()+"' ");
condition.append(" and loc_type = 'C' ");
AiscLocBean[] oldBean = AiscLocEngine.getBeans(condition.toString(), null);
if(oldBean!=null&&oldBean.length>0){
return oldBean[0];
}else{
return null;
}
}
public String upHzloc(String studyinfoId,String orgId,String conlocId,String conorgId,String locId,AiscLocBean aiscloc) throws Exception{
AiscLocBean oldBean = getHzLocInfo(aiscloc);
long newlocId = commonSV.getSequence("SEQLOCID");
if(oldBean==null){
//插入新会诊科室及关系对应
AiscLocRealBean realBean = new AiscLocRealBean();
realBean.setLocRealId(commonSV.getSequence("SEQ_AISC_LOC_REAL"));
realBean.setOrgId(aiscloc.getOrgId());
realBean.setOldLocId(aiscloc.getLocId());
aiscloc.setLocId(newlocId);
long serverId = getServerId(aiscloc.getServerId());
aiscloc.setServerId(serverId);
realBean.setLocId(aiscloc.getLocId());
commonSV.save(aiscloc);
commonSV.save(realBean);
}else{
AiscLocRealBean qryBean = commonSV.getBean(" OLD_LOC_ID = "+conlocId+" and org_id='"+oldBean.getOrgId()+"'",null,AiscLocRealBean.class);
if (qryBean==null){
AiscLocRealBean realBean = new AiscLocRealBean();
realBean.setLocRealId(commonSV.getSequence("SEQ_AISC_LOC_REAL"));
realBean.setOrgId(oldBean.getOrgId());
realBean.setOldLocId(Long.parseLong(conlocId));
realBean.setLocId(oldBean.getLocId());
commonSV.save(realBean);
}
}
//查询中心申请科室ID
AiscLocRealBean sqBean = commonSV.getBean(" OLD_LOC_ID = "+locId+" and org_id='"+orgId+"'",null,AiscLocRealBean.class);
//查询中心会诊科室ID
AiscLocRealBean hzBean = commonSV.getBean(" OLD_LOC_ID = "+conlocId+" and org_id='"+conorgId+"'",null,AiscLocRealBean.class);
AiscConorganizationBean conorgBean = commonSV.getBean(" conloc_id='"+hzBean.getLocId()+"' and org_id='"+sqBean.getOrgId()+"' and loc_id="+sqBean.getLocId()+" and conorg_id='"+hzBean.getOrgId()+"'",null,AiscConorganizationBean.class);
if(conorgBean==null){
//插入登录科室与会诊科室关联
AiscConorganizationBean newconorg = new AiscConorganizationBean();
newconorg.setConorganizatId(ServiceUtil.getSequence("SEQ_Conorganization"));
newconorg.setConlocId(String.valueOf(hzBean.getLocId()));
newconorg.setConorgId(hzBean.getOrgId());
newconorg.setOrgId(sqBean.getOrgId());
newconorg.setLocId(sqBean.getLocId());
commonSV.save(newconorg);
updateConLoc(studyinfoId,hzBean.getLocId());
}else{
updateConLoc(studyinfoId,Long.parseLong(conorgBean.getConlocId()));
}
return "0";
}
public void updateConLoc(String studyinfoId,long locId) throws Exception{
AisStudyInfoBean bean = AisStudyInfoEngine.getBean(Long.parseLong(studyinfoId));
bean.setStsToOld();
bean.setStudyConsultloc(locId);
bean.setStudystatusCode("APPConsult");
AisStudyInfoEngine.save(bean);
}
public String saveFilePDFUrl(AisFilesInfoModel filemodel) throws Exception{
AisFilesInfoBean fileBean = new AisFilesInfoBean();
long fileId = ServiceUtil.getSequence("SEQFILEID");
fileBean.setFileId(fileId);
fileBean.setStudyinfoId(filemodel.getStudyinfoId());
fileBean.setFileType(filemodel.getFileType());
fileBean.setFilePath(filemodel.getFilePath());
fileBean.setMiId(-1);
AisFilesInfoEngine.save(fileBean);
return "0";
}
public boolean isFlag(long id,String orgId) throws Exception{
StringBuffer condition = new StringBuffer();
condition.append(" ORG_ID = '" + orgId+"' and patient_globalid="+id );
AisPixInfoBean[] pixBean = AisPixInfoEngine.getBeans(condition.toString(), null);
if(pixBean!=null&&pixBean.length > 0){
return true;
}else{
return false;
}
}
public AisStudyInfoBean getStudyInfoByAccnumber(String studyAccnumber) throws Exception {
StringBuffer condition = new StringBuffer();
condition.append(" 1=1");
if (isNotBlank(studyAccnumber)) {
condition.append(" AND study_accnumber = '" + studyAccnumber + "'");
}
AisStudyInfoBean[] studyBean = AisStudyInfoEngine.getBeans(condition.toString(), null);
if (studyBean.length > 0) {
return studyBean[0];
} else {
return null;
}
}
public Map reportBack(String hzOrgId,String studyAccnumber,String hzReportExam,String hzReportResult,String ipport,String reportDoc,String verifyDoc,String studyTime) throws Exception{
Statement stmt = null;
ResultSet rs = null;
Map result = new HashMap();
String code = "0";
String message = "回传报告成功";
Timestamp dateTime = new Timestamp(new Date().getTime());
AisStudyInfoBean sbean = getStudyInfoByAccnumber(studyAccnumber);
sbean.setStudystatusCode("Consulted");
sbean.setStudyHavereport(1);
AisStudyInfoEngine.save(sbean);
AisStudyReportBean reportBean = getOldReport(sbean.getStudyinfoId());
if(reportBean ==null){
reportBean = new AisStudyReportBean();
long newReportId = ServiceUtil.getSequence("SEQREPORTID");
reportBean.setReportId(newReportId);
reportBean.setReportDatetime(dateTime);
reportBean.setReportVerifydatetime(dateTime);
reportBean.setStudyinfoId(sbean.getStudyinfoId());
// reportBean.setReportDoctorid(user.getCareProvId());
// reportBean.setReportRecord(user.getCareProvId());
reportBean.setReportExam(hzReportExam);
reportBean.setReportResult(hzReportExam);
reportBean.setReportIsprinted(0);//未打印
reportBean.setReportIscompleted(1);
AisStudyReportEngine.save(reportBean);
}else{
reportBean.setStsToOld();
reportBean.setReportExam(hzReportExam);
reportBean.setReportResult(hzReportExam);
AisStudyReportEngine.save(reportBean);
}
//3.生成html文件上传服务器
//3.1首先取到设备类型ID
String template = "";
//按设备大类查模板现在不用
AiscEquipmentBean eBean = AiscEquipmentEngine.getBean(sbean.getEquipmentId());
//3.2查html模板 //模板应该取当前登录所用的组织机构及科室标识查,还是直接用检查单中的组织机构和科室查
try{
stmt = ServiceManager.getSession().getConnection().createStatement();
String sql = " SELECT A.REPORT_FORMAT, B.ORG_ID, B.LOC_ID, B.MODALITY_ID "
+ " FROM AISC_REPORTFORMAT A, AISC_REPORTFORMAT2LOC B "
+ " WHERE A.FORMAT_ID = B.FORMAT_ID ";
sql += " AND ORG_ID = " + sbean.getOrgId() + " ";
sql += " AND LOC_ID = " + sbean.getLocId()+""
+ " AND B.MODEL_TYPE = 3 ";
rs = stmt.executeQuery(sql);
if (rs.next()) {
Clob reportFormat = rs.getClob("REPORT_FORMAT");
if (reportFormat != null) {
template = reportFormat.getSubString(1, (int) reportFormat.length());
}
}
if ("".equals(template)) {
code = "-1";
message = "回传报告失败:打印模板文件不存在,请确认!";
throw new Exception("上传报告失败:打印模板文件不存在,请确认!");
}
}catch (Exception e) {
// TODO: handle exception
}
finally {
DBUtil.release(rs, stmt, null);
ServiceManager.getSession().getConnection().close();
}
//3.3组装html文件
//3.3.1获取填充数据
Map map = getTemplateFilling(String.valueOf(reportBean.getStudyinfoId()));
//剔除strike中的记录 留痕处理 -- 正则表达式
String reportExam = String.valueOf(map.get("REPORT_EXAM"));
String reportResult = String.valueOf(map.get("REPORT_RESULT"));
Pattern p = Pattern.compile("<strike>.*</strike>");
Matcher m1 = p.matcher(reportExam);
Matcher m2 = p.matcher(reportResult);
//去除删除标签
String newReportExam = m1.replaceAll("");
String newReportResult = m2.replaceAll("");
//图片内容填充
// String patientImg = "";
// if (!"".equals(imgAddrArray)) {
// String[] imgArray = imgAddrArray.split("\\|");
// String html = "<tr>";
// for (int i = 0; i < imgArray.length; i++) {
// html += "<td align='center' height='1' valign='bottom' width='33%'><img border='0' height='172' src='" + imgArray[i] + "' width='230' /><p align='center'> </p></td>";
// if (i != 0 && (i + 1) % 2 == 0) {
// html += "</tr><tr>";
// }
// }
// html += "</tr>";
// patientImg = html;
// } else {
// patientImg = "无";
// }
String id = "";
String cardId = "";
String cardNo = "";
if ("INP".equals(String.valueOf(map.get("PATIENTTYPE_CODE")))) {
id = "住院号";
} else if ("HP".equals(String.valueOf(map.get("PATIENTTYPE_CODE")))) {
id = "体检号";
cardId = "身份证号:";
cardNo = String.valueOf(map.get("PATIENT_IDNUMBER"));
} else if ("OP".equals(String.valueOf(map.get("PATIENTTYPE_CODE")))) {
id = "门诊号";
} else {
id = "住院号";
}
//内容填充
String studyReprotMsg = template.replaceAll("#ORG_NAME#", String.valueOf(map.get("ORG_NAME")))
.replaceAll("#ORG_NAME#", String.valueOf(map.get("ORG_NAME")))
.replaceAll("#TEMP#", "")
.replaceAll("#姓名#", String.valueOf(map.get("PATIENT_NAME")))
.replaceAll("#性别#", String.valueOf(map.get("PATIENT_SEX")))
.replaceAll("#年龄#", String.valueOf(map.get("PATIENT_AGE")))
.replaceAll("#检查号#", String.valueOf(map.get("STUDY_ACCNUMBER")))
.replaceAll("#仪器型号#", String.valueOf(map.get("EQUIPMENT_ID")))
.replaceAll("#来源#", String.valueOf(map.get("PATIENTTYPE")))
.replaceAll("#PATIENT_TYPEID#", id)
.replaceAll("#AUDITORFINAL_DOC#", "审核医师")
.replaceAll("#住院号#", String.valueOf(map.get("PATIENT_INPATIENTID")))
.replaceAll("#检查项目#", String.valueOf(map.get("STUDY_ITEMDESC")))
.replaceAll("#检查部位#", String.valueOf(map.get("STUDYITEM_BODYINFO")))
// .replaceAll("#图像#", String.valueOf(patientImg))
.replaceAll("#审核日期#", String.valueOf(map.get("REPORT_VERIFYDATETIME")))
.replaceAll("#终审医生#", String.valueOf(map.get("REPORT_FINALDOCTORNAME")))
.replaceAll("#终审核期#", String.valueOf(map.get("REPORT_FINALDATETIME")))
.replaceAll("#报告医生#", URLDecoder.decode(reportDoc, "UTF-8"))
.replaceAll("#报告时间#", String.valueOf(map.get("REPORT_DATETIME")))
.replaceAll("#报告日期#", String.valueOf(map.get("REPORT_DATE")))
.replaceAll("#患者ID#", String.valueOf(map.get("PATIENT_ID")))
.replaceAll("#申请科室#", String.valueOf(map.get("STUDY_APPLOCNAME")))
.replaceAll("#检查日期#", studyTime)
.replaceAll("#门诊号#", String.valueOf(map.get("PATIENT_OUTPATIENTID")))
.replaceAll("#病区#", String.valueOf(map.get("STUDY_WARDNAME")))
.replaceAll("#床号#", String.valueOf(map.get("STUDY_BEDNO")))
.replaceAll("#房间#", String.valueOf(map.get("ROOM_ID")))
.replaceAll("#CARD_ID#", cardId)
.replaceAll("#身份证号#", cardNo)
.replaceAll("#检查所见#", newReportExam)
.replaceAll("#诊断意见#", newReportResult);
studyReprotMsg = studyReprotMsg.replaceAll("#审核医生#", URLDecoder.decode(verifyDoc, "UTF-8"));
//3.3.2生成文件上传服务器-保存文件表路径
String fileAddr = "";
long miId = 0l;
// 生成html文件
String htmlHead = "<html><meta http-equiv='Content-Type' content='text/html; charset=utf-8' />";
String htmlFoot = "</html>";
String script = "<link type='text/css' rel='stylesheet' href='"+ipport+"/aris/statics/pages/css/index/css/print.css'/><script type='text/javascript' src='"+ipport+"/aris/statics/common/js/jquery-1.11.2.js'></script><script type='text/javascript' language='javascript'>"
+ " function logout(){ "
+ " var browserName=navigator.appName; "
+ " if (browserName=='Netscape'){ "
+ " window.open('', '_self', ''); "
+ " window.close(); "
+ " } "
+ " if (browserName=='Microsoft Internet Explorer') { "
+ " window.parent.opener = 'whocares'; "
+ " window.close(); "
+ " } "
+ "} "
+ " function goBack(){ "
+ " window.location.href = '"+ipport+"/workList/init.html'; "
+ "if(!$('#menuTree',parent.document).is(':hidden')){ "
+ " parent.switchBarl(); "
+ " } "
+ " } "
+ "function print(){ "
+ " window.opener.document.getElementById('workbtnback').click();"
+ "WebBrowser.ExecWB(6, 6); "
//记录打印次数及打印状态
+ "$.ajax({ "
+ " type: 'POST', "
+ " async: true, "
+ " url: '"+ipport+"/studyReport/setReportPrintInfo.ajax?reportId=" + reportBean.getReportId() + "',"
+ " success: function (data) {setTimeout(function(){WebBrowser.execwb(45,1);},5000); "
+ " "
+ " }"
+ " });"
+ " } "
+ " </script><style media=print>.page-content{display:none;}</style><OBJECT classid='CLSID:8856F961-340A-11D0-A96B-00C04FD705A2' height='0' id='WebBrowser' width='0'></OBJECT><div class='page-content' style='text-align:right'> "
+ "<button type='button' class='btn btn-primary' onclick='print()'>打 印</button><button type='button' class='btn btn-pink' onclick='logout()'>关 闭</button></div>";
String footBtn = "<div class='page-content' style='text-align:right'><button type='button' class='btn btn-primary' onclick='print()'>打 印</button><button type='button' class='btn btn-pink' onclick='logout()'>关 闭</button></div>";
studyReprotMsg = htmlHead + script + studyReprotMsg + footBtn + htmlFoot;
if (studyReprotMsg != null && !"".equals(studyReprotMsg)) {
Timestamp t = SysdateManager.getSysTimestamp();
String date = DateUtils.getDateyyyymm(t);
String day = getDateday(t);
String time = DateUtils.getDateddmmmiss(t);
//按设备类型标识分目录存放
String mtype = eBean.getModalityId() + "";
// 生成一个随机数
Random rand = new Random();
String part2 = "";
for (int i = 0; i < 3; i++) {
part2 += rand.nextInt(10);
}
//文件存放服务器及路径处理
//1. 保存在哪个服务器,哪个介质下,根据科室取存储服务器IP及介质信息
QryServerMediumBean serverMedium = new QryServerMediumBean();
QryServerMediumBean[] serverMediums= null;
serverMediums = getServerMedium(String.valueOf(sbean.getLocId()));
if (serverMediums.length > 0) {
for (QryServerMediumBean bean : serverMediums) {
if (bean.getMediumIsfull() == 0 || bean.getMediumIsonline() == 1) {
serverMedium = bean;
break;
}
}
} else {
code = "-2";
message = "回传报告失败:存储介质异常!";
}
if ("".equals(serverMedium.getServerIp()) || "".equals(serverMedium.getMediumPath())) {
code = "-2";
message = "回传报告失败:存储介质异常!";
}
//介质标识
miId = serverMedium.getMediumId();
//组织文件名
String fileName = date + "_" + time + "_" + part2;
//将本地文件写至fileServer服务器
String reportUpPath = AIConfigManager.getConfigItem("ReportUpPath");
File targetFile = new File(reportUpPath + fileName + ".html");
if (!copy(studyReprotMsg, targetFile, reportUpPath)) {
throw new Exception("上传报告失败:存储介质异常,写HTML文件失败!!");
}
fileAddr = fileName + ".html";
//记录文件地址到库表中 ----删除临时报告文件记录
AisReportFilesBean[] fileBeans = getfileBeans(reportBean.getReportId(), "0");
if (fileBeans != null && fileBeans.length > 0) {
for (int i = 0; i < fileBeans.length; i++) {
AisReportFilesBean realBean = AisReportFilesEngine.getBean(fileBeans[i].getReportfileId());
realBean.setStsToOld();
realBean.delete();
AisReportFilesEngine.save(realBean);
AisFilesInfoBean oldFileBean = AisFilesInfoEngine.getBean(fileBeans[i].getFileId());
oldFileBean.setStsToOld();
oldFileBean.delete();
AisFilesInfoEngine.save(oldFileBean);
}
}
AisFilesInfoBean fileBean = new AisFilesInfoBean();
long fileId = ServiceUtil.getSequence("SEQFILEID");
fileBean.setFileId(fileId);
fileBean.setStudyinfoId(reportBean.getStudyinfoId());
fileBean.setFileType("html");
fileBean.setFilePath(fileAddr);
fileBean.setMiId(miId);
AisFilesInfoEngine.save(fileBean);
AisReportFilesBean reportFileBeqn = new AisReportFilesBean();
reportFileBeqn.setReportfileId(ServiceUtil.getSequence("SEQREPORTFILEID"));
reportFileBeqn.setFileId(fileId);
reportFileBeqn.setReportId(reportBean.getReportId());
reportFileBeqn.setStatus("0");
AisReportFilesEngine.save(reportFileBeqn);
}
result.put("code", code);
result.put("message", message);
return result;
}
public AisReportFilesBean[] getfileBeans(long reportId, String status) throws Exception {
StringBuffer condition = new StringBuffer();
condition.append(" 1=1");
if (reportId != 0) {
condition.append(" AND report_Id = " + reportId);
}
if (isNotBlank(status)) {
condition.append(" AND status = '" + status + "' ");
}
AisReportFilesBean[] reportFile = AisReportFilesEngine.getBeans(condition.toString(), null);
if (reportFile.length > 0) {
return reportFile;
} else {
return null;
}
}
//将模板内容copy到对应目录文件中
public static boolean copy(String src, File dest, String filePath) {
try {
FileOutputStream out = null;
try {
File fileDir = new File(filePath);
if (!fileDir.isDirectory()) {
//fileDir.mkdirs();
}
out = new FileOutputStream(dest);
out.write(src.getBytes());
} catch (FileNotFoundException e) {
e.printStackTrace();
return false;
} catch (IOException e) {
e.printStackTrace();
return false;
} finally {
if (out != null) {
out.close();
}
}
return true;
} catch (Exception e) {
return false;
}
}
public Map getTemplateFilling(String studyinfoId) throws Exception {
Map map = new HashMap();
Statement stmt = null;
ResultSet rs = null;
try {
stmt = ServiceManager.getSession().getConnection().createStatement();
String sql = " SELECT B.STUDYINFO_ID, "
+ " B.ORG_ID, "
+ " B.LOC_ID, "
+ " A.patient_idnumber, "
+ " (SELECT SO.ORG_NAME FROM SYS_ORG SO WHERE SO.ORG_ID = B.ORG_ID) AS ORG_NAME, "
+ " B.STUDY_ACCNUMBER, "
+ " B.PATIENT_GLOBALID, "
+ " A.PATIENT_NAME, "
+ " DECODE(A.PATIENT_SEX, '1', '男', '2', '女', '未知') PATIENT_SEX, "
+ " B.PATIENT_AGE, "
+ " B.STUDY_WARD, "
+ " B.STUDY_BEDNO, "
+ " B.STUDY_ITEMDESC STUDY_ITEMDESC, "
+ " (SELECT WM_CONCAT(C.STUDYITEM_BODYINFO) "
+ " FROM AIS_STUDYITEMINFO C "
+ " WHERE B.STUDYINFO_ID = C.STUDYINFO_ID) STUDYITEM_BODYINFO, "
+ " B.STUDY_REMARK, "
+ " B.STUDY_CLINIC, "
+ " B.PATIENT_INPATIENTID, "
+ " B.STUDY_DOCTORID, "
+ " B.AID_DOCTORID, "
+ " B.STUDY_EXPOSURECOUNT, "
+ " B.STUDY_FILMCOUNT, "
+ " B.STUDY_HAVEREPORT, "
+ " B.STUDY_HAVEIMAGE, "
+ " TO_CHAR(B.STUDY_STARTTIME, 'YYYY-MM-DD hh24:mi:ss') STUDY_TIME, "
+ " (SELECT CAREPROV_NAME FROM AISC_CAREPROV AC WHERE AC.CAREPROV_ID = B.STUDY_DOCTORID) STUDY_DOCTORNAME, "
+ " B.EQUIPMENT_ID, "
+ " (SELECT SD.ITEM_NAME FROM SYS_DICTITEM SD WHERE SD.ITEM_NO = B.PATIENTTYPE_CODE AND DICT_NAME='PATIENT_TYPE') PATIENTTYPE, "
+ " B.PATIENTTYPE_CODE, "
+ " C.REPORT_EXAM, "
+ " C.REPORT_RESULT, "
+ " (SELECT CAREPROV_NAME FROM AISC_CAREPROV AC WHERE AC.CAREPROV_ID = C.REPORT_DOCTORID) REPORT_DOCTORNAME, "
+ " TO_CHAR(C.REPORT_DATETIME, 'YYYY-MM-DD hh24:mi:ss') REPORT_DATETIME, "
+ " TO_CHAR(C.REPORT_DATETIME, 'YYYY-MM-DD hh24:mi:ss') REPORT_DATE, "
+ " B.STUDY_ITEMDESC, "
+ " (SELECT CAREPROV_NAME FROM AISC_CAREPROV AC WHERE AC.CAREPROV_ID = C.REPORT_VERIFYDOCTORID) REPORT_VERIFYDOCTORNAME, "
+ " TO_CHAR(C.REPORT_VERIFYDATETIME, 'YYYY-MM-DD') REPORT_VERIFYDATETIME, "
+ " (SELECT CAREPROV_NAME FROM AISC_CAREPROV AC WHERE AC.CAREPROV_ID = C.REPORT_FINALDOCTORID) REPORT_FINALDOCTORNAME, "
+ " TO_CHAR(C.REPORT_FINALDATETIME, 'YYYY-MM-DD') REPORT_FINALDATETIME, "
+ " A.PATIENT_ID , "
+ " (SELECT AL.LOC_DESC FROM AISC_LOC AL WHERE AL.LOC_ID = B.STUDY_APPLOCID AND AL.ORG_ID = B.ORG_ID AND LOC_TYPE='A') STUDY_APPLOCNAME , "
+ " (SELECT AL.LOC_DESC FROM AISC_LOC AL WHERE AL.LOC_ID = B.STUDY_WARD AND AL.ORG_ID = B.ORG_ID AND LOC_TYPE='B') STUDY_WARDNAME , "
+ " B.PATIENT_OUTPATIENTID , "
+ " B.STUDY_BEDNO , "
+ " B.ROOM_ID "
+ " FROM AIS_PATIENTINFO A, "
+ " AIS_STUDYINFO B, "
+ " AIS_STUDYREPORT C "
+ " WHERE A.PATIENT_GLOBALID = B.PATIENT_GLOBALID "
+ " AND B.STUDYINFO_ID = C.STUDYINFO_ID "
+ " AND B.STUDYINFO_ID = " + studyinfoId + " ";
rs = stmt.executeQuery(sql);
if (rs.next()) {
map.put("ORG_NAME", rs.getString("ORG_NAME") == null ? "" : rs.getString("ORG_NAME"));
map.put("PATIENT_NAME", rs.getString("PATIENT_NAME") == null ? "" : rs.getString("PATIENT_NAME"));
map.put("PATIENT_SEX", rs.getString("PATIENT_SEX") == null ? "" : rs.getString("PATIENT_SEX"));
map.put("PATIENT_AGE", rs.getString("PATIENT_AGE") == null ? "" : rs.getString("PATIENT_AGE"));
map.put("STUDY_ACCNUMBER", rs.getString("STUDY_ACCNUMBER") == null ? "" : rs.getString("STUDY_ACCNUMBER"));
map.put("EQUIPMENT_ID", rs.getString("EQUIPMENT_ID") == null ? "" : rs.getString("EQUIPMENT_ID"));
map.put("PATIENTTYPE", rs.getString("PATIENTTYPE") == null ? "" : rs.getString("PATIENTTYPE"));
map.put("PATIENT_INPATIENTID", rs.getString("PATIENT_INPATIENTID") == null ? "" : rs.getString("PATIENT_INPATIENTID"));
map.put("STUDYITEM_BODYINFO", rs.getString("STUDYITEM_BODYINFO") == null ? "" : rs.getString("STUDYITEM_BODYINFO"));
map.put("STUDY_TIME", rs.getString("STUDY_TIME") == null ? "" : rs.getString("STUDY_TIME"));
map.put("STUDY_DOCTORNAME", rs.getString("STUDY_DOCTORNAME") == null ? "" : rs.getString("STUDY_DOCTORNAME"));
map.put("REPORT_DOCTORNAME", rs.getString("REPORT_DOCTORNAME") == null ? "" : rs.getString("REPORT_DOCTORNAME"));
map.put("REPORT_DATETIME", rs.getString("REPORT_DATETIME") == null ? "" : rs.getString("REPORT_DATETIME"));
map.put("REPORT_DATE", rs.getString("REPORT_DATE") == null ? "" : rs.getString("REPORT_DATE"));
map.put("STUDY_ITEMDESC", rs.getString("STUDY_ITEMDESC") == null ? "" : rs.getString("STUDY_ITEMDESC"));
map.put("REPORT_VERIFYDOCTORNAME", rs.getString("REPORT_VERIFYDOCTORNAME") == null ? "" : rs.getString("REPORT_VERIFYDOCTORNAME"));
map.put("REPORT_VERIFYDATETIME", rs.getString("REPORT_VERIFYDATETIME") == null ? "" : rs.getString("REPORT_VERIFYDATETIME"));
map.put("REPORT_FINALDOCTORNAME", rs.getString("REPORT_FINALDOCTORNAME") == null ? "" : rs.getString("REPORT_FINALDOCTORNAME"));
map.put("REPORT_FINALDATETIME", rs.getString("REPORT_FINALDATETIME") == null ? "" : rs.getString("REPORT_FINALDATETIME"));
map.put("PATIENT_ID", rs.getString("PATIENT_ID") == null ? "" : rs.getString("PATIENT_ID"));
map.put("STUDY_APPLOCNAME", rs.getString("STUDY_APPLOCNAME") == null ? "" : rs.getString("STUDY_APPLOCNAME"));
map.put("PATIENTTYPE_CODE", rs.getString("PATIENTTYPE_CODE") == null ? "" : rs.getString("PATIENTTYPE_CODE"));
map.put("STUDY_WARDNAME", rs.getString("STUDY_WARDNAME") == null ? "" : rs.getString("STUDY_WARDNAME"));
map.put("PATIENT_OUTPATIENTID", rs.getString("PATIENT_OUTPATIENTID") == null ? "" : rs.getString("PATIENT_OUTPATIENTID"));
map.put("STUDY_BEDNO", rs.getString("STUDY_BEDNO") == null ? "" : rs.getString("STUDY_BEDNO"));
map.put("ROOM_ID", rs.getString("ROOM_ID") == null ? "" : rs.getString("ROOM_ID"));
map.put("PATIENT_IDNUMBER", rs.getString("PATIENT_IDNUMBER") == null ? "" : rs.getString("PATIENT_IDNUMBER"));
Clob exam = rs.getClob("REPORT_EXAM");//检查所见
Clob result = rs.getClob("REPORT_RESULT");//诊断结果
if (exam != null) {
map.put("REPORT_EXAM", exam.getSubString(1, (int) exam.length()) == null ? "" : exam.getSubString(1, (int) exam.length()));
}
if (result != null) {
map.put("REPORT_RESULT", result.getSubString(1, (int) result.length()) == null ? "" : result.getSubString(1, (int) result.length()));
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
DBUtil.release(rs, stmt, null);
ServiceManager.getSession().getConnection().close();
}
return map;
}
//根据科室标识,查询存储服务介质
public QryServerMediumBean[] getServerMedium(String locId) throws Exception {
StringBuffer condition = new StringBuffer();
condition.append(" 1=1");
if (isNotBlank(locId)) {
condition.append(" AND LOC_ID = " + locId);
}
condition.append(" AND SERVER_ENABLED = 1"); //状态有效
condition.append(" AND MEDIUM_ENABLED = 1"); //状态有效
condition.append(" ORDER BY MEDIUM_ID ASC");
QryServerMediumBean[] serverMediums = QryServerMediumEngine.getBeans(condition.toString(), null);
return serverMediums;
}
public static String getDateday(Timestamp t) {
String str = t.toString();
str = str.replace("-", "");
String date = str.substring(6, 8);
return date;
}
public AisStudyReportBean getOldReport(long studyinfoId) throws Exception {
StringBuffer condition = new StringBuffer();
condition.append(" 1=1");
if (studyinfoId!=0) {
condition.append(" AND studyinfo_id = " + studyinfoId);
}
AisStudyReportBean[] reportBean = AisStudyReportEngine.getBeans(condition.toString(), null);
if (reportBean!=null&&reportBean.length > 0) {
return reportBean[0];
} else {
return null;
}
}
}
| [
"[email protected]"
] | |
46c6359be0c0f9b167d5c8a3d2d4657349fabb35 | 5291f4b848fe0c4391616cec25806f9e015f23a6 | /src/todo/utils/DBUtils.java | 43e8f1e7bfb750e4d229a1ff7ba2868a1ff6b557 | [] | no_license | sudoy/todo_suzuki | 28b207beb39c7fb4640d780315eef1629a85c6dc | d4b6ad7acc48768e4ffa7a361a053c1a5aeb363c | refs/heads/master | 2020-06-10T11:11:27.178638 | 2019-07-09T05:34:56 | 2019-07-09T05:34:56 | 193,638,865 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,640 | java | package todo.utils;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
public class DBUtils {
//DB接続
public static Connection getConnection() throws NamingException, SQLException {
Context initContext = new InitialContext();
Context envContext = (Context)initContext.lookup("java:/comp/env");
DataSource ds = (DataSource)envContext.lookup("asms");
return ds.getConnection();
}
//DB閉じる
public static void close(Connection c,PreparedStatement p,ResultSet r){
try {
if(r != null){
r.close();
}
if(p != null){
p.close();
}
if(c != null){
c.close();
}
} catch (Exception e) {}
}
public static void close(Connection c,PreparedStatement p){
try {
if(p != null){
p.close();
}
if(c != null){
c.close();
}
} catch (Exception e) {}
}
public static void close(PreparedStatement p,ResultSet r){
try {
if(p != null){
p.close();
}
if(r != null){
r.close();
}
} catch (Exception e) {}
}
public static void colse(Connection c){
try{
if(c != null){ c.close(); }
}catch(Exception e) {}
}
public static void close(PreparedStatement... ps){
for(PreparedStatement p : ps) {
try{
if(p != null){ p.close(); }
}catch(Exception e) {}
}
}
public static void close(ResultSet r){
try{
if(r != null){ r.close(); }
}catch(Exception e) {}
}
}
| [
"鈴木@TSD-SUZUKI"
] | 鈴木@TSD-SUZUKI |
9208433b3d7110553c3ddee77e110d193b218051 | 79595075622ded0bf43023f716389f61d8e96e94 | /app/src/main/java/org/apache/http/impl/client/DefaultRedirectHandler.java | 5818bd1865daeb29d2dafedcb4b273281bbd912c | [] | no_license | dstmath/OppoR15 | 96f1f7bb4d9cfad47609316debc55095edcd6b56 | b9a4da845af251213d7b4c1b35db3e2415290c96 | refs/heads/master | 2020-03-24T16:52:14.198588 | 2019-05-27T02:24:53 | 2019-05-27T02:24:53 | 142,840,716 | 7 | 4 | null | null | null | null | UTF-8 | Java | false | false | 4,493 | java | package org.apache.http.impl.client;
import android.net.http.Headers;
import java.net.URI;
import java.net.URISyntaxException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.Header;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.ProtocolException;
import org.apache.http.client.CircularRedirectException;
import org.apache.http.client.RedirectHandler;
import org.apache.http.client.params.ClientPNames;
import org.apache.http.client.utils.URIUtils;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.ExecutionContext;
import org.apache.http.protocol.HttpContext;
@Deprecated
public class DefaultRedirectHandler implements RedirectHandler {
private static final String REDIRECT_LOCATIONS = "http.protocol.redirect-locations";
private final Log log = LogFactory.getLog(getClass());
public boolean isRedirectRequested(HttpResponse response, HttpContext context) {
if (response == null) {
throw new IllegalArgumentException("HTTP response may not be null");
}
switch (response.getStatusLine().getStatusCode()) {
case HttpStatus.SC_MOVED_PERMANENTLY /*301*/:
case HttpStatus.SC_MOVED_TEMPORARILY /*302*/:
case HttpStatus.SC_SEE_OTHER /*303*/:
case HttpStatus.SC_TEMPORARY_REDIRECT /*307*/:
return true;
default:
return false;
}
}
public URI getLocationURI(HttpResponse response, HttpContext context) throws ProtocolException {
if (response == null) {
throw new IllegalArgumentException("HTTP response may not be null");
}
Header locationHeader = response.getFirstHeader(Headers.LOCATION);
if (locationHeader == null) {
throw new ProtocolException("Received redirect response " + response.getStatusLine() + " but no location header");
}
String location = locationHeader.getValue();
if (this.log.isDebugEnabled()) {
this.log.debug("Redirect requested to location '" + location + "'");
}
try {
URI uri = new URI(location);
HttpParams params = response.getParams();
if (!uri.isAbsolute()) {
if (params.isParameterTrue(ClientPNames.REJECT_RELATIVE_REDIRECT)) {
throw new ProtocolException("Relative redirect location '" + uri + "' not allowed");
}
HttpHost target = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
if (target == null) {
throw new IllegalStateException("Target host not available in the HTTP context");
}
try {
uri = URIUtils.resolve(URIUtils.rewriteURI(new URI(((HttpRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST)).getRequestLine().getUri()), target, true), uri);
} catch (URISyntaxException ex) {
throw new ProtocolException(ex.getMessage(), ex);
}
}
if (params.isParameterFalse(ClientPNames.ALLOW_CIRCULAR_REDIRECTS)) {
URI redirectURI;
RedirectLocations redirectLocations = (RedirectLocations) context.getAttribute(REDIRECT_LOCATIONS);
if (redirectLocations == null) {
redirectLocations = new RedirectLocations();
context.setAttribute(REDIRECT_LOCATIONS, redirectLocations);
}
if (uri.getFragment() != null) {
try {
redirectURI = URIUtils.rewriteURI(uri, new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme()), true);
} catch (URISyntaxException ex2) {
throw new ProtocolException(ex2.getMessage(), ex2);
}
}
redirectURI = uri;
if (redirectLocations.contains(redirectURI)) {
throw new CircularRedirectException("Circular redirect to '" + redirectURI + "'");
}
redirectLocations.add(redirectURI);
}
return uri;
} catch (URISyntaxException ex22) {
throw new ProtocolException("Invalid redirect URI: " + location, ex22);
}
}
}
| [
"[email protected]"
] | |
0f581a6099a77221bcc3d52262b780ff518af9fc | f857e7ef3d3d4da42e9e683820fcc122ecb5d798 | /app/src/test/java/com/abdallah/weathery/ExampleUnitTest.java | f3a628ae0c5c0c1f268430ddf1b48d17c9b292ee | [] | no_license | Abd-Allah-muhammed-muhammed/Weathery | f21138c5942715f43a4fbbfca020190265b9ae4b | be1b579a2fde93e7de065864b42a6b5f96236962 | refs/heads/master | 2022-11-15T21:04:50.403731 | 2020-07-11T15:37:22 | 2020-07-11T15:37:22 | 278,223,919 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 383 | java | package com.abdallah.weathery;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect( ) {
assertEquals(4, 2 + 2);
}
} | [
"[email protected]"
] | |
44492187b46fba284ebf3d8cf4a75f9fb5886002 | f9f4b3244b60cf5107edafaaf1f225cbafc63cb4 | /Assignment_PM/src/com/bcj/corejava/operators/lab2/MoonWeight.java | 32913216b5d8eee3d78425865c60cdb620fea029 | [] | no_license | padmaja0922/corejava | eb10b18a4602edcb580a6618fd1569b2e4e1df6c | 5c428c170487132835afb46be35b7308b9a01d9e | refs/heads/master | 2021-07-16T22:18:28.484709 | 2017-10-23T15:47:44 | 2017-10-23T15:47:44 | 108,002,435 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 524 | java | package com.bcj.corejava.operators.lab2;
import java.util.Scanner;
/* calculating weight on moon */
public class MoonWeight {
public double weightOnMoon(double w) {
double p = w * 0.17;
w = w - p;
return w;
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter the weight on earth :");
double d = scan.nextDouble();
MoonWeight m = new MoonWeight();
d = m.weightOnMoon(d);
System.out.println("Weight on moon is : " + d);
scan.close();
}
}
| [
"[email protected]"
] | |
253106d3a5d28c3c7b47fe286c2344f1fd401a2e | c893e4f191f02e853732cc8ea82d820b98234b5e | /ShellAddScriptTool/src/com/tomagoyaky/apkeditor/utils/Charsets.java | 65ddebebfb9f40e1a67fb3d2fa23b0b25bceba9f | [] | no_license | tomagoyaky/tomagoyakyShell | 726e267fce82e56089c3b1011f1332852e3df80a | 6be018144fb943ae1ff86a8301ec2b047f7cff22 | refs/heads/master | 2021-01-10T02:39:04.223793 | 2016-03-12T09:54:49 | 2016-03-12T09:54:49 | 53,195,492 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,035 | java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.tomagoyaky.apkeditor.utils;
import java.nio.charset.Charset;
import java.util.Collections;
import java.util.SortedMap;
import java.util.TreeMap;
/**
* Charsets required of every implementation of the Java platform.
*
* From the Java documentation <a href="http://docs.oracle.com/javase/6/docs/api/java/nio/charset/Charset.html">
* Standard charsets</a>:
* <p>
* <cite>Every implementation of the Java platform is required to support the following character encodings. Consult
* the release documentation for your implementation to see if any other encodings are supported. Consult the release
* documentation for your implementation to see if any other encodings are supported. </cite>
* </p>
*
* <ul>
* <li><code>US-ASCII</code><br>
* Seven-bit ASCII, a.k.a. ISO646-US, a.k.a. the Basic Latin block of the Unicode character set.</li>
* <li><code>ISO-8859-1</code><br>
* ISO Latin Alphabet No. 1, a.k.a. ISO-LATIN-1.</li>
* <li><code>UTF-8</code><br>
* Eight-bit Unicode Transformation Format.</li>
* <li><code>UTF-16BE</code><br>
* Sixteen-bit Unicode Transformation Format, big-endian byte order.</li>
* <li><code>UTF-16LE</code><br>
* Sixteen-bit Unicode Transformation Format, little-endian byte order.</li>
* <li><code>UTF-16</code><br>
* Sixteen-bit Unicode Transformation Format, byte order specified by a mandatory initial byte-order mark (either order
* accepted on input, big-endian used on output.)</li>
* </ul>
*
* @see <a href="http://docs.oracle.com/javase/6/docs/api/java/nio/charset/Charset.html">Standard charsets</a>
* @since 2.3
* @version $Id$
*/
public class Charsets {
//
// This class should only contain Charset instances for required encodings. This guarantees that it will load
// correctly and without delay on all Java platforms.
//
/**
* Returns the given Charset or the default Charset if the given Charset is null.
*
* @param charset
* A charset or null.
* @return the given Charset or the default Charset if the given Charset is null
*/
public static Charset toCharset(final Charset charset) {
return charset == null ? Charset.defaultCharset() : charset;
}
/**
* Returns a Charset for the named charset. If the name is null, return the default Charset.
*
* @param charset
* The name of the requested charset, may be null.
* @return a Charset for the named charset
* @throws java.nio.charset.UnsupportedCharsetException
* If the named charset is unavailable
*/
public static Charset toCharset(final String charset) {
return charset == null ? Charset.defaultCharset() : Charset.forName(charset);
}
/**
* <p>
* Eight-bit Unicode Transformation Format.
* </p>
* <p>
* Every implementation of the Java platform is required to support this character encoding.
* </p>
*
* @see <a href="http://docs.oracle.com/javase/6/docs/api/java/nio/charset/Charset.html">Standard charsets</a>
* @deprecated Use Java 7's {@link java.nio.charset.StandardCharsets}
*/
@Deprecated
public static final Charset UTF_8 = Charset.forName("UTF-8");
} | [
"[email protected]"
] | |
fc08882c742365447769cb55976b71cc16ab490f | e2dc52555383dbf17b8a9f6f0a2f5280fed0298b | /fcgs/PidsCore/src/main/java/com/pids/core/creator/RandomDatasCreator.java | db89e02ff77472cd3a3a93a885927fc6a27b8d7e | [] | no_license | jiangbinboy/fcgs | 2f1e7d58f5a5923ca7003628ecd4a0c7b8b484cb | 6073f820553ac9af8cdc4d6e9a65475618a342d6 | refs/heads/master | 2022-11-17T00:17:22.836784 | 2020-07-10T03:26:11 | 2020-07-10T03:26:11 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,888 | java | package com.pids.core.creator;
/**
* 随机字符串创建器
* @author WUHAOTIAN
* @email [email protected]
* @date 2019年4月15日上午11:15:52
*/
public class RandomDatasCreator {
public static final char BIG[] = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R',
'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' };
public static final char SMALL[] = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'm', 'n', 'o', 'p', 'q',
'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
public static final char NUM[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
public static final char ALL[] = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R',
'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'm', 'n',
'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8',
'9' };
/**
* 获取指定长度字符串,包含大写、小写字母、数字
* @author WUHAOTIAN
* @param len 字符串长度
* @return
* @date 2019年4月15日上午11:20:14
*/
public static String getStr(int len) {
StringBuilder sb = new StringBuilder();
for (int i = 1; i < len + 1; i++) {
int index = (int) (Math.random() * (ALL.length));
sb.append(ALL[index] + "");
}
return sb.toString();
}
/**
* 获取指定长度大写字母
* @author WUHAOTIAN
* @param len
* @return
* @date 2019年4月15日上午11:21:18
*/
public static String getUppercaseStr(int len) {
StringBuilder sb = new StringBuilder();
for (int i = 1; i < len + 1; i++) {
int index = (int) (Math.random() * (BIG.length));
sb.append(BIG[index] + "");
}
return sb.toString();
}
/**
* 获取指定长度小写字母
* @author WUHAOTIAN
* @param len
* @return
* @date 2019年4月15日上午11:21:18
*/
public static String getLowercaseStr(int len) {
StringBuilder sb = new StringBuilder();
for (int i = 1; i < len + 1; i++) {
int index = (int) (Math.random() * (SMALL.length));
sb.append(SMALL[index] + "");
}
return sb.toString();
}
/**
* 获取指定长度数字
* @author WUHAOTIAN
* @param len
* @return
* @date 2019年4月15日上午11:21:18
*/
public static String getNum(int len) {
StringBuilder sb = new StringBuilder();
for (int i = 1; i < len + 1; i++) {
int index = (int) (Math.random() * (NUM.length));
sb.append(NUM[index] + "");
}
return sb.toString();
}
}
| [
"[email protected]"
] | |
c6fa8ec576f42d4bbe96d03e25599ef0ad74ff1d | b39d7e1122ebe92759e86421bbcd0ad009eed1db | /sources/android/media/-$$Lambda$AudioRecordingMonitorImpl$2$cn04v8rie0OYr-_fiLO_SMYka7I.java | 80ac29402da64f56fc8956fd7ed41f1af551b663 | [] | no_license | AndSource/miuiframework | ac7185dedbabd5f619a4f8fc39bfe634d101dcef | cd456214274c046663aefce4d282bea0151f1f89 | refs/heads/master | 2022-03-31T11:09:50.399520 | 2020-01-02T09:49:07 | 2020-01-02T09:49:07 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 688 | java | package android.media;
import java.util.ArrayList;
/* compiled from: lambda */
public final /* synthetic */ class -$$Lambda$AudioRecordingMonitorImpl$2$cn04v8rie0OYr-_fiLO_SMYka7I implements Runnable {
private final /* synthetic */ AudioRecordingCallbackInfo f$0;
private final /* synthetic */ ArrayList f$1;
public /* synthetic */ -$$Lambda$AudioRecordingMonitorImpl$2$cn04v8rie0OYr-_fiLO_SMYka7I(AudioRecordingCallbackInfo audioRecordingCallbackInfo, ArrayList arrayList) {
this.f$0 = audioRecordingCallbackInfo;
this.f$1 = arrayList;
}
public final void run() {
this.f$0.mCb.onRecordingConfigChanged(this.f$1);
}
}
| [
"[email protected]"
] | |
0f00d18d404b1a203e3b6e6eb8023e41c78a1246 | 58f63a6147b3c6a61b8b3c54f635c54bff4275d8 | /src/main/java/org/tsaap/lti/tp/dataconnector/None.java | 6b4d786e65dee396a1e17d789f7d22571457b76c | [] | no_license | TSaaP/tsaap-lti | 32fa51c83eb2b12d7a603b3008aad7023ed316fe | c6865d310d5dd6d6b2b0c924136b6c8721340e98 | refs/heads/master | 2021-01-20T18:04:05.694148 | 2017-09-08T10:27:18 | 2017-09-08T10:27:18 | 60,834,752 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 7,352 | java | /*
* LTIToolProvider - Classes to handle connections with an LTI 1 compliant tool consumer
* Copyright (C) 2013 Stephen P Vickers
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along
* with this program; if not, see <http://www.gnu.org/licences/>
*
* Contact: [email protected]
*/
package org.tsaap.lti.tp.dataconnector;
import org.tsaap.lti.tp.*;
import java.util.*;
/**
* Class which implements a dummy data connector with no database persistence.
*
* @author Stephen P Vickers
* @version 1.1.01 (18-Jun-13)
*/
public class None extends DataConnector {
/**
* Constructs a dummy data connector object which implements simulated methods
* without persisting any data.
*/
public None() {
}
///
/// ToolConsumer methods
///
/**
* Load tool consumer object with a default secret of <code>secret</code> and enabled.
*
* @param consumer ToolConsumer object
* @return <code>true</code> if the tool consumer object was successfully loaded
*/
@Override
public boolean loadToolConsumer(ToolConsumer consumer) {
consumer.setSecret("secret");
consumer.setEnabled(true);
Calendar now = Calendar.getInstance();
consumer.setCreated(now);
consumer.setUpdated(now);
return true;
}
/**
* Save tool consumer object.
*
* @param consumer ToolConsumer object
* @return <code>true</code> if the tool consumer object was successfully saved
*/
@Override
public boolean saveToolConsumer(ToolConsumer consumer) {
consumer.setUpdated(Calendar.getInstance());
return true;
}
/**
* Delete tool consumer object.
*
* @param consumer ToolConsumer object
* @return <code>true</code> if the tool consumer object was successfully deleted
*/
@Override
public boolean deleteToolConsumer(ToolConsumer consumer) {
consumer.initialise();
return true;
}
/**
* Load tool consumer objects.
*
* @return array of all defined ToolConsumer objects
*/
@Override
public List<ToolConsumer> getToolConsumers() {
return new ArrayList<ToolConsumer>();
}
///
/// ResourceLink methods
///
/**
* Load resource link object.
*
* @param resourceLink ResourceLink object
* @return <code>true</code> if the resource link object was successfully loaded
*/
@Override
public boolean loadResourceLink(ResourceLink resourceLink) {
Calendar now = Calendar.getInstance();
resourceLink.setCreated(now);
resourceLink.setUpdated(now);
return true;
}
/**
* Save resource link object.
*
* @param resourceLink ResourceLink object
* @return <code>true</code> if the resource link object was successfully saved
*/
@Override
public boolean saveResourceLink(ResourceLink resourceLink) {
resourceLink.setUpdated(Calendar.getInstance());
return true;
}
/**
* Delete resource link object.
*
* @param resourceLink ResourceLink object
* @return <code>true</code> if the resourceLink object was successfully deleted
*/
@Override
public boolean deleteResourceLink(ResourceLink resourceLink) {
resourceLink.initialise();
return true;
}
/**
* Get array of user objects.
*
* @param resourceLink ResourceLink object
* @param localOnly <code>true</code> if only users for the resource link are to be returned (excluding users sharing this resource link)
* @param scope Scope value to use for user IDs
* @return array of User objects
*/
@Override
public Map<String, User> getUserResultSourcedIDs(ResourceLink resourceLink, boolean localOnly, int scope) {
return new HashMap<String, User>();
}
/**
* Get shares defined for a resource link.
*
* @param resourceLink ResourceLink object
* @return array of resourceLinkShare objects
*/
@Override
public List<ResourceLinkShare> getShares(ResourceLink resourceLink) {
return new ArrayList<ResourceLinkShare>();
}
///
/// Nonce methods
///
/**
* Load nonce object.
*
* @param nonce Nonce object
* @return <code>true</code> if the nonce object was successfully loaded
*/
@Override
public boolean loadConsumerNonce(Nonce nonce) {
return false; // assume the nonce does not already exist
}
/**
* Save nonce object.
*
* @param nonce Nonce object
* @return <code>true</code> if the nonce object was successfully saved
*/
@Override
public boolean saveConsumerNonce(Nonce nonce) {
return true;
}
///
/// ResourceLinkShareKey methods
///
/**
* Load resource link share key object.
*
* @param shareKey Resource link share key object
* @return <code>true</code> if the resource link share key object was successfully loaded
*/
@Override
public boolean loadResourceLinkShareKey(ResourceLinkShareKey shareKey) {
return true;
}
/**
* Save resource link share key object.
*
* @param shareKey Resource link share key object
* @return <code>true</code> if the resource link share key object was successfully saved
*/
@Override
public boolean saveResourceLinkShareKey(ResourceLinkShareKey shareKey) {
return true;
}
/**
* Delete resource link share key object.
*
* @param shareKey Resource link share key object
* @return <code>true</code> if the resource link share key object was successfully deleted
*/
@Override
public boolean deleteResourceLinkShareKey(ResourceLinkShareKey shareKey) {
return true;
}
///
/// User methods
///
/**
* Load user object.
*
* @param user User object
* @return <code>true</code> if the user object was successfully loaded
*/
@Override
public boolean loadUser(User user) {
Calendar now = Calendar.getInstance();
user.setCreated(now);
user.setUpdated(now);
return true;
}
/**
* Save user object.
*
* @param user User object
* @return <code>true</code> if the user object was successfully saved
*/
@Override
public boolean saveUser(User user) {
user.setUpdated(Calendar.getInstance());
return true;
}
/**
* Delete user object.
*
* @param user User object
* @return <code>true</code> if the user object was successfully deleted
*/
@Override
public boolean deleteUser(User user) {
user.initialise();
return true;
}
}
| [
"[email protected]"
] | |
025e28aa2e5f368d3204a494bdc035995d75dbc4 | f1cc4a923edea421e39b78cc3b6111b719bf4ca0 | /src/main/java/com/wangsocial/app/service/PaymentService.java | c594f6c816d33595ad01ee8a3f4baf2e91cb4b38 | [] | no_license | wangzejie1993/xu | e413f0f7f7c3632b241f5f98585b57ffb9f8241c | 1a9111c8752b2445f448986779b397e9773c4734 | refs/heads/master | 2021-05-02T08:07:47.145931 | 2018-09-25T06:13:58 | 2018-09-25T06:13:58 | 120,845,346 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 276 | java | package com.wangsocial.app.service;
import com.wangsocial.app.entity.Payment;
import com.baomidou.mybatisplus.service.IService;
/**
* <p>
* 支付表 服务类
* </p>
*
* @author
* @since 2017-06-21
*/
public interface PaymentService extends IService<Payment> {
}
| [
"[email protected]"
] | |
cfe0908eea167caed8e052dc5b005b18915948e1 | 3c875e49e161ad3b692eb3a80d95b26bc51ee941 | /mall/mall-mbg/src/main/java/com/xzj/mall/mapper/UmsMemberLoginLogMapper.java | e1b5436216a75692032788fb2a6fa2ca273c6deb | [] | no_license | Xuezaijing/doc | 2cc4d4bb368152b9f727c8bd209a16e9bb58d2b7 | 53c9bfc7b3b2b7bd4b781c6e1e51702904a47020 | refs/heads/master | 2022-07-07T07:41:15.865165 | 2020-09-03T11:59:48 | 2020-09-03T11:59:48 | 192,318,423 | 0 | 1 | null | 2022-06-21T01:17:49 | 2019-06-17T09:40:29 | Java | UTF-8 | Java | false | false | 992 | java | package com.xzj.mall.mapper;
import com.xzj.mall.model.UmsMemberLoginLog;
import com.xzj.mall.model.UmsMemberLoginLogExample;
import java.util.List;
import org.apache.ibatis.annotations.Param;
public interface UmsMemberLoginLogMapper {
int countByExample(UmsMemberLoginLogExample example);
int deleteByExample(UmsMemberLoginLogExample example);
int deleteByPrimaryKey(Long id);
int insert(UmsMemberLoginLog record);
int insertSelective(UmsMemberLoginLog record);
List<UmsMemberLoginLog> selectByExample(UmsMemberLoginLogExample example);
UmsMemberLoginLog selectByPrimaryKey(Long id);
int updateByExampleSelective(@Param("record") UmsMemberLoginLog record, @Param("example") UmsMemberLoginLogExample example);
int updateByExample(@Param("record") UmsMemberLoginLog record, @Param("example") UmsMemberLoginLogExample example);
int updateByPrimaryKeySelective(UmsMemberLoginLog record);
int updateByPrimaryKey(UmsMemberLoginLog record);
} | [
"[email protected]"
] | |
a5d75c105a8d5204fd036424168b5c8ea7f6c718 | b667fd9432ccedf396f9b7ac3b6a5ada9fa0279f | /Sensor_Spring/src/main/java/me/tell/pago/RealizarPagoRequest.java | 7f3819ca873ef53eee729af5aaa6f1bb82c88538 | [] | no_license | cesar123hc/ProtectoTW | 46215c6787fdd9481111b1d971eeb9b1279d5a0a | f900037e73d250212c147ca7b441085128db7059 | refs/heads/main | 2023-05-13T02:17:55.462265 | 2021-06-03T20:45:19 | 2021-06-03T20:45:19 | 372,701,958 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,910 | java | //
// Este archivo ha sido generado por la arquitectura JavaTM para la implantación de la referencia de enlace (JAXB) XML v2.2.7
// Visite <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Todas las modificaciones realizadas en este archivo se perderán si se vuelve a compilar el esquema de origen.
// Generado el: 2021.06.02 a las 11:09:50 AM CDT
//
package me.tell.pago;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Clase Java para anonymous complex type.
*
* <p>El siguiente fragmento de esquema especifica el contenido que se espera que haya en esta clase.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="fecha" type="{http://www.w3.org/2001/XMLSchema}string"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"fecha"
})
@XmlRootElement(name = "RealizarPagoRequest")
public class RealizarPagoRequest {
@XmlElement(required = true)
protected String fecha;
/**
* Obtiene el valor de la propiedad fecha.
*
* @return
* possible object is
* {@link String }
*
*/
public String getFecha() {
return fecha;
}
/**
* Define el valor de la propiedad fecha.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setFecha(String value) {
this.fecha = value;
}
}
| [
"[email protected]"
] | |
434e3a86058d29315c579bc268e07a5632f51108 | ed5bac548c838cd6044e64870a77ddf1853f8709 | /dhis-2/dhis-services/dhis-service-dxf2/src/main/java/org/hisp/dhis/dxf2/events/importer/shared/validation/ProgramInstanceCheck.java | e62f6fc62b78d2148e971461845caac4912e1b38 | [
"BSD-3-Clause",
"BSD-2-Clause"
] | permissive | mortenoh/dhis2-core | fab20677994e6a302ab348019c01d7d48aabba67 | a5a787339f3cf971e5354a07a3987f8c493b7331 | refs/heads/master | 2023-04-07T04:29:17.387415 | 2023-04-03T14:23:41 | 2023-04-03T14:23:41 | 67,017,032 | 0 | 0 | BSD-3-Clause | 2023-02-01T10:39:06 | 2016-08-31T08:05:35 | Java | UTF-8 | Java | false | false | 4,490 | java | /*
* Copyright (c) 2004-2022, University of Oslo
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* Neither the name of the HISP project nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.hisp.dhis.dxf2.events.importer.shared.validation;
import static org.hisp.dhis.dxf2.importsummary.ImportSummary.error;
import static org.hisp.dhis.dxf2.importsummary.ImportSummary.success;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import org.hisp.dhis.dxf2.events.importer.Checker;
import org.hisp.dhis.dxf2.events.importer.context.WorkContext;
import org.hisp.dhis.dxf2.events.importer.shared.ImmutableEvent;
import org.hisp.dhis.dxf2.importsummary.ImportSummary;
import org.hisp.dhis.program.Program;
import org.hisp.dhis.program.ProgramInstance;
import org.hisp.dhis.program.ProgramStatus;
import org.hisp.dhis.trackedentity.TrackedEntityInstance;
import org.springframework.stereotype.Component;
/**
* @author Luciano Fiandesio
*/
@Component
public class ProgramInstanceCheck implements Checker
{
@Override
public ImportSummary check( ImmutableEvent event, WorkContext ctx )
{
Program program = ctx.getProgramsMap().get( event.getProgram() );
ProgramInstance programInstance = ctx.getProgramInstanceMap().get( event.getUid() );
final Optional<TrackedEntityInstance> trackedEntityInstance = ctx.getTrackedEntityInstance( event.getUid() );
String teiUid = "";
if ( trackedEntityInstance.isPresent() )
{
teiUid = trackedEntityInstance.get().getUid();
}
List<ProgramInstance> programInstances;
if ( programInstance == null ) // Program Instance should be NOT null,
// after the pre-processing stage
{
if ( program.isRegistration() )
{
programInstances = new ArrayList<>( ctx.getServiceDelegator().getProgramInstanceStore()
.get( trackedEntityInstance.orElse( null ), program, ProgramStatus.ACTIVE ) );
if ( programInstances.isEmpty() )
{
return error( "Tracked entity instance: "
+ teiUid + " is not enrolled in program: " + program.getUid(),
event.getEvent() );
}
else if ( programInstances.size() > 1 )
{
return error( "Tracked entity instance: " + teiUid
+ " has multiple active enrollments in program: " + program.getUid(),
event.getEvent() );
}
}
else
{
programInstances = ctx.getServiceDelegator().getProgramInstanceStore().get( program,
ProgramStatus.ACTIVE );
if ( programInstances.size() > 1 )
{
return error( "Multiple active program instances exists for program: " + program.getUid(),
event.getEvent() );
}
}
}
return success();
}
}
| [
"[email protected]"
] | |
d265670591721c88563da3df8c4ad7c0458fb82e | c65f507f37797de753482e3bf3a19ab36d84ec56 | /ScFrame/src/main/java/com/caihan/scframe/utils/MetaDataUtils.java | ceeeb9d9c8a8c8d8f0f71414601385cc648c84f4 | [] | no_license | tieruni/MyScFrame | 4d7a91b42af982a0f752a802d73b2d2e3ecfbee5 | 9a16c71760827f41d8a013b6fe7fe4393a53884e | refs/heads/master | 2022-02-16T01:06:15.620230 | 2019-09-15T02:16:36 | 2019-09-15T02:16:36 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,865 | java | package com.caihan.scframe.utils;
import android.app.Activity;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
/**
* meta-data标签工具类
*
* @author caihan
* @date 2018/6/26
* @e-mail [email protected]
* 维护者
*/
public class MetaDataUtils {
/**
* 获取value
* <meta-data android:name="meta_app" android:value="value from meta_app" />
*
* @param context 上下文
* @param metaStringKey meta_app
* @return value from meta_app
*/
public static String getMetaDataFromApp(Context context, String metaStringKey) {
String value = "";
try {
ApplicationInfo appInfo = context.getPackageManager()
.getApplicationInfo(context.getPackageName(),
PackageManager.GET_META_DATA);
value = appInfo.metaData.getString(metaStringKey);
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
return value;
}
/**
* 获取resource id
* <p>
* <meta-data android:name="meta_act" android:resource="@string/app_name" />
*
* @param context 上下文
* @param metaStringKey meta_act
* @return
*/
public static int getMetaDataIdFromAct(Context context, String metaStringKey) {
int resId = 0;
try {
ActivityInfo activityInfo = context.getPackageManager()
.getActivityInfo(((Activity) context).getComponentName(),
PackageManager.GET_META_DATA);
resId = activityInfo.metaData.getInt(metaStringKey);
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
return resId;
}
}
| [
"[email protected]"
] | |
0ea01f5153c3b4db63bf553dec9dc6886a79846b | b0f98be9fde920c75cb0f61776f2832cc0da9c45 | /R.java | 21b5d25ef4bce2cc680b27b7c3a13d3bb41b01ca | [] | no_license | jdserato/Database | 9a48da7a95e0180a4e6d30d8572abffc6b77f92a | 04032c84d268c9dd2c68f57393ff2b7779bd3328 | refs/heads/master | 2020-05-23T13:08:47.011439 | 2017-04-20T02:33:28 | 2017-04-20T02:33:28 | 84,771,463 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 415 | java | /* AUTO-GENERATED FILE. DO NOT MODIFY.
*
* This class was automatically generated by the
* aapt tool from the resource data it found. It
* should not be modified by hand.
*/
package com.example.danielle98.hogwartsdata.test;
public final class R {
public static final class attr {
}
public static final class string {
public static final int app_name=0x7f020000;
}
}
| [
"[email protected]"
] | |
1b8bcc08417ed5cdea9186ba34879a354f045989 | 2a515fecd1bfa95d4d8b8571a597d430a37d16db | /src/main/java/com/pwc/assignment/controller/DepartmentController.java | 8fdcc65409c4ed6ae2ed842adc2c1232c96ac508 | [] | no_license | mabulhaija/cms | 90edc60aedcfd209d8b0a5c86a053cf2c01e15f1 | 801216957e6120601fb704c04a3ad4dc6f275fa4 | refs/heads/master | 2023-07-16T17:07:48.118783 | 2021-09-01T18:55:32 | 2021-09-01T18:55:32 | 401,834,557 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,088 | java | package com.pwc.assignment.controller;
import com.pwc.assignment.authentication.JwtTokenProvider;
import com.pwc.assignment.model.Department;
import com.pwc.assignment.service.DepartmentService;
import com.pwc.assignment.service.response.Response;
import com.pwc.assignment.service.response.success.CreatedResponse;
import com.pwc.assignment.service.response.success.NoContentResponse;
import com.pwc.assignment.service.response.success.OkResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
@RestController
@RequestMapping("/departments")
public class DepartmentController {
@Autowired
DepartmentService departmentService;
@Autowired
private HttpServletRequest request;
@GetMapping
public Response getDepartments(@RequestParam(value = "size", required = false, defaultValue = "5") @Min(value = 5) @Max(value = 25) int size,
@RequestParam(value = "offset", required = false, defaultValue = "0") @Min(value = 0) int offset,
@RequestParam(value = "name", required = false) String name) {
return new OkResponse("Success!", departmentService.getEntities(size, offset, name));
}
@GetMapping("/{id}")
public Response getDepartmentById(@PathVariable("id") Integer id) {
return new OkResponse("Success!", departmentService.getEntityById(id));
}
@GetMapping("/{id}/users")
public Response getDepartmentUsers(@PathVariable("id") Integer id,
@RequestParam(value = "size", required = false, defaultValue = "5") @Min(value = 5) @Max(value = 25) int size,
@RequestParam(value = "offset", required = false, defaultValue = "0") @Min(value = 0) int offset) {
return new OkResponse("Success!", departmentService.getDepartmentUsers(id, size, offset));
}
@PostMapping
public Response addNewDepartment(@NotNull(message = "Request body cannot be null") @Valid @RequestBody Department department) {
Integer userId = JwtTokenProvider.extractUserData(request).getId();
department.setAddedBy(userId);
return new CreatedResponse("Department added successfully!", departmentService.insertEntity(department));
}
@PutMapping("/{id}")
public Response updateDepartment(@PathVariable("id") Integer id,
@NotNull(message = "Request body cannot be null") @Valid @RequestBody Department department) {
departmentService.updateEntity(id, department);
return new OkResponse("Department updated successfully!", department);
}
@DeleteMapping("/{id}")
public Response deleteDepartment(@PathVariable("id") Integer id) {
departmentService.deleteEntity(id);
return new NoContentResponse();
}
}
| [
"[email protected]"
] | |
578b9bd97443c1c261e3158d331fbbbf706ec845 | 6abe807945f29c887484f9ac4221f45ab4dd8768 | /android/app/src/main/java/com/catgallery/MainActivity.java | 967dd825c8b1b9fa070adb660e6190f04d2bc382 | [] | no_license | jinhe2305/CatGallery | aab3cf08d60928f9261eabaaf79a99dec894678c | fd863437050ddbfb5d8cc1a2886383a96473ee49 | refs/heads/master | 2020-04-27T09:14:11.796997 | 2019-03-06T19:23:52 | 2019-03-06T19:23:52 | 174,206,305 | 3 | 0 | null | null | null | null | UTF-8 | Java | false | false | 365 | java | package com.catgallery;
import com.facebook.react.ReactActivity;
public class MainActivity extends ReactActivity {
/**
* Returns the name of the main component registered from JavaScript.
* This is used to schedule rendering of the component.
*/
@Override
protected String getMainComponentName() {
return "CatGallery";
}
}
| [
"[email protected]"
] | |
2087ea21ce95685d05ab635e4344d3cc6e3aa433 | 129f58086770fc74c171e9c1edfd63b4257210f3 | /src/testcases/CWE470_Unsafe_Reflection/CWE470_Unsafe_Reflection__listen_tcp_54b.java | 75fccc2cab795bff5b42cff86fb0d441341365ed | [] | no_license | glopezGitHub/Android23 | 1bd0b6a6c7ce3c7439a74f1e4dcef2c4c0fac4ba | 6215d0684c4fbdc7217ccfbedfccfca69824cc5e | refs/heads/master | 2023-03-07T15:14:59.447795 | 2023-02-06T13:59:49 | 2023-02-06T13:59:49 | 6,856,387 | 0 | 3 | null | 2023-02-06T18:38:17 | 2012-11-25T22:04:23 | Java | UTF-8 | Java | false | false | 1,170 | java | /* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE470_Unsafe_Reflection__listen_tcp_54b.java
Label Definition File: CWE470_Unsafe_Reflection.label.xml
Template File: sources-sink-54b.tmpl.java
*/
/*
* @description
* CWE: 470 Use of Externally-Controlled Input to Select Classes or Code ('Unsafe Reflection')
* BadSource: listen_tcp Read data using a listening tcp connection
* GoodSource: Set data to a hardcoded class name
* Sinks:
* BadSink : Instantiate class named in data
* Flow Variant: 54 Data flow: data passed as an argument from one method through three others to a fifth; all five functions are in different classes in the same package
*
* */
package testcases.CWE470_Unsafe_Reflection;
import testcasesupport.*;
import javax.servlet.http.*;
public class CWE470_Unsafe_Reflection__listen_tcp_54b
{
public void bad_sink(String data ) throws Throwable
{
(new CWE470_Unsafe_Reflection__listen_tcp_54c()).bad_sink(data );
}
/* goodG2B() - use goodsource and badsink */
public void goodG2B_sink(String data ) throws Throwable
{
(new CWE470_Unsafe_Reflection__listen_tcp_54c()).goodG2B_sink(data );
}
}
| [
"[email protected]"
] | |
76b4b054fc7d303a02bdeba0260c8595627ec8dd | 42b5f055f8a3ffb64f4e27d0b0fa1fa515d2fa47 | /weka/classifiers/functions/MultilayerPerceptron.java | 3c18d154327ff2ed7fa02810b4858fe6ce91892e | [] | no_license | sinamalakouti/DeepTreeNetwork | 4de4be524b062435e1d083d0d8792f4955a47007 | 0eab518f99b00e8b6bf0e3b5771ff71c84e525f1 | refs/heads/master | 2022-01-11T08:58:59.855122 | 2019-07-24T19:02:38 | 2019-07-24T19:02:38 | 145,144,372 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 87,133 | java | /*
* 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/>.
*/
/*
* MultilayerPerceptron.java
* Copyright (C) 2000-2012 University of Waikato, Hamilton, New Zealand
*/
package weka.classifiers.functions;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Random;
import java.util.StringTokenizer;
import java.util.Vector;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import weka.classifiers.AbstractClassifier;
import weka.classifiers.Classifier;
import weka.classifiers.IterativeClassifier;
import weka.classifiers.functions.neural.LinearUnit;
import weka.classifiers.functions.neural.NeuralConnection;
import weka.classifiers.functions.neural.NeuralNode;
import weka.classifiers.functions.neural.SigmoidUnit;
import weka.core.*;
import weka.core.Capabilities.Capability;
import weka.filters.Filter;
import weka.filters.unsupervised.attribute.NominalToBinary;
/**
* <!-- globalinfo-start --> A Classifier that uses backpropagation to classify
* instances.<br/>
* This network can be built by hand, created by an algorithm or both. The
* network can also be monitored and modified during training time. The nodes in
* this network are all sigmoid (except for when the class is numeric in which
* case the the output nodes become unthresholded linear units).
* <p/>
* <!-- globalinfo-end -->
*
* <!-- options-start --> Valid options are:
* <p/>
*
* <pre>
* -L <learning rate>
* Learning Rate for the backpropagation algorithm.
* (Value should be between 0 - 1, Default = 0.3).
* </pre>
*
* <pre>
* -M <momentum>
* Momentum Rate for the backpropagation algorithm.
* (Value should be between 0 - 1, Default = 0.2).
* </pre>
*
* <pre>
* -N <number of epochs>
* Number of epochs to train through.
* (Default = 500).
* </pre>
*
* <pre>
* -V <percentage size of validation set>
* Percentage size of validation set to use to terminate
* training (if this is non zero it can pre-empt num of epochs.
* (Value should be between 0 - 100, Default = 0).
* </pre>
*
* <pre>
* -S <seed>
* The value used to seed the random number generator
* (Value should be >= 0 and and a long, Default = 0).
* </pre>
*
* <pre>
* -E <threshold for number of consequetive errors>
* The consequetive number of errors allowed for validation
* testing before the netwrok terminates.
* (Value should be > 0, Default = 20).
* </pre>
*
* <pre>
* -G
* GUI will be opened.
* (Use this to bring up a GUI).
* </pre>
*
* <pre>
* -A
* Autocreation of the network connections will NOT be done.
* (This will be ignored if -G is NOT set)
* </pre>
*
* <pre>
* -B
* A NominalToBinary filter will NOT automatically be used.
* (Set this to not use a NominalToBinary filter).
* </pre>
*
* <pre>
* -H <comma seperated numbers for nodes on each layer>
* The hidden layers to be created for the network.
* (Value should be a list of comma separated Natural
* numbers or the letters 'a' = (attribs + classes) / 2,
* 'i' = attribs, 'o' = classes, 't' = attribs .+ classes)
* for wildcard values, Default = a).
* </pre>
*
* <pre>
* -C
* Normalizing a numeric class will NOT be done.
* (Set this to not normalize the class if it's numeric).
* </pre>
*
* <pre>
* -I
* Normalizing the attributes will NOT be done.
* (Set this to not normalize the attributes).
* </pre>
*
* <pre>
* -R
* Reseting the network will NOT be allowed.
* (Set this to not allow the network to reset).
* </pre>
*
* <pre>
* -D
* Learning rate decay will occur.
* (Set this to cause the learning rate to decay).
* </pre>
*
* <!-- options-end -->
*
* @author Malcolm Ware ([email protected])
* @version $Revision: 14497 $
*/
public class MultilayerPerceptron extends AbstractClassifier implements
OptionHandler, WeightedInstancesHandler, Randomizable, IterativeClassifier {
/** for serialization */
private static final long serialVersionUID = -5990607817048210779L;
/**
* Main method for testing this class.
*
* @param argv should contain command line options (see setOptions)
*/
public static void main(String[] argv) {
runClassifier(new MultilayerPerceptron(), argv);
}
/**
* This inner class is used to connect the nodes in the network up to the data
* that they are classifying, Note that objects of this class are only
* suitable to go on the attribute side or class side of the network and not
* both.
*/
protected class NeuralEnd extends NeuralConnection {
/** for serialization */
static final long serialVersionUID = 7305185603191183338L;
/**
* the value that represents the instance value this node represents. For an
* input it is the attribute number, for an output, if nominal it is the
* class value.
*/
private int m_link;
/** True if node is an input, False if it's an output. */
private boolean m_input;
/**
* Constructor
*/
public NeuralEnd(String id) {
super(id);
m_link = 0;
m_input = true;
}
/**
* Call this function to determine if the point at x,y is on the unit.
*
* @param g The graphics context for font size info.
* @param x The x coord.
* @param y The y coord.
* @param w The width of the display.
* @param h The height of the display.
* @return True if the point is on the unit, false otherwise.
*/
@Override
public boolean onUnit(Graphics g, int x, int y, int w, int h) {
FontMetrics fm = g.getFontMetrics();
int l = (int) (m_x * w) - fm.stringWidth(m_id) / 2;
int t = (int) (m_y * h) - fm.getHeight() / 2;
if (x < l || x > l + fm.stringWidth(m_id) + 4 || y < t
|| y > t + fm.getHeight() + fm.getDescent() + 4) {
return false;
}
return true;
}
/**
* This will draw the node id to the graphics context.
*
* @param g The graphics context.
* @param w The width of the drawing area.
* @param h The height of the drawing area.
*/
@Override
public void drawNode(Graphics g, int w, int h) {
if ((m_type & PURE_INPUT) == PURE_INPUT) {
g.setColor(Color.green);
} else {
g.setColor(Color.orange);
}
FontMetrics fm = g.getFontMetrics();
int l = (int) (m_x * w) - fm.stringWidth(m_id) / 2;
int t = (int) (m_y * h) - fm.getHeight() / 2;
g.fill3DRect(l, t, fm.stringWidth(m_id) + 4,
fm.getHeight() + fm.getDescent() + 4, true);
g.setColor(Color.black);
g.drawString(m_id, l + 2, t + fm.getHeight() + 2);
}
/**
* Call this function to draw the node highlighted.
*
* @param g The graphics context.
* @param w The width of the drawing area.
* @param h The height of the drawing area.
*/
@Override
public void drawHighlight(Graphics g, int w, int h) {
g.setColor(Color.black);
FontMetrics fm = g.getFontMetrics();
int l = (int) (m_x * w) - fm.stringWidth(m_id) / 2;
int t = (int) (m_y * h) - fm.getHeight() / 2;
g.fillRect(l - 2, t - 2, fm.stringWidth(m_id) + 8,
fm.getHeight() + fm.getDescent() + 8);
drawNode(g, w, h);
}
/**
* Call this to get the output value of this unit.
*
* @param calculate True if the value should be calculated if it hasn't been
* already.
* @return The output value, or NaN, if the value has not been calculated.
*/
@Override
public double outputValue(boolean calculate) {
if (Double.isNaN(m_unitValue) && calculate) {
if (m_input) {
if (m_currentInstance.isMissing(m_link)) {
m_unitValue = 0;
} else {
m_unitValue = m_currentInstance.value(m_link);
}
} else {
// node is an output.
m_unitValue = 0;
for (int noa = 0; noa < m_numInputs; noa++) {
m_unitValue += m_inputList[noa].outputValue(true);
}
if (m_numeric && m_normalizeClass) {
// then scale the value;
// this scales linearly from between -1 and 1
m_unitValue = m_unitValue
* m_attributeRanges[m_instances.classIndex()]
+ m_attributeBases[m_instances.classIndex()];
}
}
}
return m_unitValue;
}
/**
* Call this to get the error value of this unit, which in this case is the
* difference between the predicted class, and the actual class.
*
* @param calculate True if the value should be calculated if it hasn't been
* already.
* @return The error value, or NaN, if the value has not been calculated.
*/
@Override
public double errorValue(boolean calculate) {
if (!Double.isNaN(m_unitValue) && Double.isNaN(m_unitError) && calculate) {
if (m_input) {
m_unitError = 0;
for (int noa = 0; noa < m_numOutputs; noa++) {
m_unitError += m_outputList[noa].errorValue(true);
}
} else {
if (m_currentInstance.classIsMissing()) {
m_unitError = .1;
} else if (m_instances.classAttribute().isNominal()) {
if (m_currentInstance.classValue() == m_link) {
m_unitError = 1 - m_unitValue;
} else {
m_unitError = 0 - m_unitValue;
}
} else if (m_numeric) {
if (m_normalizeClass) {
if (m_attributeRanges[m_instances.classIndex()] == 0) {
m_unitError = 0;
} else {
m_unitError = (m_currentInstance.classValue() - m_unitValue)
/ m_attributeRanges[m_instances.classIndex()];
// m_numericRange;
}
} else {
m_unitError = m_currentInstance.classValue() - m_unitValue;
}
}
}
}
return m_unitError;
}
/**
* Call this to reset the value and error for this unit, ready for the next
* run. This will also call the reset function of all units that are
* connected as inputs to this one. This is also the time that the update
* for the listeners will be performed.
*/
@Override
public void reset() {
if (!Double.isNaN(m_unitValue) || !Double.isNaN(m_unitError)) {
m_unitValue = Double.NaN;
m_unitError = Double.NaN;
m_weightsUpdated = false;
for (int noa = 0; noa < m_numInputs; noa++) {
m_inputList[noa].reset();
}
}
}
/**
* Call this to have the connection save the current weights.
*/
@Override
public void saveWeights() {
for (int i = 0; i < m_numInputs; i++) {
m_inputList[i].saveWeights();
}
}
/**
* Call this to have the connection restore from the saved weights.
*/
@Override
public void restoreWeights() {
for (int i = 0; i < m_numInputs; i++) {
m_inputList[i].restoreWeights();
}
}
/**
* Call this function to set What this end unit represents.
*
* @param input True if this unit is used for entering an attribute, False
* if it's used for determining a class value.
* @param val The attribute number or class type that this unit represents.
* (for nominal attributes).
*/
public void setLink(boolean input, int val) throws Exception {
m_input = input;
if (input) {
m_type = PURE_INPUT;
} else {
m_type = PURE_OUTPUT;
}
if (val < 0
|| (input && val > m_instances.numAttributes())
|| (!input && m_instances.classAttribute().isNominal() && val > m_instances
.classAttribute().numValues())) {
m_link = 0;
} else {
m_link = val;
}
}
/**
* @return link for this node.
*/
public int getLink() {
return m_link;
}
/**
* Returns the revision string.
*
* @return the revision
*/
@Override
public String getRevision() {
return RevisionUtils.extract("$Revision: 14497 $");
}
}
/**
* Inner class used to draw the nodes onto.(uses the node lists!!) This will
* also handle the user input.
*/
private class NodePanel extends JPanel implements RevisionHandler {
/** for serialization */
static final long serialVersionUID = -3067621833388149984L;
/**
* The constructor.
*/
public NodePanel() {
addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
if (!m_stopped) {
return;
}
if ((e.getModifiers() & MouseEvent.BUTTON1_MASK) == MouseEvent.BUTTON1_MASK
&& !e.isAltDown()) {
Graphics g = NodePanel.this.getGraphics();
int x = e.getX();
int y = e.getY();
int w = NodePanel.this.getWidth();
int h = NodePanel.this.getHeight();
ArrayList<NeuralConnection> tmp = new ArrayList<NeuralConnection>(4);
for (int noa = 0; noa < m_numAttributes; noa++) {
if (m_inputs[noa].onUnit(g, x, y, w, h)) {
tmp.add(m_inputs[noa]);
selection(
tmp,
(e.getModifiers() & MouseEvent.CTRL_MASK) == MouseEvent.CTRL_MASK,
true);
return;
}
}
for (int noa = 0; noa < m_numClasses; noa++) {
if (m_outputs[noa].onUnit(g, x, y, w, h)) {
tmp.add(m_outputs[noa]);
selection(
tmp,
(e.getModifiers() & MouseEvent.CTRL_MASK) == MouseEvent.CTRL_MASK,
true);
return;
}
}
for (NeuralConnection m_neuralNode : m_neuralNodes) {
if (m_neuralNode.onUnit(g, x, y, w, h)) {
tmp.add(m_neuralNode);
selection(
tmp,
(e.getModifiers() & MouseEvent.CTRL_MASK) == MouseEvent.CTRL_MASK,
true);
return;
}
}
NeuralNode temp = new NeuralNode(String.valueOf(m_nextId),
m_random, m_sigmoidUnit);
m_nextId++;
temp.setX((double) e.getX() / w);
temp.setY((double) e.getY() / h);
tmp.add(temp);
addNode(temp);
selection(
tmp,
(e.getModifiers() & MouseEvent.CTRL_MASK) == MouseEvent.CTRL_MASK,
true);
} else {
// then right click
Graphics g = NodePanel.this.getGraphics();
int x = e.getX();
int y = e.getY();
int w = NodePanel.this.getWidth();
int h = NodePanel.this.getHeight();
ArrayList<NeuralConnection> tmp = new ArrayList<NeuralConnection>(4);
for (int noa = 0; noa < m_numAttributes; noa++) {
if (m_inputs[noa].onUnit(g, x, y, w, h)) {
tmp.add(m_inputs[noa]);
selection(
tmp,
(e.getModifiers() & MouseEvent.CTRL_MASK) == MouseEvent.CTRL_MASK,
false);
return;
}
}
for (int noa = 0; noa < m_numClasses; noa++) {
if (m_outputs[noa].onUnit(g, x, y, w, h)) {
tmp.add(m_outputs[noa]);
selection(
tmp,
(e.getModifiers() & MouseEvent.CTRL_MASK) == MouseEvent.CTRL_MASK,
false);
return;
}
}
for (NeuralConnection m_neuralNode : m_neuralNodes) {
if (m_neuralNode.onUnit(g, x, y, w, h)) {
tmp.add(m_neuralNode);
selection(
tmp,
(e.getModifiers() & MouseEvent.CTRL_MASK) == MouseEvent.CTRL_MASK,
false);
return;
}
}
selection(
null,
(e.getModifiers() & MouseEvent.CTRL_MASK) == MouseEvent.CTRL_MASK,
false);
}
}
});
}
/**
* This function gets called when the user has clicked something It will
* amend the current selection or connect the current selection to the new
* selection. Or if nothing was selected and the right button was used it
* will delete the node.
*
* @param v The units that were selected.
* @param ctrl True if ctrl was held down.
* @param left True if it was the left mouse button.
*/
private void selection(ArrayList<NeuralConnection> v, boolean ctrl,
boolean left) {
if (v == null) {
// then unselect all.
m_selected.clear();
repaint();
return;
}
// then exclusive or the new selection with the current one.
if ((ctrl || m_selected.size() == 0) && left) {
boolean removed = false;
for (int noa = 0; noa < v.size(); noa++) {
removed = false;
for (int nob = 0; nob < m_selected.size(); nob++) {
if (v.get(noa) == m_selected.get(nob)) {
// then remove that element
m_selected.remove(nob);
removed = true;
break;
}
}
if (!removed) {
m_selected.add(v.get(noa));
}
}
repaint();
return;
}
if (left) {
// then connect the current selection to the new one.
for (int noa = 0; noa < m_selected.size(); noa++) {
for (int nob = 0; nob < v.size(); nob++) {
NeuralConnection.connect(m_selected.get(noa), v.get(nob));
}
}
} else if (m_selected.size() > 0) {
// then disconnect the current selection from the new one.
for (int noa = 0; noa < m_selected.size(); noa++) {
for (int nob = 0; nob < v.size(); nob++) {
NeuralConnection.disconnect(m_selected.get(noa), v.get(nob));
NeuralConnection.disconnect(v.get(nob), m_selected.get(noa));
}
}
} else {
// then remove the selected node. (it was right clicked while
// no other units were selected
for (int noa = 0; noa < v.size(); noa++) {
v.get(noa).removeAllInputs();
v.get(noa).removeAllOutputs();
removeNode(v.get(noa));
}
}
repaint();
}
/**
* This will paint the nodes ontot the panel.
*
* @param g The graphics context.
*/
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
int x = getWidth();
int y = getHeight();
if (25 * m_numAttributes > 25 * m_numClasses && 25 * m_numAttributes > y) {
setSize(x, 25 * m_numAttributes);
} else if (25 * m_numClasses > y) {
setSize(x, 25 * m_numClasses);
} else {
setSize(x, y);
}
y = getHeight();
for (int noa = 0; noa < m_numAttributes; noa++) {
m_inputs[noa].drawInputLines(g, x, y);
}
for (int noa = 0; noa < m_numClasses; noa++) {
m_outputs[noa].drawInputLines(g, x, y);
m_outputs[noa].drawOutputLines(g, x, y);
}
for (NeuralConnection m_neuralNode : m_neuralNodes) {
m_neuralNode.drawInputLines(g, x, y);
}
for (int noa = 0; noa < m_numAttributes; noa++) {
m_inputs[noa].drawNode(g, x, y);
}
for (int noa = 0; noa < m_numClasses; noa++) {
m_outputs[noa].drawNode(g, x, y);
}
for (NeuralConnection m_neuralNode : m_neuralNodes) {
m_neuralNode.drawNode(g, x, y);
}
for (int noa = 0; noa < m_selected.size(); noa++) {
m_selected.get(noa).drawHighlight(g, x, y);
}
}
/**
* Returns the revision string.
*
* @return the revision
*/
@Override
public String getRevision() {
return RevisionUtils.extract("$Revision: 14497 $");
}
}
/**
* This provides the basic controls for working with the neuralnetwork
*
* @author Malcolm Ware ([email protected])
* @version $Revision: 14497 $
*/
class ControlPanel extends JPanel implements RevisionHandler {
/** for serialization */
static final long serialVersionUID = 7393543302294142271L;
/** The start stop button. */
public JButton m_startStop;
/** The button to accept the network (even if it hasn't done all epochs. */
public JButton m_acceptButton;
/** A label to state the number of epochs processed so far. */
public JPanel m_epochsLabel;
/** A label to state the total number of epochs to be processed. */
public JLabel m_totalEpochsLabel;
/** A text field to allow the changing of the total number of epochs. */
public JTextField m_changeEpochs;
/** A label to state the learning rate. */
public JLabel m_learningLabel;
/** A label to state the momentum. */
public JLabel m_momentumLabel;
/** A text field to allow the changing of the learning rate. */
public JTextField m_changeLearning;
/** A text field to allow the changing of the momentum. */
public JTextField m_changeMomentum;
/**
* A label to state roughly the accuracy of the network.(because the
* accuracy is calculated per epoch, but the network is changing throughout
* each epoch train).
*/
public JPanel m_errorLabel;
/** The constructor. */
public ControlPanel() {
setBorder(BorderFactory.createTitledBorder("Controls"));
m_totalEpochsLabel = new JLabel("Num Of Epochs ");
m_epochsLabel = new JPanel() {
/** for serialization */
private static final long serialVersionUID = 2562773937093221399L;
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(m_controlPanel.m_totalEpochsLabel.getForeground());
g.drawString("Epoch " + m_epoch, 0, 10);
}
};
m_epochsLabel.setFont(m_totalEpochsLabel.getFont());
m_changeEpochs = new JTextField();
m_changeEpochs.setText("" + m_numEpochs);
m_errorLabel = new JPanel() {
/** for serialization */
private static final long serialVersionUID = 4390239056336679189L;
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(m_controlPanel.m_totalEpochsLabel.getForeground());
if (m_valSize == 0) {
g.drawString(
"Error per Epoch = " + Utils.doubleToString(m_error, 7), 0, 10);
} else {
g.drawString(
"Validation Error per Epoch = "
+ Utils.doubleToString(m_error, 7), 0, 10);
}
}
};
m_errorLabel.setFont(m_epochsLabel.getFont());
m_learningLabel = new JLabel("Learning Rate = ");
m_momentumLabel = new JLabel("Momentum = ");
m_changeLearning = new JTextField();
m_changeMomentum = new JTextField();
m_changeLearning.setText("" + m_learningRate);
m_changeMomentum.setText("" + m_momentum);
setLayout(new BorderLayout(15, 10));
m_stopIt = true;
m_accepted = false;
m_startStop = new JButton("Start");
m_startStop.setActionCommand("Start");
m_acceptButton = new JButton("Accept");
m_acceptButton.setActionCommand("Accept");
JPanel buttons = new JPanel();
buttons.setLayout(new BoxLayout(buttons, BoxLayout.Y_AXIS));
buttons.add(m_startStop);
buttons.add(m_acceptButton);
add(buttons, BorderLayout.WEST);
JPanel data = new JPanel();
data.setLayout(new BoxLayout(data, BoxLayout.Y_AXIS));
Box ab = new Box(BoxLayout.X_AXIS);
ab.add(m_epochsLabel);
data.add(ab);
ab = new Box(BoxLayout.X_AXIS);
Component b = Box.createGlue();
ab.add(m_totalEpochsLabel);
ab.add(m_changeEpochs);
m_changeEpochs.setMaximumSize(new Dimension(200, 20));
ab.add(b);
data.add(ab);
ab = new Box(BoxLayout.X_AXIS);
ab.add(m_errorLabel);
data.add(ab);
add(data, BorderLayout.CENTER);
data = new JPanel();
data.setLayout(new BoxLayout(data, BoxLayout.Y_AXIS));
ab = new Box(BoxLayout.X_AXIS);
b = Box.createGlue();
ab.add(m_learningLabel);
ab.add(m_changeLearning);
m_changeLearning.setMaximumSize(new Dimension(200, 20));
ab.add(b);
data.add(ab);
ab = new Box(BoxLayout.X_AXIS);
b = Box.createGlue();
ab.add(m_momentumLabel);
ab.add(m_changeMomentum);
m_changeMomentum.setMaximumSize(new Dimension(200, 20));
ab.add(b);
data.add(ab);
add(data, BorderLayout.EAST);
m_startStop.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("Start")) {
m_stopIt = false;
m_startStop.setText("Stop");
m_startStop.setActionCommand("Stop");
int n = Integer.valueOf(m_changeEpochs.getText()).intValue();
m_numEpochs = n;
m_changeEpochs.setText("" + m_numEpochs);
double m = Double.valueOf(m_changeLearning.getText()).doubleValue();
setLearningRate(m);
m_changeLearning.setText("" + m_learningRate);
m = Double.valueOf(m_changeMomentum.getText()).doubleValue();
setMomentum(m);
m_changeMomentum.setText("" + m_momentum);
blocker(false);
} else if (e.getActionCommand().equals("Stop")) {
m_stopIt = true;
m_startStop.setText("Start");
m_startStop.setActionCommand("Start");
}
}
});
m_acceptButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
m_accepted = true;
blocker(false);
}
});
m_changeEpochs.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
int n = Integer.valueOf(m_changeEpochs.getText()).intValue();
if (n > 0) {
m_numEpochs = n;
blocker(false);
}
}
});
}
/**
* Returns the revision string.
*
* @return the revision
*/
@Override
public String getRevision() {
return RevisionUtils.extract("$Revision: 14497 $");
}
}
/**
* a ZeroR model in case no model can be built from the data or the network
* predicts all zeros for the classes
*/
private Classifier m_ZeroR;
/** Whether to use the default ZeroR model */
private boolean m_useDefaultModel = false;
/** The training instances. */
private Instances m_instances;
/** The current instance running through the network. */
private Instance m_currentInstance;
/** A flag to say that it's a numeric class. */
private boolean m_numeric;
/** The ranges for all the attributes. */
private double[] m_attributeRanges;
/** The base values for all the attributes. */
private double[] m_attributeBases;
/** The output units.(only feeds the errors, does no calcs) */
private NeuralEnd[] m_outputs;
/** The input units.(only feeds the inputs does no calcs) */
private NeuralEnd[] m_inputs;
/** All the nodes that actually comprise the logical neural net. */
private NeuralConnection[] m_neuralNodes;
/** The number of classes. */
private int m_numClasses = 0;
/** The number of attributes. */
private int m_numAttributes = 0; // note the number doesn't include the class.
/** The panel the nodes are displayed on. */
private NodePanel m_nodePanel;
/** The control panel. */
private ControlPanel m_controlPanel;
/** The next id number available for default naming. */
private int m_nextId;
/** A Vector list of the units currently selected. */
private ArrayList<NeuralConnection> m_selected;
/** The number of epochs to train through. */
private int m_numEpochs;
/** a flag to state if the network should be running, or stopped. */
private boolean m_stopIt;
/** a flag to state that the network has in fact stopped. */
private boolean m_stopped;
/** a flag to state that the network should be accepted the way it is. */
private boolean m_accepted;
/** The window for the network. */
private JFrame m_win;
/**
* A flag to tell the build classifier to automatically build a neural net.
*/
private boolean m_autoBuild;
/**
* A flag to state that the gui for the network should be brought up. To allow
* interaction while training.
*/
private boolean m_gui;
/** An int to say how big the validation set should be. */
private int m_valSize;
/** The number to to use to quit on validation testing. */
private int m_driftThreshold;
/** The number used to seed the random number generator. */
private int m_randomSeed;
/** The actual random number generator. */
private Random m_random;
/** A flag to state that a nominal to binary filter should be used. */
private boolean m_useNomToBin;
/** The actual filter. */
private NominalToBinary m_nominalToBinaryFilter;
/** The string that defines the hidden layers */
private String m_hiddenLayers;
/** This flag states that the user wants the input values normalized. */
private boolean m_normalizeAttributes;
/** This flag states that the user wants the learning rate to decay. */
private boolean m_decay;
/** This is the learning rate for the network. */
private double m_learningRate;
/** This is the momentum for the network. */
private double m_momentum;
/** Shows the number of the epoch that the network just finished. */
private int m_epoch;
/** Shows the error of the epoch that the network just finished. */
private double m_error;
/**
* This flag states that the user wants the network to restart if it is found
* to be generating infinity or NaN for the error value. This would restart
* the network with the current options except that the learning rate would be
* smaller than before, (perhaps half of its current value). This option will
* not be available if the gui is chosen (if the gui is open the user can fix
* the network themselves, it is an architectural minefield for the network to
* be reset with the gui open).
*/
private boolean m_reset;
/**
* This flag states that the user wants the class to be normalized while
* processing in the network is done. (the final answer will be in the
* original range regardless). This option will only be used when the class is
* numeric.
*/
private boolean m_normalizeClass;
/**
* this is a sigmoid unit.
*/
private final SigmoidUnit m_sigmoidUnit;
/**
* This is a linear unit.
*/
private final LinearUnit m_linearUnit;
/**
* The constructor.
*/
public MultilayerPerceptron() {
m_instances = null;
m_currentInstance = null;
m_controlPanel = null;
m_nodePanel = null;
m_epoch = 0;
m_error = 0;
m_outputs = new NeuralEnd[0];
m_inputs = new NeuralEnd[0];
m_numAttributes = 0;
m_numClasses = 0;
m_neuralNodes = new NeuralConnection[0];
m_selected = new ArrayList<NeuralConnection>(4);
m_nextId = 0;
m_stopIt = true;
m_stopped = true;
m_accepted = false;
m_numeric = false;
m_random = null;
m_nominalToBinaryFilter = new NominalToBinary();
m_sigmoidUnit = new SigmoidUnit();
m_linearUnit = new LinearUnit();
// setting all the options to their defaults. To completely change these
// defaults they will also need to be changed down the bottom in the
// setoptions function (the text info in the accompanying functions should
// also be changed to reflect the new defaults
m_normalizeClass = true;
m_normalizeAttributes = true;
m_autoBuild = true;
m_gui = false;
m_useNomToBin = true;
m_driftThreshold = 20;
m_numEpochs = 500;
m_valSize = 0;
m_randomSeed = 0;
m_hiddenLayers = "a";
m_learningRate = .3;
m_momentum = .2;
m_reset = true;
m_decay = false;
}
/**
* @param d True if the learning rate should decay.
*/
public void setDecay(boolean d) {
m_decay = d;
}
/**
* @return the flag for having the learning rate decay.
*/
public boolean getDecay() {
return m_decay;
}
/**
* This sets the network up to be able to reset itself with the current
* settings and the learning rate at half of what it is currently. This will
* only happen if the network creates NaN or infinite errors. Also this will
* continue to happen until the network is trained properly. The learning rate
* will also get set back to it's original value at the end of this. This can
* only be set to true if the GUI is not brought up.
*
* @param r True if the network should restart with it's current options and
* set the learning rate to half what it currently is.
*/
public void setReset(boolean r) {
if (m_gui) {
r = false;
}
m_reset = r;
}
/**
* @return The flag for reseting the network.
*/
public boolean getReset() {
return m_reset;
}
/**
* @param c True if the class should be normalized (the class will only ever
* be normalized if it is numeric). (Normalization puts the range
* between -1 - 1).
*/
public void setNormalizeNumericClass(boolean c) {
m_normalizeClass = c;
}
/**
* @return The flag for normalizing a numeric class.
*/
public boolean getNormalizeNumericClass() {
return m_normalizeClass;
}
/**
* @param a True if the attributes should be normalized (even nominal
* attributes will get normalized here) (range goes between -1 - 1).
*/
public void setNormalizeAttributes(boolean a) {
m_normalizeAttributes = a;
}
/**
* @return The flag for normalizing attributes.
*/
public boolean getNormalizeAttributes() {
return m_normalizeAttributes;
}
/**
* @param f True if a nominalToBinary filter should be used on the data.
*/
public void setNominalToBinaryFilter(boolean f) {
m_useNomToBin = f;
}
/**
* @return The flag for nominal to binary filter use.
*/
public boolean getNominalToBinaryFilter() {
return m_useNomToBin;
}
/**
* This seeds the random number generator, that is used when a random number
* is needed for the network.
*
* @param l The seed.
*/
@Override
public void setSeed(int l) {
if (l >= 0) {
m_randomSeed = l;
}
}
/**
* @return The seed for the random number generator.
*/
@Override
public int getSeed() {
return m_randomSeed;
}
/**
* This sets the threshold to use for when validation testing is being done.
* It works by ending testing once the error on the validation set has
* consecutively increased a certain number of times.
*
* @param t The threshold to use for this.
*/
public void setValidationThreshold(int t) {
if (t > 0) {
m_driftThreshold = t;
}
}
/**
* @return The threshold used for validation testing.
*/
public int getValidationThreshold() {
return m_driftThreshold;
}
/**
* The learning rate can be set using this command. NOTE That this is a static
* variable so it affect all networks that are running. Must be greater than 0
* and no more than 1.
*
* @param l The New learning rate.
*/
public void setLearningRate(double l) {
if (l > 0 && l <= 1) {
m_learningRate = l;
if (m_controlPanel != null) {
m_controlPanel.m_changeLearning.setText("" + l);
}
}
}
/**
* @return The learning rate for the nodes.
*/
public double getLearningRate() {
return m_learningRate;
}
/**
* The momentum can be set using this command. THE same conditions apply to
* this as to the learning rate.
*
* @param m The new Momentum.
*/
public void setMomentum(double m) {
if (m >= 0 && m <= 1) {
m_momentum = m;
if (m_controlPanel != null) {
m_controlPanel.m_changeMomentum.setText("" + m);
}
}
}
/**
* @return The momentum for the nodes.
*/
public double getMomentum() {
return m_momentum;
}
/**
* This will set whether the network is automatically built or if it is left
* up to the user. (there is nothing to stop a user from altering an autobuilt
* network however).
*
* @param a True if the network should be auto built.
*/
public void setAutoBuild(boolean a) {
if (!m_gui) {
a = true;
}
m_autoBuild = a;
}
/**
* @return The auto build state.
*/
public boolean getAutoBuild() {
return m_autoBuild;
}
/**
* This will set what the hidden layers are made up of when auto build is
* enabled. Note to have no hidden units, just put a single 0, Any more 0's
* will indicate that the string is badly formed and make it unaccepted.
* Negative numbers, and floats will do the same. There are also some
* wildcards. These are 'a' = (number of attributes + number of classes) / 2,
* 'i' = number of attributes, 'o' = number of classes, and 't' = number of
* attributes + number of classes.
*
* @param h A string with a comma seperated list of numbers. Each number is
* the number of nodes to be on a hidden layer.
*/
public void setHiddenLayers(String h) {
String tmp = "";
StringTokenizer tok = new StringTokenizer(h, ",");
if (tok.countTokens() == 0) {
return;
}
double dval;
int val;
String c;
boolean first = true;
while (tok.hasMoreTokens()) {
c = tok.nextToken().trim();
if (c.equals("a") || c.equals("i") || c.equals("o") || c.equals("t")) {
tmp += c;
} else {
dval = Double.valueOf(c).doubleValue();
val = (int) dval;
if ((val == dval && (val != 0 || (tok.countTokens() == 0 && first)) && val >= 0)) {
tmp += val;
} else {
return;
}
}
first = false;
if (tok.hasMoreTokens()) {
tmp += ", ";
}
}
m_hiddenLayers = tmp;
}
/**
* @return A string representing the hidden layers, each number is the number
* of nodes on a hidden layer.
*/
public String getHiddenLayers() {
return m_hiddenLayers;
}
/**
* This will set whether A GUI is brought up to allow interaction by the user
* with the neural network during training.
*
* @param a True if gui should be created.
*/
public void setGUI(boolean a) {
m_gui = a;
if (!a) {
setAutoBuild(true);
} else {
setReset(false);
}
}
/**
* @return The true if should show gui.
*/
public boolean getGUI() {
return m_gui;
}
/**
* This will set the size of the validation set.
*
* @param a The size of the validation set, as a percentage of the whole.
*/
public void setValidationSetSize(int a) {
if (a < 0 || a > 99) {
return;
}
m_valSize = a;
}
/**
* @return The percentage size of the validation set.
*/
public int getValidationSetSize() {
return m_valSize;
}
/**
* Set the number of training epochs to perform. Must be greater than 0.
*
* @param n The number of epochs to train through.
*/
public void setTrainingTime(int n) {
if (n > 0) {
m_numEpochs = n;
}
}
/**
* @return The number of epochs to train through.
*/
public int getTrainingTime() {
return m_numEpochs;
}
/**
* Call this function to place a node into the network list.
*
* @param n The node to place in the list.
*/
private void addNode(NeuralConnection n) {
NeuralConnection[] temp1 = new NeuralConnection[m_neuralNodes.length + 1];
for (int noa = 0; noa < m_neuralNodes.length; noa++) {
temp1[noa] = m_neuralNodes[noa];
}
temp1[temp1.length - 1] = n;
m_neuralNodes = temp1;
}
/**
* Call this function to remove the passed node from the list. This will only
* remove the node if it is in the neuralnodes list.
*
* @param n The neuralConnection to remove.
* @return True if removed false if not (because it wasn't there).
*/
private boolean removeNode(NeuralConnection n) {
NeuralConnection[] temp1 = new NeuralConnection[m_neuralNodes.length - 1];
int skip = 0;
for (int noa = 0; noa < m_neuralNodes.length; noa++) {
if (n == m_neuralNodes[noa]) {
skip++;
} else if (!((noa - skip) >= temp1.length)) {
temp1[noa - skip] = m_neuralNodes[noa];
} else {
return false;
}
}
m_neuralNodes = temp1;
return true;
}
/**
* This function sets what the m_numeric flag to represent the passed class it
* also performs the normalization of the attributes if applicable and sets up
* the info to normalize the class. (note that regardless of the options it
* will fill an array with the range and base, set to normalize all attributes
* and the class to be between -1 and 1)
*
* @param inst the instances.
* @return The modified instances. This needs to be done. If the attributes
* are normalized then deep copies will be made of all the instances
* which will need to be passed back out.
*/
private Instances setClassType(Instances inst) throws Exception {
if (inst != null) {
// x bounds
m_attributeRanges = new double[inst.numAttributes()];
m_attributeBases = new double[inst.numAttributes()];
for (int noa = 0; noa < inst.numAttributes(); noa++) {
double min = Double.POSITIVE_INFINITY;
double max = Double.NEGATIVE_INFINITY;
for (int i = 0; i < inst.numInstances(); i++) {
if (!inst.instance(i).isMissing(noa)) {
double value = inst.instance(i).value(noa);
if (value < min) {
min = value;
}
if (value > max) {
max = value;
}
}
}
m_attributeRanges[noa] = (max - min) / 2;
m_attributeBases[noa] = (max + min) / 2;
}
if (m_normalizeAttributes) {
for (int i = 0; i < inst.numInstances(); i++) {
Instance currentInstance = inst.instance(i);
double[] instance = new double[inst.numAttributes()];
for (int noa = 0; noa < inst.numAttributes(); noa++) {
if (noa != inst.classIndex()) {
if (m_attributeRanges[noa] != 0) {
instance[noa] = (currentInstance.value(noa) - m_attributeBases[noa]) / m_attributeRanges[noa];
} else {
instance[noa] = currentInstance.value(noa) - m_attributeBases[noa];
}
} else {
instance[noa] = currentInstance.value(noa);
}
}
inst.set(i, new DenseInstance(currentInstance.weight(), instance));
}
}
if (inst.classAttribute().isNumeric()) {
m_numeric = true;
} else {
m_numeric = false;
}
}
return inst;
}
/**
* A function used to stop the code that called buildclassifier from
* continuing on before the user has finished the decision tree.
*
* @param tf True to stop the thread, False to release the thread that is
* waiting there (if one).
*/
public synchronized void blocker(boolean tf) {
if (tf) {
try {
wait();
} catch (InterruptedException e) {
}
} else {
notifyAll();
}
}
/**
* Call this function to update the control panel for the gui.
*/
private void updateDisplay() {
if (m_gui) {
m_controlPanel.m_errorLabel.repaint();
m_controlPanel.m_epochsLabel.repaint();
}
}
/**
* this will reset all the nodes in the network.
*/
private void resetNetwork() {
for (int noc = 0; noc < m_numClasses; noc++) {
m_outputs[noc].reset();
}
}
/**
* This will cause the output values of all the nodes to be calculated. Note
* that the m_currentInstance is used to calculate these values.
*/
private void calculateOutputs() {
for (int noc = 0; noc < m_numClasses; noc++) {
// get the values.
m_outputs[noc].outputValue(true);
}
}
/**
* This will cause the error values to be calculated for all nodes. Note that
* the m_currentInstance is used to calculate these values. Also the output
* values should have been calculated first.
*
* @return The squared error.
*/
private double calculateErrors() throws Exception {
double ret = 0, temp = 0;
for (int noc = 0; noc < m_numAttributes; noc++) {
// get the errors.
m_inputs[noc].errorValue(true);
}
for (int noc = 0; noc < m_numClasses; noc++) {
temp = m_outputs[noc].errorValue(false);
ret += temp * temp;
}
return ret;
}
/**
* This will cause the weight values to be updated based on the learning rate,
* momentum and the errors that have been calculated for each node.
*
* @param l The learning rate to update with.
* @param m The momentum to update with.
*/
private void updateNetworkWeights(double l, double m) {
for (int noc = 0; noc < m_numClasses; noc++) {
// update weights
m_outputs[noc].updateWeights(l, m);
}
}
/**
* This creates the required input units.
*/
private void setupInputs() throws Exception {
m_inputs = new NeuralEnd[m_numAttributes];
int now = 0;
for (int noa = 0; noa < m_numAttributes + 1; noa++) {
if (m_instances.classIndex() != noa) {
m_inputs[noa - now] = new NeuralEnd(m_instances.attribute(noa).name());
m_inputs[noa - now].setX(.1);
m_inputs[noa - now].setY((noa - now + 1.0) / (m_numAttributes + 1));
m_inputs[noa - now].setLink(true, noa);
} else {
now = 1;
}
}
}
/**
* This creates the required output units.
*/
private void setupOutputs() throws Exception {
m_outputs = new NeuralEnd[m_numClasses];
for (int noa = 0; noa < m_numClasses; noa++) {
if (m_numeric) {
m_outputs[noa] = new NeuralEnd(m_instances.classAttribute().name());
} else {
m_outputs[noa] = new NeuralEnd(m_instances.classAttribute().value(noa));
}
m_outputs[noa].setX(.9);
m_outputs[noa].setY((noa + 1.0) / (m_numClasses + 1));
m_outputs[noa].setLink(false, noa);
NeuralNode temp = new NeuralNode(String.valueOf(m_nextId), m_random,
m_sigmoidUnit);
m_nextId++;
temp.setX(.75);
temp.setY((noa + 1.0) / (m_numClasses + 1));
addNode(temp);
NeuralConnection.connect(temp, m_outputs[noa]);
}
}
/**
* Call this function to automatically generate the hidden units
*/
private void setupHiddenLayer() {
StringTokenizer tok = new StringTokenizer(m_hiddenLayers, ",");
int val = 0; // num of nodes in a layer
int prev = 0; // used to remember the previous layer
int num = tok.countTokens(); // number of layers
String c;
for (int noa = 0; noa < num; noa++) {
// note that I am using the Double to get the value rather than the
// Integer class, because for some reason the Double implementation can
// handle leading white space and the integer version can't!?!
c = tok.nextToken().trim();
if (c.equals("a")) {
val = (m_numAttributes + m_numClasses) / 2;
} else if (c.equals("i")) {
val = m_numAttributes;
} else if (c.equals("o")) {
val = m_numClasses;
} else if (c.equals("t")) {
val = m_numAttributes + m_numClasses;
} else {
val = Double.valueOf(c).intValue();
}
for (int nob = 0; nob < val; nob++) {
NeuralNode temp = new NeuralNode(String.valueOf(m_nextId), m_random,
m_sigmoidUnit);
m_nextId++;
temp.setX(.5 / (num) * noa + .25);
temp.setY((nob + 1.0) / (val + 1));
addNode(temp);
if (noa > 0) {
// then do connections
for (int noc = m_neuralNodes.length - nob - 1 - prev; noc < m_neuralNodes.length
- nob - 1; noc++) {
NeuralConnection.connect(m_neuralNodes[noc], temp);
}
}
}
prev = val;
}
tok = new StringTokenizer(m_hiddenLayers, ",");
c = tok.nextToken();
if (c.equals("a")) {
val = (m_numAttributes + m_numClasses) / 2;
} else if (c.equals("i")) {
val = m_numAttributes;
} else if (c.equals("o")) {
val = m_numClasses;
} else if (c.equals("t")) {
val = m_numAttributes + m_numClasses;
} else {
val = Double.valueOf(c).intValue();
}
if (val == 0) {
for (int noa = 0; noa < m_numAttributes; noa++) {
for (int nob = 0; nob < m_numClasses; nob++) {
NeuralConnection.connect(m_inputs[noa], m_neuralNodes[nob]);
}
}
} else {
for (int noa = 0; noa < m_numAttributes; noa++) {
for (int nob = m_numClasses; nob < m_numClasses + val; nob++) {
NeuralConnection.connect(m_inputs[noa], m_neuralNodes[nob]);
}
}
for (int noa = m_neuralNodes.length - prev; noa < m_neuralNodes.length; noa++) {
for (int nob = 0; nob < m_numClasses; nob++) {
NeuralConnection.connect(m_neuralNodes[noa], m_neuralNodes[nob]);
}
}
}
}
/**
* This will go through all the nodes and check if they are connected to a
* pure output unit. If so they will be set to be linear units. If not they
* will be set to be sigmoid units.
*/
private void setEndsToLinear() {
for (NeuralConnection m_neuralNode : m_neuralNodes) {
if ((m_neuralNode.getType() & NeuralConnection.OUTPUT) == NeuralConnection.OUTPUT) {
((NeuralNode) m_neuralNode).setMethod(m_linearUnit);
} else {
((NeuralNode) m_neuralNode).setMethod(m_sigmoidUnit);
}
}
}
/**
* Returns default capabilities of the classifier.
*
* @return the capabilities of this classifier
*/
@Override
public Capabilities getCapabilities() {
Capabilities result = super.getCapabilities();
result.disableAll();
// attributes
result.enable(Capability.NOMINAL_ATTRIBUTES);
result.enable(Capability.NUMERIC_ATTRIBUTES);
result.enable(Capability.DATE_ATTRIBUTES);
result.enable(Capability.MISSING_VALUES);
// class
result.enable(Capability.NOMINAL_CLASS);
result.enable(Capability.NUMERIC_CLASS);
result.enable(Capability.DATE_CLASS);
result.enable(Capability.MISSING_CLASS_VALUES);
return result;
}
/** The instances in the validation set (if any) */
protected transient Instances valSet = null;
/** The number of instances in the validation set (if any) */
protected transient int numInVal = 0;
/** Total weight of the instances in the training set */
protected transient double totalWeight = 0;
/** Total weight of the instances in the validation set (if any) */
protected transient double totalValWeight = 0;
/** Drift off counter */
protected transient double driftOff = 0;
/** To keep track of error */
protected transient double lastRight = Double.POSITIVE_INFINITY;
protected transient double bestError = Double.POSITIVE_INFINITY;
/** Data in original format (in case learning rate gets reset */
protected transient Instances originalFormatData = null;
/**
* Initializes an iterative classifier.
*
* @param data the instances to be used in induction
* @exception Exception if the model cannot be initialized
*/
public void initializeClassifier(Instances data) throws Exception {
// can classifier handle the data?
getCapabilities().testWithFail(data);
// remove instances with missing class
data = new Instances(data);
data.deleteWithMissingClass();
originalFormatData = data;
m_ZeroR = new weka.classifiers.rules.ZeroR();
m_ZeroR.buildClassifier(data);
// only class? -> use ZeroR model
if (data.numAttributes() == 1) {
System.err.println("Cannot build model (only class attribute present in data!), "
+ "using ZeroR model instead!");
m_useDefaultModel = true;
return;
} else {
m_useDefaultModel = false;
}
m_epoch = 0;
m_error = 0;
m_instances = null;
m_currentInstance = null;
m_controlPanel = null;
m_nodePanel = null;
m_outputs = new NeuralEnd[0];
m_inputs = new NeuralEnd[0];
m_numAttributes = 0;
m_numClasses = 0;
m_neuralNodes = new NeuralConnection[0];
m_selected = new ArrayList<NeuralConnection>(4);
m_nextId = 0;
m_stopIt = true;
m_stopped = true;
m_accepted = false;
m_instances = new Instances(data);
m_random = new Random(m_randomSeed);
m_instances.randomize(m_random);
if (m_useNomToBin) {
m_nominalToBinaryFilter = new NominalToBinary();
m_nominalToBinaryFilter.setInputFormat(m_instances);
m_instances = Filter.useFilter(m_instances, m_nominalToBinaryFilter);
}
m_numAttributes = m_instances.numAttributes() - 1;
m_numClasses = m_instances.numClasses();
setClassType(m_instances);
// this sets up the validation set.
// numinval is needed later
numInVal = (int) (m_valSize / 100.0 * m_instances.numInstances());
if (m_valSize > 0) {
if (numInVal == 0) {
numInVal = 1;
}
valSet = new Instances(m_instances, 0, numInVal);
}
// /////////
setupInputs();
setupOutputs();
if (m_autoBuild) {
setupHiddenLayer();
}
// ///////////////////////////
// this sets up the gui for usage
if (m_gui) {
m_win = Utils.getWekaJFrame("Neural Network", null);
m_win.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
boolean k = m_stopIt;
m_stopIt = true;
int well = JOptionPane.showConfirmDialog(m_win, "Are You Sure...\n"
+ "Click Yes To Accept" + " The Neural Network"
+ "\n Click No To Return", "Accept Neural Network",
JOptionPane.YES_NO_OPTION);
if (well == 0) {
m_win.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
m_accepted = true;
blocker(false);
} else {
m_win.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
}
m_stopIt = k;
}
});
m_win.getContentPane().setLayout(new BorderLayout());
m_nodePanel = new NodePanel();
// without the following two lines, the
// NodePanel.paintComponents(Graphics)
// method will go berserk if the network doesn't fit completely: it will
// get called on a constant basis, using 100% of the CPU
// see the following forum thread:
// http://forum.java.sun.com/thread.jspa?threadID=580929&messageID=2945011
m_nodePanel.setPreferredSize(new Dimension(640, 480));
m_nodePanel.revalidate();
JScrollPane sp = new JScrollPane(m_nodePanel,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
m_controlPanel = new ControlPanel();
m_win.getContentPane().add(sp, BorderLayout.CENTER);
m_win.getContentPane().add(m_controlPanel, BorderLayout.SOUTH);
m_win.setSize(640, 480);
m_win.setVisible(true);
}
// This sets up the initial state of the gui
if (m_gui) {
blocker(true);
m_controlPanel.m_changeEpochs.setEnabled(false);
m_controlPanel.m_changeLearning.setEnabled(false);
m_controlPanel.m_changeMomentum.setEnabled(false);
}
// For silly situations in which the network gets accepted before training
// commenses
if (m_numeric) {
setEndsToLinear();
}
if (m_accepted) {
return;
}
// connections done.
totalWeight = 0;
totalValWeight = 0;
driftOff = 0;
lastRight = Double.POSITIVE_INFINITY;
bestError = Double.POSITIVE_INFINITY;
// ensure that at least 1 instance is trained through.
if (numInVal == m_instances.numInstances()) {
numInVal--;
}
if (numInVal < 0) {
numInVal = 0;
}
for (int noa = numInVal; noa < m_instances.numInstances(); noa++) {
if (!m_instances.instance(noa).classIsMissing()) {
totalWeight += m_instances.instance(noa).weight();
}
}
if (m_valSize != 0) {
for (int noa = 0; noa < valSet.numInstances(); noa++) {
if (!valSet.instance(noa).classIsMissing()) {
totalValWeight += valSet.instance(noa).weight();
}
}
}
m_stopped = false;
}
/**
* Performs one iteration.
*
* @return false if no further iterations could be performed, true otherwise
* @exception Exception if this iteration fails for unexpected reasons
*/
public boolean next() throws Exception {
if (m_accepted || m_useDefaultModel) { // Has user accepted the network already or do we need to use default model?
return false;
}
m_epoch++;
double right = 0;
for (int nob = numInVal; nob < m_instances.numInstances(); nob++) {
m_currentInstance = m_instances.instance(nob);
if (!m_currentInstance.classIsMissing()) {
// this is where the network updating (and training occurs, for the
// training set
resetNetwork();
calculateOutputs();
double tempRate = m_learningRate * m_currentInstance.weight();
if (m_decay) {
tempRate /= m_epoch;
}
right += (calculateErrors() / m_instances.numClasses())
* m_currentInstance.weight();
updateNetworkWeights(tempRate, m_momentum);
}
}
right /= totalWeight;
if (Double.isInfinite(right) || Double.isNaN(right)) {
if ((!m_reset) || (originalFormatData == null)){
m_instances = null;
throw new Exception("Network cannot train. Try restarting with a smaller learning rate.");
} else {
// reset the network if possible
if (m_learningRate <= Utils.SMALL) {
throw new IllegalStateException("Learning rate got too small ("
+ m_learningRate + " <= " + Utils.SMALL + ")!");
}
double origRate = m_learningRate; // only used for when reset
m_learningRate /= 2;
buildClassifier(originalFormatData);
m_learningRate = origRate;
return false;
}
}
// //////////////////////do validation testing if applicable
if (m_valSize != 0) {
right = 0;
if (valSet == null) {
throw new IllegalArgumentException("Trying to use validation set but validation set is null.");
}
for (int nob = 0; nob < valSet.numInstances(); nob++) {
m_currentInstance = valSet.instance(nob);
if (!m_currentInstance.classIsMissing()) {
// this is where the network updating occurs, for the validation set
resetNetwork();
calculateOutputs();
right += (calculateErrors() / valSet.numClasses()) * m_currentInstance.weight();
// note 'right' could be calculated here just using
// the calculate output values. This would be faster.
// be less modular
}
}
if (right < lastRight) {
if (right < bestError) {
bestError = right;
// save the network weights at this point
for (int noc = 0; noc < m_numClasses; noc++) {
m_outputs[noc].saveWeights();
}
driftOff = 0;
}
} else {
driftOff++;
}
lastRight = right;
if (driftOff > m_driftThreshold || m_epoch + 1 >= m_numEpochs) {
for (int noc = 0; noc < m_numClasses; noc++) {
m_outputs[noc].restoreWeights();
}
m_accepted = true;
}
right /= totalValWeight;
}
m_error = right;
// shows what the neuralnet is upto if a gui exists.
updateDisplay();
// This junction controls what state the gui is in at the end of each
// epoch, Such as if it is paused, if it is resumable etc...
if (m_gui) {
while ((m_stopIt || (m_epoch >= m_numEpochs && m_valSize == 0)) && !m_accepted) {
m_stopIt = true;
m_stopped = true;
if (m_epoch >= m_numEpochs && m_valSize == 0) {
m_controlPanel.m_startStop.setEnabled(false);
} else {
m_controlPanel.m_startStop.setEnabled(true);
}
m_controlPanel.m_startStop.setText("Start");
m_controlPanel.m_startStop.setActionCommand("Start");
m_controlPanel.m_changeEpochs.setEnabled(true);
m_controlPanel.m_changeLearning.setEnabled(true);
m_controlPanel.m_changeMomentum.setEnabled(true);
blocker(true);
if (m_numeric) {
setEndsToLinear();
}
}
m_controlPanel.m_changeEpochs.setEnabled(false);
m_controlPanel.m_changeLearning.setEnabled(false);
m_controlPanel.m_changeMomentum.setEnabled(false);
m_stopped = false;
// if the network has been accepted stop the training loop
if (m_accepted) {
return false;
}
}
if (m_accepted) {
return false;
}
if (m_epoch < m_numEpochs) {
return true; // We can keep iterating
} else {
return false;
}
}
/**
* Signal end of iterating, useful for any house-keeping/cleanup
*
* @exception Exception if cleanup fails
*/
public void done() throws Exception {
if (m_gui) {
m_win.dispose();
m_controlPanel = null;
m_nodePanel = null;
}
if (!m_useDefaultModel) {
m_instances = new Instances(m_instances, 0);
}
m_currentInstance = null;
originalFormatData = null;
}
/**
* Call this function to build and train a neural network for the training
* data provided.
*
* @param i The training data.
* @throws Exception if can't build classification properly.
*/
@Override
public void buildClassifier(Instances i) throws Exception {
// Initialize classifier
initializeClassifier(i);
// For the given number of iterations
while (next()) {
}
// Clean up
done();
}
/**
* Call this function to predict the class of an instance once a
* classification model has been built with the buildClassifier call.
*
* @param i The instance to classify.
* @return A double array filled with the probabilities of each class type.
* @throws Exception if can't classify instance.
*/
@Override
public double[] distributionForInstance(Instance i) throws Exception {
// default model?
if (m_useDefaultModel) {
return m_ZeroR.distributionForInstance(i);
}
if (m_useNomToBin) {
m_nominalToBinaryFilter.input(i);
m_currentInstance = m_nominalToBinaryFilter.output();
} else {
m_currentInstance = i;
}
// Make a copy of the instance so that it isn't modified
m_currentInstance = (Instance) m_currentInstance.copy();
if (m_normalizeAttributes) {
double[] instance = new double[m_currentInstance.numAttributes()];
for (int noa = 0; noa < m_instances.numAttributes(); noa++) {
if (noa != m_instances.classIndex()) {
if (m_attributeRanges[noa] != 0) {
instance[noa] = (m_currentInstance.value(noa) - m_attributeBases[noa]) / m_attributeRanges[noa];
} else {
instance[noa] = m_currentInstance.value(noa) - m_attributeBases[noa];
}
} else {
instance[noa] = m_currentInstance.value(noa);
}
}
m_currentInstance = new DenseInstance(m_currentInstance.weight(), instance);
m_currentInstance.setDataset(m_instances);
}
resetNetwork();
// since all the output values are needed.
// They are calculated manually here and the values collected.
double[] theArray = new double[m_numClasses];
for (int noa = 0; noa < m_numClasses; noa++) {
theArray[noa] = m_outputs[noa].outputValue(true);
}
if (m_instances.classAttribute().isNumeric()) {
return theArray;
}
// now normalize the array
double count = 0;
for (int noa = 0; noa < m_numClasses; noa++) {
count += theArray[noa];
}
if (count <= 0) {
return m_ZeroR.distributionForInstance(i);
}
for (int noa = 0; noa < m_numClasses; noa++) {
theArray[noa] /= count;
}
return theArray;
}
/**
* Returns an enumeration describing the available options.
*
* @return an enumeration of all the available options.
*/
@Override
public Enumeration<Option> listOptions() {
Vector<Option> newVector = new Vector<Option>(14);
newVector.addElement(new Option(
"\tLearning Rate for the backpropagation algorithm.\n"
+ "\t(Value should be between 0 - 1, Default = 0.3).", "L", 1,
"-L <learning rate>"));
newVector.addElement(new Option(
"\tMomentum Rate for the backpropagation algorithm.\n"
+ "\t(Value should be between 0 - 1, Default = 0.2).", "M", 1,
"-M <momentum>"));
newVector.addElement(new Option("\tNumber of epochs to train through.\n"
+ "\t(Default = 500).", "N", 1, "-N <number of epochs>"));
newVector.addElement(new Option(
"\tPercentage size of validation set to use to terminate\n"
+ "\ttraining (if this is non zero it can pre-empt num of epochs.\n"
+ "\t(Value should be between 0 - 100, Default = 0).", "V", 1,
"-V <percentage size of validation set>"));
newVector.addElement(new Option(
"\tThe value used to seed the random number generator\n"
+ "\t(Value should be >= 0 and and a long, Default = 0).", "S", 1,
"-S <seed>"));
newVector.addElement(new Option(
"\tThe consequetive number of errors allowed for validation\n"
+ "\ttesting before the netwrok terminates.\n"
+ "\t(Value should be > 0, Default = 20).", "E", 1,
"-E <threshold for number of consequetive errors>"));
newVector.addElement(new Option("\tGUI will be opened.\n"
+ "\t(Use this to bring up a GUI).", "G", 0, "-G"));
newVector.addElement(new Option(
"\tAutocreation of the network connections will NOT be done.\n"
+ "\t(This will be ignored if -G is NOT set)", "A", 0, "-A"));
newVector.addElement(new Option(
"\tA NominalToBinary filter will NOT automatically be used.\n"
+ "\t(Set this to not use a NominalToBinary filter).", "B", 0, "-B"));
newVector.addElement(new Option(
"\tThe hidden layers to be created for the network.\n"
+ "\t(Value should be a list of comma separated Natural \n"
+ "\tnumbers or the letters 'a' = (attribs + classes) / 2, \n"
+ "\t'i' = attribs, 'o' = classes, 't' = attribs .+ classes)\n"
+ "\tfor wildcard values, Default = a).", "H", 1,
"-H <comma seperated numbers for nodes on each layer>"));
newVector.addElement(new Option(
"\tNormalizing a numeric class will NOT be done.\n"
+ "\t(Set this to not normalize the class if it's numeric).", "C", 0,
"-C"));
newVector.addElement(new Option(
"\tNormalizing the attributes will NOT be done.\n"
+ "\t(Set this to not normalize the attributes).", "I", 0, "-I"));
newVector.addElement(new Option(
"\tReseting the network will NOT be allowed.\n"
+ "\t(Set this to not allow the network to reset).", "R", 0, "-R"));
newVector.addElement(new Option("\tLearning rate decay will occur.\n"
+ "\t(Set this to cause the learning rate to decay).", "D", 0, "-D"));
newVector.addAll(Collections.list(super.listOptions()));
return newVector.elements();
}
/**
* Parses a given list of options.
* <p/>
*
* <!-- options-start --> Valid options are:
* <p/>
*
* <pre>
* -L <learning rate>
* Learning Rate for the backpropagation algorithm.
* (Value should be between 0 - 1, Default = 0.3).
* </pre>
*
* <pre>
* -M <momentum>
* Momentum Rate for the backpropagation algorithm.
* (Value should be between 0 - 1, Default = 0.2).
* </pre>
*
* <pre>
* -N <number of epochs>
* Number of epochs to train through.
* (Default = 500).
* </pre>
*
* <pre>
* -V <percentage size of validation set>
* Percentage size of validation set to use to terminate
* training (if this is non zero it can pre-empt num of epochs.
* (Value should be between 0 - 100, Default = 0).
* </pre>
*
* <pre>
* -S <seed>
* The value used to seed the random number generator
* (Value should be >= 0 and and a long, Default = 0).
* </pre>
*
* <pre>
* -E <threshold for number of consequetive errors>
* The consequetive number of errors allowed for validation
* testing before the netwrok terminates.
* (Value should be > 0, Default = 20).
* </pre>
*
* <pre>
* -G
* GUI will be opened.
* (Use this to bring up a GUI).
* </pre>
*
* <pre>
* -A
* Autocreation of the network connections will NOT be done.
* (This will be ignored if -G is NOT set)
* </pre>
*
* <pre>
* -B
* A NominalToBinary filter will NOT automatically be used.
* (Set this to not use a NominalToBinary filter).
* </pre>
*
* <pre>
* -H <comma seperated numbers for nodes on each layer>
* The hidden layers to be created for the network.
* (Value should be a list of comma separated Natural
* numbers or the letters 'a' = (attribs + classes) / 2,
* 'i' = attribs, 'o' = classes, 't' = attribs .+ classes)
* for wildcard values, Default = a).
* </pre>
*
* <pre>
* -C
* Normalizing a numeric class will NOT be done.
* (Set this to not normalize the class if it's numeric).
* </pre>
*
* <pre>
* -I
* Normalizing the attributes will NOT be done.
* (Set this to not normalize the attributes).
* </pre>
*
* <pre>
* -R
* Reseting the network will NOT be allowed.
* (Set this to not allow the network to reset).
* </pre>
*
* <pre>
* -D
* Learning rate decay will occur.
* (Set this to cause the learning rate to decay).
* </pre>
*
* <!-- options-end -->
*
* @param options the list of options as an array of strings
* @throws Exception if an option is not supported
*/
@Override
public void setOptions(String[] options) throws Exception {
// the defaults can be found here!!!!
String learningString = Utils.getOption('L', options);
if (learningString.length() != 0) {
setLearningRate((new Double(learningString)).doubleValue());
} else {
setLearningRate(0.3);
}
String momentumString = Utils.getOption('M', options);
if (momentumString.length() != 0) {
setMomentum((new Double(momentumString)).doubleValue());
} else {
setMomentum(0.2);
}
String epochsString = Utils.getOption('N', options);
if (epochsString.length() != 0) {
setTrainingTime(Integer.parseInt(epochsString));
} else {
setTrainingTime(500);
}
String valSizeString = Utils.getOption('V', options);
if (valSizeString.length() != 0) {
setValidationSetSize(Integer.parseInt(valSizeString));
} else {
setValidationSetSize(0);
}
String seedString = Utils.getOption('S', options);
if (seedString.length() != 0) {
setSeed(Integer.parseInt(seedString));
} else {
setSeed(0);
}
String thresholdString = Utils.getOption('E', options);
if (thresholdString.length() != 0) {
setValidationThreshold(Integer.parseInt(thresholdString));
} else {
setValidationThreshold(20);
}
String hiddenLayers = Utils.getOption('H', options);
if (hiddenLayers.length() != 0) {
setHiddenLayers(hiddenLayers);
} else {
setHiddenLayers("a");
}
if (Utils.getFlag('G', options)) {
setGUI(true);
} else {
setGUI(false);
} // small note. since the gui is the only option that can change the other
// options this should be set first to allow the other options to set
// properly
if (Utils.getFlag('A', options)) {
setAutoBuild(false);
} else {
setAutoBuild(true);
}
if (Utils.getFlag('B', options)) {
setNominalToBinaryFilter(false);
} else {
setNominalToBinaryFilter(true);
}
if (Utils.getFlag('C', options)) {
setNormalizeNumericClass(false);
} else {
setNormalizeNumericClass(true);
}
if (Utils.getFlag('I', options)) {
setNormalizeAttributes(false);
} else {
setNormalizeAttributes(true);
}
if (Utils.getFlag('R', options)) {
setReset(false);
} else {
setReset(true);
}
if (Utils.getFlag('D', options)) {
setDecay(true);
} else {
setDecay(false);
}
super.setOptions(options);
Utils.checkForRemainingOptions(options);
}
/**
* Gets the current settings of NeuralNet.
*
* @return an array of strings suitable for passing to setOptions()
*/
@Override
public String[] getOptions() {
Vector<String> options = new Vector<String>();
options.add("-L");
options.add("" + getLearningRate());
options.add("-M");
options.add("" + getMomentum());
options.add("-N");
options.add("" + getTrainingTime());
options.add("-V");
options.add("" + getValidationSetSize());
options.add("-S");
options.add("" + getSeed());
options.add("-E");
options.add("" + getValidationThreshold());
options.add("-H");
options.add(getHiddenLayers());
if (getGUI()) {
options.add("-G");
}
if (!getAutoBuild()) {
options.add("-A");
}
if (!getNominalToBinaryFilter()) {
options.add("-B");
}
if (!getNormalizeNumericClass()) {
options.add("-C");
}
if (!getNormalizeAttributes()) {
options.add("-I");
}
if (!getReset()) {
options.add("-R");
}
if (getDecay()) {
options.add("-D");
}
Collections.addAll(options, super.getOptions());
return options.toArray(new String[0]);
}
/**
* @return string describing the model.
*/
@Override
public String toString() {
// only ZeroR model?
if (m_useDefaultModel) {
StringBuffer buf = new StringBuffer();
buf.append(this.getClass().getName().replaceAll(".*\\.", "") + "\n");
buf.append(this.getClass().getName().replaceAll(".*\\.", "")
.replaceAll(".", "=")
+ "\n\n");
buf
.append("Warning: No model could be built, hence ZeroR model is used:\n\n");
buf.append(m_ZeroR.toString());
return buf.toString();
}
StringBuffer model = new StringBuffer(m_neuralNodes.length * 100);
// just a rough size guess
NeuralNode con;
double[] weights;
NeuralConnection[] inputs;
for (NeuralConnection m_neuralNode : m_neuralNodes) {
con = (NeuralNode) m_neuralNode; // this would need a change
// for items other than nodes!!!
weights = con.getWeights();
inputs = con.getInputs();
if (con.getMethod() instanceof SigmoidUnit) {
model.append("Sigmoid ");
} else if (con.getMethod() instanceof LinearUnit) {
model.append("Linear ");
}
model.append("Node " + con.getId() + "\n Inputs Weights\n");
model.append(" Threshold " + weights[0] + "\n");
for (int nob = 1; nob < con.getNumInputs() + 1; nob++) {
if ((inputs[nob - 1].getType() & NeuralConnection.PURE_INPUT) == NeuralConnection.PURE_INPUT) {
model.append(" Attrib "
+ m_instances.attribute(((NeuralEnd) inputs[nob - 1]).getLink())
.name() + " " + weights[nob] + "\n");
} else {
model.append(" Node " + inputs[nob - 1].getId() + " "
+ weights[nob] + "\n");
}
}
}
// now put in the ends
for (NeuralEnd m_output : m_outputs) {
inputs = m_output.getInputs();
model.append("Class "
+ m_instances.classAttribute().value(m_output.getLink())
+ "\n Input\n");
for (int nob = 0; nob < m_output.getNumInputs(); nob++) {
if ((inputs[nob].getType() & NeuralConnection.PURE_INPUT) == NeuralConnection.PURE_INPUT) {
model.append(" Attrib "
+ m_instances.attribute(((NeuralEnd) inputs[nob]).getLink()).name()
+ "\n");
} else {
model.append(" Node " + inputs[nob].getId() + "\n");
}
}
}
return model.toString();
}
/**
* This will return a string describing the classifier.
*
* @return The string.
*/
public String globalInfo() {
return "A Classifier that uses backpropagation to classify instances.\n"
+ "This network can be built by hand, created by an algorithm or both. "
+ "The network can also be monitored and modified during training time. "
+ "The nodes in this network are all sigmoid (except for when the class "
+ "is numeric in which case the the output nodes become unthresholded "
+ "linear units).";
}
/**
* @return a string to describe the learning rate option.
*/
public String learningRateTipText() {
return "The amount the" + " weights are updated.";
}
/**
* @return a string to describe the momentum option.
*/
public String momentumTipText() {
return "Momentum applied to the weights during updating.";
}
/**
* @return a string to describe the AutoBuild option.
*/
public String autoBuildTipText() {
return "Adds and connects up hidden layers in the network.";
}
/**
* @return a string to describe the random seed option.
*/
public String seedTipText() {
return "Seed used to initialise the random number generator."
+ "Random numbers are used for setting the initial weights of the"
+ " connections betweem nodes, and also for shuffling the training data.";
}
/**
* @return a string to describe the validation threshold option.
*/
public String validationThresholdTipText() {
return "Used to terminate validation testing."
+ "The value here dictates how many times in a row the validation set"
+ " error can get worse before training is terminated.";
}
/**
* @return a string to describe the GUI option.
*/
public String GUITipText() {
return "Brings up a gui interface."
+ " This will allow the pausing and altering of the nueral network"
+ " during training.\n\n"
+ "* To add a node left click (this node will be automatically selected,"
+ " ensure no other nodes were selected).\n"
+ "* To select a node left click on it either while no other node is"
+ " selected or while holding down the control key (this toggles that"
+ " node as being selected and not selected.\n"
+ "* To connect a node, first have the start node(s) selected, then click"
+ " either the end node or on an empty space (this will create a new node"
+ " that is connected with the selected nodes). The selection status of"
+ " nodes will stay the same after the connection. (Note these are"
+ " directed connections, also a connection between two nodes will not"
+ " be established more than once and certain connections that are"
+ " deemed to be invalid will not be made).\n"
+ "* To remove a connection select one of the connected node(s) in the"
+ " connection and then right click the other node (it does not matter"
+ " whether the node is the start or end the connection will be removed"
+ ").\n"
+ "* To remove a node right click it while no other nodes (including it)"
+ " are selected. (This will also remove all connections to it)\n."
+ "* To deselect a node either left click it while holding down control,"
+ " or right click on empty space.\n"
+ "* The raw inputs are provided from the labels on the left.\n"
+ "* The red nodes are hidden layers.\n"
+ "* The orange nodes are the output nodes.\n"
+ "* The labels on the right show the class the output node represents."
+ " Note that with a numeric class the output node will automatically be"
+ " made into an unthresholded linear unit.\n\n"
+ "Alterations to the neural network can only be done while the network"
+ " is not running, This also applies to the learning rate and other"
+ " fields on the control panel.\n\n"
+ "* You can accept the network as being finished at any time.\n"
+ "* The network is automatically paused at the beginning.\n"
+ "* There is a running indication of what epoch the network is up to"
+ " and what the (rough) error for that epoch was (or for"
+ " the validation if that is being used). Note that this error value"
+ " is based on a network that changes as the value is computed."
+ " (also depending on whether"
+ " the class is normalized will effect the error reported for numeric"
+ " classes.\n"
+ "* Once the network is done it will pause again and either wait to be"
+ " accepted or trained more.\n\n"
+ "Note that if the gui is not set the network will not require any"
+ " interaction.\n";
}
/**
* @return a string to describe the validation size option.
*/
public String validationSetSizeTipText() {
return "The percentage size of the validation set."
+ "(The training will continue until it is observed that"
+ " the error on the validation set has been consistently getting"
+ " worse, or if the training time is reached).\n"
+ "If This is set to zero no validation set will be used and instead"
+ " the network will train for the specified number of epochs.";
}
/**
* @return a string to describe the learning rate option.
*/
public String trainingTimeTipText() {
return "The number of epochs to train through."
+ " If the validation set is non-zero then it can terminate the network"
+ " early";
}
/**
* @return a string to describe the nominal to binary option.
*/
public String nominalToBinaryFilterTipText() {
return "This will preprocess the instances with the filter."
+ " This could help improve performance if there are nominal attributes"
+ " in the data.";
}
/**
* @return a string to describe the hidden layers in the network.
*/
public String hiddenLayersTipText() {
return "This defines the hidden layers of the neural network."
+ " This is a list of positive whole numbers. 1 for each hidden layer."
+ " Comma seperated. To have no hidden layers put a single 0 here."
+ " This will only be used if autobuild is set. There are also wildcard"
+ " values 'a' = (attribs + classes) / 2, 'i' = attribs, 'o' = classes"
+ " , 't' = attribs + classes.";
}
/**
* @return a string to describe the nominal to binary option.
*/
public String normalizeNumericClassTipText() {
return "This will normalize the class if it's numeric."
+ " This could help improve performance of the network, It normalizes"
+ " the class to be between -1 and 1. Note that this is only internally"
+ ", the output will be scaled back to the original range.";
}
/**
* @return a string to describe the nominal to binary option.
*/
public String normalizeAttributesTipText() {
return "This will normalize the attributes."
+ " This could help improve performance of the network."
+ " This is not reliant on the class being numeric. This will also"
+ " normalize nominal attributes as well (after they have been run"
+ " through the nominal to binary filter if that is in use) so that the"
+ " nominal values are between -1 and 1";
}
/**
* @return a string to describe the Reset option.
*/
public String resetTipText() {
return "This will allow the network to reset with a lower learning rate."
+ " If the network diverges from the answer this will automatically"
+ " reset the network with a lower learning rate and begin training"
+ " again. This option is only available if the gui is not set. Note"
+ " that if the network diverges but isn't allowed to reset it will"
+ " fail the training process and return an error message.";
}
/**
* @return a string to describe the Decay option.
*/
public String decayTipText() {
return "This will cause the learning rate to decrease."
+ " This will divide the starting learning rate by the epoch number, to"
+ " determine what the current learning rate should be. This may help"
+ " to stop the network from diverging from the target output, as well"
+ " as improve general performance. Note that the decaying learning"
+ " rate will not be shown in the gui, only the original learning rate"
+ ". If the learning rate is changed in the gui, this is treated as the"
+ " starting learning rate.";
}
/**
* Returns the revision string.
*
* @return the revision
*/
@Override
public String getRevision() {
return RevisionUtils.extract("$Revision: 14497 $");
}
}
| [
"[email protected]"
] | |
400839822eaee8ff33858b2fc5d72039be8a5f80 | 5ecc519431b0ccfd9895306c79dab89288d75ec9 | /JAVA/basicAlgrithms/ShellSort.java | 647c07bd5c47542b0942c4ac56cc4596f1dc09a7 | [] | no_license | changlongG/Algorithms | d07b3e0eccbf015a543d96ae0d777dfcbd144543 | 89316f5260996d4cacba0d42182026387add1ef9 | refs/heads/master | 2020-04-17T10:47:02.810092 | 2019-03-13T02:47:08 | 2019-03-13T02:47:08 | 166,513,811 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 790 | java | package algorithm;
public class ShellSort {
public static int[] shellSort(int[] array) {
int increment = array.length / 3;
while (true) {
// System.out.println(increment);
int index = 0;
while (index < array.length - increment) {
for (int i = index; i >= 0 && i + increment < array.length; i--) {
if (array[i] > array[i + increment]) {
int temp = array[i];
array[i] = array[i + increment];
array[i + increment] = temp;
}
}
index++;
}
if (increment == 1) {
break;
}
increment = increment / 3;
}
return array;
}
public static void main(String[] args) {
int[] array = { 4, 5, 3, 7, 9, 5, 8, 11, -1, 9, 2, 5, 11, 29, 4 };
array = shellSort(array);
for (int i : array) {
System.out.print(i + ", ");
}
}
}
| [
"[email protected]"
] | |
bd622e13b39bf8b37efd65b9248fe31d666abd55 | bc6ab85b295e6f6a50452037f79bcf492557d3b5 | /src/main/java/com/nel/chan/dsalgo/array/rearrange/MultiArrayReverse.java | 1809f88925e73c96d2c371fb849f538e819b9d08 | [] | no_license | chandrakanth-nelge/dsalgo | 23ce2c91031667736190fb9b09e386967e65076b | 83b479b66988d788c941f4e6763f10100568cc20 | refs/heads/master | 2022-05-01T20:10:17.551085 | 2022-03-16T07:24:34 | 2022-03-16T07:24:34 | 232,068,313 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,336 | java | package com.nel.chan.dsalgo.array.rearrange;
import java.util.Arrays;
import java.util.Scanner;
public class MultiArrayReverse {
static Scanner in = new Scanner(System.in);
public static void main(String[] args) {
int rowCount = getRowCount();
int colCount = getColCount();
int[][] mulDimenArr = readMultiDimensionalArray(rowCount, colCount);
System.out.println();
printMultiDimensionalArray(mulDimenArr, rowCount, colCount);
System.out.println();
reverseMultiDimensionalArray(mulDimenArr, rowCount, colCount);
System.out.println();
in.close();
}
private static int[][] readMultiDimensionalArray(int rowCount, int colCount) {
System.out.println("Enter multi dimensional array elements");
int[][] mulDimenArr = new int[rowCount][colCount];
for (int i = 0; i < rowCount; i++) {
for (int j = 0; j < colCount; j++) {
mulDimenArr[i][j] = in.nextInt();
}
}
return mulDimenArr;
}
private static void printMultiDimensionalArray(int[][] mulDimenArr, int rowCount, int colCount) {
System.out.println("Printing multi dimensional array elements");
for (int i = 0; i < rowCount; i++) {
System.out.print("[");
for (int j = 0; j < colCount; j++) {
if (j == colCount - 1) {
System.out.print(mulDimenArr[i][j]);
} else {
System.out.print(mulDimenArr[i][j] + ", ");
}
}
System.out.print("]");
System.out.println();
}
}
private static void reverseMultiDimensionalArray(int[][] mulDimenArr, int rowCount, int colCount) {
System.out.println("Reversing multi dimensional array");
for (int i = 0; i < colCount; i++) {
System.out.print("[");
for (int j = 0; j < rowCount; j++) {
if (j == rowCount - 1) {
System.out.print(mulDimenArr[j][i]);
} else {
System.out.print(mulDimenArr[j][i] + ", ");
}
}
System.out.print("]");
System.out.println();
}
}
@SuppressWarnings("unused")
private static void printMultiDimensionalArray(int[][] mulDimenArr) {
System.out.println("Printing multi dimensional array elements");
for (int[] rowArr : mulDimenArr) {
System.out.println(Arrays.toString(rowArr));
}
}
private static int getRowCount() {
System.out.println("Enetr row count");
return in.nextInt();
}
private static int getColCount() {
System.out.println("Enetr column count");
return in.nextInt();
}
} | [
"[email protected]"
] | |
cefc0542b22443e91915396f310ad2f081a9346a | 666f226474bbf225646c1e4d56d52612c8b50aab | /app/src/main/java/com/aou/cheba/Activity/HuaTi_Activity.java | 044c7ffa4bd27e3220fdbf37da05c686570e295a | [] | no_license | Single-Shadow/CheBa_new | cbea8900b0b1bf1f9321f398e6426250a08be585 | aad5afa6f225af5be0741270f3482cff4fcde7a6 | refs/heads/master | 2021-05-05T03:56:38.274045 | 2018-01-23T02:26:26 | 2018-01-23T02:26:26 | 118,542,195 | 2 | 0 | null | null | null | null | UTF-8 | Java | false | false | 72,234 | java | package com.aou.cheba.Activity;
import android.animation.ObjectAnimator;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.aou.cheba.Fragment.Me_Fragment;
import com.aou.cheba.Fragment_new.CheYouQuan_Fragment;
import com.aou.cheba.Fragment_new.ShaiChe_Fragment;
import com.aou.cheba.Fragment_new.WenDa_Fragment;
import com.aou.cheba.Fragment_new.ZiXun_Fragment;
import com.aou.cheba.R;
import com.aou.cheba.bean.MyCode1;
import com.aou.cheba.bean.MyCodeInfo;
import com.aou.cheba.bean.MyCode_data;
import com.aou.cheba.bean.MyCode_pinglun;
import com.aou.cheba.bean.MyCode_uplist;
import com.aou.cheba.utils.Data_Util;
import com.aou.cheba.utils.SPUtils;
import com.aou.cheba.utils.SerializeUtils;
import com.aou.cheba.utils.TimeUtil;
import com.aou.cheba.utils.Utils;
import com.aou.cheba.view.LoadMoreListView;
import com.aou.cheba.view.MyListView;
import com.aou.cheba.view.MyToast;
import com.aou.cheba.view.RefreshAndLoadMoreView;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import net.qiujuer.genius.blur.StackBlur;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import cn.sharesdk.onekeyshare.OnekeyShare;
import de.hdodenhof.circleimageview.CircleImageView;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
/**
* Created by Administrator on 2016/11/29.
*/
public class HuaTi_Activity extends SwipeBackActivity implements View.OnClickListener {
private ImageView finish;
private Button fabiao;
private EditText et;
private String biaoti;
private LoadMoreListView mLoadMoreListView;
private RefreshAndLoadMoreView mRefreshAndLoadMoreView;
private MyListView lv;
private int position_cheka;
private ImageView iv_beijing;
private TextView tv_nickname;
private TextView tv_time;
private CircleImageView iv_head;
private TextView tv_titlfe;
private TextView tv_conftent;
private LinearLayout ll_love;
private ImageView iv_1;
private ImageView iv_2;
private ImageView iv_3;
private ImageView iv_4;
private ImageView iv_5;
private ImageView iv_6;
private ImageView iv_7;
private List<MyCode_uplist.ObjBean> obj = new ArrayList<>();
private List<MyCode_pinglun.ObjBean> comment_list = new ArrayList<>();
private int page = 1;
private Long isson = null;
private RelativeLayout rl_wai;
private LinearLayout rl_xia;
private EditText tv_huitie2;
private String s;
private ImageView iv_xin;
private ImageView iv_shoucang;
private ImageView iv_fenxiang;
private MyCode_data.ObjBean ser = new MyCode_data.ObjBean();
private ImageView iv_gender;
private boolean isclickson;
private LinearLayout ll_hide;
private WebView web;
private TextView btn_guanzhu;
private TextView tv_dizhi;
private LinearLayout ll_suiyi;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.huati_activity);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
ser = (MyCode_data.ObjBean) getIntent().getSerializableExtra("ser");
position_cheka = getIntent().getIntExtra("position", 0);
findViewById();
getHead();
inithttp_getpinglun_list(1);
}
private void initData() {
adapter = new MyAdapter();
mLoadMoreListView.setAdapter(adapter);
mRefreshAndLoadMoreView.setLoadMoreListView(mLoadMoreListView);
mLoadMoreListView.setRefreshAndLoadMoreView(mRefreshAndLoadMoreView);
mRefreshAndLoadMoreView.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
page = 1;
inithttp_getpinglun_list(page);
}
});
mLoadMoreListView.setOnLoadMoreListener(new LoadMoreListView.OnLoadMoreListener() {
@Override
public void onLoadMore() {
page += 1;
inithttp_getpinglun_list(page);
}
});
mLoadMoreListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.i("test", "键盘");
if (position != 0) {
isclickson = true;
h.postDelayed(new Runnable() {
@Override
public void run() {
isclickson = false;
}
}, 500);
//打开软键盘
InputMethodManager imm = (InputMethodManager) HuaTi_Activity.this.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
// 获取编辑框焦点
tv_huitie2.setFocusable(true);
tv_huitie2.setFocusableInTouchMode(true);
tv_huitie2.requestFocus();
/* InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(tv_huitie2, InputMethodManager.SHOW_FORCED);*/
// ((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE)).showSoftInput(tv_huitie2,InputMethodManager.SHOW_FORCED);
isson = comment_list.get(position - 1).getId();
s = "回复" + comment_list.get(position - 1).getNickname();
}
}
});
}
private boolean isenter = false;
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.iv_finish:
if (!isenter) {
isenter = true;
h.postDelayed(new Runnable() {
@Override
public void run() {
isenter = false;
}
}, 500);
finish();
}
break;
case R.id.tv_zan:
int tag = (int) v.getTag();
if (TextUtils.isEmpty(SPUtils.getString(HuaTi_Activity.this, "token"))) {
finish();
startActivity(new Intent(HuaTi_Activity.this, Login_Activity.class));
MyToast.showToast(HuaTi_Activity.this, "请先登录");
} else {
if (comment_list.get(tag).getUped() == null || !(comment_list.get(tag).getUped() == Integer.parseInt(SPUtils.getString(HuaTi_Activity.this, "uid")))) {
inithttp_pl_up(tag);
}
}
break;
case R.id.btn_guanzhu:
if (!isenter) {
isenter = true;
h.postDelayed(new Runnable() {
@Override
public void run() {
isenter = false;
}
}, 500);
if (TextUtils.isEmpty(SPUtils.getString(HuaTi_Activity.this, "token"))) {
finish();
startActivity(new Intent(HuaTi_Activity.this, Login_Activity.class));
MyToast.showToast(HuaTi_Activity.this, "请先登录");
} else {
if (ser.isFollowed()) {
MyToast.showToast(HuaTi_Activity.this, "已关注");
} else {
inithttp_guanzhu(ser.getUid(), SPUtils.getString(HuaTi_Activity.this, "token"), position_cheka);
}
}
}
break;
case R.id.iv_head:
if (!isenter) {
isenter = true;
h.postDelayed(new Runnable() {
@Override
public void run() {
isenter = false;
}
}, 500);
Intent intent = new Intent(HuaTi_Activity.this, Other_Activity.class);
intent.putExtra("uid", ser.getUid());
startActivity(intent);
}
break;
case R.id.ll_love:
if (!isenter) {
isenter = true;
h.postDelayed(new Runnable() {
@Override
public void run() {
isenter = false;
}
}, 500);
Intent intent1 = new Intent(HuaTi_Activity.this, Love_Activity.class);
intent1.putExtra("id", ser.getId());
startActivity(intent1);
}
break;
case R.id.tv_huitie2:
break;
case R.id.iv_xin:
if (!isenter) {
isenter = true;
h.postDelayed(new Runnable() {
@Override
public void run() {
isenter = false;
}
}, 500);
if (TextUtils.isEmpty(SPUtils.getString(HuaTi_Activity.this, "token"))) {
finish();
startActivity(new Intent(HuaTi_Activity.this, Login_Activity.class));
MyToast.showToast(HuaTi_Activity.this, "请先登录");
} else {
if (ser.isUped()) {
MyToast.showToast(HuaTi_Activity.this, "您已经赞过了");
} else {
inithttp_up(position_cheka);
}
}
}
break;
case R.id.iv_shoucang:
if (!isenter) {
isenter = true;
h.postDelayed(new Runnable() {
@Override
public void run() {
isenter = false;
}
}, 500);
if (TextUtils.isEmpty(SPUtils.getString(HuaTi_Activity.this, "token"))) {
finish();
startActivity(new Intent(HuaTi_Activity.this, Login_Activity.class));
MyToast.showToast(HuaTi_Activity.this, "请先登录");
} else {
if (ser.isCollected()) {
inithttp_delshoucang(ser.getId(), SPUtils.getString(HuaTi_Activity.this, "token"), position_cheka);
} else {
inithttp_shoucang(ser.getId(), SPUtils.getString(HuaTi_Activity.this, "token"), position_cheka);
}
}
}
break;
case R.id.iv_fenxiang:
if (!isenter) {
isenter = true;
h.postDelayed(new Runnable() {
@Override
public void run() {
isenter = false;
}
}, 500);
OnekeyShare oks = new OnekeyShare();
// 关闭sso授权
oks.disableSSOWhenAuthorize();
// 分享时Notification的图标和文字 2.5.9以后的版本不调用此方法
// oks.setNotification(R.drawable.ic_launcher,
// getString(R.string.app_name));
// title标题,印象笔记、邮箱、信息、微信、人人网和QQ空间使用
oks.setTitle(ser.getTitle());
// titleUrl是标题的网络链接,仅在人人网和QQ空间使用
oks.setTitleUrl("http://www.anou.net.cn/web/share/cbshare.jsp");
// text是分享文本,所有平台都需要这个字段
if (ser.getContent() != null && ser.getContent().length() > 33) {
oks.setText(ser.getContent().substring(33, ser.getContent().length()));
} else {
oks.setText("");
}
// 分享网络图片,新浪微博分享网络图片需要通过审核后申请高级写入接口,否则请注释掉测试新浪微博
if (ser.getPictrue() != null && !TextUtils.isEmpty(ser.getPictrue())) {
oks.setImageUrl(Data_Util.IMG+ser.getPictrue().split(",")[0]);
} else {
oks.setImageUrl("http://www.szcheba.com/CarbarFileServer/download/41fd795ddb0a38421f0269371c516b08");
}
// Log.i("test",list_tucao.get(position).getPictrue().split(",")[0]);
// oks.setImageUrl("http://b248.photo.store.qq.com/psb?/2c280a19-7f4f-4e7d-a168-20d7fd2f70cc/pUL9tktoc3SHsXcU8hba08Tt5pRL2r.6SaZN4imCsls!/b/dCJ805PTDQAA&bo=ngL2AQAAAAABCUU!&rf=viewer_4" + "");
// imagePath是图片的本地路径,Linked-In以外的平台都支持此参数
// oks.setImagePath("/sdcard/test.jpg");//确保SDcard下面存在此张图片
// url仅在微信(包括好友和朋友圈)中使用
oks.setUrl("http://www.anou.net.cn/web/share/cbshare.jsp");
// comment是我对这条分享的评论,仅在人人网和QQ空间使用
oks.setComment("文章的评论");
// site是分享此内容的网站名称,仅在QQ空间使用
oks.setSite("分享内容的地址");
// siteUrl是分享此内容的网站地址,仅在QQ空间使用
oks.setSiteUrl("http://www.anou.net.cn/web/share/cbshare.jsp");
// 启动分享GUI
oks.show(HuaTi_Activity.this);
}
break;
case R.id.tv_publish:
if (!isenter) {
isenter = true;
h.postDelayed(new Runnable() {
@Override
public void run() {
isenter = false;
}
}, 500);
if (TextUtils.isEmpty(SPUtils.getString(HuaTi_Activity.this, "token"))) {
finish();
startActivity(new Intent(HuaTi_Activity.this, Login_Activity.class));
MyToast.showToast(HuaTi_Activity.this, "请先登录");
} else {
String trim = tv_huitie2.getText().toString().trim();
String s = readStream(getResources().openRawResource(R.raw.mingan));
String[] split = s.split(",");
for (int i = 0; i < split.length; i++) {
String x = split[i]; //x为敏感词汇
if (trim.contains(x)) {
trim = trim.replaceAll(x, getXing(x));
}
}
if (TextUtils.isEmpty(trim)) {
} else {
if (isson == null) {
inithttp_tjpl(trim, null);
} else {
inithttp_tjpl(trim, isson);
isson = null;
}
}
}
}
break;
}
}
private String getXing(String f) {
String a = "";
for (int i = 0; i < f.length(); i++) {
a = a + "*";
}
return a;
}
private String readStream(InputStream is) {
// 资源流(GBK汉字码)变为串
String res;
try {
byte[] buf = new byte[is.available()];
is.read(buf);
res = new String(buf, "GBK"); // 必须将GBK码制转成Unicode
is.close();
} catch (Exception e) {
res = "";
}
return res; // 把资源文本文件送到String串中
}
private void inithttp_guanzhu(final long uid, String token, final int position) {
OkHttpClient okHttpClient =
new OkHttpClient.Builder()
.connectTimeout(5000, TimeUnit.SECONDS)//设置连接超时时间
.build();
MediaType JSON = MediaType.parse("application/json; Charset=utf-8");
RequestBody requestBody = RequestBody.create(JSON, "{\"obj\": {\"uid\": " + uid + "},\"token\": \"" + token + "\"}");
//创建一个请求对象
Request request = new Request.Builder()
.url(Data_Util.HttPHEAD + "/Carbar/User!FollowUser.action")
.post(requestBody)
.build();
Call call = okHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
h.post(new Runnable() {
@Override
public void run() {
MyToast.showToast(HuaTi_Activity.this, "连接服务器失败");
}
});
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String res = response.body().string();
Gson gson = new Gson();
final MyCode1 mycode = gson.fromJson(res, MyCode1.class);
h.post(new Runnable() {
@Override
public void run() {
if (0 == mycode.getCode()) {
btn_guanzhu.setVisibility(View.VISIBLE);
btn_guanzhu.setText("已关注");
btn_guanzhu.setTextColor(Color.parseColor("#d9d9d9"));
btn_guanzhu.setBackgroundResource(R.drawable.custom_hui);
btn_guanzhu.setEnabled(false);
if (position >= 0) {
if (ser.getType() == 5) {
new ZiXun_Fragment().list_data.get(position).setFollowed(true);
} else if (ser.getType() == 6) {
new CheYouQuan_Fragment().list_data.get(position).setFollowed(true);
} else if (ser.getType() == 7) {
new ShaiChe_Fragment().list_data.get(position).setFollowed(true);
} else if (ser.getType() == 9) {
new WenDa_Fragment().list_data.get(position).setFollowed(true);
}
}
MyCodeInfo me_mycodes = new Me_Fragment().mycodes;
if (me_mycodes != null&&me_mycodes.getObj()!=null) {
me_mycodes.getObj().setFollowCount(me_mycodes.getObj().getFollowCount() + 1);
}
SPUtils.put(HuaTi_Activity.this, "islogin", true);
MyToast.showToast(HuaTi_Activity.this, "关注成功");
} else if (mycode.getCode() == 4) {
SPUtils.put(HuaTi_Activity.this, "token", "");
MyToast.showToast(HuaTi_Activity.this, "请先登录");
}
}
});
}
});
}
private void inithttp_up(final int position) {
OkHttpClient okHttpClient =
new OkHttpClient.Builder()
.connectTimeout(5000, TimeUnit.SECONDS)//设置连接超时时间
.build();
MediaType JSON = MediaType.parse("application/json; Charset=utf-8");
RequestBody requestBody = RequestBody.create(JSON, "{\"token\":\"" + SPUtils.getString(HuaTi_Activity.this, "token") + "\",\"obj\":{\"id\":\"" + ser.getId() + "\"}}");
String urls = "";
switch (ser.getType()) {
case 5:
urls = "/Carbar/Server!Like.action";
break;
case 6:
urls = "/Carbar/Traffic!Like.action";
break;
case 7:
urls = "/Carbar/ShaiChe!Like.action";
break;
case 9:
urls = "/Carbar/WenDa!Like.action";
break;
}
//创建一个请求对象
Request request = new Request.Builder()
.url(Data_Util.HttPHEAD + urls)
.post(requestBody)
.build();
Call call = okHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
h.post(new Runnable() {
@Override
public void run() {
MyToast.showToast(HuaTi_Activity.this, "连接服务器失败");
}
});
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String res = response.body().string();
Gson gson = new Gson();
final MyCode1 mycode = gson.fromJson(res, MyCode1.class);
h.post(new Runnable() {
@Override
public void run() {
if (mycode.getCode() == 0) {
if (position >= 0) {
if (ser.getType() == 5) {
new ZiXun_Fragment().list_data.get(position).setUpCount(new ZiXun_Fragment().list_data.get(position).getUpCount() + 1);
new ZiXun_Fragment().list_data.get(position).setUped(true);
} else if (ser.getType() == 6) {
new CheYouQuan_Fragment().list_data.get(position).setUpCount(new CheYouQuan_Fragment().list_data.get(position).getUpCount() + 1);
new CheYouQuan_Fragment().list_data.get(position).setUped(true);
} else if (ser.getType() == 7) {
new ShaiChe_Fragment().list_data.get(position).setUpCount(new ShaiChe_Fragment().list_data.get(position).getUpCount() + 1);
new ShaiChe_Fragment().list_data.get(position).setUped(true);
} else if (ser.getType() == 9) {
new WenDa_Fragment().list_data.get(position).setUpCount(new WenDa_Fragment().list_data.get(position).getUpCount() + 1);
new WenDa_Fragment().list_data.get(position).setUped(true);
}
}
ser.setUped(true);
iv_xin.setImageResource(R.mipmap.x_hong);
setResult(55);
/*MyCode_uplist.ObjBean objBean = new MyCode_uplist.ObjBean();
objBean.setHeadImg(SPUtils.getString(HuaTi_Activity.this, "headImage"));
obj.add(0, objBean);
data_up(obj);*/
MyToast.showToast(HuaTi_Activity.this, "赞");
} else if (mycode.getCode() == 4) {
SPUtils.put(HuaTi_Activity.this, "token", "");
MyToast.showToast(HuaTi_Activity.this, "请先登录");
}
}
});
}
});
}
private void inithttp_shoucang(long did, String token, final int position) {
OkHttpClient okHttpClient =
new OkHttpClient.Builder()
.connectTimeout(5000, TimeUnit.SECONDS)//设置连接超时时间
.build();
MediaType JSON = MediaType.parse("application/json; Charset=utf-8");
RequestBody requestBody = RequestBody.create(JSON, "{\"obj\": {\"did\": " + did + "},\"token\": \"" + token + "\"}");
//创建一个请求对象
Request request = new Request.Builder()
.url(Data_Util.HttPHEAD + "/Carbar/User!Collection.action")
.post(requestBody)
.build();
Call call = okHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
h.post(new Runnable() {
@Override
public void run() {
MyToast.showToast(HuaTi_Activity.this, "连接服务器失败");
}
});
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String res = response.body().string();
Gson gson = new Gson();
final MyCode1 mycode = gson.fromJson(res, MyCode1.class);
h.post(new Runnable() {
@Override
public void run() {
if (0 == mycode.getCode()) {
ser.setCollected(true);
if (position >= 0) {
if (ser.getType() == 5) {
new ZiXun_Fragment().list_data.get(position).setCollected(true);
} else if (ser.getType() == 6) {
new CheYouQuan_Fragment().list_data.get(position).setCollected(true);
} else if (ser.getType() == 7) {
new ShaiChe_Fragment().list_data.get(position).setCollected(true);
} else if (ser.getType() == 9) {
new WenDa_Fragment().list_data.get(position).setCollected(true);
}
}
iv_shoucang.setImageResource(R.mipmap.sc_hong);
setResult(55);
MyToast.showToast(HuaTi_Activity.this, "收藏");
} else if (mycode.getCode() == 4) {
SPUtils.put(HuaTi_Activity.this, "token", "");
MyToast.showToast(HuaTi_Activity.this, "请先登录");
}
}
});
}
});
}
private void inithttp_delshoucang(long did, String token, final int position) {
OkHttpClient okHttpClient =
new OkHttpClient.Builder()
.connectTimeout(5000, TimeUnit.SECONDS)//设置连接超时时间
.build();
MediaType JSON = MediaType.parse("application/json; Charset=utf-8");
RequestBody requestBody = RequestBody.create(JSON, "{\"obj\": {\"did\": " + did + "},\"token\": \"" + token + "\"}");
//创建一个请求对象
Request request = new Request.Builder()
.url(Data_Util.HttPHEAD + "/Carbar/User!DelCollection.action")
.post(requestBody)
.build();
Call call = okHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
h.post(new Runnable() {
@Override
public void run() {
MyToast.showToast(HuaTi_Activity.this, "连接服务器失败");
}
});
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String res = response.body().string();
Gson gson = new Gson();
final MyCode1 mycode = gson.fromJson(res, MyCode1.class);
h.post(new Runnable() {
@Override
public void run() {
if (0 == mycode.getCode()) {
ser.setCollected(false);
if (position >= 0) {
if (ser.getType() == 5) {
new ZiXun_Fragment().list_data.get(position).setCollected(false);
} else if (ser.getType() == 6) {
new CheYouQuan_Fragment().list_data.get(position).setCollected(false);
} else if (ser.getType() == 7) {
new ShaiChe_Fragment().list_data.get(position).setCollected(false);
} else if (ser.getType() == 9) {
new WenDa_Fragment().list_data.get(position).setCollected(false);
}
}
iv_shoucang.setImageResource(R.mipmap.sc);
setResult(55);
MyToast.showToast(HuaTi_Activity.this, "取消收藏");
} else if (mycode.getCode() == 4) {
SPUtils.put(HuaTi_Activity.this, "token", "");
MyToast.showToast(HuaTi_Activity.this, "请先登录");
}
}
});
}
});
}
ArrayList<ImageView> list_iv = new ArrayList<>();
boolean isup = false;
private void findViewById() {
rl_wai = (RelativeLayout) findViewById(R.id.rl_wai);
rl_xia = (LinearLayout) findViewById(R.id.rl_xia);
ll_suiyi = (LinearLayout) findViewById(R.id.ll_suiyi);
finish = (ImageView) findViewById(R.id.iv_finish);
iv_xin = (ImageView) findViewById(R.id.iv_xin);
iv_shoucang = (ImageView) findViewById(R.id.iv_shoucang);
iv_fenxiang = (ImageView) findViewById(R.id.iv_fenxiang);
tv_huitie2 = (EditText) findViewById(R.id.tv_huitie2);
fabiao = (Button) findViewById(R.id.tv_publish);
mLoadMoreListView = (LoadMoreListView) findViewById(R.id.load_more_list);
mRefreshAndLoadMoreView = (RefreshAndLoadMoreView) findViewById(R.id.refresh_and_load_more);
finish.setOnClickListener(this);
fabiao.setOnClickListener(this);
// tv_huitie2.setOnClickListener(this);
iv_xin.setOnClickListener(this);
iv_shoucang.setOnClickListener(this);
iv_fenxiang.setOnClickListener(this);
if (ser.isUped()) {
iv_xin.setImageResource(R.mipmap.x_hong);
} else {
iv_xin.setImageResource(R.mipmap.x);
}
if (ser.isCollected()) {
iv_shoucang.setImageResource(R.mipmap.sc_hong);
} else {
iv_shoucang.setImageResource(R.mipmap.sc);
}
//软键盘的弹出监听
controlKeyboardLayout(rl_wai, rl_xia);
rl_wai.getViewTreeObserver().addOnGlobalLayoutListener(
new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
Rect r = new Rect();
rl_wai.getWindowVisibleDisplayFrame(r);
int screenHeight = rl_wai.getRootView()
.getHeight();
int heightDifference = screenHeight - (r.bottom);
if (heightDifference > 200) {
fabiao.setVisibility(View.VISIBLE);
ll_suiyi.setVisibility(View.GONE);
isup = true;
Log.i("test", "弹出键盘");
tv_huitie2.setHint(s);
} else {
if (isup) {
fabiao.setVisibility(View.GONE);
ll_suiyi.setVisibility(View.VISIBLE);
Log.i("test", "键盘收回");
isup = false;
isson = null;
s = "";
tv_huitie2.setText("");
tv_huitie2.setHint("说几句...");
}
}
}
});
}
private int size = 0;
private void controlKeyboardLayout(final View root, final View needToScrollView) {
root.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
private Rect r = new Rect();
@Override
public void onGlobalLayout() {
HuaTi_Activity.this.getWindow().getDecorView().getWindowVisibleDisplayFrame(r);
int screenHeight = HuaTi_Activity.this.getWindow().getDecorView().getRootView().getHeight();
int heightDifference = screenHeight - r.bottom;
if (Math.abs(heightDifference - size) != 0) {
final ObjectAnimator animator = ObjectAnimator.ofFloat(needToScrollView, "translationY", 0, -heightDifference);
size = heightDifference;
animator.setDuration(0);
animator.start();
}
}
});
}
private void getHead() {
View inflate = View.inflate(HuaTi_Activity.this, R.layout.huati_head, null);
mLoadMoreListView.addHeaderView(inflate);
lv = (MyListView) inflate.findViewById(R.id.lv);
iv_beijing = (ImageView) inflate.findViewById(R.id.iv_beijing);
iv_gender = (ImageView) inflate.findViewById(R.id.iv_gender);
iv_head = (CircleImageView) inflate.findViewById(R.id.iv_head);
tv_nickname = (TextView) inflate.findViewById(R.id.tv_nickname);
tv_time = (TextView) inflate.findViewById(R.id.tv_time);
btn_guanzhu = (TextView) inflate.findViewById(R.id.btn_guanzhu);
tv_dizhi = (TextView) inflate.findViewById(R.id.tv_dizhi);
tv_conftent = (TextView) inflate.findViewById(R.id.tv_content);
tv_titlfe = (TextView) inflate.findViewById(R.id.tv_title);
ll_love = (LinearLayout) inflate.findViewById(R.id.ll_love);
ll_hide = (LinearLayout) inflate.findViewById(R.id.ll_hide);
web = (WebView) inflate.findViewById(R.id.web);
iv_1 = (ImageView) inflate.findViewById(R.id.iv_1);
iv_2 = (ImageView) inflate.findViewById(R.id.iv_2);
iv_3 = (ImageView) inflate.findViewById(R.id.iv_3);
iv_4 = (ImageView) inflate.findViewById(R.id.iv_4);
iv_5 = (ImageView) inflate.findViewById(R.id.iv_5);
iv_6 = (ImageView) inflate.findViewById(R.id.iv_6);
iv_7 = (ImageView) inflate.findViewById(R.id.iv_7);
list_iv.add(iv_1);
list_iv.add(iv_2);
list_iv.add(iv_3);
list_iv.add(iv_4);
list_iv.add(iv_5);
list_iv.add(iv_6);
list_iv.add(iv_7);
ll_love.setOnClickListener(this);
iv_head.setOnClickListener(this);
btn_guanzhu.setOnClickListener(this);
initData();
// inithttp_getup_list(1, ser.getId());
if (ser.getPictrue() != null && ser.getPictrue().length() != 0) {
String[] split = ser.getPictrue().split(",");
final List<String> list_image = Arrays.asList(split);
// Glide.with(HuaTi_Activity.this).load(Data_Util.IMG+list_image.get(0)).into(iv_beijing);
if (list_image == null || list_image.size() == 0) {
} else {
mohu(Data_Util.IMG + list_image.get(0), iv_beijing);
}
}
if (ser.getGender() == 1) {
iv_gender.setImageResource(R.mipmap.nan);
} else {
iv_gender.setImageResource(R.mipmap.nv);
}
if (TextUtils.isEmpty(ser.getLocation())) {
tv_dizhi.setVisibility(View.INVISIBLE);
} else {
tv_dizhi.setVisibility(View.VISIBLE);
tv_dizhi.setText(ser.getLocation());
}
if (SPUtils.getString(HuaTi_Activity.this, "uid").equals(ser.getUid() + "")) {
btn_guanzhu.setVisibility(View.GONE);
} else {
if (ser.isFollowed() && !TextUtils.isEmpty(SPUtils.getString(HuaTi_Activity.this, "token"))) {
btn_guanzhu.setVisibility(View.VISIBLE);
btn_guanzhu.setText("已关注");
btn_guanzhu.setTextColor(Color.parseColor("#d9d9d9"));
btn_guanzhu.setBackgroundResource(R.drawable.custom_hui);
btn_guanzhu.setEnabled(false);
} else {
btn_guanzhu.setEnabled(true);
btn_guanzhu.setVisibility(View.VISIBLE);
btn_guanzhu.setText("+ 关注");
btn_guanzhu.setTextColor(Color.parseColor("#ffffff"));
btn_guanzhu.setBackgroundResource(R.drawable.custom_lv);
}
}
Glide.with(HuaTi_Activity.this).load(Data_Util.IMG + ser.getHeadImg()).into(iv_head);
tv_nickname.setText(ser.getNickname());
tv_time.setText(TimeUtil.getDateTimeFromMillisecond2(ser.getAddtime()));
ll_hide.setVisibility(View.GONE);
web.setVisibility(View.VISIBLE);
web.getSettings().setJavaScriptEnabled(true);
web.getSettings().setBlockNetworkImage(false);
web.setInitialScale(100);
web.getSettings().setTextSize(WebSettings.TextSize.LARGEST);
String web_url;
if (ser.getContent().contains(",")) {
web_url = ser.getContent().split(",")[0];
} else {
web_url = ser.getContent();
}
loadWebView(Data_Util.HTML + web_url, web);
/* if (ser.getContent() != null && !Utils.isContainChinese(ser.getContent().substring(0,33))) {
// web.loadUrl(Data_Util.HTML+web_url);
// web.setWebViewClient(new HelloWebViewClient());
} else {
ll_hide.setVisibility(View.VISIBLE);
web.setVisibility(View.GONE);
tv_conftent.setText(ser.getContent());
tv_titlfe.setText(ser.getTitle());
lv.setAdapter(new BaseAdapter() {
@Override
public int getCount() {
return list_image.size() - 1;
}
@Override
public Object getItem(int position) {
return null;
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = View.inflate(HuaTi_Activity.this, R.layout.item_layout, null);
}
ImageView image = (ImageView) convertView.findViewById(R.id.iv_image);
ViewGroup.LayoutParams vParams = image.getLayoutParams();
vParams.height = (int) (DisplayUtil.getMobileHeight(HuaTi_Activity.this) * 0.37);
image.setLayoutParams(vParams);
Glide.with(HuaTi_Activity.this).load(Data_Util.IMG+list_image.get(position + 1)).into(image);
return convertView;
}
});
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (!isenter) {
isenter = true;
h.postDelayed(new Runnable() {
@Override
public void run() {
isenter = false;
}
}, 500);
String[] split1 = ser.getPictrue().split(",");
String sp = "";
for (int i = 0; i < split1.length; i++) {
if (i != 0) {
if (i == 1) {
sp = sp + split1[i];
} else {
sp = sp + "," + split1[i];
}
}
}
Intent i = new Intent(HuaTi_Activity.this, LiuLan_Activity.class);
i.putExtra("split", sp);
i.putExtra("item", position);
startActivity(i);
}
}
});
}*/
}
public void loadWebView(final String url2, final WebView web) {
new Thread(new Runnable() {
@Override
public void run() {
Connection connection = null;
connection = Jsoup.connect(url2);
System.out.println("网页:");
try {
Document document = connection.get();
String s = document.html();
System.out.println("网页:" + s);
String[] src = Utils.substringsBetween(s, "src=\"", "\"");
Set<String> src_set = new HashSet<>();
//去重
if (src != null && src.length != 0) {
Collections.addAll(src_set, src);
for (String src_str : src_set) {
s = s.replace(src_str, Data_Util.IMG + src_str);
}
}
String[] src2 = Utils.substringsBetween(s, "src=\'", "\'");
if (src2 != null && src2.length != 0) {
src_set = new HashSet<>();
Collections.addAll(src_set, src2);
for (String src_str : src_set) {
s = s.replace(src_str, Data_Util.IMG + src_str);
}
}
String s1 = Utils.substringBetween(s, "img{", "}");
if (s1 == null || s1.length() == 0) {
s = s.replace("img{}", "img{width: 100%;max-width: 100%;height: auto;margin: 10px auto;display: block;}");
} else {
s = s.replace(s1, "width: 100%;max-width: 100%;height: auto; margin: 10px auto ;display: block;");
}
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
int widthPixels = metrics.widthPixels;
String[] src3 = Utils.substringsBetween(s, "font-size:", "}");
String pix = "22px";
if (widthPixels <= 540) {
pix = "13px";
} else if (widthPixels > 540 && widthPixels < 640) {
pix = "14px";
} else if (widthPixels >= 640 && widthPixels < 720) {
pix = "15px";
} else if (widthPixels >= 720 && widthPixels < 750) {
pix = "16px";
} else if (widthPixels >= 750 && widthPixels < 800) {
pix = "17px";
} else if (widthPixels >= 800 && widthPixels < 960) {
pix = "18px";
} else if (widthPixels >= 960 && widthPixels < 1080) {
pix = "19px";
} else {
pix = "22px";
}
Utils.i("手机像素宽度:" + widthPixels);
for (String sp : src3) {
s = s.replace(sp, pix); //字体大小统一调整
}
String[] src4 = Utils.substringsBetween(s, "<div", ">");
if (src4!=null){
for (String style : src4) {
s = s.replace("<div"+style+">", ""); //统一去掉div 删掉样式
}
}
s=s.replace("</div>","");
String body = Utils.substringBetween(s, "<body>", "</body>");
String body1=body.replace("width","");
body1=body1.replace("height","");
body1=body1.replace("margin","");
body1=body1.replace("padding","");
s=s.replace(body,body1);
// MyDebug.showLargeLog(s);
final String finalS = s;
h.post(new Runnable() {
@Override
public void run() {
web.loadDataWithBaseURL(null, finalS, "text/html", "utf-8", null);
}
});
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
}
private class HelloWebViewClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// view.loadUrl(url);
return true;
}
}
private void inithttp_pl_up(final int position) {
OkHttpClient okHttpClient =
new OkHttpClient.Builder()
.connectTimeout(5000, TimeUnit.SECONDS)//设置连接超时时间
.build();
MediaType JSON = MediaType.parse("application/json; Charset=utf-8");
RequestBody requestBody = RequestBody.create(JSON, "{\"token\":\"" + SPUtils.getString(HuaTi_Activity.this, "token") + "\",\"obj\":{\"id\":" + comment_list.get(position).getId() + "}}");
String urls = "";
switch (ser.getType()) {
case 5:
urls = "/Carbar/Server!CommentLike.action";
break;
case 6:
urls = "/Carbar/Server!CommentLike.action";
break;
case 7:
urls = "/Carbar/ShaiChe!CommentLike.action";
break;
case 9:
urls = "/Carbar/WenDa!CommentLike.action";
break;
}
//创建一个请求对象
Request request = new Request.Builder()
.url(Data_Util.HttPHEAD + urls)
.post(requestBody)
.build();
Call call = okHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
h.post(new Runnable() {
@Override
public void run() {
MyToast.showToast(HuaTi_Activity.this, "连接服务器失败");
}
});
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String res = response.body().string();
Gson gson = new Gson();
final MyCode1 mycode = gson.fromJson(res, MyCode1.class);
h.post(new Runnable() {
@Override
public void run() {
if (mycode.getCode() == 0) {
comment_list.get(position).setUped(Integer.parseInt(SPUtils.getString(HuaTi_Activity.this, "uid")));
comment_list.get(position).setUpCount(comment_list.get(position).getUpCount() + 1);
adapter.notifyDataSetChanged();
MyToast.showToast(HuaTi_Activity.this, "赞");
} else if (mycode.getCode() == 4) {
SPUtils.put(HuaTi_Activity.this, "token", "");
MyToast.showToast(HuaTi_Activity.this, "请先登录");
}
}
});
}
});
}
private void inithttp_getpinglun_list(final int page) {
OkHttpClient okHttpClient =
new OkHttpClient.Builder()
.connectTimeout(5000, TimeUnit.SECONDS)//设置连接超时时间
.build();
MediaType JSON = MediaType.parse("application/json; Charset=utf-8");
RequestBody requestBody = RequestBody.create(JSON, "{\"page\":{\"page\":" + page + "},\"obj\":{\"did\":" + ser.getId() + "},\"token\":\"" + SPUtils.getString(HuaTi_Activity.this, "token") + "\"}");
Utils.i("ID评论:" + ser.getId() + " " + page);
String urls = "";
switch (ser.getType()) {
case 5:
urls = "/Carbar/Server!LoadComment.action";
break;
case 6:
urls = "/Carbar/Traffic!LoadComment.action";
break;
case 7:
urls = "/Carbar/ShaiChe!LoadComment.action";
break;
case 9:
urls = "/Carbar/WenDa!LoadComment.action";
break;
}
//创建一个请求对象
Request request = new Request.Builder()
.url(Data_Util.HttPHEAD + urls)
.post(requestBody)
.build();
Call call = okHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
h.post(new Runnable() {
@Override
public void run() {
mRefreshAndLoadMoreView.setRefreshing(false);
mLoadMoreListView.onLoadComplete();
MyToast.showToast(HuaTi_Activity.this, "连接服务器失败");
}
});
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String res = response.body().string();
Utils.i("评论列表:" + res);
Gson gson = new Gson();
final MyCode_pinglun mycode = gson.fromJson(res, MyCode_pinglun.class);
h.post(new Runnable() {
@Override
public void run() {
if (mycode.getCode() == 0) {
if (page == 1) {
h.postDelayed(new Runnable() {
@Override
public void run() {
comment_list = mycode.getObj();
if (adapter != null) {
adapter.notifyDataSetChanged();
} else {
initData();
}
if (comment_list.size() < 10) {
mLoadMoreListView.setHaveMoreData(false);
mRefreshAndLoadMoreView.setRefreshing(false);
mLoadMoreListView.onLoadComplete();
} else {
mLoadMoreListView.setHaveMoreData(true);
mRefreshAndLoadMoreView.setRefreshing(false);
mLoadMoreListView.onLoadComplete();
}
}
}, 300);
} else {
h.postDelayed(new Runnable() {
@Override
public void run() {
List<MyCode_pinglun.ObjBean> obj = mycode.getObj();
if (obj.size() == 0) {
mLoadMoreListView.setHaveMoreData(false);
} else {
mLoadMoreListView.setHaveMoreData(true);
comment_list.addAll(obj);
}
adapter.notifyDataSetChanged();
//当加载完成之后设置此时不在刷新状态
mRefreshAndLoadMoreView.setRefreshing(false);
mLoadMoreListView.onLoadComplete();
}
}, 300);
}
}
}
});
}
});
}
private void inithttp_getup_list(final int page, long l) {
OkHttpClient okHttpClient =
new OkHttpClient.Builder()
.connectTimeout(5000, TimeUnit.SECONDS)//设置连接超时时间
.build();
MediaType JSON = MediaType.parse("application/json; Charset=utf-8");
RequestBody requestBody = RequestBody.create(JSON, "{\"page\":{\"page\":" + page + "},\"obj\":{\"id\":" + l + "}}");
String urls = "";
switch (ser.getType()) {
case 5:
urls = "/Carbar/Server!LoadUp.action";
break;
case 6:
urls = "/Carbar/Traffic!LoadUp.action";
break;
case 7:
urls = "/Carbar/ShaiChe!LoadUp.action";
break;
case 9:
urls = "/Carbar/WenDa!LoadUp.action";
break;
}
//创建一个请求对象
Request request = new Request.Builder()
.url(Data_Util.HttPHEAD + urls)
.post(requestBody)
.build();
Call call = okHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
h.post(new Runnable() {
@Override
public void run() {
MyToast.showToast(HuaTi_Activity.this, "连接服务器失败");
}
});
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String res = response.body().string();
Utils.i(res);
Gson gson = new Gson();
final MyCode_uplist mycode = gson.fromJson(res, MyCode_uplist.class);
h.post(new Runnable() {
@Override
public void run() {
if (mycode.getCode() == 0) {
obj = mycode.getObj();
//初始化点赞列表
data_up(obj);
}
}
});
}
});
}
private void data_up(List<MyCode_uplist.ObjBean> obj) {
if (obj == null || obj.size() == 0) {
ll_love.setVisibility(View.GONE);
} else {
ll_love.setVisibility(View.VISIBLE);
if (obj.size() >= 6) {
for (int i = 0; i < 7; i++) {
list_iv.get(i).setVisibility(View.VISIBLE);
if (i == 6) {
list_iv.get(i).setImageResource(R.mipmap.shenlue);
} else {
try {
Glide.with(HuaTi_Activity.this).load(Data_Util.IMG + obj.get(i).getHeadImg()).into(list_iv.get(i));
} catch (Exception e) {
e.printStackTrace();
}
}
}
} else {
for (int i = 0; i < 7; i++) {
if (i < obj.size()) {
list_iv.get(i).setVisibility(View.VISIBLE);
try {
Glide.with(HuaTi_Activity.this).load(Data_Util.IMG + obj.get(i).getHeadImg()).into(list_iv.get(i));
} catch (Exception e) {
e.printStackTrace();
}
} else if (i == obj.size()) {
list_iv.get(i).setVisibility(View.VISIBLE);
list_iv.get(i).setImageResource(R.mipmap.shenlue);
} else {
list_iv.get(i).setVisibility(View.INVISIBLE);
}
}
}
}
}
Handler h = new Handler();
private void mohu(final String s, final ImageView iv) {
new Thread(new Runnable() {
@Override
public void run() {
// final Bitmap bitmap_s = BitmapFactory.decodeFile(s);
Bitmap bitmap_s = getBitMBitmap(s);
final Bitmap newBitmap;
try {
if (bitmap_s != null) {
newBitmap = StackBlur.blurNatively(bitmap_s, 20, false);
} else {
return;
}
h.post(new Runnable() {
@Override
public void run() {
iv.setImageBitmap(newBitmap);
}
});
} catch (Exception e) {
}
}
}).start();
}
//高斯模糊 保留
public static Bitmap getBitMBitmap(String urlpath) {
Bitmap map = null;
try {
URL url = new URL(urlpath);
URLConnection conn = url.openConnection();
conn.connect();
InputStream in;
in = conn.getInputStream();
map = BitmapFactory.decodeStream(in);
// TODO Auto-generated catch block
} catch (IOException e) {
e.printStackTrace();
}
return map;
}
private MyAdapter adapter;
public class MyAdapter extends BaseAdapter {
@Override
public int getCount() {
return comment_list.size();
}
@Override
public Object getItem(int position) {
return null;
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder = null;
if (convertView == null) {
convertView = View.inflate(HuaTi_Activity.this, R.layout.pinglun_item, null);
viewHolder = new ViewHolder();
viewHolder.headima = (CircleImageView) convertView.findViewById(R.id.iv_headima);
viewHolder.nickname = (TextView) convertView.findViewById(R.id.tv_nickname);
viewHolder.tv_zan = (TextView) convertView.findViewById(R.id.tv_zan);
viewHolder.content = (TextView) convertView.findViewById(R.id.tv_content);
viewHolder.lv = (MyListView) convertView.findViewById(R.id.lv_pinglun);
convertView.setTag(viewHolder);
}
viewHolder = (ViewHolder) convertView.getTag();
Glide.with(HuaTi_Activity.this).load(Data_Util.IMG + comment_list.get(position).getHeadImg()).into(viewHolder.headima);
viewHolder.nickname.setText(comment_list.get(position).getNickname());
Log.i("test", comment_list.get(position).getUped() + "");
if (comment_list.get(position).getUped() != null && (comment_list.get(position).getUped() == Integer.parseInt(SPUtils.getString(HuaTi_Activity.this, "uid")))) {
viewHolder.tv_zan.setCompoundDrawablesWithIntrinsicBounds(ContextCompat.getDrawable(HuaTi_Activity.this, R.mipmap.zan_hong), null, null, null);
} else {
viewHolder.tv_zan.setCompoundDrawablesWithIntrinsicBounds(ContextCompat.getDrawable(HuaTi_Activity.this, R.mipmap.zan2), null, null, null);
}
if (comment_list.get(position).getUpCount() == 0) {
viewHolder.tv_zan.setText("");
} else {
viewHolder.tv_zan.setText(comment_list.get(position).getUpCount() + "");
}
viewHolder.content.setText(comment_list.get(position).getContent());
viewHolder.headima.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(HuaTi_Activity.this, Other_Activity.class);
intent.putExtra("uid", comment_list.get(position).getUid());
startActivity(intent);
}
});
viewHolder.tv_zan.setTag(position);
viewHolder.tv_zan.setOnClickListener(HuaTi_Activity.this);
if (comment_list.get(position).getSubList() == null || comment_list.get(position).getSubList().size() == 0) {
viewHolder.lv.setVisibility(View.GONE);
} else {
viewHolder.lv.setVisibility(View.VISIBLE);
viewHolder.lv.setAdapter(new BaseAdapter() {
@Override
public int getCount() {
return comment_list.get(position).getSubList().size();
}
@Override
public Object getItem(int position) {
return null;
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(int i, View convertView, ViewGroup parent) {
ViewHolder2 viewHolder2 = null;
if (convertView == null) {
convertView = View.inflate(HuaTi_Activity.this, R.layout.pinglun_item_son, null);
viewHolder2 = new ViewHolder2();
viewHolder2.tv_content_son = (TextView) convertView.findViewById(R.id.tv_content_son);
viewHolder2.tv_nickname_son = (TextView) convertView.findViewById(R.id.tv_nickname_son);
convertView.setTag(viewHolder2);
}
viewHolder2 = (ViewHolder2) convertView.getTag();
viewHolder2.tv_content_son.setText(":" + comment_list.get(position).getSubList().get(i).getContent());
viewHolder2.tv_nickname_son.setText(comment_list.get(position).getSubList().get(i).getNickname());
return convertView;
}
});
}
return convertView;
}
}
private void inithttp_tjpl(String s, final Long pid) {
OkHttpClient okHttpClient =
new OkHttpClient.Builder()
.connectTimeout(5000, TimeUnit.SECONDS)//设置连接超时时间
.build();
MediaType JSON = MediaType.parse("application/json; Charset=utf-8");
Map<String, Object> reqData = new HashMap<>();
Map<String, Object> reqDataObj = new HashMap<>();
reqDataObj.put("content", s);
reqDataObj.put("did", ser.getId());
reqDataObj.put("pid", pid);
reqData.put("obj", reqDataObj);
reqData.put("token", SPUtils.getString(HuaTi_Activity.this, "token"));
String s1 = "";
try {
s1 = SerializeUtils.object2Json(reqData);
} catch (Exception e) {
e.printStackTrace();
}
RequestBody requestBody = RequestBody.create(JSON, s1);
String urls = "";
switch (ser.getType()) {
case 5:
urls = "/Carbar/Server!Comment.action";
break;
case 6:
urls = "/Carbar/Traffic!Comment.action";
break;
case 7:
urls = "/Carbar/ShaiChe!Comment.action";
break;
case 9:
urls = "/Carbar/WenDa!Comment.action";
break;
}
//创建一个请求对象
Request request = new Request.Builder()
.url(Data_Util.HttPHEAD + urls)
.post(requestBody)
.build();
Call call = okHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
h.post(new Runnable() {
@Override
public void run() {
MyToast.showToast(HuaTi_Activity.this, "连接服务器失败");
}
});
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String res = response.body().string();
Gson gson = new Gson();
final MyCode1 mycode = gson.fromJson(res, MyCode1.class);
if (mycode.getCode() == 0) {
h.post(new Runnable() {
@Override
public void run() {
// myAdapter.notifyDataSetChanged();
if (pid == null) {
if (position_cheka >= 0) {
if (ser.getType() == 5) {
new ZiXun_Fragment().list_data.get(position_cheka).setCommentNum(new ZiXun_Fragment().list_data.get(position_cheka).getCommentNum() + 1);
} else if (ser.getType() == 6) {
new CheYouQuan_Fragment().list_data.get(position_cheka).setCommentNum(new CheYouQuan_Fragment().list_data.get(position_cheka).getCommentNum() + 1);
} else if (ser.getType() == 7) {
new ShaiChe_Fragment().list_data.get(position_cheka).setCommentNum(new ShaiChe_Fragment().list_data.get(position_cheka).getCommentNum() + 1);
} else if (ser.getType() == 9) {
new WenDa_Fragment().list_data.get(position_cheka).setCommentNum(new WenDa_Fragment().list_data.get(position_cheka).getCommentNum() + 1);
}
}
}
tv_huitie2.setText(null);
tv_huitie2.setHint("说几句...");
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
// imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
imm.hideSoftInputFromWindow(tv_huitie2.getWindowToken(), 0);
page = 1;
inithttp_getpinglun_list(page);
setResult(55);
}
});
}
if (mycode.getCode() == 4) {
h.post(new Runnable() {
@Override
public void run() {
MyToast.showToast(HuaTi_Activity.this, "请先登录");
}
});
}
}
});
}
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
if (ev.getAction() == MotionEvent.ACTION_DOWN) {
View v = getCurrentFocus();
if (isShouldHideInput(v, ev) && isShouldHideInput(fabiao, ev)) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm != null) {
imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
}
}
return super.dispatchTouchEvent(ev);
}
// 必不可少,否则所有的组件都不会有TouchEvent了
if (getWindow().superDispatchTouchEvent(ev)) {
return true;
}
return onTouchEvent(ev);
}
public boolean isShouldHideInput(View v, MotionEvent event) {
if (v != null) {
int[] leftTop = {0, 0};
//获取输入框当前的location位置
v.getLocationInWindow(leftTop);
int left = leftTop[0];
int top = leftTop[1];
int bottom = top + v.getHeight();
int right = left + v.getWidth();
if (event.getX() > left && event.getX() < right && event.getY() > top && event.getY() < bottom) {
// 点击的是输入框区域,保留点击EditText的事件
return false;
} else {
return true;
}
}
return false;
}
@Override
protected void onDestroy() {
super.onDestroy();
web.destroy();
}
static class ViewHolder {
MyListView lv;
CircleImageView headima;
TextView nickname;
TextView tv_zan;
TextView content;
}
static class ViewHolder2 {
TextView tv_content_son;
TextView tv_nickname_son;
}
}
| [
"[email protected]"
] | |
36f4e873994547d1e0a7575545426a5b4fea2fc9 | 70b5aa0bcc271af9f9483492ab9beef4975db296 | /mall-tiny-01/src/main/java/com/macro/mall/tiny/controller/TestController.java | a2a478a43adade2952206cf7b761276db69dcd75 | [] | no_license | qiusu/mallLearning | 1b22162d8f856fbdc942700579db2350aefdbca5 | 135706ba21178e4129d43b2d4829981a339bb70c | refs/heads/master | 2022-08-18T12:22:28.904830 | 2019-08-10T15:49:36 | 2019-08-10T15:49:36 | 201,069,452 | 0 | 0 | null | 2022-06-21T01:38:23 | 2019-08-07T14:42:21 | Java | UTF-8 | Java | false | false | 300 | java | package com.macro.mall.tiny.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class TestController {
@RequestMapping("/hi")
public String getInfo(){
return "hi";
}
}
| [
"[email protected]"
] | |
aef7e4f677bd35405ab553bdc4c20381ef23cf9b | fa91450deb625cda070e82d5c31770be5ca1dec6 | /Diff-Raw-Data/10/10_075d9a966c5814e55323bcab0de14ccc53b498d7/Autoboxer/10_075d9a966c5814e55323bcab0de14ccc53b498d7_Autoboxer_t.java | d9813581942a872acce5e5659a5b01fc914d972a | [] | no_license | zhongxingyu/Seer | 48e7e5197624d7afa94d23f849f8ea2075bcaec0 | c11a3109fdfca9be337e509ecb2c085b60076213 | refs/heads/master | 2023-07-06T12:48:55.516692 | 2023-06-22T07:55:56 | 2023-06-22T07:55:56 | 259,613,157 | 6 | 2 | null | 2023-06-22T07:55:57 | 2020-04-28T11:07:49 | null | UTF-8 | Java | false | false | 19,249 | java | /*
* Copyright 2011 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.devtools.j2objc.translate;
import com.google.common.collect.Lists;
import com.google.devtools.j2objc.types.IOSMethodBinding;
import com.google.devtools.j2objc.types.NodeCopier;
import com.google.devtools.j2objc.types.Types;
import com.google.devtools.j2objc.util.ASTUtil;
import com.google.devtools.j2objc.util.BindingUtil;
import com.google.devtools.j2objc.util.ErrorReportingASTVisitor;
import com.google.devtools.j2objc.util.NameTable;
import org.eclipse.jdt.core.dom.AST;
import org.eclipse.jdt.core.dom.ASTNode;
import org.eclipse.jdt.core.dom.ArrayAccess;
import org.eclipse.jdt.core.dom.ArrayInitializer;
import org.eclipse.jdt.core.dom.Assignment;
import org.eclipse.jdt.core.dom.CastExpression;
import org.eclipse.jdt.core.dom.ClassInstanceCreation;
import org.eclipse.jdt.core.dom.ConditionalExpression;
import org.eclipse.jdt.core.dom.ConstructorInvocation;
import org.eclipse.jdt.core.dom.DoStatement;
import org.eclipse.jdt.core.dom.EnumConstantDeclaration;
import org.eclipse.jdt.core.dom.Expression;
import org.eclipse.jdt.core.dom.IBinding;
import org.eclipse.jdt.core.dom.IMethodBinding;
import org.eclipse.jdt.core.dom.ITypeBinding;
import org.eclipse.jdt.core.dom.IfStatement;
import org.eclipse.jdt.core.dom.InfixExpression;
import org.eclipse.jdt.core.dom.MethodDeclaration;
import org.eclipse.jdt.core.dom.MethodInvocation;
import org.eclipse.jdt.core.dom.PostfixExpression;
import org.eclipse.jdt.core.dom.PrefixExpression;
import org.eclipse.jdt.core.dom.ReturnStatement;
import org.eclipse.jdt.core.dom.StringLiteral;
import org.eclipse.jdt.core.dom.SuperConstructorInvocation;
import org.eclipse.jdt.core.dom.SuperMethodInvocation;
import org.eclipse.jdt.core.dom.SwitchStatement;
import org.eclipse.jdt.core.dom.VariableDeclarationFragment;
import org.eclipse.jdt.core.dom.WhileStatement;
import java.util.List;
/**
* Adds support for boxing and unboxing numeric primitive values.
*
* @author Tom Ball
*/
public class Autoboxer extends ErrorReportingASTVisitor {
private final AST ast;
private static final String VALUE_METHOD = "Value";
private static final String VALUEOF_METHOD = "valueOf";
public Autoboxer(AST ast) {
this.ast = ast;
}
/**
* Convert a primitive type expression into a wrapped instance. Each
* wrapper class has a static valueOf factory method, so "expr" gets
* translated to "Wrapper.valueOf(expr)".
*/
private Expression box(Expression expr) {
ITypeBinding wrapperBinding = Types.getWrapperType(Types.getTypeBinding(expr));
if (wrapperBinding != null) {
return newBoxExpression(expr, wrapperBinding);
} else {
return NodeCopier.copySubtree(ast, expr);
}
}
private Expression boxWithType(Expression expr, ITypeBinding wrapperType) {
if (Types.isBoxedPrimitive(wrapperType)) {
return newBoxExpression(expr, wrapperType);
}
return box(expr);
}
private Expression newBoxExpression(Expression expr, ITypeBinding wrapperType) {
ITypeBinding primitiveType = Types.getPrimitiveType(wrapperType);
assert primitiveType != null;
IMethodBinding wrapperMethod = BindingUtil.findDeclaredMethod(
wrapperType, VALUEOF_METHOD, primitiveType.getName());
assert wrapperMethod != null : "could not find valueOf method for " + wrapperType;
MethodInvocation invocation = ASTFactory.newMethodInvocation(
ast, wrapperMethod, ASTFactory.newSimpleName(ast, wrapperType));
ASTUtil.getArguments(invocation).add(NodeCopier.copySubtree(ast, expr));
return invocation;
}
/**
* Convert a wrapper class instance to its primitive equivalent. Each
* wrapper class has a "classValue()" method, such as intValue() or
* booleanValue(). This method therefore converts "expr" to
* "expr.classValue()".
*/
private Expression unbox(Expression expr) {
ITypeBinding binding = Types.getTypeBinding(expr);
ITypeBinding primitiveType = Types.getPrimitiveType(binding);
if (primitiveType != null) {
IMethodBinding valueMethod = BindingUtil.findDeclaredMethod(
binding, primitiveType.getName() + VALUE_METHOD);
assert valueMethod != null : "could not find value method for " + binding;
return ASTFactory.newMethodInvocation(ast, valueMethod, NodeCopier.copySubtree(ast, expr));
} else {
return NodeCopier.copySubtree(ast, expr);
}
}
@Override
public void endVisit(Assignment node) {
Expression lhs = node.getLeftHandSide();
ITypeBinding lhType = Types.getTypeBinding(lhs);
Expression rhs = node.getRightHandSide();
ITypeBinding rhType = Types.getTypeBinding(rhs);
Assignment.Operator op = node.getOperator();
if (op != Assignment.Operator.ASSIGN && !lhType.isPrimitive() &&
!lhType.equals(node.getAST().resolveWellKnownType("java.lang.String"))) {
// Not a simple assignment; need to break the <operation>-WITH_ASSIGN
// assignment apart.
node.setOperator(Assignment.Operator.ASSIGN);
node.setRightHandSide(box(newInfixExpression(lhs, rhs, op, lhType)));
} else {
if (lhType.isPrimitive() && !rhType.isPrimitive()) {
node.setRightHandSide(unbox(rhs));
} else if (!lhType.isPrimitive() && rhType.isPrimitive()) {
node.setRightHandSide(boxWithType(rhs, lhType));
}
}
}
private InfixExpression newInfixExpression(
Expression lhs, Expression rhs, Assignment.Operator op, ITypeBinding lhType) {
InfixExpression newRhs = ast.newInfixExpression();
newRhs.setLeftOperand(unbox(lhs));
newRhs.setRightOperand(unbox(rhs));
InfixExpression.Operator infixOp;
// op isn't an enum, so this can't be a switch.
if (op == Assignment.Operator.PLUS_ASSIGN) {
infixOp = InfixExpression.Operator.PLUS;
} else if (op == Assignment.Operator.MINUS_ASSIGN) {
infixOp = InfixExpression.Operator.MINUS;
} else if (op == Assignment.Operator.TIMES_ASSIGN) {
infixOp = InfixExpression.Operator.TIMES;
} else if (op == Assignment.Operator.DIVIDE_ASSIGN) {
infixOp = InfixExpression.Operator.DIVIDE;
} else if (op == Assignment.Operator.BIT_AND_ASSIGN) {
infixOp = InfixExpression.Operator.AND;
} else if (op == Assignment.Operator.BIT_OR_ASSIGN) {
infixOp = InfixExpression.Operator.OR;
} else if (op == Assignment.Operator.BIT_XOR_ASSIGN) {
infixOp = InfixExpression.Operator.XOR;
} else if (op == Assignment.Operator.REMAINDER_ASSIGN) {
infixOp = InfixExpression.Operator.REMAINDER;
} else if (op == Assignment.Operator.LEFT_SHIFT_ASSIGN) {
infixOp = InfixExpression.Operator.LEFT_SHIFT;
} else if (op == Assignment.Operator.RIGHT_SHIFT_SIGNED_ASSIGN) {
infixOp = InfixExpression.Operator.RIGHT_SHIFT_SIGNED;
} else if (op == Assignment.Operator.RIGHT_SHIFT_UNSIGNED_ASSIGN) {
infixOp = InfixExpression.Operator.RIGHT_SHIFT_UNSIGNED;
} else {
throw new IllegalArgumentException();
}
newRhs.setOperator(infixOp);
Types.addBinding(newRhs, Types.getPrimitiveType(lhType));
return newRhs;
}
@Override
public void endVisit(ArrayAccess node) {
Expression index = node.getIndex();
if (!Types.getTypeBinding(index).isPrimitive()) {
node.setIndex(unbox(index));
}
}
@Override
public void endVisit(ArrayInitializer node) {
ITypeBinding type = Types.getTypeBinding(node).getElementType();
List<Expression> expressions = ASTUtil.getExpressions(node);
for (int i = 0; i < expressions.size(); i++) {
Expression expr = expressions.get(i);
Expression result = boxOrUnboxExpression(expr, type);
if (expr != result) {
expressions.set(i, result);
}
}
}
@Override
public void endVisit(CastExpression node) {
Expression expr = boxOrUnboxExpression(node.getExpression(), Types.getTypeBinding(node));
if (expr != node.getExpression()) {
ASTNode parent = node.getParent();
if (parent instanceof Expression) {
// Check if this cast is an argument or the invocation's expression.
if (parent instanceof MethodInvocation) {
List<Expression> args = ASTUtil.getArguments((MethodInvocation) parent);
for (int i = 0; i < args.size(); i++) {
if (node.equals(args.get(i))) {
args.set(i, expr);
return;
}
}
}
ASTUtil.setProperty(node.getParent(), expr);
}
}
}
@Override
public void endVisit(ClassInstanceCreation node) {
convertArguments(Types.getMethodBinding(node), ASTUtil.getArguments(node));
}
@Override
public void endVisit(ConditionalExpression node) {
ITypeBinding nodeType = Types.getTypeBinding(node);
Expression thenExpr = node.getThenExpression();
ITypeBinding thenType = Types.getTypeBinding(thenExpr);
Expression elseExpr = node.getElseExpression();
ITypeBinding elseType = Types.getTypeBinding(elseExpr);
if (thenType.isPrimitive() && !nodeType.isPrimitive()) {
node.setThenExpression(box(thenExpr));
} else if (!thenType.isPrimitive() && nodeType.isPrimitive()) {
node.setThenExpression(unbox(thenExpr));
}
if (elseType.isPrimitive() && !nodeType.isPrimitive()) {
node.setElseExpression(box(elseExpr));
} else if (!elseType.isPrimitive() && nodeType.isPrimitive()) {
node.setElseExpression(unbox(elseExpr));
}
}
@Override
public void endVisit(ConstructorInvocation node) {
convertArguments(Types.getMethodBinding(node), ASTUtil.getArguments(node));
}
@Override
public void endVisit(DoStatement node) {
Expression expression = node.getExpression();
ITypeBinding exprType = Types.getTypeBinding(expression);
if (!exprType.isPrimitive()) {
node.setExpression(unbox(expression));
}
}
@Override
public void endVisit(EnumConstantDeclaration node) {
convertArguments(Types.getMethodBinding(node), ASTUtil.getArguments(node));
}
@Override
public void endVisit(IfStatement node) {
Expression expr = node.getExpression();
ITypeBinding binding = Types.getTypeBinding(expr);
if (!binding.isPrimitive()) {
node.setExpression(unbox(expr));
}
}
@Override
public void endVisit(InfixExpression node) {
ITypeBinding type = Types.getTypeBinding(node);
Expression lhs = node.getLeftOperand();
ITypeBinding lhBinding = Types.getTypeBinding(lhs);
Expression rhs = node.getRightOperand();
ITypeBinding rhBinding = Types.getTypeBinding(rhs);
InfixExpression.Operator op = node.getOperator();
// Don't unbox for equality tests where both operands are boxed types.
if ((op == InfixExpression.Operator.EQUALS || op == InfixExpression.Operator.NOT_EQUALS)
&& !lhBinding.isPrimitive() && !rhBinding.isPrimitive()) {
return;
}
// Don't unbox for string concatenation.
if (op == InfixExpression.Operator.PLUS && Types.isJavaStringType(type)) {
return;
}
if (!lhBinding.isPrimitive()) {
node.setLeftOperand(unbox(lhs));
}
if (!rhBinding.isPrimitive()) {
node.setRightOperand(unbox(rhs));
}
List<Expression> extendedOperands = ASTUtil.getExtendedOperands(node);
for (int i = 0; i < extendedOperands.size(); i++) {
Expression expr = extendedOperands.get(i);
if (!Types.getTypeBinding(expr).isPrimitive()) {
extendedOperands.set(i, unbox(expr));
}
}
}
@Override
public void endVisit(MethodInvocation node) {
convertArguments(Types.getMethodBinding(node), ASTUtil.getArguments(node));
}
@Override
public void endVisit(PrefixExpression node) {
PrefixExpression.Operator op = node.getOperator();
Expression operand = node.getOperand();
if (op == PrefixExpression.Operator.INCREMENT) {
rewriteBoxedPrefixOrPostfix(node, operand, "PreIncr");
} else if (op == PrefixExpression.Operator.DECREMENT) {
rewriteBoxedPrefixOrPostfix(node, operand, "PreDecr");
} else if (!Types.getTypeBinding(operand).isPrimitive()) {
node.setOperand(unbox(operand));
}
}
@Override
public void endVisit(PostfixExpression node) {
PostfixExpression.Operator op = node.getOperator();
if (op == PostfixExpression.Operator.INCREMENT) {
rewriteBoxedPrefixOrPostfix(node, node.getOperand(), "PostIncr");
} else if (op == PostfixExpression.Operator.DECREMENT) {
rewriteBoxedPrefixOrPostfix(node, node.getOperand(), "PostDecr");
}
}
private void rewriteBoxedPrefixOrPostfix(
ASTNode node, Expression operand, String methodPrefix) {
ITypeBinding type = Types.getTypeBinding(operand);
if (!Types.isBoxedPrimitive(type)) {
return;
}
AST ast = node.getAST();
String methodName = methodPrefix + NameTable.capitalize(Types.getPrimitiveType(type).getName());
IOSMethodBinding methodBinding = IOSMethodBinding.newFunction(methodName, type, type, type);
MethodInvocation invocation = ASTFactory.newMethodInvocation(ast, methodBinding, null);
ASTUtil.getArguments(invocation).add(
ASTFactory.newAddressOf(ast, NodeCopier.copySubtree(ast, operand)));
ASTUtil.setProperty(node, invocation);
}
@Override
public void endVisit(ReturnStatement node) {
Expression expr = node.getExpression();
if (expr != null) {
ASTNode n = node.getParent();
while (!(n instanceof MethodDeclaration)) {
n = n.getParent();
}
ITypeBinding returnType = Types.getMethodBinding(n).getReturnType();
ITypeBinding exprType = Types.getTypeBinding(expr);
if (returnType.isPrimitive() && !exprType.isPrimitive()) {
node.setExpression(unbox(expr));
}
if (!returnType.isPrimitive() && exprType.isPrimitive()) {
node.setExpression(box(expr));
}
}
}
@Override
public void endVisit(SuperConstructorInvocation node) {
convertArguments(Types.getMethodBinding(node), ASTUtil.getArguments(node));
}
@Override
public void endVisit(SuperMethodInvocation node) {
convertArguments(Types.getMethodBinding(node), ASTUtil.getArguments(node));
}
@Override
public void endVisit(VariableDeclarationFragment node) {
Expression initializer = node.getInitializer();
if (initializer != null) {
ITypeBinding nodeType = Types.getTypeBinding(node);
ITypeBinding initType = Types.getTypeBinding(initializer);
if (nodeType.isPrimitive() && !initType.isPrimitive()) {
node.setInitializer(unbox(initializer));
} else if (!nodeType.isPrimitive() && initType.isPrimitive()) {
node.setInitializer(boxWithType(initializer, nodeType));
}
}
}
@Override
public void endVisit(WhileStatement node) {
Expression expression = node.getExpression();
ITypeBinding exprType = Types.getTypeBinding(expression);
if (!exprType.isPrimitive()) {
node.setExpression(unbox(expression));
}
}
@Override
public void endVisit(SwitchStatement node) {
Expression expression = node.getExpression();
ITypeBinding exprType = Types.getTypeBinding(expression);
if (!exprType.isPrimitive()) {
node.setExpression(unbox(expression));
}
}
private void convertArguments(IMethodBinding methodBinding, List<Expression> args) {
if (methodBinding instanceof IOSMethodBinding) {
return; // already converted
}
if (Types.isJavaStringType(methodBinding.getDeclaringClass()) &&
methodBinding.getName().equals("format")) {
// The String.format methods are mapped directly to NSString methods,
// but arguments referred to as objects by the format string need to
// be boxed.
if (!args.isEmpty()) {
Expression first = args.get(0);
int firstArg = 1;
ITypeBinding typeBinding = Types.getTypeBinding(first);
if (typeBinding.getQualifiedName().equals("java.util.Locale")) {
first = args.get(1);
firstArg = 2;
typeBinding = Types.getTypeBinding(first);
}
if (first instanceof StringLiteral) {
List<Boolean> formatSpecifiers =
getFormatSpecifiers(((StringLiteral) first).getLiteralValue());
for (int i = 0; i < formatSpecifiers.size(); i++) {
if (formatSpecifiers.get(i)) {
int iArg = i + firstArg;
Expression arg = args.get(iArg);
if (Types.getTypeBinding(arg).isPrimitive()) {
args.set(iArg, box(arg));
}
}
}
}
}
return;
}
ITypeBinding[] paramTypes = methodBinding.getParameterTypes();
for (int i = 0; i < args.size(); i++) {
ITypeBinding paramType;
if (methodBinding.isVarargs() && i >= paramTypes.length - 1) {
paramType = paramTypes[paramTypes.length - 1].getComponentType();
} else {
paramType = paramTypes[i];
}
Expression arg = args.get(i);
Expression replacementArg = boxOrUnboxExpression(arg, paramType);
if (replacementArg != arg) {
args.set(i, replacementArg);
}
}
}
// Returns a list of booleans indicating whether the format specifier
// refers to an object argument or not.
private List<Boolean> getFormatSpecifiers(String format) {
List<Boolean> specifiers = Lists.newArrayList();
int i = 0;
while ((i = format.indexOf('%', i)) != -1) {
if (format.charAt(++i) == '%') {
// Skip %% sequences, since they don't have associated args.
++i;
continue;
}
specifiers.add(format.charAt(i) == '@');
}
return specifiers;
}
private Expression boxOrUnboxExpression(Expression arg, ITypeBinding argType) {
ITypeBinding argBinding;
IBinding binding = Types.getBinding(arg);
if (binding instanceof IMethodBinding) {
argBinding = ((IMethodBinding) binding).getReturnType();
} else {
argBinding = Types.getTypeBinding(arg);
}
if (argType.isPrimitive() && !argBinding.isPrimitive()) {
return unbox(arg);
} else if (!argType.isPrimitive() && argBinding.isPrimitive()) {
return box(arg);
} else {
return arg;
}
}
}
| [
"[email protected]"
] | |
209b8dbe48389caa610c56ceface04f598889f30 | b586df5309b2c9e86a22f5fb19beff83dca57fc3 | /src/main/java/com/example/hike/rabbitmq/Consumer.java | 2bb3865822944c56527dfdba3828bf35bc4fe6d3 | [] | no_license | Vikuolia/HikeService | ad1afb3d9de10bb6180c542173359dca344bdc26 | 48ff0eeec361ce13f3a0172883bb871a9e53ed28 | refs/heads/master | 2023-02-04T17:29:26.098247 | 2020-12-23T00:12:00 | 2020-12-23T00:12:00 | 313,717,478 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 585 | java | package com.example.hike.rabbitmq;
import com.example.hike.model.Hike;
import com.example.hike.service.HikeService;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import static com.example.hike.rabbitmq.Config.QUEUE;
@Component
public class Consumer {
@Autowired
HikeService hikeService;
@RabbitListener(queues = QUEUE)
public void consumeMessageFromQueue(Hike hike){
System.out.println(hikeService.addHike(hike));
}
}
| [
"[email protected]"
] | |
df497b6018c63de4c527132bfde9144ff3b1be95 | ceced64751c092feca544ab3654cf40d4141e012 | /DesignModel/src/main/java/com/pri/observer/Client.java | 03f11e71a0a87c553b01e96b26bbd5f42eb1bff3 | [] | no_license | 1163646727/pri_play | 80ec6fc99ca58cf717984db82de7db33ef1e71ca | fbd3644ed780c91bfc535444c54082f4414b8071 | refs/heads/master | 2022-06-30T05:14:02.082236 | 2021-01-05T08:02:40 | 2021-01-05T08:02:40 | 196,859,419 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,039 | java | package com.pri.observer;
/**
* className: Client <BR>
* description: 客户端<BR>
* remark: 观察者模式测试<BR>
* author: ChenQi <BR>
* createDate: 2019-09-02 20:14 <BR>
*/
public class Client {
public static void main(String[] args) {
// 实例化具体观察者 ChenQi;
RealObserver realObserver = new RealObserver();
// 创建微信用户 ChenQi;
WeiXinUser weiXinUser1 = new WeiXinUser("张三");
WeiXinUser weiXinUser2 = new WeiXinUser("李四");
WeiXinUser weiXinUser3 = new WeiXinUser("王五");
// 添加订阅者,是一个订阅主题的行为 ChenQi;
realObserver.registerObserver(weiXinUser1);
realObserver.registerObserver(weiXinUser2);
realObserver.registerObserver(weiXinUser3);
// 公众号更新消息发布给订阅的微信用户,是一个发布行为 ChenQi;
realObserver.notifyAllObserver("公众号内容更新!");
realObserver.notifyAllObserver("测试是否消费成功!");
}
}
| [
"[email protected]"
] | |
ca06be891702d0f30542a9c88a5d1cd23f055d2f | d6c36b52b7f32819f0f7db1a2d8ba118a700a41b | /src/Course2/w2/StringsFirstAssignments/Part4.java | 5ea239bb3f4644d01236fcd1c9ea4e34f96efb5a | [] | no_license | leonardloh/Duke-University-Java-Programming-and-Software-Engineering-Fundamentals-Specialization | d0620f55609a3f45de03bb757ba058a9d19cbdd3 | 355e282b0be578efcf97ecc592d3f61ca8f6f7d1 | refs/heads/master | 2022-08-18T19:18:48.298605 | 2020-05-18T14:59:12 | 2020-05-18T14:59:12 | 262,826,523 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 839 | java | package Course2.w2.StringsFirstAssignments;
import edu.duke.URLResource;
public class Part4 {
public static String pattern = "youtube.com";
public static String quote = "\"";
public void findOccurence()
{
URLResource ur = new URLResource("http://www.dukelearntoprogram.com/course2/data/manylinks.html");
for(String word: ur.words())
{
int patternIndex = word.indexOf(pattern);
if (patternIndex != -1 )
{
int indexQuote1 = word.indexOf(quote);
int indexQuote2 = word.indexOf(quote, word.indexOf(quote)+1);
System.out.println(word.substring(indexQuote1, indexQuote2+1));
}
}
}
public static void main(String[] args) {
Part4 p4 = new Part4();
p4.findOccurence();
}
}
| [
"[email protected]"
] | |
a8bcbead62687a9ff453494821369b9d1d354328 | a370ff524a6e317488970dac65d93a727039f061 | /src/main/java/template/algo/MatroidIntersect.java | 1ea28621f836baff608cc86b8072cade88348a85 | [] | no_license | taodaling/contest | 235f4b2a033ecc30ec675a4526e3f031a27d8bbf | 86824487c2e8d4fc405802fff237f710f4e73a5c | refs/heads/master | 2023-04-14T12:41:41.718630 | 2023-04-10T14:12:47 | 2023-04-10T14:12:47 | 213,876,299 | 9 | 1 | null | 2021-06-12T06:33:05 | 2019-10-09T09:28:43 | Java | UTF-8 | Java | false | false | 3,957 | java | package template.algo;
import template.primitve.generated.datastructure.IntegerDequeImpl;
import java.util.Arrays;
import java.util.function.Consumer;
/**
* O(r) invoke computeAdj and extend. O(r^2n)
*/
public class MatroidIntersect {
protected IntegerDequeImpl dq;
protected int[] dists;
protected boolean[] added;
protected boolean[][] adj1;
protected boolean[][] adj2;
protected int n;
protected boolean[] x1;
protected boolean[] x2;
protected static int distInf = (int) 1e9;
protected int[] pre;
protected Consumer<boolean[]> callback;
protected static Consumer<boolean[]> nilCallback = x -> {
};
public void setCallback(Consumer<boolean[]> callback) {
if (callback == null) {
callback = nilCallback;
}
this.callback = callback;
}
public MatroidIntersect(int n) {
this.n = n;
dq = new IntegerDequeImpl(n);
dists = new int[n];
added = new boolean[n];
adj1 = new boolean[n][];
adj2 = new boolean[n][];
x1 = new boolean[n];
x2 = new boolean[n];
pre = new int[n];
setCallback(nilCallback);
}
protected boolean adj(int i, int j) {
if (added[i]) {
return adj1[i][j];
} else {
return adj2[j][i];
}
}
protected boolean expand(MatroidIndependentSet a, MatroidIndependentSet b, int round) {
Arrays.fill(x1, false);
Arrays.fill(x2, false);
a.prepare(added);
b.prepare(added);
a.extend(added, x1);
b.extend(added, x2);
for (int i = 0; i < n; i++) {
if (x1[i] && x2[i]) {
pre[i] = -1;
xorPath(i);
return true;
}
}
for (int i = 0; i < n; i++) {
if (added[i]) {
Arrays.fill(adj1[i], false);
Arrays.fill(adj2[i], false);
}
}
a.computeAdj(added, adj1);
b.computeAdj(added, adj2);
Arrays.fill(dists, distInf);
Arrays.fill(pre, -1);
dq.clear();
for (int i = 0; i < n; i++) {
if (added[i]) {
continue;
}
//right
if (x1[i]) {
dists[i] = 0;
dq.addLast(i);
}
}
int tail = -1;
while (!dq.isEmpty()) {
int head = dq.removeFirst();
if (x2[head]) {
tail = head;
break;
}
for (int j = 0; j < n; j++) {
if (added[head] != added[j] && adj(head, j) && dists[j] > dists[head] + 1) {
dists[j] = dists[head] + 1;
dq.addLast(j);
pre[j] = head;
}
}
}
if (tail == -1) {
return false;
}
xorPath(tail);
return true;
}
protected void xorPath(int tail) {
boolean[] last1 = new boolean[n];
boolean[] last2 = new boolean[n];
for (boolean add = true; tail != -1; tail = pre[tail], add = !add) {
assert added[tail] != add;
added[tail] = add;
if (add) {
adj1[tail] = last1;
adj2[tail] = last2;
} else {
last1 = adj1[tail];
last2 = adj2[tail];
adj1[tail] = null;
adj2[tail] = null;
}
}
}
/**
* Find a basis with largest possible size
*
* @param a
* @param b
* @return
*/
public boolean[] intersect(MatroidIndependentSet a, MatroidIndependentSet b) {
Arrays.fill(added, false);
int round = 0;
callback.accept(added);
while (expand(a, b, round)) {
round++;
callback.accept(added);
}
return added;
}
}
| [
"[email protected]"
] | |
8a66863e43a7fb814ecb3e88746e10b37018c9b3 | 3e5891022aed9a23691898414c0e50d28b4e504a | /focus-module/gateway/src/main/java/com/focus/module/gateway/swagger/SwaggerProvider.java | e420d17fdc93cf3fb9fd2f90a50251d670ae2650 | [] | no_license | doublecancel/focus | c066229f041507852ae183a3fc47a007f3b8b9e2 | 5364d1c18a40257d05341b66fc6eee442d8c9435 | refs/heads/master | 2022-07-13T16:12:08.277375 | 2019-08-13T11:23:40 | 2019-08-13T11:23:40 | 187,060,365 | 0 | 0 | null | 2022-06-21T01:08:17 | 2019-05-16T16:03:38 | Java | UTF-8 | Java | false | false | 2,137 | java | package com.focus.module.gateway.swagger;
import lombok.AllArgsConstructor;
import org.springframework.cloud.gateway.config.GatewayProperties;
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.support.NameUtils;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;
import springfox.documentation.swagger.web.SwaggerResource;
import springfox.documentation.swagger.web.SwaggerResourcesProvider;
import java.util.ArrayList;
import java.util.List;
@Component
@Primary
@AllArgsConstructor
public class SwaggerProvider implements SwaggerResourcesProvider {
public static final String API_URI = "/v2/api-docs";
private final RouteLocator routeLocator;
private final GatewayProperties gatewayProperties;
@Override
public List<SwaggerResource> get() {
List<SwaggerResource> resources = new ArrayList<>();
List<String> routes = new ArrayList<>();
//取出gateway的route
routeLocator.getRoutes().subscribe(route -> routes.add(route.getId()));
//结合配置的route-路径(Path),和route过滤,只获取有效的route节点
gatewayProperties.getRoutes().stream().filter(routeDefinition -> routes.contains(routeDefinition.getId()))
.forEach(routeDefinition -> routeDefinition.getPredicates().stream()
.filter(predicateDefinition -> ("Path").equalsIgnoreCase(predicateDefinition.getName()))
.forEach(predicateDefinition -> resources.add(swaggerResource(routeDefinition.getId(),
predicateDefinition.getArgs().get(NameUtils.GENERATED_NAME_PREFIX + "0")
.replace("/**", API_URI)))));
return resources;
}
private SwaggerResource swaggerResource(String name, String location) {
SwaggerResource swaggerResource = new SwaggerResource();
swaggerResource.setName(name);
swaggerResource.setLocation(location);
swaggerResource.setSwaggerVersion("2.0");
return swaggerResource;
}
}
| [
"[email protected]"
] | |
5e37718cc0462c2a669d025f85c69e86e48f1e7b | e665666b082fdd0304fc05cf26fac65676bc71e0 | /src/java/ca/savi/horse/model/hwunmarshaller/UnmarshalGenericOperationRequestParamsResponse.java | dd545d06555eef3de10506ee5b1c38c1185dbdbb | [] | no_license | savi-dev/horse | 827da67da56f87d3b85c1508eb69bc1847451c93 | d71a80d066ada52f8d0c4a8b6e047923cd1e8e4a | refs/heads/master | 2021-01-25T12:09:23.870319 | 2012-08-20T15:32:38 | 2012-08-20T15:32:38 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,238 | java | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB)
// Reference Implementation, vhudson-jaxb-ri-2.2-147
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source
// schema.
// Generated on: 2012.03.19 at 01:54:32 PM EDT
//
package ca.savi.horse.model.hwunmarshaller;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>
* Java class for anonymous complex type.
* <p>
* The following schema fragment specifies the expected content contained within
* this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="setRegisterValue" type="{http://www.w3.org/2001/XMLSchema}base64Binary" minOccurs="0"/>
* <element name="uuid" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = { "setRegisterValue", "uuid" })
@XmlRootElement(name = "UnmarshalGenericOperationRequestParams-Response")
public class UnmarshalGenericOperationRequestParamsResponse {
protected byte[] setRegisterValue;
protected String uuid;
/**
* Gets the value of the setRegisterValue property.
* @return possible object is byte[]
*/
public byte[] getSetRegisterValue() {
return setRegisterValue;
}
/**
* Sets the value of the setRegisterValue property.
* @param value allowed object is byte[]
*/
public void setSetRegisterValue(byte[] value) {
this.setRegisterValue = ((byte[]) value);
}
/**
* Gets the value of the uuid property.
* @return possible object is {@link String }
*/
public String getUuid() {
return uuid;
}
/**
* Sets the value of the uuid property.
* @param value allowed object is {@link String }
*/
public void setUuid(String value) {
this.uuid = value;
}
}
| [
"[email protected]"
] | |
594196c3133e18c06189259310b0641cede8dd00 | 86152af493decf40f53d7951d4c7f8a60f363d64 | /seoulMarketDayAndroid/seoulMarketDayAndroid/app/src/main/java/com/stm/market/fragment/video/presenter/impl/MarketVideoPresenterImpl.java | 1bd07a7ba95eb19e77d6ea3ba237cbc230f81c8f | [
"MIT"
] | permissive | MobileSeoul/2017seoul-15 | b54fb7d95c6bf685203d9948e4087385b02f6170 | 620eb72e4cdba9f355327b66a299da257c5b0b40 | refs/heads/master | 2021-09-05T14:39:35.702491 | 2018-01-29T00:15:01 | 2018-01-29T00:15:01 | 119,310,262 | 5 | 1 | null | null | null | null | UTF-8 | Java | false | false | 4,270 | java | package com.stm.market.fragment.video.presenter.impl;
import com.stm.common.dao.File;
import com.stm.common.dao.Market;
import com.stm.common.dao.User;
import com.stm.common.dto.HttpErrorDto;
import com.stm.common.flag.DefaultFileFlag;
import com.stm.common.flag.InfiniteScrollFlag;
import com.stm.market.fragment.video.interactor.MarketVideoInteractor;
import com.stm.market.fragment.video.interactor.impl.MarketVideoInteractorImpl;
import com.stm.market.fragment.video.presenter.MarketVideoPresenter;
import com.stm.market.fragment.video.view.MarketVideoView;
import java.util.List;
/**
* Created by ㅇㅇ on 2017-08-24.
*/
public class MarketVideoPresenterImpl implements MarketVideoPresenter {
private MarketVideoInteractor marketVideoInteractor;
private MarketVideoView marketVideoView;
public MarketVideoPresenterImpl(MarketVideoView marketVideoView) {
this.marketVideoInteractor = new MarketVideoInteractorImpl(this);
this.marketVideoView = marketVideoView;
}
@Override
public void init(User user, Market market) {
marketVideoView.showProgressDialog();
marketVideoInteractor.setUser(user);
marketVideoInteractor.setMarket(market);
if (user != null) {
String accessToken = user.getAccessToken();
marketVideoInteractor.setMarketRepository(accessToken);
marketVideoInteractor.setFileRepository(accessToken);
} else {
marketVideoInteractor.setMarketRepository();
marketVideoInteractor.setFileRepository();
}
}
@Override
public void onCreateView() {
marketVideoView.setScrollViewOnScrollChangeListener();
Market market = marketVideoInteractor.getMarket();
long marketId = market.getId();
long offset = InfiniteScrollFlag.DEFAULT_OFFSET;
marketVideoView.setScrollViewOnScrollChangeListener();
marketVideoInteractor.getFileListByIdAndTypeAndOffset(marketId, DefaultFileFlag.VIDEO_THUMBNAIL_TYPE, offset);
}
@Override
public void onScrollChange(int difference) {
if (difference <= 0) {
marketVideoView.showProgressDialog();
Market market = marketVideoInteractor.getMarket();
long marketId = market.getId();
List<File> files = marketVideoInteractor.getFiles();
long offset = files.size();
marketVideoInteractor.getFileListByIdAndTypeAndOffset(marketId, DefaultFileFlag.VIDEO_THUMBNAIL_TYPE, offset);
}
}
@Override
public void onNetworkError(HttpErrorDto httpErrorDto) {
if (httpErrorDto == null) {
marketVideoView.showMessage("네트워크 불안정합니다. 다시 시도하세요.");
} else {
marketVideoView.showMessage(httpErrorDto.message());
}
}
@Override
public void onClickVideo(File file, int position) {
marketVideoView.showProgressDialog();
marketVideoInteractor.updateFileByHits(file, position);
}
@Override
public void onSuccessGetFileListByIdAndTypeAndOffset(List<File> newFiles) {
List<File> files = marketVideoInteractor.getFiles();
int fileSize = files.size();
int newFileSize = newFiles.size();
if (newFileSize > 0) {
if(fileSize == 0){
marketVideoInteractor.setFiles(newFiles);
marketVideoView.clearMarketVideoAdapter();
marketVideoView.setMarketVideoAdapterItem(newFiles);
} else {
marketVideoInteractor.setFilesAddAll(newFiles);
marketVideoView.marketVideoAdapterNotifyItemRangeInserted(fileSize, newFileSize);
}
} else {
marketVideoView.showEmptyView();
}
marketVideoView.goneProgressDialog();
}
@Override
public void onSuccessUpdateFileByHits(int position) {
List<File> files = marketVideoInteractor.getFiles();
File file = files.get(position);
int prevHit = file.getHits();
file.setHits(prevHit + 1);
marketVideoView.marketVideoAdapterNotifyItemChanged(position);
marketVideoView.goneProgressDialog();
marketVideoView.navigateToVideoPlayerActivity(file);
}
}
| [
"[email protected]"
] | |
a382794f073a3254f45e7bb1f9301f8c0a052bca | b084fbf785f5b115cc60b37ac0e32a3fe6e4fe30 | /src/main/java/com/group_finity/mascot/script/Script.java | a6b7abf713ee727d67506d575dc548ee8548e518 | [
"BSD-2-Clause"
] | permissive | helpimnotdrowning/shimeji-universal | efcc22d765a13454f32c7211da192129a4f892e3 | bbfbef081da6d457c6c29a8e214a11d996ca9cd3 | refs/heads/master | 2023-07-27T22:30:42.018080 | 2021-09-11T04:00:37 | 2021-09-11T04:00:37 | 404,561,888 | 0 | 0 | NOASSERTION | 2021-09-09T02:38:24 | 2021-09-09T02:38:24 | null | UTF-8 | Java | false | false | 2,247 | java | package com.group_finity.mascot.script;
import com.group_finity.mascot.exception.VariableException;
import javax.script.*;
/**
* Original Author: Yuki Yamada of Group Finity (http://www.group-finity.com/Shimeji/)
* Currently developed by Shimeji-ee Group.
*/
public class Script extends Variable {
private static final ScriptEngineManager manager = new ScriptEngineManager();
private static final ScriptEngine engine = manager.getEngineByMimeType("text/javascript");
private final String source;
private final boolean clearAtInitFrame;
private final CompiledScript compiled;
private Object value;
public Script(final String source, final boolean clearAtInitFrame) throws VariableException {
this.source = source;
this.clearAtInitFrame = clearAtInitFrame;
try {
this.compiled = ((Compilable) engine).compile(this.source);
} catch (final ScriptException e) {
throw new VariableException("An error occurred in compiling a script: " + this.source, e);
}
}
@Override
public String toString() {
return this.isClearAtInitFrame() ? "#{" + this.getSource() + "}" : "${" + this.getSource() + "}";
}
@Override
public void init() {
setValue(null);
}
@Override
public void initFrame() {
if (this.isClearAtInitFrame()) {
setValue(null);
}
}
@Override
public synchronized Object get(final VariableMap variables) throws VariableException {
if (getValue() != null) {
return getValue();
}
try {
setValue(getCompiled().eval(variables));
} catch (final ScriptException e) {
throw new VariableException("An error occurred in script evaluation: " + this.source, e);
}
return getValue();
}
private Object getValue() {
return this.value;
}
private void setValue(final Object value) {
this.value = value;
}
private boolean isClearAtInitFrame() {
return this.clearAtInitFrame;
}
private CompiledScript getCompiled() {
return this.compiled;
}
private String getSource() {
return this.source;
}
}
| [
"[email protected]"
] | |
a763a44385728bdb6211ac7917ab78953d9c8a36 | 2a342d6d34693a0307684dcf8a2b0e2a8c56979c | /src/main/java/com/loiclude/PtitQuiz/model/Target.java | 4078b7e12ff1dac9be03c44ba40638651a0be87d | [] | no_license | nguyentriloi/PtitQiz | 2a5e4d8686666bf4656e66438967350bee374e53 | 1bbd08f679ec7243d15cf449100a5ed36163a975 | refs/heads/master | 2020-05-01T09:02:23.202844 | 2019-06-22T05:39:48 | 2019-06-22T05:39:48 | 177,390,543 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,275 | java | package com.loiclude.PtitQuiz.model;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "target")
public class Target {
@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@Column(name = "date")
private Date date;
@Column(name = "id_monhoc")
private Integer idMonhoc;
@Column(name = "soccer")
private Integer soccer;
@Column(name = "ma_sv")
private String maSv;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public Integer getIdMonhoc() {
return idMonhoc;
}
public void setIdMonhoc(Integer idMonhoc) {
this.idMonhoc = idMonhoc;
}
public Integer getSoccer() {
return soccer;
}
public void setSoccer(Integer soccer) {
this.soccer = soccer;
}
public String getMaSv() {
return maSv;
}
public void setMaSv(String maSv) {
this.maSv = maSv;
}
}
| [
"Meograce@123"
] | Meograce@123 |
4320f9fbf5069b34d30aa2c81a2885bbf1f2ca08 | 4523f35d6264b007b85853b4e95b6e890b6e60f5 | /src/main/java/top/wsure/bot/utils/DynamicEnumUtils.java | 2156aa55821136eb4a72b1ee22af58c6a17e5fdd | [] | no_license | WsureWarframe/ws-jcq | 7fd751eb9db37a110311a94af6841ec22d7a64fc | 46bd364e88519d00f08104e4132ba12318ad7f05 | refs/heads/master | 2023-03-05T12:51:51.205940 | 2021-02-15T18:03:50 | 2021-02-15T18:03:50 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 6,393 | java | package top.wsure.bot.utils;
import java.lang.reflect.AccessibleObject;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.ToString;
import sun.reflect.ConstructorAccessor;
import sun.reflect.FieldAccessor;
import sun.reflect.ReflectionFactory;
import top.wsure.bot.common.cache.CacheManagerImpl;
import top.wsure.bot.common.cache.EntityCache;
import top.wsure.bot.common.enums.CacheEnum;
public class DynamicEnumUtils {
private static final ReflectionFactory reflectionFactory = ReflectionFactory.getReflectionFactory();
private static void setFailsafeFieldValue(Field field, Object target, Object value) throws NoSuchFieldException,
IllegalAccessException {
// let's make the field accessible
field.setAccessible(true);
// next we change the modifier in the Field instance to
// not be final anymore, thus tricking reflection into
// letting us modify the static final field
Field modifiersField = Field.class.getDeclaredField("modifiers");
modifiersField.setAccessible(true);
int modifiers = modifiersField.getInt(field);
// blank out the final bit in the modifiers int
modifiers &= ~Modifier.FINAL;
modifiersField.setInt(field, modifiers);
FieldAccessor fa = reflectionFactory.newFieldAccessor(field, false);
fa.set(target, value);
}
private static void blankField(Class<?> enumClass, String fieldName) throws NoSuchFieldException,
IllegalAccessException {
for (Field field : Class.class.getDeclaredFields()) {
if (field.getName().contains(fieldName)) {
AccessibleObject.setAccessible(new Field[] { field }, true);
setFailsafeFieldValue(field, enumClass, null);
break;
}
}
}
private static void cleanEnumCache(Class<?> enumClass) throws NoSuchFieldException, IllegalAccessException {
blankField(enumClass, "enumConstantDirectory"); // Sun (Oracle?!?) JDK 1.5/6
blankField(enumClass, "enumConstants"); // IBM JDK
}
private static ConstructorAccessor getConstructorAccessor(Class<?> enumClass, Class<?>[] additionalParameterTypes)
throws NoSuchMethodException {
Class<?>[] parameterTypes = new Class[additionalParameterTypes.length + 2];
parameterTypes[0] = String.class;
parameterTypes[1] = int.class;
System.arraycopy(additionalParameterTypes, 0, parameterTypes, 2, additionalParameterTypes.length);
return reflectionFactory.newConstructorAccessor(enumClass.getDeclaredConstructor(parameterTypes));
}
private static Object makeEnum(Class<?> enumClass, String value, int ordinal, Class<?>[] additionalTypes,
Object[] additionalValues) throws Exception {
Object[] params = new Object[additionalValues.length + 2];
params[0] = value;
params[1] = ordinal;
System.arraycopy(additionalValues, 0, params, 2, additionalValues.length);
return enumClass.cast(getConstructorAccessor(enumClass, additionalTypes).newInstance(params));
}
/**
* Add an enum instance to the enum class given as argument
*
* @param <T> the type of the enum (implicit)
* @param enumType the class of the enum to be modified
* @param enumName the name of the new enum instance to be added to the class.
*/
@SuppressWarnings("unchecked")
public static <T extends Enum<?>> void addEnum(Class<T> enumType, String enumName,Class<?>[] classes,Object[] args) {
// 0. Sanity checks
if (!Enum.class.isAssignableFrom(enumType)) {
throw new RuntimeException("class " + enumType + " is not an instance of Enum");
}
// 1. Lookup "$VALUES" holder in enum class and get previous enum instances
Field valuesField = null;
Field[] fields = enumType.getDeclaredFields();
for (Field field : fields) {
if (field.getName().contains("$VALUES")) {
valuesField = field;
break;
}
}
AccessibleObject.setAccessible(new Field[] { valuesField }, true);
try {
// 2. Copy it
T[] previousValues = (T[]) valuesField.get(enumType);
List<T> values = new ArrayList<T>(Arrays.asList(previousValues));
// 3. build new enum
T newValue = (T) makeEnum(enumType, // The target enum class
enumName, // THE NEW ENUM INSTANCE TO BE DYNAMICALLY ADDED
values.size(),
classes, // could be used to pass values to the enum constuctor if needed
args); // could be used to pass values to the enum constuctor if needed
// 4. add new value
values.add(newValue);
// 5. Set new values field
setFailsafeFieldValue(valuesField, null, values.toArray((T[]) Array.newInstance(enumType, 0)));
// 6. Clean enum cache
cleanEnumCache(enumType);
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e.getMessage(), e);
}
}
/**
* TestEnum And Test Main
*/
@AllArgsConstructor
@Getter
@ToString
private static enum TestEnum {
a("aa"),
b("bb"),
c("cc");
private String test;
};
public static void main(String[] args) {
// Dynamically add 3 new enum instances d, e, f to TestEnum
addEnum(TestEnum.class, "d",new Class[]{String.class},new Object[]{"dd"});
addEnum(TestEnum.class, "e",new Class[]{String.class},new Object[]{"ee"});
addEnum(TestEnum.class, "f",new Class[]{String.class},new Object[]{"ff"});
addEnum(CacheEnum.class,"TestCache",
new Class[]{String.class},
new Object[]{"test"});
CacheManagerImpl cache = CacheEnum.getManager("test");
cache.putCache("11","22",100L);
System.out.println(cache.getCacheDataByKey("11").toString());
// Run a few tests just to show it works OK.
System.out.println(Arrays.deepToString(TestEnum.values()));
// Shows : [a, b, c, d, e, f]
}
}
| [
"[email protected]"
] | |
0c2505d83ba318596abeac72db30b9157a48b540 | 322e857697c3bc562d7dec3fa4be145583916fd9 | /ObjectsClasses/src/ObjectClassesExample.java | 033cb668d43655469dbfe0239db6c9412a571e59 | [] | no_license | gitsourced/JavaTutorials | a63fbe0d707c7bcdb1faa134822a739fad423376 | 062b0af4d73d79defed9799de3c5259674e7ada8 | refs/heads/master | 2022-11-04T21:50:05.515279 | 2020-06-26T22:44:01 | 2020-06-26T22:44:01 | 263,464,989 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 315 | java | public class ObjectClassesExample {
public static void main(String[] args) {
String name = new String("Bob");
System.out.println(name.toUpperCase());
System.out.println(name.toLowerCase());
System.out.println(name.equalsIgnoreCase("bob"));
System.out.println(name.charAt(1));
}
}
| [
"COMPSCISTUDY@DESKTOP-M2PCUTN"
] | COMPSCISTUDY@DESKTOP-M2PCUTN |
0c059c59c84cd4d451a9b627e1a781f4597f77cb | 5d0b2e4b8bafa0784a778a74694092a876265ba7 | /chicha/src/main/java/sw/chicha/Schedule/domain/Schedule.java | 6b126f49ca6ff5a1f39387f73057110e27f53cc0 | [] | no_license | leeyeonjeong/chicha | 936d3cc058284986dd20052f8d06d2d2af31cf34 | 24667ef5d7c5fc449b6533ebdb61c874c2a8a45b | refs/heads/master | 2023-08-04T19:47:30.969303 | 2021-09-15T04:19:01 | 2021-09-15T04:19:01 | 301,101,730 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,921 | java | package sw.chicha.Schedule.domain;
import lombok.*;
import org.springframework.data.annotation.CreatedDate;
import sw.chicha.Calendar.domain.Calendar;
import sw.chicha.Coach.domain.Coach;
import sw.chicha.Coach.dto.CoachDto;
import sw.chicha.Member.domain.Therapist;
import javax.persistence.*;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
@AllArgsConstructor
@NoArgsConstructor(access = AccessLevel.PROTECTED) // 기본 생성자 (protected type)
@Entity
@Getter
public class Schedule {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String state; // 전체 상태
private String start;
private String end;
private String repitation;
private String memo;
private String child;
private String gender;
private String birthday;
private String session;
private String counseling;
@CreatedDate
private LocalDate createdDate;
@ManyToOne
@JoinColumn(name = "calendar_id")
private Calendar calendar;
@OneToOne
@JoinColumn(name = "coach_id")
private Coach coach;
@Builder
public Schedule(Long id, String name, String state, String start, String end, String repitation,String memo,String child,
String gender, String birthday, LocalDate createdDate,Calendar calendar,Coach coach, String session, String counseling) {
this.id = id;
this.name = name;
this.state = state;
this.start = start;
this.end = end;
this.repitation = repitation;
this.memo = memo;
this.child = child;
this.gender = gender;
this.birthday = birthday;
this.createdDate = createdDate;
this.calendar = calendar;
this.coach = coach;
this.session = session;
this.counseling = counseling;
}
}
| [
"[email protected]"
] | |
50610b76c52f7071d0a866999d4e6f0bfe1b74e3 | 36c0a0e21f3758284242b8d2e40b60c36bd23468 | /src/main/java/com/datasphere/server/query/druid/aggregations/CountAggregation.java | 40a022c8fed44b3e91c5f5908a433bb3f87302b6 | [
"LicenseRef-scancode-mulanpsl-1.0-en"
] | permissive | neeeekoooo/datasphere-service | 0185bca5a154164b4bc323deac23a5012e2e6475 | cb800033ba101098b203dbe0a7e8b7f284319a7b | refs/heads/master | 2022-11-15T01:10:05.530442 | 2020-02-01T13:54:36 | 2020-02-01T13:54:36 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,008 | java | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.datasphere.server.query.druid.aggregations;
import com.fasterxml.jackson.annotation.JsonTypeName;
import com.datasphere.server.query.druid.Aggregation;
@JsonTypeName("count")
public class CountAggregation implements Aggregation {
String name;
public CountAggregation(String name){
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
| [
"[email protected]"
] | |
0c9631cc8bfeeca79f6480a8a6397d0c1e5efa50 | ed166738e5dec46078b90f7cca13a3c19a1fd04b | /minor/guice-OOM-error-reproduction/src/main/java/gen/I_Gen147.java | a1e25fb7ebde63c028903b30472205efeaa27fed | [] | no_license | michalradziwon/script | 39efc1db45237b95288fe580357e81d6f9f84107 | 1fd5f191621d9da3daccb147d247d1323fb92429 | refs/heads/master | 2021-01-21T21:47:16.432732 | 2016-03-23T02:41:50 | 2016-03-23T02:41:50 | 22,663,317 | 2 | 0 | null | null | null | null | UTF-8 | Java | false | false | 331 | java |
package gen;
public class I_Gen147 {
@com.google.inject.Inject
public I_Gen147(I_Gen148 i_gen148){
System.out.println(this.getClass().getCanonicalName() + " created. " + i_gen148 );
}
@com.google.inject.Inject public void injectInterfaceWithoutImpl(gen.InterfaceWithoutImpl i){} // should expolode :)
}
| [
"[email protected]"
] | |
01ffa93373d068bb86221454b0a714deda0797a2 | 8a84d4f9824c0fd28bb3646d2fe8f2c0f32af760 | /e-vending/src/main/java/com/mkyong/users/dao/UserDao.java | 24f1da3893219f3feb10a2be93c1817bdf4cab91 | [] | no_license | Severov/e-vending | ec52c8c30c0610219d1fb3975d0b4c6ce801ed7f | ee65d88d796f4f32f78ab6c5f98bf5862e5dfe3d | refs/heads/master | 2021-01-10T15:36:39.192331 | 2015-10-28T15:10:18 | 2015-10-28T15:10:18 | 45,034,267 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 383 | java | package com.mkyong.users.dao;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import com.mkyong.users.model.User;
public interface UserDao {
User findByUserName(String username);
@Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW)
void saveUser(User user);
} | [
"mishka@debian-pavilion"
] | mishka@debian-pavilion |
e7f84d5600950552425f88a7ec89fc8e9ab2b87f | 860abece3545a35328cea17054bf7abbcd09ee69 | /Source Code/OSMS/OSMSValidator/OSMSValidatorREST/src/main/java/com/gcom/osms/validator/rest/OSMSValidatorService.java | ea485484d16bb70153c7c999ff07567e17fed9ae | [] | no_license | message-switch/main | 6dcdc7b0307daac6539642c9a2e729de37557d70 | b7d7ca8515c53da6db7639267c250aeb4002f810 | refs/heads/master | 2021-05-11T06:57:31.883699 | 2018-10-24T20:24:53 | 2018-10-24T20:24:53 | 118,005,211 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 2,396 | java | /**
* Copyright (c) GCOM Software Inc, NY. All Rights Reserved.
*
* THIS INFORMATION IS COMPANY CONFIDENTIAL.
*
* NOTICE: This material is a confidential trade secret and proprietary
* information of GCOM Software Inc, NY which may not be reproduced, used, sold, or
* transferred to any third party without the prior written consent of GCOM Software Inc, NY.
*/
package com.gcom.osms.validator.rest;
import java.nio.file.Files;
import java.nio.file.Paths;
import javax.enterprise.context.RequestScoped;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.gcom.osms.validator.common.ValidatorRequest;
import com.gcom.osms.validator.common.ValidatorResponse;
import com.gcom.osms.validator.exception.OSMSValidatorServiceException;
import com.gcom.osms.validator.service.RuleValidatorService;
import com.gcom.osms.validator.services.impl.RuleValidatorServiceImpl;
@Path("/OSMSValidator")
@Consumes("application/json")
@Produces("application/json")
@RequestScoped
/**
*
* Rest service for OSMSValidations
*
*/
public class OSMSValidatorService {
/** The Constant LOGGER. */
private static final Logger LOGGER = LoggerFactory.getLogger(OSMSValidatorService.class);
/**
* Instantiate Constructor
*/
public OSMSValidatorService() {
}
/**
* Execute validations
* @param request
* @return
* @throws OSMSValidatorServiceException
*/
@POST
@Path("validate")
public ValidatorResponse validate(final ValidatorRequest request)
throws OSMSValidatorServiceException {
LOGGER.debug("inside validate params{request: {}}"+request);
RuleValidatorService ruleValidatorService = new RuleValidatorServiceImpl();
ValidatorResponse response = ruleValidatorService.executeValidations(request);
LOGGER.debug("end validate "+response);
return response;
}
public static void main(String[] args) throws Exception {
String fileName = "C://Users/jchalamala/Desktop/projects/OSMS/Message Log XML/FQ.xml";
String content = new String(Files.readAllBytes(Paths.get(fileName)));
ValidatorRequest request = new ValidatorRequest();
request.setMessage(content);
request.setContentType("XML");
request.setMke("FQ");
request.setInputSource("NLETS");
OSMSValidatorService m = new OSMSValidatorService();
m.validate(request);
}
}
| [
"[email protected]"
] | |
0857aeed73ed61255168ec153c9eebd26334b733 | e545e261e5cadb90f6e9431de8b0a1311be28f2a | /src/main/java/com/library/controller/exceptions/BorrowNotFoundException.java | e0855e59a1c150998343ed521a07ab5d78acd18a | [] | no_license | daniellsoon/library-rest-api | b508b9814881db1258d3767c8a3867ffe1f1e711 | fbf68599b0ca6c25d5bfa8c0d3ce44617f2bc844 | refs/heads/master | 2022-12-16T08:34:41.401027 | 2020-09-10T22:55:55 | 2020-09-10T22:55:55 | 262,011,755 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 257 | java | package com.library.controller.exceptions;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
@ResponseStatus(value = HttpStatus.NOT_FOUND)
public class BorrowNotFoundException extends Exception {
}
| [
"[email protected]"
] | |
3fffb8a9e32898ce4c357683bea91c12f557d984 | 61af113714ca14303a8aa5901013fabe78b911d7 | /src/main/java/aura/hadoop/mapreduce/mapreduce_writablecomparable01/ScoreDriver.java | 171ec3f3dec733a1d937e5538de77985b072dd98 | [] | no_license | linyongfei001/SSODemo | 0c57b05290e22d3914df64eb257c9a4a34963c76 | 60edaff9ae600870fc548161f6eca90df4854cd4 | refs/heads/master | 2022-12-22T09:26:09.015376 | 2019-07-02T07:39:05 | 2019-07-02T07:39:05 | 190,027,538 | 0 | 0 | null | 2022-12-16T07:46:07 | 2019-06-03T15:00:28 | Java | UTF-8 | Java | false | false | 1,195 | java | package aura.hadoop.mapreduce.mapreduce_writablecomparable01;
import java.io.IOException;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
public class ScoreDriver {
public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException {
System.setProperty("HADOOP_USER_NAME", "hadoop");
Configuration conf=new Configuration();
Job job=Job.getInstance(conf);
job.setJarByClass(ScoreDriver.class);
job.setMapperClass(ScoreMapper.class);
job.setReducerClass(ScoreReducer.class);
//设置map和reduce的输出 如果map和reduce的输出的key value类型一样 只需要设置一个
//设置最终的输出类型就可以
job.setOutputKeyClass(ScoreBean.class);
job.setOutputValueClass(Text.class);
FileInputFormat.addInputPath(job, new Path("hdfs://hadoop01:9000/scorein"));
FileOutputFormat.setOutputPath(job, new Path("hdfs://hadoop01:9000/scoreout06"));
job.waitForCompletion(true);
}
}
| [
"[email protected]"
] | |
284aaa4f7c3788e275cbf4c44abc7ef485c64e83 | 62d5f786cd248518f475acba5cdc8ec0c162c107 | /scalable-ot-core/src/main/java/com/brotherjing/core/loadbalance/ServerEntity.java | c76bde78d69b209ae62baf8d7af7619085010fa0 | [
"MIT"
] | permissive | Sudarsan-Sridharan/scalable-ot-java-backend | 566e55ec0f826d23fca822e8f5a35e1ba1eb16fb | 75287dcd02d6187b2f0895ff4af06fcb5799e9d2 | refs/heads/master | 2023-03-04T10:25:22.019141 | 2019-11-27T10:42:32 | 2019-11-27T10:42:32 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 416 | java | package com.brotherjing.core.loadbalance;
import lombok.Builder;
import lombok.Data;
import lombok.ToString;
@Data
@Builder
@ToString
public class ServerEntity {
private String host;
private int serverPort;
private int dubboPort;
public String getServerAddress() {
return host + ":" + serverPort;
}
public String getDubboAddress() {
return host + ":" + dubboPort;
}
}
| [
"[email protected]"
] | |
e1a487c33d959b629c955b9eda03a847415e41a6 | 276df0eab5504f7e0253153175ff8cab0a2705ae | /Engine/mahout-core/org/apache/mahout/cf/taste/impl/common/SamplingIterator.java | 2e9cf491897535158cf1c639daf74f0975d45c82 | [] | no_license | ankitgoswami/SuggestionEngine | 0b9b56d276e515d1e6ede0f2c5e83ebb8ed30011 | 9279f47f0aa2df81f21d9150375df2c8418204e7 | refs/heads/master | 2016-09-05T23:26:16.245404 | 2012-03-01T10:22:53 | 2012-03-01T10:22:53 | 3,546,476 | 2 | 2 | null | null | null | null | UTF-8 | Java | false | false | 2,800 | java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.mahout.cf.taste.impl.common;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Random;
/**
* Wraps an {@link Iterator} and returns only some subset of the elements that it would, as determined by a sampling
* rate parameter.
*/
public final class SamplingIterator<T> implements Iterator<T> {
private static final Random r = RandomUtils.getRandom();
private final Iterator<? extends T> delegate;
private final double samplingRate;
private T next;
private boolean hasNext;
public SamplingIterator(Iterator<? extends T> delegate, double samplingRate) {
this.delegate = delegate;
this.samplingRate = samplingRate;
this.hasNext = true;
doNext();
}
@Override
public boolean hasNext() {
return hasNext;
}
@Override
public T next() {
if (hasNext) {
T result = next;
doNext();
return result;
}
throw new NoSuchElementException();
}
private void doNext() {
boolean found = false;
if (delegate instanceof SkippingIterator) {
SkippingIterator<? extends T> skippingDelegate = (SkippingIterator<? extends T>) delegate;
int toSkip = 0;
while (r.nextDouble() >= samplingRate) {
toSkip++;
}
// Really, would be nicer to select value from geometric distribution, for small values of samplingRate
if (toSkip > 0) {
skippingDelegate.skip(toSkip);
}
if (skippingDelegate.hasNext()) {
next = skippingDelegate.next();
found = true;
}
} else {
while (delegate.hasNext()) {
T delegateNext = delegate.next();
if (r.nextDouble() < samplingRate) {
next = delegateNext;
found = true;
break;
}
}
}
if (!found) {
hasNext = false;
next = null;
}
}
/**
* @throws UnsupportedOperationException
*/
@Override
public void remove() {
throw new UnsupportedOperationException();
}
}
| [
"[email protected]"
] | |
4fbc6d5da6080b5dbe7c02f703243f609d2870cc | 5eaa268d2b26a1e6b9c8ed8ef5d024a4e4c3c7f8 | /src/week08/zoo_v2/Fish.java | c939d32402b5bbedc82c1d934bc1f6b2cc3b744b | [] | no_license | nordnes/CS102 | df0389ae3277526ea8c51ff44d0ac221ddf2b668 | 35e313eb606a46e4e414056f9ee91acf7572c39d | refs/heads/master | 2020-05-01T08:32:37.405783 | 2018-05-15T07:36:09 | 2018-05-15T07:36:09 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 262 | java | package week08.zoo_v2;
public abstract class Fish extends Animal implements Swimmer {
public Fish(String name, String color) {
super(name, color);
}
public void swim() {
System.out.println(this.getName() + " is swimming.");
}
}
| [
"[email protected]"
] | |
ed724f75663cebc8848b0c32fb82a456fd67a4ab | aa7fc9a5c155160d634df58a8b29b847e2305d5e | /emailtemplates-ui-starter/src/main/java/io/jmix/autoconfigure/emailtemplatesui/package-info.java | 98734872d4901efb6415f2ac07ad941ad5c974bb | [
"Apache-2.0"
] | permissive | stvliu/jmix-emailtemplates | b2993554cccc2fd091825d7b9add2e65f701a708 | 7fe96ae540b53f09c165392c7493e6ec10677591 | refs/heads/master | 2023-03-29T17:53:36.831239 | 2021-03-24T13:37:40 | 2021-03-24T13:37:40 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 693 | java | /*
* Copyright 2020 Haulmont.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@Internal
package io.jmix.autoconfigure.emailtemplatesui;
import io.jmix.core.annotation.Internal; | [
"[email protected]"
] | |
704bf67a3f864517d9bf99f63b2c6f3d9f08e900 | 6e3d08c5660e27eb00233c73b302ecd918895098 | /pet-clinic-data/src/main/java/guru/springframework/sfgpetclinic/model/Visit.java | e2341c06ae07f398ada373e208fb8c78c862ee45 | [
"Apache-2.0"
] | permissive | wyzx/sfg-pet-clinic | ad4b3e410ab716a166a6015ac4fdeffd50328f53 | a7aa31d7e6f186799d16c44f4ff89f295dc2e235 | refs/heads/master | 2020-05-07T10:05:04.995077 | 2019-07-24T16:57:08 | 2019-07-24T16:57:08 | 180,404,267 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 702 | java | package guru.springframework.sfgpetclinic.model;
import java.time.LocalDate;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
@Builder
@Entity
@Table(name = "visits")
public class Visit extends BaseEntity {
@Column(name = "date")
private LocalDate date;
@Column(name = "description")
private String description;
@ManyToOne
@JoinColumn(name = "pet_id")
private Pet pet;
}
| [
"[email protected]"
] | |
1f5d5ec762841d2e0c80b92f69c1ab857e29ee98 | ad64a14fac1f0d740ccf74a59aba8d2b4e85298c | /linkwee-supermarket/src/main/java/com/linkwee/web/dao/CimProductMapper.java | ee52dcb8e2629b4ef4af0b5f96d2f644175864aa | [] | no_license | zhangjiayin/supermarket | f7715aa3fdd2bf202a29c8683bc9322b06429b63 | 6c37c7041b5e1e32152e80564e7ea4aff7128097 | refs/heads/master | 2020-06-10T16:57:09.556486 | 2018-10-30T07:03:15 | 2018-10-30T07:03:15 | 193,682,975 | 0 | 1 | null | 2019-06-25T10:03:03 | 2019-06-25T10:03:03 | null | UTF-8 | Java | false | false | 11,469 | java | package com.linkwee.web.dao;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.session.RowBounds;
import com.linkwee.api.request.cim.HotProductRequest;
import com.linkwee.api.request.cim.ProductCateForShowRequest;
import com.linkwee.api.request.cim.ProductDetailRequest;
import com.linkwee.api.request.cim.ProductPageList4Request;
import com.linkwee.api.request.cim.ProductPageListClassifyRequest;
import com.linkwee.api.request.cim.ProductPageListLimitRequest;
import com.linkwee.api.request.cim.ProductPageListRecommendRequest;
import com.linkwee.api.request.cim.ProductPageListRequest;
import com.linkwee.api.request.cim.ProductStatisticsRequest;
import com.linkwee.api.request.cim.ScreenProductPageListRequest;
import com.linkwee.api.request.cim.SelectedProductsListRequest;
import com.linkwee.api.response.cim.ProductDetailResponse;
import com.linkwee.api.response.cim.ProductInvestResponse;
import com.linkwee.api.response.cim.ProductPageList4Response;
import com.linkwee.api.response.cim.ProductPageListResponse;
import com.linkwee.api.response.cim.ProductStatistics460Response;
import com.linkwee.api.response.cim.ProductStatisticsResponse;
import com.linkwee.core.datatable.DataTable;
import com.linkwee.core.generic.GenericDao;
import com.linkwee.core.orm.paging.Page;
import com.linkwee.openapi.response.OmsProductResponse;
import com.linkwee.web.model.CimProduct;
import com.linkwee.web.request.ProductListDataRequest;
import com.linkwee.web.request.ProductSaleDetailRequest;
import com.linkwee.web.request.ProductSaleListRequest;
import com.linkwee.web.request.ProductsSalesStatisticsRequest;
import com.linkwee.web.response.ProductDetailForManageResponse;
import com.linkwee.web.response.ProductListForManageResponse;
import com.linkwee.web.response.ProductSaleDetailResponse;
import com.linkwee.web.response.ProductSaleListResponse;
import com.linkwee.web.response.ProductsSalesStatisticsResponse;
import com.linkwee.web.response.act.ProductPageResponse;
import com.linkwee.web.response.orgInfo.OrgSaleProductResponse;
/**
*
* @描述: Dao接口
*
* @创建人: liqi
*
* @创建时间:2016年07月14日 18:23:34
*
* Copyright (c) 深圳领会科技有限公司-版权所有
*/
public interface CimProductMapper extends GenericDao<CimProduct,Long>{
/**
* 封装DataTable对象查询
* @param dt
* @param page
* @return
*/
List<CimProduct> selectBySearchInfo(@Param("dt")DataTable dt,RowBounds page);
/**
* 查询热门产品
* @param userId
* @param page
* @return
*/
List<ProductPageListResponse> queryHotProduct(HotProductRequest hotProductRequest,RowBounds page);
/**
* 理财-产品列表
* @param userId
* @param page
* @return
*/
List<ProductPageListResponse> queryProductPageList(ProductPageListRequest productPageListRequest,Page<ProductPageListResponse> page);
/**
* 理财-理财师推荐产品列表 带排序
* @param userId
* @param page
* @return
*/
List<ProductPageListResponse> queryRecdProductPageList(ProductPageListRecommendRequest productPageListRecommendRequest,Page<ProductPageListResponse> page);
/**
* 查询机构在售产品列表
* @param orgNumber 机构编码
* @param page 分页信息
* @return
*/
List<OrgSaleProductResponse> queryOrgSaleProducts(@Param("orgNumber")String orgNumber,RowBounds page);
/**
* 查询产品详情
* @param productDetailRequest
* @return
*/
ProductDetailResponse queryProductDetail(ProductDetailRequest productDetailRequest);
/**
* 获取浮动期限产品 -
* @return
*/
List<CimProduct> getFlowProducts();
/**
* 查询筛选产品
* @param productPageListRequest
* @param page
* @return
*/
List<ProductPageListResponse> queryProductScreenPageList(ScreenProductPageListRequest productPageListRequest, Page<ProductPageListResponse> page);
/**
* 根据条件查询产品
* @param orgNumber
* @param proName
* @param page
* @return
*/
List<ProductPageResponse> queryProductByProductName(@Param("orgNumber")String orgNumber,@Param("proName")String proName,RowBounds page);
/**
* 根据条件查询产品
* @param pids
* @param page
* @return
*/
List<ProductPageResponse> queryProductByProductIds(@Param("pids")String[] pids);
/**
* 管理后台查询产品列表
* @param productListDataRequest
* @param page
* @return
*/
List<ProductListForManageResponse> selectProductListForManage(@Param("query")ProductListDataRequest productListDataRequest,Page<ProductListForManageResponse> page);
/**
* 后台管理-根据产品id查询产品详情
* @param productId
* @return
*/
ProductDetailForManageResponse queryProductDetailForManerge(String productId);
/**
* 产品审核
* @param auditType 审核类型 partAudit-部分审核 allAudit-全部审核
* @param auditCode 审核code 0-审核通过 1-审核未通过
* @param productTableIdList 待审核的产品表主键id列 格式 1,2,3,4
* @return
*/
void productAudit(@Param("auditType")String auditType,@Param("auditCode")Integer auditCode,@Param("productTableIdList")String productTableIdList);
/**
* 后台管理系统-查询产品销售列表
* @param productSaleListRequest
* @param page
* @return
*/
List<ProductSaleListResponse> selectProductSaleListForManage(@Param("query")ProductSaleListRequest productSaleListRequest,Page<ProductSaleListResponse> page);
/**
* 后台管理系统-查询产品销售详情
* @param productSaleDetailRequest
* @return
*/
List<ProductSaleDetailResponse> selectProductSaleDetail(@Param("query")ProductSaleDetailRequest productSaleDetailRequest);
/**
* 查询产品销售统计 为data-tables封装
* @param productsSalesStatisticsRequest
* @param page
* @return
*/
List<ProductsSalesStatisticsResponse> selectSalesStatisticsByDatatables(@Param("query")ProductsSalesStatisticsRequest productsSalesStatisticsRequest,Page<ProductsSalesStatisticsResponse> page);
/**
* 查询产品销售统计
* @param productsSalesStatisticsRequest
* @param page
* @return
*/
List<ProductsSalesStatisticsResponse> selectSalesStatisticsByDatatables(@Param("query")ProductsSalesStatisticsRequest productsSalesStatisticsRequest);
/**
* 查询询产品销售详情(PC)
* @param productId
* @param page
* @return
*/
List<ProductInvestResponse> getProductInvestList(@Param("productId")String productId,RowBounds page);
/**
* 查询产品分类统计
* @param productStatisticsRequest
* @return
*/
List<ProductStatisticsResponse> productClassifyStatistics(ProductStatisticsRequest productStatisticsRequest);
/**
* 查询产品分类统计
* @param productStatisticsRequest
* @return
*/
List<ProductStatistics460Response> productClassifyStatistics460(ProductStatisticsRequest productStatisticsRequest);
/**
* 理财师推荐产品 统计
* @param productStatisticsExtendRequest
* @return
*/
ProductStatisticsResponse queryRecdProductStatistics(ProductStatisticsRequest productStatisticsRequest);
/**
* 根据产品分类查询产品分类列表 翻页
* @param productPageListClassifyRequest
* @param page
* @return
*/
List<ProductPageListResponse> queryProductCatePageList(ProductPageListClassifyRequest productPageListClassifyRequest,Page<ProductPageListResponse> page);
/**
* 根据产品分类查询产品分类列表 翻页
* @param productPageListClassifyRequest
* @param page
* @return
*/
List<ProductPageList4Response> queryProductCatePageList460(ProductPageList4Request productPageList4Request,Page<ProductPageList4Response> page);
/**
* 扩展产品分类查询产品分类列表 翻页
* @param productPageListClassifyRequest
* @param page
* @return
*/
List<ProductPageListResponse> queryProductCateExtendsPageList(ProductPageListClassifyRequest productPageListClassifyRequest,Page<ProductPageListResponse> page);
/**
* 扩展产品分类 产品 统计
* 901-首投标 902-复投标
* @param productStatisticsRequest
* @return
*/
ProductStatisticsResponse queryProductCateExtendsStatistics(ProductStatisticsRequest productStatisticsRequest);
/**
* 查询产品可展示的标签列表
* @param productId
* @return
*/
ArrayList<String> queryProductCateForShow(ProductCateForShowRequest productCateForShowRequest);
/**
* 根据机构代码更改产品的佣金
* @param orgNumber 机构代码
* @param feeRatio 佣金
* @return
*/
int updateFeeRatioByOrgNumber(@Param("orgNumber")String orgNumber, @Param("feeRatio")BigDecimal feeRatio);
/**
* 热推产品列表分页
* @param productPageListClassifyRequest
* @param page
* @return
*/
List<ProductPageListResponse> queryHotRecommendPageList(ProductPageListClassifyRequest productPageListClassifyRequest,Page<ProductPageListResponse> page);
/**
* 理财师最新推荐的产品
* @param productPageListRecommendRequest
* @return
*/
ProductPageListResponse queryNewestRecdProduct(ProductPageListRecommendRequest productPageListRecommendRequest);
/**
* 没有投资记录的平台的新手标
* @param productPageListClassifyRequest
* @return
*/
ProductPageListResponse queryNotInvestPlatformNewerProduct(ProductPageListClassifyRequest productPageListClassifyRequest);
/**
*
* @param productPageListClassifyRequest
* @return
*/
ProductPageListResponse queryProductCateList(ProductPageListClassifyRequest productPageListClassifyRequest);
/**
* 热推产品列表(TOP10)
* @param ProductPageListRequest
* @param page
* @return
*/
List<ProductPageListResponse> queryHotRecommendPageListTop(ProductPageListRequest productPageListRequest);
/**
* 查询产品补全理财师排行榜
* @param productPageListLimitRequest
* @return
*/
List<ProductPageListResponse> queryAddProductPageList(ProductPageListLimitRequest productPageListLimitRequest);
/**
* 查询产品列表4.0
* @param productPageList4Request
* @param page
* @return
*/
List<ProductPageList4Response> queryProductPageList4(ProductPageList4Request productPageList4Request,Page<ProductPageList4Response> page);
/**
* 查询产品列表统计4.0
* @param productPageList4Request
* @return
*/
Integer productPageListStatistics4(ProductPageList4Request productPageList4Request);
/**
* 猎财大师首页精选产品
* @return
*/
List<ProductPageList4Response> querySelectedProducts(ProductPageListRequest productPageListRequest);
/**
* 猎财大师首页精选产品列表
* @param selectedProductsListRequest
* @param page
* @return
*/
List<ProductPageList4Response> querySelectedProductsList(SelectedProductsListRequest selectedProductsListRequest,Page<ProductPageList4Response> page);
/**
* 开放平台接入领会理财产品列表
* @param queryProductSql
* @return
*/
List<OmsProductResponse> queryOmsProductList(@Param("queryProductSql")String queryProductSql,Page<OmsProductResponse> page);
}
| [
"[email protected]"
] | |
ace88f1efe571e78fb8ed0cee44d03992a415118 | b5d08e195cae9a3fad0772ea2b359f5791d5b4e3 | /src/test/java/starter/navigation/NavigateTo.java | 90eb7f84903dedd3739d885f5931881331006a0d | [] | no_license | axstav/retoTecnicoChoucair | 121dd2b9ed25980db0998c313995d1c048be97ff | 4d1dc922ca634ad1792813b1d9b6a1b4871d3e19 | refs/heads/main | 2023-04-11T01:45:24.778401 | 2021-04-23T04:52:00 | 2021-04-23T04:52:00 | 360,764,213 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 424 | java | package starter.navigation;
import net.serenitybdd.screenplay.Performable;
import net.serenitybdd.screenplay.Task;
import net.serenitybdd.screenplay.actions.Open;
public class NavigateTo {
public static Performable theNewExperienceSignInPage() {
return Task.where("{0} opens the NewExperience sign in page",
Open.browserOn().the(NewExperienceSignInPage.class)
);
}
} | [
"[email protected]"
] | |
7f26515e0b63603c5bb1e83d9221fafaa967e779 | 7a4a3daf299c451a7f5104e7632027240dace19b | /Week_07/itjun-week07-homework02/base-mysql-proxy/src/main/java/io/itjun/week07/work14/datasource/SlaveDatasource.java | a3e151f82092b27c5726e5e57010a54df70cbee8 | [] | no_license | itjun/JAVA-01 | 6135aefad5f660c8b805de27f1093d4c8e387c6c | bd1d1822625a0a70e1c16a1ae46029ac285fcc33 | refs/heads/main | 2023-05-01T15:37:28.874177 | 2021-05-16T13:56:31 | 2021-05-16T13:56:31 | 325,822,092 | 0 | 0 | null | 2020-12-31T15:03:19 | 2020-12-31T15:03:18 | null | UTF-8 | Java | false | false | 736 | java | package io.itjun.week07.work14.datasource;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import java.util.ArrayList;
import java.util.List;
@Configuration
@ConfigurationProperties(prefix = "datasource")
public class SlaveDatasource {
List<BaseDataSourceAttribute> slave = new ArrayList<BaseDataSourceAttribute>();
public SlaveDatasource() {
}
public SlaveDatasource(List<BaseDataSourceAttribute> slave) {
this.slave = slave;
}
public List<BaseDataSourceAttribute> getSlave() {
return slave;
}
public void setSlave(List<BaseDataSourceAttribute> slave) {
this.slave = slave;
}
}
| [
"[email protected]"
] | |
cc5d5562ba71c926795c0d110461adb2273fc104 | 2fdc9e132234f68c939360f4213447129e7b9f4d | /spring-boot-distributedlock/src/main/java/com/darren/center/springboot/filter/FilterChain.java | 4aad8536d29e59094d91665751e36acc4eea7264 | [] | no_license | axin1240101543/spring-boot | 20086a3a9afb1f14b294097ee1fd41b2a91e5e67 | af305bd7e367bd3422a879ab568660107d6fb529 | refs/heads/master | 2022-07-04T14:46:01.129482 | 2019-09-12T08:53:40 | 2019-09-12T08:53:40 | 176,437,648 | 0 | 2 | null | 2022-06-17T02:10:24 | 2019-03-19T06:14:52 | CSS | UTF-8 | Java | false | false | 335 | java | package com.darren.center.springboot.filter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public interface FilterChain {
/**
* 构建处理链
* @param request
* @param response
*/
void handler(HttpServletRequest request, HttpServletResponse response);
}
| [
"[email protected]"
] | |
f8761833687391e68efb747ec20bd82214a19af0 | dcb181bcde682958930a48184e9422b7f15d3fbd | /Testowy/src/RoomState.java | 46d5af6df64f582093ee8abefde453607d6d033d | [] | no_license | jalowiec/test | 10c9f28501c90947c27f1bf5a9a104bb56298587 | 76acc8f2fc08b98b31771c0a3692d9168ca3cb13 | refs/heads/master | 2020-03-10T02:58:43.937276 | 2018-04-20T19:07:40 | 2018-04-20T19:07:40 | 129,146,472 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 72 | java |
public interface RoomState {
public void stateDescription();
}
| [
"[email protected]"
] | |
3e9dc9790fdd3ff340683642d2f62f93df831f89 | fa91450deb625cda070e82d5c31770be5ca1dec6 | /Diff-Raw-Data/10/10_ff53eaf3dd2a020888e9c9290f08a723f9be3dbb/ArchiveFragment/10_ff53eaf3dd2a020888e9c9290f08a723f9be3dbb_ArchiveFragment_s.java | 7e28d25cbdc49a326ab2c0c0d50fc20faee497bc | [] | no_license | zhongxingyu/Seer | 48e7e5197624d7afa94d23f849f8ea2075bcaec0 | c11a3109fdfca9be337e509ecb2c085b60076213 | refs/heads/master | 2023-07-06T12:48:55.516692 | 2023-06-22T07:55:56 | 2023-06-22T07:55:56 | 259,613,157 | 6 | 2 | null | 2023-06-22T07:55:57 | 2020-04-28T11:07:49 | null | UTF-8 | Java | false | false | 2,801 | java | package se.slashat.slashat.fragment;
import se.slashat.slashat.CallbackPair;
import se.slashat.slashat.R;
import se.slashat.slashat.adapter.EpisodeDetailAdapter;
import se.slashat.slashat.adapter.PersonAdapter;
import se.slashat.slashat.adapter.PersonalAdapter;
import se.slashat.slashat.androidservice.EpisodePlayer;
import se.slashat.slashat.async.EpisodeLoaderAsyncTask;
import se.slashat.slashat.model.Episode;
import se.slashat.slashat.model.Personal;
import se.slashat.slashat.service.PersonalService;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
public class ArchiveFragment extends ListFragment implements CallbackPair<Episode, Boolean> {
public final static String EPISODEPLAYER = "episodePlayer";
public static final String ADAPTER = "adapter";
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_archive, container, false);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle bundle = savedInstanceState == null ? getArguments()
: savedInstanceState;
@SuppressWarnings("unchecked")
ArrayAdapter<Personal> adapter = (ArrayAdapter<Personal>) bundle.getSerializable(ADAPTER);
// If no adapter is found in the bundle create a new one with all
// people.
if (adapter == null) {
EpisodeLoaderAsyncTask episodeLoaderAsyncTask = new EpisodeLoaderAsyncTask(this);
episodeLoaderAsyncTask.execute();
}else{
setListAdapter(adapter);
}
}
/**
* Callback from the Adapter requesting an episode to be played.
*/
@Override
public void call(Episode episode, Boolean showDetails) {
if (showDetails) {
EpisodeDetailAdapter p = new EpisodeDetailAdapter(getActivity(), R.layout.archive_item_details, new Episode[] { episode },this);
Bundle bundle = new Bundle();
bundle.putSerializable(ADAPTER, p);
ArchiveFragment archiveFragment = new ArchiveFragment();
archiveFragment.setArguments(bundle);
FragmentSwitcher.getInstance().switchFragment(archiveFragment, true);
} else {
ProgressDialog progressDialog = new ProgressDialog(getActivity());
progressDialog.setTitle("Buffrar avsnitt");
progressDialog.setMessage(episode.getFullEpisodeName());
progressDialog.show();
EpisodePlayer.getEpisodePlayer().stopPlay();
EpisodePlayer.getEpisodePlayer().initializePlayer(episode.getStreamUrl(), episode.getFullEpisodeName(), 0, progressDialog);
}
}
}
| [
"[email protected]"
] | |
d705d0b4207c021b79849b697683f64d5f9d2654 | 672122a49e104424393c413eeac954f4ae33ed1a | /src/main/java/com/example/landsale/repository/UserRepository.java | 3f6e5808ca31394ea0a2778a8f5c5a0107f146f3 | [] | no_license | RavinduLakmal/landsale | 627185f14df235eaebc23cd93949dec3789e4b75 | 54a069530109a5e9d2bd18608a3da2dfa19e73d3 | refs/heads/master | 2021-06-16T04:50:46.599916 | 2019-07-11T08:15:12 | 2019-07-11T08:15:12 | 193,671,072 | 0 | 0 | null | 2021-04-26T19:20:05 | 2019-06-25T08:53:02 | Java | UTF-8 | Java | false | false | 326 | java | package com.example.landsale.repository;
import com.example.landsale.entit.User;
import com.example.landsale.repository.custom.UserCustom;
import org.springframework.data.jpa.repository.JpaRepository;
public interface UserRepository extends JpaRepository<User,Long>, UserCustom {
User findByUsername(String userName);
}
| [
"[email protected]"
] | |
74f3e0f5325be4d33d04a4134778ff324e6a04d9 | a703e00b9a7d317941187663a10d438a1a651b0c | /src/coinpurse/Valuable.java | 9388de1c56679d15a7efaae8ee456dfc26413eee | [] | no_license | Pimwalun/coinpurse | 3e1368f97cdd6229d3a4a1d3ca2852e5fb13b7fd | cad2795214c16570a86f00e52e5ba5145c62b2c8 | refs/heads/master | 2021-01-22T05:54:11.022095 | 2017-02-26T16:39:09 | 2017-02-26T16:39:09 | 81,719,122 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 435 | java | package coinpurse;
/**
* An interface for objects having a monetary value and currency.
* @author Pimwalun Witchawanitchanun
*/
public interface Valuable extends Comparable<Valuable>{
/**
* Get the monetary value of this object, in its own currency.
* @return the value of this object
*/
public double getValue();
/**
* Get the currency of item.
* @return the currency of item
*/
public String getCurrency();
}
| [
"[email protected]"
] | |
f99ae417bd5fd902ce847e312b8571f5304fd010 | b24e0163985b052650e81d1381a71a0ab5219472 | /src/main/java/dev/omoladecodes/employeemanagement/exception/ResourceNotFoundException.java | d4d3a2d3603a2fb783820832ab605f1eb00405ff | [] | no_license | Omojolade/EmployeeManagementSystem | 1ed0c79da3dccd0cabb1edc291c7ada60a5b5740 | aba31d46c2de2f355962b7cb513d658f109e9947 | refs/heads/master | 2023-07-27T00:40:58.441573 | 2021-09-11T00:29:01 | 2021-09-11T00:29:01 | 405,247,195 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 946 | java | package dev.omoladecodes.employeemanagement.exception;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
@ResponseStatus(value= HttpStatus.NOT_FOUND)
public class ResourceNotFoundException extends RuntimeException{
private static final long serialVersionUID = 1L;
private String resourceName;
private String fieldName;
private Object fieldValue;
public ResourceNotFoundException(String resourceName, String fieldName, Object fieldValue) {
super(String.format("%s not found %s : '%s'", resourceName,fieldName,fieldValue));
this.resourceName = resourceName;
this.fieldName = fieldName;
this.fieldValue = fieldValue;
}
public String getResourceName() {
return resourceName;
}
public String getFieldName() {
return fieldName;
}
public Object getFieldValue() {
return fieldValue;
}
}
| [
"[email protected]"
] | |
cdb2fd51e6692137a530d8d65d31d29fb4579c4a | 456ea24b146ca940807cfb7605f41be17f9b14e2 | /project1027/SwingMail/src/com/swingmall/cart/Cart.java | 5363e32f69c08270a62cd9054defb507b9f89e04 | [] | no_license | ShinHyungjin/Java_WorkSpace | 88832cba936ec9dd292908c65dde165182130e0f | 1bfecfb8e830c40cbe85e7475f1cdf2ae507044b | refs/heads/master | 2023-01-28T08:20:10.436036 | 2020-12-04T05:02:22 | 2020-12-04T05:02:22 | 305,313,266 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,571 | java | /*
* 장바구니 페이지를 정의한다
* */
package com.swingmall.cart;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import com.swingmall.main.Page;
import com.swingmall.main.ShopMain;
public class Cart extends Page{
JPanel bt_container; //버튼을 묶어줄 컨테이너
JButton bt_pay;//결제단계로 가기
JButton bt_del; //장바구니 비우기
//장바구니 역할을 컬렉션 프레임웍 객체를 선언
HashMap<Integer,CartVO> cartList;
JPanel p_content;
public Cart(ShopMain shopMain) {
super(shopMain);
cartList = new HashMap<Integer, CartVO>();
//this.setBackground(Color.BLACK);
bt_container = new JPanel();
bt_pay = new JButton("결제하기");
bt_del = new JButton("장바구니 비우기");
//스타일
bt_container.setPreferredSize(new Dimension(ShopMain.WIDTH, 100));
bt_container.setBackground(Color.CYAN);
//getCartList();
bt_container.add(bt_pay);
bt_container.add(bt_del);
add(bt_container, BorderLayout.SOUTH);
bt_del.addActionListener((e) -> {
removeAll();
});
}
//장바구니에 넣기
public void addCart(CartVO vo) { //상품1건을 장바구니에 추가하기!!!
cartList.put(vo.getProduct_id(), vo); //key와 값을 저장
}
//장바구니 삭제하기
public void removeCart(int key) { //상품1건을 장바구니에서 제거하기
cartList.remove(key);
}
//장바구니 비우기
public void removeAll() { //모든 상품을 장바구니에서 제거하기
if(JOptionPane.showConfirmDialog(this, "정말 모든 내역을 삭제하시겠습니까?")==JOptionPane.OK_OPTION) {
cartList.clear();
getCartList();
}
}
public void updateCart(int key, int ea) {
cartList.get(key).setEa(ea);
}
//장바구니 목록 가져오기 (주의: 맵은 순서가 없는 집합이므로 먼저 일렬로 늘어뜨려야 한다..그 후 접근..)
public void getCartList() {
Set<Integer> set = cartList.keySet(); //키들을 set으로 반환받는다..즉 맵은 한번에 일렬로 늘어서는 것이 아니라, set으로 먼저
//key를 가져와야 함
Iterator<Integer> it = set.iterator();
//add()하기 전에 기존에 붙어있던 모든 컴포넌트는 제거
int count=0;
if(p_content!=null) {
this.remove(p_content);
this.revalidate();
this.updateUI();
this.repaint();
}
p_content = new JPanel();
p_content.setPreferredSize(new Dimension(ShopMain.WIDTH-350, 500));
while(it.hasNext()) {//요소가 있는 동안..
int key=it.next();//요소를 추출
System.out.println("key : "+key);
CartVO vo=cartList.get(key);
//디자인을 표현하는 CartItem에 CartVO의 정보를 채워넣자!!
CartItem item = new CartItem(vo);
item.bt_del.addActionListener((e) -> {
if(JOptionPane.showConfirmDialog(this, "정말 삭제하시겠습니까?")==JOptionPane.OK_OPTION) {
removeCart(vo.getProduct_id());
getCartList();
}
});
item.bt_update.addActionListener((e) -> {
if(JOptionPane.showConfirmDialog(this, "정말 수량을 수정 하시겠습니까?")==JOptionPane.OK_OPTION) {
updateCart(vo.getProduct_id(), Integer.parseInt(item.t_ea.getText()));
getCartList();
}
});
p_content.add(item);
count++;
}
add(p_content);
this.updateUI();
System.out.println("count is "+count);
}
}
| [
"[email protected]"
] | |
407f95dcc6e835d4a36a9950237732414e578f15 | 24d6ff6473e3ecbb67e80f2e6910c68dd53d4b74 | /app/src/main/java/faatih/com/startupnews/fragments/Teknopedia.java | 9a5dc23f61c93fd10503445dbb71d0b5046a7481 | [] | no_license | faatihrifqi/StartupNews | cb99b26cbf004bd2eed2e6f4fc50b72b46fbda75 | 2062595acb398e827b55a9ae7706059b8ab85bda | refs/heads/master | 2021-01-16T19:38:42.362945 | 2017-08-13T15:55:29 | 2017-08-13T15:55:29 | 100,187,084 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,323 | java | package faatih.com.startupnews.fragments;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.orangegangsters.github.swipyrefreshlayout.library.SwipyRefreshLayout;
import com.orangegangsters.github.swipyrefreshlayout.library.SwipyRefreshLayoutDirection;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.io.IOException;
import java.util.ArrayList;
import faatih.com.startupnews.News;
import faatih.com.startupnews.R;
import faatih.com.startupnews.adapter.MyAdapter;
public class Teknopedia extends Fragment implements MyAdapter.ListItemClickListener {
private final static String BASE_URL = "http://www.teknopedia.asia/";
private final static String MAIN_CLASS = "meta-image";
private int myPages = 1;
private ArrayList<News> list_news;
private MyAdapter adapter;
private SwipyRefreshLayout mSwipyRefreshLayout;
public Teknopedia() {
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.recycler_list, container, false);
list_news = new ArrayList<>();
myPages = 1;
mSwipyRefreshLayout = (SwipyRefreshLayout) view.findViewById(R.id.swipyrefreshlayout);
mSwipyRefreshLayout.setColorSchemeResources(R.color.colorAccent, R.color.orange, R.color.green, R.color.blue);
RecyclerView rv = (RecyclerView) view.findViewById(R.id.rv);
rv.setHasFixedSize(true);
LinearLayoutManager llm = new LinearLayoutManager(getActivity().getApplicationContext());
rv.setLayoutManager(llm);
adapter = new MyAdapter(list_news, this);
rv.setAdapter(adapter);
mSwipyRefreshLayout.setOnRefreshListener(new SwipyRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh(SwipyRefreshLayoutDirection direction) {
myPages+=1;
new DownloadNewsTask().execute();
}
});
//run first when onCreate called
mSwipyRefreshLayout.post(new Runnable() {
@Override
public void run() {
new DownloadNewsTask().execute();
}
});
return view;
}
private Document openConnection(String newUrl){
Connection.Response response;
try {
response = Jsoup.connect(newUrl).userAgent("Mozilla").timeout(5000).execute();
if(response.statusCode() == 200)
return response.parse();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private class DownloadNewsTask extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
mSwipyRefreshLayout.setRefreshing(true);
}
@Override
protected Void doInBackground(Void... params) {
Document new_doc = openConnection(BASE_URL + "page/" + myPages);
if(new_doc != null){
Elements links = new_doc.getElementsByClass(MAIN_CLASS);
for (Element link : links) {
Elements myLink = link.getElementsByTag("a");
String title = myLink.attr("title");
String url = myLink.attr("href");
list_news.add(new News(title, url));
}
}
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
mSwipyRefreshLayout.setRefreshing(false);
mSwipyRefreshLayout.setDirection(SwipyRefreshLayoutDirection.BOTTOM);
adapter.notifyDataSetChanged();
}
}
@Override
public void onListItemClick(News news) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(news.getUrl())));
}
}
| [
"[email protected]"
] | |
26f548076aebf56a272044bb7a9cef4781be86ff | 2b6cfe45e00bdefad33432d8a29baae82391fc3b | /src/main/java/com/gahon/utils/IpUtils.java | 8ef6360442de88979c182a0bd47e6f8bb253733d | [] | no_license | Gahon1995/GahonUtils | beedb7adb0600a816ab68e49af385bed8d715ad4 | 42a3bd5d3641fedcaf6a1204bd1b5bb61b2354d9 | refs/heads/master | 2022-12-21T02:33:36.281924 | 2021-04-15T15:52:20 | 2021-04-15T15:52:20 | 233,371,123 | 0 | 0 | null | 2022-12-16T05:11:32 | 2020-01-12T09:57:59 | Java | UTF-8 | Java | false | false | 1,876 | java | package com.gahon.utils;
import javax.servlet.http.HttpServletRequest;
/**
* @author Gahon
* @date 2020/1/12
*/
public class IpUtils {
/**
* 获取用户真实IP地址,不使用request.getRemoteAddr();的原因是有可能用户使用了代理软件方式避免真实IP地址,
* <p>
* 可是,如果通过了多级反向代理的话,X-Forwarded-For的值并不止一个,而是一串IP值,究竟哪个才是真正的用户端的真实IP呢?
* 答案是取X-Forwarded-For中第一个非unknown的有效IP字符串。
* <p>
* 如:X-Forwarded-For:192.168.1.110, 192.168.1.120, 192.168.1.130,
* 192.168.1.100
* <p>
* 用户真实IP为: 192.168.1.110
*
* @param request
* @return
*/
public static String getIpAddr(HttpServletRequest request) {
String ip = request.getHeader("X-Forwarded-For");
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("X-Real-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_CLIENT_IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_X_FORWARDED_FOR");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
if (ip.contains(",")) {
return ip.split(",")[0];
} else {
return ip;
}
}
}
| [
"[email protected]"
] | |
3bce8df444d5df54b1fbd7d9f87d7b8d9f5a8340 | fc31b57a1d225e0971b6def80293cb403ba35fdd | /Surveillance/src/Location.java | 9617551077a8aceb117072ff5971219d7f3840db | [] | no_license | KovaxG/Distributed-Control-Systems-Project | 7e95322c53ccf487b31cac208ae5883ee97921e0 | 890cbd54228e54c61517db75806974701afc7968 | refs/heads/master | 2020-06-14T09:42:05.716804 | 2017-01-16T14:50:22 | 2017-01-16T14:50:22 | 75,202,330 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 619 | java | public class Location {
private int ID;
private String latitude;
private String longitude;
private long timestamp;
public Location(int id, String lat, String lon, long ts) {
ID = id;
latitude = lat;
longitude = lon;
timestamp = ts;
} // End of Location
public int getID() {return ID;}
public String getLat() {return latitude;}
public String getLon() {return longitude;}
public long getTS() {return timestamp;}
/// Actually to DIY JSON
public String toString() {
return "(" + ID + ", " + latitude + ", " + longitude + ", " + timestamp + ")";
} // End of toString
} // End of Class Location
| [
"[email protected]"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.