blob_id
stringlengths
40
40
__id__
int64
225
39,780B
directory_id
stringlengths
40
40
path
stringlengths
6
313
content_id
stringlengths
40
40
detected_licenses
list
license_type
stringclasses
2 values
repo_name
stringlengths
6
132
repo_url
stringlengths
25
151
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
70
visit_date
timestamp[ns]
revision_date
timestamp[ns]
committer_date
timestamp[ns]
github_id
int64
7.28k
689M
star_events_count
int64
0
131k
fork_events_count
int64
0
48k
gha_license_id
stringclasses
23 values
gha_fork
bool
2 classes
gha_event_created_at
timestamp[ns]
gha_created_at
timestamp[ns]
gha_updated_at
timestamp[ns]
gha_pushed_at
timestamp[ns]
gha_size
int64
0
40.4M
gha_stargazers_count
int32
0
112k
gha_forks_count
int32
0
39.4k
gha_open_issues_count
int32
0
11k
gha_language
stringlengths
1
21
gha_archived
bool
2 classes
gha_disabled
bool
1 class
content
stringlengths
7
4.37M
src_encoding
stringlengths
3
16
language
stringclasses
1 value
length_bytes
int64
7
4.37M
extension
stringclasses
24 values
filename
stringlengths
4
174
language_id
stringclasses
1 value
entities
list
contaminating_dataset
stringclasses
0 values
malware_signatures
list
redacted_content
stringlengths
7
4.37M
redacted_length_bytes
int64
7
4.37M
alphanum_fraction
float32
0.25
0.94
alpha_fraction
float32
0.25
0.94
num_lines
int32
1
84k
avg_line_length
float32
0.76
99.9
std_line_length
float32
0
220
max_line_length
int32
5
998
is_vendor
bool
2 classes
is_generated
bool
1 class
max_hex_length
int32
0
319
hex_fraction
float32
0
0.38
max_unicode_length
int32
0
408
unicode_fraction
float32
0
0.36
max_base64_length
int32
0
506
base64_fraction
float32
0
0.5
avg_csv_sep_count
float32
0
4
is_autogen_header
bool
1 class
is_empty_html
bool
1 class
shard
stringclasses
16 values
203a908ab600f17fa99161208b6b1b8cdc7a7c5c
8,546,984,980,778
3196222fa8a23a22a57409421c1572ea328bd2f7
/src/com/davis_newman_group18/chess/Coordinate.java
d0ed350af7f20f475c6d367747e5fd8747425a0a
[]
no_license
JD797/ChessApp
https://github.com/JD797/ChessApp
83e3cbf6faaf87514d6eab5cce244fd899b221ab
fc0b2744eebc8adfb01a67c2206c5aa1c3e8aaa8
refs/heads/master
2020-04-01T13:14:21.904000
2015-05-03T18:39:25
2015-05-03T18:39:25
34,772,259
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.davis_newman_group18.chess; import java.io.Serializable; public class Coordinate implements Serializable { private static final long serialVersionUID = 1L; int row; int col; public Coordinate(int row, int col) { this.row = row; this.col = col; } public boolean equals(Object o) { if (!(o instanceof Coordinate)) return false; Coordinate coordinate = (Coordinate)o; return (coordinate.row == row && coordinate.col == col); } }
UTF-8
Java
466
java
Coordinate.java
Java
[]
null
[]
package com.davis_newman_group18.chess; import java.io.Serializable; public class Coordinate implements Serializable { private static final long serialVersionUID = 1L; int row; int col; public Coordinate(int row, int col) { this.row = row; this.col = col; } public boolean equals(Object o) { if (!(o instanceof Coordinate)) return false; Coordinate coordinate = (Coordinate)o; return (coordinate.row == row && coordinate.col == col); } }
466
0.706009
0.699571
23
19.26087
19.891483
58
false
false
0
0
0
0
0
0
1.391304
false
false
2
a7b226d97a6249782fda795ec8fa1f970ee220f1
24,309,514,959,775
6d63db8dab8db05e0c015dc9e52d8bfa9b73e208
/src/main/java/it/epicode/controller/EdificioController.java
a061a90829c4bee845359130001e4944fbc6e5d2
[]
no_license
dieveg82/GestioniPrenotazioniRest
https://github.com/dieveg82/GestioniPrenotazioniRest
58e3b258fa73e41aaf9f766c838ad25ea8ace760
25205a38bd61ff23e5dc7a3c7c5fa0ca82c5b888
refs/heads/master
2023-08-23T14:58:45.240000
2021-11-07T09:33:33
2021-11-07T09:33:33
425,462,166
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package it.epicode.controller; import java.util.HashMap; import java.util.List; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import it.epicode.model.Città; import it.epicode.model.Edificio; import it.epicode.service.EdificioService; @RestController @RequestMapping("/controlleredificio") public class EdificioController { @Autowired EdificioService edificioService; @GetMapping("/findedificio") List<Edificio> findAll() { return edificioService.myFindAllUsers(); } @GetMapping("/insertedificio") String insertEdificio(@RequestParam String nomeEdificio, @RequestParam String indirizzo, @RequestParam String nomeCitta) { edificioService.myInsertEdificio(nomeEdificio, indirizzo, nomeCitta); return "Edificio inserito con successo"; } @GetMapping("/findedificionome") List<Edificio> findEdificio(@RequestParam String nomeEdificio) { return edificioService.myFindByEdificio(nomeEdificio); } @GetMapping(value = "/findedificioalledificiopagesize", produces = MediaType.APPLICATION_JSON_VALUE) public Page myGetAllEdificioPageSize(@RequestParam(defaultValue = "0") int page, @RequestParam(defaultValue = "3") int size) { Page<Edificio> edificio = edificioService.myFindAllEdificioPageSize(page, size); return edificio; } @GetMapping(value = "/mygetalledificiopagesizesort", produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<List<Edificio>> myGetAllEdificioPageSizeSort(@RequestParam(defaultValue = "0") Integer page, @RequestParam(defaultValue = "2") Integer size, @RequestParam(defaultValue = "id") String sort) { List<Edificio> list = edificioService.myFindAllEdificioPageSizeSort(page, size, sort); return new ResponseEntity<List<Edificio>>(list, new HttpHeaders(), HttpStatus.OK); } @GetMapping(value = "/mygetalledificiosortbyname", produces = MediaType.APPLICATION_JSON_VALUE) public List<Edificio> myGetAllusersSortByName() { return edificioService.myFindAllEdificioSorted(); } }
UTF-8
Java
2,512
java
EdificioController.java
Java
[]
null
[]
package it.epicode.controller; import java.util.HashMap; import java.util.List; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import it.epicode.model.Città; import it.epicode.model.Edificio; import it.epicode.service.EdificioService; @RestController @RequestMapping("/controlleredificio") public class EdificioController { @Autowired EdificioService edificioService; @GetMapping("/findedificio") List<Edificio> findAll() { return edificioService.myFindAllUsers(); } @GetMapping("/insertedificio") String insertEdificio(@RequestParam String nomeEdificio, @RequestParam String indirizzo, @RequestParam String nomeCitta) { edificioService.myInsertEdificio(nomeEdificio, indirizzo, nomeCitta); return "Edificio inserito con successo"; } @GetMapping("/findedificionome") List<Edificio> findEdificio(@RequestParam String nomeEdificio) { return edificioService.myFindByEdificio(nomeEdificio); } @GetMapping(value = "/findedificioalledificiopagesize", produces = MediaType.APPLICATION_JSON_VALUE) public Page myGetAllEdificioPageSize(@RequestParam(defaultValue = "0") int page, @RequestParam(defaultValue = "3") int size) { Page<Edificio> edificio = edificioService.myFindAllEdificioPageSize(page, size); return edificio; } @GetMapping(value = "/mygetalledificiopagesizesort", produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<List<Edificio>> myGetAllEdificioPageSizeSort(@RequestParam(defaultValue = "0") Integer page, @RequestParam(defaultValue = "2") Integer size, @RequestParam(defaultValue = "id") String sort) { List<Edificio> list = edificioService.myFindAllEdificioPageSizeSort(page, size, sort); return new ResponseEntity<List<Edificio>>(list, new HttpHeaders(), HttpStatus.OK); } @GetMapping(value = "/mygetalledificiosortbyname", produces = MediaType.APPLICATION_JSON_VALUE) public List<Edificio> myGetAllusersSortByName() { return edificioService.myFindAllEdificioSorted(); } }
2,512
0.791318
0.789725
63
38.857143
38.921516
216
false
false
0
0
0
0
0
0
1.126984
false
false
2
5f83d7c77f80c6d7998e49d6998e9dd04cecc8c8
30,339,649,028,626
6da7059bc6a8c666f59bec598a2cb815d3bd5917
/Exemplo023/app/src/main/java/desenvolvimento/nassau/exemplo023/MainActivity.java
59dd412ca140b71ddfc51a91984d74dc632fd5f5
[]
no_license
pacalexandrecosta/dispositivos_moveis
https://github.com/pacalexandrecosta/dispositivos_moveis
d042144066544d935ee11c3b0acf37ae8c646a12
90fbc8a39e9141c709e55f1ee222079f262e3890
refs/heads/master
2020-05-24T20:53:44.098000
2017-05-24T20:40:41
2017-05-24T20:40:41
84,875,224
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package desenvolvimento.nassau.exemplo023; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.support.v4.content.LocalBroadcastManager; import android.view.View; import android.widget.EditText; import android.widget.Toast; import org.json.JSONException; import org.json.JSONObject; /** * Created by paulo on 24/04/2017. */ public class MainActivity extends Activity { public final static String DADO_RECEBIDO = "desenvolvimento.nassau.exemplo023.DADO_RECEBIDO"; EditText edtNumeroIssue = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); edtNumeroIssue = (EditText) findViewById(R.id.edtNumeroIssue); registrarLocalBroadcastReceiver(); } public void onBtnStartServiceClick(View v) { int numeroIssue = Integer.valueOf(edtNumeroIssue.getText().toString()); Intent intencao = new Intent(this, MeuServico.class); intencao.putExtra("numeroIssue", numeroIssue); startService(intencao); } private void registrarLocalBroadcastReceiver() { BroadcastReceiver br = new MeuBroadcast(); IntentFilter intencao = new IntentFilter(DADO_RECEBIDO); LocalBroadcastManager.getInstance(this).registerReceiver(br, intencao); } public class MeuBroadcast extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { String jsonStr = intent.getExtras().getString("ticket"); try { JSONObject jsonObj = new JSONObject(jsonStr); Toast.makeText(MainActivity.this, jsonObj.getString("id"), Toast.LENGTH_LONG).show(); } catch (JSONException e) { e.printStackTrace(); } } } }
UTF-8
Java
2,001
java
MainActivity.java
Java
[ { "context": "on;\nimport org.json.JSONObject;\n\n/**\n * Created by paulo on 24/04/2017.\n */\n\npublic class MainActivity ext", "end": 469, "score": 0.9978294372558594, "start": 464, "tag": "USERNAME", "value": "paulo" } ]
null
[]
package desenvolvimento.nassau.exemplo023; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.support.v4.content.LocalBroadcastManager; import android.view.View; import android.widget.EditText; import android.widget.Toast; import org.json.JSONException; import org.json.JSONObject; /** * Created by paulo on 24/04/2017. */ public class MainActivity extends Activity { public final static String DADO_RECEBIDO = "desenvolvimento.nassau.exemplo023.DADO_RECEBIDO"; EditText edtNumeroIssue = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); edtNumeroIssue = (EditText) findViewById(R.id.edtNumeroIssue); registrarLocalBroadcastReceiver(); } public void onBtnStartServiceClick(View v) { int numeroIssue = Integer.valueOf(edtNumeroIssue.getText().toString()); Intent intencao = new Intent(this, MeuServico.class); intencao.putExtra("numeroIssue", numeroIssue); startService(intencao); } private void registrarLocalBroadcastReceiver() { BroadcastReceiver br = new MeuBroadcast(); IntentFilter intencao = new IntentFilter(DADO_RECEBIDO); LocalBroadcastManager.getInstance(this).registerReceiver(br, intencao); } public class MeuBroadcast extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { String jsonStr = intent.getExtras().getString("ticket"); try { JSONObject jsonObj = new JSONObject(jsonStr); Toast.makeText(MainActivity.this, jsonObj.getString("id"), Toast.LENGTH_LONG).show(); } catch (JSONException e) { e.printStackTrace(); } } } }
2,001
0.701649
0.694153
64
30.265625
26.659451
101
false
false
0
0
0
0
0
0
0.5625
false
false
2
d3ad6a974154bafb60bcc4c74148d1ee9f15ec2c
7,705,171,372,498
06dd890ab21e10669d860540bd0e5c39efa4069a
/sample-service/src/test/java/org/landg/lgrs/imagechannel/ImageChannelTestHelper.java
8ac0edb2ca6c3eccc0d918fde3869b438953ed52
[]
no_license
ckhurram/spring-boot-docker-k8s
https://github.com/ckhurram/spring-boot-docker-k8s
f01b2f3f508c5e3d68ec602437f70c29303265f1
45c474062522db65824b8e5e583a32065f31df66
refs/heads/master
2023-04-30T13:25:39.778000
2023-04-15T15:17:15
2023-04-15T15:17:15
93,404,539
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.landg.lgrs.imagechannel; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; public class ImageChannelTestHelper { InputStream getFileFromResourceAsStream(String fileName) { ClassLoader classLoader = getClass().getClassLoader(); InputStream inputStream = classLoader.getResourceAsStream(fileName); if (inputStream == null) { throw new IllegalArgumentException("file not found! " + fileName); } else { return inputStream; } } public static byte[] readFileIntoByteArray(String fileName) { InputStream rvDataInputStream = new ImageChannelTestHelper().getFileFromResourceAsStream(fileName); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); int nRead; byte[] data = new byte[16384]; try { while ((nRead = rvDataInputStream.read(data, 0, data.length)) != -1) { buffer.write(data, 0, nRead); } } catch (IOException ioe) { throw new IllegalStateException("Unable to read the file"); } return buffer.toByteArray(); } }
UTF-8
Java
1,179
java
ImageChannelTestHelper.java
Java
[]
null
[]
package org.landg.lgrs.imagechannel; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; public class ImageChannelTestHelper { InputStream getFileFromResourceAsStream(String fileName) { ClassLoader classLoader = getClass().getClassLoader(); InputStream inputStream = classLoader.getResourceAsStream(fileName); if (inputStream == null) { throw new IllegalArgumentException("file not found! " + fileName); } else { return inputStream; } } public static byte[] readFileIntoByteArray(String fileName) { InputStream rvDataInputStream = new ImageChannelTestHelper().getFileFromResourceAsStream(fileName); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); int nRead; byte[] data = new byte[16384]; try { while ((nRead = rvDataInputStream.read(data, 0, data.length)) != -1) { buffer.write(data, 0, nRead); } } catch (IOException ioe) { throw new IllegalStateException("Unable to read the file"); } return buffer.toByteArray(); } }
1,179
0.651399
0.644614
37
30.864864
28.925964
107
false
false
0
0
0
0
0
0
0.513514
false
false
2
28e94ab6d1b08f360eacc9b2717bb7d19c573489
17,025,250,418,937
9ba7197f9ea611df47cbfa68a2a4ccfed9c470dd
/wedsos-manager/src/main/java/cn/wedsos/manager/mind/impl/MindManagerImpl.java
546fed2b4859feeddd8e7cf1e8d9a40291a120e4
[]
no_license
treejames/wedsos
https://github.com/treejames/wedsos
319d3679eeca490084686a9611b89157187f28d7
06b50953846cc91af0eb962dd6001ad72f3bc7ff
refs/heads/master
2018-03-25T23:31:51.182000
2014-06-21T09:43:39
2014-06-21T09:43:39
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package cn.wedsos.manager.mind.impl; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.log4j.LogManager; import org.apache.log4j.Logger; import org.springframework.transaction.TransactionStatus; import org.springframework.transaction.support.TransactionCallback; import org.springframework.transaction.support.TransactionTemplate; import cn.wedsos.common.util.PaginatedList; import cn.wedsos.common.util.base.PaginatedArrayList; import cn.wedsos.dao.mind.MindDao; import cn.wedsos.domain.mind.MindComment; import cn.wedsos.domain.mind.MindMain; import cn.wedsos.manager.base.BaseManager; import cn.wedsos.manager.comment.impl.CommentManagerImpl; import cn.wedsos.manager.constant.Constant; import cn.wedsos.manager.mind.MindManager; /** * * @Description: * @author jackcheng * @date 2012-11-28 下午09:33:35 */ public class MindManagerImpl extends BaseManager implements MindManager { public static final Logger LOGGER = LogManager.getLogger(MindManagerImpl.class); MindDao mindDao; public void setMindDao(MindDao mindDao) { this.mindDao = mindDao; } public List<Map> findCommentByMainId(Long id) { return mindDao.mindComment(id); } public List<Map> findMindList(String userName, String showType,int indexPage, int pageSize) { if(showType == null || "".equals(showType)){//所有的心语信息 return allMindMain(indexPage,pageSize); } else if(Constant.MIND_FOR_SELF.equals(showType)){//个人的心语信息 return selfMindMain(userName,indexPage,pageSize); } else if(Constant.MIND_FOR_SELF_FAVORITES.equals(showType)){//个人的收藏心语信息 return myfavoritesMind(userName,indexPage,pageSize); } else if(Constant.MIND_FOR_SELF_CONCERN.equals(showType)){//个人所关注人员的心语信息 return myConcernMind(userName,indexPage,pageSize); } return null; } /** * 根据userName 查找所于本人所关注人心语信息 * @param userName * @param indexPage * @param pageSize * @return */ private List<Map> myConcernMind(String userName,int indexPage, int pageSize){ PaginatedList<Map> pagePaginatedList = new PaginatedArrayList<Map>(indexPage, pageSize); Map map = new HashMap(); map.put("userName", userName); int count; count = mindDao.myConcernMindCount(map); if(count > 0){ //设置总的个数 pagePaginatedList.setTotalItem(count); //设置起始行 map.put("startNum", getMySqlStartRow(pagePaginatedList.getStartRow())); //设置每页记录数 map.put("endNum", pageSize); pagePaginatedList.addAll(mindDao.myConcernMind(map)); } return pagePaginatedList; } /** * 根据userName 查找所于本人的收藏心语信息 * @param userName * @param indexPage * @param pageSize * @return */ private List<Map> myfavoritesMind(String userName,int indexPage, int pageSize){ PaginatedList<Map> pagePaginatedList = new PaginatedArrayList<Map>(indexPage, pageSize); Map map = new HashMap(); int count; map.put("userName", userName); count = mindDao.myfavoritesMindCount(map); if(count > 0){ //设置总的个数 pagePaginatedList.setTotalItem(count); //设置起始行 map.put("startNum", getMySqlStartRow(pagePaginatedList.getStartRow())); //设置每页记录数 map.put("endNum", pageSize); pagePaginatedList.addAll(mindDao.myfavoritesMind(map)); } return pagePaginatedList; } /** * 根据userName 查找所于本人的心语信息 * @param userName * @param indexPage * @param pageSize * @return */ private List<Map> selfMindMain(String userName,int indexPage, int pageSize){ PaginatedList<Map> pagePaginatedList = new PaginatedArrayList<Map>(indexPage, pageSize); Map map = new HashMap(); map.put("userName", userName); int count; count = mindDao.allSelfMindCount(map); if(count > 0){ //设置总的个数 pagePaginatedList.setTotalItem(count); //设置起始行 map.put("startNum", getMySqlStartRow(pagePaginatedList.getStartRow())); //设置每页记录数 map.put("endNum", pageSize); pagePaginatedList.addAll(mindDao.allSelfMind(map)); } return pagePaginatedList; } /** * 所有的心语信息 * @param indexPage * @param pageSize * @return */ private List<Map> allMindMain(int indexPage, int pageSize){ PaginatedList<Map> pagePaginatedList = new PaginatedArrayList<Map>(indexPage, pageSize); Map map = new HashMap(); int count; count = mindDao.allMindMainCount(map); if(count > 0){ //设置总的个数 pagePaginatedList.setTotalItem(count); //设置起始行 map.put("startNum", getMySqlStartRow(pagePaginatedList.getStartRow())); //设置每页记录数 map.put("endNum", pageSize); pagePaginatedList.addAll(mindDao.allMindMain(map)); } return pagePaginatedList; } public List<Map> listCommentByMindId(long id) { return mindDao.mindComment(id); } public boolean neverGetIn(String userName) { int result = mindDao.haveEnterMind(userName); if(0 == result){ mindDao.addMindRelate(userName); return true; } return false; } public List<Map> getIntelligentMind() { return mindDao.intelligentMind(Constant.MIND_INTELLIGENT); } public Map getMindRelate(String userName){ return mindDao.getMindRelate(userName); } public int updateCommentByType(final Map paramMap) { final String operateType = (String)paramMap.get("operateType"); TransactionTemplate template = this.getWedsosDataSourceTransactionManager(); int resultCode = (Integer) template.execute(new TransactionCallback() { public Object doInTransaction(TransactionStatus transactionStatus) { int result = 0;//默认失败。 try { MindComment mindComment = new MindComment(); mindComment.setContent(paramMap.get("content").toString()); mindComment.setCreateUser(paramMap.get("createUser").toString()); mindComment.setMainId(Long.parseLong(paramMap.get("mainId").toString()) ); if(Constant.COMMENT_MIND.equals(operateType)){//评论某条心语 mindDao.addMindComment(mindComment); mindDao.addMindCommentNumber(mindComment.getMainId()); result = 1; } else if(Constant.REPLAY_COMMENT.equals(operateType)){//回复某条评论 mindComment.setParentId(Long.parseLong(paramMap.get("commentId").toString()));//如果是回复,需要指定哪个是哪个评论的回复 mindDao.addMindComment(mindComment); result = 1; } } catch (Exception e) { LOGGER.error("心语评论["+operateType+"]操作 失败,error="+e.toString()); transactionStatus.setRollbackOnly(); } return result; } }); return resultCode; } public int updateMindByType(final Map paramMap) { final String operateType = (String)paramMap.get("operateType"); TransactionTemplate template = this.getWedsosDataSourceTransactionManager(); int resultCode = (Integer) template.execute(new TransactionCallback() { public Object doInTransaction(TransactionStatus transactionStatus) { int result = 0;//默认失败。 try { MindMain mind = new MindMain(); mind.setContent((String)paramMap.get("content")); mind.setCreateUser((String)paramMap.get("createUser")); if(Constant.ADD_MIND.equals(operateType)){ mind.setIsHidden((String)paramMap.get("isHidden")); mindDao.addMindMain(mind); mindDao.addMindNumber(mind); result = 1; } else if(Constant.MODIFY_MIND.equals(operateType)){ mind.setId(Long.parseLong(paramMap.get("id").toString())); mindDao.updateMindContent(mind); result = 1; } else if(Constant.DELETE_MIND.equals(operateType)){ mind.setId(Long.parseLong(paramMap.get("id").toString())); mindDao.delMindContent(mind); result = 1; } return result; } catch (Exception e) { LOGGER.error("心语["+operateType+"]操作 失败,error:"+e.toString()); transactionStatus.setRollbackOnly(); } return result; } }); return resultCode; } public int addConcernMind(final Map map) { TransactionTemplate template = this.getWedsosDataSourceTransactionManager(); int resultCode = (Integer) template.execute(new TransactionCallback() { public Object doInTransaction(TransactionStatus transactionStatus) { int result = 0;//默认失败。 try { mindDao.addConcernMind(map); mindDao.addMindVisitNumber(Long.parseLong(map.get("mindId").toString())); result = 1; } catch (Exception e) { System.out.println("mainId="+Long.parseLong(map.get("mindId").toString())); e.printStackTrace(); LOGGER.error("心语添加关注人操作 失败"); transactionStatus.setRollbackOnly(); } return result; } }); return resultCode; } public int addFavoritesMind(final Map map) { TransactionTemplate template = this.getWedsosDataSourceTransactionManager(); int resultCode = (Integer) template.execute(new TransactionCallback() { public Object doInTransaction(TransactionStatus transactionStatus) { int result = 0;//默认失败。 try { mindDao.addFavoritesMind(map); mindDao.addMindVisitNumber(Long.parseLong(map.get("mainId").toString())); result = 1; } catch (Exception e) { e.printStackTrace(); LOGGER.error("收藏心语操作 失败"); transactionStatus.setRollbackOnly(); } return result; } }); return resultCode; } public int addMindVisitNumber(Long id) { return mindDao.addMindVisitNumber(id); } public List<Map> findMindList(Map map) { PaginatedList<Map> pagePaginatedList = new PaginatedArrayList<Map>(Integer.parseInt(map.get("indexPage").toString()),Integer.parseInt(map.get("pageSize").toString())); // Map map = new HashMap(); int count; count = mindDao.allMindMainCount(map); if(count > 0){ //设置总的个数 pagePaginatedList.setTotalItem(count); //设置起始行 map.put("startNum", getMySqlStartRow(pagePaginatedList.getStartRow())); //设置每页记录数 map.put("endNum", Integer.parseInt(map.get("pageSize").toString())); pagePaginatedList.addAll(mindDao.allMindMain(map)); } return pagePaginatedList; } }
GB18030
Java
11,763
java
MindManagerImpl.java
Java
[ { "context": "Manager;\r\n\r\n/**\r\n * \r\n * @Description:\r\n * @author jackcheng\r\n * @date 2012-11-28 下午09:33:35\r\n */\r\npublic clas", "end": 846, "score": 0.9620620012283325, "start": 837, "tag": "USERNAME", "value": "jackcheng" }, { "context": "howType)){//个人的收藏心语信息\r\n\t\t...
null
[]
package cn.wedsos.manager.mind.impl; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.log4j.LogManager; import org.apache.log4j.Logger; import org.springframework.transaction.TransactionStatus; import org.springframework.transaction.support.TransactionCallback; import org.springframework.transaction.support.TransactionTemplate; import cn.wedsos.common.util.PaginatedList; import cn.wedsos.common.util.base.PaginatedArrayList; import cn.wedsos.dao.mind.MindDao; import cn.wedsos.domain.mind.MindComment; import cn.wedsos.domain.mind.MindMain; import cn.wedsos.manager.base.BaseManager; import cn.wedsos.manager.comment.impl.CommentManagerImpl; import cn.wedsos.manager.constant.Constant; import cn.wedsos.manager.mind.MindManager; /** * * @Description: * @author jackcheng * @date 2012-11-28 下午09:33:35 */ public class MindManagerImpl extends BaseManager implements MindManager { public static final Logger LOGGER = LogManager.getLogger(MindManagerImpl.class); MindDao mindDao; public void setMindDao(MindDao mindDao) { this.mindDao = mindDao; } public List<Map> findCommentByMainId(Long id) { return mindDao.mindComment(id); } public List<Map> findMindList(String userName, String showType,int indexPage, int pageSize) { if(showType == null || "".equals(showType)){//所有的心语信息 return allMindMain(indexPage,pageSize); } else if(Constant.MIND_FOR_SELF.equals(showType)){//个人的心语信息 return selfMindMain(userName,indexPage,pageSize); } else if(Constant.MIND_FOR_SELF_FAVORITES.equals(showType)){//个人的收藏心语信息 return myfavoritesMind(userName,indexPage,pageSize); } else if(Constant.MIND_FOR_SELF_CONCERN.equals(showType)){//个人所关注人员的心语信息 return myConcernMind(userName,indexPage,pageSize); } return null; } /** * 根据userName 查找所于本人所关注人心语信息 * @param userName * @param indexPage * @param pageSize * @return */ private List<Map> myConcernMind(String userName,int indexPage, int pageSize){ PaginatedList<Map> pagePaginatedList = new PaginatedArrayList<Map>(indexPage, pageSize); Map map = new HashMap(); map.put("userName", userName); int count; count = mindDao.myConcernMindCount(map); if(count > 0){ //设置总的个数 pagePaginatedList.setTotalItem(count); //设置起始行 map.put("startNum", getMySqlStartRow(pagePaginatedList.getStartRow())); //设置每页记录数 map.put("endNum", pageSize); pagePaginatedList.addAll(mindDao.myConcernMind(map)); } return pagePaginatedList; } /** * 根据userName 查找所于本人的收藏心语信息 * @param userName * @param indexPage * @param pageSize * @return */ private List<Map> myfavoritesMind(String userName,int indexPage, int pageSize){ PaginatedList<Map> pagePaginatedList = new PaginatedArrayList<Map>(indexPage, pageSize); Map map = new HashMap(); int count; map.put("userName", userName); count = mindDao.myfavoritesMindCount(map); if(count > 0){ //设置总的个数 pagePaginatedList.setTotalItem(count); //设置起始行 map.put("startNum", getMySqlStartRow(pagePaginatedList.getStartRow())); //设置每页记录数 map.put("endNum", pageSize); pagePaginatedList.addAll(mindDao.myfavoritesMind(map)); } return pagePaginatedList; } /** * 根据userName 查找所于本人的心语信息 * @param userName * @param indexPage * @param pageSize * @return */ private List<Map> selfMindMain(String userName,int indexPage, int pageSize){ PaginatedList<Map> pagePaginatedList = new PaginatedArrayList<Map>(indexPage, pageSize); Map map = new HashMap(); map.put("userName", userName); int count; count = mindDao.allSelfMindCount(map); if(count > 0){ //设置总的个数 pagePaginatedList.setTotalItem(count); //设置起始行 map.put("startNum", getMySqlStartRow(pagePaginatedList.getStartRow())); //设置每页记录数 map.put("endNum", pageSize); pagePaginatedList.addAll(mindDao.allSelfMind(map)); } return pagePaginatedList; } /** * 所有的心语信息 * @param indexPage * @param pageSize * @return */ private List<Map> allMindMain(int indexPage, int pageSize){ PaginatedList<Map> pagePaginatedList = new PaginatedArrayList<Map>(indexPage, pageSize); Map map = new HashMap(); int count; count = mindDao.allMindMainCount(map); if(count > 0){ //设置总的个数 pagePaginatedList.setTotalItem(count); //设置起始行 map.put("startNum", getMySqlStartRow(pagePaginatedList.getStartRow())); //设置每页记录数 map.put("endNum", pageSize); pagePaginatedList.addAll(mindDao.allMindMain(map)); } return pagePaginatedList; } public List<Map> listCommentByMindId(long id) { return mindDao.mindComment(id); } public boolean neverGetIn(String userName) { int result = mindDao.haveEnterMind(userName); if(0 == result){ mindDao.addMindRelate(userName); return true; } return false; } public List<Map> getIntelligentMind() { return mindDao.intelligentMind(Constant.MIND_INTELLIGENT); } public Map getMindRelate(String userName){ return mindDao.getMindRelate(userName); } public int updateCommentByType(final Map paramMap) { final String operateType = (String)paramMap.get("operateType"); TransactionTemplate template = this.getWedsosDataSourceTransactionManager(); int resultCode = (Integer) template.execute(new TransactionCallback() { public Object doInTransaction(TransactionStatus transactionStatus) { int result = 0;//默认失败。 try { MindComment mindComment = new MindComment(); mindComment.setContent(paramMap.get("content").toString()); mindComment.setCreateUser(paramMap.get("createUser").toString()); mindComment.setMainId(Long.parseLong(paramMap.get("mainId").toString()) ); if(Constant.COMMENT_MIND.equals(operateType)){//评论某条心语 mindDao.addMindComment(mindComment); mindDao.addMindCommentNumber(mindComment.getMainId()); result = 1; } else if(Constant.REPLAY_COMMENT.equals(operateType)){//回复某条评论 mindComment.setParentId(Long.parseLong(paramMap.get("commentId").toString()));//如果是回复,需要指定哪个是哪个评论的回复 mindDao.addMindComment(mindComment); result = 1; } } catch (Exception e) { LOGGER.error("心语评论["+operateType+"]操作 失败,error="+e.toString()); transactionStatus.setRollbackOnly(); } return result; } }); return resultCode; } public int updateMindByType(final Map paramMap) { final String operateType = (String)paramMap.get("operateType"); TransactionTemplate template = this.getWedsosDataSourceTransactionManager(); int resultCode = (Integer) template.execute(new TransactionCallback() { public Object doInTransaction(TransactionStatus transactionStatus) { int result = 0;//默认失败。 try { MindMain mind = new MindMain(); mind.setContent((String)paramMap.get("content")); mind.setCreateUser((String)paramMap.get("createUser")); if(Constant.ADD_MIND.equals(operateType)){ mind.setIsHidden((String)paramMap.get("isHidden")); mindDao.addMindMain(mind); mindDao.addMindNumber(mind); result = 1; } else if(Constant.MODIFY_MIND.equals(operateType)){ mind.setId(Long.parseLong(paramMap.get("id").toString())); mindDao.updateMindContent(mind); result = 1; } else if(Constant.DELETE_MIND.equals(operateType)){ mind.setId(Long.parseLong(paramMap.get("id").toString())); mindDao.delMindContent(mind); result = 1; } return result; } catch (Exception e) { LOGGER.error("心语["+operateType+"]操作 失败,error:"+e.toString()); transactionStatus.setRollbackOnly(); } return result; } }); return resultCode; } public int addConcernMind(final Map map) { TransactionTemplate template = this.getWedsosDataSourceTransactionManager(); int resultCode = (Integer) template.execute(new TransactionCallback() { public Object doInTransaction(TransactionStatus transactionStatus) { int result = 0;//默认失败。 try { mindDao.addConcernMind(map); mindDao.addMindVisitNumber(Long.parseLong(map.get("mindId").toString())); result = 1; } catch (Exception e) { System.out.println("mainId="+Long.parseLong(map.get("mindId").toString())); e.printStackTrace(); LOGGER.error("心语添加关注人操作 失败"); transactionStatus.setRollbackOnly(); } return result; } }); return resultCode; } public int addFavoritesMind(final Map map) { TransactionTemplate template = this.getWedsosDataSourceTransactionManager(); int resultCode = (Integer) template.execute(new TransactionCallback() { public Object doInTransaction(TransactionStatus transactionStatus) { int result = 0;//默认失败。 try { mindDao.addFavoritesMind(map); mindDao.addMindVisitNumber(Long.parseLong(map.get("mainId").toString())); result = 1; } catch (Exception e) { e.printStackTrace(); LOGGER.error("收藏心语操作 失败"); transactionStatus.setRollbackOnly(); } return result; } }); return resultCode; } public int addMindVisitNumber(Long id) { return mindDao.addMindVisitNumber(id); } public List<Map> findMindList(Map map) { PaginatedList<Map> pagePaginatedList = new PaginatedArrayList<Map>(Integer.parseInt(map.get("indexPage").toString()),Integer.parseInt(map.get("pageSize").toString())); // Map map = new HashMap(); int count; count = mindDao.allMindMainCount(map); if(count > 0){ //设置总的个数 pagePaginatedList.setTotalItem(count); //设置起始行 map.put("startNum", getMySqlStartRow(pagePaginatedList.getStartRow())); //设置每页记录数 map.put("endNum", Integer.parseInt(map.get("pageSize").toString())); pagePaginatedList.addAll(mindDao.allMindMain(map)); } return pagePaginatedList; } }
11,763
0.6152
0.612263
332
31.846386
27.516214
170
false
false
0
0
0
0
0
0
2.048193
false
false
2
f7853502ed1a4c6c684860b5e29fc9bb4f37ff51
8,435,315,804,964
b97ec86b02f5108648846dfbd25fa7c2cf76b38d
/src/test/java/it/cn/home1/oss/lib/security/SecuredService.java
63316672bc554788165b9b8253ab0eb7dcad4c61
[ "MIT" ]
permissive
home1-oss/oss-lib-security
https://github.com/home1-oss/oss-lib-security
b3c9f5968e1cb695cebd3841e0573c2b54963d65
a062cc5099786364899c23522a5768fa352b4852
refs/heads/master
2021-01-19T12:09:25.626000
2017-08-24T02:06:32
2017-08-24T02:06:32
88,024,623
0
6
null
false
2017-04-28T12:01:57
2017-04-12T07:49:27
2017-04-13T11:37:01
2017-04-28T12:01:57
159
0
1
0
Java
null
null
package it.cn.home1.oss.lib.security; import org.springframework.stereotype.Component; /** * Created by zhanghaolun on 16/10/29. */ @Component public class SecuredService { public void forAdminOnly() { } }
UTF-8
Java
216
java
SecuredService.java
Java
[ { "context": "framework.stereotype.Component;\n\n/**\n * Created by zhanghaolun on 16/10/29.\n */\n@Component\npublic class SecuredS", "end": 118, "score": 0.9993993639945984, "start": 107, "tag": "USERNAME", "value": "zhanghaolun" } ]
null
[]
package it.cn.home1.oss.lib.security; import org.springframework.stereotype.Component; /** * Created by zhanghaolun on 16/10/29. */ @Component public class SecuredService { public void forAdminOnly() { } }
216
0.726852
0.694444
14
14.428572
17.053337
48
false
false
0
0
0
0
0
0
0.142857
false
false
2
25620125265c949c0145f72cea33bd452ca03df8
9,723,805,963,062
69011b4a6233db48e56db40bc8a140f0dd721d62
/src/com/jshx/zzqk/web/IntSitAction.java
43ba572363b3a118ff44ee757eef7277bbf27207
[]
no_license
gechenrun/scysuper
https://github.com/gechenrun/scysuper
bc5397e5220ee42dae5012a0efd23397c8c5cda0
e706d287700ff11d289c16f118ce7e47f7f9b154
refs/heads/master
2020-03-23T19:06:43.185000
2018-06-10T07:51:18
2018-06-10T07:51:18
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.jshx.zzqk.web; import java.io.FileInputStream; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.xml.ws.handler.Handler; import javax.xml.ws.handler.HandlerResolver; import javax.xml.ws.handler.PortInfo; import net.sf.json.JSONArray; import net.sf.json.JSONObject; import net.sf.json.JsonConfig; import net.sf.json.util.PropertyFilter; import org.apache.commons.lang.StringUtils; import org.apache.struts2.ServletActionContext; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import com.jshx.core.base.action.BaseAction; import com.jshx.core.base.vo.Pagination; import com.jshx.core.json.CodeJsonValueProcessor; import com.jshx.core.json.DateJsonValueProcessor; import com.jshx.http.service.HttpService; import com.jshx.module.admin.entity.User; import com.jshx.module.admin.entity.UserRight; import com.jshx.module.admin.service.CodeService; import com.jshx.module.admin.service.UserService; import com.jshx.photoPic.entity.PhotoPic; import com.jshx.photoPic.service.PhotoPicService; import com.jshx.qyjbxx.entity.EntBaseInfo; import com.jshx.qyjbxx.service.EntBaseInfoService; import com.jshx.qyjbxx.util.ClientAuthenticationHandler; import com.jshx.shjl.entity.CheckRecord; import com.jshx.shjl.service.CheckRecordService; import com.jshx.zzqk.entity.IntSit; import com.jshx.zzqk.service.IntSitService; import com.lkdj.kzk.GetTkzxxRequest; import com.lkdj.kzk.GetTkzxxResponse; import com.lkdj.kzk.TkzxxPort; import com.lkdj.kzk.TkzxxPortService; import com.lkdj.kzk.GetTkzxxRequest.Tkzxxs; import com.lkdj.lkLog.entity.LkLog; import com.lkdj.lkLog.service.LkLogService; import com.lkdj.util.ceateTkzxxUtil; import com.xypt.SynchronizeCompanyInfo; import com.xypt.SynchronizeCompanyInfoService; public class IntSitAction extends BaseAction { /** * 主键ID列表,用于接收页面提交的多条主键ID信息 */ private String ids; /** * 实体类 */ private IntSit intSit = new IntSit(); /** * 业务类 */ @Autowired private IntSitService intSitService; /** * 修改新增标记,add为新增、mod为修改 */ private String flag; /** * 分页信息 */ private Pagination pagination; private Date queryIntelligenceCardDateStart; private Date queryIntelligenceCardDateEnd; private Date queryIntelligenceValidityStartStart; private Date queryIntelligenceValidityStartEnd; private Date queryIntelligenceValidityEndStart; private Date queryIntelligenceValidityEndEnd; @Autowired private HttpService httpService; @Autowired private LkLogService lkLogService; @Autowired() @Qualifier("sessionFactory") private SessionFactory sessionFactory; @Autowired private CheckRecordService checkRecordService; /** * 执行查询的方法,返回json数据 */ @Autowired private PhotoPicService photoPicService; @Autowired private EntBaseInfoService entBaseInfoService; @Autowired private CodeService codeService; /** * 审核记录 */ private List<CheckRecord> checkRecords; private CheckRecord checkRecord=new CheckRecord(); private boolean canCheck=false; private String roleName; private int pageNo; private int pageSize; private String searchLike; @Autowired private UserService userService; private String companyId; private String entBaseInfoId; /** * 初始化 用于判断审核角色 */ public String init(){ //判断登录人的角色 List<UserRight> list = (List<UserRight>) this.getLoginUser().getUserRoles(); for(UserRight ur:list) { //登录人 可以审核 if(ur.getRole().getRoleCode().equals("A02")) { roleName = "1"; setCanCheck(true); break; } if(ur.getRole().getRoleCode().equals("A23")) { roleName = "0"; break; } } return SUCCESS; } private List<PhotoPic> picList = new ArrayList<PhotoPic>(); public List<PhotoPic> getPicList() { return picList; } public void setPicList(List<PhotoPic> picList) { this.picList = picList; } public void list() throws Exception{ try { Map<String, Object> paraMap = new HashMap<String, Object>(); paraMap=httpService.addParamByRole(paraMap,this.getLoginUser().getId(), this.getLoginUser().getDeptCode()); String userId=this.getLoginUser().getId(); if(httpService.judgeRoleCode(userId, "A23")){ paraMap.put("createUserId", userId); } else { paraMap.put("state", "待提交"); } String url = ServletActionContext.getRequest().getRequestURL().toString(); if(StringUtils.isNotEmpty(entBaseInfoId)){ paraMap.put("companyId", "entBaseInfoId"); } if (pagination == null) pagination = new Pagination(this.getRequest()); if (null != intSit) { //设置查询条件,开发人员可以在此增加过滤条件 if ((null != intSit.getAreaId()) && (0 < intSit.getAreaId().trim().length())) { paraMap.put("areaId", intSit.getAreaId().trim()); } if ((null != intSit.getAreaName()) && (0 < intSit.getAreaName().trim().length())) { paraMap.put("areaName", intSit.getAreaName().trim()); } if ((null != intSit.getCompanyName()) && (0 < intSit.getCompanyName().trim().length())) { paraMap.put("companyName", "%" + intSit.getCompanyName().trim() + "%"); } if ((null != intSit.getCompanyId()) && (0 < intSit.getCompanyId().trim().length())) { paraMap.put("companyId", intSit.getCompanyId().trim() ); } if ((null != intSit.getIntelligenceCardnum()) && (0 < intSit.getIntelligenceCardnum().trim().length())) { paraMap.put("intelligenceCardnum", "%" + intSit.getIntelligenceCardnum().trim() + "%"); } if ((null != intSit.getIntelligenceCardname()) && (0 < intSit.getIntelligenceCardname().trim() .length())) { paraMap.put("intelligenceCardname", "%" + intSit.getIntelligenceCardname().trim() + "%"); } if ((null != intSit.getIntelligenceType()) && (0 < intSit.getIntelligenceType().trim().length())) { paraMap.put("intelligenceType", intSit .getIntelligenceType().trim()); } if ((null != intSit.getAuditResult()) && (0 < intSit.getAuditResult().trim().length())) { paraMap.put("auditResult", "%" + intSit.getAuditResult().trim() + "%"); } if ((null != intSit.getAuditState()) && (0 < intSit.getAuditState().trim().length())) { paraMap.put("auditState", intSit.getAuditState().trim()); } } JsonConfig config = new JsonConfig(); config.registerJsonValueProcessor(java.util.Date.class, new DateJsonValueProcessor()); Map<String, String> codeMap = new HashMap<String, String>(); //此处添加需要转换的一维代码,key是一维代码在数据对象中的属性名,value是一维代码的codeId codeMap.put("intelligenceType", "40288008416c6c1a01416ccf6ab100a7"); config.registerJsonValueProcessor(String.class, new CodeJsonValueProcessor(codeMap)); final String filter = "id|areaName|companyName|intelligenceCardnum|intelligenceCardname|intelligenceType|auditResult|auditState|createUserID|"; if (filter != null && filter.length() > 1) { config.setJsonPropertyFilter(new PropertyFilter() { public boolean apply(Object source, String name, Object value) { if (filter.indexOf(name + "|") != -1) return false; else return true; } }); } pagination = intSitService.findByPage(pagination, paraMap); convObjectToJson(pagination, config); } catch (Exception e) {e.printStackTrace(); // TODO: handle exception } } /** * 查看详细信息 */ public String view() throws Exception{ if((null != intSit)&&(null != intSit.getId())) { intSit = intSitService.getById(intSit.getId()); if(intSit.getLinkId() == null || "".equals(intSit.getLinkId())) { String linkId = java.util.UUID.randomUUID().toString().replace("-", ""); intSit.setLinkId(linkId); } else { Map map = new HashMap(); map.put("linkId",intSit.getLinkId()); map.put("mkType", "zzqk"); map.put("picType","zzfj"); picList = photoPicService.findPicPath(map);//获取执法文书材料 } } else { String linkId = java.util.UUID.randomUUID().toString().replace("-", ""); intSit.setLinkId(linkId); } //审核记录 Map<String, Object> paraMap = new HashMap<String, Object>(); paraMap.put("infoId", intSit.getId()); checkRecords=checkRecordService.findCheckRecord(paraMap); return VIEW; } /** * 初始化修改信息 */ public String initEdit() throws Exception{ view(); return EDIT; } /** * 保存信息(包括新增和修改) */ public String save() throws Exception{ FileInputStream in = null; try { //设置Blob字段 setBlobField(in); } finally { if (null != in) { try { in.close(); } catch (Exception ex) { } } } Map map = new HashMap(); map.put("loginId", this.getLoginUser().getLoginId()); EntBaseInfo enBaseInfo = entBaseInfoService.findEntBaseInfoByMap(map); intSit.setAreaId(enBaseInfo.getEnterprisePossession()); Map m = new HashMap(); m.put("codeName", "企业属地"); m.put("itemValue", enBaseInfo.getEnterprisePossession()); intSit.setAreaName(codeService.findCodeValueByMap(m).getItemText()); intSit.setCompanyId(enBaseInfo.getId()); intSit.setCompanyName(enBaseInfo.getEnterpriseName()); if ("add".equalsIgnoreCase(this.flag)){ intSit.setDeptId(this.getLoginUserDepartmentId()); intSit.setDelFlag(0); intSitService.save(intSit); }else{ intSitService.update(intSit); } try { String zjhm = NullToString(enBaseInfo.getRegistrationNumber()).replaceAll(" ", ""); if(zjhm != null && !"".equals(zjhm)) { LkLog log1 = new LkLog(); log1.setNrid(intSit.getId()); log1.setLb("intSit扩展信息"); //对接资质情况 GetTkzxxRequest kzqq = new GetTkzxxRequest(); ceateTkzxxUtil ceateTkzxxUtil = new ceateTkzxxUtil(); JSONArray ja = new JSONArray(); String intelligenceCardDate = intSit.getIntelligenceCardDate() != null?new SimpleDateFormat("yyyy-MM-dd").format(intSit.getIntelligenceCardDate()):""; String intelligenceValidityStart = intSit.getIntelligenceValidityStart() != null?new SimpleDateFormat("yyyy-MM-dd").format(intSit.getIntelligenceValidityStart()):""; String intelligenceValidityEnd = intSit.getIntelligenceValidityEnd() != null?new SimpleDateFormat("yyyy-MM-dd").format(intSit.getIntelligenceValidityEnd()):"" ; String changeDate = intSit.getChangeDate() != null?new SimpleDateFormat("yyyy-MM-dd").format(intSit.getChangeDate()):"" ; ja.add((new JSONObject()).put("QYMC" , NullToString(intSit.getCompanyName())));//企业名称 ja.add((new JSONObject()).put("ZSBH" , NullToString(intSit.getIntelligenceCardnum())));//证书编号 ja.add((new JSONObject()).put("ZSMC" , NullToString(intSit.getIntelligenceCardname())));//证书名称 ja.add((new JSONObject()).put("ZZLX" , zzlx(intSit.getIntelligenceType())));//确认类型 ja.add((new JSONObject()).put("ZZLR" , NullToString(intSit.getIntelligenceContent()) ));//资质内容 ja.add((new JSONObject()).put("FZJG" , NullToString(intSit.getIntelligenceInstitution())));//发证机关 ja.add((new JSONObject()).put("FZRQ" ,intelligenceCardDate ));//发证日期 ja.add((new JSONObject()).put("YXQQSRQ" , intelligenceValidityStart));//有效期开始日期 ja.add((new JSONObject()).put("YXQJZRQ" ,intelligenceValidityEnd));//有效期截止时间 ja.add((new JSONObject()).put("ZZJB" ,NullToString(intSit.getZzjb())));//资质级别 ja.add((new JSONObject()).put("BGRQ" ,changeDate));//变更日期 ja.add((new JSONObject()).put("YWFW" ,NullToString(intSit.getBussinessScope())));//业务范围 JSONObject jo = new JSONObject(); jo.put("frkzxx", ja.toString()); String kzxx = jo.toString(); Tkzxxs tkzxxs = ceateTkzxxUtil.ceateTkzxxs("zzqkb",intSit.getCreateTime(), kzxx, "",zjhm); kzqq.getTkzxxs().add(tkzxxs); TkzxxPortService tkzxxPortService= new TkzxxPortService(); tkzxxPortService.setHandlerResolver(new HandlerResolver() { @Override public List<Handler> getHandlerChain(PortInfo arg0) { List<Handler> handlerList = new ArrayList(); handlerList.add(new ClientAuthenticationHandler( "Zhaj_seivice@APP-00199", "zhaj")); return handlerList; } }); TkzxxPort tkzxxPort = tkzxxPortService.getTkzxxPortSoap11(); GetTkzxxResponse getTkzxxResponse = tkzxxPort.getTkzxx(kzqq); System.out.println("资质情况"+getTkzxxResponse.getMsg()); log1.setResult(getTkzxxResponse.getMsg()); lkLogService.save(log1); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return RELOAD; } /** * 审核信息 */ public String check() throws Exception{ view(); return "check"; } /** * 保存审核信息 */ public String checkSave() throws Exception{ intSit=intSitService.getById(intSit.getId()); if("审核通过并上报信用平台".equals(checkRecord.getCheckResult())){ try { SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMddHHmmss"); SimpleDateFormat sdf1=new SimpleDateFormat("yyyy-MM-dd"); EntBaseInfo entBaseInfo = entBaseInfoService.getById(intSit.getCompanyId()); SynchronizeCompanyInfoService service = new SynchronizeCompanyInfoService(); service.setHandlerResolver(new HandlerResolver() { @Override public List<Handler> getHandlerChain(PortInfo arg0) { List<Handler> handlerList = new ArrayList(); handlerList.add(new ClientAuthenticationHandler( "Zhaj_seivice@APP-00199", "zhaj")); return handlerList; } }); SynchronizeCompanyInfo syn = service.getSynchronizeCompanyInfoPort(); Map map = new HashMap(); map.put("codeName", "资质类型"); map.put("itemValue", intSit.getIntelligenceType()); String zzlx=(null==codeService.findCodeValueByMap(map).getItemText()?"":codeService.findCodeValueByMap(map).getItemText()); String a=(null==intSit.getChangeDate()?"":sdf1.format(intSit.getChangeDate())); String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><Request><Head>"+ "<DeptID><![CDATA[54]]></DeptID>"+ "<InfoClass><![CDATA[安监-机构资质认定(变更)信息]]></InfoClass>"+ "<UploadTime><![CDATA["+sdf.format(new Date())+"]]></UploadTime></Head>"+ "<Body><FIELDS><![CDATA[发证日期,变更日期,组织机构代码,企业全称(中文),工商注册号/统一社会信用代码,资质名称,资质证书编号,法定代表人证件号码,资质级别,业务范围,注册地址,证书有效起始日期,证书有效截止日期,发证机关名称]]></FIELDS>"+ "<DATA>"+ "<FZRQ><![CDATA["+sdf1.format(intSit.getIntelligenceCardDate())+"]]></FZRQ>"+ "<BGRQ><![CDATA["+a+"]]></BGRQ>"+ "<ZZJGDM><![CDATA["+entBaseInfo.getEnterpriseCode()+"]]></ZZJGDM>"+ "<QYMC><![CDATA["+entBaseInfo.getEnterpriseName() +"]]></QYMC>"+ "<GSZCH><![CDATA["+entBaseInfo.getRegistrationNumber() +"]]></GSZCH>"+ "<ZZMC><![CDATA["+zzlx +"]]></ZZMC>"+ "<ZZZSBH><![CDATA["+intSit.getIntelligenceCardnum() +"]]></ZZZSBH>"+ "<FDDBRZJHM><![CDATA["+entBaseInfo.getEnterpriseLegalCardnum() +"]]></FDDBRZJHM>"+ "<ZZJB><![CDATA["+intSit.getZzjb() +"]]></ZZJB>"+ "<YWFW><![CDATA["+intSit.getBussinessScope() +"]]></YWFW>"+ "<ZCDZ><![CDATA["+entBaseInfo.getEnterpriseAddress() +"]]></ZCDZ>"+ "<ZSYXQSRQ><![CDATA["+sdf1.format(intSit.getIntelligenceValidityStart())+"]]></ZSYXQSRQ>"+ "<ZSYXJZRQ><![CDATA["+intSit.getIntelligenceValidityEnd() != null && !"".equals(intSit.getIntelligenceValidityEnd())?sdf1.format(intSit.getIntelligenceValidityEnd()):""+"]]></ZSYXJZRQ>"+ "<FZJGMC><![CDATA["+intSit.getIntelligenceInstitution()+"]]></FZJGMC>"+ "</DATA></Body></Request>"; System.out.println(xml); System.out.println(syn.uploadCompanyInfo(xml)); intSit.setAuditState("审核通过"); intSit.setCheckRemark(checkRecord.getCheckRemark()); intSitService.update(intSit); checkRecord .setCheckUserid(this.getLoginUser().getId()); checkRecord.setDelFlag(0); checkRecord.setCheckUsername(this.getLoginUser().getDisplayName()); checkRecordService.save(checkRecord); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { intSit.setAuditState(checkRecord.getCheckResult()); intSit.setCheckRemark(checkRecord.getCheckRemark()); intSitService.update(intSit); checkRecord .setCheckUserid(this.getLoginUser().getId()); checkRecord.setDelFlag(0); checkRecord.setCheckUsername(this.getLoginUser().getDisplayName()); checkRecordService.save(checkRecord); } return RELOAD; } /** * 将File对象转换为Blob对象,并设置到实体类中 * 如果没有File对象,可删除此方法,并一并删除save方法中调用此方法的代码 */ private void setBlobField(FileInputStream in) { if (null != intSit) { try { //此处将File对象转换成blob对象,并设置到intSit中去 } catch (Exception ex) { ex.printStackTrace(); } } } /** * 删除信息 */ public String delete() throws Exception{ try{ intSitService.deleteWithFlag(ids); this.getResponse().getWriter().println("{\"result\":true}"); }catch(Exception e){ this.getResponse().getWriter().println("{\"result\":false}"); } return null; } public String zwtInit(){ User user=userService.findUserByLoginId("test2"); setSessionAttribute("curr_user", user); String userId=user.getId(); if(httpService.judgeRoleCode(userId, "A02")){ roleName = "1"; setCanCheck(true); }else if(httpService.judgeRoleCode(userId, "A23")){ roleName = "0"; }else{ } return SUCCESS; } public void zwtList() throws Exception{ try { Map<String, Object> paraMap = new HashMap<String, Object>(); paraMap=httpService.addParamByRole(paraMap,this.getLoginUser().getId(), this.getLoginUser().getDeptCode()); String userId=this.getLoginUser().getId(); if(httpService.judgeRoleCode(userId, "A23")){ paraMap.put("createUserId", userId); } else { paraMap.put("state", "待提交"); } if (pagination == null) pagination = new Pagination(this.getRequest()); if (null != intSit) { //设置查询条件,开发人员可以在此增加过滤条件 if ((null != intSit.getAreaId()) && (0 < intSit.getAreaId().trim().length())) { paraMap.put("areaId", intSit.getAreaId().trim()); } if ((null != intSit.getCompanyId()) && (0 < intSit.getCompanyId().trim().length())) { paraMap.put("companyId", intSit.getCompanyId().trim()); } if ((null != intSit.getAreaName()) && (0 < intSit.getAreaName().trim().length())) { paraMap.put("areaName", intSit.getAreaName().trim()); } if ((null != intSit.getCompanyName()) && (0 < intSit.getCompanyName().trim().length())) { paraMap.put("companyName", "%" + intSit.getCompanyName().trim() + "%"); } if ((null != intSit.getIntelligenceCardnum()) && (0 < intSit.getIntelligenceCardnum().trim().length())) { paraMap.put("intelligenceCardnum", "%" + intSit.getIntelligenceCardnum().trim() + "%"); } if ((null != intSit.getIntelligenceCardname()) && (0 < intSit.getIntelligenceCardname().trim() .length())) { paraMap.put("intelligenceCardname", "%" + intSit.getIntelligenceCardname().trim() + "%"); } if ((null != intSit.getIntelligenceType()) && (0 < intSit.getIntelligenceType().trim().length())) { paraMap.put("intelligenceType", intSit .getIntelligenceType().trim()); } if ((null != intSit.getAuditResult()) && (0 < intSit.getAuditResult().trim().length())) { paraMap.put("auditResult", "%" + intSit.getAuditResult().trim() + "%"); } if ((null != intSit.getAuditState()) && (0 < intSit.getAuditState().trim().length())) { paraMap.put("auditState", intSit.getAuditState().trim()); } } if(null!=companyId&&!"".equals(companyId)){ paraMap.put("companyId", companyId.trim() ); } if(null!=searchLike&&!"".equals(searchLike)&&!"搜索企业名称、证书名称或编号".equals(searchLike)){ paraMap.put("searchLike", "%" + searchLike.trim() + "%"); } JsonConfig config = new JsonConfig(); config.registerJsonValueProcessor(java.util.Date.class, new DateJsonValueProcessor()); Map<String, String> codeMap = new HashMap<String, String>(); //此处添加需要转换的一维代码,key是一维代码在数据对象中的属性名,value是一维代码的codeId codeMap.put("intelligenceType", "40288008416c6c1a01416ccf6ab100a7"); config.registerJsonValueProcessor(String.class, new CodeJsonValueProcessor(codeMap)); final String filter = "id|areaName|companyName|intelligenceCardnum|intelligenceCardname|intelligenceType|auditResult|auditState|"; if (filter != null && filter.length() > 1) { config.setJsonPropertyFilter(new PropertyFilter() { public boolean apply(Object source, String name, Object value) { if (filter.indexOf(name + "|") != -1) return false; else return true; } }); } pagination.setPageNumber(pageNo); pagination.setPageSize(pageSize); pagination = intSitService.findByPage(pagination, paraMap); JSONObject json=new JSONObject(); JSONArray ja = JSONArray.fromObject(pagination.getListOfObject(), config); json.put("result", ja); json.put("count", pagination.getTotalCount()); int totalPage; totalPage = (pagination.getTotalCount()%pageSize==0?pagination.getTotalCount()/pageSize:(pagination.getTotalCount()/pageSize+1)); json.put("totalPage", totalPage); json.put("pageNo", pageNo); try { this.getResponse().getWriter().println(json.toString()); } catch (IOException e) { e.printStackTrace(); } } catch (Exception e) {e.printStackTrace(); // TODO: handle exception } } public String zzqk(){ //判断登录人的角色 List<UserRight> list = (List<UserRight>) this.getLoginUser().getUserRoles(); for(UserRight ur:list) { //登录人 可以审核 if(ur.getRole().getRoleCode().equals("A02")) { roleName = "1"; setCanCheck(true); break; } if(ur.getRole().getRoleCode().equals("A23")) { roleName = "0"; break; } } return SUCCESS; } public String getIds(){ return ids; } public void setIds(String ids){ this.ids = ids; } public Pagination getPagination(){ return pagination; } public void setPagination(Pagination pagination){ this.pagination = pagination; } public IntSit getIntSit(){ return this.intSit; } public void setIntSit(IntSit intSit){ this.intSit = intSit; } public String getFlag(){ return flag; } public void setFlag(String flag){ this.flag = flag; } public Date getQueryIntelligenceCardDateStart(){ return this.queryIntelligenceCardDateStart; } public void setQueryIntelligenceCardDateStart(Date queryIntelligenceCardDateStart){ this.queryIntelligenceCardDateStart = queryIntelligenceCardDateStart; } public Date getQueryIntelligenceCardDateEnd(){ return this.queryIntelligenceCardDateEnd; } public void setQueryIntelligenceCardDateEnd(Date queryIntelligenceCardDateEnd){ this.queryIntelligenceCardDateEnd = queryIntelligenceCardDateEnd; } public Date getQueryIntelligenceValidityStartStart(){ return this.queryIntelligenceValidityStartStart; } public void setQueryIntelligenceValidityStartStart(Date queryIntelligenceValidityStartStart){ this.queryIntelligenceValidityStartStart = queryIntelligenceValidityStartStart; } public Date getQueryIntelligenceValidityStartEnd(){ return this.queryIntelligenceValidityStartEnd; } public void setQueryIntelligenceValidityStartEnd(Date queryIntelligenceValidityStartEnd){ this.queryIntelligenceValidityStartEnd = queryIntelligenceValidityStartEnd; } public Date getQueryIntelligenceValidityEndStart(){ return this.queryIntelligenceValidityEndStart; } public void setQueryIntelligenceValidityEndStart(Date queryIntelligenceValidityEndStart){ this.queryIntelligenceValidityEndStart = queryIntelligenceValidityEndStart; } public Date getQueryIntelligenceValidityEndEnd(){ return this.queryIntelligenceValidityEndEnd; } public void setQueryIntelligenceValidityEndEnd(Date queryIntelligenceValidityEndEnd){ this.queryIntelligenceValidityEndEnd = queryIntelligenceValidityEndEnd; } public List<CheckRecord> getCheckRecords() { return checkRecords; } public void setCheckRecords(List<CheckRecord> checkRecords) { this.checkRecords = checkRecords; } public CheckRecord getCheckRecord() { return checkRecord; } public void setCheckRecord(CheckRecord checkRecord) { this.checkRecord = checkRecord; } public void setCanCheck(boolean canCheck) { this.canCheck = canCheck; } public boolean isCanCheck() { return canCheck; } public void setRoleName(String roleName) { this.roleName = roleName; } public String getRoleName() { return roleName; } public int getPageNo() { return pageNo; } public void setPageNo(int pageNo) { this.pageNo = pageNo; } public int getPageSize() { return pageSize; } public void setPageSize(int pageSize) { this.pageSize = pageSize; } public String getSearchLike() { return searchLike; } public void setSearchLike(String searchLike) { this.searchLike = searchLike; } public String getCompanyId() { return companyId; } public void setCompanyId(String companyId) { this.companyId = companyId; } public void sendInfo() { try { //对接资质情况 List<IntSit> zzlist = intSitService.findIntSits(null); int total1 = zzlist.size(); int num1 = total1/100; int ys1 = total1%100; if(ys1 != 0) { num1 = num1 + 1; } for(int i=0;i<num1;i++) { int start = 100*i; int end = 100*(i+1); if(end > total1) { end = total1; } GetTkzxxRequest kzqq = new GetTkzxxRequest(); ceateTkzxxUtil ceateTkzxxUtil = new ceateTkzxxUtil(); for(int j=start;j<end;j++) { IntSit zzqk = zzlist.get(j); if(zzqk.getCompanyId() != null && !"".equals(zzqk.getCompanyId())) { EntBaseInfo ent = entBaseInfoService.getById(zzqk.getCompanyId()); if(ent != null) { //对接资质情况 String zjhm = NullToString(ent.getRegistrationNumber()).replaceAll(" ", ""); if(zjhm != null && !"".equals(zjhm)) { //对接资质情况 JSONArray ja = new JSONArray(); String intelligenceCardDate = zzqk.getIntelligenceCardDate() != null?new SimpleDateFormat("yyyy-MM-dd").format(zzqk.getIntelligenceCardDate()):""; String intelligenceValidityStart = zzqk.getIntelligenceValidityStart() != null?new SimpleDateFormat("yyyy-MM-dd").format(zzqk.getIntelligenceValidityStart()):""; String intelligenceValidityEnd = zzqk.getIntelligenceValidityEnd() != null?new SimpleDateFormat("yyyy-MM-dd").format(zzqk.getIntelligenceValidityEnd()):"" ; String changeDate = zzqk.getChangeDate() != null?new SimpleDateFormat("yyyy-MM-dd").format(zzqk.getChangeDate()):"" ; ja.add((new JSONObject()).put("QYMC" , NullToString(zzqk.getCompanyName())));//企业名称 ja.add((new JSONObject()).put("ZSBH" , NullToString(zzqk.getIntelligenceCardnum())));//证书编号 ja.add((new JSONObject()).put("ZSMC" , NullToString(zzqk.getIntelligenceCardname())));//证书名称 ja.add((new JSONObject()).put("ZZLX" , zzlx(zzqk.getIntelligenceType())));//确认类型 ja.add((new JSONObject()).put("ZZLR" , NullToString(zzqk.getIntelligenceContent()) ));//资质内容 ja.add((new JSONObject()).put("FZJG" , NullToString(zzqk.getIntelligenceInstitution())));//发证机关 ja.add((new JSONObject()).put("FZRQ" ,intelligenceCardDate ));//发证日期 ja.add((new JSONObject()).put("YXQQSRQ" , intelligenceValidityStart));//有效期开始日期 ja.add((new JSONObject()).put("YXQJZRQ" ,intelligenceValidityEnd));//有效期截止时间 ja.add((new JSONObject()).put("ZZJB" ,NullToString(zzqk.getZzjb())));//资质级别 ja.add((new JSONObject()).put("BGRQ" ,changeDate));//变更日期 ja.add((new JSONObject()).put("YWFW" ,NullToString(zzqk.getBussinessScope())));//业务范围 JSONObject jo = new JSONObject(); jo.put("frkzxx", ja.toString()); String kzxx = jo.toString(); Tkzxxs tkzxxs = ceateTkzxxUtil.ceateTkzxxs("zzqkb",zzqk.getCreateTime(), kzxx, "", zjhm); kzqq.getTkzxxs().add(tkzxxs); } } } } TkzxxPortService tkzxxPortService= new TkzxxPortService(); tkzxxPortService.setHandlerResolver(new HandlerResolver() { @Override public List<Handler> getHandlerChain(PortInfo arg0) { List<Handler> handlerList = new ArrayList(); handlerList.add(new ClientAuthenticationHandler( "Zhaj_seivice@APP-00199", "zhaj")); return handlerList; } }); TkzxxPort tkzxxPort = tkzxxPortService.getTkzxxPortSoap11(); GetTkzxxResponse getTkzxxResponse = tkzxxPort.getTkzxx(kzqq); System.out.println("资质情况"+getTkzxxResponse.getStatus()); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } public String NullToString(String s) { if(s == null) { return ""; } else { return s; } } public String zzlx(String lx) { if(lx != null) { if(lx.equals("1")) { return "fglx"; //发改立项 } else if(lx.equals("2")) { return "ghxk"; //规划许可 } else if(lx.equals("3")) { return "jsxk"; //建设许可 } else if(lx.equals("4")) { return "hbxk"; //环保许可 } else if(lx.equals("5")) { return "xfxk"; //消防许可 } else if(lx.equals("6")) { return "flsc"; //防雷审查 } else if(lx.equals("7")) { return "tdz"; //土地证 } else if(lx.equals("8")) { return "fcz"; //房产证 } else if(lx.equals("9")) { return "yyzz"; //营业执照 } else if(lx.equals("10")) { return "bzhzs"; //标准化证书 } else if(lx.equals("11")) { return "ohsaszs"; //OHSAS证书 } } return ""; } public String getEntBaseInfoId() { return entBaseInfoId; } public void setEntBaseInfoId(String entBaseInfoId) { this.entBaseInfoId = entBaseInfoId; } }
UTF-8
Java
31,052
java
IntSitAction.java
Java
[ { "context": "(){\n\t\t\n\t\tUser user=userService.findUserByLoginId(\"test2\");\n\t\tsetSessionAttribute(\"curr_user\", user);\n\t\tSt", "end": 17021, "score": 0.9995086193084717, "start": 17016, "tag": "USERNAME", "value": "test2" } ]
null
[]
package com.jshx.zzqk.web; import java.io.FileInputStream; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.xml.ws.handler.Handler; import javax.xml.ws.handler.HandlerResolver; import javax.xml.ws.handler.PortInfo; import net.sf.json.JSONArray; import net.sf.json.JSONObject; import net.sf.json.JsonConfig; import net.sf.json.util.PropertyFilter; import org.apache.commons.lang.StringUtils; import org.apache.struts2.ServletActionContext; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import com.jshx.core.base.action.BaseAction; import com.jshx.core.base.vo.Pagination; import com.jshx.core.json.CodeJsonValueProcessor; import com.jshx.core.json.DateJsonValueProcessor; import com.jshx.http.service.HttpService; import com.jshx.module.admin.entity.User; import com.jshx.module.admin.entity.UserRight; import com.jshx.module.admin.service.CodeService; import com.jshx.module.admin.service.UserService; import com.jshx.photoPic.entity.PhotoPic; import com.jshx.photoPic.service.PhotoPicService; import com.jshx.qyjbxx.entity.EntBaseInfo; import com.jshx.qyjbxx.service.EntBaseInfoService; import com.jshx.qyjbxx.util.ClientAuthenticationHandler; import com.jshx.shjl.entity.CheckRecord; import com.jshx.shjl.service.CheckRecordService; import com.jshx.zzqk.entity.IntSit; import com.jshx.zzqk.service.IntSitService; import com.lkdj.kzk.GetTkzxxRequest; import com.lkdj.kzk.GetTkzxxResponse; import com.lkdj.kzk.TkzxxPort; import com.lkdj.kzk.TkzxxPortService; import com.lkdj.kzk.GetTkzxxRequest.Tkzxxs; import com.lkdj.lkLog.entity.LkLog; import com.lkdj.lkLog.service.LkLogService; import com.lkdj.util.ceateTkzxxUtil; import com.xypt.SynchronizeCompanyInfo; import com.xypt.SynchronizeCompanyInfoService; public class IntSitAction extends BaseAction { /** * 主键ID列表,用于接收页面提交的多条主键ID信息 */ private String ids; /** * 实体类 */ private IntSit intSit = new IntSit(); /** * 业务类 */ @Autowired private IntSitService intSitService; /** * 修改新增标记,add为新增、mod为修改 */ private String flag; /** * 分页信息 */ private Pagination pagination; private Date queryIntelligenceCardDateStart; private Date queryIntelligenceCardDateEnd; private Date queryIntelligenceValidityStartStart; private Date queryIntelligenceValidityStartEnd; private Date queryIntelligenceValidityEndStart; private Date queryIntelligenceValidityEndEnd; @Autowired private HttpService httpService; @Autowired private LkLogService lkLogService; @Autowired() @Qualifier("sessionFactory") private SessionFactory sessionFactory; @Autowired private CheckRecordService checkRecordService; /** * 执行查询的方法,返回json数据 */ @Autowired private PhotoPicService photoPicService; @Autowired private EntBaseInfoService entBaseInfoService; @Autowired private CodeService codeService; /** * 审核记录 */ private List<CheckRecord> checkRecords; private CheckRecord checkRecord=new CheckRecord(); private boolean canCheck=false; private String roleName; private int pageNo; private int pageSize; private String searchLike; @Autowired private UserService userService; private String companyId; private String entBaseInfoId; /** * 初始化 用于判断审核角色 */ public String init(){ //判断登录人的角色 List<UserRight> list = (List<UserRight>) this.getLoginUser().getUserRoles(); for(UserRight ur:list) { //登录人 可以审核 if(ur.getRole().getRoleCode().equals("A02")) { roleName = "1"; setCanCheck(true); break; } if(ur.getRole().getRoleCode().equals("A23")) { roleName = "0"; break; } } return SUCCESS; } private List<PhotoPic> picList = new ArrayList<PhotoPic>(); public List<PhotoPic> getPicList() { return picList; } public void setPicList(List<PhotoPic> picList) { this.picList = picList; } public void list() throws Exception{ try { Map<String, Object> paraMap = new HashMap<String, Object>(); paraMap=httpService.addParamByRole(paraMap,this.getLoginUser().getId(), this.getLoginUser().getDeptCode()); String userId=this.getLoginUser().getId(); if(httpService.judgeRoleCode(userId, "A23")){ paraMap.put("createUserId", userId); } else { paraMap.put("state", "待提交"); } String url = ServletActionContext.getRequest().getRequestURL().toString(); if(StringUtils.isNotEmpty(entBaseInfoId)){ paraMap.put("companyId", "entBaseInfoId"); } if (pagination == null) pagination = new Pagination(this.getRequest()); if (null != intSit) { //设置查询条件,开发人员可以在此增加过滤条件 if ((null != intSit.getAreaId()) && (0 < intSit.getAreaId().trim().length())) { paraMap.put("areaId", intSit.getAreaId().trim()); } if ((null != intSit.getAreaName()) && (0 < intSit.getAreaName().trim().length())) { paraMap.put("areaName", intSit.getAreaName().trim()); } if ((null != intSit.getCompanyName()) && (0 < intSit.getCompanyName().trim().length())) { paraMap.put("companyName", "%" + intSit.getCompanyName().trim() + "%"); } if ((null != intSit.getCompanyId()) && (0 < intSit.getCompanyId().trim().length())) { paraMap.put("companyId", intSit.getCompanyId().trim() ); } if ((null != intSit.getIntelligenceCardnum()) && (0 < intSit.getIntelligenceCardnum().trim().length())) { paraMap.put("intelligenceCardnum", "%" + intSit.getIntelligenceCardnum().trim() + "%"); } if ((null != intSit.getIntelligenceCardname()) && (0 < intSit.getIntelligenceCardname().trim() .length())) { paraMap.put("intelligenceCardname", "%" + intSit.getIntelligenceCardname().trim() + "%"); } if ((null != intSit.getIntelligenceType()) && (0 < intSit.getIntelligenceType().trim().length())) { paraMap.put("intelligenceType", intSit .getIntelligenceType().trim()); } if ((null != intSit.getAuditResult()) && (0 < intSit.getAuditResult().trim().length())) { paraMap.put("auditResult", "%" + intSit.getAuditResult().trim() + "%"); } if ((null != intSit.getAuditState()) && (0 < intSit.getAuditState().trim().length())) { paraMap.put("auditState", intSit.getAuditState().trim()); } } JsonConfig config = new JsonConfig(); config.registerJsonValueProcessor(java.util.Date.class, new DateJsonValueProcessor()); Map<String, String> codeMap = new HashMap<String, String>(); //此处添加需要转换的一维代码,key是一维代码在数据对象中的属性名,value是一维代码的codeId codeMap.put("intelligenceType", "40288008416c6c1a01416ccf6ab100a7"); config.registerJsonValueProcessor(String.class, new CodeJsonValueProcessor(codeMap)); final String filter = "id|areaName|companyName|intelligenceCardnum|intelligenceCardname|intelligenceType|auditResult|auditState|createUserID|"; if (filter != null && filter.length() > 1) { config.setJsonPropertyFilter(new PropertyFilter() { public boolean apply(Object source, String name, Object value) { if (filter.indexOf(name + "|") != -1) return false; else return true; } }); } pagination = intSitService.findByPage(pagination, paraMap); convObjectToJson(pagination, config); } catch (Exception e) {e.printStackTrace(); // TODO: handle exception } } /** * 查看详细信息 */ public String view() throws Exception{ if((null != intSit)&&(null != intSit.getId())) { intSit = intSitService.getById(intSit.getId()); if(intSit.getLinkId() == null || "".equals(intSit.getLinkId())) { String linkId = java.util.UUID.randomUUID().toString().replace("-", ""); intSit.setLinkId(linkId); } else { Map map = new HashMap(); map.put("linkId",intSit.getLinkId()); map.put("mkType", "zzqk"); map.put("picType","zzfj"); picList = photoPicService.findPicPath(map);//获取执法文书材料 } } else { String linkId = java.util.UUID.randomUUID().toString().replace("-", ""); intSit.setLinkId(linkId); } //审核记录 Map<String, Object> paraMap = new HashMap<String, Object>(); paraMap.put("infoId", intSit.getId()); checkRecords=checkRecordService.findCheckRecord(paraMap); return VIEW; } /** * 初始化修改信息 */ public String initEdit() throws Exception{ view(); return EDIT; } /** * 保存信息(包括新增和修改) */ public String save() throws Exception{ FileInputStream in = null; try { //设置Blob字段 setBlobField(in); } finally { if (null != in) { try { in.close(); } catch (Exception ex) { } } } Map map = new HashMap(); map.put("loginId", this.getLoginUser().getLoginId()); EntBaseInfo enBaseInfo = entBaseInfoService.findEntBaseInfoByMap(map); intSit.setAreaId(enBaseInfo.getEnterprisePossession()); Map m = new HashMap(); m.put("codeName", "企业属地"); m.put("itemValue", enBaseInfo.getEnterprisePossession()); intSit.setAreaName(codeService.findCodeValueByMap(m).getItemText()); intSit.setCompanyId(enBaseInfo.getId()); intSit.setCompanyName(enBaseInfo.getEnterpriseName()); if ("add".equalsIgnoreCase(this.flag)){ intSit.setDeptId(this.getLoginUserDepartmentId()); intSit.setDelFlag(0); intSitService.save(intSit); }else{ intSitService.update(intSit); } try { String zjhm = NullToString(enBaseInfo.getRegistrationNumber()).replaceAll(" ", ""); if(zjhm != null && !"".equals(zjhm)) { LkLog log1 = new LkLog(); log1.setNrid(intSit.getId()); log1.setLb("intSit扩展信息"); //对接资质情况 GetTkzxxRequest kzqq = new GetTkzxxRequest(); ceateTkzxxUtil ceateTkzxxUtil = new ceateTkzxxUtil(); JSONArray ja = new JSONArray(); String intelligenceCardDate = intSit.getIntelligenceCardDate() != null?new SimpleDateFormat("yyyy-MM-dd").format(intSit.getIntelligenceCardDate()):""; String intelligenceValidityStart = intSit.getIntelligenceValidityStart() != null?new SimpleDateFormat("yyyy-MM-dd").format(intSit.getIntelligenceValidityStart()):""; String intelligenceValidityEnd = intSit.getIntelligenceValidityEnd() != null?new SimpleDateFormat("yyyy-MM-dd").format(intSit.getIntelligenceValidityEnd()):"" ; String changeDate = intSit.getChangeDate() != null?new SimpleDateFormat("yyyy-MM-dd").format(intSit.getChangeDate()):"" ; ja.add((new JSONObject()).put("QYMC" , NullToString(intSit.getCompanyName())));//企业名称 ja.add((new JSONObject()).put("ZSBH" , NullToString(intSit.getIntelligenceCardnum())));//证书编号 ja.add((new JSONObject()).put("ZSMC" , NullToString(intSit.getIntelligenceCardname())));//证书名称 ja.add((new JSONObject()).put("ZZLX" , zzlx(intSit.getIntelligenceType())));//确认类型 ja.add((new JSONObject()).put("ZZLR" , NullToString(intSit.getIntelligenceContent()) ));//资质内容 ja.add((new JSONObject()).put("FZJG" , NullToString(intSit.getIntelligenceInstitution())));//发证机关 ja.add((new JSONObject()).put("FZRQ" ,intelligenceCardDate ));//发证日期 ja.add((new JSONObject()).put("YXQQSRQ" , intelligenceValidityStart));//有效期开始日期 ja.add((new JSONObject()).put("YXQJZRQ" ,intelligenceValidityEnd));//有效期截止时间 ja.add((new JSONObject()).put("ZZJB" ,NullToString(intSit.getZzjb())));//资质级别 ja.add((new JSONObject()).put("BGRQ" ,changeDate));//变更日期 ja.add((new JSONObject()).put("YWFW" ,NullToString(intSit.getBussinessScope())));//业务范围 JSONObject jo = new JSONObject(); jo.put("frkzxx", ja.toString()); String kzxx = jo.toString(); Tkzxxs tkzxxs = ceateTkzxxUtil.ceateTkzxxs("zzqkb",intSit.getCreateTime(), kzxx, "",zjhm); kzqq.getTkzxxs().add(tkzxxs); TkzxxPortService tkzxxPortService= new TkzxxPortService(); tkzxxPortService.setHandlerResolver(new HandlerResolver() { @Override public List<Handler> getHandlerChain(PortInfo arg0) { List<Handler> handlerList = new ArrayList(); handlerList.add(new ClientAuthenticationHandler( "Zhaj_seivice@APP-00199", "zhaj")); return handlerList; } }); TkzxxPort tkzxxPort = tkzxxPortService.getTkzxxPortSoap11(); GetTkzxxResponse getTkzxxResponse = tkzxxPort.getTkzxx(kzqq); System.out.println("资质情况"+getTkzxxResponse.getMsg()); log1.setResult(getTkzxxResponse.getMsg()); lkLogService.save(log1); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return RELOAD; } /** * 审核信息 */ public String check() throws Exception{ view(); return "check"; } /** * 保存审核信息 */ public String checkSave() throws Exception{ intSit=intSitService.getById(intSit.getId()); if("审核通过并上报信用平台".equals(checkRecord.getCheckResult())){ try { SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMddHHmmss"); SimpleDateFormat sdf1=new SimpleDateFormat("yyyy-MM-dd"); EntBaseInfo entBaseInfo = entBaseInfoService.getById(intSit.getCompanyId()); SynchronizeCompanyInfoService service = new SynchronizeCompanyInfoService(); service.setHandlerResolver(new HandlerResolver() { @Override public List<Handler> getHandlerChain(PortInfo arg0) { List<Handler> handlerList = new ArrayList(); handlerList.add(new ClientAuthenticationHandler( "Zhaj_seivice@APP-00199", "zhaj")); return handlerList; } }); SynchronizeCompanyInfo syn = service.getSynchronizeCompanyInfoPort(); Map map = new HashMap(); map.put("codeName", "资质类型"); map.put("itemValue", intSit.getIntelligenceType()); String zzlx=(null==codeService.findCodeValueByMap(map).getItemText()?"":codeService.findCodeValueByMap(map).getItemText()); String a=(null==intSit.getChangeDate()?"":sdf1.format(intSit.getChangeDate())); String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><Request><Head>"+ "<DeptID><![CDATA[54]]></DeptID>"+ "<InfoClass><![CDATA[安监-机构资质认定(变更)信息]]></InfoClass>"+ "<UploadTime><![CDATA["+sdf.format(new Date())+"]]></UploadTime></Head>"+ "<Body><FIELDS><![CDATA[发证日期,变更日期,组织机构代码,企业全称(中文),工商注册号/统一社会信用代码,资质名称,资质证书编号,法定代表人证件号码,资质级别,业务范围,注册地址,证书有效起始日期,证书有效截止日期,发证机关名称]]></FIELDS>"+ "<DATA>"+ "<FZRQ><![CDATA["+sdf1.format(intSit.getIntelligenceCardDate())+"]]></FZRQ>"+ "<BGRQ><![CDATA["+a+"]]></BGRQ>"+ "<ZZJGDM><![CDATA["+entBaseInfo.getEnterpriseCode()+"]]></ZZJGDM>"+ "<QYMC><![CDATA["+entBaseInfo.getEnterpriseName() +"]]></QYMC>"+ "<GSZCH><![CDATA["+entBaseInfo.getRegistrationNumber() +"]]></GSZCH>"+ "<ZZMC><![CDATA["+zzlx +"]]></ZZMC>"+ "<ZZZSBH><![CDATA["+intSit.getIntelligenceCardnum() +"]]></ZZZSBH>"+ "<FDDBRZJHM><![CDATA["+entBaseInfo.getEnterpriseLegalCardnum() +"]]></FDDBRZJHM>"+ "<ZZJB><![CDATA["+intSit.getZzjb() +"]]></ZZJB>"+ "<YWFW><![CDATA["+intSit.getBussinessScope() +"]]></YWFW>"+ "<ZCDZ><![CDATA["+entBaseInfo.getEnterpriseAddress() +"]]></ZCDZ>"+ "<ZSYXQSRQ><![CDATA["+sdf1.format(intSit.getIntelligenceValidityStart())+"]]></ZSYXQSRQ>"+ "<ZSYXJZRQ><![CDATA["+intSit.getIntelligenceValidityEnd() != null && !"".equals(intSit.getIntelligenceValidityEnd())?sdf1.format(intSit.getIntelligenceValidityEnd()):""+"]]></ZSYXJZRQ>"+ "<FZJGMC><![CDATA["+intSit.getIntelligenceInstitution()+"]]></FZJGMC>"+ "</DATA></Body></Request>"; System.out.println(xml); System.out.println(syn.uploadCompanyInfo(xml)); intSit.setAuditState("审核通过"); intSit.setCheckRemark(checkRecord.getCheckRemark()); intSitService.update(intSit); checkRecord .setCheckUserid(this.getLoginUser().getId()); checkRecord.setDelFlag(0); checkRecord.setCheckUsername(this.getLoginUser().getDisplayName()); checkRecordService.save(checkRecord); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { intSit.setAuditState(checkRecord.getCheckResult()); intSit.setCheckRemark(checkRecord.getCheckRemark()); intSitService.update(intSit); checkRecord .setCheckUserid(this.getLoginUser().getId()); checkRecord.setDelFlag(0); checkRecord.setCheckUsername(this.getLoginUser().getDisplayName()); checkRecordService.save(checkRecord); } return RELOAD; } /** * 将File对象转换为Blob对象,并设置到实体类中 * 如果没有File对象,可删除此方法,并一并删除save方法中调用此方法的代码 */ private void setBlobField(FileInputStream in) { if (null != intSit) { try { //此处将File对象转换成blob对象,并设置到intSit中去 } catch (Exception ex) { ex.printStackTrace(); } } } /** * 删除信息 */ public String delete() throws Exception{ try{ intSitService.deleteWithFlag(ids); this.getResponse().getWriter().println("{\"result\":true}"); }catch(Exception e){ this.getResponse().getWriter().println("{\"result\":false}"); } return null; } public String zwtInit(){ User user=userService.findUserByLoginId("test2"); setSessionAttribute("curr_user", user); String userId=user.getId(); if(httpService.judgeRoleCode(userId, "A02")){ roleName = "1"; setCanCheck(true); }else if(httpService.judgeRoleCode(userId, "A23")){ roleName = "0"; }else{ } return SUCCESS; } public void zwtList() throws Exception{ try { Map<String, Object> paraMap = new HashMap<String, Object>(); paraMap=httpService.addParamByRole(paraMap,this.getLoginUser().getId(), this.getLoginUser().getDeptCode()); String userId=this.getLoginUser().getId(); if(httpService.judgeRoleCode(userId, "A23")){ paraMap.put("createUserId", userId); } else { paraMap.put("state", "待提交"); } if (pagination == null) pagination = new Pagination(this.getRequest()); if (null != intSit) { //设置查询条件,开发人员可以在此增加过滤条件 if ((null != intSit.getAreaId()) && (0 < intSit.getAreaId().trim().length())) { paraMap.put("areaId", intSit.getAreaId().trim()); } if ((null != intSit.getCompanyId()) && (0 < intSit.getCompanyId().trim().length())) { paraMap.put("companyId", intSit.getCompanyId().trim()); } if ((null != intSit.getAreaName()) && (0 < intSit.getAreaName().trim().length())) { paraMap.put("areaName", intSit.getAreaName().trim()); } if ((null != intSit.getCompanyName()) && (0 < intSit.getCompanyName().trim().length())) { paraMap.put("companyName", "%" + intSit.getCompanyName().trim() + "%"); } if ((null != intSit.getIntelligenceCardnum()) && (0 < intSit.getIntelligenceCardnum().trim().length())) { paraMap.put("intelligenceCardnum", "%" + intSit.getIntelligenceCardnum().trim() + "%"); } if ((null != intSit.getIntelligenceCardname()) && (0 < intSit.getIntelligenceCardname().trim() .length())) { paraMap.put("intelligenceCardname", "%" + intSit.getIntelligenceCardname().trim() + "%"); } if ((null != intSit.getIntelligenceType()) && (0 < intSit.getIntelligenceType().trim().length())) { paraMap.put("intelligenceType", intSit .getIntelligenceType().trim()); } if ((null != intSit.getAuditResult()) && (0 < intSit.getAuditResult().trim().length())) { paraMap.put("auditResult", "%" + intSit.getAuditResult().trim() + "%"); } if ((null != intSit.getAuditState()) && (0 < intSit.getAuditState().trim().length())) { paraMap.put("auditState", intSit.getAuditState().trim()); } } if(null!=companyId&&!"".equals(companyId)){ paraMap.put("companyId", companyId.trim() ); } if(null!=searchLike&&!"".equals(searchLike)&&!"搜索企业名称、证书名称或编号".equals(searchLike)){ paraMap.put("searchLike", "%" + searchLike.trim() + "%"); } JsonConfig config = new JsonConfig(); config.registerJsonValueProcessor(java.util.Date.class, new DateJsonValueProcessor()); Map<String, String> codeMap = new HashMap<String, String>(); //此处添加需要转换的一维代码,key是一维代码在数据对象中的属性名,value是一维代码的codeId codeMap.put("intelligenceType", "40288008416c6c1a01416ccf6ab100a7"); config.registerJsonValueProcessor(String.class, new CodeJsonValueProcessor(codeMap)); final String filter = "id|areaName|companyName|intelligenceCardnum|intelligenceCardname|intelligenceType|auditResult|auditState|"; if (filter != null && filter.length() > 1) { config.setJsonPropertyFilter(new PropertyFilter() { public boolean apply(Object source, String name, Object value) { if (filter.indexOf(name + "|") != -1) return false; else return true; } }); } pagination.setPageNumber(pageNo); pagination.setPageSize(pageSize); pagination = intSitService.findByPage(pagination, paraMap); JSONObject json=new JSONObject(); JSONArray ja = JSONArray.fromObject(pagination.getListOfObject(), config); json.put("result", ja); json.put("count", pagination.getTotalCount()); int totalPage; totalPage = (pagination.getTotalCount()%pageSize==0?pagination.getTotalCount()/pageSize:(pagination.getTotalCount()/pageSize+1)); json.put("totalPage", totalPage); json.put("pageNo", pageNo); try { this.getResponse().getWriter().println(json.toString()); } catch (IOException e) { e.printStackTrace(); } } catch (Exception e) {e.printStackTrace(); // TODO: handle exception } } public String zzqk(){ //判断登录人的角色 List<UserRight> list = (List<UserRight>) this.getLoginUser().getUserRoles(); for(UserRight ur:list) { //登录人 可以审核 if(ur.getRole().getRoleCode().equals("A02")) { roleName = "1"; setCanCheck(true); break; } if(ur.getRole().getRoleCode().equals("A23")) { roleName = "0"; break; } } return SUCCESS; } public String getIds(){ return ids; } public void setIds(String ids){ this.ids = ids; } public Pagination getPagination(){ return pagination; } public void setPagination(Pagination pagination){ this.pagination = pagination; } public IntSit getIntSit(){ return this.intSit; } public void setIntSit(IntSit intSit){ this.intSit = intSit; } public String getFlag(){ return flag; } public void setFlag(String flag){ this.flag = flag; } public Date getQueryIntelligenceCardDateStart(){ return this.queryIntelligenceCardDateStart; } public void setQueryIntelligenceCardDateStart(Date queryIntelligenceCardDateStart){ this.queryIntelligenceCardDateStart = queryIntelligenceCardDateStart; } public Date getQueryIntelligenceCardDateEnd(){ return this.queryIntelligenceCardDateEnd; } public void setQueryIntelligenceCardDateEnd(Date queryIntelligenceCardDateEnd){ this.queryIntelligenceCardDateEnd = queryIntelligenceCardDateEnd; } public Date getQueryIntelligenceValidityStartStart(){ return this.queryIntelligenceValidityStartStart; } public void setQueryIntelligenceValidityStartStart(Date queryIntelligenceValidityStartStart){ this.queryIntelligenceValidityStartStart = queryIntelligenceValidityStartStart; } public Date getQueryIntelligenceValidityStartEnd(){ return this.queryIntelligenceValidityStartEnd; } public void setQueryIntelligenceValidityStartEnd(Date queryIntelligenceValidityStartEnd){ this.queryIntelligenceValidityStartEnd = queryIntelligenceValidityStartEnd; } public Date getQueryIntelligenceValidityEndStart(){ return this.queryIntelligenceValidityEndStart; } public void setQueryIntelligenceValidityEndStart(Date queryIntelligenceValidityEndStart){ this.queryIntelligenceValidityEndStart = queryIntelligenceValidityEndStart; } public Date getQueryIntelligenceValidityEndEnd(){ return this.queryIntelligenceValidityEndEnd; } public void setQueryIntelligenceValidityEndEnd(Date queryIntelligenceValidityEndEnd){ this.queryIntelligenceValidityEndEnd = queryIntelligenceValidityEndEnd; } public List<CheckRecord> getCheckRecords() { return checkRecords; } public void setCheckRecords(List<CheckRecord> checkRecords) { this.checkRecords = checkRecords; } public CheckRecord getCheckRecord() { return checkRecord; } public void setCheckRecord(CheckRecord checkRecord) { this.checkRecord = checkRecord; } public void setCanCheck(boolean canCheck) { this.canCheck = canCheck; } public boolean isCanCheck() { return canCheck; } public void setRoleName(String roleName) { this.roleName = roleName; } public String getRoleName() { return roleName; } public int getPageNo() { return pageNo; } public void setPageNo(int pageNo) { this.pageNo = pageNo; } public int getPageSize() { return pageSize; } public void setPageSize(int pageSize) { this.pageSize = pageSize; } public String getSearchLike() { return searchLike; } public void setSearchLike(String searchLike) { this.searchLike = searchLike; } public String getCompanyId() { return companyId; } public void setCompanyId(String companyId) { this.companyId = companyId; } public void sendInfo() { try { //对接资质情况 List<IntSit> zzlist = intSitService.findIntSits(null); int total1 = zzlist.size(); int num1 = total1/100; int ys1 = total1%100; if(ys1 != 0) { num1 = num1 + 1; } for(int i=0;i<num1;i++) { int start = 100*i; int end = 100*(i+1); if(end > total1) { end = total1; } GetTkzxxRequest kzqq = new GetTkzxxRequest(); ceateTkzxxUtil ceateTkzxxUtil = new ceateTkzxxUtil(); for(int j=start;j<end;j++) { IntSit zzqk = zzlist.get(j); if(zzqk.getCompanyId() != null && !"".equals(zzqk.getCompanyId())) { EntBaseInfo ent = entBaseInfoService.getById(zzqk.getCompanyId()); if(ent != null) { //对接资质情况 String zjhm = NullToString(ent.getRegistrationNumber()).replaceAll(" ", ""); if(zjhm != null && !"".equals(zjhm)) { //对接资质情况 JSONArray ja = new JSONArray(); String intelligenceCardDate = zzqk.getIntelligenceCardDate() != null?new SimpleDateFormat("yyyy-MM-dd").format(zzqk.getIntelligenceCardDate()):""; String intelligenceValidityStart = zzqk.getIntelligenceValidityStart() != null?new SimpleDateFormat("yyyy-MM-dd").format(zzqk.getIntelligenceValidityStart()):""; String intelligenceValidityEnd = zzqk.getIntelligenceValidityEnd() != null?new SimpleDateFormat("yyyy-MM-dd").format(zzqk.getIntelligenceValidityEnd()):"" ; String changeDate = zzqk.getChangeDate() != null?new SimpleDateFormat("yyyy-MM-dd").format(zzqk.getChangeDate()):"" ; ja.add((new JSONObject()).put("QYMC" , NullToString(zzqk.getCompanyName())));//企业名称 ja.add((new JSONObject()).put("ZSBH" , NullToString(zzqk.getIntelligenceCardnum())));//证书编号 ja.add((new JSONObject()).put("ZSMC" , NullToString(zzqk.getIntelligenceCardname())));//证书名称 ja.add((new JSONObject()).put("ZZLX" , zzlx(zzqk.getIntelligenceType())));//确认类型 ja.add((new JSONObject()).put("ZZLR" , NullToString(zzqk.getIntelligenceContent()) ));//资质内容 ja.add((new JSONObject()).put("FZJG" , NullToString(zzqk.getIntelligenceInstitution())));//发证机关 ja.add((new JSONObject()).put("FZRQ" ,intelligenceCardDate ));//发证日期 ja.add((new JSONObject()).put("YXQQSRQ" , intelligenceValidityStart));//有效期开始日期 ja.add((new JSONObject()).put("YXQJZRQ" ,intelligenceValidityEnd));//有效期截止时间 ja.add((new JSONObject()).put("ZZJB" ,NullToString(zzqk.getZzjb())));//资质级别 ja.add((new JSONObject()).put("BGRQ" ,changeDate));//变更日期 ja.add((new JSONObject()).put("YWFW" ,NullToString(zzqk.getBussinessScope())));//业务范围 JSONObject jo = new JSONObject(); jo.put("frkzxx", ja.toString()); String kzxx = jo.toString(); Tkzxxs tkzxxs = ceateTkzxxUtil.ceateTkzxxs("zzqkb",zzqk.getCreateTime(), kzxx, "", zjhm); kzqq.getTkzxxs().add(tkzxxs); } } } } TkzxxPortService tkzxxPortService= new TkzxxPortService(); tkzxxPortService.setHandlerResolver(new HandlerResolver() { @Override public List<Handler> getHandlerChain(PortInfo arg0) { List<Handler> handlerList = new ArrayList(); handlerList.add(new ClientAuthenticationHandler( "Zhaj_seivice@APP-00199", "zhaj")); return handlerList; } }); TkzxxPort tkzxxPort = tkzxxPortService.getTkzxxPortSoap11(); GetTkzxxResponse getTkzxxResponse = tkzxxPort.getTkzxx(kzqq); System.out.println("资质情况"+getTkzxxResponse.getStatus()); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } public String NullToString(String s) { if(s == null) { return ""; } else { return s; } } public String zzlx(String lx) { if(lx != null) { if(lx.equals("1")) { return "fglx"; //发改立项 } else if(lx.equals("2")) { return "ghxk"; //规划许可 } else if(lx.equals("3")) { return "jsxk"; //建设许可 } else if(lx.equals("4")) { return "hbxk"; //环保许可 } else if(lx.equals("5")) { return "xfxk"; //消防许可 } else if(lx.equals("6")) { return "flsc"; //防雷审查 } else if(lx.equals("7")) { return "tdz"; //土地证 } else if(lx.equals("8")) { return "fcz"; //房产证 } else if(lx.equals("9")) { return "yyzz"; //营业执照 } else if(lx.equals("10")) { return "bzhzs"; //标准化证书 } else if(lx.equals("11")) { return "ohsaszs"; //OHSAS证书 } } return ""; } public String getEntBaseInfoId() { return entBaseInfoId; } public void setEntBaseInfoId(String entBaseInfoId) { this.entBaseInfoId = entBaseInfoId; } }
31,052
0.676872
0.671018
986
29.144016
28.755589
190
false
false
0
0
0
0
0
0
3.207911
false
false
2
d9c335b812d636d1982bb180016432c1d8caab2a
21,071,109,620,155
4c0452c90068a88520a081725dcec5cc80e0e3ec
/app/src/main/java/com/viaplayapi/sample/viewmodel/PageViewModelFactory.java
712b8eb1f07a45a3a2893f6721d2912368b1cdc3
[]
no_license
tusharrjadhav/ViaPlayAPI
https://github.com/tusharrjadhav/ViaPlayAPI
d05bb46e876a40df4e54cb364d8ece1568b52cdc
c8c4bc358a1ddec1f91cd7bf79fc42034ee4bb55
refs/heads/master
2021-09-09T23:10:06.573000
2018-03-20T06:44:11
2018-03-20T06:44:11
111,391,279
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.viaplayapi.sample.viewmodel; import android.arch.lifecycle.ViewModel; import android.arch.lifecycle.ViewModelProvider; import android.support.annotation.NonNull; import com.viaplayapi.sample.data.source.local.LocalRepository; import com.viaplayapi.sample.data.source.remote.RemoteRepository; /** * Created by Tushar_temp on 19/11/17 */ public class PageViewModelFactory implements ViewModelProvider.Factory { private static PageViewModelFactory INSTANCE; private RemoteRepository remoteRepository; private LocalRepository localRepository; public static void initialize(RemoteRepository remoteRepository, LocalRepository localRepository) { INSTANCE = new PageViewModelFactory(remoteRepository, localRepository); } public static synchronized PageViewModelFactory getInstance() { if (INSTANCE == null) { throw new RuntimeException("PageViewModelFactory not initialized"); } return INSTANCE; } private PageViewModelFactory(RemoteRepository remoteRepository, LocalRepository localRepository) { this.remoteRepository = remoteRepository; this.localRepository = localRepository; } @Override public <T extends ViewModel> T create(@NonNull Class<T> modelClass) { if (modelClass.isAssignableFrom(PageViewModel.class)) { //noinspection unchecked return (T) new PageViewModel(remoteRepository, localRepository); } throw new IllegalArgumentException("Wrong ViewModel class"); } }
UTF-8
Java
1,546
java
PageViewModelFactory.java
Java
[ { "context": "source.remote.RemoteRepository;\n\n/**\n * Created by Tushar_temp on 19/11/17\n */\n\npublic class PageViewModelFactor", "end": 336, "score": 0.9995515942573547, "start": 325, "tag": "USERNAME", "value": "Tushar_temp" } ]
null
[]
package com.viaplayapi.sample.viewmodel; import android.arch.lifecycle.ViewModel; import android.arch.lifecycle.ViewModelProvider; import android.support.annotation.NonNull; import com.viaplayapi.sample.data.source.local.LocalRepository; import com.viaplayapi.sample.data.source.remote.RemoteRepository; /** * Created by Tushar_temp on 19/11/17 */ public class PageViewModelFactory implements ViewModelProvider.Factory { private static PageViewModelFactory INSTANCE; private RemoteRepository remoteRepository; private LocalRepository localRepository; public static void initialize(RemoteRepository remoteRepository, LocalRepository localRepository) { INSTANCE = new PageViewModelFactory(remoteRepository, localRepository); } public static synchronized PageViewModelFactory getInstance() { if (INSTANCE == null) { throw new RuntimeException("PageViewModelFactory not initialized"); } return INSTANCE; } private PageViewModelFactory(RemoteRepository remoteRepository, LocalRepository localRepository) { this.remoteRepository = remoteRepository; this.localRepository = localRepository; } @Override public <T extends ViewModel> T create(@NonNull Class<T> modelClass) { if (modelClass.isAssignableFrom(PageViewModel.class)) { //noinspection unchecked return (T) new PageViewModel(remoteRepository, localRepository); } throw new IllegalArgumentException("Wrong ViewModel class"); } }
1,546
0.746442
0.742561
45
33.355556
31.261021
103
false
false
0
0
0
0
0
0
0.444444
false
false
2
779051b0949389134653513600c747308f191cab
21,010,980,033,268
960785b60157efd87e585538b851b0e4a0a27c5c
/web/src/main/java/com/soffid/iam/addons/federation/web/KeytabParser.java
583a650e6dc7bba53b11de79d55faaae7faa8cdb
[]
no_license
SoffidIAM/addon-federation
https://github.com/SoffidIAM/addon-federation
116392374983685aa632a96c1bf7ddc7de8b9f1f
53f338497315045a4752ae596d5150ecfb48e0af
refs/heads/master
2023-08-05T02:52:43.584000
2021-03-11T16:32:42
2021-03-11T16:32:42
20,012,684
0
0
null
false
2022-11-16T10:37:43
2014-05-21T07:49:07
2021-03-11T16:32:47
2022-11-16T10:37:39
2,591
0
0
9
Java
false
false
package com.soffid.iam.addons.federation.web; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import javax.security.auth.kerberos.KerberosPrincipal; import sun.security.krb5.PrincipalName; import sun.security.krb5.internal.ktab.*; import org.zkoss.util.media.Media; import org.zkoss.zk.ui.UiException; import com.soffid.iam.addons.federation.common.FederationMember; import com.soffid.iam.addons.federation.common.KerberosKeytab; public class KeytabParser { public void parse (Media media, FederationMember federationMember) throws IOException { File tmpFile = File.createTempFile("test", ".keytab"); FileOutputStream out = new FileOutputStream(tmpFile); ByteArrayOutputStream bout = new ByteArrayOutputStream(); if (! media.isBinary()) throw new UiException("Uplodaded data seems to be text. It should be binary a keytab file"); if (media.inMemory()) { out.write(media.getByteData()); bout.write(media.getByteData()); } else { InputStream in = media.getStreamData(); for (int read = in.read(); read >= 0; read = in.read()) { out.write(read); bout.write(read); } } out.close(); bout.close(); KeyTab kt = KeyTab.getInstance(tmpFile); for (KeyTabEntry entry: kt.getEntries()) { PrincipalName principal = entry.getService(); KerberosKeytab kkt = new KerberosKeytab(); kkt.setDescription(""); kkt.setDomain( principal.getRealmAsString() ); kkt.setPrincipal( principal.getName() ); kkt.setKeyTab(bout.toByteArray()); federationMember.getKeytabs().add(kkt); break; } } }
UTF-8
Java
1,665
java
KeytabParser.java
Java
[]
null
[]
package com.soffid.iam.addons.federation.web; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import javax.security.auth.kerberos.KerberosPrincipal; import sun.security.krb5.PrincipalName; import sun.security.krb5.internal.ktab.*; import org.zkoss.util.media.Media; import org.zkoss.zk.ui.UiException; import com.soffid.iam.addons.federation.common.FederationMember; import com.soffid.iam.addons.federation.common.KerberosKeytab; public class KeytabParser { public void parse (Media media, FederationMember federationMember) throws IOException { File tmpFile = File.createTempFile("test", ".keytab"); FileOutputStream out = new FileOutputStream(tmpFile); ByteArrayOutputStream bout = new ByteArrayOutputStream(); if (! media.isBinary()) throw new UiException("Uplodaded data seems to be text. It should be binary a keytab file"); if (media.inMemory()) { out.write(media.getByteData()); bout.write(media.getByteData()); } else { InputStream in = media.getStreamData(); for (int read = in.read(); read >= 0; read = in.read()) { out.write(read); bout.write(read); } } out.close(); bout.close(); KeyTab kt = KeyTab.getInstance(tmpFile); for (KeyTabEntry entry: kt.getEntries()) { PrincipalName principal = entry.getService(); KerberosKeytab kkt = new KerberosKeytab(); kkt.setDescription(""); kkt.setDomain( principal.getRealmAsString() ); kkt.setPrincipal( principal.getName() ); kkt.setKeyTab(bout.toByteArray()); federationMember.getKeytabs().add(kkt); break; } } }
1,665
0.72973
0.727928
59
27.220339
23.235031
95
false
false
0
0
0
0
0
0
2.186441
false
false
2
f2a4ea4c65c03bcdfca9e5f5ecc036c629ca8e32
28,321,014,374,185
89e5555bb0972def566596cf7a405263e56d1ce1
/src/main/java/com/hyp/entity/ScosAuditTask.java
2536389bfd8200c055603de844128e27d205bf65
[]
no_license
IT-Financial/KafkaConsumer
https://github.com/IT-Financial/KafkaConsumer
1f985045e673285263d3680c8cd53a6e21daa28e
b267bb49423ef0db14be7895dafa2e8dd763737d
refs/heads/master
2022-07-20T19:00:20.159000
2019-10-16T16:31:23
2019-10-16T16:31:23
203,692,632
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.hyp.entity; public class ScosAuditTask { private static final long serialVersionUID = 1L; private String id; private String change_date; private String change_emp; private String create_date; private String create_emp; private String enable_flag; private String accept_serial_no; private String atomic_no; private String match_atomic_no; private String audit_status; private String cert_no; private String cert_type; private String curr_flow_node; private String cust_no; private String cust_type; private String lock_emp; private String lock_flag; private String name; private String next_flow_emp; private String next_flow_mode; private String next_flow_node; private String next_flow_post; private String type_scope; private String business_schedule_id; private String process_audit_detail_id; private String process_audit_id; private String audit_type; private String ser_no; private String GetTime; /* 以下三个字段, 调试专用, 非 kafka 消息包含的数据 */ private int topic_par; /* 非 json 包含字段, 用于记录该消息所在的 topic partition */ private long par_offset; /* 非 json 包含字段, 用于记录该消息所在的 partition 的 offset */ private int payload_length; /* 非 json 包含字段, 用于记录该消息的 长度 */ public String getId() { return id; } public void setId(String id) { this.id = id; } public String getChange_date() { return change_date; } public void setChange_date(String change_date) { this.change_date = change_date; } public String getChange_emp() { return change_emp; } public void setChange_emp(String change_emp) { this.change_emp = change_emp; } public String getCreate_date() { return create_date; } public void setCreate_date(String create_date) { this.create_date = create_date; } public String getCreate_emp() { return create_emp; } public void setCreate_emp(String create_emp) { this.create_emp = create_emp; } public String getEnable_flag() { return enable_flag; } public void setEnable_flag(String enable_flag) { this.enable_flag = enable_flag; } public String getAccept_serial_no() { return accept_serial_no; } public void setAccept_serial_no(String accept_serial_no) { this.accept_serial_no = accept_serial_no; } public String getAtomic_no() { return atomic_no; } public void setAtomic_no(String atomic_no) { this.atomic_no = atomic_no; } public String getMatch_atomic_no() { return match_atomic_no; } public void setMatch_atomic_no(String match_atomic_no) { this.match_atomic_no = match_atomic_no; } public String getAudit_status() { return audit_status; } public void setAudit_status(String audit_status) { this.audit_status = audit_status; } public String getCert_no() { return cert_no; } public void setCert_no(String cert_no) { this.cert_no = cert_no; } public String getCert_type() { return cert_type; } public void setCert_type(String cert_type) { this.cert_type = cert_type; } public String getCurr_flow_node() { return curr_flow_node; } public void setCurr_flow_node(String curr_flow_node) { this.curr_flow_node = curr_flow_node; } public String getCust_no() { return cust_no; } public void setCust_no(String cust_no) { this.cust_no = cust_no; } public String getCust_type() { return cust_type; } public void setCust_type(String cust_type) { this.cust_type = cust_type; } public String getLock_emp() { return lock_emp; } public void setLock_emp(String lock_emp) { this.lock_emp = lock_emp; } public String getLock_flag() { return lock_flag; } public void setLock_flag(String lock_flag) { this.lock_flag = lock_flag; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getNext_flow_emp() { return next_flow_emp; } public void setNext_flow_emp(String next_flow_emp) { this.next_flow_emp = next_flow_emp; } public String getNext_flow_mode() { return next_flow_mode; } public void setNext_flow_mode(String next_flow_mode) { this.next_flow_mode = next_flow_mode; } public String getNext_flow_node() { return next_flow_node; } public void setNext_flow_node(String next_flow_node) { this.next_flow_node = next_flow_node; } public String getNext_flow_post() { return next_flow_post; } public void setNext_flow_post(String next_flow_post) { this.next_flow_post = next_flow_post; } public String getType_scope() { return type_scope; } public void setType_scope(String type_scope) { this.type_scope = type_scope; } public String getBusiness_schedule_id() { return business_schedule_id; } public void setBusiness_schedule_id(String business_schedule_id) { this.business_schedule_id = business_schedule_id; } public String getProcess_audit_detail_id() { return process_audit_detail_id; } public void setProcess_audit_detail_id(String process_audit_detail_id) { this.process_audit_detail_id = process_audit_detail_id; } public String getProcess_audit_id() { return process_audit_id; } public void setProcess_audit_id(String process_audit_id) { this.process_audit_id = process_audit_id; } public String getAudit_type() { return audit_type; } public void setAudit_type(String audit_type) { this.audit_type = audit_type; } public String getSer_no() { return ser_no; } public void setSer_no(String ser_no) { this.ser_no = ser_no; } public String getGetTime() { return GetTime; } public void setGetTime(String getTime) { GetTime = getTime; } public int getTopic_par() { return topic_par; } public void setTopic_par(int topic_par) { this.topic_par = topic_par; } public long getPar_offset() { return par_offset; } public void setPar_offset(long par_offset) { this.par_offset = par_offset; } public int getPayload_length() { return payload_length; } public void setPayload_length(int payload_length) { this.payload_length = payload_length; } @Override public String toString() { return "ScosAuditTask{" + "id='" + id + '\'' + ", change_date='" + change_date + '\'' + ", change_emp='" + change_emp + '\'' + ", create_date='" + create_date + '\'' + ", create_emp='" + create_emp + '\'' + ", enable_flag='" + enable_flag + '\'' + ", accept_serial_no='" + accept_serial_no + '\'' + ", atomic_no='" + atomic_no + '\'' + ", match_atomic_no='" + match_atomic_no + '\'' + ", audit_status='" + audit_status + '\'' + ", cert_no='" + cert_no + '\'' + ", cert_type='" + cert_type + '\'' + ", curr_flow_node='" + curr_flow_node + '\'' + ", cust_no='" + cust_no + '\'' + ", cust_type='" + cust_type + '\'' + ", lock_emp='" + lock_emp + '\'' + ", lock_flag='" + lock_flag + '\'' + ", name='" + name + '\'' + ", next_flow_emp='" + next_flow_emp + '\'' + ", next_flow_mode='" + next_flow_mode + '\'' + ", next_flow_node='" + next_flow_node + '\'' + ", next_flow_post='" + next_flow_post + '\'' + ", type_scope='" + type_scope + '\'' + ", business_schedule_id='" + business_schedule_id + '\'' + ", process_audit_detail_id='" + process_audit_detail_id + '\'' + ", process_audit_id='" + process_audit_id + '\'' + ", audit_type='" + audit_type + '\'' + ", ser_no='" + ser_no + '\'' + ", GetTime='" + GetTime + '\'' + ", topic_par=" + topic_par + ", par_offset=" + par_offset + ", payload_length=" + payload_length + '}'; } }
UTF-8
Java
8,826
java
ScosAuditTask.java
Java
[ { "context": " + lock_flag + '\\'' +\n \", name='\" + name + '\\'' +\n \", next_flow_emp='\" + ne", "end": 7833, "score": 0.8976261615753174, "start": 7829, "tag": "NAME", "value": "name" } ]
null
[]
package com.hyp.entity; public class ScosAuditTask { private static final long serialVersionUID = 1L; private String id; private String change_date; private String change_emp; private String create_date; private String create_emp; private String enable_flag; private String accept_serial_no; private String atomic_no; private String match_atomic_no; private String audit_status; private String cert_no; private String cert_type; private String curr_flow_node; private String cust_no; private String cust_type; private String lock_emp; private String lock_flag; private String name; private String next_flow_emp; private String next_flow_mode; private String next_flow_node; private String next_flow_post; private String type_scope; private String business_schedule_id; private String process_audit_detail_id; private String process_audit_id; private String audit_type; private String ser_no; private String GetTime; /* 以下三个字段, 调试专用, 非 kafka 消息包含的数据 */ private int topic_par; /* 非 json 包含字段, 用于记录该消息所在的 topic partition */ private long par_offset; /* 非 json 包含字段, 用于记录该消息所在的 partition 的 offset */ private int payload_length; /* 非 json 包含字段, 用于记录该消息的 长度 */ public String getId() { return id; } public void setId(String id) { this.id = id; } public String getChange_date() { return change_date; } public void setChange_date(String change_date) { this.change_date = change_date; } public String getChange_emp() { return change_emp; } public void setChange_emp(String change_emp) { this.change_emp = change_emp; } public String getCreate_date() { return create_date; } public void setCreate_date(String create_date) { this.create_date = create_date; } public String getCreate_emp() { return create_emp; } public void setCreate_emp(String create_emp) { this.create_emp = create_emp; } public String getEnable_flag() { return enable_flag; } public void setEnable_flag(String enable_flag) { this.enable_flag = enable_flag; } public String getAccept_serial_no() { return accept_serial_no; } public void setAccept_serial_no(String accept_serial_no) { this.accept_serial_no = accept_serial_no; } public String getAtomic_no() { return atomic_no; } public void setAtomic_no(String atomic_no) { this.atomic_no = atomic_no; } public String getMatch_atomic_no() { return match_atomic_no; } public void setMatch_atomic_no(String match_atomic_no) { this.match_atomic_no = match_atomic_no; } public String getAudit_status() { return audit_status; } public void setAudit_status(String audit_status) { this.audit_status = audit_status; } public String getCert_no() { return cert_no; } public void setCert_no(String cert_no) { this.cert_no = cert_no; } public String getCert_type() { return cert_type; } public void setCert_type(String cert_type) { this.cert_type = cert_type; } public String getCurr_flow_node() { return curr_flow_node; } public void setCurr_flow_node(String curr_flow_node) { this.curr_flow_node = curr_flow_node; } public String getCust_no() { return cust_no; } public void setCust_no(String cust_no) { this.cust_no = cust_no; } public String getCust_type() { return cust_type; } public void setCust_type(String cust_type) { this.cust_type = cust_type; } public String getLock_emp() { return lock_emp; } public void setLock_emp(String lock_emp) { this.lock_emp = lock_emp; } public String getLock_flag() { return lock_flag; } public void setLock_flag(String lock_flag) { this.lock_flag = lock_flag; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getNext_flow_emp() { return next_flow_emp; } public void setNext_flow_emp(String next_flow_emp) { this.next_flow_emp = next_flow_emp; } public String getNext_flow_mode() { return next_flow_mode; } public void setNext_flow_mode(String next_flow_mode) { this.next_flow_mode = next_flow_mode; } public String getNext_flow_node() { return next_flow_node; } public void setNext_flow_node(String next_flow_node) { this.next_flow_node = next_flow_node; } public String getNext_flow_post() { return next_flow_post; } public void setNext_flow_post(String next_flow_post) { this.next_flow_post = next_flow_post; } public String getType_scope() { return type_scope; } public void setType_scope(String type_scope) { this.type_scope = type_scope; } public String getBusiness_schedule_id() { return business_schedule_id; } public void setBusiness_schedule_id(String business_schedule_id) { this.business_schedule_id = business_schedule_id; } public String getProcess_audit_detail_id() { return process_audit_detail_id; } public void setProcess_audit_detail_id(String process_audit_detail_id) { this.process_audit_detail_id = process_audit_detail_id; } public String getProcess_audit_id() { return process_audit_id; } public void setProcess_audit_id(String process_audit_id) { this.process_audit_id = process_audit_id; } public String getAudit_type() { return audit_type; } public void setAudit_type(String audit_type) { this.audit_type = audit_type; } public String getSer_no() { return ser_no; } public void setSer_no(String ser_no) { this.ser_no = ser_no; } public String getGetTime() { return GetTime; } public void setGetTime(String getTime) { GetTime = getTime; } public int getTopic_par() { return topic_par; } public void setTopic_par(int topic_par) { this.topic_par = topic_par; } public long getPar_offset() { return par_offset; } public void setPar_offset(long par_offset) { this.par_offset = par_offset; } public int getPayload_length() { return payload_length; } public void setPayload_length(int payload_length) { this.payload_length = payload_length; } @Override public String toString() { return "ScosAuditTask{" + "id='" + id + '\'' + ", change_date='" + change_date + '\'' + ", change_emp='" + change_emp + '\'' + ", create_date='" + create_date + '\'' + ", create_emp='" + create_emp + '\'' + ", enable_flag='" + enable_flag + '\'' + ", accept_serial_no='" + accept_serial_no + '\'' + ", atomic_no='" + atomic_no + '\'' + ", match_atomic_no='" + match_atomic_no + '\'' + ", audit_status='" + audit_status + '\'' + ", cert_no='" + cert_no + '\'' + ", cert_type='" + cert_type + '\'' + ", curr_flow_node='" + curr_flow_node + '\'' + ", cust_no='" + cust_no + '\'' + ", cust_type='" + cust_type + '\'' + ", lock_emp='" + lock_emp + '\'' + ", lock_flag='" + lock_flag + '\'' + ", name='" + name + '\'' + ", next_flow_emp='" + next_flow_emp + '\'' + ", next_flow_mode='" + next_flow_mode + '\'' + ", next_flow_node='" + next_flow_node + '\'' + ", next_flow_post='" + next_flow_post + '\'' + ", type_scope='" + type_scope + '\'' + ", business_schedule_id='" + business_schedule_id + '\'' + ", process_audit_detail_id='" + process_audit_detail_id + '\'' + ", process_audit_id='" + process_audit_id + '\'' + ", audit_type='" + audit_type + '\'' + ", ser_no='" + ser_no + '\'' + ", GetTime='" + GetTime + '\'' + ", topic_par=" + topic_par + ", par_offset=" + par_offset + ", payload_length=" + payload_length + '}'; } }
8,826
0.558979
0.558864
333
25.120121
21.130169
80
false
false
0
0
0
0
0
0
0.405405
false
false
2
1299e66677346838a9816a725e179b21c10b6677
2,628,519,990,867
a2dcd79a51fbaadca0f9345d2c24dedb7a0b570a
/src/main/java/com/andyn/repository/MaintenanceTypeRepository.java
bf5a1c188272f9439be191bd31ecbf2e669a2dc3
[]
no_license
andyN42/autoMaintenance
https://github.com/andyN42/autoMaintenance
0e1211fc4de5d979ba824370402a377908e3133e
8d31213cb7c68a85d7dddab534ff8c1b9d3725c0
refs/heads/master
2022-09-02T08:29:41.195000
2016-06-15T19:23:56
2016-06-15T19:23:56
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.andyn.repository; import com.andyn.model.MaintenanceType; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; @Repository public interface MaintenanceTypeRepository extends CrudRepository<MaintenanceType, Integer> { }
UTF-8
Java
289
java
MaintenanceTypeRepository.java
Java
[]
null
[]
package com.andyn.repository; import com.andyn.model.MaintenanceType; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; @Repository public interface MaintenanceTypeRepository extends CrudRepository<MaintenanceType, Integer> { }
289
0.858131
0.858131
9
31.111111
30.160477
93
false
false
0
0
0
0
0
0
0.555556
false
false
2
a24168db1477853c8c544ebee8d22c4836e3e14e
28,424,093,591,085
b28e4958db918fb1da18a1a3173b1def4b447e1d
/Example24.java
fad87d3083aa7d32502e7a4c4012ebc25caaa2d7
[]
no_license
iamsuryasikharej/FizzBizz
https://github.com/iamsuryasikharej/FizzBizz
398770950921b85e5e8e4091c9cfaedd1d4e08e8
0703a001358e9fc65f2c0df2e507e751c4136406
refs/heads/master
2020-04-19T09:32:18.310000
2019-01-30T09:49:03
2019-01-30T09:49:03
168,113,991
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
class a{ public void fizzbizz() { for(int i=1;i<=100;i++) { if (i%3==0) { System.out.println("fizz"+i); } else if(i%5==0) { System.out.println("bizz"+i); } else continue; } } } class Example24{ public static void main(String [] args){ a obj=new a(); System.out.println("wait a minute"); obj.fizzbizz(); } }
UTF-8
Java
327
java
Example24.java
Java
[]
null
[]
class a{ public void fizzbizz() { for(int i=1;i<=100;i++) { if (i%3==0) { System.out.println("fizz"+i); } else if(i%5==0) { System.out.println("bizz"+i); } else continue; } } } class Example24{ public static void main(String [] args){ a obj=new a(); System.out.println("wait a minute"); obj.fizzbizz(); } }
327
0.59633
0.565749
25
12.12
12.077483
41
false
false
0
0
0
0
0
0
1.16
false
false
2
56f5ca3656f0e3dcc677e93e0c611aac7d478ab4
7,078,106,115,650
fcc3fcd8da44b7d6bd46098df9693d6fb01cef73
/jans-eleven/server/src/main/java/io/jans/eleven/service/AppInitializer.java
9416e87a273b1881dff1a8563646a9e2bec244aa
[ "Apache-2.0" ]
permissive
JanssenProject/jans
https://github.com/JanssenProject/jans
cb633472825787b68ecfba7db97b5b7e5c87e7a5
66c4ef766a62788437cce88974357a9a2b20de21
refs/heads/main
2023-09-01T07:04:48.645000
2023-08-31T10:57:05
2023-08-31T10:57:05
309,721,058
400
68
Apache-2.0
false
2023-09-14T17:42:33
2020-11-03T15:00:37
2023-09-11T18:46:12
2023-09-14T17:42:32
965,627
274
51
398
Java
false
false
/* * Janssen Project software is available under the Apache License (2004). See http://www.apache.org/licenses/ for full text. * * Copyright (c) 2020, Janssen Project */ package io.jans.eleven.service; import org.slf4j.Logger; import io.jans.util.security.SecurityProviderUtility; import jakarta.annotation.PostConstruct; import jakarta.enterprise.context.ApplicationScoped; import jakarta.enterprise.context.Initialized; import jakarta.enterprise.event.Observes; import jakarta.inject.Inject; import jakarta.inject.Named; /** * Initialize application level beans * * @author Yuriy Movchan Date: 06/24/2017 */ @ApplicationScoped @Named public class AppInitializer { @Inject private Logger log; @PostConstruct public void createApplicationComponents() { SecurityProviderUtility.installBCProvider(); } // Don't remove this. It force CDI to create bean at startup public void applicationInitialized(@Observes @Initialized(ApplicationScoped.class) Object init) { log.info("Application initialized"); } }
UTF-8
Java
1,037
java
AppInitializer.java
Java
[ { "context": "* Initialize application level beans\n *\n * @author Yuriy Movchan Date: 06/24/2017\n */\n@ApplicationScoped\n@Named\npu", "end": 600, "score": 0.9998752474784851, "start": 587, "tag": "NAME", "value": "Yuriy Movchan" } ]
null
[]
/* * Janssen Project software is available under the Apache License (2004). See http://www.apache.org/licenses/ for full text. * * Copyright (c) 2020, Janssen Project */ package io.jans.eleven.service; import org.slf4j.Logger; import io.jans.util.security.SecurityProviderUtility; import jakarta.annotation.PostConstruct; import jakarta.enterprise.context.ApplicationScoped; import jakarta.enterprise.context.Initialized; import jakarta.enterprise.event.Observes; import jakarta.inject.Inject; import jakarta.inject.Named; /** * Initialize application level beans * * @author <NAME> Date: 06/24/2017 */ @ApplicationScoped @Named public class AppInitializer { @Inject private Logger log; @PostConstruct public void createApplicationComponents() { SecurityProviderUtility.installBCProvider(); } // Don't remove this. It force CDI to create bean at startup public void applicationInitialized(@Observes @Initialized(ApplicationScoped.class) Object init) { log.info("Application initialized"); } }
1,030
0.774349
0.757956
41
24.292683
27.417498
124
false
false
0
0
0
0
0
0
0.536585
false
false
2
4a8a93e1430769b90fb7f292f12558e9bc2a6521
352,187,334,375
e5aa2370801596c49ba0afca41a32c40d41c4a49
/site/shadyside/logger/Logger.java
dd6e327ca5dc0b38eacabebbd394c3212cccb7ab
[]
no_license
stnevans/BytecodeParser
https://github.com/stnevans/BytecodeParser
c674edbe78c2676279b88b56f4d46c4fefa2d979
a82b161c64132a89507971a6690b12a2a8582468
refs/heads/master
2021-01-13T16:22:23.837000
2017-01-23T02:47:20
2017-01-23T02:47:20
79,751,809
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package site.shadyside.logger; import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; public class Logger { private static Logger logger = new Logger(); PrintWriter outputWriter; protected Logger(){ try { outputWriter = new PrintWriter(new File("bytecodeLog.log")); } catch (FileNotFoundException e) { e.printStackTrace(); } } public void log(String string){ outputWriter.println(string); outputWriter.flush(); System.out.println(string); } public static Logger getLogger(){ return logger; } }
UTF-8
Java
566
java
Logger.java
Java
[]
null
[]
package site.shadyside.logger; import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; public class Logger { private static Logger logger = new Logger(); PrintWriter outputWriter; protected Logger(){ try { outputWriter = new PrintWriter(new File("bytecodeLog.log")); } catch (FileNotFoundException e) { e.printStackTrace(); } } public void log(String string){ outputWriter.println(string); outputWriter.flush(); System.out.println(string); } public static Logger getLogger(){ return logger; } }
566
0.720848
0.720848
30
17.866667
16.404741
63
false
false
0
0
0
0
0
0
1.5
false
false
2
69ec0c28d7204285f511495689766f4d00ad3a39
5,652,176,966,647
cf4fd977f4594d3e7556d7d8b68a6b70b74ad89d
/lib/src/main/java/com/example/lib/MyClass.java
f338e30fa57926ab6b3a926e7c63e772d6fe9ab9
[]
no_license
cryingpotato/java_EX_number-size-array
https://github.com/cryingpotato/java_EX_number-size-array
361fef753331a1467710ee6b6fd41440027d34b7
5ec9f6e3159d7f6b50ecab0f23879a305918037c
refs/heads/master
2020-09-06T10:49:58.757000
2019-11-08T06:42:56
2019-11-08T06:42:56
220,403,653
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.lib; import java.util.Scanner; public class MyClass { public static void main(String[] s) { int x=0; int y=0; int z=0; int t=0; Scanner scanner = new Scanner(System.in); System.out.println("Please input number:"); x= scanner.nextInt(); y= scanner.nextInt(); z= scanner.nextInt(); if(x>y) { t=x; x=y; y=t; } if(x>z) { t=x; x=z; z=t; } if(y>z); { t=y; y=z; z=t; } System.out.println(x+","+y+","+z); } }
UTF-8
Java
695
java
MyClass.java
Java
[]
null
[]
package com.example.lib; import java.util.Scanner; public class MyClass { public static void main(String[] s) { int x=0; int y=0; int z=0; int t=0; Scanner scanner = new Scanner(System.in); System.out.println("Please input number:"); x= scanner.nextInt(); y= scanner.nextInt(); z= scanner.nextInt(); if(x>y) { t=x; x=y; y=t; } if(x>z) { t=x; x=z; z=t; } if(y>z); { t=y; y=z; z=t; } System.out.println(x+","+y+","+z); } }
695
0.381295
0.37554
40
16.375
12.723379
51
false
false
0
0
0
0
0
0
0.6
false
false
2
0b64f113c46485c405a8e7d232003900b8bbb37a
21,157,008,910,117
374af07ab6d61ea5c6b3326aebad06842cf07de8
/src/main/java/com/epam/jsf/util/NewsDAOUtil.java
569ab1e9cd9285753804fefef4279c14934fd958
[]
no_license
NikiTOSS3000/JSFNewsManagment
https://github.com/NikiTOSS3000/JSFNewsManagment
68b11be2c8e71a21034f8ec6ceb35241ac00bcae
d20bb52a348ddc2d649fa391611d1e1fbeef3c85
refs/heads/master
2016-09-05T23:33:28.885000
2013-08-07T12:55:04
2013-08-07T12:55:04
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.epam.jsf.util; import com.epam.jsf.database.INewsDAO; import org.springframework.web.context.ContextLoaderListener; import org.springframework.web.context.WebApplicationContext; public final class NewsDAOUtil { public static INewsDAO getNewsDao() { WebApplicationContext listener = ContextLoaderListener.getCurrentWebApplicationContext(); INewsDAO newsDAO = (INewsDAO) listener.getBean(MessageManager.getStr("other.newsDAO")); return newsDAO; } private NewsDAOUtil(){} }
UTF-8
Java
548
java
NewsDAOUtil.java
Java
[]
null
[]
package com.epam.jsf.util; import com.epam.jsf.database.INewsDAO; import org.springframework.web.context.ContextLoaderListener; import org.springframework.web.context.WebApplicationContext; public final class NewsDAOUtil { public static INewsDAO getNewsDao() { WebApplicationContext listener = ContextLoaderListener.getCurrentWebApplicationContext(); INewsDAO newsDAO = (INewsDAO) listener.getBean(MessageManager.getStr("other.newsDAO")); return newsDAO; } private NewsDAOUtil(){} }
548
0.733577
0.733577
16
32.25
31.065454
97
false
false
0
0
0
0
0
0
0.4375
false
false
2
546be75a198d2c4a64a7e3139e5936419a234359
32,684,701,175,215
b6115f6b74048cbe12b5a49cb82bcbc348860ae6
/libJava/com/earndero/sqlwrapper/java/WritableDatabase.java
22f41f8cf35870a30e5d99a969fe668ae6cd2553
[ "Apache-2.0" ]
permissive
earndero/sqlwrapper
https://github.com/earndero/sqlwrapper
d4373643b9d3b838b91002f04e45dd813cb5175a
1672b0a6f256d43c1498c90bf4933a8d8c8bd28d
refs/heads/main
2023-07-26T16:20:33.343000
2021-09-12T10:58:22
2021-09-12T10:58:22
405,563,403
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.earndero.sqlwrapper.java; import java.io.Closeable; import java.io.IOException; import java.sql.SQLException; public class WritableDatabase extends Database implements Closeable { public WritableDatabase(Context context, String name) throws Exception { super(name); } @Override public void close() throws IOException { } public Table createTable(String name) { return new Table(false, name, this); } boolean TransactionSuccessful = false; public void beginTransaction() throws SQLException { TransactionSuccessful = false; connection.setAutoCommit(false); } public void setTransactionSuccessful() { TransactionSuccessful = true; } public void endTransaction() throws SQLException { if (TransactionSuccessful) connection.commit(); else connection.rollback(); connection.setAutoCommit(true); } public void drop(String name, boolean ifExists) throws SQLException { String stmt = "DROP TABLE "; if (ifExists) stmt+="IF EXISTS "; stmt+=name; java.sql.Statement statement = connection.createStatement(); statement.execute(stmt); } }
UTF-8
Java
1,242
java
WritableDatabase.java
Java
[]
null
[]
package com.earndero.sqlwrapper.java; import java.io.Closeable; import java.io.IOException; import java.sql.SQLException; public class WritableDatabase extends Database implements Closeable { public WritableDatabase(Context context, String name) throws Exception { super(name); } @Override public void close() throws IOException { } public Table createTable(String name) { return new Table(false, name, this); } boolean TransactionSuccessful = false; public void beginTransaction() throws SQLException { TransactionSuccessful = false; connection.setAutoCommit(false); } public void setTransactionSuccessful() { TransactionSuccessful = true; } public void endTransaction() throws SQLException { if (TransactionSuccessful) connection.commit(); else connection.rollback(); connection.setAutoCommit(true); } public void drop(String name, boolean ifExists) throws SQLException { String stmt = "DROP TABLE "; if (ifExists) stmt+="IF EXISTS "; stmt+=name; java.sql.Statement statement = connection.createStatement(); statement.execute(stmt); } }
1,242
0.665861
0.665861
47
25.425531
22.503658
76
false
false
0
0
0
0
0
0
0.468085
false
false
2
f6a4dee516ba85f4c677fe4da3dfe2ebf3725901
4,440,996,251,847
53e1530d418dcda795cd140db4d736a65695f37b
/SpringInAction/src/main/java/sia/springidolqualifiers/qualifiers/Guitar.java
ed0b01856f02ec45ea6ad670bb71773a7dd9a35b
[]
no_license
Zed180881/Zed_repo
https://github.com/Zed180881/Zed_repo
a03bac736e3c61c0bea61b2f81624c4bc604870b
6e9499e7ec3cfa9dc11f9d7a92221522c56b5f61
refs/heads/master
2020-04-05T18:57:47.596000
2016-11-02T07:51:30
2016-11-02T07:51:30
52,864,144
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package sia.springidolqualifiers.qualifiers; import sia.springidolqualifiers.Instrument; @StringedInstrument @Strummed public class Guitar implements Instrument { public void play() { System.out.println("Strum strum strum"); } }
UTF-8
Java
248
java
Guitar.java
Java
[]
null
[]
package sia.springidolqualifiers.qualifiers; import sia.springidolqualifiers.Instrument; @StringedInstrument @Strummed public class Guitar implements Instrument { public void play() { System.out.println("Strum strum strum"); } }
248
0.754032
0.754032
12
19.666666
19.018997
48
false
false
0
0
0
0
0
0
0.25
false
false
2
8e33f0bd2accb01784e46bdd9e1af3fb8d35a1ee
27,633,819,617,914
9647fb64eefac2cb29a6df8e9a44448a5715b3ae
/app/src/main/java/com/example/prikkie/Api/recipe_api/PrikkieApi/PrikkieRandomRecipeAsync.java
0ecef5aa42983a4c7fb8c717e2b5a8d222360e31
[]
no_license
stefangrebenar/Prikkie
https://github.com/stefangrebenar/Prikkie
2d79f95437012481956005c0b28e7e6f649f7d70
3c21806ce0e6403ce26d13c9f3ff3a78b0e7fca7
refs/heads/master
2021-07-02T21:04:32.546000
2020-01-08T20:50:30
2020-01-08T20:50:30
215,262,890
0
0
null
false
2020-01-19T11:42:27
2019-10-15T09:46:00
2020-01-08T20:50:38
2020-01-19T11:42:26
1,236
0
0
1
Java
false
false
package com.example.prikkie.Api.recipe_api.PrikkieApi; import android.os.AsyncTask; import com.example.prikkie.Api.recipe_api.Recipe; import com.example.prikkie.App; import com.example.prikkie.R; import com.example.prikkie.ingredientDB.Ingredient; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; import org.json.JSONArray; import org.json.JSONObject; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class PrikkieRandomRecipeAsync extends AsyncTask<String, Void, ArrayList<Recipe>> { private final String urlQuery = App.getContext().getString(R.string.prikkie_api) + App.getContext().getString(R.string.prikkie_randomRecipes); private ArrayList<Recipe> recipes; public int[] checkedIds; @Override protected ArrayList<Recipe> doInBackground(String... strings) { try{ String entityString = ""; for(int i = 0; i < checkedIds.length; i++){ if(i == 0){ entityString += checkedIds[i]; }else{ entityString += (", " + checkedIds[i]); } } // Preform request HttpPost httppost = new HttpPost(urlQuery); List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); nameValuePairs.add((new BasicNameValuePair("stringdata", entityString))); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpClient httpclient = new DefaultHttpClient(); HttpResponse response = httpclient.execute(httppost); // StatusLine stat = response.getStatusLine(); int status = response.getStatusLine().getStatusCode(); // If response is Ok 200 if(status == 200) { HttpEntity entity = response.getEntity(); String data = EntityUtils.toString(entity); JSONArray recipeArray = new JSONArray(data); int length = recipeArray.length(); if (recipes == null){ recipes = new ArrayList<Recipe>(); } // Read JSON-response // For each recipe in the response, create a representing Recipe object and add it to the recipes-List for(int i = 0; i < length; i++){ JSONObject base = recipeArray.getJSONObject(i); Recipe recipe = new Recipe(); if(base.has("recipe_id")){ recipe.id = base.getInt("recipe_id"); } if(base.has("title")){ recipe.title = base.getString("title"); } if(base.has("description")){ recipe.description = base.getString("description"); } if(base.has("method")){ recipe.method = base.getString("method"); } if(base.has("persons")){ recipe.persons = base.getInt("persons"); } if(base.has("image")){ recipe.imagePath = base.getString("image"); } if(base.has("ingredients")){ JSONArray ingredientArray = base.getJSONArray("ingredients"); int amountOfIngredients = ingredientArray.length(); ArrayList<Ingredient> ingredients = new ArrayList<Ingredient>(); // Add all ingredients for(int j = 0; j < amountOfIngredients; j++){ Ingredient ingredient = new Ingredient(); JSONObject ingredientObject = ingredientArray.getJSONObject(j); if(ingredientObject.has("ingredient_id")){ ingredient.Id = ingredientObject.getInt("ingredient_id"); } if(ingredientObject.has("name")){ ingredient.Dutch = ingredientObject.getString("name"); } if (ingredientObject.has("amount")) { ingredient.amount = ingredientObject.getString("amount"); } if (ingredientObject.has("unit")) { ingredient.unit = ingredientObject.getString("unit"); } if(ingredientObject.has("taxonomy")) { ingredient.Taxonomy = ingredientObject.getString("taxonomy"); } ingredients.add(ingredient); } recipe.ingredients = ingredients; } recipes.add(recipe); Collections.shuffle(recipes); } return recipes; } // no OK response from server } catch(Exception e){ e.printStackTrace(); } return null; } }
UTF-8
Java
5,580
java
PrikkieRandomRecipeAsync.java
Java
[]
null
[]
package com.example.prikkie.Api.recipe_api.PrikkieApi; import android.os.AsyncTask; import com.example.prikkie.Api.recipe_api.Recipe; import com.example.prikkie.App; import com.example.prikkie.R; import com.example.prikkie.ingredientDB.Ingredient; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; import org.json.JSONArray; import org.json.JSONObject; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class PrikkieRandomRecipeAsync extends AsyncTask<String, Void, ArrayList<Recipe>> { private final String urlQuery = App.getContext().getString(R.string.prikkie_api) + App.getContext().getString(R.string.prikkie_randomRecipes); private ArrayList<Recipe> recipes; public int[] checkedIds; @Override protected ArrayList<Recipe> doInBackground(String... strings) { try{ String entityString = ""; for(int i = 0; i < checkedIds.length; i++){ if(i == 0){ entityString += checkedIds[i]; }else{ entityString += (", " + checkedIds[i]); } } // Preform request HttpPost httppost = new HttpPost(urlQuery); List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); nameValuePairs.add((new BasicNameValuePair("stringdata", entityString))); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpClient httpclient = new DefaultHttpClient(); HttpResponse response = httpclient.execute(httppost); // StatusLine stat = response.getStatusLine(); int status = response.getStatusLine().getStatusCode(); // If response is Ok 200 if(status == 200) { HttpEntity entity = response.getEntity(); String data = EntityUtils.toString(entity); JSONArray recipeArray = new JSONArray(data); int length = recipeArray.length(); if (recipes == null){ recipes = new ArrayList<Recipe>(); } // Read JSON-response // For each recipe in the response, create a representing Recipe object and add it to the recipes-List for(int i = 0; i < length; i++){ JSONObject base = recipeArray.getJSONObject(i); Recipe recipe = new Recipe(); if(base.has("recipe_id")){ recipe.id = base.getInt("recipe_id"); } if(base.has("title")){ recipe.title = base.getString("title"); } if(base.has("description")){ recipe.description = base.getString("description"); } if(base.has("method")){ recipe.method = base.getString("method"); } if(base.has("persons")){ recipe.persons = base.getInt("persons"); } if(base.has("image")){ recipe.imagePath = base.getString("image"); } if(base.has("ingredients")){ JSONArray ingredientArray = base.getJSONArray("ingredients"); int amountOfIngredients = ingredientArray.length(); ArrayList<Ingredient> ingredients = new ArrayList<Ingredient>(); // Add all ingredients for(int j = 0; j < amountOfIngredients; j++){ Ingredient ingredient = new Ingredient(); JSONObject ingredientObject = ingredientArray.getJSONObject(j); if(ingredientObject.has("ingredient_id")){ ingredient.Id = ingredientObject.getInt("ingredient_id"); } if(ingredientObject.has("name")){ ingredient.Dutch = ingredientObject.getString("name"); } if (ingredientObject.has("amount")) { ingredient.amount = ingredientObject.getString("amount"); } if (ingredientObject.has("unit")) { ingredient.unit = ingredientObject.getString("unit"); } if(ingredientObject.has("taxonomy")) { ingredient.Taxonomy = ingredientObject.getString("taxonomy"); } ingredients.add(ingredient); } recipe.ingredients = ingredients; } recipes.add(recipe); Collections.shuffle(recipes); } return recipes; } // no OK response from server } catch(Exception e){ e.printStackTrace(); } return null; } }
5,580
0.525806
0.523835
130
41.923077
28.529772
146
false
false
0
0
0
0
0
0
0.576923
false
false
2
ec01d25f8fd0abb9feb2dad3bc0f7fd9d96c18e4
8,229,157,380,229
3b340c90919a6dc7f068ea852f9fe1fac0600139
/src/main/java/com/qf/service/impl/ProductInfoServiceImpl.java
05f9c22f7f6e8f56b43acbcbbcf5397695f9ec85
[]
no_license
muziLee226/brandShop_new
https://github.com/muziLee226/brandShop_new
1ca0c2629bbebab5c3038d475bde102226ec0db1
9790f9d1f28c30cd9ae8924c662e3b7c34abfad4
refs/heads/master
2022-11-27T18:23:29.719000
2020-07-25T01:09:40
2020-07-25T01:09:40
281,687,331
0
0
null
true
2020-07-22T13:37:19
2020-07-22T13:37:18
2020-07-22T02:24:29
2020-07-22T13:30:49
63
0
0
0
null
false
false
package com.qf.service.impl; import com.alibaba.fastjson.JSON; import com.qf.config.RedisKeyConfig; import com.qf.dao.ProductInfoDao; import com.qf.pojo.ProductInfo; import com.qf.service.ProductInfoService; import com.qf.util.JedisCore; import com.qf.util.TokenUtil; import com.qf.vo.R; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service public class ProductInfoServiceImpl implements ProductInfoService { @Autowired private ProductInfoDao productInfoDao; @Autowired private JedisCore jedisCore; @Override public R findAllGoods() { List<ProductInfo> allGoods = productInfoDao.findAllGoods(); return R.ok(allGoods); } @Override public R findByProductLike(String findCondition) { List<ProductInfo> byProductLike = productInfoDao.findByProductLike(findCondition); String token = TokenUtil.createProductToken(123456); jedisCore.set(RedisKeyConfig.TOKEN_USER+token, JSON.toJSONString(byProductLike),RedisKeyConfig.TOKEN_TIME); // return R.ok(token); return R.ok(byProductLike); } @Override public R findGoodById(Integer productId) { ProductInfo goodById = productInfoDao.findGoodById(productId); String token = TokenUtil.createProductToken(productId); //存储商品信息到redis jedisCore.set(RedisKeyConfig.TOKEN_USER+token, JSON.toJSONString(goodById),RedisKeyConfig.TOKEN_TIME); // return R.ok(token); return R.ok(goodById); } @Override public R findByHot() { List<ProductInfo> byHot = productInfoDao.findByHot(); return R.ok(byHot); } @Override public R findByLowerOfMonth() { List<ProductInfo> byLowerOfMonth = productInfoDao.findByLowerOfMonth(); return R.ok(byLowerOfMonth); } @Override public R findByFactoryAddressId(Integer factoryAddressId) { List<ProductInfo> byFactoryAddressId = productInfoDao.findByFactoryAddressId(factoryAddressId); return R.ok(byFactoryAddressId); } @Override public R findByGoodsType(Integer goodsTypeId) { List<ProductInfo> byGoodsType = productInfoDao.findByGoodsType(goodsTypeId); return R.ok(byGoodsType); } }
UTF-8
Java
2,326
java
ProductInfoServiceImpl.java
Java
[]
null
[]
package com.qf.service.impl; import com.alibaba.fastjson.JSON; import com.qf.config.RedisKeyConfig; import com.qf.dao.ProductInfoDao; import com.qf.pojo.ProductInfo; import com.qf.service.ProductInfoService; import com.qf.util.JedisCore; import com.qf.util.TokenUtil; import com.qf.vo.R; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service public class ProductInfoServiceImpl implements ProductInfoService { @Autowired private ProductInfoDao productInfoDao; @Autowired private JedisCore jedisCore; @Override public R findAllGoods() { List<ProductInfo> allGoods = productInfoDao.findAllGoods(); return R.ok(allGoods); } @Override public R findByProductLike(String findCondition) { List<ProductInfo> byProductLike = productInfoDao.findByProductLike(findCondition); String token = TokenUtil.createProductToken(123456); jedisCore.set(RedisKeyConfig.TOKEN_USER+token, JSON.toJSONString(byProductLike),RedisKeyConfig.TOKEN_TIME); // return R.ok(token); return R.ok(byProductLike); } @Override public R findGoodById(Integer productId) { ProductInfo goodById = productInfoDao.findGoodById(productId); String token = TokenUtil.createProductToken(productId); //存储商品信息到redis jedisCore.set(RedisKeyConfig.TOKEN_USER+token, JSON.toJSONString(goodById),RedisKeyConfig.TOKEN_TIME); // return R.ok(token); return R.ok(goodById); } @Override public R findByHot() { List<ProductInfo> byHot = productInfoDao.findByHot(); return R.ok(byHot); } @Override public R findByLowerOfMonth() { List<ProductInfo> byLowerOfMonth = productInfoDao.findByLowerOfMonth(); return R.ok(byLowerOfMonth); } @Override public R findByFactoryAddressId(Integer factoryAddressId) { List<ProductInfo> byFactoryAddressId = productInfoDao.findByFactoryAddressId(factoryAddressId); return R.ok(byFactoryAddressId); } @Override public R findByGoodsType(Integer goodsTypeId) { List<ProductInfo> byGoodsType = productInfoDao.findByGoodsType(goodsTypeId); return R.ok(byGoodsType); } }
2,326
0.717993
0.715398
82
27.195122
28.390327
115
false
false
0
0
0
0
0
0
0.463415
false
false
2
46d2f3cc574709dcd3811c87a777d0ef8227ef12
11,656,541,308,287
7cd616e71c3c93608f65a871cc655f2b7add36bc
/app/src/main/java/virus/endtheboss/Serveur/JoueurServeur.java
02c3b06695560929c12658ccafdeea603153a2eb
[]
no_license
GeneralQuarter/EndTheBoss
https://github.com/GeneralQuarter/EndTheBoss
51bd85f01d05a361ecfc39cbe0761174101f411c
b0b1363e0d044dbd81e7743f07e69bd491ffb8d2
refs/heads/master
2021-05-31T21:50:53.843000
2016-03-17T19:15:56
2016-03-17T19:15:56
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package virus.endtheboss.Serveur; import java.io.ObjectOutputStream; import virus.endtheboss.Client.Joueur; /** * Created by Quentin Gangler on 19/02/2016. * Object qui représente un joueur coté serveur */ public class JoueurServeur { private ObjectOutputStream output; private Joueur joueur; public JoueurServeur(Joueur joueur, int id, ObjectOutputStream output) { this.joueur = joueur; this.joueur.setId(id); this.output = output; } public ObjectOutputStream getOutput() { return output; } public Joueur getJoueur() { return joueur; } public void setJoueur(Joueur joueur) { this.joueur = joueur; } }
UTF-8
Java
703
java
JoueurServeur.java
Java
[ { "context": "virus.endtheboss.Client.Joueur;\n\n/**\n * Created by Quentin Gangler on 19/02/2016.\n * Object qui représente un joueur", "end": 144, "score": 0.9998645782470703, "start": 129, "tag": "NAME", "value": "Quentin Gangler" } ]
null
[]
package virus.endtheboss.Serveur; import java.io.ObjectOutputStream; import virus.endtheboss.Client.Joueur; /** * Created by <NAME> on 19/02/2016. * Object qui représente un joueur coté serveur */ public class JoueurServeur { private ObjectOutputStream output; private Joueur joueur; public JoueurServeur(Joueur joueur, int id, ObjectOutputStream output) { this.joueur = joueur; this.joueur.setId(id); this.output = output; } public ObjectOutputStream getOutput() { return output; } public Joueur getJoueur() { return joueur; } public void setJoueur(Joueur joueur) { this.joueur = joueur; } }
694
0.671897
0.660485
33
20.242424
19.129591
76
false
false
0
0
0
0
0
0
0.393939
false
false
2
b5bc6b9903027a549b752d0d318ac682607e40ba
17,849,884,151,732
2bf5de605bc045af0368e56a3991d87426ef1e9c
/src/drawables/Drawable.java
ae9fe85d041b5e3c7c610e4debabb40c0af5f53f
[]
no_license
A-Hussien96/MazeGame
https://github.com/A-Hussien96/MazeGame
698f140f1d6b5eb07a7fd9f05ccdf4db0a00a344
022026b084ef95dfc680ed1de691d31de0e31c75
refs/heads/master
2021-09-13T14:04:11.351000
2018-05-01T00:04:16
2018-05-01T00:04:16
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package drawables; import drawables_observers.ImageChangeObserver; import drawables_observers.PositionChangeObserver; import java.awt.*; import java.util.Observable; /** * Created by Bassam on 12/7/2017. */ public abstract class Drawable extends Observable { public static final String KEY_IMAGE_DIRECTORY = "image-directory"; public static final String KEY_CENTER_POINT = "center-point"; public static final String KEY_START_POINT = "start-point"; public static final String KEY_END_POINT = "end-point"; protected final static String ASSETS_MAIN_DIRECTORY = "\\src\\assets\\"; private Point centerPoint; private Point startPoint; private Point endPoint; private String imageDirectory; protected Drawable() { addObserver(new ImageChangeObserver()); addObserver(new PositionChangeObserver()); } public static String getAssetsMainDirectory() { return ASSETS_MAIN_DIRECTORY; } public Point getCenterPoint() { return centerPoint; } public void setCenterPoint(Point centerPoint) { this.centerPoint = centerPoint; notifyObserversWithKey(KEY_CENTER_POINT); } public Point getStartPoint() { return startPoint; } public void setStartPoint(Point startPoint) { this.startPoint = startPoint; notifyObserversWithKey(KEY_START_POINT); } public Point getEndPoint() { return endPoint; } public void setEndPoint(Point endPoint) { this.endPoint = endPoint; notifyObserversWithKey(KEY_END_POINT); } public String getImageDirectory() { return imageDirectory; } public void setImageDirectory(String imageDirectory) { this.imageDirectory = imageDirectory; notifyObserversWithKey(KEY_IMAGE_DIRECTORY); } protected void notifyObserversWithKey(String key) { setChanged(); notifyObservers(key); } }
UTF-8
Java
1,953
java
Drawable.java
Java
[ { "context": "*;\nimport java.util.Observable;\n\n/**\n * Created by Bassam on 12/7/2017.\n */\npublic abstract class Drawable ", "end": 193, "score": 0.9731406569480896, "start": 187, "tag": "USERNAME", "value": "Bassam" } ]
null
[]
package drawables; import drawables_observers.ImageChangeObserver; import drawables_observers.PositionChangeObserver; import java.awt.*; import java.util.Observable; /** * Created by Bassam on 12/7/2017. */ public abstract class Drawable extends Observable { public static final String KEY_IMAGE_DIRECTORY = "image-directory"; public static final String KEY_CENTER_POINT = "center-point"; public static final String KEY_START_POINT = "start-point"; public static final String KEY_END_POINT = "end-point"; protected final static String ASSETS_MAIN_DIRECTORY = "\\src\\assets\\"; private Point centerPoint; private Point startPoint; private Point endPoint; private String imageDirectory; protected Drawable() { addObserver(new ImageChangeObserver()); addObserver(new PositionChangeObserver()); } public static String getAssetsMainDirectory() { return ASSETS_MAIN_DIRECTORY; } public Point getCenterPoint() { return centerPoint; } public void setCenterPoint(Point centerPoint) { this.centerPoint = centerPoint; notifyObserversWithKey(KEY_CENTER_POINT); } public Point getStartPoint() { return startPoint; } public void setStartPoint(Point startPoint) { this.startPoint = startPoint; notifyObserversWithKey(KEY_START_POINT); } public Point getEndPoint() { return endPoint; } public void setEndPoint(Point endPoint) { this.endPoint = endPoint; notifyObserversWithKey(KEY_END_POINT); } public String getImageDirectory() { return imageDirectory; } public void setImageDirectory(String imageDirectory) { this.imageDirectory = imageDirectory; notifyObserversWithKey(KEY_IMAGE_DIRECTORY); } protected void notifyObserversWithKey(String key) { setChanged(); notifyObservers(key); } }
1,953
0.686124
0.68254
76
24.697369
22.16625
76
false
false
0
0
0
0
0
0
0.407895
false
false
2
6b6a38e153d9b5f1016bf131ff84d6b0cb53c9d6
29,386,166,266,238
087b557a9fdb68a47e24a121d9aa3950bfb31f74
/src/com/masqueprogramar/recursividad/TribonacciRecursivo.java
29e55ed4e4e4c64156f962edc47b208542bcd8b8
[]
no_license
LorneyZizzart/JavaBasico
https://github.com/LorneyZizzart/JavaBasico
71b04162b13ddee07a121deb9c7fae958dba8836
7a9ab3c38c58b703ed7cc4d909164bbc690a76b3
refs/heads/master
2020-06-22T06:16:12.568000
2019-02-07T10:26:47
2019-02-07T10:26:47
197,655,265
1
0
null
true
2019-07-18T20:52:57
2019-07-18T20:52:55
2019-07-18T20:52:20
2019-02-07T10:27:14
84
0
0
0
null
false
false
package com.masqueprogramar.recursividad; import javax.swing.JOptionPane; import javax.swing.JTextArea; /** * @author masqueprogramar (https://masqueprogramar.wordpress.com) * @date 10-enero-2019 * @description Programa que muestra los N primeros números de la serie de Tribonacci de forma recursiva * @version 1.0 * @url https://masqueprogramar.wordpress.com/2019/01/10/serie-tribonacci-de-forma-recursiva/ */ public class TribonacciRecursivo { public static void main(String[] args) { String strLimite = JOptionPane.showInputDialog(null, "Introduce el número de elementos a mostrar", "Serie de Tribonacci", JOptionPane.QUESTION_MESSAGE); int limite = Integer.parseInt(strLimite); JTextArea textArea = new JTextArea(""); for(int ind=1; ind<=limite; ind++){ textArea.append(funcionTribonacci(ind) + "\t"); if(ind%4==0){ textArea.append("\n"); } } JOptionPane.showMessageDialog(null, textArea, "Serie de Tribonacci", JOptionPane.INFORMATION_MESSAGE); } private static int funcionTribonacci(int num){ if(num == 0 || num == 1 || num == 2){ return 0; } if (num == 3) { return 1; } else { return funcionTribonacci(num-1) + funcionTribonacci(num-2) + funcionTribonacci(num-3); } } }
UTF-8
Java
1,438
java
TribonacciRecursivo.java
Java
[ { "context": "ane;\nimport javax.swing.JTextArea;\n\n/**\n * @author masqueprogramar (https://masqueprogramar.wordpress.com)\n * @date ", "end": 136, "score": 0.9995152950286865, "start": 121, "tag": "USERNAME", "value": "masqueprogramar" } ]
null
[]
package com.masqueprogramar.recursividad; import javax.swing.JOptionPane; import javax.swing.JTextArea; /** * @author masqueprogramar (https://masqueprogramar.wordpress.com) * @date 10-enero-2019 * @description Programa que muestra los N primeros números de la serie de Tribonacci de forma recursiva * @version 1.0 * @url https://masqueprogramar.wordpress.com/2019/01/10/serie-tribonacci-de-forma-recursiva/ */ public class TribonacciRecursivo { public static void main(String[] args) { String strLimite = JOptionPane.showInputDialog(null, "Introduce el número de elementos a mostrar", "Serie de Tribonacci", JOptionPane.QUESTION_MESSAGE); int limite = Integer.parseInt(strLimite); JTextArea textArea = new JTextArea(""); for(int ind=1; ind<=limite; ind++){ textArea.append(funcionTribonacci(ind) + "\t"); if(ind%4==0){ textArea.append("\n"); } } JOptionPane.showMessageDialog(null, textArea, "Serie de Tribonacci", JOptionPane.INFORMATION_MESSAGE); } private static int funcionTribonacci(int num){ if(num == 0 || num == 1 || num == 2){ return 0; } if (num == 3) { return 1; } else { return funcionTribonacci(num-1) + funcionTribonacci(num-2) + funcionTribonacci(num-3); } } }
1,438
0.614206
0.594708
49
28.306122
26.163694
106
false
false
0
0
0
0
0
0
1.081633
false
false
2
243bca2bac4a986b618d21241c7dde6096ed588e
7,550,552,511,466
7d704e5016f3db68508522b55055483a16e7bb1a
/selfoptsys/src/selfoptsys/sched/AMetaSchedulerFactorySelector.java
4eb91e571c4d518175cb29393b8d78a1c553c33b
[]
no_license
pdewan/SelfOptSys
https://github.com/pdewan/SelfOptSys
866934cb45d810c831ab00ecc456ddcf5ae40ec2
6e0ea5462223ea66a6c30584e4d88f208fea7393
refs/heads/master
2020-04-27T04:47:17.687000
2014-05-06T14:42:37
2014-05-06T14:42:37
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package selfoptsys.sched; public class AMetaSchedulerFactorySelector { private static MetaSchedulerFactory m_factory = new ADefaultMetaSchedulerFactory(); public static void setFactory( MetaSchedulerFactory factory ) { m_factory = factory; } public static MetaSchedulerFactory getFactory() { return m_factory; } }
UTF-8
Java
337
java
AMetaSchedulerFactorySelector.java
Java
[]
null
[]
package selfoptsys.sched; public class AMetaSchedulerFactorySelector { private static MetaSchedulerFactory m_factory = new ADefaultMetaSchedulerFactory(); public static void setFactory( MetaSchedulerFactory factory ) { m_factory = factory; } public static MetaSchedulerFactory getFactory() { return m_factory; } }
337
0.765579
0.765579
17
18.82353
22.891651
84
false
false
0
0
0
0
0
0
1.294118
false
false
2
3be36983096cc2b88a336591429596d789cf44ff
28,613,072,145,968
849b5025a690042b23378ddde56795ebb820db1c
/src/com/cocos/mfcn/cralwer/MyFreeCamsProfile.java
29c41e0636f5cfbd41dd6a609b0c009c164b50ed
[]
no_license
w21fanfan1314/MyFreeCamsNotification
https://github.com/w21fanfan1314/MyFreeCamsNotification
ef9666d177379a27f178a77cc22be429b9a38320
77c1b3a96f56285892b08be6137b1f6cd1a7898c
refs/heads/master
2020-09-17T08:14:17.451000
2017-06-16T01:48:57
2017-06-16T01:48:57
94,493,259
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.cocos.mfcn.cralwer; import com.cocos.mfcn.cralwer.modals.GrilPageInfo; import com.cocos.mfcn.models.Gril; public interface MyFreeCamsProfile { String PROFILE_URL = "https://profiles.myfreecams.com/"; /** * 读取用户信息 * @param userName * @return */ GrilPageInfo read(String userName); }
UTF-8
Java
340
java
MyFreeCamsProfile.java
Java
[]
null
[]
package com.cocos.mfcn.cralwer; import com.cocos.mfcn.cralwer.modals.GrilPageInfo; import com.cocos.mfcn.models.Gril; public interface MyFreeCamsProfile { String PROFILE_URL = "https://profiles.myfreecams.com/"; /** * 读取用户信息 * @param userName * @return */ GrilPageInfo read(String userName); }
340
0.689024
0.689024
14
22.428572
18.783405
60
false
false
0
0
0
0
0
0
0.357143
false
false
2
1e4a066bc2fc1d54a38da1a35227495760c22b7b
33,861,522,164,402
d57116406b84856639e5a78b0cbd7fcfb7dca8c2
/boot/src/main/java/com/mochenxi/model/UserInfoDO.java
403c0fa7b27135307e960fdca9bf26048ee1086c
[]
no_license
mochenxi/testExample
https://github.com/mochenxi/testExample
4cf946cda59cc88656e83dd48949c850071b00eb
a1a171f28109b7bad0c0e8e622f76b4aa444c855
refs/heads/master
2018-12-06T05:12:32.319000
2018-11-22T14:47:24
2018-11-22T14:47:24
140,994,036
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.mochenxi.model; import lombok.Data; /** * @Description: * @author: mochenxi * @create: 2018/09/12 */ @Data public class UserInfoDO extends BaseObject<UserInfoDO> { /** * 名称 */ private String name; /** * 证件号码 */ private String idCard; /** * 手机号 */ private String mobilePhone; /** * 性别 */ private Integer userSex; /** * 年龄 */ private Integer userAge; /** * 国际 */ private String international; /** * 额外信息 */ private String extra; }
UTF-8
Java
619
java
UserInfoDO.java
Java
[ { "context": "ort lombok.Data;\n\n/**\n * @Description:\n * @author: mochenxi\n * @create: 2018/09/12\n */\n@Data\npublic class Use", "end": 92, "score": 0.99966961145401, "start": 84, "tag": "USERNAME", "value": "mochenxi" } ]
null
[]
package com.mochenxi.model; import lombok.Data; /** * @Description: * @author: mochenxi * @create: 2018/09/12 */ @Data public class UserInfoDO extends BaseObject<UserInfoDO> { /** * 名称 */ private String name; /** * 证件号码 */ private String idCard; /** * 手机号 */ private String mobilePhone; /** * 性别 */ private Integer userSex; /** * 年龄 */ private Integer userAge; /** * 国际 */ private String international; /** * 额外信息 */ private String extra; }
619
0.507745
0.493976
48
11.104167
11.491373
56
false
false
0
0
0
0
0
0
0.1875
false
false
2
2fbd8d44a4a080a479e32ce45ee2443e4f480a4d
4,973,572,160,614
9aec6d19a52c4c09f054399a8d758fbb8dbc922f
/src/main/java/ru/fds/tavrzcms3/converter/dtoconverter/impl/PledgeAgreementConverterDto.java
5e57a3a6d665f187dfd25807cc1886c278932db4
[]
no_license
Dmitriy1Fokin/tavrzcms3
https://github.com/Dmitriy1Fokin/tavrzcms3
b651d6e6d59e256287bc16a3db66298335206719
deb11171670f83c801fe99b2d0f7676e43e82d18
refs/heads/master
2020-06-04T08:54:42.463000
2020-01-13T11:22:00
2020-01-13T11:22:00
191,951,478
2
0
null
false
2019-12-23T13:33:09
2019-06-14T13:52:50
2019-12-23T13:07:43
2019-12-23T13:33:09
791
1
0
0
Java
false
false
package ru.fds.tavrzcms3.converter.dtoconverter.impl; import org.springframework.stereotype.Component; import ru.fds.tavrzcms3.converter.dtoconverter.ConverterDto; import ru.fds.tavrzcms3.domain.LoanAgreement; import ru.fds.tavrzcms3.domain.PledgeAgreement; import ru.fds.tavrzcms3.domain.PledgeSubject; import ru.fds.tavrzcms3.dto.PledgeAgreementDto; import ru.fds.tavrzcms3.service.ClientService; import ru.fds.tavrzcms3.service.LoanAgreementService; import ru.fds.tavrzcms3.service.PledgeAgreementService; import ru.fds.tavrzcms3.service.PledgeSubjectService; import java.time.LocalDate; import java.util.ArrayList; import java.util.Collections; import java.util.List; @Component public class PledgeAgreementConverterDto implements ConverterDto<PledgeAgreement, PledgeAgreementDto> { private final ClientService clientService; private final LoanAgreementService loanAgreementService; private final PledgeSubjectService pledgeSubjectService; private final PledgeAgreementService pledgeAgreementService; public PledgeAgreementConverterDto(ClientService clientService, LoanAgreementService loanAgreementService, PledgeSubjectService pledgeSubjectService, PledgeAgreementService pledgeAgreementService) { this.clientService = clientService; this.loanAgreementService = loanAgreementService; this.pledgeSubjectService = pledgeSubjectService; this.pledgeAgreementService = pledgeAgreementService; } @Override public PledgeAgreement toEntity(PledgeAgreementDto dto) { List<LoanAgreement> loanAgreementList; if(dto.getLoanAgreementsIds() != null) loanAgreementList = loanAgreementService.getLoanAgreementsByIds(dto.getLoanAgreementsIds()); else loanAgreementList = Collections.emptyList(); List<PledgeSubject> pledgeSubjectList; if(dto.getPledgeSubjectsIds() != null) pledgeSubjectList = pledgeSubjectService.getPledgeSubjectByIds(dto.getPledgeSubjectsIds()); else pledgeSubjectList = Collections.emptyList(); return PledgeAgreement.builder() .pledgeAgreementId(dto.getPledgeAgreementId()) .numPA(dto.getNumPA()) .dateBeginPA(dto.getDateBeginPA()) .dateEndPA(dto.getDateEndPA()) .pervPosl(dto.getPervPosl()) .statusPA(dto.getStatusPA()) .noticePA(dto.getNoticePA()) .zsDz(dto.getZsDz()) .zsZz(dto.getZsZz()) .rsDz(dto.getRsDz()) .rsZz(dto.getRsZz()) .ss(dto.getSs()) .loanAgreements(loanAgreementList) .client(clientService.getClientById(dto.getClientId()).orElse(null)) .pledgeSubjects(pledgeSubjectList) .build(); } @Override public PledgeAgreementDto toDto(PledgeAgreement entity) { List<Long> loanAgreementDtoList = new ArrayList<>(); for(LoanAgreement la : loanAgreementService.getAllLoanAgreementByPledgeAgreement(entity)) loanAgreementDtoList.add(la.getLoanAgreementId()); List<Long> pledgeSubjectDtoList = new ArrayList<>(); List<PledgeSubject> pledgeSubjectList = pledgeSubjectService.getPledgeSubjectByPledgeAgreement(entity); for (PledgeSubject ps : pledgeSubjectList) pledgeSubjectDtoList.add(ps.getPledgeSubjectId()); List<String> briefInfoAboutCollateral = new ArrayList<>(); for(int i = 0; i < pledgeSubjectList.size() && i <= 5; i++){ briefInfoAboutCollateral.add(pledgeSubjectList.get(i).getName()); } List<String> typesOfCollateral = pledgeAgreementService.getTypeOfCollateral(entity); List<LocalDate> datesOfConclusions = pledgeAgreementService.getDatesOfConclusion(entity); List<LocalDate> datesOfMonitoring = pledgeAgreementService.getDatesOfMonitoring(entity); List<String> resultsOfMonitoring = pledgeAgreementService.getResultsOfMonitoring(entity); return PledgeAgreementDto.builder() .pledgeAgreementId(entity.getPledgeAgreementId()) .numPA(entity.getNumPA()) .dateBeginPA(entity.getDateBeginPA()) .dateEndPA(entity.getDateEndPA()) .pervPosl(entity.getPervPosl()) .statusPA(entity.getStatusPA()) .noticePA(entity.getNoticePA()) .zsDz(entity.getZsDz()) .zsZz(entity.getZsZz()) .rsDz(entity.getRsDz()) .rsZz(entity.getRsZz()) .ss(entity.getSs()) .loanAgreementsIds(loanAgreementDtoList) .clientId(entity.getClient().getClientId()) .pledgeSubjectsIds(pledgeSubjectDtoList) .briefInfoAboutCollateral(briefInfoAboutCollateral) .typesOfCollateral(typesOfCollateral) .datesOfConclusions(datesOfConclusions) .datesOfMonitoring(datesOfMonitoring) .resultsOfMonitoring(resultsOfMonitoring) .clientName(clientService.getFullNameClient(entity.getClient().getClientId())) .build(); } }
UTF-8
Java
5,358
java
PledgeAgreementConverterDto.java
Java
[]
null
[]
package ru.fds.tavrzcms3.converter.dtoconverter.impl; import org.springframework.stereotype.Component; import ru.fds.tavrzcms3.converter.dtoconverter.ConverterDto; import ru.fds.tavrzcms3.domain.LoanAgreement; import ru.fds.tavrzcms3.domain.PledgeAgreement; import ru.fds.tavrzcms3.domain.PledgeSubject; import ru.fds.tavrzcms3.dto.PledgeAgreementDto; import ru.fds.tavrzcms3.service.ClientService; import ru.fds.tavrzcms3.service.LoanAgreementService; import ru.fds.tavrzcms3.service.PledgeAgreementService; import ru.fds.tavrzcms3.service.PledgeSubjectService; import java.time.LocalDate; import java.util.ArrayList; import java.util.Collections; import java.util.List; @Component public class PledgeAgreementConverterDto implements ConverterDto<PledgeAgreement, PledgeAgreementDto> { private final ClientService clientService; private final LoanAgreementService loanAgreementService; private final PledgeSubjectService pledgeSubjectService; private final PledgeAgreementService pledgeAgreementService; public PledgeAgreementConverterDto(ClientService clientService, LoanAgreementService loanAgreementService, PledgeSubjectService pledgeSubjectService, PledgeAgreementService pledgeAgreementService) { this.clientService = clientService; this.loanAgreementService = loanAgreementService; this.pledgeSubjectService = pledgeSubjectService; this.pledgeAgreementService = pledgeAgreementService; } @Override public PledgeAgreement toEntity(PledgeAgreementDto dto) { List<LoanAgreement> loanAgreementList; if(dto.getLoanAgreementsIds() != null) loanAgreementList = loanAgreementService.getLoanAgreementsByIds(dto.getLoanAgreementsIds()); else loanAgreementList = Collections.emptyList(); List<PledgeSubject> pledgeSubjectList; if(dto.getPledgeSubjectsIds() != null) pledgeSubjectList = pledgeSubjectService.getPledgeSubjectByIds(dto.getPledgeSubjectsIds()); else pledgeSubjectList = Collections.emptyList(); return PledgeAgreement.builder() .pledgeAgreementId(dto.getPledgeAgreementId()) .numPA(dto.getNumPA()) .dateBeginPA(dto.getDateBeginPA()) .dateEndPA(dto.getDateEndPA()) .pervPosl(dto.getPervPosl()) .statusPA(dto.getStatusPA()) .noticePA(dto.getNoticePA()) .zsDz(dto.getZsDz()) .zsZz(dto.getZsZz()) .rsDz(dto.getRsDz()) .rsZz(dto.getRsZz()) .ss(dto.getSs()) .loanAgreements(loanAgreementList) .client(clientService.getClientById(dto.getClientId()).orElse(null)) .pledgeSubjects(pledgeSubjectList) .build(); } @Override public PledgeAgreementDto toDto(PledgeAgreement entity) { List<Long> loanAgreementDtoList = new ArrayList<>(); for(LoanAgreement la : loanAgreementService.getAllLoanAgreementByPledgeAgreement(entity)) loanAgreementDtoList.add(la.getLoanAgreementId()); List<Long> pledgeSubjectDtoList = new ArrayList<>(); List<PledgeSubject> pledgeSubjectList = pledgeSubjectService.getPledgeSubjectByPledgeAgreement(entity); for (PledgeSubject ps : pledgeSubjectList) pledgeSubjectDtoList.add(ps.getPledgeSubjectId()); List<String> briefInfoAboutCollateral = new ArrayList<>(); for(int i = 0; i < pledgeSubjectList.size() && i <= 5; i++){ briefInfoAboutCollateral.add(pledgeSubjectList.get(i).getName()); } List<String> typesOfCollateral = pledgeAgreementService.getTypeOfCollateral(entity); List<LocalDate> datesOfConclusions = pledgeAgreementService.getDatesOfConclusion(entity); List<LocalDate> datesOfMonitoring = pledgeAgreementService.getDatesOfMonitoring(entity); List<String> resultsOfMonitoring = pledgeAgreementService.getResultsOfMonitoring(entity); return PledgeAgreementDto.builder() .pledgeAgreementId(entity.getPledgeAgreementId()) .numPA(entity.getNumPA()) .dateBeginPA(entity.getDateBeginPA()) .dateEndPA(entity.getDateEndPA()) .pervPosl(entity.getPervPosl()) .statusPA(entity.getStatusPA()) .noticePA(entity.getNoticePA()) .zsDz(entity.getZsDz()) .zsZz(entity.getZsZz()) .rsDz(entity.getRsDz()) .rsZz(entity.getRsZz()) .ss(entity.getSs()) .loanAgreementsIds(loanAgreementDtoList) .clientId(entity.getClient().getClientId()) .pledgeSubjectsIds(pledgeSubjectDtoList) .briefInfoAboutCollateral(briefInfoAboutCollateral) .typesOfCollateral(typesOfCollateral) .datesOfConclusions(datesOfConclusions) .datesOfMonitoring(datesOfMonitoring) .resultsOfMonitoring(resultsOfMonitoring) .clientName(clientService.getFullNameClient(entity.getClient().getClientId())) .build(); } }
5,358
0.670959
0.66872
118
44.40678
28.075031
111
false
false
0
0
0
0
0
0
0.40678
false
false
2
4a5edc123fcb72b2eeb62660e652abf243b6a2b3
5,574,867,598,163
106a4e3515c3fe546444d32ae711de71a7544016
/app/src/main/java/com/system/donate/activity_registration.java
1deb3ecf562e403b5f4cadb182aef6a27de3b264
[]
no_license
rajaaqib449/donatingsystemkashif
https://github.com/rajaaqib449/donatingsystemkashif
818aa61445ce5ac430e9291cc24bbece33547587
ec473c34397c0b4ac9b5885184f53a3dc7b8b51c
refs/heads/master
2023-05-13T02:35:04.036000
2021-06-09T18:17:57
2021-06-09T18:17:57
375,451,163
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.system.donate; import android.app.ProgressDialog; import android.content.Intent; import android.os.Bundle; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.android.material.snackbar.Snackbar; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import android.provider.Settings; import android.text.TextUtils; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import androidx.navigation.NavController; import androidx.navigation.Navigation; import androidx.navigation.ui.AppBarConfiguration; import androidx.navigation.ui.NavigationUI; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import com.system.donate.databinding.ActivityRegistrationBinding; import com.system.donate.model.User; import java.util.HashMap; public class activity_registration extends AppCompatActivity { Button registration; EditText inputFullName, inputEmail, inputPassword, inputConformPassword; private ProgressDialog loadingBar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_registration); registration = (Button) findViewById(R.id.btnRegister); inputFullName = (EditText) findViewById(R.id.inputUsername); inputEmail = (EditText) findViewById(R.id.inputEmail); inputPassword = (EditText) findViewById(R.id.inputPassword); inputConformPassword = (EditText) findViewById(R.id.inputConformPassword); loadingBar = new ProgressDialog(this); registration.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { CreateAccount(); } }); } private void CreateAccount() { { String email = inputEmail.getText().toString(); String password = inputPassword.getText().toString(); String username = inputFullName.getText().toString(); String retypepassword = inputConformPassword.getText().toString(); if (TextUtils.isEmpty(email)) { //snake bar Toast.makeText(this, "Please Enter Your E-mail", Toast.LENGTH_SHORT).show(); } else if (TextUtils.isEmpty(password)) { Toast.makeText(this, "Please Enter Your Password", Toast.LENGTH_SHORT).show(); } else if (TextUtils.isEmpty(username)) { Toast.makeText(this, "Please Enter Your Confirm Password", Toast.LENGTH_SHORT).show(); } else if (TextUtils.isEmpty(retypepassword)) { Toast.makeText(this, "Please Enter Your Confirm Password", Toast.LENGTH_SHORT).show(); } else { loadingBar.setTitle("Create Account"); loadingBar.setMessage("Please Wait, while we are checking the credentials."); loadingBar.setCanceledOnTouchOutside(false); loadingBar.show(); ValidateEmail(email, password, username,retypepassword); } } } private void ValidateEmail(String email, String password, String username, String retypepassword) { final DatabaseReference RootRef; RootRef = FirebaseDatabase.getInstance().getReference(); final FirebaseDatabase database = FirebaseDatabase.getInstance(); // DatabaseReference ref = database.getReference("server/saving-data/fireblog"); User newUser = new User(); newUser.email = email; newUser.fullname = username; newUser.password = password; newUser.retypepassword = retypepassword; String uDiD = Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID) + System.currentTimeMillis(); RootRef.child("Users").child(uDiD).setValue(newUser); // RootRef.child(uDiD).setValue(newUser); RootRef.addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { if (!(dataSnapshot.child(email).exists())){ HashMap<String, Object> userdataMap = new HashMap<>(); userdataMap.put("email", email); userdataMap.put("password", password); userdataMap.put("repassword",retypepassword); userdataMap.put("username", username); RootRef.child("Users").child(uDiD).updateChildren(userdataMap) .addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if (task.isSuccessful()){ Toast.makeText(activity_registration.this, "Congratulations, your account has been created.", Toast.LENGTH_SHORT).show(); loadingBar.dismiss(); Intent intent = new Intent(activity_registration.this, activity_login.class); startActivity(intent); } // else { loadingBar.dismiss(); Toast.makeText(activity_registration.this, "Network Error: Please try again later...", Toast.LENGTH_SHORT).show(); } } }); } else { Toast.makeText(activity_registration.this, "This " + email + " already exists.", Toast.LENGTH_SHORT).show(); loadingBar.dismiss(); Toast.makeText(activity_registration.this, "Please try again using another email account.", Toast.LENGTH_SHORT).show(); Intent intent = new Intent(activity_registration.this, activity_login.class); startActivity(intent); } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); } }
UTF-8
Java
6,657
java
activity_registration.java
Java
[ { "context": " newUser.email = email;\n newUser.fullname = username;\n newUser.password = password;\n new", "end": 3894, "score": 0.8148283958435059, "start": 3886, "tag": "NAME", "value": "username" }, { "context": "er.fullname = username;\n newUser.passw...
null
[]
package com.system.donate; import android.app.ProgressDialog; import android.content.Intent; import android.os.Bundle; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.android.material.snackbar.Snackbar; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import android.provider.Settings; import android.text.TextUtils; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import androidx.navigation.NavController; import androidx.navigation.Navigation; import androidx.navigation.ui.AppBarConfiguration; import androidx.navigation.ui.NavigationUI; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import com.system.donate.databinding.ActivityRegistrationBinding; import com.system.donate.model.User; import java.util.HashMap; public class activity_registration extends AppCompatActivity { Button registration; EditText inputFullName, inputEmail, inputPassword, inputConformPassword; private ProgressDialog loadingBar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_registration); registration = (Button) findViewById(R.id.btnRegister); inputFullName = (EditText) findViewById(R.id.inputUsername); inputEmail = (EditText) findViewById(R.id.inputEmail); inputPassword = (EditText) findViewById(R.id.inputPassword); inputConformPassword = (EditText) findViewById(R.id.inputConformPassword); loadingBar = new ProgressDialog(this); registration.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { CreateAccount(); } }); } private void CreateAccount() { { String email = inputEmail.getText().toString(); String password = inputPassword.getText().toString(); String username = inputFullName.getText().toString(); String retypepassword = inputConformPassword.getText().toString(); if (TextUtils.isEmpty(email)) { //snake bar Toast.makeText(this, "Please Enter Your E-mail", Toast.LENGTH_SHORT).show(); } else if (TextUtils.isEmpty(password)) { Toast.makeText(this, "Please Enter Your Password", Toast.LENGTH_SHORT).show(); } else if (TextUtils.isEmpty(username)) { Toast.makeText(this, "Please Enter Your Confirm Password", Toast.LENGTH_SHORT).show(); } else if (TextUtils.isEmpty(retypepassword)) { Toast.makeText(this, "Please Enter Your Confirm Password", Toast.LENGTH_SHORT).show(); } else { loadingBar.setTitle("Create Account"); loadingBar.setMessage("Please Wait, while we are checking the credentials."); loadingBar.setCanceledOnTouchOutside(false); loadingBar.show(); ValidateEmail(email, password, username,retypepassword); } } } private void ValidateEmail(String email, String password, String username, String retypepassword) { final DatabaseReference RootRef; RootRef = FirebaseDatabase.getInstance().getReference(); final FirebaseDatabase database = FirebaseDatabase.getInstance(); // DatabaseReference ref = database.getReference("server/saving-data/fireblog"); User newUser = new User(); newUser.email = email; newUser.fullname = username; newUser.password = <PASSWORD>; newUser.retypepassword = <PASSWORD>; String uDiD = Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID) + System.currentTimeMillis(); RootRef.child("Users").child(uDiD).setValue(newUser); // RootRef.child(uDiD).setValue(newUser); RootRef.addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { if (!(dataSnapshot.child(email).exists())){ HashMap<String, Object> userdataMap = new HashMap<>(); userdataMap.put("email", email); userdataMap.put("password", <PASSWORD>); userdataMap.put("repassword",<PASSWORD>); userdataMap.put("username", username); RootRef.child("Users").child(uDiD).updateChildren(userdataMap) .addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if (task.isSuccessful()){ Toast.makeText(activity_registration.this, "Congratulations, your account has been created.", Toast.LENGTH_SHORT).show(); loadingBar.dismiss(); Intent intent = new Intent(activity_registration.this, activity_login.class); startActivity(intent); } // else { loadingBar.dismiss(); Toast.makeText(activity_registration.this, "Network Error: Please try again later...", Toast.LENGTH_SHORT).show(); } } }); } else { Toast.makeText(activity_registration.this, "This " + email + " already exists.", Toast.LENGTH_SHORT).show(); loadingBar.dismiss(); Toast.makeText(activity_registration.this, "Please try again using another email account.", Toast.LENGTH_SHORT).show(); Intent intent = new Intent(activity_registration.this, activity_login.class); startActivity(intent); } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); } }
6,653
0.611987
0.611987
157
41.407642
33.219395
161
false
false
0
0
0
0
0
0
0.751592
false
false
2
ff5757db7c3e4c704b12acd46ed5e6eae789c65f
5,952,824,706,339
9b6aef95fe5cb11aefcccd01bdd4eeaf7ea1b7d1
/src/encryptor/CaesarEncryptor.java
2ad97b443405e93e6f3851c204f671b62778b4fa
[]
no_license
sderevianko/simple-data-encryptor
https://github.com/sderevianko/simple-data-encryptor
ca2220b491eef28ec1e5b9c4c8e5c6760fd1f00f
06ca908e0c0fac9840ad0b6d2da119a03abe8610
refs/heads/master
2022-10-21T22:56:04.711000
2020-06-09T21:04:40
2020-06-09T21:04:40
266,882,097
0
0
null
true
2020-05-25T21:18:33
2020-05-25T21:18:32
2020-01-16T22:44:23
2020-01-16T22:44:21
5
0
0
0
null
false
false
package encryptor; import cipher.CaesarCipher; public class CaesarEncryptor extends BaseEncryptor { public CaesarEncryptor() { cipherMethod = new CaesarCipher(); } }
UTF-8
Java
184
java
CaesarEncryptor.java
Java
[]
null
[]
package encryptor; import cipher.CaesarCipher; public class CaesarEncryptor extends BaseEncryptor { public CaesarEncryptor() { cipherMethod = new CaesarCipher(); } }
184
0.728261
0.728261
9
19.444445
18.391491
52
false
false
0
0
0
0
0
0
0.333333
false
false
2
ab1f0f351e3bd155fff7e70d2158019dc53c2b2e
5,952,824,704,739
50ff96da05217a5ffa8e77ecc382e7d7e78f0dc2
/src/main/java/pkmhaijr/manager/DatabaseFacade.java
58d4ba1ffd8a122f55a6acbb1473d28022119dd1
[]
no_license
kacperski195605/PKMHAIJR
https://github.com/kacperski195605/PKMHAIJR
cef3513438930911439a6c27f04f62320e058bb7
9e58c75107aba70ec1db9053c84179fbdf5781f0
refs/heads/master
2020-04-16T01:45:44.625000
2017-06-13T12:00:43
2017-06-13T12:00:43
83,527,219
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package pkmhaijr.manager; import lombok.RequiredArgsConstructor; import lombok.extern.log4j.Log4j2; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import pkmhaijr.model.app.SearchContext; import pkmhaijr.model.dbEntities.Product; import pkmhaijr.model.dbEntities.User; import pkmhaijr.model.enums.Genre; import pkmhaijr.service.*; import javax.inject.Inject; import java.util.ArrayList; import java.util.List; /** * Created by Asasello on 19-Apr-17. */ @Component @Log4j2 public class DatabaseFacade { @Autowired private ProductService productService; @Autowired private AddressService addressService; @Autowired private AuthorService authorService; @Autowired private CreditCardService creditCardService; @Autowired private UserService userService; @Autowired private WishlistService wishlistService; public User getUser(int id){ return userService.findUserByd(id); } //Field SortingType in SearchContext should be ignored in this method public List<Product> getProducts(SearchContext searchContext) { if(searchContext.getGenreType() == Genre.ALL) { if(searchContext.getSearchPhrase().length() == 0) return getAllProducts(); return productService.getSortedProduct(searchContext.getSearchPhrase()); }else{ return productService.getSortedProduct(searchContext.getGenreType()); } } public List<Product> getAllProducts() { return productService.findAllProducts(); } public List<Product> getUsersOrderHistory(int userId) { User user = userService.findUserByd(userId); return user.getOrderHistory(); } }
UTF-8
Java
1,757
java
DatabaseFacade.java
Java
[ { "context": "rayList;\nimport java.util.List;\n\n/**\n * Created by Asasello on 19-Apr-17.\n */\n@Component\n@Log4j2\npublic class", "end": 505, "score": 0.9856342673301697, "start": 497, "tag": "USERNAME", "value": "Asasello" } ]
null
[]
package pkmhaijr.manager; import lombok.RequiredArgsConstructor; import lombok.extern.log4j.Log4j2; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import pkmhaijr.model.app.SearchContext; import pkmhaijr.model.dbEntities.Product; import pkmhaijr.model.dbEntities.User; import pkmhaijr.model.enums.Genre; import pkmhaijr.service.*; import javax.inject.Inject; import java.util.ArrayList; import java.util.List; /** * Created by Asasello on 19-Apr-17. */ @Component @Log4j2 public class DatabaseFacade { @Autowired private ProductService productService; @Autowired private AddressService addressService; @Autowired private AuthorService authorService; @Autowired private CreditCardService creditCardService; @Autowired private UserService userService; @Autowired private WishlistService wishlistService; public User getUser(int id){ return userService.findUserByd(id); } //Field SortingType in SearchContext should be ignored in this method public List<Product> getProducts(SearchContext searchContext) { if(searchContext.getGenreType() == Genre.ALL) { if(searchContext.getSearchPhrase().length() == 0) return getAllProducts(); return productService.getSortedProduct(searchContext.getSearchPhrase()); }else{ return productService.getSortedProduct(searchContext.getGenreType()); } } public List<Product> getAllProducts() { return productService.findAllProducts(); } public List<Product> getUsersOrderHistory(int userId) { User user = userService.findUserByd(userId); return user.getOrderHistory(); } }
1,757
0.734206
0.728514
60
28.283333
23.600206
86
false
false
0
0
0
0
0
0
0.433333
false
false
2
0579c6341d79c5785e20607168c34c5495fad613
22,316,650,098,925
b284051bad0709b29ba83af209aa1fb5d64dcd12
/src/main/java/cn/cdz/java8/bean/Man.java
91de97ad3b397216d0ca280b68d17309264ec32a
[]
no_license
CDz1129/algolearn
https://github.com/CDz1129/algolearn
cff949927307edb37d0b95fdacae17c857c87a25
6d50de9387023da0b73cd8d5cc966ac4e75a1999
refs/heads/master
2021-09-10T09:55:34.901000
2018-03-24T03:22:15
2018-03-24T03:22:15
109,771,557
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package cn.cdz.java8.bean; /** * User: Cdz * Date: 2017/8/3 * Time: 20:21 */ public class Man { public Man() { this.speak(); } public void speak(){ System.out.println("i'm man"); } }
UTF-8
Java
222
java
Man.java
Java
[ { "context": "package cn.cdz.java8.bean;\n\n/**\n * User: Cdz\n * Date: 2017/8/3\n * Time: 20:21\n */\npublic class", "end": 44, "score": 0.9995843172073364, "start": 41, "tag": "USERNAME", "value": "Cdz" } ]
null
[]
package cn.cdz.java8.bean; /** * User: Cdz * Date: 2017/8/3 * Time: 20:21 */ public class Man { public Man() { this.speak(); } public void speak(){ System.out.println("i'm man"); } }
222
0.513514
0.463964
17
12.058824
10.876151
38
false
false
0
0
0
0
0
0
0.176471
false
false
2
65b96ca5426bb936d9eaa32f1bf60ab845327139
730,144,470,161
5cd6e5d6a5263fdb7ef94bf8a1c15c09bdb274e4
/src/UnionFindMax.java
f9e8c16cfc72250590e020e93a75be03d71b670c
[]
no_license
richardg999/Algorithms_Part1
https://github.com/richardg999/Algorithms_Part1
eac6815663820567574b49ef9c1bbc2f4d35de1a
b335335191190b33ab0aa1d5bf4c8b75a248094e
refs/heads/master
2020-04-01T08:26:12.978000
2019-03-15T19:35:33
2019-03-15T19:35:33
153,030,577
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
public class UnionFindMax { private int[] uf; private int[] size; private int[] maxValue; public UnionFindMax(int num) { uf = new int[num]; size = new int[num]; maxValue = new int[num]; for (int i = 0; i < num; i++) { uf[i] = i; size[i] = 1; maxValue[i] = i; } } public boolean connected(int a, int b) { return root(a) == root(b); } public int maxValue(int num) { return maxValue[root(num)]; } public int root(int num) { while (uf[num] != num) { uf[num] = uf[uf[num]]; num = uf[num]; } return num; } public void union(int a, int b) { int root1 = root(a); int root2 = root(b); if (root1 == root2) return; // add to a if a is larger than b if (size[root1] > size[root2]) { uf[root1] = uf[root2]; size[root1] += size[root2]; maxValue[root1] = Math.max(maxValue[root1], maxValue[root2]); } else { uf[root1] = uf[root2]; size[root1] += size[root2]; maxValue[root2] = Math.max(maxValue[root1], maxValue[root2]); } } public static void main(String[] args) { // TODO Auto-generated method stub } }
UTF-8
Java
1,095
java
UnionFindMax.java
Java
[]
null
[]
public class UnionFindMax { private int[] uf; private int[] size; private int[] maxValue; public UnionFindMax(int num) { uf = new int[num]; size = new int[num]; maxValue = new int[num]; for (int i = 0; i < num; i++) { uf[i] = i; size[i] = 1; maxValue[i] = i; } } public boolean connected(int a, int b) { return root(a) == root(b); } public int maxValue(int num) { return maxValue[root(num)]; } public int root(int num) { while (uf[num] != num) { uf[num] = uf[uf[num]]; num = uf[num]; } return num; } public void union(int a, int b) { int root1 = root(a); int root2 = root(b); if (root1 == root2) return; // add to a if a is larger than b if (size[root1] > size[root2]) { uf[root1] = uf[root2]; size[root1] += size[root2]; maxValue[root1] = Math.max(maxValue[root1], maxValue[root2]); } else { uf[root1] = uf[root2]; size[root1] += size[root2]; maxValue[root2] = Math.max(maxValue[root1], maxValue[root2]); } } public static void main(String[] args) { // TODO Auto-generated method stub } }
1,095
0.586301
0.56621
57
18.192982
15.662492
64
false
false
0
0
0
0
0
0
2.157895
false
false
2
85d5e5de18e6e27882a8a7cd2915c27617c2d655
6,021,544,163,822
1b63d8cb237a61d55006842783a65ee66e133cec
/src/main/java/org/orderManager/boundary/helper/RestExceptionHelper.java
176b280ba976c7d497829a60e485838fa092dc5f
[]
no_license
edupalermo/glimpsy
https://github.com/edupalermo/glimpsy
03afa26ab9ea4ec943070cdd6dee0f452d99b770
22955cb511cf13abe8a3de6c4ae6851df16bf237
refs/heads/master
2021-01-16T21:03:16.669000
2016-07-25T04:06:18
2016-07-25T04:06:18
63,738,709
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.orderManager.boundary.helper; import javax.validation.ConstraintViolationException; import org.orderManager.exception.DuplicatedEntityException; import org.orderManager.exception.EntityNotFoundException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; public class RestExceptionHelper { private static Logger logger = LoggerFactory.getLogger(RestExceptionHelper.class); public static ResponseEntity<?> treatException(Exception e) throws Exception { ResponseEntity<?> responseEntity = null; if (e instanceof DuplicatedEntityException) { logger.error(e.getMessage()); responseEntity = new ResponseEntity<Void>(HttpStatus.BAD_REQUEST); } else if (e instanceof EntityNotFoundException) { logger.error(e.getMessage()); responseEntity = new ResponseEntity<Void>(HttpStatus.NOT_FOUND); } else if (e instanceof ConstraintViolationException) { logger.error(((ConstraintViolationException) e).getConstraintViolations().iterator().next().getMessage()); responseEntity = new ResponseEntity<Void>(HttpStatus.BAD_REQUEST); } else { throw e; } return responseEntity; } }
UTF-8
Java
1,223
java
RestExceptionHelper.java
Java
[]
null
[]
package org.orderManager.boundary.helper; import javax.validation.ConstraintViolationException; import org.orderManager.exception.DuplicatedEntityException; import org.orderManager.exception.EntityNotFoundException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; public class RestExceptionHelper { private static Logger logger = LoggerFactory.getLogger(RestExceptionHelper.class); public static ResponseEntity<?> treatException(Exception e) throws Exception { ResponseEntity<?> responseEntity = null; if (e instanceof DuplicatedEntityException) { logger.error(e.getMessage()); responseEntity = new ResponseEntity<Void>(HttpStatus.BAD_REQUEST); } else if (e instanceof EntityNotFoundException) { logger.error(e.getMessage()); responseEntity = new ResponseEntity<Void>(HttpStatus.NOT_FOUND); } else if (e instanceof ConstraintViolationException) { logger.error(((ConstraintViolationException) e).getConstraintViolations().iterator().next().getMessage()); responseEntity = new ResponseEntity<Void>(HttpStatus.BAD_REQUEST); } else { throw e; } return responseEntity; } }
1,223
0.787408
0.785773
37
32.054054
29.298046
109
false
false
0
0
0
0
0
0
1.72973
false
false
2
8ade94059ffc77e2f2a2337935e1c1ba1b402799
38,766,374,833,699
bbdc5aa9fe30dce061a145bb15e2172e8bac5bdc
/app/src/main/java/com/forasoft/androidopus/WorkerThread.java
85f2c073d91bd6b9df769d52b545a22ca87df5c6
[]
no_license
vitaliyFora/AndroidOpus
https://github.com/vitaliyFora/AndroidOpus
596d76a135cb410800ae2a735cc616370d7300a8
097149c09962ead27f185727e8116866e2446580
refs/heads/master
2020-04-17T21:58:09.745000
2019-03-18T09:41:12
2019-03-18T09:41:12
166,974,373
2
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.forasoft.androidopus; import android.os.Handler; import android.os.HandlerThread; class WorkerThread extends HandlerThread { public final static String TAG = "WorkerThread"; WorkerThread() { super(TAG); } private Handler mWorkerHandler = null; void prepareHandler() { mWorkerHandler = new Handler(getLooper()); } void postTask(Runnable task) { mWorkerHandler.post(task); } void postDelayTask(long delayInMillis, Runnable task) { if (delayInMillis == 0) { mWorkerHandler.post(task); return; } mWorkerHandler.postDelayed(task, delayInMillis); } }
UTF-8
Java
678
java
WorkerThread.java
Java
[]
null
[]
package com.forasoft.androidopus; import android.os.Handler; import android.os.HandlerThread; class WorkerThread extends HandlerThread { public final static String TAG = "WorkerThread"; WorkerThread() { super(TAG); } private Handler mWorkerHandler = null; void prepareHandler() { mWorkerHandler = new Handler(getLooper()); } void postTask(Runnable task) { mWorkerHandler.post(task); } void postDelayTask(long delayInMillis, Runnable task) { if (delayInMillis == 0) { mWorkerHandler.post(task); return; } mWorkerHandler.postDelayed(task, delayInMillis); } }
678
0.641593
0.640118
32
20.1875
19.344633
59
false
false
0
0
0
0
0
0
0.40625
false
false
2
f7b5e8c47b5ed12ec07f8fc1d1a33ca91c07e6c8
34,084,860,518,697
a8c5b7b04eace88b19b5a41a45f1fb030df393e3
/projects/financial-rest-client/src/main/java/com/opengamma/financial/rest/RestfulJmsResultPublisherExpiryJob.java
5d63173dcf5d816bcb4ece69a555cf422243540c
[ "Apache-2.0" ]
permissive
McLeodMoores/starling
https://github.com/McLeodMoores/starling
3f6cfe89cacfd4332bad4861f6c5d4648046519c
7ae0689e06704f78fd9497f8ddb57ee82974a9c8
refs/heads/master
2022-12-04T14:02:00.480000
2020-04-28T17:22:44
2020-04-28T17:22:44
46,577,620
4
4
Apache-2.0
false
2022-11-24T07:26:39
2015-11-20T17:48:10
2022-11-15T07:46:39
2022-11-24T07:26:38
299,457
3
4
45
Java
false
false
/** * Copyright (C) 2011 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. */ package com.opengamma.financial.rest; import java.util.Collection; import java.util.Iterator; import org.threeten.bp.Instant; /** * Class for monitoring a collection of {@code AbstractRestfulJmsResultPublisher} resources and expiring those which have not been accessed recently. It is * expected that this will be invoked on a schedule, for example: <code> * private void someMethod() { * _scheduler.scheduleAtFixedRate(createExpiryJob(), VIEW_CLIENT_TIMEOUT_MILLIS, VIEW_CLIENT_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS); * } * * private RestfulJmsResultPublisherExpiryJob&lt;DataViewClientResource&gt; createExpiryJob() { * return new RestfulJmsResultPublisherExpiryJob&lt;&gt;( VIEW_CLIENT_TIMEOUT_MILLIS, _createdViewClients.values()); * } * </code> * * @param <T> * the type of the resource */ public class RestfulJmsResultPublisherExpiryJob<T extends AbstractRestfulJmsResultPublisher> implements Runnable { /** * The collection of resources to be checked for termination/expiry. This is expected * to be a live collection. Because of the need for multi-threaded access the passed * collection needs to be threadsafe. */ private final Collection<T> _resources; /** * How long to wait after the last access time of a resource * before expiring it. */ private final long _resourceTimeoutMillis; /** * Create the job to expire members of the collection of resources if * they have not been accessed in the period specified by the timeout. * @param resources the collection of resources to be checked for termination/expiry. * This is expected to be a live collection. Because of the need for multi-threaded * access the passed collection needs to be threadsafe. * @param resourceTimeoutMillis how long to wait after the last access time of a resource * before expiring it */ public RestfulJmsResultPublisherExpiryJob(final Collection<T> resources, final long resourceTimeoutMillis) { _resourceTimeoutMillis = resourceTimeoutMillis; _resources = resources; } @Override public void run() { final Instant timeoutBefore = Instant.now().minusMillis(_resourceTimeoutMillis); for (final Iterator<T> iterator = _resources.iterator(); iterator.hasNext();) { final T resource = iterator.next(); if (resource.isTerminated()) { iterator.remove(); } else if (resource.getLastAccessed().isBefore(timeoutBefore)) { iterator.remove(); resource.expire(); } } } }
UTF-8
Java
2,669
java
RestfulJmsResultPublisherExpiryJob.java
Java
[]
null
[]
/** * Copyright (C) 2011 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. */ package com.opengamma.financial.rest; import java.util.Collection; import java.util.Iterator; import org.threeten.bp.Instant; /** * Class for monitoring a collection of {@code AbstractRestfulJmsResultPublisher} resources and expiring those which have not been accessed recently. It is * expected that this will be invoked on a schedule, for example: <code> * private void someMethod() { * _scheduler.scheduleAtFixedRate(createExpiryJob(), VIEW_CLIENT_TIMEOUT_MILLIS, VIEW_CLIENT_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS); * } * * private RestfulJmsResultPublisherExpiryJob&lt;DataViewClientResource&gt; createExpiryJob() { * return new RestfulJmsResultPublisherExpiryJob&lt;&gt;( VIEW_CLIENT_TIMEOUT_MILLIS, _createdViewClients.values()); * } * </code> * * @param <T> * the type of the resource */ public class RestfulJmsResultPublisherExpiryJob<T extends AbstractRestfulJmsResultPublisher> implements Runnable { /** * The collection of resources to be checked for termination/expiry. This is expected * to be a live collection. Because of the need for multi-threaded access the passed * collection needs to be threadsafe. */ private final Collection<T> _resources; /** * How long to wait after the last access time of a resource * before expiring it. */ private final long _resourceTimeoutMillis; /** * Create the job to expire members of the collection of resources if * they have not been accessed in the period specified by the timeout. * @param resources the collection of resources to be checked for termination/expiry. * This is expected to be a live collection. Because of the need for multi-threaded * access the passed collection needs to be threadsafe. * @param resourceTimeoutMillis how long to wait after the last access time of a resource * before expiring it */ public RestfulJmsResultPublisherExpiryJob(final Collection<T> resources, final long resourceTimeoutMillis) { _resourceTimeoutMillis = resourceTimeoutMillis; _resources = resources; } @Override public void run() { final Instant timeoutBefore = Instant.now().minusMillis(_resourceTimeoutMillis); for (final Iterator<T> iterator = _resources.iterator(); iterator.hasNext();) { final T resource = iterator.next(); if (resource.isTerminated()) { iterator.remove(); } else if (resource.getLastAccessed().isBefore(timeoutBefore)) { iterator.remove(); resource.expire(); } } } }
2,669
0.724991
0.723492
73
35.561646
37.059738
155
false
false
0
0
0
0
0
0
0.369863
false
false
2
45d6f1d60b41c54793f3f5eab77492a855424a84
39,384,850,129,466
df9c1058885f346cabc12ad99eb8ff00b68b328c
/src/main/java/se/kth/id1212/globalapps/view/DTOs/ApplicationUpdate.java
81162aa743243782f289a1b2e8c84d9b6ba976b8
[]
no_license
FlyHighXX/GlobAppProj
https://github.com/FlyHighXX/GlobAppProj
8a63c576a2a7b1b517dc12a46460a0d4355b6227
d25bb405048b65d89d047983ffaf37f119192637
refs/heads/master
2020-08-09T17:28:14.878000
2018-03-15T16:32:00
2018-03-15T16:32:00
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * 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 se.kth.id1212.globalapps.view.DTOs; import java.util.Date; import se.kth.id1212.globalapps.dtos.ApplicationDTO; import se.kth.id1212.globalapps.dtos.TimePeriodDTO; import se.kth.id1212.globalapps.dtos.YearsWithExpertiseDTO; /** * Implementation of se.kth.id1212.globalapps.dtos.ApplicationDTO * for updating applications */ public class ApplicationUpdate implements ApplicationDTO { private final long applicationId; private final int versionNumber; private final boolean status; /** * Create a new Application update * @param applicationId application's Id * @param versionNumber application's version number * @param status application's status */ public ApplicationUpdate(long applicationId, int versionNumber, boolean status) { this.applicationId = applicationId; this.versionNumber = versionNumber; this.status = status; } @Override public boolean getStatus() { return status; } @Override public int getVersionNumber() { return versionNumber; } @Override public long getApplicationId() { return applicationId; } @Override public String getFirstName() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public String getLastName() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public Date getDateOfBirth() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public YearsWithExpertiseDTO[] getExpertises() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public TimePeriodDTO[] getAvailabilityPeriods() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public String getUsername() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public Date getDateOfRegistration() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } }
UTF-8
Java
2,827
java
ApplicationUpdate.java
Java
[]
null
[]
/* * 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 se.kth.id1212.globalapps.view.DTOs; import java.util.Date; import se.kth.id1212.globalapps.dtos.ApplicationDTO; import se.kth.id1212.globalapps.dtos.TimePeriodDTO; import se.kth.id1212.globalapps.dtos.YearsWithExpertiseDTO; /** * Implementation of se.kth.id1212.globalapps.dtos.ApplicationDTO * for updating applications */ public class ApplicationUpdate implements ApplicationDTO { private final long applicationId; private final int versionNumber; private final boolean status; /** * Create a new Application update * @param applicationId application's Id * @param versionNumber application's version number * @param status application's status */ public ApplicationUpdate(long applicationId, int versionNumber, boolean status) { this.applicationId = applicationId; this.versionNumber = versionNumber; this.status = status; } @Override public boolean getStatus() { return status; } @Override public int getVersionNumber() { return versionNumber; } @Override public long getApplicationId() { return applicationId; } @Override public String getFirstName() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public String getLastName() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public Date getDateOfBirth() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public YearsWithExpertiseDTO[] getExpertises() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public TimePeriodDTO[] getAvailabilityPeriods() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public String getUsername() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public Date getDateOfRegistration() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } }
2,827
0.687301
0.680226
85
31.258823
37.295055
135
false
false
0
0
0
0
0
0
0.470588
false
false
2
3c55e26286a157307c4d8e23784d30a78e17357d
34,411,278,034,053
5a6d1ae7179b5c5bd854454786286b2d82c419e9
/src/com/facebook/buck/event/listener/BuildTargetDurationListener.java
f211e9825dac3276f3781b919f71988788d56846
[ "Apache-2.0" ]
permissive
edsilfer/buck
https://github.com/edsilfer/buck
a9919bdbc871a7a4a80d2dd14afa99ca3ac2276b
5621a193e70886c1cb3c268437c4f47d9caa23ff
refs/heads/master
2020-04-18T11:23:26.079000
2019-01-25T01:06:40
2019-01-25T01:51:10
167,498,157
1
0
Apache-2.0
true
2019-01-25T06:40:10
2019-01-25T06:40:10
2019-01-25T01:51:25
2019-01-25T01:51:15
992,870
0
0
0
null
false
null
/* * Copyright 2018-present Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.facebook.buck.event.listener; import com.facebook.buck.core.build.event.BuildEvent.RuleCountCalculated; import com.facebook.buck.core.build.event.BuildRuleEvent; import com.facebook.buck.core.build.event.BuildRuleEvent.BeginningBuildRuleEvent; import com.facebook.buck.core.build.event.BuildRuleEvent.EndingBuildRuleEvent; import com.facebook.buck.core.model.BuildTarget; import com.facebook.buck.core.model.actiongraph.ActionGraph; import com.facebook.buck.core.rules.BuildRule; import com.facebook.buck.core.util.graph.AbstractBottomUpTraversal; import com.facebook.buck.core.util.graph.TraversableGraph; import com.facebook.buck.core.util.immutables.BuckStyleImmutable; import com.facebook.buck.core.util.log.Logger; import com.facebook.buck.event.ActionGraphEvent; import com.facebook.buck.event.BuckEventListener; import com.facebook.buck.event.chrome_trace.ChromeTraceEvent; import com.facebook.buck.event.chrome_trace.ChromeTraceEvent.Phase; import com.facebook.buck.event.chrome_trace.ChromeTraceWriter; import com.facebook.buck.io.filesystem.ProjectFilesystem; import com.facebook.buck.log.InvocationInfo; import com.facebook.buck.support.bgtasks.BackgroundTask; import com.facebook.buck.support.bgtasks.ImmutableBackgroundTask; import com.facebook.buck.support.bgtasks.TaskAction; import com.facebook.buck.support.bgtasks.TaskManagerScope; import com.facebook.buck.support.bgtasks.Timeout; import com.facebook.buck.util.json.ObjectMappers; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Objects; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.MinMaxPriorityQueue; import com.google.common.collect.Queues; import com.google.common.collect.Sets; import com.google.common.eventbus.Subscribe; import java.io.BufferedOutputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.nio.file.Path; import java.util.Collection; import java.util.Collections; import java.util.Deque; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import org.immutables.value.Value; /** * Listens {@link ActionGraphEvent.Finished} to get {@link ActionGraph}, {@link BuildRuleEvent} to * trace {@link BuildRule} to compute critical path for test targets. */ public class BuildTargetDurationListener implements BuckEventListener { private static final Logger LOG = Logger.get(BuildTargetDurationListener.class); public static final String CRITICAL_PATH_FILE_NAME = "critical-path"; public static final String CRITICAL_PATH_TRACE_FILE_NAME = "critical-path.trace"; public static final String TARGETS_BUILD_TIMES_FILE_NAME = "targets-build-times"; private static final int SHUTDOWN_TIMEOUT_SECONDS = 60; private final InvocationInfo info; private final ProjectFilesystem filesystem; private final int criticalPathCount; private final TaskManagerScope managerScope; private Optional<ActionGraph> actionGraph = Optional.empty(); private Optional<ImmutableSet<BuildTarget>> targetBuildRules = Optional.empty(); @VisibleForTesting ConcurrentMap<String, BuildRuleInfo> getBuildRuleInfos() { return buildRuleInfos; } // Hold the latest one for the target private ConcurrentMap<String, BuildRuleInfo> buildRuleInfos = Maps.newConcurrentMap(); public BuildTargetDurationListener( InvocationInfo info, ProjectFilesystem filesystem, int criticalPathCount, TaskManagerScope managerScope) { this.info = info; this.filesystem = filesystem; this.criticalPathCount = criticalPathCount; this.managerScope = managerScope; } /** Save start of the {@link BuildRuleEvent}. */ @Subscribe public void buildRuleEventStarted(BuildRuleEvent.Started event) { final String buildRuleName = event.getBuildRule().getFullyQualifiedName(); final long startEpochMillis = event.getTimestamp(); Preconditions.checkState( !buildRuleInfos.containsKey(buildRuleName), "There can not be more than one BuildRuleEvent.Started for the %s BuildRule.", buildRuleName); LOG.info("BuildRuleEventStarted{name=%s, time=%d}", buildRuleName, startEpochMillis); BuildRuleInfo ruleInfo = new BuildRuleInfo(buildRuleName, criticalPathCount, startEpochMillis, startEpochMillis); buildRuleInfos.put(buildRuleName, ruleInfo); event .getBuildRule() .getBuildDeps() .stream() .map(BuildRule::getFullyQualifiedName) .forEach(ruleInfo::addDependency); } /** * Save end of the {@link BuildRuleEvent} for {@link * com.facebook.buck.event.RuleKeyCalculationEvent}. */ @Subscribe public synchronized void buildRuleEventSuspended(BuildRuleEvent.Suspended event) { LOG.info( "BuildRuleEventSuspended{name=%s, time=%d}", event.getBuildRule().getFullyQualifiedName(), event.getTimestamp()); saveEndOfBuildRuleEvent( event.getBuildRule().getFullyQualifiedName(), event.getBeginningEvent(), event); } /** Save end of the {@link BuildRuleEvent}. */ @Subscribe public synchronized void buildRuleEventFinished(BuildRuleEvent.Finished event) { LOG.info( "BuildRuleEventFinished{name=%s, time=%d}", event.getBuildRule().getFullyQualifiedName(), event.getTimestamp()); saveEndOfBuildRuleEvent( event.getBuildRule().getFullyQualifiedName(), event.getBeginningEvent(), event); } /** Update end of the {@link BuildRuleEvent}. */ private void saveEndOfBuildRuleEvent( String buildRuleName, BeginningBuildRuleEvent begin, EndingBuildRuleEvent end) { Preconditions.checkState( buildRuleInfos.containsKey(buildRuleName), "First, a BuildRuleEvent %s has to start in order to finish.", buildRuleName); BuildRuleInfo currentBuildRuleInfo = buildRuleInfos.get(buildRuleName); currentBuildRuleInfo.updateDuration(end.getDuration().getWallMillisDuration()); currentBuildRuleInfo.updateFinish(end.getTimestamp()); currentBuildRuleInfo.addBuildRuleEventInterval( TimeUnit.NANOSECONDS.toMicros(begin.getNanoTime()), TimeUnit.NANOSECONDS.toMicros(end.getNanoTime())); } /** Save the {@link ActionGraph} */ @Subscribe public synchronized void actionGraphFinished(ActionGraphEvent.Finished finished) { actionGraph = finished.getActionGraph(); } @Subscribe public synchronized void ruleCountCalculated(RuleCountCalculated ruleCountCalculated) { targetBuildRules = Optional.of(ruleCountCalculated.getBuildRules()); } private Path getLogFilePath() { return filesystem.resolve(info.getBuckLogDir()).resolve(CRITICAL_PATH_FILE_NAME); } private Path getTraceFilePath() { return filesystem.resolve(info.getBuckLogDir()).resolve(CRITICAL_PATH_TRACE_FILE_NAME); } private Path getTargetFilePath() { return filesystem.resolve(info.getBuckLogDir()).resolve(TARGETS_BUILD_TIMES_FILE_NAME); } @VisibleForTesting static ImmutableList<ImmutableBuildRuleCriticalPath> constructBuildRuleCriticalPaths( List<Deque<CriticalPathEntry>> criticalPaths) { ImmutableList.Builder<ImmutableBuildRuleCriticalPath> criticalPathsBuilder = ImmutableList.builder(); for (Deque<CriticalPathEntry> path : criticalPaths) { CriticalPathEntry last = path.getLast(); criticalPathsBuilder.add( ImmutableBuildRuleCriticalPath.of( last.ruleName(), last.wholeDuration(), path, last.longest())); } return criticalPathsBuilder.build(); } @VisibleForTesting static ImmutableList<Deque<CriticalPathEntry>> constructCriticalPaths( Collection<BuildRuleInfo> rootBuildRuleInfos, int k) { MinMaxPriorityQueue<BuildRuleInfoSelectedChain> topK = findCriticalNodes(rootBuildRuleInfos, k); Map<BuildRuleInfo, Set<BuildRuleInfo.Chain>> usedChainsMap = Maps.newHashMap(); ImmutableList.Builder<Deque<CriticalPathEntry>> criticalPaths = ImmutableList.builder(); while (!topK.isEmpty()) { BuildRuleInfoSelectedChain root = topK.poll(); Set<BuildRuleInfo.Chain> usedChains = usedChainsMap.getOrDefault(root.buildRuleInfo(), Sets.newHashSet()); criticalPaths.add(criticalPath(root.chain(), root.buildRuleInfo(), usedChains)); } return criticalPaths.build(); } @VisibleForTesting static void rendersCriticalPathsTraceFile( List<Deque<CriticalPathEntry>> criticalPaths, OutputStream os) { try (ChromeTraceWriter traceWriter = new ChromeTraceWriter(os)) { traceWriter.writeStart(); traceWriter.writeEvent( new ChromeTraceEvent( "buck", "process_name", Phase.METADATA, 0, 0, 0, 0, ImmutableMap.of("name", "Critical Path"))); rendersCriticalPaths(criticalPaths, traceWriter); traceWriter.writeEnd(); } catch (IOException e) { LOG.error(e, "Could not write critical path to trace file."); } } private static void rendersCriticalPaths( List<Deque<CriticalPathEntry>> criticalPaths, ChromeTraceWriter traceWriter) throws IOException { int threadId = 0; for (Deque<CriticalPathEntry> path : criticalPaths) { for (CriticalPathEntry criticalPathEntry : path) { rendersCriticalPathEntry(criticalPathEntry, traceWriter, threadId); } ++threadId; } } /** * Renders rule in a similar way to {@link * com.facebook.buck.distributed.build_slave.DistBuildChromeTraceRenderer#renderRule}. */ private static void rendersCriticalPathEntry( CriticalPathEntry criticalPathEntry, ChromeTraceWriter traceWriter, int tid) throws IOException { for (BuildRuleEventInterval interval : criticalPathEntry.intervals()) { long end = interval.end() > interval.start() ? interval.end() : interval.start() + 1; ImmutableMap<String, String> startArgs = ImmutableMap.of( "critical_blocking_rule", criticalPathEntry.prev().map(rule -> rule.ruleName).orElse("None"), "length_of_critical_path", String.format("%dms", criticalPathEntry.longest())); traceWriter.writeEvent( new ChromeTraceEvent( "buck", criticalPathEntry.ruleName(), Phase.BEGIN, 0, tid, interval.start(), 0, startArgs)); traceWriter.writeEvent( new ChromeTraceEvent( "buck", criticalPathEntry.ruleName(), Phase.END, 0, tid, end, 0, ImmutableMap.of())); } } @Override public synchronized void close() { BuildTargetDurationListenerCloseArgs args = BuildTargetDurationListenerCloseArgs.builder() .setLogFilePath(getLogFilePath()) .setTargetFilePath(getTargetFilePath()) .setTraceFilePath(getTraceFilePath()) .setInvocationInfo(info) .setCriticalPathCount(criticalPathCount) .setTargetBuildRules(targetBuildRules) .setBuildRuleInfos(buildRuleInfos) .setActionGraph(actionGraph) .build(); BackgroundTask<BuildTargetDurationListenerCloseArgs> task = ImmutableBackgroundTask.<BuildTargetDurationListenerCloseArgs>builder() .setAction(new BuildTargetDurationListenerCloseAction()) .setActionArgs(args) .setName("BuildTargetDurationListener_close") .setTimeout(Timeout.of(SHUTDOWN_TIMEOUT_SECONDS, TimeUnit.SECONDS)) .build(); managerScope.schedule(task); } /** {@link TaskAction} implementation for closing {@link BuildTargetDurationListener}. */ static class BuildTargetDurationListenerCloseAction implements TaskAction<BuildTargetDurationListenerCloseArgs> { @Override public void run(BuildTargetDurationListenerCloseArgs args) { try (BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(args.getLogFilePath().toFile())); BufferedOutputStream targetStream = new BufferedOutputStream(new FileOutputStream(args.getTargetFilePath().toFile()))) { LOG.info("Starting critical path calculation for %s", args.getInvocationInfo()); LOG.info("Writing critical path to %s", args.getLogFilePath().toString()); if (args.getActionGraph().isPresent()) { updateBuildRuleInfosWithDependents(args.getActionGraph(), args.getBuildRuleInfos()); computeCriticalPathsUsingGraphTraversal(args.getBuildRuleInfos()); // Find root build rules Collection<BuildRuleInfo> rootBuildRuleInfos = Lists.newArrayList(); if (args.getTargetBuildRules().isPresent()) { for (BuildTarget buildTarget : args.getTargetBuildRules().get()) { BuildRuleInfo buildRuleInfo = args.getBuildRuleInfos().get(buildTarget.getFullyQualifiedName()); if (buildRuleInfo != null) { rootBuildRuleInfos.add(buildRuleInfo); } else { LOG.warn( "Could not find build rule for the target %s!", buildTarget.getFullyQualifiedName()); } } } else { LOG.warn("There were not any target, construction of critical paths will be skipped."); } List<Deque<CriticalPathEntry>> kCriticalPaths = constructCriticalPaths(rootBuildRuleInfos, args.getCriticalPathCount()); // Render chrome trace of the critical path of the longest rendersCriticalPaths(args.getTraceFilePath(), kCriticalPaths); // Serialize BuildRuleCriticalPaths ObjectMappers.WRITER.writeValue( outputStream, constructBuildRuleCriticalPaths(kCriticalPaths)); // Serialize BuildTargetResults ObjectMappers.WRITER.writeValue( targetStream, constructBuildTargetResults(rootBuildRuleInfos)); LOG.info("Critical path and target results have been written successfully."); } else { ObjectMappers.WRITER.writeValue(outputStream, Collections.emptyList()); LOG.warn("There was no action graph, computation is skipped."); } } catch (IOException e) { LOG.warn(e, "Could not complete IO Request."); } } private void rendersCriticalPaths( Path traceFilePath, List<Deque<CriticalPathEntry>> criticalPaths) throws IOException { try (FileOutputStream fos = new FileOutputStream(traceFilePath.toFile())) { rendersCriticalPathsTraceFile(criticalPaths, fos); } } private void updateBuildRuleInfosWithDependents( Optional<ActionGraph> actionGraph, ConcurrentMap<String, BuildRuleInfo> buildRuleInfos) { if (!actionGraph.isPresent()) { return; } for (BuildRule buildRule : actionGraph.get().getNodes()) { // for each dependency include a back-edge from dependency to dependent buildRule .getBuildDeps() .forEach( dependency -> { BuildRuleInfo dependencyBuildRuleInfo = buildRuleInfos.get(dependency.getFullyQualifiedName()); // It might not exist if a BuildRuleEvent is not executed! if (dependencyBuildRuleInfo != null) { dependencyBuildRuleInfo.addDependent(buildRule.getFullyQualifiedName()); } }); } } } /** Arguments to {@link BuildTargetDurationListenerCloseAction}. */ @Value.Immutable @BuckStyleImmutable abstract static class AbstractBuildTargetDurationListenerCloseArgs { @Value.Parameter public abstract Path getLogFilePath(); @Value.Parameter public abstract Path getTargetFilePath(); @Value.Parameter public abstract Path getTraceFilePath(); @Value.Parameter public abstract InvocationInfo getInvocationInfo(); @Value.Parameter public abstract int getCriticalPathCount(); @Value.Parameter public abstract Optional<ImmutableSet<BuildTarget>> getTargetBuildRules(); @Value.Parameter public abstract ConcurrentMap<String, BuildRuleInfo> getBuildRuleInfos(); @Value.Parameter public abstract Optional<ActionGraph> getActionGraph(); } /** Construct {@link BuildTargetResult} list for all given roots. */ @VisibleForTesting static ImmutableList<ImmutableBuildTargetResult> constructBuildTargetResults( Collection<BuildRuleInfo> rootBuildRuleInfos) { ImmutableList.Builder<ImmutableBuildTargetResult> buildTargetResults = ImmutableList.builder(); for (BuildRuleInfo buildRuleInfo : rootBuildRuleInfos) { buildTargetResults.add( ImmutableBuildTargetResult.of( buildRuleInfo.ruleName, buildRuleInfo.getWholeTargetDuration())); } return buildTargetResults.build(); } /** Modifies {@link BuildRuleInfo#chain} to save the longest paths. */ @VisibleForTesting static BuildRuleInfoGraph computeCriticalPathsUsingGraphTraversal( Map<String, BuildRuleInfo> buildRuleInfos) throws IOException { BuildRuleInfoGraph graph = new BuildRuleInfoGraph(buildRuleInfos); for (BuildRuleInfo buildRuleInfo : graph.getNodesWithNoOutgoingEdges()) { buildRuleInfo.chain.add( new BuildRuleInfo.Chain(buildRuleInfo.getDuration(), Optional.empty())); } new BuildRuleInfoGraphTraversal(graph).traverse(); return graph; } /** Finds top K critical nodes and corresponding chain for the critical paths. */ @VisibleForTesting static MinMaxPriorityQueue<BuildRuleInfoSelectedChain> findCriticalNodes( Iterable<BuildRuleInfo> rootRules, int k) { MinMaxPriorityQueue<BuildRuleInfoSelectedChain> topK = MinMaxPriorityQueue.orderedBy( (BuildRuleInfoSelectedChain first, BuildRuleInfoSelectedChain second) -> Long.compare(second.chain().longest, first.chain().longest)) .maximumSize(k) .create(); for (BuildRuleInfo ruleInfo : rootRules) { for (BuildRuleInfo.Chain chain : ruleInfo.chain) { topK.add(ImmutableBuildRuleInfoSelectedChain.of(ruleInfo, chain)); } } return topK; } /** * Construct the critical path to the target coming from the given chain. usedChain prevents * duplicate paths. */ @VisibleForTesting static Deque<CriticalPathEntry> criticalPath( BuildRuleInfo.Chain chain, BuildRuleInfo target, Set<BuildRuleInfo.Chain> usedChains) { Deque<CriticalPathEntry> path = Queues.newArrayDeque(); path.push( ImmutableCriticalPathEntry.of( target.ruleName, target.startEpochMillis, target.finishEpochMillis, target.getDuration(), target.getWholeTargetDuration(), chain.longest, chain.prev, target.intervals)); long longest = chain.longest; Optional<BuildRuleInfo> prev = chain.prev; while (prev.isPresent()) { chain = null; longest -= target.getDuration(); target = prev.get(); /** Search for previous {@link BuildRuleInfo} matching longest and not selected before. */ for (BuildRuleInfo.Chain c : target.chain) { if (c.longest == longest && !usedChains.contains(c)) { chain = c; usedChains.add(c); break; } } prev = chain != null ? chain.prev : Optional.empty(); longest = chain != null ? chain.longest : 0L; path.push( ImmutableCriticalPathEntry.of( target.ruleName, target.startEpochMillis, target.finishEpochMillis, target.getDuration(), target.getWholeTargetDuration(), longest, prev, target.intervals)); } return path; } /** Class extending {@link AbstractBottomUpTraversal} to do traversal bottom up. */ public static class BuildRuleInfoGraphTraversal extends AbstractBottomUpTraversal<BuildRuleInfo, IOException> { private BuildRuleInfoGraph graph; public BuildRuleInfoGraphTraversal(BuildRuleInfoGraph graph) { super(graph); this.graph = graph; } @Override public void visit(BuildRuleInfo currentBuildRuleInfo) { for (BuildRuleInfo neigborBuildRuleInfo : graph.getOutgoingNodesFor(currentBuildRuleInfo)) { for (BuildRuleInfo.Chain c : neigborBuildRuleInfo.chain) { currentBuildRuleInfo.chain.add( new BuildRuleInfo.Chain( c.longest + currentBuildRuleInfo.getDuration(), Optional.of(neigborBuildRuleInfo))); } } } } /** Implementing {@link TraversableGraph} interface. */ public static class BuildRuleInfoGraph implements TraversableGraph<BuildRuleInfo> { private Map<String, BuildRuleInfo> buildRuleInfos; public BuildRuleInfoGraph(Map<String, BuildRuleInfo> buildRuleInfos) { this.buildRuleInfos = buildRuleInfos; } @Override public Iterable<BuildRuleInfo> getNodesWithNoIncomingEdges() { return getBuildRuleInfos() .stream() .filter(buildRuleInfo -> buildRuleInfo.dependents.isEmpty()) .collect(Collectors.toList()); } @Override public Iterable<BuildRuleInfo> getNodesWithNoOutgoingEdges() { return getBuildRuleInfos() .stream() .filter(buildRuleInfo -> buildRuleInfo.dependencies.isEmpty()) .collect(Collectors.toList()); } /** Ignoring nodes, they are not in buildRuleInfos, since not received a start event for them */ @Override public Iterable<BuildRuleInfo> getIncomingNodesFor(BuildRuleInfo sink) { return sink.dependents .stream() .filter(buildRuleInfos::containsKey) // Ignoring Rules without Start event .map(buildRuleInfos::get) .collect(Collectors.toList()); } /** Ignoring nodes, they are not in buildRuleInfos, since not received a start event for them */ @Override public Iterable<BuildRuleInfo> getOutgoingNodesFor(BuildRuleInfo source) { return source .dependencies .stream() .filter(buildRuleInfos::containsKey) // Ignoring Rules without Start event .map(buildRuleInfos::get) .collect(Collectors.toList()); } @Override public Iterable<BuildRuleInfo> getNodes() { return getBuildRuleInfos(); } private Collection<BuildRuleInfo> getBuildRuleInfos() { return buildRuleInfos.values(); } } /** An entry in the critical path of the target. */ @Value.Immutable(copy = false, builder = false) @JsonSerialize(as = ImmutableCriticalPathEntry.class) interface CriticalPathEntry { @JsonProperty("rule-name") @Value.Parameter String ruleName(); @JsonProperty("start") @Value.Parameter long startTimestamp(); @JsonProperty("finish") @Value.Parameter long finishTimestamp(); @JsonProperty("duration") @Value.Parameter long duration(); @Value.Parameter @JsonIgnore long wholeDuration(); @Value.Parameter @JsonIgnore long longest(); @Value.Parameter @JsonIgnore Optional<BuildRuleInfo> prev(); @Value.Parameter @JsonIgnore List<ImmutableBuildRuleEventInterval> intervals(); } /** Used to keep top k critical paths, and serialize as json. */ @Value.Immutable(copy = false, builder = false) @JsonSerialize(as = ImmutableBuildRuleCriticalPath.class) interface BuildRuleCriticalPath { @JsonProperty("target-name") @Value.Parameter String targetName(); @JsonProperty("target-duration") @Value.Parameter long targetDuration(); @JsonProperty("critical-path") @Value.Parameter ImmutableList<CriticalPathEntry> criticalPath(); @JsonProperty("critical-path-duration") @Value.Parameter long criticalPathDuration(); } /** Used to keep duration for each test target, and serialize as json. */ @Value.Immutable(copy = false, builder = false) @JsonSerialize(as = ImmutableBuildTargetResult.class) interface BuildTargetResult { @JsonProperty("target-name") @Value.Parameter String targetName(); @JsonProperty("target-duration") @Value.Parameter long targetDuration(); } /** * An entry to hold selected {@link BuildRuleInfo.Chain} chain from k chains of a {@link * BuildRuleInfo}. */ @Value.Immutable(copy = false, builder = false) interface BuildRuleInfoSelectedChain { @Value.Parameter BuildRuleInfo buildRuleInfo(); @Value.Parameter BuildRuleInfo.Chain chain(); } /** An entry to hold interval of {@link BuildRuleEvent}. */ @Value.Immutable(copy = false, builder = false) interface BuildRuleEventInterval { @Value.Parameter long start(); @Value.Parameter long end(); } /** * Similar to {@link com.facebook.buck.distributed.build_slave.DistBuildTrace.RuleTrace} keeps * information regarding {@link BuildRule}. Start, End times and dependents, dependencies of this * {@link BuildRule}. */ public static class BuildRuleInfo { private final String ruleName; private final long startEpochMillis; private long finishEpochMillis; private long duration; private final Set<String> dependents; private final Set<String> dependencies; private final List<ImmutableBuildRuleEventInterval> intervals; private MinMaxPriorityQueue<Chain> chain; /** * Keeps a pointer to previous {@link BuildRuleInfo} and its time. Implements {@link Comparable} * interface in natural order. */ static class Chain implements Comparable<Chain> { private final long longest; private final Optional<BuildRuleInfo> prev; public Chain(long longest, Optional<BuildRuleInfo> prev) { this.longest = longest; this.prev = prev; } public long getLongest() { return longest; } public Optional<BuildRuleInfo> getPrev() { return prev; } @Override public int compareTo(Chain other) { return Long.compare(this.longest, other.longest); } @Override public String toString() { return "Chain{" + "longest=" + longest + ", prev=" + (prev.isPresent() ? prev.get() : "none") + '}'; } } public BuildRuleInfo(String ruleName, int k, long startEpochMillis, long finishEpochMillis) { this.ruleName = ruleName; this.startEpochMillis = startEpochMillis; this.finishEpochMillis = finishEpochMillis; this.duration = 0; this.dependents = Sets.newHashSet(); this.dependencies = Sets.newHashSet(); this.chain = MinMaxPriorityQueue.orderedBy(Collections.reverseOrder()).maximumSize(k).create(); this.intervals = Lists.newArrayList(); } public void addDependent(String dependent) { this.dependents.add(dependent); } public boolean noDependent() { return this.dependents.isEmpty(); } public void addDependency(String dependency) { this.dependencies.add(dependency); } public void updateFinish(long finishEpochMillis) { this.finishEpochMillis = Math.max(finishEpochMillis, this.finishEpochMillis); } public void addBuildRuleEventInterval(long startEpochMicros, long finishEpochMicros) { this.intervals.add(ImmutableBuildRuleEventInterval.of(startEpochMicros, finishEpochMicros)); } public void updateDuration(long duration) { this.duration += duration; } public long getDuration() { return duration; } public long getWholeTargetDuration() { return this.finishEpochMillis - this.startEpochMillis; } public String getRuleName() { return ruleName; } public MinMaxPriorityQueue<Chain> getChain() { return chain; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } BuildRuleInfo that = (BuildRuleInfo) o; return Objects.equal(ruleName, that.ruleName); } @Override public int hashCode() { return Objects.hashCode(ruleName); } @Override public String toString() { return "BuildRuleInfo{" + "ruleName='" + ruleName + '\'' + '}'; } } }
UTF-8
Java
29,706
java
BuildTargetDurationListener.java
Java
[]
null
[]
/* * Copyright 2018-present Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.facebook.buck.event.listener; import com.facebook.buck.core.build.event.BuildEvent.RuleCountCalculated; import com.facebook.buck.core.build.event.BuildRuleEvent; import com.facebook.buck.core.build.event.BuildRuleEvent.BeginningBuildRuleEvent; import com.facebook.buck.core.build.event.BuildRuleEvent.EndingBuildRuleEvent; import com.facebook.buck.core.model.BuildTarget; import com.facebook.buck.core.model.actiongraph.ActionGraph; import com.facebook.buck.core.rules.BuildRule; import com.facebook.buck.core.util.graph.AbstractBottomUpTraversal; import com.facebook.buck.core.util.graph.TraversableGraph; import com.facebook.buck.core.util.immutables.BuckStyleImmutable; import com.facebook.buck.core.util.log.Logger; import com.facebook.buck.event.ActionGraphEvent; import com.facebook.buck.event.BuckEventListener; import com.facebook.buck.event.chrome_trace.ChromeTraceEvent; import com.facebook.buck.event.chrome_trace.ChromeTraceEvent.Phase; import com.facebook.buck.event.chrome_trace.ChromeTraceWriter; import com.facebook.buck.io.filesystem.ProjectFilesystem; import com.facebook.buck.log.InvocationInfo; import com.facebook.buck.support.bgtasks.BackgroundTask; import com.facebook.buck.support.bgtasks.ImmutableBackgroundTask; import com.facebook.buck.support.bgtasks.TaskAction; import com.facebook.buck.support.bgtasks.TaskManagerScope; import com.facebook.buck.support.bgtasks.Timeout; import com.facebook.buck.util.json.ObjectMappers; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Objects; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.MinMaxPriorityQueue; import com.google.common.collect.Queues; import com.google.common.collect.Sets; import com.google.common.eventbus.Subscribe; import java.io.BufferedOutputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.nio.file.Path; import java.util.Collection; import java.util.Collections; import java.util.Deque; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import org.immutables.value.Value; /** * Listens {@link ActionGraphEvent.Finished} to get {@link ActionGraph}, {@link BuildRuleEvent} to * trace {@link BuildRule} to compute critical path for test targets. */ public class BuildTargetDurationListener implements BuckEventListener { private static final Logger LOG = Logger.get(BuildTargetDurationListener.class); public static final String CRITICAL_PATH_FILE_NAME = "critical-path"; public static final String CRITICAL_PATH_TRACE_FILE_NAME = "critical-path.trace"; public static final String TARGETS_BUILD_TIMES_FILE_NAME = "targets-build-times"; private static final int SHUTDOWN_TIMEOUT_SECONDS = 60; private final InvocationInfo info; private final ProjectFilesystem filesystem; private final int criticalPathCount; private final TaskManagerScope managerScope; private Optional<ActionGraph> actionGraph = Optional.empty(); private Optional<ImmutableSet<BuildTarget>> targetBuildRules = Optional.empty(); @VisibleForTesting ConcurrentMap<String, BuildRuleInfo> getBuildRuleInfos() { return buildRuleInfos; } // Hold the latest one for the target private ConcurrentMap<String, BuildRuleInfo> buildRuleInfos = Maps.newConcurrentMap(); public BuildTargetDurationListener( InvocationInfo info, ProjectFilesystem filesystem, int criticalPathCount, TaskManagerScope managerScope) { this.info = info; this.filesystem = filesystem; this.criticalPathCount = criticalPathCount; this.managerScope = managerScope; } /** Save start of the {@link BuildRuleEvent}. */ @Subscribe public void buildRuleEventStarted(BuildRuleEvent.Started event) { final String buildRuleName = event.getBuildRule().getFullyQualifiedName(); final long startEpochMillis = event.getTimestamp(); Preconditions.checkState( !buildRuleInfos.containsKey(buildRuleName), "There can not be more than one BuildRuleEvent.Started for the %s BuildRule.", buildRuleName); LOG.info("BuildRuleEventStarted{name=%s, time=%d}", buildRuleName, startEpochMillis); BuildRuleInfo ruleInfo = new BuildRuleInfo(buildRuleName, criticalPathCount, startEpochMillis, startEpochMillis); buildRuleInfos.put(buildRuleName, ruleInfo); event .getBuildRule() .getBuildDeps() .stream() .map(BuildRule::getFullyQualifiedName) .forEach(ruleInfo::addDependency); } /** * Save end of the {@link BuildRuleEvent} for {@link * com.facebook.buck.event.RuleKeyCalculationEvent}. */ @Subscribe public synchronized void buildRuleEventSuspended(BuildRuleEvent.Suspended event) { LOG.info( "BuildRuleEventSuspended{name=%s, time=%d}", event.getBuildRule().getFullyQualifiedName(), event.getTimestamp()); saveEndOfBuildRuleEvent( event.getBuildRule().getFullyQualifiedName(), event.getBeginningEvent(), event); } /** Save end of the {@link BuildRuleEvent}. */ @Subscribe public synchronized void buildRuleEventFinished(BuildRuleEvent.Finished event) { LOG.info( "BuildRuleEventFinished{name=%s, time=%d}", event.getBuildRule().getFullyQualifiedName(), event.getTimestamp()); saveEndOfBuildRuleEvent( event.getBuildRule().getFullyQualifiedName(), event.getBeginningEvent(), event); } /** Update end of the {@link BuildRuleEvent}. */ private void saveEndOfBuildRuleEvent( String buildRuleName, BeginningBuildRuleEvent begin, EndingBuildRuleEvent end) { Preconditions.checkState( buildRuleInfos.containsKey(buildRuleName), "First, a BuildRuleEvent %s has to start in order to finish.", buildRuleName); BuildRuleInfo currentBuildRuleInfo = buildRuleInfos.get(buildRuleName); currentBuildRuleInfo.updateDuration(end.getDuration().getWallMillisDuration()); currentBuildRuleInfo.updateFinish(end.getTimestamp()); currentBuildRuleInfo.addBuildRuleEventInterval( TimeUnit.NANOSECONDS.toMicros(begin.getNanoTime()), TimeUnit.NANOSECONDS.toMicros(end.getNanoTime())); } /** Save the {@link ActionGraph} */ @Subscribe public synchronized void actionGraphFinished(ActionGraphEvent.Finished finished) { actionGraph = finished.getActionGraph(); } @Subscribe public synchronized void ruleCountCalculated(RuleCountCalculated ruleCountCalculated) { targetBuildRules = Optional.of(ruleCountCalculated.getBuildRules()); } private Path getLogFilePath() { return filesystem.resolve(info.getBuckLogDir()).resolve(CRITICAL_PATH_FILE_NAME); } private Path getTraceFilePath() { return filesystem.resolve(info.getBuckLogDir()).resolve(CRITICAL_PATH_TRACE_FILE_NAME); } private Path getTargetFilePath() { return filesystem.resolve(info.getBuckLogDir()).resolve(TARGETS_BUILD_TIMES_FILE_NAME); } @VisibleForTesting static ImmutableList<ImmutableBuildRuleCriticalPath> constructBuildRuleCriticalPaths( List<Deque<CriticalPathEntry>> criticalPaths) { ImmutableList.Builder<ImmutableBuildRuleCriticalPath> criticalPathsBuilder = ImmutableList.builder(); for (Deque<CriticalPathEntry> path : criticalPaths) { CriticalPathEntry last = path.getLast(); criticalPathsBuilder.add( ImmutableBuildRuleCriticalPath.of( last.ruleName(), last.wholeDuration(), path, last.longest())); } return criticalPathsBuilder.build(); } @VisibleForTesting static ImmutableList<Deque<CriticalPathEntry>> constructCriticalPaths( Collection<BuildRuleInfo> rootBuildRuleInfos, int k) { MinMaxPriorityQueue<BuildRuleInfoSelectedChain> topK = findCriticalNodes(rootBuildRuleInfos, k); Map<BuildRuleInfo, Set<BuildRuleInfo.Chain>> usedChainsMap = Maps.newHashMap(); ImmutableList.Builder<Deque<CriticalPathEntry>> criticalPaths = ImmutableList.builder(); while (!topK.isEmpty()) { BuildRuleInfoSelectedChain root = topK.poll(); Set<BuildRuleInfo.Chain> usedChains = usedChainsMap.getOrDefault(root.buildRuleInfo(), Sets.newHashSet()); criticalPaths.add(criticalPath(root.chain(), root.buildRuleInfo(), usedChains)); } return criticalPaths.build(); } @VisibleForTesting static void rendersCriticalPathsTraceFile( List<Deque<CriticalPathEntry>> criticalPaths, OutputStream os) { try (ChromeTraceWriter traceWriter = new ChromeTraceWriter(os)) { traceWriter.writeStart(); traceWriter.writeEvent( new ChromeTraceEvent( "buck", "process_name", Phase.METADATA, 0, 0, 0, 0, ImmutableMap.of("name", "Critical Path"))); rendersCriticalPaths(criticalPaths, traceWriter); traceWriter.writeEnd(); } catch (IOException e) { LOG.error(e, "Could not write critical path to trace file."); } } private static void rendersCriticalPaths( List<Deque<CriticalPathEntry>> criticalPaths, ChromeTraceWriter traceWriter) throws IOException { int threadId = 0; for (Deque<CriticalPathEntry> path : criticalPaths) { for (CriticalPathEntry criticalPathEntry : path) { rendersCriticalPathEntry(criticalPathEntry, traceWriter, threadId); } ++threadId; } } /** * Renders rule in a similar way to {@link * com.facebook.buck.distributed.build_slave.DistBuildChromeTraceRenderer#renderRule}. */ private static void rendersCriticalPathEntry( CriticalPathEntry criticalPathEntry, ChromeTraceWriter traceWriter, int tid) throws IOException { for (BuildRuleEventInterval interval : criticalPathEntry.intervals()) { long end = interval.end() > interval.start() ? interval.end() : interval.start() + 1; ImmutableMap<String, String> startArgs = ImmutableMap.of( "critical_blocking_rule", criticalPathEntry.prev().map(rule -> rule.ruleName).orElse("None"), "length_of_critical_path", String.format("%dms", criticalPathEntry.longest())); traceWriter.writeEvent( new ChromeTraceEvent( "buck", criticalPathEntry.ruleName(), Phase.BEGIN, 0, tid, interval.start(), 0, startArgs)); traceWriter.writeEvent( new ChromeTraceEvent( "buck", criticalPathEntry.ruleName(), Phase.END, 0, tid, end, 0, ImmutableMap.of())); } } @Override public synchronized void close() { BuildTargetDurationListenerCloseArgs args = BuildTargetDurationListenerCloseArgs.builder() .setLogFilePath(getLogFilePath()) .setTargetFilePath(getTargetFilePath()) .setTraceFilePath(getTraceFilePath()) .setInvocationInfo(info) .setCriticalPathCount(criticalPathCount) .setTargetBuildRules(targetBuildRules) .setBuildRuleInfos(buildRuleInfos) .setActionGraph(actionGraph) .build(); BackgroundTask<BuildTargetDurationListenerCloseArgs> task = ImmutableBackgroundTask.<BuildTargetDurationListenerCloseArgs>builder() .setAction(new BuildTargetDurationListenerCloseAction()) .setActionArgs(args) .setName("BuildTargetDurationListener_close") .setTimeout(Timeout.of(SHUTDOWN_TIMEOUT_SECONDS, TimeUnit.SECONDS)) .build(); managerScope.schedule(task); } /** {@link TaskAction} implementation for closing {@link BuildTargetDurationListener}. */ static class BuildTargetDurationListenerCloseAction implements TaskAction<BuildTargetDurationListenerCloseArgs> { @Override public void run(BuildTargetDurationListenerCloseArgs args) { try (BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(args.getLogFilePath().toFile())); BufferedOutputStream targetStream = new BufferedOutputStream(new FileOutputStream(args.getTargetFilePath().toFile()))) { LOG.info("Starting critical path calculation for %s", args.getInvocationInfo()); LOG.info("Writing critical path to %s", args.getLogFilePath().toString()); if (args.getActionGraph().isPresent()) { updateBuildRuleInfosWithDependents(args.getActionGraph(), args.getBuildRuleInfos()); computeCriticalPathsUsingGraphTraversal(args.getBuildRuleInfos()); // Find root build rules Collection<BuildRuleInfo> rootBuildRuleInfos = Lists.newArrayList(); if (args.getTargetBuildRules().isPresent()) { for (BuildTarget buildTarget : args.getTargetBuildRules().get()) { BuildRuleInfo buildRuleInfo = args.getBuildRuleInfos().get(buildTarget.getFullyQualifiedName()); if (buildRuleInfo != null) { rootBuildRuleInfos.add(buildRuleInfo); } else { LOG.warn( "Could not find build rule for the target %s!", buildTarget.getFullyQualifiedName()); } } } else { LOG.warn("There were not any target, construction of critical paths will be skipped."); } List<Deque<CriticalPathEntry>> kCriticalPaths = constructCriticalPaths(rootBuildRuleInfos, args.getCriticalPathCount()); // Render chrome trace of the critical path of the longest rendersCriticalPaths(args.getTraceFilePath(), kCriticalPaths); // Serialize BuildRuleCriticalPaths ObjectMappers.WRITER.writeValue( outputStream, constructBuildRuleCriticalPaths(kCriticalPaths)); // Serialize BuildTargetResults ObjectMappers.WRITER.writeValue( targetStream, constructBuildTargetResults(rootBuildRuleInfos)); LOG.info("Critical path and target results have been written successfully."); } else { ObjectMappers.WRITER.writeValue(outputStream, Collections.emptyList()); LOG.warn("There was no action graph, computation is skipped."); } } catch (IOException e) { LOG.warn(e, "Could not complete IO Request."); } } private void rendersCriticalPaths( Path traceFilePath, List<Deque<CriticalPathEntry>> criticalPaths) throws IOException { try (FileOutputStream fos = new FileOutputStream(traceFilePath.toFile())) { rendersCriticalPathsTraceFile(criticalPaths, fos); } } private void updateBuildRuleInfosWithDependents( Optional<ActionGraph> actionGraph, ConcurrentMap<String, BuildRuleInfo> buildRuleInfos) { if (!actionGraph.isPresent()) { return; } for (BuildRule buildRule : actionGraph.get().getNodes()) { // for each dependency include a back-edge from dependency to dependent buildRule .getBuildDeps() .forEach( dependency -> { BuildRuleInfo dependencyBuildRuleInfo = buildRuleInfos.get(dependency.getFullyQualifiedName()); // It might not exist if a BuildRuleEvent is not executed! if (dependencyBuildRuleInfo != null) { dependencyBuildRuleInfo.addDependent(buildRule.getFullyQualifiedName()); } }); } } } /** Arguments to {@link BuildTargetDurationListenerCloseAction}. */ @Value.Immutable @BuckStyleImmutable abstract static class AbstractBuildTargetDurationListenerCloseArgs { @Value.Parameter public abstract Path getLogFilePath(); @Value.Parameter public abstract Path getTargetFilePath(); @Value.Parameter public abstract Path getTraceFilePath(); @Value.Parameter public abstract InvocationInfo getInvocationInfo(); @Value.Parameter public abstract int getCriticalPathCount(); @Value.Parameter public abstract Optional<ImmutableSet<BuildTarget>> getTargetBuildRules(); @Value.Parameter public abstract ConcurrentMap<String, BuildRuleInfo> getBuildRuleInfos(); @Value.Parameter public abstract Optional<ActionGraph> getActionGraph(); } /** Construct {@link BuildTargetResult} list for all given roots. */ @VisibleForTesting static ImmutableList<ImmutableBuildTargetResult> constructBuildTargetResults( Collection<BuildRuleInfo> rootBuildRuleInfos) { ImmutableList.Builder<ImmutableBuildTargetResult> buildTargetResults = ImmutableList.builder(); for (BuildRuleInfo buildRuleInfo : rootBuildRuleInfos) { buildTargetResults.add( ImmutableBuildTargetResult.of( buildRuleInfo.ruleName, buildRuleInfo.getWholeTargetDuration())); } return buildTargetResults.build(); } /** Modifies {@link BuildRuleInfo#chain} to save the longest paths. */ @VisibleForTesting static BuildRuleInfoGraph computeCriticalPathsUsingGraphTraversal( Map<String, BuildRuleInfo> buildRuleInfos) throws IOException { BuildRuleInfoGraph graph = new BuildRuleInfoGraph(buildRuleInfos); for (BuildRuleInfo buildRuleInfo : graph.getNodesWithNoOutgoingEdges()) { buildRuleInfo.chain.add( new BuildRuleInfo.Chain(buildRuleInfo.getDuration(), Optional.empty())); } new BuildRuleInfoGraphTraversal(graph).traverse(); return graph; } /** Finds top K critical nodes and corresponding chain for the critical paths. */ @VisibleForTesting static MinMaxPriorityQueue<BuildRuleInfoSelectedChain> findCriticalNodes( Iterable<BuildRuleInfo> rootRules, int k) { MinMaxPriorityQueue<BuildRuleInfoSelectedChain> topK = MinMaxPriorityQueue.orderedBy( (BuildRuleInfoSelectedChain first, BuildRuleInfoSelectedChain second) -> Long.compare(second.chain().longest, first.chain().longest)) .maximumSize(k) .create(); for (BuildRuleInfo ruleInfo : rootRules) { for (BuildRuleInfo.Chain chain : ruleInfo.chain) { topK.add(ImmutableBuildRuleInfoSelectedChain.of(ruleInfo, chain)); } } return topK; } /** * Construct the critical path to the target coming from the given chain. usedChain prevents * duplicate paths. */ @VisibleForTesting static Deque<CriticalPathEntry> criticalPath( BuildRuleInfo.Chain chain, BuildRuleInfo target, Set<BuildRuleInfo.Chain> usedChains) { Deque<CriticalPathEntry> path = Queues.newArrayDeque(); path.push( ImmutableCriticalPathEntry.of( target.ruleName, target.startEpochMillis, target.finishEpochMillis, target.getDuration(), target.getWholeTargetDuration(), chain.longest, chain.prev, target.intervals)); long longest = chain.longest; Optional<BuildRuleInfo> prev = chain.prev; while (prev.isPresent()) { chain = null; longest -= target.getDuration(); target = prev.get(); /** Search for previous {@link BuildRuleInfo} matching longest and not selected before. */ for (BuildRuleInfo.Chain c : target.chain) { if (c.longest == longest && !usedChains.contains(c)) { chain = c; usedChains.add(c); break; } } prev = chain != null ? chain.prev : Optional.empty(); longest = chain != null ? chain.longest : 0L; path.push( ImmutableCriticalPathEntry.of( target.ruleName, target.startEpochMillis, target.finishEpochMillis, target.getDuration(), target.getWholeTargetDuration(), longest, prev, target.intervals)); } return path; } /** Class extending {@link AbstractBottomUpTraversal} to do traversal bottom up. */ public static class BuildRuleInfoGraphTraversal extends AbstractBottomUpTraversal<BuildRuleInfo, IOException> { private BuildRuleInfoGraph graph; public BuildRuleInfoGraphTraversal(BuildRuleInfoGraph graph) { super(graph); this.graph = graph; } @Override public void visit(BuildRuleInfo currentBuildRuleInfo) { for (BuildRuleInfo neigborBuildRuleInfo : graph.getOutgoingNodesFor(currentBuildRuleInfo)) { for (BuildRuleInfo.Chain c : neigborBuildRuleInfo.chain) { currentBuildRuleInfo.chain.add( new BuildRuleInfo.Chain( c.longest + currentBuildRuleInfo.getDuration(), Optional.of(neigborBuildRuleInfo))); } } } } /** Implementing {@link TraversableGraph} interface. */ public static class BuildRuleInfoGraph implements TraversableGraph<BuildRuleInfo> { private Map<String, BuildRuleInfo> buildRuleInfos; public BuildRuleInfoGraph(Map<String, BuildRuleInfo> buildRuleInfos) { this.buildRuleInfos = buildRuleInfos; } @Override public Iterable<BuildRuleInfo> getNodesWithNoIncomingEdges() { return getBuildRuleInfos() .stream() .filter(buildRuleInfo -> buildRuleInfo.dependents.isEmpty()) .collect(Collectors.toList()); } @Override public Iterable<BuildRuleInfo> getNodesWithNoOutgoingEdges() { return getBuildRuleInfos() .stream() .filter(buildRuleInfo -> buildRuleInfo.dependencies.isEmpty()) .collect(Collectors.toList()); } /** Ignoring nodes, they are not in buildRuleInfos, since not received a start event for them */ @Override public Iterable<BuildRuleInfo> getIncomingNodesFor(BuildRuleInfo sink) { return sink.dependents .stream() .filter(buildRuleInfos::containsKey) // Ignoring Rules without Start event .map(buildRuleInfos::get) .collect(Collectors.toList()); } /** Ignoring nodes, they are not in buildRuleInfos, since not received a start event for them */ @Override public Iterable<BuildRuleInfo> getOutgoingNodesFor(BuildRuleInfo source) { return source .dependencies .stream() .filter(buildRuleInfos::containsKey) // Ignoring Rules without Start event .map(buildRuleInfos::get) .collect(Collectors.toList()); } @Override public Iterable<BuildRuleInfo> getNodes() { return getBuildRuleInfos(); } private Collection<BuildRuleInfo> getBuildRuleInfos() { return buildRuleInfos.values(); } } /** An entry in the critical path of the target. */ @Value.Immutable(copy = false, builder = false) @JsonSerialize(as = ImmutableCriticalPathEntry.class) interface CriticalPathEntry { @JsonProperty("rule-name") @Value.Parameter String ruleName(); @JsonProperty("start") @Value.Parameter long startTimestamp(); @JsonProperty("finish") @Value.Parameter long finishTimestamp(); @JsonProperty("duration") @Value.Parameter long duration(); @Value.Parameter @JsonIgnore long wholeDuration(); @Value.Parameter @JsonIgnore long longest(); @Value.Parameter @JsonIgnore Optional<BuildRuleInfo> prev(); @Value.Parameter @JsonIgnore List<ImmutableBuildRuleEventInterval> intervals(); } /** Used to keep top k critical paths, and serialize as json. */ @Value.Immutable(copy = false, builder = false) @JsonSerialize(as = ImmutableBuildRuleCriticalPath.class) interface BuildRuleCriticalPath { @JsonProperty("target-name") @Value.Parameter String targetName(); @JsonProperty("target-duration") @Value.Parameter long targetDuration(); @JsonProperty("critical-path") @Value.Parameter ImmutableList<CriticalPathEntry> criticalPath(); @JsonProperty("critical-path-duration") @Value.Parameter long criticalPathDuration(); } /** Used to keep duration for each test target, and serialize as json. */ @Value.Immutable(copy = false, builder = false) @JsonSerialize(as = ImmutableBuildTargetResult.class) interface BuildTargetResult { @JsonProperty("target-name") @Value.Parameter String targetName(); @JsonProperty("target-duration") @Value.Parameter long targetDuration(); } /** * An entry to hold selected {@link BuildRuleInfo.Chain} chain from k chains of a {@link * BuildRuleInfo}. */ @Value.Immutable(copy = false, builder = false) interface BuildRuleInfoSelectedChain { @Value.Parameter BuildRuleInfo buildRuleInfo(); @Value.Parameter BuildRuleInfo.Chain chain(); } /** An entry to hold interval of {@link BuildRuleEvent}. */ @Value.Immutable(copy = false, builder = false) interface BuildRuleEventInterval { @Value.Parameter long start(); @Value.Parameter long end(); } /** * Similar to {@link com.facebook.buck.distributed.build_slave.DistBuildTrace.RuleTrace} keeps * information regarding {@link BuildRule}. Start, End times and dependents, dependencies of this * {@link BuildRule}. */ public static class BuildRuleInfo { private final String ruleName; private final long startEpochMillis; private long finishEpochMillis; private long duration; private final Set<String> dependents; private final Set<String> dependencies; private final List<ImmutableBuildRuleEventInterval> intervals; private MinMaxPriorityQueue<Chain> chain; /** * Keeps a pointer to previous {@link BuildRuleInfo} and its time. Implements {@link Comparable} * interface in natural order. */ static class Chain implements Comparable<Chain> { private final long longest; private final Optional<BuildRuleInfo> prev; public Chain(long longest, Optional<BuildRuleInfo> prev) { this.longest = longest; this.prev = prev; } public long getLongest() { return longest; } public Optional<BuildRuleInfo> getPrev() { return prev; } @Override public int compareTo(Chain other) { return Long.compare(this.longest, other.longest); } @Override public String toString() { return "Chain{" + "longest=" + longest + ", prev=" + (prev.isPresent() ? prev.get() : "none") + '}'; } } public BuildRuleInfo(String ruleName, int k, long startEpochMillis, long finishEpochMillis) { this.ruleName = ruleName; this.startEpochMillis = startEpochMillis; this.finishEpochMillis = finishEpochMillis; this.duration = 0; this.dependents = Sets.newHashSet(); this.dependencies = Sets.newHashSet(); this.chain = MinMaxPriorityQueue.orderedBy(Collections.reverseOrder()).maximumSize(k).create(); this.intervals = Lists.newArrayList(); } public void addDependent(String dependent) { this.dependents.add(dependent); } public boolean noDependent() { return this.dependents.isEmpty(); } public void addDependency(String dependency) { this.dependencies.add(dependency); } public void updateFinish(long finishEpochMillis) { this.finishEpochMillis = Math.max(finishEpochMillis, this.finishEpochMillis); } public void addBuildRuleEventInterval(long startEpochMicros, long finishEpochMicros) { this.intervals.add(ImmutableBuildRuleEventInterval.of(startEpochMicros, finishEpochMicros)); } public void updateDuration(long duration) { this.duration += duration; } public long getDuration() { return duration; } public long getWholeTargetDuration() { return this.finishEpochMillis - this.startEpochMillis; } public String getRuleName() { return ruleName; } public MinMaxPriorityQueue<Chain> getChain() { return chain; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } BuildRuleInfo that = (BuildRuleInfo) o; return Objects.equal(ruleName, that.ruleName); } @Override public int hashCode() { return Objects.hashCode(ruleName); } @Override public String toString() { return "BuildRuleInfo{" + "ruleName='" + ruleName + '\'' + '}'; } } }
29,706
0.694977
0.694237
819
35.271061
27.702938
100
false
false
0
0
0
0
0
0
0.483516
false
false
2
42ccb48808b543ac6de93598853c669a8226809b
34,411,278,034,175
96d2f17b0b308a7bb91bbc72f7c42a01e3ae24ea
/src/main/java/com/sumang/rewards/demo/model/Transactions.java
49095ce263b8217eeee73b5eb7f7c78d21bcd057
[]
no_license
suman-ghimire/CalculateRewardPoints
https://github.com/suman-ghimire/CalculateRewardPoints
6889dda5d0d0ba841056e4394ee12570848fb1df
1e492db68bf8d239ab628ffe8e5e8c18149e92da
refs/heads/master
2023-04-20T06:50:41.820000
2021-05-09T19:33:49
2021-05-09T19:33:49
365,594,688
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.sumang.rewards.demo.model; import com.fasterxml.jackson.annotation.JsonIgnore; import javax.persistence.*; import java.time.LocalDateTime; import java.util.Date; @Entity public class Transactions extends Rewards{ @Id @GeneratedValue private Long id; @JsonIgnore @ManyToOne @JoinColumn private Customer customer; private Double total; private LocalDateTime purchaseDate; public Transactions() { super(); } public Transactions(Long id, Customer customer, Double total, LocalDateTime purchaseDate) { this.id = id; this.customer = customer; this.total = total; this.purchaseDate = purchaseDate; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Customer getCustomer() { return customer; } public void setCustomer(Customer customer) { this.customer = customer; } public Double getTotal() { return total; } public void setTotal(Double total) { this.total = total; } public LocalDateTime getPurchaseDate() { return purchaseDate; } public void setPurchaseDate(LocalDateTime purchaseDate) { this.purchaseDate = purchaseDate; } @Override public Long getRewardPoints() { this.points = 0l; if (this.total > 50 && this.total <= 100) { this.points += (this.total.intValue() - 50) * 1; } if (this.total > 100) { this.points += 50; this.points += (this.total.intValue() - 100) * 2; } return this.points; } @Override public String toString() { return "Transactions{" + "id=" + id + ", customer=" + customer + ", total=" + total + ", purchase_date=" + purchaseDate + '}'; } }
UTF-8
Java
1,945
java
Transactions.java
Java
[]
null
[]
package com.sumang.rewards.demo.model; import com.fasterxml.jackson.annotation.JsonIgnore; import javax.persistence.*; import java.time.LocalDateTime; import java.util.Date; @Entity public class Transactions extends Rewards{ @Id @GeneratedValue private Long id; @JsonIgnore @ManyToOne @JoinColumn private Customer customer; private Double total; private LocalDateTime purchaseDate; public Transactions() { super(); } public Transactions(Long id, Customer customer, Double total, LocalDateTime purchaseDate) { this.id = id; this.customer = customer; this.total = total; this.purchaseDate = purchaseDate; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Customer getCustomer() { return customer; } public void setCustomer(Customer customer) { this.customer = customer; } public Double getTotal() { return total; } public void setTotal(Double total) { this.total = total; } public LocalDateTime getPurchaseDate() { return purchaseDate; } public void setPurchaseDate(LocalDateTime purchaseDate) { this.purchaseDate = purchaseDate; } @Override public Long getRewardPoints() { this.points = 0l; if (this.total > 50 && this.total <= 100) { this.points += (this.total.intValue() - 50) * 1; } if (this.total > 100) { this.points += 50; this.points += (this.total.intValue() - 100) * 2; } return this.points; } @Override public String toString() { return "Transactions{" + "id=" + id + ", customer=" + customer + ", total=" + total + ", purchase_date=" + purchaseDate + '}'; } }
1,945
0.571722
0.562468
91
20.373627
18.764971
95
false
false
0
0
0
0
0
0
0.373626
false
false
2
36027ee7f5ee52c5ce07f1ed2754d6e60199aa62
39,513,699,129,606
9331e730c574c381282d2748c44727e7e4b6390c
/biz/src/main/java/com/jet/realestate/biz/model/Order.java
061f29fbc680989b46d497c3810ddf59ccafeccd
[]
no_license
jet-cabin/realestate
https://github.com/jet-cabin/realestate
b6185ddd684956b23b0a2a25b5c395ddbb66ea52
7eaffdb8e3ecd220c5f4a0da7769d1b21434743f
refs/heads/master
2022-12-11T22:43:37.504000
2020-05-03T04:04:16
2020-05-03T04:04:16
230,552,533
1
0
null
false
2022-12-09T01:39:17
2019-12-28T03:24:44
2020-05-03T04:08:07
2022-12-09T01:39:17
2,856
1
0
11
Java
false
false
package com.jet.realestate.biz.model; import com.jet.realestate.biz.common.OrderStatus; import lombok.Data; import java.time.LocalDateTime; @Data public class Order { private Long id; private String code; private LocalDateTime createTime; private Long vendeeId; private Long houseId; private Integer price; private String note; private OrderStatus status; }
UTF-8
Java
401
java
Order.java
Java
[]
null
[]
package com.jet.realestate.biz.model; import com.jet.realestate.biz.common.OrderStatus; import lombok.Data; import java.time.LocalDateTime; @Data public class Order { private Long id; private String code; private LocalDateTime createTime; private Long vendeeId; private Long houseId; private Integer price; private String note; private OrderStatus status; }
401
0.730673
0.730673
26
14.423077
15.150966
49
false
false
0
0
0
0
0
0
0.461538
false
false
2
78f2534e0bdc31aae0717c3730f047d17608836f
39,591,008,539,815
893292d9eddabf3c037793ab91e54479419cd2a1
/java/valid-parens/src/tests/SolutionTest.java
c212d8ce84348e5d5dd07d919f8c8da0f382978d
[]
no_license
rileymiller/l337-practice
https://github.com/rileymiller/l337-practice
775383bcd5bb60b85028116e12f93696233965e9
c9df67998bd68210b146545e2d43dc20c33d2e19
refs/heads/master
2023-07-11T12:54:30.571000
2023-07-05T17:43:22
2023-07-05T17:43:22
293,720,829
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import main.Solution; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; public class SolutionTest { @Test void BasicParensTest() { Solution sol = new Solution(); assertEquals(true, sol.isValid("()")); } @Test void MismatchTest() { Solution sol = new Solution(); assertEquals(false, sol.isValid("(]")); } @Test void SingleCharTest() { Solution sol = new Solution(); assertEquals(false, sol.isValid("(")); } @Test void ComplexMismatchTest() { Solution sol = new Solution(); assertEquals(false, sol.isValid("([)]")); } @Test void OrderedCharsTest() { Solution sol = new Solution(); assertEquals(true, sol.isValid("{[]}")); } @Test void ImmediateClosedCharsTest() { Solution sol = new Solution(); assertEquals(true, sol.isValid("()[]{}")); } }
UTF-8
Java
955
java
SolutionTest.java
Java
[]
null
[]
import main.Solution; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; public class SolutionTest { @Test void BasicParensTest() { Solution sol = new Solution(); assertEquals(true, sol.isValid("()")); } @Test void MismatchTest() { Solution sol = new Solution(); assertEquals(false, sol.isValid("(]")); } @Test void SingleCharTest() { Solution sol = new Solution(); assertEquals(false, sol.isValid("(")); } @Test void ComplexMismatchTest() { Solution sol = new Solution(); assertEquals(false, sol.isValid("([)]")); } @Test void OrderedCharsTest() { Solution sol = new Solution(); assertEquals(true, sol.isValid("{[]}")); } @Test void ImmediateClosedCharsTest() { Solution sol = new Solution(); assertEquals(true, sol.isValid("()[]{}")); } }
955
0.573822
0.573822
47
19.319149
18.162512
50
false
false
0
0
0
0
0
0
0.446809
false
false
2
35fbee217ba6a127c39063017a5b360bec475cb4
34,179,349,800,429
9ae4ae3ecb7a7699de44b61bbf0b5b0c9dcfc24b
/src/main/java/com/codeup/codeup_demo/controllers/HelloController.java
3be44133e1b55e5407dcdf83ecccd17c1c65555e
[]
no_license
arthur-gamboa/spring-blog
https://github.com/arthur-gamboa/spring-blog
dce93792a6824f92352171532beae57e7865bc4b
ab4fa243626266681e2d972094e1d4f6ea4d0134
refs/heads/main
2023-04-07T20:05:33.478000
2021-04-07T01:04:10
2021-04-07T01:04:10
350,862,775
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.codeup.codeup_demo.controllers; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; import java.util.ArrayList; import java.util.List; @Controller class HelloController { @GetMapping("/hello/{name}") public String sayHello(@PathVariable String name, Model model) { model.addAttribute("name", name); List<String> names = new ArrayList<>(); names.add("Sam"); names.add("Dorian"); names.add("Diego"); model.addAttribute("aName", name.toUpperCase()); model.addAttribute("admin", name.equals("fer")); model.addAttribute("nameList", names); return "hello"; } @GetMapping("/join") public String showJoinForm() { return "join"; } @PostMapping("/join") public String joinCohort( @RequestParam(name = "cohort") String cohort, Model model) { model.addAttribute("welcomeMessage", "Welcome to " + cohort + "!"); return "join"; } }
UTF-8
Java
1,070
java
HelloController.java
Java
[ { "context": "g> names = new ArrayList<>();\n\n names.add(\"Sam\");\n names.add(\"Dorian\");\n names.add", "end": 488, "score": 0.9998745918273926, "start": 485, "tag": "NAME", "value": "Sam" }, { "context": "();\n\n names.add(\"Sam\");\n names.add(...
null
[]
package com.codeup.codeup_demo.controllers; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; import java.util.ArrayList; import java.util.List; @Controller class HelloController { @GetMapping("/hello/{name}") public String sayHello(@PathVariable String name, Model model) { model.addAttribute("name", name); List<String> names = new ArrayList<>(); names.add("Sam"); names.add("Dorian"); names.add("Diego"); model.addAttribute("aName", name.toUpperCase()); model.addAttribute("admin", name.equals("fer")); model.addAttribute("nameList", names); return "hello"; } @GetMapping("/join") public String showJoinForm() { return "join"; } @PostMapping("/join") public String joinCohort( @RequestParam(name = "cohort") String cohort, Model model) { model.addAttribute("welcomeMessage", "Welcome to " + cohort + "!"); return "join"; } }
1,070
0.638318
0.638318
43
23.906977
22.03466
75
false
false
0
0
0
0
0
0
0.581395
false
false
2
566a5f911a7f550bd9ea7c648e532bacc5594af0
5,557,687,701,395
35a3cb2ba22efcabb2b1858e936885e2644e5e6d
/branches/V1.0-M2-2012-07-09/src/com/sefryek/doublepizza/device/PhoneServicesServlet.java
b7f56f60469502face94cda8b11c205496ed0949
[]
no_license
ismaelsadeghi111/gitco001
https://github.com/ismaelsadeghi111/gitco001
340eac89e91583e39bb327f7fc604847eb91fb23
d70e9c5c7c118870dc9f853e0ba2057c52a16b87
refs/heads/master
2021-08-15T22:30:00.578000
2017-11-18T11:22:53
2017-11-18T11:22:53
111,198,664
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.sefryek.doublepizza.device; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.ServletException; import javax.jws.WebService; import java.io.IOException; import java.io.PrintWriter; /** * Created by IntelliJ IDEA. * User: vahid.s * Date: Mar 28, 2012 */ @WebService(serviceName = "/phoneServices") public class PhoneServicesServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse httpServletResponse) throws ServletException, IOException { doGet(request, httpServletResponse); } protected void doGet(HttpServletRequest request, HttpServletResponse httpServletResponse) throws ServletException, IOException { ServicesHandler servicesHandler = ServicesHandler.getHandler(request, httpServletResponse); String res = ""; if (servicesHandler != null) { try { res = servicesHandler.handleRequest(request); } catch (Exception e) { res = "ERROR IN REQUEST"; } } if (res != null) { httpServletResponse.setContentType("text/html;charset=UTF-8"); PrintWriter output = httpServletResponse.getWriter(); output.write(res); output.flush(); output.close(); } } }
UTF-8
Java
1,415
java
PhoneServicesServlet.java
Java
[ { "context": "Writer;\n\n/**\n * Created by IntelliJ IDEA.\n * User: vahid.s\n * Date: Mar 28, 2012\n */\n@WebService(servi", "end": 341, "score": 0.690121054649353, "start": 340, "tag": "NAME", "value": "v" }, { "context": "iter;\n\n/**\n * Created by IntelliJ IDEA.\n * User: vahid....
null
[]
package com.sefryek.doublepizza.device; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.ServletException; import javax.jws.WebService; import java.io.IOException; import java.io.PrintWriter; /** * Created by IntelliJ IDEA. * User: vahid.s * Date: Mar 28, 2012 */ @WebService(serviceName = "/phoneServices") public class PhoneServicesServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse httpServletResponse) throws ServletException, IOException { doGet(request, httpServletResponse); } protected void doGet(HttpServletRequest request, HttpServletResponse httpServletResponse) throws ServletException, IOException { ServicesHandler servicesHandler = ServicesHandler.getHandler(request, httpServletResponse); String res = ""; if (servicesHandler != null) { try { res = servicesHandler.handleRequest(request); } catch (Exception e) { res = "ERROR IN REQUEST"; } } if (res != null) { httpServletResponse.setContentType("text/html;charset=UTF-8"); PrintWriter output = httpServletResponse.getWriter(); output.write(res); output.flush(); output.close(); } } }
1,415
0.681979
0.677032
43
31.906977
31.361221
133
false
false
0
0
0
0
0
0
0.604651
false
false
2
862f262a6bb7209bd316bb9b166bf380ffc92988
17,300,128,294,184
503d5e067c03347f54ec288d51110ac376529faa
/Solutions/src/ReversedBinaryNumbers.java
7bebe9bcefbfe6cbafe31cb16430b15256bb99a7
[]
no_license
Grevor/NWERC
https://github.com/Grevor/NWERC
40e94dd2ca484395ded702fffd83f315af648b49
f49b64ca867fdc807805fd65641270761064ccc6
refs/heads/master
2021-01-17T10:21:59.226000
2017-01-09T01:07:34
2017-01-09T01:07:34
14,172,396
1
2
null
null
null
null
null
null
null
null
null
null
null
null
null
public class ReversedBinaryNumbers { public static void main(String[] args) { Kattio io = new Kattio(); int number = io.getInt(); int high = highestOneBit(number); int rev = 0; for(int i = 0; i <= high; i++) { rev |= ((number & (1 << i)) >> i) << (high - i); } io.println(rev); io.close(); } private static int highestOneBit(int number) { for(int i = 31; i >= 0; i--) if((number & (1 << i)) != 0) return i; return 0; } }
UTF-8
Java
485
java
ReversedBinaryNumbers.java
Java
[]
null
[]
public class ReversedBinaryNumbers { public static void main(String[] args) { Kattio io = new Kattio(); int number = io.getInt(); int high = highestOneBit(number); int rev = 0; for(int i = 0; i <= high; i++) { rev |= ((number & (1 << i)) >> i) << (high - i); } io.println(rev); io.close(); } private static int highestOneBit(int number) { for(int i = 31; i >= 0; i--) if((number & (1 << i)) != 0) return i; return 0; } }
485
0.523711
0.505155
22
19.954546
16.904753
51
false
false
0
0
0
0
0
0
2.272727
false
false
2
3861dd49087e427f61c1253e44771624f71350df
14,070,312,881,798
8efaead19f2d6f4c7cf63d397808860a25426d02
/src/main/java/com/appleyk/relation/LocatedIn.java
cf46e46d55193acf58c7ad14d065e3896d8ed597
[]
no_license
cafe3165/Spring-Boot-Neo4j-Relation
https://github.com/cafe3165/Spring-Boot-Neo4j-Relation
b9f451a6840bf7482207153faf519ab4d909bff9
856f93748cbf1bc7d31eb571e5893994cf3d28d3
refs/heads/master
2020-04-17T21:11:30.715000
2019-04-21T13:41:54
2019-04-21T13:41:54
166,938,088
1
0
null
true
2019-01-22T06:15:12
2019-01-22T06:15:12
2018-11-15T17:30:18
2018-06-02T07:08:18
10
0
0
0
null
false
null
package com.appleyk.relation; import org.neo4j.ogm.annotation.EndNode; import org.neo4j.ogm.annotation.GraphId; import org.neo4j.ogm.annotation.RelationshipEntity; import org.neo4j.ogm.annotation.StartNode; import com.appleyk.node.Device; import com.appleyk.node.Location; @RelationshipEntity(type = "LocatedIn") public class LocatedIn { @GraphId private Long id; @StartNode private Device startNode; @EndNode private Location endNode; public LocatedIn() { } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Device getStartNode() { return startNode; } public void setStartNode(Device startNode) { this.startNode = startNode; } public Location getEndNode() { return endNode; } public void setEndNode(Location endNode) { this.endNode = endNode; } }
UTF-8
Java
889
java
LocatedIn.java
Java
[]
null
[]
package com.appleyk.relation; import org.neo4j.ogm.annotation.EndNode; import org.neo4j.ogm.annotation.GraphId; import org.neo4j.ogm.annotation.RelationshipEntity; import org.neo4j.ogm.annotation.StartNode; import com.appleyk.node.Device; import com.appleyk.node.Location; @RelationshipEntity(type = "LocatedIn") public class LocatedIn { @GraphId private Long id; @StartNode private Device startNode; @EndNode private Location endNode; public LocatedIn() { } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Device getStartNode() { return startNode; } public void setStartNode(Device startNode) { this.startNode = startNode; } public Location getEndNode() { return endNode; } public void setEndNode(Location endNode) { this.endNode = endNode; } }
889
0.690664
0.686164
52
15.134615
15.597126
51
false
false
0
0
0
0
0
0
1.038462
false
false
2
fe292cda628b83bc780e26f2e5ce61c51f2d3f18
14,070,312,885,399
fe6a500ea24b9448555838dec906d780bd8280bc
/crosschain/src/main/java/org/hyperledger/besu/crosschain/core/messages/ThresholdSignedMessage.java
fb73fc0103c36d1885fb0abe466be97660c34f12
[ "Apache-2.0" ]
permissive
PegaSysEng/sidechains-besu
https://github.com/PegaSysEng/sidechains-besu
d510e26766d302a1eae7fd8e0eaa9cf1e44d6d78
fc888aef685b071018092cc33b47e85b47d59f7f
refs/heads/master
2020-07-26T17:18:08.748000
2020-03-30T01:58:49
2020-03-30T01:58:49
208,715,593
5
3
Apache-2.0
true
2020-03-30T01:58:51
2019-09-16T05:18:34
2020-02-22T18:15:59
2020-03-30T01:58:50
26,673
4
1
1
Java
false
false
/* * Copyright 2019 ConsenSys AG. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package org.hyperledger.besu.crosschain.core.messages; import org.hyperledger.besu.ethereum.core.Address; import org.hyperledger.besu.ethereum.core.CrosschainTransaction; import org.hyperledger.besu.ethereum.rlp.RLP; import org.hyperledger.besu.ethereum.rlp.RLPInput; import org.hyperledger.besu.util.bytes.BytesValue; import java.math.BigInteger; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; /** * The message format is: * * <p>Core Message: Message Type Coordination Blockchain Id Coordination Contract Address * Originating Blockchain Id Crosschain Transaction Id Message Digest of the part of the Crosschain * Transaction being processed. This includes any subordinate transactions or views below the * current transaction or view. Message specific field. * * <p>Signed Core Message: Core Message Key Version used to sign Signature of the RLP of the Core * Message. * * <p>Message Core Message Part of the Crosschain Transaction being processed * * <p>Signed Message Signed Core Message Part of the Crosschain Transaction being processed * * <p>The message specific field is: Start: Transaction Time-out Block Number Commit: Nothing * Ignore: Nothing Transaction Ready: Blockchain Id that Subordinate Transaction was executed on. * View Result: Blockchain Id that Subordinate View was executed on. Block number when view was * executed. RLP encoded result */ public interface ThresholdSignedMessage { Logger LOG = LogManager.getLogger(); static ThresholdSignedMessage decodeEncodedMessage(final BytesValue encoded) { RLPInput in = RLP.input(encoded); in.enterList(); long type = in.readLongScalar(); ThresholdSignedMessageType messageType = ThresholdSignedMessageType.create((int) type); switch (messageType) { case CROSSCHAIN_TRANSACTION_START: return new CrosschainTransactionStartMessage(in); case CROSSCHAIN_TRANSACTION_COMMIT: return new CrosschainTransactionCommitMessage(in); case CROSSCHAIN_TRANSACTION_IGNORE: return new CrosschainTransactionIgnoreMessage(in); case SUBORDINATE_VIEW_RESULT: return new SubordinateViewResultMessage(in); case SUBORDINATE_TRANSACTION_READY: return new SubordinateTransactionReadyMessage(in); default: String msg = "Unknown Threshold Message type " + messageType; LOG.error(msg); throw new RuntimeException(msg); } } void setSignature(long keyVersion, BytesValue signature); ThresholdSignedMessageType getType(); boolean verifiedByCoordContract(); BigInteger getCoordinationBlockchainId(); Address getCoordinationContractAddress(); BigInteger getOriginatingBlockchainId(); BigInteger getCrosschainTransactionId(); BytesValue getCrosschainTransactionHash(); long getKeyVersion(); BytesValue getSignature(); CrosschainTransaction getTransaction(); // Create a message to be signed. BytesValue getEncodedCoreMessage(); BytesValue getEncodedMessageForCoordContract(); // Create the blob to be sent to other nodes so they have enough information to know whether they // should sign. BytesValue getEncodedMessage(); }
UTF-8
Java
3,780
java
ThresholdSignedMessage.java
Java
[]
null
[]
/* * Copyright 2019 ConsenSys AG. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package org.hyperledger.besu.crosschain.core.messages; import org.hyperledger.besu.ethereum.core.Address; import org.hyperledger.besu.ethereum.core.CrosschainTransaction; import org.hyperledger.besu.ethereum.rlp.RLP; import org.hyperledger.besu.ethereum.rlp.RLPInput; import org.hyperledger.besu.util.bytes.BytesValue; import java.math.BigInteger; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; /** * The message format is: * * <p>Core Message: Message Type Coordination Blockchain Id Coordination Contract Address * Originating Blockchain Id Crosschain Transaction Id Message Digest of the part of the Crosschain * Transaction being processed. This includes any subordinate transactions or views below the * current transaction or view. Message specific field. * * <p>Signed Core Message: Core Message Key Version used to sign Signature of the RLP of the Core * Message. * * <p>Message Core Message Part of the Crosschain Transaction being processed * * <p>Signed Message Signed Core Message Part of the Crosschain Transaction being processed * * <p>The message specific field is: Start: Transaction Time-out Block Number Commit: Nothing * Ignore: Nothing Transaction Ready: Blockchain Id that Subordinate Transaction was executed on. * View Result: Blockchain Id that Subordinate View was executed on. Block number when view was * executed. RLP encoded result */ public interface ThresholdSignedMessage { Logger LOG = LogManager.getLogger(); static ThresholdSignedMessage decodeEncodedMessage(final BytesValue encoded) { RLPInput in = RLP.input(encoded); in.enterList(); long type = in.readLongScalar(); ThresholdSignedMessageType messageType = ThresholdSignedMessageType.create((int) type); switch (messageType) { case CROSSCHAIN_TRANSACTION_START: return new CrosschainTransactionStartMessage(in); case CROSSCHAIN_TRANSACTION_COMMIT: return new CrosschainTransactionCommitMessage(in); case CROSSCHAIN_TRANSACTION_IGNORE: return new CrosschainTransactionIgnoreMessage(in); case SUBORDINATE_VIEW_RESULT: return new SubordinateViewResultMessage(in); case SUBORDINATE_TRANSACTION_READY: return new SubordinateTransactionReadyMessage(in); default: String msg = "Unknown Threshold Message type " + messageType; LOG.error(msg); throw new RuntimeException(msg); } } void setSignature(long keyVersion, BytesValue signature); ThresholdSignedMessageType getType(); boolean verifiedByCoordContract(); BigInteger getCoordinationBlockchainId(); Address getCoordinationContractAddress(); BigInteger getOriginatingBlockchainId(); BigInteger getCrosschainTransactionId(); BytesValue getCrosschainTransactionHash(); long getKeyVersion(); BytesValue getSignature(); CrosschainTransaction getTransaction(); // Create a message to be signed. BytesValue getEncodedCoreMessage(); BytesValue getEncodedMessageForCoordContract(); // Create the blob to be sent to other nodes so they have enough information to know whether they // should sign. BytesValue getEncodedMessage(); }
3,780
0.767989
0.765344
102
36.058823
32.926186
118
false
false
0
0
0
0
0
0
0.411765
false
false
2
c3883f7c0186c9a2119c051ebe9aed957b126b9f
9,947,144,293,815
8ca7ba514482d3b4373f1eedfedbc7ae6bc44bba
/src/main/java/com/yao/hashtab/HashTabDemo.java
bc3d5317be9b144684356db66edcb44fe1b05e89
[]
no_license
GoldenML/dataStructure
https://github.com/GoldenML/dataStructure
eb4e4eff0beb7aa318286c257ba091d009f9ed3d
7852c0e36a887072b0a283b6502a7a625373514c
refs/heads/master
2020-07-24T03:37:08.843000
2019-09-17T14:40:21
2019-09-17T14:40:21
207,790,071
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.yao.hashtab; import com.sun.glass.ui.Size; import java.util.Scanner; /** * @author yanghui * @create 2019-09-03 11:51 * @description */ public class HashTabDemo { public static void main(String[] args){ HashTab tab = new HashTab(7); String key = ""; Scanner sc = new Scanner(System.in); while(true){ System.out.println("add:添加雇员"); System.out.println("print:显示雇员"); System.out.println("find:查找雇员"); System.out.println("exit:退出"); System.out.println("输入你的选择"); key = sc.next(); switch (key){ case "add": int id = sc.nextInt(); String name = sc.next(); Emp emp = new Emp(id,name); tab.add(emp); break; case "print": tab.print(); break; case "find": id = sc.nextInt(); System.out.println(tab.findEmpById(id)); break; case "exit": sc.close(); System.exit(0); break; default: break; } } } } class HashTab{ private EmpLinkedList[] empLinkedLists; private int size; public HashTab(int size){ empLinkedLists = new EmpLinkedList[size]; for (int i = 0; i < size; i++) { empLinkedLists[i] = new EmpLinkedList(); } this.size = size; } public void add(Emp emp){ int h = hashCode(emp.id); empLinkedLists[h].add(emp); } public int hashCode(int id){ return id%size; } public void print(){ for (int i = 0; i < size; i++) { empLinkedLists[i].print(); } } public Emp findEmpById(int id){ int h = hashCode(id); Emp emp = empLinkedLists[h].findEmpById(id); if(emp!=null){ return emp; }else{ System.out.println("没找到该雇员"); return null; } } } class Emp{ public int id; public String name; public Emp next; public Emp(int id, String name) { super(); this.id = id; this.name = name; } @Override public String toString() { return "Emp{" + "id=" + id + ", name='" + name + '\'' + '}'; } } class EmpLinkedList{ private Emp head; public void add(Emp emp){ if(head == null){ head = emp; }else{ Emp cur = head; while(cur.next!=null){ cur =cur.next; } cur.next = emp; } } public void print(){ if(head == null){ System.out.println("无数据"); return; } Emp cur = head; while(cur!=null){ System.out.print("id:"+cur.id+" name: "+cur.name+"\t "); cur = cur.next; } System.out.println(); } public Emp findEmpById(int id){ if(head == null){ return null; } Emp cur = head; while (cur!= null){ if(cur.id != id) { cur = cur.next; }else{ break; } } return cur; } }
UTF-8
Java
3,487
java
HashTabDemo.java
Java
[ { "context": "i.Size;\n\nimport java.util.Scanner;\n\n/**\n * @author yanghui\n * @create 2019-09-03 11:51\n * @description\n */\np", "end": 106, "score": 0.9104693531990051, "start": 99, "tag": "USERNAME", "value": "yanghui" } ]
null
[]
package com.yao.hashtab; import com.sun.glass.ui.Size; import java.util.Scanner; /** * @author yanghui * @create 2019-09-03 11:51 * @description */ public class HashTabDemo { public static void main(String[] args){ HashTab tab = new HashTab(7); String key = ""; Scanner sc = new Scanner(System.in); while(true){ System.out.println("add:添加雇员"); System.out.println("print:显示雇员"); System.out.println("find:查找雇员"); System.out.println("exit:退出"); System.out.println("输入你的选择"); key = sc.next(); switch (key){ case "add": int id = sc.nextInt(); String name = sc.next(); Emp emp = new Emp(id,name); tab.add(emp); break; case "print": tab.print(); break; case "find": id = sc.nextInt(); System.out.println(tab.findEmpById(id)); break; case "exit": sc.close(); System.exit(0); break; default: break; } } } } class HashTab{ private EmpLinkedList[] empLinkedLists; private int size; public HashTab(int size){ empLinkedLists = new EmpLinkedList[size]; for (int i = 0; i < size; i++) { empLinkedLists[i] = new EmpLinkedList(); } this.size = size; } public void add(Emp emp){ int h = hashCode(emp.id); empLinkedLists[h].add(emp); } public int hashCode(int id){ return id%size; } public void print(){ for (int i = 0; i < size; i++) { empLinkedLists[i].print(); } } public Emp findEmpById(int id){ int h = hashCode(id); Emp emp = empLinkedLists[h].findEmpById(id); if(emp!=null){ return emp; }else{ System.out.println("没找到该雇员"); return null; } } } class Emp{ public int id; public String name; public Emp next; public Emp(int id, String name) { super(); this.id = id; this.name = name; } @Override public String toString() { return "Emp{" + "id=" + id + ", name='" + name + '\'' + '}'; } } class EmpLinkedList{ private Emp head; public void add(Emp emp){ if(head == null){ head = emp; }else{ Emp cur = head; while(cur.next!=null){ cur =cur.next; } cur.next = emp; } } public void print(){ if(head == null){ System.out.println("无数据"); return; } Emp cur = head; while(cur!=null){ System.out.print("id:"+cur.id+" name: "+cur.name+"\t "); cur = cur.next; } System.out.println(); } public Emp findEmpById(int id){ if(head == null){ return null; } Emp cur = head; while (cur!= null){ if(cur.id != id) { cur = cur.next; }else{ break; } } return cur; } }
3,487
0.433071
0.428405
142
23.15493
14.032305
68
false
false
0
0
0
0
0
0
0.492958
false
false
2
b85a098a309a6d9b3d5b5ad144596536fa3dda52
9,947,144,293,617
82963b7aac94471acc0dcfc92e07e585948156b6
/src/test/java/com/test/thread/testparentlock/Child.java
303d74077dab701769cc1be68ee58a2ad7c7715b
[ "Apache-2.0" ]
permissive
hanweida/JerryCodeApp
https://github.com/hanweida/JerryCodeApp
fec72f884a459f4cd9fe8f9f6902eda26cde7e9b
b9cfd3ae4048c4154efe4f5ad17ae84aee035de6
refs/heads/master
2022-12-26T16:24:30.590000
2022-07-18T06:20:59
2022-07-18T06:20:59
110,661,228
0
0
Apache-2.0
false
2022-12-16T10:32:34
2017-11-14T08:22:51
2021-12-27T12:16:17
2022-12-16T10:32:33
27,579
0
0
17
Java
false
false
package com.test.thread.testparentlock; public class Child extends Parent implements Runnable { @Override public void run() { sum(); } }
UTF-8
Java
158
java
Child.java
Java
[]
null
[]
package com.test.thread.testparentlock; public class Child extends Parent implements Runnable { @Override public void run() { sum(); } }
158
0.664557
0.664557
8
18.75
18.21229
55
false
false
0
0
0
0
0
0
0.25
false
false
2
e89cbc21974a07970cf1f22d8857f321aac7f5e6
17,480,516,922,449
3ea11eda899db3ef7522591aaa1b3c5da533f1a0
/src/main/java/cn/nuaa/rpc/client/HelloRPC(1).java
ec1eb1e0e1241f322e2333a644344801ff36468a
[]
no_license
raintor/NettyRPC
https://github.com/raintor/NettyRPC
3379af59d0c3f631ad87eea01fbba57cbe7d2851
ab955d63cd188645ed39e3e2a0abdebedfcb0ec9
refs/heads/master
2020-05-25T20:13:26.313000
2019-07-21T02:46:44
2019-07-21T02:46:44
187,970,379
2
0
null
false
2019-11-02T14:36:20
2019-05-22T05:42:28
2019-07-21T02:46:46
2019-11-02T14:36:19
13
1
0
1
Java
false
false
package cn.nuaa.rpc.client; interface HelloRPC { String hello(String name); }
UTF-8
Java
82
java
HelloRPC(1).java
Java
[]
null
[]
package cn.nuaa.rpc.client; interface HelloRPC { String hello(String name); }
82
0.731707
0.731707
5
15.6
12.753038
30
false
false
0
0
0
0
0
0
0.4
false
false
2
6df44d8a2d415ba47cd0e16a00f5c59984a7d919
20,839,181,355,210
a42f70eb4c33b644141c7c593c16371005fae99b
/src/main/java/icbm/classic/content/blast/gas/BlastColor.java
05a75e23ce4dd62fbb415ff555e430fcd03af9d8
[ "MIT" ]
permissive
BuiltBrokenModding/ICBM-Classic
https://github.com/BuiltBrokenModding/ICBM-Classic
107f5eed162b9de4eb431f7e5505e06c38b9b04b
3e6e0f4fa7db5a656ea6537516dc51c030b38dc5
refs/heads/prod/1.12
2023-08-30T10:54:27.051000
2023-08-25T18:01:38
2023-08-25T18:01:38
78,190,318
49
85
MIT
false
2023-08-25T18:01:40
2017-01-06T08:49:03
2023-08-10T14:31:00
2023-08-25T18:01:38
66,252
40
46
37
Java
false
false
package icbm.classic.content.blast.gas; import icbm.classic.lib.colors.ColorB; import icbm.classic.lib.colors.ColorHelper; import net.minecraft.util.math.Vec3i; import java.util.ArrayList; import java.util.List; /** * Created by Robin Seifert on 4/1/2022. */ public class BlastColor extends BlastGasBase { public static final int DURATION = 20 * 30; //TODO move to config /** Number of particle colors to use */ public static final int COLOR_COUNT = 100; /** Random set of particle colors */ public static final List<ColorB> PARTICLE_COLORS = new ArrayList(COLOR_COUNT); /** True of random colors have been setup, done once per game */ private static boolean hasSetupColors = false; private int currentColorIndex = 0; public BlastColor() { super(DURATION, false); } @Override protected boolean setupBlast() { if (!hasSetupColors) { generateRandomColors(); hasSetupColors = true; } return true; } @Override protected boolean canEffectEntities() { return false; } private void generateRandomColors() { for (int i = 0; i < COLOR_COUNT; i++) { final float hue = world.rand.nextFloat(); final float saturation = 0.9f;//1.0 for brilliant, 0.0 for dull final float luminance = 0.5f; //1.0 for brighter, 0.0 for black PARTICLE_COLORS.add(ColorHelper.HSBtoRGB(hue, saturation, luminance)); } } @Override protected void spawnGasParticles(final Vec3i pos) { super.spawnGasParticles(pos); currentColorIndex = (currentColorIndex + 1) % COLOR_COUNT; } @Override protected float getParticleColorRed(final Vec3i pos) { if(currentColorIndex >= 0 && currentColorIndex < PARTICLE_COLORS.size()) { return PARTICLE_COLORS.get(currentColorIndex).getRed(); } return 1; } @Override protected float getParticleColorGreen(final Vec3i pos) { if(currentColorIndex >= 0 && currentColorIndex < PARTICLE_COLORS.size()) { return PARTICLE_COLORS.get(currentColorIndex).getGreen(); } return 1; } @Override protected float getParticleColorBlue(final Vec3i pos) { if(currentColorIndex >= 0 && currentColorIndex < PARTICLE_COLORS.size()) { return PARTICLE_COLORS.get(currentColorIndex).getBlue(); } return 1; } }
UTF-8
Java
2,537
java
BlastColor.java
Java
[ { "context": "rayList;\nimport java.util.List;\n\n/**\n * Created by Robin Seifert on 4/1/2022.\n */\npublic class BlastColor extends ", "end": 246, "score": 0.9998329877853394, "start": 233, "tag": "NAME", "value": "Robin Seifert" } ]
null
[]
package icbm.classic.content.blast.gas; import icbm.classic.lib.colors.ColorB; import icbm.classic.lib.colors.ColorHelper; import net.minecraft.util.math.Vec3i; import java.util.ArrayList; import java.util.List; /** * Created by <NAME> on 4/1/2022. */ public class BlastColor extends BlastGasBase { public static final int DURATION = 20 * 30; //TODO move to config /** Number of particle colors to use */ public static final int COLOR_COUNT = 100; /** Random set of particle colors */ public static final List<ColorB> PARTICLE_COLORS = new ArrayList(COLOR_COUNT); /** True of random colors have been setup, done once per game */ private static boolean hasSetupColors = false; private int currentColorIndex = 0; public BlastColor() { super(DURATION, false); } @Override protected boolean setupBlast() { if (!hasSetupColors) { generateRandomColors(); hasSetupColors = true; } return true; } @Override protected boolean canEffectEntities() { return false; } private void generateRandomColors() { for (int i = 0; i < COLOR_COUNT; i++) { final float hue = world.rand.nextFloat(); final float saturation = 0.9f;//1.0 for brilliant, 0.0 for dull final float luminance = 0.5f; //1.0 for brighter, 0.0 for black PARTICLE_COLORS.add(ColorHelper.HSBtoRGB(hue, saturation, luminance)); } } @Override protected void spawnGasParticles(final Vec3i pos) { super.spawnGasParticles(pos); currentColorIndex = (currentColorIndex + 1) % COLOR_COUNT; } @Override protected float getParticleColorRed(final Vec3i pos) { if(currentColorIndex >= 0 && currentColorIndex < PARTICLE_COLORS.size()) { return PARTICLE_COLORS.get(currentColorIndex).getRed(); } return 1; } @Override protected float getParticleColorGreen(final Vec3i pos) { if(currentColorIndex >= 0 && currentColorIndex < PARTICLE_COLORS.size()) { return PARTICLE_COLORS.get(currentColorIndex).getGreen(); } return 1; } @Override protected float getParticleColorBlue(final Vec3i pos) { if(currentColorIndex >= 0 && currentColorIndex < PARTICLE_COLORS.size()) { return PARTICLE_COLORS.get(currentColorIndex).getBlue(); } return 1; } }
2,530
0.622783
0.60741
97
25.154638
25.343554
82
false
false
0
0
0
0
0
0
0.371134
false
false
2
9c29806195e1051edfde24d05abc327ba75ece90
7,464,653,186,997
ba769ebb0b9c3eea347ea9195fe004e08cd07c5e
/src/main/java/br/uff/ic/gardener/versioning/Project.java
9fd3ee4bf0e96443cd851977ab6fce508ae73d93
[]
no_license
leomurta/gardener
https://github.com/leomurta/gardener
a59597fb3dce12b52cafdfe00e7a4652b9f9dc95
af87b0f26d95e8416ddd1c44204bb4e5cf98f503
refs/heads/master
2021-01-10T22:21:30.096000
2010-12-04T20:02:45
2010-12-04T20:02:45
883,265
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package br.uff.ic.gardener.versioning; /** * * @author Evaldo de Oliveira */ public class Project { private String nameProject; public Project(String nameProject) { this.setNameProject(nameProject); } public String getNameProject(){ return this.nameProject; } public void setNameProject(String nameProject){ this.nameProject = nameProject; } }
UTF-8
Java
510
java
Project.java
Java
[ { "context": " br.uff.ic.gardener.versioning;\n\n/**\n *\n * @author Evaldo de Oliveira\n */\npublic class Project {\n\n private String na", "end": 177, "score": 0.9998717904090881, "start": 159, "tag": "NAME", "value": "Evaldo de Oliveira" } ]
null
[]
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package br.uff.ic.gardener.versioning; /** * * @author <NAME> */ public class Project { private String nameProject; public Project(String nameProject) { this.setNameProject(nameProject); } public String getNameProject(){ return this.nameProject; } public void setNameProject(String nameProject){ this.nameProject = nameProject; } }
498
0.662745
0.662745
29
16.586206
18.202911
52
false
false
0
0
0
0
0
0
0.241379
false
false
2
1c1e71fdbdcd69982810002911ea13022af407a6
30,657,476,587,603
3b796677e4fcd78d919bbe6608bfed0438db6515
/Java/CodingPractice/src/main/java/Arrays/array/intersect.java
e87d2ad6e9dd990a607ca76fa13369fe2796ad06
[]
no_license
soniaarora/Algorithms-Practice
https://github.com/soniaarora/Algorithms-Practice
764ec553fa7ac58dd8c7828b9af3742bfdff3f85
d58d88487ff525dc234d98a4d4e47f3d38da97a8
refs/heads/master
2020-08-25T05:37:19.715000
2019-10-23T04:57:56
2019-10-23T04:57:56
216,968,917
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * 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 array; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; /** * * @author Hp */ public class intersect { public static void main(String[] arg){ int[] nums1 = {1,2,2,1}; int[] nums2 = {2,2}; int[] res =findIntersect(nums1,nums2); } public static int[] findIntersect(int[] nums1, int nums2[]){ int length1= nums1.length; int length2 = nums2.length; int[] maxArray,minorArray; if(length1 > length2 ){ maxArray = Arrays.copyOf(nums1,length1); minorArray = Arrays.copyOf(nums2,length2); } else{ maxArray = Arrays.copyOf(nums2,length2); minorArray = Arrays.copyOf(nums1,length1); } List<Integer> list = new ArrayList(); HashMap<Integer, Integer> map = new HashMap(); for(int i = 0; i< maxArray.length ; i++){ if(!map.containsKey(maxArray[i])){ map.put(maxArray[i], 1); } else{ map.put(maxArray[i], map.get(maxArray[i]) + 1); } // map.put(maxArray[i], map.getOrDefault(maxArray[i],0)+1); } for(int i = 0; i< minorArray.length;i++){ int key = minorArray[i]; if(map.containsKey(key) && (map.get(key)) > 0){ int val = map.get(key); list.add(key); map.put(key,val-1); } } int[] res = new int[list.size()]; int i= 0; for(int val :list){ res[i] = val; i++; } return res; } }
UTF-8
Java
2,010
java
intersect.java
Java
[ { "context": "HashMap;\nimport java.util.List;\n\n/**\n *\n * @author Hp\n */\npublic class intersect {\n \n public stat", "end": 324, "score": 0.9992768168449402, "start": 322, "tag": "USERNAME", "value": "Hp" } ]
null
[]
/* * 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 array; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; /** * * @author Hp */ public class intersect { public static void main(String[] arg){ int[] nums1 = {1,2,2,1}; int[] nums2 = {2,2}; int[] res =findIntersect(nums1,nums2); } public static int[] findIntersect(int[] nums1, int nums2[]){ int length1= nums1.length; int length2 = nums2.length; int[] maxArray,minorArray; if(length1 > length2 ){ maxArray = Arrays.copyOf(nums1,length1); minorArray = Arrays.copyOf(nums2,length2); } else{ maxArray = Arrays.copyOf(nums2,length2); minorArray = Arrays.copyOf(nums1,length1); } List<Integer> list = new ArrayList(); HashMap<Integer, Integer> map = new HashMap(); for(int i = 0; i< maxArray.length ; i++){ if(!map.containsKey(maxArray[i])){ map.put(maxArray[i], 1); } else{ map.put(maxArray[i], map.get(maxArray[i]) + 1); } // map.put(maxArray[i], map.getOrDefault(maxArray[i],0)+1); } for(int i = 0; i< minorArray.length;i++){ int key = minorArray[i]; if(map.containsKey(key) && (map.get(key)) > 0){ int val = map.get(key); list.add(key); map.put(key,val-1); } } int[] res = new int[list.size()]; int i= 0; for(int val :list){ res[i] = val; i++; } return res; } }
2,010
0.480099
0.462687
80
24.125
19.793543
79
false
false
0
0
0
0
0
0
0.6625
false
false
2
d9dc62e53de27004a4be782511e8da84645dc37f
13,116,830,163,678
bf349ab794f54249438330f717b42c2395e076bf
/src/test/java/CryptoCurrency/CryptoCurrencyAppApplicationTests.java
54ab6edcbf01205f1da9af1e753d1999d6da550b
[]
no_license
Annemiekff/CryptoCurrencyApp
https://github.com/Annemiekff/CryptoCurrencyApp
39f38325c2a91416c8cb69550e26ef65688ae5c0
d956da9f3fe7263d14b051b2ef621110409dfc59
refs/heads/master
2022-11-06T13:27:09.225000
2020-06-25T07:17:52
2020-06-25T07:17:52
274,424,129
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package CryptoCurrency; import CryptoCurrency.controller.CurrencyController; import CryptoCurrency.controller.CurrencyService; import CryptoCurrency.model.Currency; import CryptoCurrency.model.Currency2; import CryptoCurrency.model.CurrencyRepository; import CryptoCurrency.model.CurrencyRepository2; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.orm.jpa.AutoConfigureTestEntityManager; import org.springframework.boot.test.context.SpringBootTest; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; @AutoConfigureTestEntityManager @SpringBootTest class CryptoCurrencyAppApplicationTests { @Test void contextLoads() { } @Autowired private CurrencyRepository currencyRepository; @Autowired private CurrencyRepository2 currencyRepository2; @Autowired private CurrencyController currencyController; @Autowired private CurrencyService currencyService; /** Testing if we can load one currency */ @Test public void whenFindByTicker_thenReturnCurrency() { //given Currency btc = new Currency("BTC", "Bitcoin", 16770000L, 189580000000L); //when Currency found = currencyController.getOneCurrency(btc.getTicker()); //then assertThat(found.getName()).isEqualTo(btc.getName()); } /** Testing if we can load all currencies */ @Test public void loadAll() { //when List<Currency> currencies = currencyController.getAllCurrencies(0, 10, "ticker").getBody(); //then Iterable<Currency> x = currencyRepository.findAll(); x.forEach(currency -> { assert currencies != null; assertThat(currencies.contains(currency)); }); } /** Testing if we can delete a new currency. * Adding the currency at the end so the other tests don't give false results because the currency was deleted * */ @Test public void deleteCurrency() { //given Currency btc = new Currency("BTC", "Bitcoin", 16770000L, 189580000000L); //when currencyController.deleteCurrency(btc.getTicker()); //then assertThat(!currencyRepository.existsById(btc.getTicker())); currencyRepository.save(btc); } /** Testing if we can post a new currency. * Deleting the currency at the end so it won't interfere with other tests * */ @Test public void postCurrency(){ Currency btd = new Currency("BTd", "Bitcoined", 16770000L, 189580000000L); //when currencyController.postCurrency(btd); //then assertThat(currencyRepository.existsById(btd.getTicker())); currencyController.deleteCurrency(btd.getTicker()); } /** Testing if we can update a currency * Afterwards returning it to the original so it doesn't interfere with other tests*/ @Test public void putCurrency(){ Currency btcUpdate = new Currency("BTC", "Bitcoinz", 16770000L, 189580000000L); Currency btc = new Currency("BTC", "Bitcoin", 16770000L, 189580000000L); //when currencyController.putCurrency(btcUpdate, btcUpdate.getTicker()); Currency updatedBtc = currencyController.getOneCurrency(btcUpdate.getTicker()); //then assertThat(updatedBtc.getName().equals(btcUpdate.getName())); assertThat(updatedBtc.getTicker().equals(btcUpdate.getTicker())); assertThat(updatedBtc.getMarket_cap() == btcUpdate.getMarket_cap()); assertThat(updatedBtc.getNumber_of_coins() == btcUpdate.getNumber_of_coins()); currencyController.putCurrency(btc, btcUpdate.getTicker()); } /** Testing to see if the database is pre-filled with 4 currencies */ @Test public void checkingDatabaseFilled(){ int databaseSize = currencyService.getAllCurrencies(0, 10, "ticker").size(); assertThat(databaseSize == 4); } /** Testing if we can load one currency2 */ @Test public void whenFindByTicker_thenReturnCurrency2() { //given Currency2 btc = new Currency2.CurrencyBuilder("BTC", "Bitcoin").number_of_coins(16770000L).market_cap(189580000000L).build(); //when Currency2 found = currencyController.getOneCurrency2(btc.getTicker()); //then assertThat(found.getName()).isEqualTo(btc.getName()); } /** Testing if we can load all currencies2 */ @Test public void loadAll2() { //when List<Currency2> currencies = currencyController.getAllCurrencies2(0, 10, "ticker").getBody(); //then Iterable<Currency2> x = currencyRepository2.findAll(); x.forEach(currency -> { assert currencies != null; assertThat(currencies.contains(currency)); }); } /** Testing if we can delete a new currency2. * Adding the currency2 at the end so the other tests don't give false results because the currency was deleted * */ @Test public void deleteCurrency2() { //given Currency2 btc = new Currency2.CurrencyBuilder("BTC", "Bitcoin").number_of_coins(16770000L).market_cap(189580000000L).build(); //when currencyController.deleteCurrency2(btc.getTicker()); //then assertThat(!currencyRepository2.existsById(btc.getTicker())); currencyRepository2.save(btc); } /** Testing if we can post a new currency2. * Deleting the currency2 at the end so it won't interfere with other tests * */ @Test public void postCurrency2(){ Currency2 btd = new Currency2.CurrencyBuilder("BTd", "Bitcoined").number_of_coins(16770000L).market_cap(189580000000L).build(); //when currencyController.postCurrency2(btd); //then assertThat(currencyRepository2.existsById(btd.getTicker())); currencyController.deleteCurrency2(btd.getTicker()); } /** Testing if we can update a currency2 * Afterwards returning it to the original so it doesn't interfere with other tests*/ @Test public void putCurrency2(){ Currency2 btcUpdate = new Currency2.CurrencyBuilder("BTC", "Bitcoinz").number_of_coins(167700000L).market_cap(1895800000L).build(); Currency2 btc = new Currency2.CurrencyBuilder("BTC", "Bitcoin").number_of_coins(16770000L).market_cap(189580000000L).build(); //when currencyController.putCurrency2(btcUpdate, btcUpdate.getTicker()); Currency2 updatedBtc = currencyController.getOneCurrency2(btcUpdate.getTicker()); //then assertThat(updatedBtc.getName().equals(btcUpdate.getName())); assertThat(updatedBtc.getTicker().equals(btcUpdate.getTicker())); assertThat(updatedBtc.getMarket_cap() == btcUpdate.getMarket_cap()); assertThat(updatedBtc.getNumber_of_coins() == btcUpdate.getNumber_of_coins()); currencyController.putCurrency2(btc, btcUpdate.getTicker()); } /** Testing to see if the database is pre-filled with 4 currencies2 */ @Test public void checkingDatabaseFilled2(){ int databaseSize = currencyService.getAllCurrencies2(0, 10, "ticker").size(); assertThat(databaseSize == 4); } }
UTF-8
Java
6,606
java
CryptoCurrencyAppApplicationTests.java
Java
[]
null
[]
package CryptoCurrency; import CryptoCurrency.controller.CurrencyController; import CryptoCurrency.controller.CurrencyService; import CryptoCurrency.model.Currency; import CryptoCurrency.model.Currency2; import CryptoCurrency.model.CurrencyRepository; import CryptoCurrency.model.CurrencyRepository2; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.orm.jpa.AutoConfigureTestEntityManager; import org.springframework.boot.test.context.SpringBootTest; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; @AutoConfigureTestEntityManager @SpringBootTest class CryptoCurrencyAppApplicationTests { @Test void contextLoads() { } @Autowired private CurrencyRepository currencyRepository; @Autowired private CurrencyRepository2 currencyRepository2; @Autowired private CurrencyController currencyController; @Autowired private CurrencyService currencyService; /** Testing if we can load one currency */ @Test public void whenFindByTicker_thenReturnCurrency() { //given Currency btc = new Currency("BTC", "Bitcoin", 16770000L, 189580000000L); //when Currency found = currencyController.getOneCurrency(btc.getTicker()); //then assertThat(found.getName()).isEqualTo(btc.getName()); } /** Testing if we can load all currencies */ @Test public void loadAll() { //when List<Currency> currencies = currencyController.getAllCurrencies(0, 10, "ticker").getBody(); //then Iterable<Currency> x = currencyRepository.findAll(); x.forEach(currency -> { assert currencies != null; assertThat(currencies.contains(currency)); }); } /** Testing if we can delete a new currency. * Adding the currency at the end so the other tests don't give false results because the currency was deleted * */ @Test public void deleteCurrency() { //given Currency btc = new Currency("BTC", "Bitcoin", 16770000L, 189580000000L); //when currencyController.deleteCurrency(btc.getTicker()); //then assertThat(!currencyRepository.existsById(btc.getTicker())); currencyRepository.save(btc); } /** Testing if we can post a new currency. * Deleting the currency at the end so it won't interfere with other tests * */ @Test public void postCurrency(){ Currency btd = new Currency("BTd", "Bitcoined", 16770000L, 189580000000L); //when currencyController.postCurrency(btd); //then assertThat(currencyRepository.existsById(btd.getTicker())); currencyController.deleteCurrency(btd.getTicker()); } /** Testing if we can update a currency * Afterwards returning it to the original so it doesn't interfere with other tests*/ @Test public void putCurrency(){ Currency btcUpdate = new Currency("BTC", "Bitcoinz", 16770000L, 189580000000L); Currency btc = new Currency("BTC", "Bitcoin", 16770000L, 189580000000L); //when currencyController.putCurrency(btcUpdate, btcUpdate.getTicker()); Currency updatedBtc = currencyController.getOneCurrency(btcUpdate.getTicker()); //then assertThat(updatedBtc.getName().equals(btcUpdate.getName())); assertThat(updatedBtc.getTicker().equals(btcUpdate.getTicker())); assertThat(updatedBtc.getMarket_cap() == btcUpdate.getMarket_cap()); assertThat(updatedBtc.getNumber_of_coins() == btcUpdate.getNumber_of_coins()); currencyController.putCurrency(btc, btcUpdate.getTicker()); } /** Testing to see if the database is pre-filled with 4 currencies */ @Test public void checkingDatabaseFilled(){ int databaseSize = currencyService.getAllCurrencies(0, 10, "ticker").size(); assertThat(databaseSize == 4); } /** Testing if we can load one currency2 */ @Test public void whenFindByTicker_thenReturnCurrency2() { //given Currency2 btc = new Currency2.CurrencyBuilder("BTC", "Bitcoin").number_of_coins(16770000L).market_cap(189580000000L).build(); //when Currency2 found = currencyController.getOneCurrency2(btc.getTicker()); //then assertThat(found.getName()).isEqualTo(btc.getName()); } /** Testing if we can load all currencies2 */ @Test public void loadAll2() { //when List<Currency2> currencies = currencyController.getAllCurrencies2(0, 10, "ticker").getBody(); //then Iterable<Currency2> x = currencyRepository2.findAll(); x.forEach(currency -> { assert currencies != null; assertThat(currencies.contains(currency)); }); } /** Testing if we can delete a new currency2. * Adding the currency2 at the end so the other tests don't give false results because the currency was deleted * */ @Test public void deleteCurrency2() { //given Currency2 btc = new Currency2.CurrencyBuilder("BTC", "Bitcoin").number_of_coins(16770000L).market_cap(189580000000L).build(); //when currencyController.deleteCurrency2(btc.getTicker()); //then assertThat(!currencyRepository2.existsById(btc.getTicker())); currencyRepository2.save(btc); } /** Testing if we can post a new currency2. * Deleting the currency2 at the end so it won't interfere with other tests * */ @Test public void postCurrency2(){ Currency2 btd = new Currency2.CurrencyBuilder("BTd", "Bitcoined").number_of_coins(16770000L).market_cap(189580000000L).build(); //when currencyController.postCurrency2(btd); //then assertThat(currencyRepository2.existsById(btd.getTicker())); currencyController.deleteCurrency2(btd.getTicker()); } /** Testing if we can update a currency2 * Afterwards returning it to the original so it doesn't interfere with other tests*/ @Test public void putCurrency2(){ Currency2 btcUpdate = new Currency2.CurrencyBuilder("BTC", "Bitcoinz").number_of_coins(167700000L).market_cap(1895800000L).build(); Currency2 btc = new Currency2.CurrencyBuilder("BTC", "Bitcoin").number_of_coins(16770000L).market_cap(189580000000L).build(); //when currencyController.putCurrency2(btcUpdate, btcUpdate.getTicker()); Currency2 updatedBtc = currencyController.getOneCurrency2(btcUpdate.getTicker()); //then assertThat(updatedBtc.getName().equals(btcUpdate.getName())); assertThat(updatedBtc.getTicker().equals(btcUpdate.getTicker())); assertThat(updatedBtc.getMarket_cap() == btcUpdate.getMarket_cap()); assertThat(updatedBtc.getNumber_of_coins() == btcUpdate.getNumber_of_coins()); currencyController.putCurrency2(btc, btcUpdate.getTicker()); } /** Testing to see if the database is pre-filled with 4 currencies2 */ @Test public void checkingDatabaseFilled2(){ int databaseSize = currencyService.getAllCurrencies2(0, 10, "ticker").size(); assertThat(databaseSize == 4); } }
6,606
0.752044
0.712685
204
31.382353
32.601288
133
false
false
0
0
0
0
0
0
1.647059
false
false
2
ace85cfd39e6b63ab499c399440f9de56c0771e6
16,423,954,971,477
fea8e7336c70ce4ed062e30c1627376f041380fc
/app/src/main/java/com/yuncai/call/tdvrcall/MainActivity.java
a289d77ab4777bc2bb40c323e45add62f7eb8455
[]
no_license
stoneWangL/laidianxiu
https://github.com/stoneWangL/laidianxiu
533b466f8f50e5c6a822b308c5230a67b5c3a278
808a9a218c0c4391a000aa6eb787bd735bc1cca4
refs/heads/master
2022-01-05T07:27:36.565000
2018-12-27T10:44:05
2018-12-27T10:44:05
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.yuncai.call.tdvrcall; import android.content.Intent; import android.content.SharedPreferences; import android.net.Uri; import android.os.Bundle; import android.preference.PreferenceManager; import android.provider.Contacts; import android.provider.Settings; import android.support.annotation.Nullable; import android.support.design.widget.TextInputLayout; import android.support.v4.app.Fragment; import android.support.v4.view.ViewPager; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.view.LayoutInflater; import android.view.View; import android.view.WindowManager; import android.widget.Button; import android.widget.EditText; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.TextView; import com.yuncai.call.tdvrcall.activity.DutyStatisticsActivity; import com.yuncai.call.tdvrcall.activity.VoiceRecordActivity; import com.yuncai.call.tdvrcall.adapter.FragmentAdapter; import com.yuncai.call.tdvrcall.fragment.QuickDialFragment; import com.yuncai.call.tdvrcall.leavingmsg.RecordingActivity; import com.yuncai.call.tdvrcall.service.CallService; import com.yuncai.call.tdvrcall.service.IncomingCallService; import com.yuncai.call.tdvrcall.util.TimeThread; import java.util.ArrayList; public class MainActivity extends AppCompatActivity { private static final int REQUEST_CODE = 1; private ViewPager viewpager; private RadioGroup rgQuickDialGroup; private RadioButton rbGroup1; private RadioButton rbGroup2; private RadioButton rbGroup3; private RadioButton rbGroup4; private RadioButton rbGroup5; private TextView btnGroupEdit; private TextView tvSetting; private TextView tvVoiceRecord; private TextView tvDutyStatistics; private TextView tvLeavingMsg; private TextView tvAddressBook; private TextView tvCallInfo; private TextView tvDial; private TextView tvDateTime; // 组名键值 private String GROUP_KEY1 = "group1"; private String GROUP_KEY2 = "group2"; private String GROUP_KEY3 = "group3"; private String GROUP_KEY4 = "group4"; private String GROUP_KEY5 = "group5"; private Button btnGroupNameCancel; private Button btnSaveGroupName; private EditText etGroupName5; private TextInputLayout groupnameWrapper5; private EditText etGroupName4; private TextInputLayout groupnameWrapper4; private EditText etGroupName3; private TextInputLayout groupnameWrapper3; private EditText etGroupName2; private TextInputLayout groupnameWrapper2; private EditText etGroupName1; private TextInputLayout groupnameWrapper1; private AlertDialog alertEditGroupDialog; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN); setContentView(R.layout.activity_main); initView(); initViewPager(); initGroupName(); showSystemDateTime(); initSetData(); startPhoneCoreService(); } private void startPhoneCoreService() { // 启动来电去电服务 startService(new Intent(this, IncomingCallService.class)); startService(new Intent(this, CallService.class)); } private void initGroupName() { SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this); // 显示原来的组名 String strGroup1 = sp.getString(GROUP_KEY1, getString(R.string.group_null_name)); String strGroup2 = sp.getString(GROUP_KEY2, getString(R.string.group_null_name)); String strGroup3 = sp.getString(GROUP_KEY3, getString(R.string.group_null_name)); String strGroup4 = sp.getString(GROUP_KEY4, getString(R.string.group_null_name)); String strGroup5 = sp.getString(GROUP_KEY5, getString(R.string.group_null_name)); rbGroup1.setText(strGroup1); rbGroup2.setText(strGroup2); rbGroup3.setText(strGroup3); rbGroup4.setText(strGroup4); rbGroup5.setText(strGroup5); } private void initSetData() { // 系统设置 tvSetting.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(Settings.ACTION_SETTINGS); startActivity(intent); } }); // 录音记录 tvVoiceRecord.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { startActivity(new Intent(MainActivity.this, VoiceRecordActivity.class)); } }); // 值班统计 tvDutyStatistics.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { startActivity(new Intent(MainActivity.this, DutyStatisticsActivity.class)); } }); // 交办留言 tvLeavingMsg.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { startActivity(new Intent(MainActivity.this, RecordingActivity.class)); } }); // 联系人 tvAddressBook.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(); intent.setAction(Intent.ACTION_VIEW); intent.setData(Contacts.People.CONTENT_URI); startActivity(intent); } }); // 通话记录 tvCallInfo.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(Intent.ACTION_DIAL); startActivity(intent); } }); // 拨号 tvDial.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:")); startActivity(intent); } }); } private void showSystemDateTime() { //实时更新时间(1秒更新一次) TimeThread timeThread = new TimeThread(tvDateTime);//tvDate 是显示时间的控件TextView timeThread.start(); } private void initView() { tvDateTime = findViewById(R.id.tv_date_time); viewpager = findViewById(R.id.viewpager); rgQuickDialGroup = findViewById(R.id.rg_quick_dial_group); rbGroup1 = findViewById(R.id.rb_group1); rbGroup2 = findViewById(R.id.rb_group2); rbGroup3 = findViewById(R.id.rb_group3); rbGroup4 = findViewById(R.id.rb_group4); rbGroup5 = findViewById(R.id.rb_group5); btnGroupEdit = findViewById(R.id.btn_group_edit); tvSetting = findViewById(R.id.tv_setting); tvVoiceRecord = findViewById(R.id.tv_voice_record); tvDutyStatistics = findViewById(R.id.tv_duty_statistics); tvLeavingMsg = findViewById(R.id.tv_leaving_msg); tvAddressBook = findViewById(R.id.tv_address_book); tvCallInfo = findViewById(R.id.tv_call_info); tvDial = findViewById(R.id.tv_dial); } private void initEditGroupNameDialogView(View view) { groupnameWrapper1 = view.findViewById(R.id.groupnameWrapper1); etGroupName1 = view.findViewById(R.id.et_group_name1); groupnameWrapper2 = view.findViewById(R.id.groupnameWrapper2); etGroupName2 = view.findViewById(R.id.et_group_name2); groupnameWrapper3 = view.findViewById(R.id.groupnameWrapper3); etGroupName3 = view.findViewById(R.id.et_group_name3); groupnameWrapper4 = view.findViewById(R.id.groupnameWrapper4); etGroupName4 = view.findViewById(R.id.et_group_name4); groupnameWrapper5 = view.findViewById(R.id.groupnameWrapper5); etGroupName5 = view.findViewById(R.id.et_group_name5); btnSaveGroupName = view.findViewById(R.id.btn_save_group_name); btnGroupNameCancel = view.findViewById(R.id.btn_group_name_cancel); } private void initViewPager() { // 一键拨号,分组 ArrayList<Integer> titles = new ArrayList<>(); titles.add(1); titles.add(2); titles.add(3); titles.add(4); titles.add(5); ArrayList<Fragment> fragments = new ArrayList<>(); for (int i = 0; i < titles.size(); i++) { fragments.add(QuickDialFragment.newInstance("" + titles.get(i), "")); } FragmentAdapter fragmentAdapter = new FragmentAdapter(getSupportFragmentManager(), fragments); viewpager.setAdapter(fragmentAdapter); viewpager.setCurrentItem(0); rbGroup1.setChecked(true); viewpager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() { @Override public void onPageScrolled(int i, float v, int i1) { } @Override public void onPageSelected(int selectPageIndex) { showTitleButtonState(selectPageIndex); } @Override public void onPageScrollStateChanged(int i) { } }); rgQuickDialGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup radioGroup, int i) { showQuickDialContactPage(i); } }); btnGroupEdit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { View dialogEditGroupView = LayoutInflater.from(MainActivity.this).inflate(R.layout.edit_group_name_dialog, null); initEditGroupNameDialogView(dialogEditGroupView); initGroupNameDialogData(); alertEditGroupDialog = new AlertDialog.Builder(MainActivity.this).setView(dialogEditGroupView).create(); alertEditGroupDialog.show(); } }); } // 组名编辑 private void initGroupNameDialogData() { final SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this); // 显示原来的组名 String strGroup1 = sp.getString(GROUP_KEY1, getString(R.string.group_null_name)); String strGroup2 = sp.getString(GROUP_KEY2, getString(R.string.group_null_name)); String strGroup3 = sp.getString(GROUP_KEY3, getString(R.string.group_null_name)); String strGroup4 = sp.getString(GROUP_KEY4, getString(R.string.group_null_name)); String strGroup5 = sp.getString(GROUP_KEY5, getString(R.string.group_null_name)); etGroupName1.setText(strGroup1); etGroupName2.setText(strGroup2); etGroupName3.setText(strGroup3); etGroupName4.setText(strGroup4); etGroupName5.setText(strGroup5); btnSaveGroupName.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String groupName1 = etGroupName1.getText().toString(); String groupName2 = etGroupName2.getText().toString(); String groupName3 = etGroupName3.getText().toString(); String groupName4 = etGroupName4.getText().toString(); String groupName5 = etGroupName5.getText().toString(); sp.edit().putString(GROUP_KEY1,groupName1) .putString(GROUP_KEY2,groupName2) .putString(GROUP_KEY3,groupName3) .putString(GROUP_KEY4,groupName4) .putString(GROUP_KEY5,groupName5).apply(); if(alertEditGroupDialog!=null && alertEditGroupDialog.isShowing()){ alertEditGroupDialog.dismiss(); } initGroupName();// 刷新主界面 } }); btnGroupNameCancel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if(alertEditGroupDialog!=null && alertEditGroupDialog.isShowing()){ alertEditGroupDialog.dismiss(); } } }); } private void showQuickDialContactPage(int res_id) { switch (res_id) { case R.id.rb_group1: viewpager.setCurrentItem(0); break; case R.id.rb_group2: viewpager.setCurrentItem(1); break; case R.id.rb_group3: viewpager.setCurrentItem(2); break; case R.id.rb_group4: viewpager.setCurrentItem(3); break; case R.id.rb_group5: viewpager.setCurrentItem(4); break; } } private void showTitleButtonState(int selectPageIndex) { switch (selectPageIndex) { case 0: rbGroup1.setChecked(true); break; case 1: rbGroup2.setChecked(true); break; case 2: rbGroup3.setChecked(true); break; case 3: rbGroup4.setChecked(true); break; case 4: rbGroup5.setChecked(true); break; } } }
UTF-8
Java
13,605
java
MainActivity.java
Java
[ { "context": "me;\n\n // 组名键值\n private String GROUP_KEY1 = \"group1\";\n private String GROUP_KEY2 = \"group2\";\n p", "end": 2009, "score": 0.941153883934021, "start": 2003, "tag": "KEY", "value": "group1" }, { "context": "KEY1 = \"group1\";\n private String GROUP_KE...
null
[]
package com.yuncai.call.tdvrcall; import android.content.Intent; import android.content.SharedPreferences; import android.net.Uri; import android.os.Bundle; import android.preference.PreferenceManager; import android.provider.Contacts; import android.provider.Settings; import android.support.annotation.Nullable; import android.support.design.widget.TextInputLayout; import android.support.v4.app.Fragment; import android.support.v4.view.ViewPager; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.view.LayoutInflater; import android.view.View; import android.view.WindowManager; import android.widget.Button; import android.widget.EditText; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.TextView; import com.yuncai.call.tdvrcall.activity.DutyStatisticsActivity; import com.yuncai.call.tdvrcall.activity.VoiceRecordActivity; import com.yuncai.call.tdvrcall.adapter.FragmentAdapter; import com.yuncai.call.tdvrcall.fragment.QuickDialFragment; import com.yuncai.call.tdvrcall.leavingmsg.RecordingActivity; import com.yuncai.call.tdvrcall.service.CallService; import com.yuncai.call.tdvrcall.service.IncomingCallService; import com.yuncai.call.tdvrcall.util.TimeThread; import java.util.ArrayList; public class MainActivity extends AppCompatActivity { private static final int REQUEST_CODE = 1; private ViewPager viewpager; private RadioGroup rgQuickDialGroup; private RadioButton rbGroup1; private RadioButton rbGroup2; private RadioButton rbGroup3; private RadioButton rbGroup4; private RadioButton rbGroup5; private TextView btnGroupEdit; private TextView tvSetting; private TextView tvVoiceRecord; private TextView tvDutyStatistics; private TextView tvLeavingMsg; private TextView tvAddressBook; private TextView tvCallInfo; private TextView tvDial; private TextView tvDateTime; // 组名键值 private String GROUP_KEY1 = "group1"; private String GROUP_KEY2 = "group2"; private String GROUP_KEY3 = "group3"; private String GROUP_KEY4 = "group4"; private String GROUP_KEY5 = "group5"; private Button btnGroupNameCancel; private Button btnSaveGroupName; private EditText etGroupName5; private TextInputLayout groupnameWrapper5; private EditText etGroupName4; private TextInputLayout groupnameWrapper4; private EditText etGroupName3; private TextInputLayout groupnameWrapper3; private EditText etGroupName2; private TextInputLayout groupnameWrapper2; private EditText etGroupName1; private TextInputLayout groupnameWrapper1; private AlertDialog alertEditGroupDialog; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN); setContentView(R.layout.activity_main); initView(); initViewPager(); initGroupName(); showSystemDateTime(); initSetData(); startPhoneCoreService(); } private void startPhoneCoreService() { // 启动来电去电服务 startService(new Intent(this, IncomingCallService.class)); startService(new Intent(this, CallService.class)); } private void initGroupName() { SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this); // 显示原来的组名 String strGroup1 = sp.getString(GROUP_KEY1, getString(R.string.group_null_name)); String strGroup2 = sp.getString(GROUP_KEY2, getString(R.string.group_null_name)); String strGroup3 = sp.getString(GROUP_KEY3, getString(R.string.group_null_name)); String strGroup4 = sp.getString(GROUP_KEY4, getString(R.string.group_null_name)); String strGroup5 = sp.getString(GROUP_KEY5, getString(R.string.group_null_name)); rbGroup1.setText(strGroup1); rbGroup2.setText(strGroup2); rbGroup3.setText(strGroup3); rbGroup4.setText(strGroup4); rbGroup5.setText(strGroup5); } private void initSetData() { // 系统设置 tvSetting.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(Settings.ACTION_SETTINGS); startActivity(intent); } }); // 录音记录 tvVoiceRecord.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { startActivity(new Intent(MainActivity.this, VoiceRecordActivity.class)); } }); // 值班统计 tvDutyStatistics.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { startActivity(new Intent(MainActivity.this, DutyStatisticsActivity.class)); } }); // 交办留言 tvLeavingMsg.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { startActivity(new Intent(MainActivity.this, RecordingActivity.class)); } }); // 联系人 tvAddressBook.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(); intent.setAction(Intent.ACTION_VIEW); intent.setData(Contacts.People.CONTENT_URI); startActivity(intent); } }); // 通话记录 tvCallInfo.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(Intent.ACTION_DIAL); startActivity(intent); } }); // 拨号 tvDial.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:")); startActivity(intent); } }); } private void showSystemDateTime() { //实时更新时间(1秒更新一次) TimeThread timeThread = new TimeThread(tvDateTime);//tvDate 是显示时间的控件TextView timeThread.start(); } private void initView() { tvDateTime = findViewById(R.id.tv_date_time); viewpager = findViewById(R.id.viewpager); rgQuickDialGroup = findViewById(R.id.rg_quick_dial_group); rbGroup1 = findViewById(R.id.rb_group1); rbGroup2 = findViewById(R.id.rb_group2); rbGroup3 = findViewById(R.id.rb_group3); rbGroup4 = findViewById(R.id.rb_group4); rbGroup5 = findViewById(R.id.rb_group5); btnGroupEdit = findViewById(R.id.btn_group_edit); tvSetting = findViewById(R.id.tv_setting); tvVoiceRecord = findViewById(R.id.tv_voice_record); tvDutyStatistics = findViewById(R.id.tv_duty_statistics); tvLeavingMsg = findViewById(R.id.tv_leaving_msg); tvAddressBook = findViewById(R.id.tv_address_book); tvCallInfo = findViewById(R.id.tv_call_info); tvDial = findViewById(R.id.tv_dial); } private void initEditGroupNameDialogView(View view) { groupnameWrapper1 = view.findViewById(R.id.groupnameWrapper1); etGroupName1 = view.findViewById(R.id.et_group_name1); groupnameWrapper2 = view.findViewById(R.id.groupnameWrapper2); etGroupName2 = view.findViewById(R.id.et_group_name2); groupnameWrapper3 = view.findViewById(R.id.groupnameWrapper3); etGroupName3 = view.findViewById(R.id.et_group_name3); groupnameWrapper4 = view.findViewById(R.id.groupnameWrapper4); etGroupName4 = view.findViewById(R.id.et_group_name4); groupnameWrapper5 = view.findViewById(R.id.groupnameWrapper5); etGroupName5 = view.findViewById(R.id.et_group_name5); btnSaveGroupName = view.findViewById(R.id.btn_save_group_name); btnGroupNameCancel = view.findViewById(R.id.btn_group_name_cancel); } private void initViewPager() { // 一键拨号,分组 ArrayList<Integer> titles = new ArrayList<>(); titles.add(1); titles.add(2); titles.add(3); titles.add(4); titles.add(5); ArrayList<Fragment> fragments = new ArrayList<>(); for (int i = 0; i < titles.size(); i++) { fragments.add(QuickDialFragment.newInstance("" + titles.get(i), "")); } FragmentAdapter fragmentAdapter = new FragmentAdapter(getSupportFragmentManager(), fragments); viewpager.setAdapter(fragmentAdapter); viewpager.setCurrentItem(0); rbGroup1.setChecked(true); viewpager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() { @Override public void onPageScrolled(int i, float v, int i1) { } @Override public void onPageSelected(int selectPageIndex) { showTitleButtonState(selectPageIndex); } @Override public void onPageScrollStateChanged(int i) { } }); rgQuickDialGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup radioGroup, int i) { showQuickDialContactPage(i); } }); btnGroupEdit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { View dialogEditGroupView = LayoutInflater.from(MainActivity.this).inflate(R.layout.edit_group_name_dialog, null); initEditGroupNameDialogView(dialogEditGroupView); initGroupNameDialogData(); alertEditGroupDialog = new AlertDialog.Builder(MainActivity.this).setView(dialogEditGroupView).create(); alertEditGroupDialog.show(); } }); } // 组名编辑 private void initGroupNameDialogData() { final SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this); // 显示原来的组名 String strGroup1 = sp.getString(GROUP_KEY1, getString(R.string.group_null_name)); String strGroup2 = sp.getString(GROUP_KEY2, getString(R.string.group_null_name)); String strGroup3 = sp.getString(GROUP_KEY3, getString(R.string.group_null_name)); String strGroup4 = sp.getString(GROUP_KEY4, getString(R.string.group_null_name)); String strGroup5 = sp.getString(GROUP_KEY5, getString(R.string.group_null_name)); etGroupName1.setText(strGroup1); etGroupName2.setText(strGroup2); etGroupName3.setText(strGroup3); etGroupName4.setText(strGroup4); etGroupName5.setText(strGroup5); btnSaveGroupName.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String groupName1 = etGroupName1.getText().toString(); String groupName2 = etGroupName2.getText().toString(); String groupName3 = etGroupName3.getText().toString(); String groupName4 = etGroupName4.getText().toString(); String groupName5 = etGroupName5.getText().toString(); sp.edit().putString(GROUP_KEY1,groupName1) .putString(GROUP_KEY2,groupName2) .putString(GROUP_KEY3,groupName3) .putString(GROUP_KEY4,groupName4) .putString(GROUP_KEY5,groupName5).apply(); if(alertEditGroupDialog!=null && alertEditGroupDialog.isShowing()){ alertEditGroupDialog.dismiss(); } initGroupName();// 刷新主界面 } }); btnGroupNameCancel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if(alertEditGroupDialog!=null && alertEditGroupDialog.isShowing()){ alertEditGroupDialog.dismiss(); } } }); } private void showQuickDialContactPage(int res_id) { switch (res_id) { case R.id.rb_group1: viewpager.setCurrentItem(0); break; case R.id.rb_group2: viewpager.setCurrentItem(1); break; case R.id.rb_group3: viewpager.setCurrentItem(2); break; case R.id.rb_group4: viewpager.setCurrentItem(3); break; case R.id.rb_group5: viewpager.setCurrentItem(4); break; } } private void showTitleButtonState(int selectPageIndex) { switch (selectPageIndex) { case 0: rbGroup1.setChecked(true); break; case 1: rbGroup2.setChecked(true); break; case 2: rbGroup3.setChecked(true); break; case 3: rbGroup4.setChecked(true); break; case 4: rbGroup5.setChecked(true); break; } } }
13,605
0.636458
0.625289
346
37.812138
25.034126
129
false
false
0
0
0
0
0
0
0.66763
false
false
2
e54667349676bdb46efd4eeb8efa50ebc0d2b92d
29,059,748,766,729
e9072556b050e74e09a8c3f18c555f4a53c8ed77
/priest-satellite-manager/src/main/java/com/kinstalk/satellite/filter/AdminLoginFilter.java
9e4d7cc842b66c3df29bccc988d0cee6c949a746
[ "Apache-2.0" ]
permissive
coder-blog/satellite
https://github.com/coder-blog/satellite
40db51db219e2cbe804095df00f95144fd32af50
f0b398fa4dc89029a7e90489f2b1dfbb123e2719
refs/heads/master
2021-01-24T11:36:14.399000
2018-03-20T03:41:49
2018-03-20T03:41:49
123,091,955
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.kinstalk.satellite.filter; import com.google.gson.Gson; import com.google.gson.JsonArray; import com.google.gson.JsonObject; import com.google.gson.reflect.TypeToken; import com.kinstalk.satellite.domain.AdminUser; import com.kinstalk.satellite.domain.Menu; import com.kinstalk.satellite.domain.RunScriptTimerDetail; import com.kinstalk.satellite.service.api.AdminUserService; import com.kinstalk.satellite.utils.CacheUtils; import com.kinstalk.satellite.utils.CookieUtils; import com.kinstalk.satellite.utils.EncryptUtil; import net.sf.ehcache.Element; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.ApplicationContext; import org.springframework.web.context.ContextLoader; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import sun.misc.BASE64Decoder; import javax.servlet.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.ResourceBundle; public class AdminLoginFilter implements Filter { private Logger logger = LoggerFactory.getLogger(AdminLoginFilter.class); //cookie 超时时间,默认一天。 //private String cookieTimeout = "864//白名单列表。00"; private List<String> whiteListUrl = new ArrayList<String>(); private String passportUrl = ""; private AdminUserService adminUserService; // 系统分类.如新统计系统menuTypeId是1,在web.xml里面进行配置。 private String menuTypeId = ""; private static final String rightErrorPage = "/rightError"; public static final boolean isMac = System.getProperty("os.name") != null && System.getProperty("os.name").toLowerCase().contains("mac"); public static final boolean isWindows = System.getProperty("os.name") != null && System.getProperty("os.name").toLowerCase().contains("windows"); public static String USER_MENU_FILTER_KEY = "user_menu_filter_key"; public static String USER_MENU_HTML_FIELD = "user_menu_html_key_"; public static String USER_MENU_JSON_FIELD = "user_menu_json_key_"; @Override public void init(FilterConfig filterConfig) throws ServletException { this.passportUrl = ResourceBundle.getBundle("project").getString("priest.return.url"); this.menuTypeId = filterConfig.getInitParameter("menuTypeId"); //this.cookieTimeout = filterConfig.getInitParameter("cookieTimeout"); String tmpWhiteListUrl = filterConfig.getInitParameter("whiteListUrl"); if (tmpWhiteListUrl != null && !tmpWhiteListUrl.equals("")) { String[] tmpWhiteListUrlList = tmpWhiteListUrl.split(","); Collections.addAll(whiteListUrl, tmpWhiteListUrlList); } //System.out.println("cookieTimeout:" + cookieTimeout); logger.debug("whiteListUrl:{}", whiteListUrl); } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { HttpServletRequest httpRequest = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest(); HttpServletResponse httpResponse = (HttpServletResponse) servletResponse; String url = httpRequest.getPathInfo(); String referer = httpRequest.getHeader("referer"); boolean isWhiteUrl = false; //增加判断白名单。 for (String whiteUrl : whiteListUrl) { if (whiteUrl != null && url.startsWith(whiteUrl)) { isWhiteUrl = true; } } //如果是白名单直接返回,不进行权限过滤。 if (isWhiteUrl) { filterChain.doFilter(servletRequest, servletResponse); return; } // try { // if (url != null && !url.equals("")) { // URL urlTmp = new URL(url); // referer = urlTmp.getProtocol() + "://" + urlTmp.getHost(); // } // } catch (MalformedURLException e) { // } // (String) httpRequest.getSession().getAttribute("passport_user"); String userId = null; //测试使用。 //String userId = "zhangsan"; //httpRequest.getSession().setAttribute("passport_user", userId); boolean isLogin = false; //判断用户登录。 //测试cookie登陆。 String passportCode = CookieUtils.getCookie(httpRequest, "passport_code"); //校验key。 String passportKey = CookieUtils.getCookie(httpRequest, "passport_key"); if (passportCode != null && !passportCode.equals("") && passportKey != null && !passportKey.equals("")) { //生成校验字符串。 String newPassportKey = EncryptUtil.sha(passportCode); if (newPassportKey != null && newPassportKey.equals(passportKey)) { //校验成功。 userId = AdminLoginFilter.passportDecoder(passportCode); //校验成功,将userId放到 passport_user 里面。 //httpRequest.getSession().setAttribute("passport_user", userId); isLogin = true; } } // 本机开发。 // if (isWindows || isMac) { // // 如果是windows返回测试,系统的用户 // userId = "dev_test_" + menuTypeId; // isLogin = true; // } //判断用户是否登录,然后进行拦截,跳转到登录页面。 if (!isLogin) { String newPassportUrl = String.format(this.passportUrl, referer); httpResponse.sendRedirect(newPassportUrl); } // 设置缓存数据 RunScriptTimerDetail.UserMenuJson userMenuJson = null; String userMenuJsonStr = null;//(UserMenuJson) httpRequest.getSession().getAttribute("UserMenuJsonCache"); Element jsonElement = CacheUtils.getElementByKeyAndField(USER_MENU_FILTER_KEY, USER_MENU_JSON_FIELD + userId); try { if(jsonElement != null) { userMenuJsonStr = (String) jsonElement.getValue(); } } catch (Exception e) {// 有可能缓存会有问题. logger.error("Read Cache Fail", e); } //存储字符串。 if (userMenuJsonStr == null || userMenuJsonStr.contains("\"menuList\":[]") || userMenuJsonStr.equals("") || "{\"menuList\":[]}".equals(userMenuJsonStr)) { // 获得json接口数据. userMenuJsonStr = getUserMenuJson(userId); logger.debug(userMenuJsonStr); CacheUtils.setElementByKeyAndField(USER_MENU_FILTER_KEY, USER_MENU_JSON_FIELD + userId, userMenuJsonStr); } // 字符替换处理 //str = commReplace(str); Gson gson = new Gson(); //System.out.println(str); Type type = new TypeToken<RunScriptTimerDetail.UserMenuJson>() { }.getType(); try { // 转换后的json. userMenuJson = gson.fromJson(userMenuJsonStr, type); } catch (Exception e) { e.printStackTrace(); } // 3分钟更新一次缓存.***************结束*************** if (userMenuJson != null) { // 设置用户名 //httpRequest.setAttribute("UserName", userMenuJson.getUserName()); httpRequest.setAttribute("UserName", userId); JsonArray menuJsonArray = new JsonArray(); List<Menu> menuList = userMenuJson.getMenuList(); if (menuList != null && menuList.size() > 0) { menuJsonArray = loopMenuJson(menuList, "_self"); } // 添加到数组里面 // menuTypeJson.add("nodes", menuJsonArray); // 放到页面展示 httpRequest.setAttribute("MenuUserList", new Gson().toJson(menuJsonArray)); //增加用户菜单. // httpRequest.setAttribute("MenuList", userMenuJson.getMenuList()); } // 统计的url是 /admin/开始的 if (url.indexOf("/admin/") == 0 && !url.contains("/admin/index")) { // /pages/admin/index.jsp 不包括首页 if (userMenuJson != null && userMenuJson.getMenuList() != null) { boolean haveRight = false; // 用户菜单 for (Menu userMenu : userMenuJson.getMenuList()) { // 判断系统是否有权限 if (userMenu != null && userMenu.getUrl() != null && url.equals(userMenu.getUrl())) { // 有权限 haveRight = true; // break;循环全部 } } // 判断用户是否没有权限//查询全部菜单. if (!haveRight) { haveRight = true; for (Menu userMenu : userMenuJson.getMenuList()) { // 判断系统是否没有有权限 if (userMenu != null && userMenu.getUrl() != null && url.equals(userMenu.getUrl())) { // 有权限 haveRight = false; // break;循环全部 } } } if (haveRight) { if (httpResponse != null && httpRequest != null) { filterChain.doFilter(servletRequest, servletResponse); } return; } else { httpResponse.sendRedirect(rightErrorPage); return; } } else { httpResponse.sendRedirect(rightErrorPage); return; } } else { if (httpResponse != null && httpRequest != null) { filterChain.doFilter(servletRequest, servletResponse); } return; } } private String getUserMenuJson(String uid) { // 返回类 JsonObject tmpJson = new JsonObject(); /* 用户菜单json. */ JsonArray menuJsonArray = new JsonArray(); if (adminUserService == null) { ApplicationContext act = ContextLoader.getCurrentWebApplicationContext(); adminUserService = (AdminUserService) act.getBean("adminUserService"); } AdminUser adminUser = adminUserService.queryAdminUserAndMenuList(uid); if (adminUser != null && adminUser.getMenuList() != null) { for (Menu menu : adminUser.getMenuList()) { // set json属性。 // 得到当前系统菜单. JsonObject menuJson = new JsonObject(); menuJson.addProperty("name", menu.getName()); menuJson.addProperty("id", menu.getId()); menuJson.addProperty("url", menu.getUrl()); menuJson.addProperty("parentId", menu.getParentId()); menuJson.addProperty("level", menu.getLevel()); menuJson.addProperty("orderId", menu.getOrderId()); menuJsonArray.add(menuJson); } // 返回菜单权限 tmpJson.add("menuList", menuJsonArray); tmpJson.addProperty("userName", adminUser.getName()); } return new Gson().toJson(tmpJson); } @Override public void destroy() { } //对密码进行加密解密,默认使用一个最简单的方式。 public static String passportEncoder(String str) { return BASE64Encoder(str); } public static String passportDecoder(String str) { return BASE64Decoder(str); } // 将 s 进行 BASE64 编码 private static String BASE64Encoder(String str) { if (str == null) return null; try { return (new sun.misc.BASE64Encoder()).encode(str.getBytes()); } catch (Exception e) { return null; } } // 将 BASE64 编码的字符串 s 进行解码 private static String BASE64Decoder(String str) { if (str == null) return null; BASE64Decoder decoder = new BASE64Decoder();// try { byte[] b = decoder.decodeBuffer(str); return new String(b); } catch (Exception e) { return null; } } /** * 递归json 组装数组. */ private JsonArray loopMenuJson(List<com.kinstalk.satellite.domain.Menu> menuList, String a_target) { JsonArray menuJsonArray = new JsonArray(); for (com.kinstalk.satellite.domain.Menu menu : menuList) { JsonObject menuJson = new JsonObject(); menuJson.addProperty("id", menu.getId()); menuJson.addProperty("name", menu.getName()); menuJson.addProperty("url", menu.getUrl()); menuJson.addProperty("open", true); menuJson.addProperty("level", menu.getLevel()); menuJson.addProperty("parentId", menu.getParentId()); if (menu.getChildren() != null) { // 添加到子节点 JsonArray childrenMenuJsonArray = loopMenuJson( menu.getChildren(), a_target); menuJson.add("children", childrenMenuJsonArray); } menuJsonArray.add(menuJson); } return menuJsonArray; } }
UTF-8
Java
11,666
java
AdminLoginFilter.java
Java
[ { "context": "ing userId = null;\n\t\t//测试使用。\n\t\t//String userId = \"zhangsan\";\n\t\t//httpRequest.getSession().setAttribute(\"pass", "end": 4019, "score": 0.9991964101791382, "start": 4011, "tag": "USERNAME", "value": "zhangsan" }, { "context": "menuJsonArray);\n\t\t\ttmpJson.add...
null
[]
package com.kinstalk.satellite.filter; import com.google.gson.Gson; import com.google.gson.JsonArray; import com.google.gson.JsonObject; import com.google.gson.reflect.TypeToken; import com.kinstalk.satellite.domain.AdminUser; import com.kinstalk.satellite.domain.Menu; import com.kinstalk.satellite.domain.RunScriptTimerDetail; import com.kinstalk.satellite.service.api.AdminUserService; import com.kinstalk.satellite.utils.CacheUtils; import com.kinstalk.satellite.utils.CookieUtils; import com.kinstalk.satellite.utils.EncryptUtil; import net.sf.ehcache.Element; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.ApplicationContext; import org.springframework.web.context.ContextLoader; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import sun.misc.BASE64Decoder; import javax.servlet.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.ResourceBundle; public class AdminLoginFilter implements Filter { private Logger logger = LoggerFactory.getLogger(AdminLoginFilter.class); //cookie 超时时间,默认一天。 //private String cookieTimeout = "864//白名单列表。00"; private List<String> whiteListUrl = new ArrayList<String>(); private String passportUrl = ""; private AdminUserService adminUserService; // 系统分类.如新统计系统menuTypeId是1,在web.xml里面进行配置。 private String menuTypeId = ""; private static final String rightErrorPage = "/rightError"; public static final boolean isMac = System.getProperty("os.name") != null && System.getProperty("os.name").toLowerCase().contains("mac"); public static final boolean isWindows = System.getProperty("os.name") != null && System.getProperty("os.name").toLowerCase().contains("windows"); public static String USER_MENU_FILTER_KEY = "user_menu_filter_key"; public static String USER_MENU_HTML_FIELD = "user_menu_html_key_"; public static String USER_MENU_JSON_FIELD = "user_menu_json_key_"; @Override public void init(FilterConfig filterConfig) throws ServletException { this.passportUrl = ResourceBundle.getBundle("project").getString("priest.return.url"); this.menuTypeId = filterConfig.getInitParameter("menuTypeId"); //this.cookieTimeout = filterConfig.getInitParameter("cookieTimeout"); String tmpWhiteListUrl = filterConfig.getInitParameter("whiteListUrl"); if (tmpWhiteListUrl != null && !tmpWhiteListUrl.equals("")) { String[] tmpWhiteListUrlList = tmpWhiteListUrl.split(","); Collections.addAll(whiteListUrl, tmpWhiteListUrlList); } //System.out.println("cookieTimeout:" + cookieTimeout); logger.debug("whiteListUrl:{}", whiteListUrl); } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { HttpServletRequest httpRequest = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest(); HttpServletResponse httpResponse = (HttpServletResponse) servletResponse; String url = httpRequest.getPathInfo(); String referer = httpRequest.getHeader("referer"); boolean isWhiteUrl = false; //增加判断白名单。 for (String whiteUrl : whiteListUrl) { if (whiteUrl != null && url.startsWith(whiteUrl)) { isWhiteUrl = true; } } //如果是白名单直接返回,不进行权限过滤。 if (isWhiteUrl) { filterChain.doFilter(servletRequest, servletResponse); return; } // try { // if (url != null && !url.equals("")) { // URL urlTmp = new URL(url); // referer = urlTmp.getProtocol() + "://" + urlTmp.getHost(); // } // } catch (MalformedURLException e) { // } // (String) httpRequest.getSession().getAttribute("passport_user"); String userId = null; //测试使用。 //String userId = "zhangsan"; //httpRequest.getSession().setAttribute("passport_user", userId); boolean isLogin = false; //判断用户登录。 //测试cookie登陆。 String passportCode = CookieUtils.getCookie(httpRequest, "passport_code"); //校验key。 String passportKey = CookieUtils.getCookie(httpRequest, "passport_key"); if (passportCode != null && !passportCode.equals("") && passportKey != null && !passportKey.equals("")) { //生成校验字符串。 String newPassportKey = EncryptUtil.sha(passportCode); if (newPassportKey != null && newPassportKey.equals(passportKey)) { //校验成功。 userId = AdminLoginFilter.passportDecoder(passportCode); //校验成功,将userId放到 passport_user 里面。 //httpRequest.getSession().setAttribute("passport_user", userId); isLogin = true; } } // 本机开发。 // if (isWindows || isMac) { // // 如果是windows返回测试,系统的用户 // userId = "dev_test_" + menuTypeId; // isLogin = true; // } //判断用户是否登录,然后进行拦截,跳转到登录页面。 if (!isLogin) { String newPassportUrl = String.format(this.passportUrl, referer); httpResponse.sendRedirect(newPassportUrl); } // 设置缓存数据 RunScriptTimerDetail.UserMenuJson userMenuJson = null; String userMenuJsonStr = null;//(UserMenuJson) httpRequest.getSession().getAttribute("UserMenuJsonCache"); Element jsonElement = CacheUtils.getElementByKeyAndField(USER_MENU_FILTER_KEY, USER_MENU_JSON_FIELD + userId); try { if(jsonElement != null) { userMenuJsonStr = (String) jsonElement.getValue(); } } catch (Exception e) {// 有可能缓存会有问题. logger.error("Read Cache Fail", e); } //存储字符串。 if (userMenuJsonStr == null || userMenuJsonStr.contains("\"menuList\":[]") || userMenuJsonStr.equals("") || "{\"menuList\":[]}".equals(userMenuJsonStr)) { // 获得json接口数据. userMenuJsonStr = getUserMenuJson(userId); logger.debug(userMenuJsonStr); CacheUtils.setElementByKeyAndField(USER_MENU_FILTER_KEY, USER_MENU_JSON_FIELD + userId, userMenuJsonStr); } // 字符替换处理 //str = commReplace(str); Gson gson = new Gson(); //System.out.println(str); Type type = new TypeToken<RunScriptTimerDetail.UserMenuJson>() { }.getType(); try { // 转换后的json. userMenuJson = gson.fromJson(userMenuJsonStr, type); } catch (Exception e) { e.printStackTrace(); } // 3分钟更新一次缓存.***************结束*************** if (userMenuJson != null) { // 设置用户名 //httpRequest.setAttribute("UserName", userMenuJson.getUserName()); httpRequest.setAttribute("UserName", userId); JsonArray menuJsonArray = new JsonArray(); List<Menu> menuList = userMenuJson.getMenuList(); if (menuList != null && menuList.size() > 0) { menuJsonArray = loopMenuJson(menuList, "_self"); } // 添加到数组里面 // menuTypeJson.add("nodes", menuJsonArray); // 放到页面展示 httpRequest.setAttribute("MenuUserList", new Gson().toJson(menuJsonArray)); //增加用户菜单. // httpRequest.setAttribute("MenuList", userMenuJson.getMenuList()); } // 统计的url是 /admin/开始的 if (url.indexOf("/admin/") == 0 && !url.contains("/admin/index")) { // /pages/admin/index.jsp 不包括首页 if (userMenuJson != null && userMenuJson.getMenuList() != null) { boolean haveRight = false; // 用户菜单 for (Menu userMenu : userMenuJson.getMenuList()) { // 判断系统是否有权限 if (userMenu != null && userMenu.getUrl() != null && url.equals(userMenu.getUrl())) { // 有权限 haveRight = true; // break;循环全部 } } // 判断用户是否没有权限//查询全部菜单. if (!haveRight) { haveRight = true; for (Menu userMenu : userMenuJson.getMenuList()) { // 判断系统是否没有有权限 if (userMenu != null && userMenu.getUrl() != null && url.equals(userMenu.getUrl())) { // 有权限 haveRight = false; // break;循环全部 } } } if (haveRight) { if (httpResponse != null && httpRequest != null) { filterChain.doFilter(servletRequest, servletResponse); } return; } else { httpResponse.sendRedirect(rightErrorPage); return; } } else { httpResponse.sendRedirect(rightErrorPage); return; } } else { if (httpResponse != null && httpRequest != null) { filterChain.doFilter(servletRequest, servletResponse); } return; } } private String getUserMenuJson(String uid) { // 返回类 JsonObject tmpJson = new JsonObject(); /* 用户菜单json. */ JsonArray menuJsonArray = new JsonArray(); if (adminUserService == null) { ApplicationContext act = ContextLoader.getCurrentWebApplicationContext(); adminUserService = (AdminUserService) act.getBean("adminUserService"); } AdminUser adminUser = adminUserService.queryAdminUserAndMenuList(uid); if (adminUser != null && adminUser.getMenuList() != null) { for (Menu menu : adminUser.getMenuList()) { // set json属性。 // 得到当前系统菜单. JsonObject menuJson = new JsonObject(); menuJson.addProperty("name", menu.getName()); menuJson.addProperty("id", menu.getId()); menuJson.addProperty("url", menu.getUrl()); menuJson.addProperty("parentId", menu.getParentId()); menuJson.addProperty("level", menu.getLevel()); menuJson.addProperty("orderId", menu.getOrderId()); menuJsonArray.add(menuJson); } // 返回菜单权限 tmpJson.add("menuList", menuJsonArray); tmpJson.addProperty("userName", adminUser.getName()); } return new Gson().toJson(tmpJson); } @Override public void destroy() { } //对密码进行加密解密,默认使用一个最简单的方式。 public static String passportEncoder(String str) { return BASE64Encoder(str); } public static String passportDecoder(String str) { return BASE64Decoder(str); } // 将 s 进行 BASE64 编码 private static String BASE64Encoder(String str) { if (str == null) return null; try { return (new sun.misc.BASE64Encoder()).encode(str.getBytes()); } catch (Exception e) { return null; } } // 将 BASE64 编码的字符串 s 进行解码 private static String BASE64Decoder(String str) { if (str == null) return null; BASE64Decoder decoder = new BASE64Decoder();// try { byte[] b = decoder.decodeBuffer(str); return new String(b); } catch (Exception e) { return null; } } /** * 递归json 组装数组. */ private JsonArray loopMenuJson(List<com.kinstalk.satellite.domain.Menu> menuList, String a_target) { JsonArray menuJsonArray = new JsonArray(); for (com.kinstalk.satellite.domain.Menu menu : menuList) { JsonObject menuJson = new JsonObject(); menuJson.addProperty("id", menu.getId()); menuJson.addProperty("name", menu.getName()); menuJson.addProperty("url", menu.getUrl()); menuJson.addProperty("open", true); menuJson.addProperty("level", menu.getLevel()); menuJson.addProperty("parentId", menu.getParentId()); if (menu.getChildren() != null) { // 添加到子节点 JsonArray childrenMenuJsonArray = loopMenuJson( menu.getChildren(), a_target); menuJson.add("children", childrenMenuJsonArray); } menuJsonArray.add(menuJson); } return menuJsonArray; } }
11,666
0.692364
0.689532
372
28.430107
27.494143
156
false
false
0
0
0
0
0
0
2.392473
false
false
2
cad9d8d3247bb24c9e56e0480bd69959cd66b597
2,370,821,979,677
91a40fc0c3b17bf3ae2a594ecbafa40df9b3091f
/src/main/java/com/mihil/App.java
e2fa3ec1cbda771555f55b9ef3f9407f9e00d59f
[ "MIT" ]
permissive
mihilranathunga/iosPushSender
https://github.com/mihilranathunga/iosPushSender
5654b8cfb7e7c3647fb27a997c4f5b50d1db14a1
eb8d852c416e456656d775a1bd8705b4ea2d8616
refs/heads/master
2021-03-27T08:39:14.184000
2016-11-30T11:20:17
2016-11-30T11:20:17
75,179,410
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.mihil; import com.notnoop.apns.APNS; import com.notnoop.apns.ApnsDelegate; import com.notnoop.apns.ApnsService; import com.notnoop.apns.EnhancedApnsNotification; import java.util.Date; /** * Hello world! */ public class App { public static void main(String[] args) { ApnsDelegate delegate = new NotificationDelegate(); ApnsService service = APNS.newService() //.withCert("egypt_apns_prod.p12", "123456") .withCert("dbfs_apns_prod.p12", "123456") //.withCert("global_push_no_prod.p12", "123456") .withDelegate(delegate) .withSandboxDestination() //.withProductionDestination() .build(); String payload = APNS.newPayload().alertBody("First one!").badge(1).sound("push").customField("mt", "rm").build(); String token = "8020ac842a8e693b382b34521688eda25273b4ce027e5ad6400a162e5d39ec90"; int now = (int) (new Date().getTime() / 1000); EnhancedApnsNotification notification = new EnhancedApnsNotification(EnhancedApnsNotification.INCREMENT_ID() /* Next ID */, now + 60 * 1 /* Expire in one minute */, token /* Device Token */, payload); try { service.push(notification); } catch (Exception e) { System.out.println(e.getMessage()); } } }
UTF-8
Java
1,490
java
App.java
Java
[ { "context": "ield(\"mt\", \"rm\").build();\n String token = \"8020ac842a8e693b382b34521688eda25273b4ce027e5ad6400a162e5d39ec90\";\n\n int now = (int) (new Date().getTime() ", "end": 1020, "score": 0.9748570919036865, "start": 956, "tag": "KEY", "value": "8020ac842a8e693b382b34...
null
[]
package com.mihil; import com.notnoop.apns.APNS; import com.notnoop.apns.ApnsDelegate; import com.notnoop.apns.ApnsService; import com.notnoop.apns.EnhancedApnsNotification; import java.util.Date; /** * Hello world! */ public class App { public static void main(String[] args) { ApnsDelegate delegate = new NotificationDelegate(); ApnsService service = APNS.newService() //.withCert("egypt_apns_prod.p12", "123456") .withCert("dbfs_apns_prod.p12", "123456") //.withCert("global_push_no_prod.p12", "123456") .withDelegate(delegate) .withSandboxDestination() //.withProductionDestination() .build(); String payload = APNS.newPayload().alertBody("First one!").badge(1).sound("push").customField("mt", "rm").build(); String token = "8020ac842a8e693b382b34521688eda25273b4ce027e5ad6400a162e5d39ec90"; int now = (int) (new Date().getTime() / 1000); EnhancedApnsNotification notification = new EnhancedApnsNotification(EnhancedApnsNotification.INCREMENT_ID() /* Next ID */, now + 60 * 1 /* Expire in one minute */, token /* Device Token */, payload); try { service.push(notification); } catch (Exception e) { System.out.println(e.getMessage()); } } }
1,490
0.574497
0.52349
43
33.651161
31.272905
131
false
false
0
0
0
0
64
0.042953
0.488372
false
false
2
19eb5848ed9f7a678eff14cb8a134db7b4c10314
12,970,801,267,450
49b65a380a78dad9c81bff610dd52a56f15212c0
/all new naya java/CORE_Java_prog/Chapter7/excep1.java
a0c9f6e1d6b8ab387081d344f3e2e3f94e2ff8c4
[]
no_license
harry611/myLocalTestRepo
https://github.com/harry611/myLocalTestRepo
fac53d5013844886a9b8f45456d504fc8afb35f7
cf7654af62724a8193e66e5963844f442559104a
refs/heads/master
2022-01-20T20:01:12.098000
2018-08-07T06:49:56
2018-08-07T06:49:56
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
class excep1 { public static void main(String args[]) { int a=Integer.parseInt(args[0]); int b=Integer.parseInt(args[1]); int c; try { c=a/b; System.out.println(" C value in try block:" + c); } catch(ArithmeticException e) { System.out.println(" Div: Error "); c=a/3; System.out.println(" c value in catch block: "+ c); } } } /* try { ...... ...... } catch(exceptiontype e) { ...... ....... } */
UTF-8
Java
414
java
excep1.java
Java
[]
null
[]
class excep1 { public static void main(String args[]) { int a=Integer.parseInt(args[0]); int b=Integer.parseInt(args[1]); int c; try { c=a/b; System.out.println(" C value in try block:" + c); } catch(ArithmeticException e) { System.out.println(" Div: Error "); c=a/3; System.out.println(" c value in catch block: "+ c); } } } /* try { ...... ...... } catch(exceptiontype e) { ...... ....... } */
414
0.582126
0.572464
45
8.155556
13.894773
52
false
false
0
0
0
0
0
0
0.177778
false
false
2
fd613da0f0c5699801131a55a932948e76e6b656
21,440,476,779,503
49713f2f12d0edb1e7bea2e7659b4e00796e587c
/siseduca-ejb/src/test/java/br/com/cdan/negocio/pedagogico/factory/SituacaoDoAlunoNaTurmaFabricaTest.java
63103524659d0cd9fd0b9f9a9c205fa4ebd53495
[]
no_license
drm2003/siseduca
https://github.com/drm2003/siseduca
7dd06396ce0ec39fe75be15c9fdbcb1a62238d4b
1016f9160deb92613e15989e51699f343ff3b65d
refs/heads/master
2021-01-21T15:53:44.390000
2016-05-16T14:40:15
2016-05-16T14:40:15
54,774,588
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package br.com.cdan.negocio.pedagogico.factory; import javax.persistence.EntityManager; import br.com.cdan.model.pedagogico.SituacaoDoAlunoNaTurma; import br.com.cdan.negocio.pedagogico.SituacaoDoAlunoNaTurmaDao; public class SituacaoDoAlunoNaTurmaFabricaTest { private static SituacaoDoAlunoNaTurmaFabricaTest instance = null; public static synchronized SituacaoDoAlunoNaTurmaFabricaTest getInstance() { if (instance == null) { instance = new SituacaoDoAlunoNaTurmaFabricaTest(); } return instance; } public SituacaoDoAlunoNaTurma criaSituacaoDoAlunoNaTurma() { SituacaoDoAlunoNaTurma s = new SituacaoDoAlunoNaTurma(); s.setAbreviatura("abreviatura"); s.setAtivo(Boolean.TRUE); s.setCompartilhado(Boolean.TRUE); s.setDescricao("descricao"); // return s; } public SituacaoDoAlunoNaTurma criaSituacaoDoAlunoNaTurmaPersistido(EntityManager em) { SituacaoDoAlunoNaTurma s = criaSituacaoDoAlunoNaTurma(); SituacaoDoAlunoNaTurmaDao dao = new SituacaoDoAlunoNaTurmaDao(em); // dao.persist(s); return s; } }
UTF-8
Java
1,047
java
SituacaoDoAlunoNaTurmaFabricaTest.java
Java
[]
null
[]
package br.com.cdan.negocio.pedagogico.factory; import javax.persistence.EntityManager; import br.com.cdan.model.pedagogico.SituacaoDoAlunoNaTurma; import br.com.cdan.negocio.pedagogico.SituacaoDoAlunoNaTurmaDao; public class SituacaoDoAlunoNaTurmaFabricaTest { private static SituacaoDoAlunoNaTurmaFabricaTest instance = null; public static synchronized SituacaoDoAlunoNaTurmaFabricaTest getInstance() { if (instance == null) { instance = new SituacaoDoAlunoNaTurmaFabricaTest(); } return instance; } public SituacaoDoAlunoNaTurma criaSituacaoDoAlunoNaTurma() { SituacaoDoAlunoNaTurma s = new SituacaoDoAlunoNaTurma(); s.setAbreviatura("abreviatura"); s.setAtivo(Boolean.TRUE); s.setCompartilhado(Boolean.TRUE); s.setDescricao("descricao"); // return s; } public SituacaoDoAlunoNaTurma criaSituacaoDoAlunoNaTurmaPersistido(EntityManager em) { SituacaoDoAlunoNaTurma s = criaSituacaoDoAlunoNaTurma(); SituacaoDoAlunoNaTurmaDao dao = new SituacaoDoAlunoNaTurmaDao(em); // dao.persist(s); return s; } }
1,047
0.797517
0.797517
35
28.914286
27.117071
87
false
false
0
0
0
0
0
0
1.628571
false
false
2
e91c6747ee3a760e3d22d8632b0804443d3182ec
30,829,275,282,852
090eecec3a9361d23f2590d964ea8dd8227f2261
/Main1.java
2fd26c6e9a33f6e767133966769e44a8fc83310b
[]
no_license
Dodger456/Project3
https://github.com/Dodger456/Project3
6e1ae4d6d6f5b12dc3ce4f24cdc071fc0bf42b69
524dbe7aace8aed1b9106cc168f7e0d03b72cb23
refs/heads/master
2020-03-11T15:46:34.873000
2018-04-19T20:51:39
2018-04-19T20:51:39
130,095,619
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.awt.Color; import java.util.Scanner; public class Main1 { public static void main(String[] args) throws InterruptedException { Scanner keyboard = new Scanner(System.in); int counter = 1, num=100, counter2=1; ImageUtils util = new ImageUtils(); Color[][] news = util.loadImage("src/LennaCV.png"); Color[][] myNewImage = processNew(news); System.out.println("What color would you like to change picture to red, green, or blue?"); String quad1 = keyboard.next(); if (quad1.equalsIgnoreCase("red")) { System.out.println("**Please wait while your picture is loading**\n\n"); while (counter2<20) { util.addImage(process(news,counter),"tab"); util.display(); counter2++; Thread.sleep(300); util.removeTabs(); counter=counter+30; } counter=0; System.out.println("**Your color is now being changed**"); while (counter<10) { util.addImage( myNewImage, "tab"); util.display(); Thread.sleep(3*num); util.removeTabs(); util.addImage(processRed(news), "tab"); Thread.sleep(3*num); util.removeTabs(); util.addImage(processGreen(news), "tab"); Thread.sleep(3*num); util.removeTabs(); util.addImage(processBlue(news), "tab"); Thread.sleep(3*num); util.removeTabs(); counter ++; num= num-10; } util.addImage(processRed(news), "tab"); } else if (quad1.equalsIgnoreCase("green")) { System.out.println("**Please wait while your picture is loading**\n\n"); while (counter2<20) { util.addImage(process(news,counter),"tab"); util.display(); counter2++; Thread.sleep(300); util.removeTabs(); counter=counter+30; } counter=0; System.out.println("**Your color is now being changed**"); while (counter<10) { util.addImage( myNewImage, "tab"); util.display(); Thread.sleep(3*num); util.removeTabs(); util.addImage(processRed(news), "tab"); Thread.sleep(3*num); util.removeTabs(); util.addImage(processGreen(news), "tab"); Thread.sleep(3*num); util.removeTabs(); util.addImage(processBlue(news), "tab"); Thread.sleep(3*num); util.removeTabs(); counter ++; num= num-10; } util.addImage(processGreen(news), "tab"); } else if (quad1.equalsIgnoreCase("blue")) { System.out.println("**Please wait while your picture is loading**\n\n"); while (counter2<20) { util.addImage(process(news,counter),"tab"); util.display(); counter2++; Thread.sleep(300); util.removeTabs(); counter=counter+30; } counter=0; System.out.println("**Your color is now being changed**"); while (counter<10) { util.addImage( myNewImage, "tab"); util.display(); Thread.sleep(3*num); util.removeTabs(); util.addImage(processRed(news), "tab"); Thread.sleep(3*num); util.removeTabs(); util.addImage(processGreen(news), "tab"); Thread.sleep(3*num); util.removeTabs(); util.addImage(processBlue(news), "tab"); Thread.sleep(3*num); util.removeTabs(); counter ++; num= num-10; } util.addImage(processBlue(news), "tab"); counter=0; } } public static Color[][] process(Color[][] img, int a){ Color[][] tmp = ImageUtils.cloneArray(img); for (int i =0; i < tmp.length; i++) { for (int j=0; j< tmp[i].length; j++) { if (j<tmp.length-a) { // Red, Green, Blue : 0-250 Color pixel = tmp[i][j]; int r = pixel.getRed(); int g = pixel.getGreen(); int b = pixel.getBlue(); int h = pixel.getTransparency(); tmp[i][j] = new Color(0,0,0); } if (i<tmp.length-a) { Color pixel = tmp[i][j]; int r = pixel.getRed(); int g = pixel.getGreen(); int b = pixel.getBlue(); int h = pixel.getTransparency(); tmp[i][j] = new Color(0,0,0); } } } return tmp; } public static Color[][] processBlue(Color[][] img){ Color[][] tmp = ImageUtils.cloneArray(img); for (int i =0; i < tmp.length; i++) { for (int j=0; j< tmp[i].length; j++) { if (i<tmp.length) { Color pixel = tmp[i][j]; int h = pixel.getTransparency(); int b = pixel.getBlue(); tmp[i][j] = new Color(h,h,b); } } } return tmp; } public static Color[][] processGreen(Color[][] img){ Color[][] tmp = ImageUtils.cloneArray(img); for (int i =0; i < tmp.length; i++) { for (int j=0; j< tmp[i].length; j++) { if (i<tmp.length) { Color pixel = tmp[i][j]; int h = pixel.getTransparency(); int g = pixel.getGreen(); tmp[i][j] = new Color(h,g,h); } } } return tmp; } public static Color[][] processRed(Color[][] img){ Color[][] tmp = ImageUtils.cloneArray(img); for (int i =0; i < tmp.length; i++) { for (int j=0; j< tmp[i].length; j++) { if (i<tmp.length) { Color pixel = tmp[i][j]; int r = pixel.getRed(); int h = pixel.getTransparency(); tmp[i][j] = new Color(r,h,h); } } } return tmp; } public static Color[][] processNew(Color[][] img){ Color[][] tmp = ImageUtils.cloneArray(img); for (int i =0; i < tmp.length; i++) { for (int j=0; j< tmp[i].length; j++) { if (i<tmp.length) { Color pixel = tmp[i][j]; int r = pixel.getRed(); int g = pixel.getGreen(); int b = pixel.getBlue(); int h = pixel.getTransparency(); tmp[i][j] = new Color(r,g,b); } } } return tmp; } public static Color[][] processNew2(Color[][] img){ Color[][] tmp = ImageUtils.cloneArray(img); for (int i =0; i < tmp.length; i++) { for (int j=0; j< tmp[i].length; j++) { if (i<tmp.length) { Color pixel = tmp[i][j]; int r = pixel.getRed(); int g = pixel.getGreen(); int b = pixel.getBlue(); int h = pixel.getTransparency(); tmp[i][j] = new Color(r,h,h); } } } return tmp; } }
UTF-8
Java
6,200
java
Main1.java
Java
[]
null
[]
import java.awt.Color; import java.util.Scanner; public class Main1 { public static void main(String[] args) throws InterruptedException { Scanner keyboard = new Scanner(System.in); int counter = 1, num=100, counter2=1; ImageUtils util = new ImageUtils(); Color[][] news = util.loadImage("src/LennaCV.png"); Color[][] myNewImage = processNew(news); System.out.println("What color would you like to change picture to red, green, or blue?"); String quad1 = keyboard.next(); if (quad1.equalsIgnoreCase("red")) { System.out.println("**Please wait while your picture is loading**\n\n"); while (counter2<20) { util.addImage(process(news,counter),"tab"); util.display(); counter2++; Thread.sleep(300); util.removeTabs(); counter=counter+30; } counter=0; System.out.println("**Your color is now being changed**"); while (counter<10) { util.addImage( myNewImage, "tab"); util.display(); Thread.sleep(3*num); util.removeTabs(); util.addImage(processRed(news), "tab"); Thread.sleep(3*num); util.removeTabs(); util.addImage(processGreen(news), "tab"); Thread.sleep(3*num); util.removeTabs(); util.addImage(processBlue(news), "tab"); Thread.sleep(3*num); util.removeTabs(); counter ++; num= num-10; } util.addImage(processRed(news), "tab"); } else if (quad1.equalsIgnoreCase("green")) { System.out.println("**Please wait while your picture is loading**\n\n"); while (counter2<20) { util.addImage(process(news,counter),"tab"); util.display(); counter2++; Thread.sleep(300); util.removeTabs(); counter=counter+30; } counter=0; System.out.println("**Your color is now being changed**"); while (counter<10) { util.addImage( myNewImage, "tab"); util.display(); Thread.sleep(3*num); util.removeTabs(); util.addImage(processRed(news), "tab"); Thread.sleep(3*num); util.removeTabs(); util.addImage(processGreen(news), "tab"); Thread.sleep(3*num); util.removeTabs(); util.addImage(processBlue(news), "tab"); Thread.sleep(3*num); util.removeTabs(); counter ++; num= num-10; } util.addImage(processGreen(news), "tab"); } else if (quad1.equalsIgnoreCase("blue")) { System.out.println("**Please wait while your picture is loading**\n\n"); while (counter2<20) { util.addImage(process(news,counter),"tab"); util.display(); counter2++; Thread.sleep(300); util.removeTabs(); counter=counter+30; } counter=0; System.out.println("**Your color is now being changed**"); while (counter<10) { util.addImage( myNewImage, "tab"); util.display(); Thread.sleep(3*num); util.removeTabs(); util.addImage(processRed(news), "tab"); Thread.sleep(3*num); util.removeTabs(); util.addImage(processGreen(news), "tab"); Thread.sleep(3*num); util.removeTabs(); util.addImage(processBlue(news), "tab"); Thread.sleep(3*num); util.removeTabs(); counter ++; num= num-10; } util.addImage(processBlue(news), "tab"); counter=0; } } public static Color[][] process(Color[][] img, int a){ Color[][] tmp = ImageUtils.cloneArray(img); for (int i =0; i < tmp.length; i++) { for (int j=0; j< tmp[i].length; j++) { if (j<tmp.length-a) { // Red, Green, Blue : 0-250 Color pixel = tmp[i][j]; int r = pixel.getRed(); int g = pixel.getGreen(); int b = pixel.getBlue(); int h = pixel.getTransparency(); tmp[i][j] = new Color(0,0,0); } if (i<tmp.length-a) { Color pixel = tmp[i][j]; int r = pixel.getRed(); int g = pixel.getGreen(); int b = pixel.getBlue(); int h = pixel.getTransparency(); tmp[i][j] = new Color(0,0,0); } } } return tmp; } public static Color[][] processBlue(Color[][] img){ Color[][] tmp = ImageUtils.cloneArray(img); for (int i =0; i < tmp.length; i++) { for (int j=0; j< tmp[i].length; j++) { if (i<tmp.length) { Color pixel = tmp[i][j]; int h = pixel.getTransparency(); int b = pixel.getBlue(); tmp[i][j] = new Color(h,h,b); } } } return tmp; } public static Color[][] processGreen(Color[][] img){ Color[][] tmp = ImageUtils.cloneArray(img); for (int i =0; i < tmp.length; i++) { for (int j=0; j< tmp[i].length; j++) { if (i<tmp.length) { Color pixel = tmp[i][j]; int h = pixel.getTransparency(); int g = pixel.getGreen(); tmp[i][j] = new Color(h,g,h); } } } return tmp; } public static Color[][] processRed(Color[][] img){ Color[][] tmp = ImageUtils.cloneArray(img); for (int i =0; i < tmp.length; i++) { for (int j=0; j< tmp[i].length; j++) { if (i<tmp.length) { Color pixel = tmp[i][j]; int r = pixel.getRed(); int h = pixel.getTransparency(); tmp[i][j] = new Color(r,h,h); } } } return tmp; } public static Color[][] processNew(Color[][] img){ Color[][] tmp = ImageUtils.cloneArray(img); for (int i =0; i < tmp.length; i++) { for (int j=0; j< tmp[i].length; j++) { if (i<tmp.length) { Color pixel = tmp[i][j]; int r = pixel.getRed(); int g = pixel.getGreen(); int b = pixel.getBlue(); int h = pixel.getTransparency(); tmp[i][j] = new Color(r,g,b); } } } return tmp; } public static Color[][] processNew2(Color[][] img){ Color[][] tmp = ImageUtils.cloneArray(img); for (int i =0; i < tmp.length; i++) { for (int j=0; j< tmp[i].length; j++) { if (i<tmp.length) { Color pixel = tmp[i][j]; int r = pixel.getRed(); int g = pixel.getGreen(); int b = pixel.getBlue(); int h = pixel.getTransparency(); tmp[i][j] = new Color(r,h,h); } } } return tmp; } }
6,200
0.55
0.535645
269
21.048326
18.152224
92
false
false
0
0
0
0
0
0
3.557621
false
false
2
dd1750611f2740aa039b4eca6bd9279941f631a7
10,711,648,484,883
6f672fb72caedccb841ee23f53e32aceeaf1895e
/Pandora_source/src/com/yume/android/bsp/t.java
30e2df6570d39990c309c873fd5abf432f33b482
[]
no_license
cha63506/CompSecurity
https://github.com/cha63506/CompSecurity
5c69743f660b9899146ed3cf21eceabe3d5f4280
eee7e74f4088b9c02dd711c061fc04fb1e4e2654
refs/heads/master
2018-03-23T04:15:18.480000
2015-12-19T01:29:58
2015-12-19T01:29:58
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
// Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov. // Jad home page: http://www.geocities.com/kpdus/jad.html // Decompiler options: braces fieldsfirst space lnc package com.yume.android.bsp; import android.content.SharedPreferences; import android.os.Binder; import android.os.Parcel; // Referenced classes of package com.yume.android.bsp: // YuMeUUIDService final class t extends Binder { private YuMeUUIDService a; t(YuMeUUIDService yumeuuidservice) { a = yumeuuidservice; super(); } public final boolean onTransact(int i, Parcel parcel, Parcel parcel1, int j) { SharedPreferences sharedpreferences = a.getSharedPreferences("uuid_prefs", 0); parcel1.writeInt(parcel.readInt()); parcel1.writeString(sharedpreferences.getString("uuid", null)); return true; } }
UTF-8
Java
868
java
t.java
Java
[ { "context": "// Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov.\n// Jad home page: http://www.geocities.com/kpdus", "end": 61, "score": 0.9996681213378906, "start": 45, "tag": "NAME", "value": "Pavel Kouznetsov" } ]
null
[]
// Decompiled by Jad v1.5.8e. Copyright 2001 <NAME>. // Jad home page: http://www.geocities.com/kpdus/jad.html // Decompiler options: braces fieldsfirst space lnc package com.yume.android.bsp; import android.content.SharedPreferences; import android.os.Binder; import android.os.Parcel; // Referenced classes of package com.yume.android.bsp: // YuMeUUIDService final class t extends Binder { private YuMeUUIDService a; t(YuMeUUIDService yumeuuidservice) { a = yumeuuidservice; super(); } public final boolean onTransact(int i, Parcel parcel, Parcel parcel1, int j) { SharedPreferences sharedpreferences = a.getSharedPreferences("uuid_prefs", 0); parcel1.writeInt(parcel.readInt()); parcel1.writeString(sharedpreferences.getString("uuid", null)); return true; } }
858
0.700461
0.687788
32
26.125
25.520519
86
false
false
0
0
0
0
0
0
0.5
false
false
2
73e06ca4ad7aace74b3ddd9f2c424d7d2e896c80
10,711,648,482,944
a280aa9ac69d3834dc00219e9a4ba07996dfb4dd
/regularexpress/home/weilaidb/work/app/hadoop-2.7.3-src/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapreduce/lib/input/SequenceFileAsTextRecordReader.java
25d0460174f567ced912b8122dfc219866d58c72
[]
no_license
weilaidb/PythonExample
https://github.com/weilaidb/PythonExample
b2cc6c514816a0e1bfb7c0cbd5045cf87bd28466
798bf1bdfdf7594f528788c4df02f79f0f7827ce
refs/heads/master
2021-01-12T13:56:19.346000
2017-07-22T16:30:33
2017-07-22T16:30:33
68,925,741
4
2
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.apache.hadoop.mapreduce.lib.input; import java.io.IOException; import org.apache.hadoop.classification.InterfaceAudience; import org.apache.hadoop.classification.InterfaceStability; import org.apache.hadoop.io.Text; import org.apache.hadoop.io.Writable; import org.apache.hadoop.io.WritableComparable; import org.apache.hadoop.mapreduce.InputSplit; import org.apache.hadoop.mapreduce.RecordReader; import org.apache.hadoop.mapreduce.TaskAttemptContext; @InterfaceAudience.Public @InterfaceStability.Stable public class SequenceFileAsTextRecordReader extends RecordReader<Text, Text>
UTF-8
Java
595
java
SequenceFileAsTextRecordReader.java
Java
[]
null
[]
package org.apache.hadoop.mapreduce.lib.input; import java.io.IOException; import org.apache.hadoop.classification.InterfaceAudience; import org.apache.hadoop.classification.InterfaceStability; import org.apache.hadoop.io.Text; import org.apache.hadoop.io.Writable; import org.apache.hadoop.io.WritableComparable; import org.apache.hadoop.mapreduce.InputSplit; import org.apache.hadoop.mapreduce.RecordReader; import org.apache.hadoop.mapreduce.TaskAttemptContext; @InterfaceAudience.Public @InterfaceStability.Stable public class SequenceFileAsTextRecordReader extends RecordReader<Text, Text>
595
0.858824
0.858824
14
41.5
11.197895
59
false
false
0
0
0
0
0
0
0.785714
false
false
2
3112bec75c5b435c932fe3ef1239a73e88baa209
26,302,379,727,723
341b816e7c6deb6a2332f26c3bdbd7db79052c0f
/Data-Structures/src/test/java/treeIntersection/TreeIntersectionTest.java
4e47778f7eeef64265d15ec8fdf1b6dac6c73e48
[]
no_license
martinpapacodes/data-structures-and-algorithms
https://github.com/martinpapacodes/data-structures-and-algorithms
4cd7b4c057b021faf4ce24ed5855ef790a36477c
b235816dc2f04d90deb40d02be15502aa7d4f63f
refs/heads/master
2020-09-23T06:56:19.730000
2020-03-07T18:23:29
2020-03-07T18:23:29
225,432,673
0
0
null
false
2020-03-07T18:23:30
2019-12-02T17:35:24
2020-03-06T01:41:43
2020-03-07T18:23:29
20,039
0
0
0
JavaScript
false
false
package treeIntersection; import org.junit.Test; import static org.junit.Assert.*; public class TreeIntersectionTest { TreeIntersection test; Node rootOne; Node rootTwo; @Test public void tree_intersectionTest() { String expected = "[160, 100, 500, 200, 125, 350, 175]"; test = new TreeIntersection(); rootOne = test.insertNode(rootOne, 150); rootOne = test.insertNode(rootOne, 100); rootOne = test.insertNode(rootOne, 250); rootOne = test.insertNode(rootOne, 75); rootOne = test.insertNode(rootOne, 160); rootOne = test.insertNode(rootOne, 200); rootOne = test.insertNode(rootOne, 350); rootOne = test.insertNode(rootOne, 125); rootOne = test.insertNode(rootOne, 175); rootOne = test.insertNode(rootOne, 300); rootOne = test.insertNode(rootOne, 500); rootTwo = test.insertNode(rootTwo, 42); rootTwo = test.insertNode(rootTwo, 100); rootTwo = test.insertNode(rootTwo, 600); rootTwo = test.insertNode(rootTwo, 15); rootTwo = test.insertNode(rootTwo, 160); rootTwo = test.insertNode(rootTwo, 200); rootTwo = test.insertNode(rootTwo, 350); rootTwo = test.insertNode(rootTwo, 125); rootTwo = test.insertNode(rootTwo, 175); rootTwo = test.insertNode(rootTwo, 4); rootTwo = test.insertNode(rootTwo, 500); String actual = test.tree_intersection(rootOne, rootTwo).toString(); assertEquals(expected, actual); } @Test public void anotherTree_intersectionTest() { String expected = "[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]"; test = new TreeIntersection(); rootOne = test.insertNode(rootOne, 1); rootOne = test.insertNode(rootOne, 2); rootOne = test.insertNode(rootOne, 3); rootOne = test.insertNode(rootOne, 4); rootOne = test.insertNode(rootOne, 5); rootOne = test.insertNode(rootOne, 6); rootOne = test.insertNode(rootOne, 7); rootOne = test.insertNode(rootOne, 8); rootOne = test.insertNode(rootOne, 9); rootOne = test.insertNode(rootOne, 10); rootOne = test.insertNode(rootOne, 11); rootTwo = test.insertNode(rootTwo, 1); rootTwo = test.insertNode(rootTwo, 2); rootTwo = test.insertNode(rootTwo, 3); rootTwo = test.insertNode(rootTwo, 4); rootTwo = test.insertNode(rootTwo, 5); rootTwo = test.insertNode(rootTwo, 6); rootTwo = test.insertNode(rootTwo, 7); rootTwo = test.insertNode(rootTwo, 8); rootTwo = test.insertNode(rootTwo, 9); rootTwo = test.insertNode(rootTwo, 10); rootTwo = test.insertNode(rootTwo, 11); String actual = test.tree_intersection(rootOne, rootTwo).toString(); assertEquals(expected, actual); } @Test public void anotherAnotherTree_intersectionTest() { String expected = "[3, 53, 9, 234, 11]"; test = new TreeIntersection(); rootOne = test.insertNode(rootOne, 3); rootOne = test.insertNode(rootOne, 6); rootOne = test.insertNode(rootOne, 9); rootOne = test.insertNode(rootOne, 11); rootOne = test.insertNode(rootOne, 13); rootOne = test.insertNode(rootOne, 41); rootOne = test.insertNode(rootOne, 64); rootOne = test.insertNode(rootOne, 234); rootOne = test.insertNode(rootOne, 532); rootOne = test.insertNode(rootOne, 35); rootOne = test.insertNode(rootOne, 53); rootTwo = test.insertNode(rootTwo, 53); rootTwo = test.insertNode(rootTwo, 2); rootTwo = test.insertNode(rootTwo, 3); rootTwo = test.insertNode(rootTwo, 4); rootTwo = test.insertNode(rootTwo, 5); rootTwo = test.insertNode(rootTwo, 11); rootTwo = test.insertNode(rootTwo, 7); rootTwo = test.insertNode(rootTwo, 8); rootTwo = test.insertNode(rootTwo, 9); rootTwo = test.insertNode(rootTwo, 234); rootTwo = test.insertNode(rootTwo, 11); String actual = test.tree_intersection(rootOne, rootTwo).toString(); assertEquals(expected, actual); } }
UTF-8
Java
4,209
java
TreeIntersectionTest.java
Java
[]
null
[]
package treeIntersection; import org.junit.Test; import static org.junit.Assert.*; public class TreeIntersectionTest { TreeIntersection test; Node rootOne; Node rootTwo; @Test public void tree_intersectionTest() { String expected = "[160, 100, 500, 200, 125, 350, 175]"; test = new TreeIntersection(); rootOne = test.insertNode(rootOne, 150); rootOne = test.insertNode(rootOne, 100); rootOne = test.insertNode(rootOne, 250); rootOne = test.insertNode(rootOne, 75); rootOne = test.insertNode(rootOne, 160); rootOne = test.insertNode(rootOne, 200); rootOne = test.insertNode(rootOne, 350); rootOne = test.insertNode(rootOne, 125); rootOne = test.insertNode(rootOne, 175); rootOne = test.insertNode(rootOne, 300); rootOne = test.insertNode(rootOne, 500); rootTwo = test.insertNode(rootTwo, 42); rootTwo = test.insertNode(rootTwo, 100); rootTwo = test.insertNode(rootTwo, 600); rootTwo = test.insertNode(rootTwo, 15); rootTwo = test.insertNode(rootTwo, 160); rootTwo = test.insertNode(rootTwo, 200); rootTwo = test.insertNode(rootTwo, 350); rootTwo = test.insertNode(rootTwo, 125); rootTwo = test.insertNode(rootTwo, 175); rootTwo = test.insertNode(rootTwo, 4); rootTwo = test.insertNode(rootTwo, 500); String actual = test.tree_intersection(rootOne, rootTwo).toString(); assertEquals(expected, actual); } @Test public void anotherTree_intersectionTest() { String expected = "[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]"; test = new TreeIntersection(); rootOne = test.insertNode(rootOne, 1); rootOne = test.insertNode(rootOne, 2); rootOne = test.insertNode(rootOne, 3); rootOne = test.insertNode(rootOne, 4); rootOne = test.insertNode(rootOne, 5); rootOne = test.insertNode(rootOne, 6); rootOne = test.insertNode(rootOne, 7); rootOne = test.insertNode(rootOne, 8); rootOne = test.insertNode(rootOne, 9); rootOne = test.insertNode(rootOne, 10); rootOne = test.insertNode(rootOne, 11); rootTwo = test.insertNode(rootTwo, 1); rootTwo = test.insertNode(rootTwo, 2); rootTwo = test.insertNode(rootTwo, 3); rootTwo = test.insertNode(rootTwo, 4); rootTwo = test.insertNode(rootTwo, 5); rootTwo = test.insertNode(rootTwo, 6); rootTwo = test.insertNode(rootTwo, 7); rootTwo = test.insertNode(rootTwo, 8); rootTwo = test.insertNode(rootTwo, 9); rootTwo = test.insertNode(rootTwo, 10); rootTwo = test.insertNode(rootTwo, 11); String actual = test.tree_intersection(rootOne, rootTwo).toString(); assertEquals(expected, actual); } @Test public void anotherAnotherTree_intersectionTest() { String expected = "[3, 53, 9, 234, 11]"; test = new TreeIntersection(); rootOne = test.insertNode(rootOne, 3); rootOne = test.insertNode(rootOne, 6); rootOne = test.insertNode(rootOne, 9); rootOne = test.insertNode(rootOne, 11); rootOne = test.insertNode(rootOne, 13); rootOne = test.insertNode(rootOne, 41); rootOne = test.insertNode(rootOne, 64); rootOne = test.insertNode(rootOne, 234); rootOne = test.insertNode(rootOne, 532); rootOne = test.insertNode(rootOne, 35); rootOne = test.insertNode(rootOne, 53); rootTwo = test.insertNode(rootTwo, 53); rootTwo = test.insertNode(rootTwo, 2); rootTwo = test.insertNode(rootTwo, 3); rootTwo = test.insertNode(rootTwo, 4); rootTwo = test.insertNode(rootTwo, 5); rootTwo = test.insertNode(rootTwo, 11); rootTwo = test.insertNode(rootTwo, 7); rootTwo = test.insertNode(rootTwo, 8); rootTwo = test.insertNode(rootTwo, 9); rootTwo = test.insertNode(rootTwo, 234); rootTwo = test.insertNode(rootTwo, 11); String actual = test.tree_intersection(rootOne, rootTwo).toString(); assertEquals(expected, actual); } }
4,209
0.624614
0.584937
119
34.378151
21.138992
76
false
false
0
0
0
0
0
0
1.478992
false
false
2
d752097eeee275f3cac3a1b95c3bd55d22ff157e
22,737,556,899,629
8a7698af3a1005644dd82bad0021718caccf4a9c
/ingAsignment/src/test/java/com/ing/assignment/dto/AtmLimitDTOTest.java
23efa5165a4d86b9be9a4e3140ea859c8988b670
[]
no_license
SoumendraSogeti/ingAssignment
https://github.com/SoumendraSogeti/ingAssignment
e4ec930febce310fceaf2f039e9c8d8090893b4a
74272da175325bba8b4f5372c6edb2604dbe7275
refs/heads/main
2023-06-11T22:32:14.705000
2021-07-09T00:04:34
2021-07-09T00:04:34
384,259,473
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.ing.assignment.dto; import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; public class AtmLimitDTOTest { @Test public void atmLimitDTOTest(){ AtmLimitDTO atmLimitDTO = AtmLimitDTO.builder().limit(100).periodUnit("Month").build(); assertThat(atmLimitDTO.getLimit()).isEqualTo(100); assertThat(atmLimitDTO.getPeriodUnit()).isEqualTo("Month"); } }
UTF-8
Java
436
java
AtmLimitDTOTest.java
Java
[]
null
[]
package com.ing.assignment.dto; import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; public class AtmLimitDTOTest { @Test public void atmLimitDTOTest(){ AtmLimitDTO atmLimitDTO = AtmLimitDTO.builder().limit(100).periodUnit("Month").build(); assertThat(atmLimitDTO.getLimit()).isEqualTo(100); assertThat(atmLimitDTO.getPeriodUnit()).isEqualTo("Month"); } }
436
0.722477
0.708716
14
30.142857
29.127447
96
false
false
0
0
0
0
0
0
0.428571
false
false
2
ad1887569bbde7d91df415d4576b563381c57050
22,737,556,898,853
b2400ca22421d4132109b23f2ef3a0297d3d23a0
/app/src/main/java/edu/zhdata/android/zhapp/MyQuestionActivity.java
841d8fe81733196be08d6acffc027380eacfcf19
[ "Apache-2.0" ]
permissive
bestseason/ZHData
https://github.com/bestseason/ZHData
d9011bf273c76feb7df53c5a704c4420d8c3e619
f1ae8932ca705a8a2af5c72d7c7d2a02a65b5d9e
refs/heads/master
2020-12-24T21:22:51.695000
2017-03-27T09:03:10
2017-03-27T09:03:10
86,300,089
3
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package edu.zhdata.android.zhapp; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.view.View; import android.widget.AdapterView; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.SimpleAdapter; import android.widget.TextView; import android.widget.Toast; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import edu.zhdata.android.zhapp.entity.GetMyQuestion; import edu.zhdata.android.zhapp.tools.BaseNetwork1; public class MyQuestionActivity extends Activity { Handler handler=new Handler(){ public void handleMessage(Message message){ if(message.what==1){ SimpleAdapter sa=new SimpleAdapter(MyQuestionActivity.this,getDatalist,R.layout.activity_my_answer_listview,new String[]{"title","time"},new int[]{R.id.activity_my_answer_listview_tx1,R.id.activity_my_answer_listview_tx2}); lv.setAdapter(sa); if (sid.equals("-1")){ linearLayout.setBackgroundResource(R.drawable.empty); } }else if(message.what==2){ linearLayout.setBackgroundResource(R.drawable.empty); Toast.makeText(MyQuestionActivity.this,"请检查网络连接",Toast.LENGTH_SHORT).show(); }else if(message.what==3){ linearLayout.setBackgroundResource(R.drawable.empty); } } }; List<GetMyQuestion> list; private ImageView imageView; private ListView lv; private List<HashMap<String,Object>> datalist; private HashMap<String,Object> map; private String sid="163680"; private List<HashMap<String,Object>> getDatalist; private LinearLayout linearLayout; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_my_question); linearLayout=(LinearLayout)findViewById(R.id.activity_my_question_bg); lv=(ListView)findViewById(R.id.activity_my_question_list); lv.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Intent intent=new Intent(MyQuestionActivity.this,Question_page_Activity.class); intent.putExtra("Qid",list.get(position).getQid()); startActivity(intent); } }); Intent intent=getIntent(); sid=intent.getStringExtra("Sid"); boolean is=intent.getBooleanExtra("isme",true); if(is==false){ TextView tx=(TextView)findViewById(R.id.activity_my_question_tx); tx.setText("他的提问"); } new Thread(new Runnable() { @Override public void run() { try { BaseNetwork1 baseNetwork1 = new BaseNetwork1(); list = baseNetwork1.getQuestionList(sid); getDatalist = new ArrayList<HashMap<String, Object>>(); HashMap<String, Object> map; for (int i = 0; i < list.size(); i++) { map = new HashMap<String, Object>(); map.put("title", list.get(i).getQname()); map.put("time", list.get(i).getQtime()); getDatalist.add(map); Message message = new Message(); message.what = 1; handler.sendMessage(message); } if (list.size()==0) { Message message = new Message(); message.what = 3; handler.sendMessage(message); } }catch (NullPointerException e){ Message message = new Message(); message.what = 2; handler.sendMessage(message); } } }).start(); imageView=(ImageView)findViewById(R.id.activity_my_question_img1); imageView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); } }
UTF-8
Java
4,422
java
MyQuestionActivity.java
Java
[]
null
[]
package edu.zhdata.android.zhapp; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.view.View; import android.widget.AdapterView; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.SimpleAdapter; import android.widget.TextView; import android.widget.Toast; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import edu.zhdata.android.zhapp.entity.GetMyQuestion; import edu.zhdata.android.zhapp.tools.BaseNetwork1; public class MyQuestionActivity extends Activity { Handler handler=new Handler(){ public void handleMessage(Message message){ if(message.what==1){ SimpleAdapter sa=new SimpleAdapter(MyQuestionActivity.this,getDatalist,R.layout.activity_my_answer_listview,new String[]{"title","time"},new int[]{R.id.activity_my_answer_listview_tx1,R.id.activity_my_answer_listview_tx2}); lv.setAdapter(sa); if (sid.equals("-1")){ linearLayout.setBackgroundResource(R.drawable.empty); } }else if(message.what==2){ linearLayout.setBackgroundResource(R.drawable.empty); Toast.makeText(MyQuestionActivity.this,"请检查网络连接",Toast.LENGTH_SHORT).show(); }else if(message.what==3){ linearLayout.setBackgroundResource(R.drawable.empty); } } }; List<GetMyQuestion> list; private ImageView imageView; private ListView lv; private List<HashMap<String,Object>> datalist; private HashMap<String,Object> map; private String sid="163680"; private List<HashMap<String,Object>> getDatalist; private LinearLayout linearLayout; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_my_question); linearLayout=(LinearLayout)findViewById(R.id.activity_my_question_bg); lv=(ListView)findViewById(R.id.activity_my_question_list); lv.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Intent intent=new Intent(MyQuestionActivity.this,Question_page_Activity.class); intent.putExtra("Qid",list.get(position).getQid()); startActivity(intent); } }); Intent intent=getIntent(); sid=intent.getStringExtra("Sid"); boolean is=intent.getBooleanExtra("isme",true); if(is==false){ TextView tx=(TextView)findViewById(R.id.activity_my_question_tx); tx.setText("他的提问"); } new Thread(new Runnable() { @Override public void run() { try { BaseNetwork1 baseNetwork1 = new BaseNetwork1(); list = baseNetwork1.getQuestionList(sid); getDatalist = new ArrayList<HashMap<String, Object>>(); HashMap<String, Object> map; for (int i = 0; i < list.size(); i++) { map = new HashMap<String, Object>(); map.put("title", list.get(i).getQname()); map.put("time", list.get(i).getQtime()); getDatalist.add(map); Message message = new Message(); message.what = 1; handler.sendMessage(message); } if (list.size()==0) { Message message = new Message(); message.what = 3; handler.sendMessage(message); } }catch (NullPointerException e){ Message message = new Message(); message.what = 2; handler.sendMessage(message); } } }).start(); imageView=(ImageView)findViewById(R.id.activity_my_question_img1); imageView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); } }
4,422
0.591591
0.586364
114
37.596493
29.574385
237
false
false
0
0
0
0
0
0
0.807018
false
false
2
c636eaeb83db93a3e4bde0aeef2442b5c8455dcf
22,608,707,885,880
28b49cd8c5879d307914c0c0fbcb01d0664c014b
/src/main/java/com/usky/sms/field/screen/FieldScreenSchemeDao.java
a7b42cf24ba9d6a5f8de49abcce125351266f14b
[]
no_license
bellmit/jxhk
https://github.com/bellmit/jxhk
37afb3a55eb6bc436ffc0befcae0cb9e3ee70268
ebe996c821003e19b996e1e00e95d6db45d16353
refs/heads/master
2022-03-10T18:33:14.023000
2018-10-29T10:59:13
2018-10-29T10:59:13
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.usky.sms.field.screen; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.transaction.annotation.Isolation; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import com.usky.sms.core.BaseDao; public class FieldScreenSchemeDao extends BaseDao<FieldScreenSchemeDO> { @Autowired private ActivityTypeFieldScreenSchemeEntityDao activityTypeFieldScreenSchemeEntityDao; @Autowired private FieldScreenSchemeItemDao fieldScreenSchemeItemDao; public FieldScreenSchemeDao() { super(FieldScreenSchemeDO.class); } @Transactional(readOnly = false, propagation = Propagation.REQUIRED, isolation = Isolation.READ_COMMITTED) public Integer save(Map<String, Object> map) { Integer screenId = ((Number) map.remove("defaultFieldScreen")).intValue(); FieldScreenSchemeDO scheme = new FieldScreenSchemeDO(); copyValues(scheme, map); Integer id = (Integer) this.internalSave(scheme); FieldScreenSchemeItemDO item = new FieldScreenSchemeItemDO(); item.setScheme(scheme); FieldScreenDO screen = new FieldScreenDO(); screen.setId(screenId); item.setScreen(screen); fieldScreenSchemeItemDao.internalSave(item); return id; } @Override protected void beforeDelete(Collection<FieldScreenSchemeDO> schemes) { if (schemes == null || schemes.size() == 0) return; @SuppressWarnings("unchecked") List<FieldScreenSchemeItemDO> list = this.getHibernateTemplate().findByNamedParam("from FieldScreenSchemeItemDO where scheme in (:schemes)", "schemes", schemes); fieldScreenSchemeItemDao.delete(list); } @Override protected void afterGetList(List<Map<String, Object>> list, Map<String, Object> paramMap, Map<String, Object> searchMap, List<String> orders) { List<ActivityTypeFieldScreenSchemeEntityDO> entities = activityTypeFieldScreenSchemeEntityDao.getList(); Map<Integer, List<Map<String, Object>>> idSchemesMap = new HashMap<Integer, List<Map<String, Object>>>(); for (ActivityTypeFieldScreenSchemeEntityDO entity : entities) { Integer id = entity.getFieldScreenScheme().getId(); List<Map<String, Object>> schemeMaps = idSchemesMap.get(id); if (schemeMaps == null) { schemeMaps = new ArrayList<Map<String, Object>>(); idSchemesMap.put(id, schemeMaps); } Map<String, Object> schemeMap = null; ActivityTypeFieldScreenSchemeDO scheme = entity.getScheme(); for (Map<String, Object> map : schemeMaps) { if (scheme.getId().equals(map.get("id"))) { schemeMap = map; break; } } if (schemeMap == null) { schemeMap = new HashMap<String, Object>(); } else { continue; } schemeMap.put("id", scheme.getId()); schemeMap.put("name", scheme.getName()); schemeMaps.add(schemeMap); } for (Object obj : list) { @SuppressWarnings("unchecked") Map<String, Object> map = (Map<String, Object>) obj; map.put("schemes", idSchemesMap.get(map.get("id"))); } } @Transactional(readOnly = false, propagation = Propagation.REQUIRED, isolation = Isolation.READ_COMMITTED) public void copy(Integer id, String name, String description) throws Exception { FieldScreenSchemeDO src = this.internalGetById(id); FieldScreenSchemeDO dest = new FieldScreenSchemeDO(); this.copyValues(src, dest); dest.setName(name); dest.setDescription(description); this.internalSave(dest); fieldScreenSchemeItemDao.copyByFieldScreenScheme(src, dest); } public void setActivityTypeFieldScreenSchemeEntityDao(ActivityTypeFieldScreenSchemeEntityDao activityTypeFieldScreenSchemeEntityDao) { this.activityTypeFieldScreenSchemeEntityDao = activityTypeFieldScreenSchemeEntityDao; } public void setFieldScreenSchemeItemDao(FieldScreenSchemeItemDao fieldScreenSchemeItemDao) { this.fieldScreenSchemeItemDao = fieldScreenSchemeItemDao; } }
UTF-8
Java
4,000
java
FieldScreenSchemeDao.java
Java
[]
null
[]
package com.usky.sms.field.screen; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.transaction.annotation.Isolation; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import com.usky.sms.core.BaseDao; public class FieldScreenSchemeDao extends BaseDao<FieldScreenSchemeDO> { @Autowired private ActivityTypeFieldScreenSchemeEntityDao activityTypeFieldScreenSchemeEntityDao; @Autowired private FieldScreenSchemeItemDao fieldScreenSchemeItemDao; public FieldScreenSchemeDao() { super(FieldScreenSchemeDO.class); } @Transactional(readOnly = false, propagation = Propagation.REQUIRED, isolation = Isolation.READ_COMMITTED) public Integer save(Map<String, Object> map) { Integer screenId = ((Number) map.remove("defaultFieldScreen")).intValue(); FieldScreenSchemeDO scheme = new FieldScreenSchemeDO(); copyValues(scheme, map); Integer id = (Integer) this.internalSave(scheme); FieldScreenSchemeItemDO item = new FieldScreenSchemeItemDO(); item.setScheme(scheme); FieldScreenDO screen = new FieldScreenDO(); screen.setId(screenId); item.setScreen(screen); fieldScreenSchemeItemDao.internalSave(item); return id; } @Override protected void beforeDelete(Collection<FieldScreenSchemeDO> schemes) { if (schemes == null || schemes.size() == 0) return; @SuppressWarnings("unchecked") List<FieldScreenSchemeItemDO> list = this.getHibernateTemplate().findByNamedParam("from FieldScreenSchemeItemDO where scheme in (:schemes)", "schemes", schemes); fieldScreenSchemeItemDao.delete(list); } @Override protected void afterGetList(List<Map<String, Object>> list, Map<String, Object> paramMap, Map<String, Object> searchMap, List<String> orders) { List<ActivityTypeFieldScreenSchemeEntityDO> entities = activityTypeFieldScreenSchemeEntityDao.getList(); Map<Integer, List<Map<String, Object>>> idSchemesMap = new HashMap<Integer, List<Map<String, Object>>>(); for (ActivityTypeFieldScreenSchemeEntityDO entity : entities) { Integer id = entity.getFieldScreenScheme().getId(); List<Map<String, Object>> schemeMaps = idSchemesMap.get(id); if (schemeMaps == null) { schemeMaps = new ArrayList<Map<String, Object>>(); idSchemesMap.put(id, schemeMaps); } Map<String, Object> schemeMap = null; ActivityTypeFieldScreenSchemeDO scheme = entity.getScheme(); for (Map<String, Object> map : schemeMaps) { if (scheme.getId().equals(map.get("id"))) { schemeMap = map; break; } } if (schemeMap == null) { schemeMap = new HashMap<String, Object>(); } else { continue; } schemeMap.put("id", scheme.getId()); schemeMap.put("name", scheme.getName()); schemeMaps.add(schemeMap); } for (Object obj : list) { @SuppressWarnings("unchecked") Map<String, Object> map = (Map<String, Object>) obj; map.put("schemes", idSchemesMap.get(map.get("id"))); } } @Transactional(readOnly = false, propagation = Propagation.REQUIRED, isolation = Isolation.READ_COMMITTED) public void copy(Integer id, String name, String description) throws Exception { FieldScreenSchemeDO src = this.internalGetById(id); FieldScreenSchemeDO dest = new FieldScreenSchemeDO(); this.copyValues(src, dest); dest.setName(name); dest.setDescription(description); this.internalSave(dest); fieldScreenSchemeItemDao.copyByFieldScreenScheme(src, dest); } public void setActivityTypeFieldScreenSchemeEntityDao(ActivityTypeFieldScreenSchemeEntityDao activityTypeFieldScreenSchemeEntityDao) { this.activityTypeFieldScreenSchemeEntityDao = activityTypeFieldScreenSchemeEntityDao; } public void setFieldScreenSchemeItemDao(FieldScreenSchemeItemDao fieldScreenSchemeItemDao) { this.fieldScreenSchemeItemDao = fieldScreenSchemeItemDao; } }
4,000
0.76425
0.764
108
36.027779
34.273533
163
false
false
0
0
0
0
0
0
2.537037
false
false
2
853a588a79fe538e95bf80afe5cc1531047150b9
22,608,707,884,657
2f6ef0358a7f8c8b922ed0587dedb5f0cdb7ef72
/TDT4100 - OOP/Practical8/src/inheritance/ForeldreSpar.java
0b9f2bedde2da52bdcc43b2f70f9a8b59c8b5cb0
[]
no_license
Meneth/Schoolwork
https://github.com/Meneth/Schoolwork
bfb1cb4171f5b24eee2208cdf6b28d59cb30e919
539d2a3c61a75c86399c3bf7c198f601e843d7ab
refs/heads/master
2020-04-01T17:26:44.798000
2016-06-02T15:38:34
2016-06-02T15:38:34
43,456,356
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package inheritance; public class ForeldreSpar extends SavingsAccount { private int withdrawLimit; private int remainingWithdrawals; public ForeldreSpar(double interestRate, int withdrawLimit) { super(interestRate); this.withdrawLimit = withdrawLimit; this.remainingWithdrawals = withdrawLimit; } public int getRemainingWithdrawals() { return remainingWithdrawals; } @Override public void withdraw(double amount) { if (remainingWithdrawals <= 0) throw new IllegalStateException("All withdrawals for the year have been used up."); super.withdraw(amount); remainingWithdrawals--; } @Override public void endYearUpdate() { super.endYearUpdate(); remainingWithdrawals = withdrawLimit; } }
UTF-8
Java
725
java
ForeldreSpar.java
Java
[]
null
[]
package inheritance; public class ForeldreSpar extends SavingsAccount { private int withdrawLimit; private int remainingWithdrawals; public ForeldreSpar(double interestRate, int withdrawLimit) { super(interestRate); this.withdrawLimit = withdrawLimit; this.remainingWithdrawals = withdrawLimit; } public int getRemainingWithdrawals() { return remainingWithdrawals; } @Override public void withdraw(double amount) { if (remainingWithdrawals <= 0) throw new IllegalStateException("All withdrawals for the year have been used up."); super.withdraw(amount); remainingWithdrawals--; } @Override public void endYearUpdate() { super.endYearUpdate(); remainingWithdrawals = withdrawLimit; } }
725
0.769655
0.768276
30
23.166666
20.871166
86
false
false
0
0
0
0
0
0
1.6
false
false
2
89abc97fc51c01d36f62e7cc30cbdd7306cf01d7
9,345,848,900,160
df2271608db1a80c78a753283870ecef6468a82b
/Android-example/1.button/app/src/main/java/com/example/leo/android_1/MainActivity.java
ff90f435c8444326cc9aae9c86e3c8245ea0c862
[]
no_license
MrAntu/Android-Study
https://github.com/MrAntu/Android-Study
adf0a03bc64217072e25afc68c263c4822101676
ed699ec3835e71b7e532d0a08c57b5e250e3a84c
refs/heads/master
2020-05-03T18:36:11.525000
2019-04-01T01:57:23
2019-04-01T01:57:23
178,766,389
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.leo.android_1; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // 目录结构 // mainfests 应用清单,描述app所包含的东西 // java: 程序代码 // res: 应用所需的资源文件 // drawble: 颜色相关的设置 // layout : 布局 // Gradle :编译打包工具 // 修改textview // findViewById: 返回值是view类, // TextView view = (TextView)findViewById(R.id.id_hello); // view.setText("helloafa"); // 方式1 获取button2,纯代码添加点击事件 Button btn = (Button)findViewById(R.id.id_btn_2); MyButtonListener listener = new MyButtonListener(); // btn.setOnClickListener(listener); // 方式2 匿名类方法,主流都是这样写 btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { TextView v2 = (TextView)findViewById(R.id.id_text_1); v2.setText("你好阿发"); } }); } // 按钮点击事件 xml中实现 public void onBtnCliked(View view) { System.out.println("qweqweqweqwe"); TextView v = (TextView)findViewById(R.id.id_text_1); v.setText("helloafa"); } // 纯代码添加点击事件,必须实现OnClickListener接口 private class MyButtonListener implements View.OnClickListener { @Override public void onClick(View v) { TextView v1 = (TextView)findViewById(R.id.id_text_1); v1.setText("你好阿发"); } } }
UTF-8
Java
1,964
java
MainActivity.java
Java
[]
null
[]
package com.example.leo.android_1; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // 目录结构 // mainfests 应用清单,描述app所包含的东西 // java: 程序代码 // res: 应用所需的资源文件 // drawble: 颜色相关的设置 // layout : 布局 // Gradle :编译打包工具 // 修改textview // findViewById: 返回值是view类, // TextView view = (TextView)findViewById(R.id.id_hello); // view.setText("helloafa"); // 方式1 获取button2,纯代码添加点击事件 Button btn = (Button)findViewById(R.id.id_btn_2); MyButtonListener listener = new MyButtonListener(); // btn.setOnClickListener(listener); // 方式2 匿名类方法,主流都是这样写 btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { TextView v2 = (TextView)findViewById(R.id.id_text_1); v2.setText("你好阿发"); } }); } // 按钮点击事件 xml中实现 public void onBtnCliked(View view) { System.out.println("qweqweqweqwe"); TextView v = (TextView)findViewById(R.id.id_text_1); v.setText("helloafa"); } // 纯代码添加点击事件,必须实现OnClickListener接口 private class MyButtonListener implements View.OnClickListener { @Override public void onClick(View v) { TextView v1 = (TextView)findViewById(R.id.id_text_1); v1.setText("你好阿发"); } } }
1,964
0.614764
0.607266
59
28.38983
20.415195
69
false
false
0
0
0
0
0
0
0.372881
false
false
2
015b2e0ae918267b0be7c719726cd92631f80659
30,958,124,312,403
e3c093367c35638cd20024069e16af3a0d7dee6e
/src/main/java/com/cmu/ratatouille/models/MealHistory.java
b0ac069b5db2a9d9761629177c4bd52c2939897a
[]
no_license
evanshwu/Ratatouille
https://github.com/evanshwu/Ratatouille
fcc583dd168fbe6d668450f693115d0c5d6107bc
95b0aef0d660cfd9c11729cf9e77afdd5949ef33
refs/heads/master
2020-08-19T11:23:59.448000
2019-12-09T21:11:45
2019-12-09T21:11:45
215,915,579
0
0
null
false
2019-10-28T03:50:28
2019-10-18T01:21:20
2019-10-28T02:31:39
2019-10-28T03:50:27
20,483
0
0
0
Java
false
false
package com.cmu.ratatouille.models; public class MealHistory { public String date; public MealPlan mealPlan; public String getDate() { return date; } public void setDate(String date) { this.date = date; } public MealPlan getMealPlan() { return mealPlan; } public void setMealPlan(MealPlan mealPlan) { this.mealPlan = mealPlan; } }
UTF-8
Java
408
java
MealHistory.java
Java
[]
null
[]
package com.cmu.ratatouille.models; public class MealHistory { public String date; public MealPlan mealPlan; public String getDate() { return date; } public void setDate(String date) { this.date = date; } public MealPlan getMealPlan() { return mealPlan; } public void setMealPlan(MealPlan mealPlan) { this.mealPlan = mealPlan; } }
408
0.622549
0.622549
22
17.545454
15.230732
48
false
false
0
0
0
0
0
0
0.318182
false
false
2
84241e1533a4802b168b429e78e66c943f3e032c
2,740,189,146,902
e9fc9e4c1fe5435a100ae443c840163cf11e112b
/src/main/java/es/source/code/activity/FoodOrderView.java
ba291c696213149ee0b162b21c4eb628beb23bc3
[ "MIT" ]
permissive
hekkl/COS
https://github.com/hekkl/COS
5062c5c5266daf81345f04881f067622a89e940d
cb95ae9f78fec9a4175aaebb3dda9283603040ab
refs/heads/master
2022-04-09T05:14:56.032000
2016-07-11T06:20:33
2016-07-11T06:20:33
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package es.source.code.activity; import android.content.Intent; import android.graphics.Color; import android.support.v4.app.ListFragment; import android.support.v4.view.PagerTabStrip; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import java.util.ArrayList; import java.util.List; import es.source.code.model.User; import es.source.code.view.FoodDisorderFragment; import es.source.code.view.FoodListFragmentPagerAdapter; import es.source.code.view.FoodOrderFragment; public class FoodOrderView extends AppCompatActivity { private ViewPager viewPager; private PagerTabStrip pagerTabStrip; private List<ListFragment> fragmentList; private List<String> titleList; private User user; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.food_order_view); viewPager = (ViewPager) findViewById(R.id.food_order_view_pager); Intent intent = this.getIntent(); user = (User) intent.getSerializableExtra("User"); int page = intent.getIntExtra("Page", 0); viewPager.setCurrentItem(page); pagerTabStrip = (PagerTabStrip) findViewById(R.id.food_order_view_pager_tab); pagerTabStrip.setTabIndicatorColor(Color.WHITE); pagerTabStrip.setTextColor(Color.WHITE); pagerTabStrip.setTextSize(0, 60); pagerTabStrip.setClickable(false); pagerTabStrip.setTextSpacing(80); pagerTabStrip.setBackgroundColor(Color.parseColor("#668B8B")); pagerTabStrip.setDrawFullUnderline(true); ListFragment orderedFragment = new FoodOrderFragment(); ListFragment disorderedFragment = new FoodDisorderFragment(); fragmentList = new ArrayList<>(); fragmentList.add(orderedFragment); fragmentList.add(disorderedFragment); titleList = new ArrayList<>(); titleList.add("已下菜单"); titleList.add("未下菜单"); viewPager.setAdapter(new FoodListFragmentPagerAdapter(getSupportFragmentManager(), fragmentList, titleList)); } }
UTF-8
Java
2,160
java
FoodOrderView.java
Java
[]
null
[]
package es.source.code.activity; import android.content.Intent; import android.graphics.Color; import android.support.v4.app.ListFragment; import android.support.v4.view.PagerTabStrip; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import java.util.ArrayList; import java.util.List; import es.source.code.model.User; import es.source.code.view.FoodDisorderFragment; import es.source.code.view.FoodListFragmentPagerAdapter; import es.source.code.view.FoodOrderFragment; public class FoodOrderView extends AppCompatActivity { private ViewPager viewPager; private PagerTabStrip pagerTabStrip; private List<ListFragment> fragmentList; private List<String> titleList; private User user; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.food_order_view); viewPager = (ViewPager) findViewById(R.id.food_order_view_pager); Intent intent = this.getIntent(); user = (User) intent.getSerializableExtra("User"); int page = intent.getIntExtra("Page", 0); viewPager.setCurrentItem(page); pagerTabStrip = (PagerTabStrip) findViewById(R.id.food_order_view_pager_tab); pagerTabStrip.setTabIndicatorColor(Color.WHITE); pagerTabStrip.setTextColor(Color.WHITE); pagerTabStrip.setTextSize(0, 60); pagerTabStrip.setClickable(false); pagerTabStrip.setTextSpacing(80); pagerTabStrip.setBackgroundColor(Color.parseColor("#668B8B")); pagerTabStrip.setDrawFullUnderline(true); ListFragment orderedFragment = new FoodOrderFragment(); ListFragment disorderedFragment = new FoodDisorderFragment(); fragmentList = new ArrayList<>(); fragmentList.add(orderedFragment); fragmentList.add(disorderedFragment); titleList = new ArrayList<>(); titleList.add("已下菜单"); titleList.add("未下菜单"); viewPager.setAdapter(new FoodListFragmentPagerAdapter(getSupportFragmentManager(), fragmentList, titleList)); } }
2,160
0.733675
0.727145
58
35.965519
23.974819
117
false
false
0
0
0
0
0
0
0.810345
false
false
2
eea6a5aabd717f00cc35b93a9ccfdcf23d420c31
35,605,278,894,030
b84df4d4e53492db87b3a699f978fa87b33e3a3c
/proj4-bakingapp/app/src/androidTest/java/com/arushi/bakingapp/BaseTest.java
19bac0155d7fb765bbaf11bc9478478b3d433246
[ "MIT" ]
permissive
AMRIT3911/android-developer-nanodegree
https://github.com/AMRIT3911/android-developer-nanodegree
8ae6493c22ebb330020cd12d8adabe83d7a4c3ea
d36be99b0d7071a5e240f0f713fdf6c0b6674768
refs/heads/master
2021-09-25T00:32:35.503000
2018-10-16T07:51:54
2018-10-16T07:51:54
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * * * * * This project was submitted by Arushi Pant as part of the Android Developer Nanodegree at Udacity. * * * * As part of Udacity Honor code, your submissions must be your own work, hence * * submitting this project as yours will cause you to break the Udacity Honor Code * * and the suspension of your account. * * * * I, the author of the project, allow you to check the code as a reference, but if * * you submit it, it's your own responsibility if you get expelled. * * * * Besides the above notice, the MIT license applies and this license notice * * must be included in all works derived from this project * * * * Copyright (c) 2018 Arushi Pant * * * */ package com.arushi.bakingapp; import android.app.Activity; import com.arushi.bakingapp.utils.PhoneTest; import com.arushi.bakingapp.utils.TabletTest; import org.junit.Before; import org.junit.Rule; import org.junit.rules.TestName; import java.lang.reflect.Method; import static org.junit.Assume.assumeTrue; public class BaseTest { public Activity mActivity; @Rule public TestName testName = new TestName(); @Before public void setUp() throws Exception { /* IMP: requires setting mActivity in any class that extends this */ assertDeviceOrSkip(); } private void assertDeviceOrSkip() { try { Method m = getClass().getMethod(testName.getMethodName()); if (m.isAnnotationPresent(TabletTest.class)) { assumeTrue(isTablet()); } else if (m.isAnnotationPresent(PhoneTest.class)) { assumeTrue(isPhone()); } } catch (NoSuchMethodException e) { // Do nothing } } private boolean isPhone() { return !isTablet(); } private boolean isTablet() { return mActivity.getResources().getBoolean(R.bool.isTablet); } }
UTF-8
Java
1,913
java
BaseTest.java
Java
[ { "context": "/*\n *\n * *\n * * This project was submitted by Arushi Pant as part of the Android Developer Nanodegree at Ud", "end": 60, "score": 0.9998764991760254, "start": 49, "tag": "NAME", "value": "Arushi Pant" }, { "context": " from this project\n * *\n * * Copyright (c...
null
[]
/* * * * * * This project was submitted by <NAME> as part of the Android Developer Nanodegree at Udacity. * * * * As part of Udacity Honor code, your submissions must be your own work, hence * * submitting this project as yours will cause you to break the Udacity Honor Code * * and the suspension of your account. * * * * I, the author of the project, allow you to check the code as a reference, but if * * you submit it, it's your own responsibility if you get expelled. * * * * Besides the above notice, the MIT license applies and this license notice * * must be included in all works derived from this project * * * * Copyright (c) 2018 <NAME> * * * */ package com.arushi.bakingapp; import android.app.Activity; import com.arushi.bakingapp.utils.PhoneTest; import com.arushi.bakingapp.utils.TabletTest; import org.junit.Before; import org.junit.Rule; import org.junit.rules.TestName; import java.lang.reflect.Method; import static org.junit.Assume.assumeTrue; public class BaseTest { public Activity mActivity; @Rule public TestName testName = new TestName(); @Before public void setUp() throws Exception { /* IMP: requires setting mActivity in any class that extends this */ assertDeviceOrSkip(); } private void assertDeviceOrSkip() { try { Method m = getClass().getMethod(testName.getMethodName()); if (m.isAnnotationPresent(TabletTest.class)) { assumeTrue(isTablet()); } else if (m.isAnnotationPresent(PhoneTest.class)) { assumeTrue(isPhone()); } } catch (NoSuchMethodException e) { // Do nothing } } private boolean isPhone() { return !isTablet(); } private boolean isTablet() { return mActivity.getResources().getBoolean(R.bool.isTablet); } }
1,903
0.653947
0.651856
68
27.132353
27.37641
104
false
false
0
0
0
0
0
0
0.352941
false
false
2
7096b0770575f22193884d7865fd0d840be68aaf
23,038,204,602,288
c42225d0cd5608c3e81ce5a2ee34c6022d766c05
/rbtsdk2.0/src/main/java/com/onmobile/rbt/baseline/http/api_action/errormodule/NoConnectionException.java
dba1e9ff49ae7fe7f0da3c6e3c33390d8199f95b
[]
no_license
IMPK/RBTSDK2.0
https://github.com/IMPK/RBTSDK2.0
ac7a70983fdcee798777ae79fb1647ce4ad46f16
1ed2b9fc066d5d75e4dc503c2621663a4e3ae2dd
refs/heads/master
2020-09-29T02:37:20.089000
2019-12-25T18:50:48
2019-12-25T18:50:48
226,928,983
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.onmobile.rbt.baseline.http.api_action.errormodule; import java.io.IOException; public class NoConnectionException extends IOException { @Override public String getMessage() { return "No Connection exception"; } }
UTF-8
Java
248
java
NoConnectionException.java
Java
[]
null
[]
package com.onmobile.rbt.baseline.http.api_action.errormodule; import java.io.IOException; public class NoConnectionException extends IOException { @Override public String getMessage() { return "No Connection exception"; } }
248
0.737903
0.737903
11
21.545454
22.366222
62
false
false
0
0
0
0
0
0
0.272727
false
false
2
d1ca524fb35ef6007df72ca4a0299f89a00a21cb
32,959,579,097,452
f3f0457b064f26106cef767f5bd8953f916d2859
/src/test/JavaGenerateTest.java
ccaa163cd87ed83407b3ef960f6b750fd472cc2e
[]
no_license
tyvonnou/minispec
https://github.com/tyvonnou/minispec
42f36d6d8ae05a0594f9a101b92a47467eadf205
7254f9e593565059c4f749fb816f71fcad712947
refs/heads/main
2023-03-18T21:16:57.610000
2021-03-12T17:49:35
2021-03-12T17:49:35
344,416,602
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package test; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; import javax.xml.parsers.ParserConfigurationException; import org.junit.jupiter.api.Test; import org.xml.sax.SAXException; import handler.JavaDOMReader; import model.Model; class JavaGenerateTest { /* * Find the differences between two string */ public static List<String> findNotMatching(String sourceStr, String anotherStr){ StringTokenizer at = new StringTokenizer(sourceStr, " "); StringTokenizer bt = null; int i = 0, token_count = 0; String token = null; boolean flag = false; List<String> missingWords = new ArrayList<String>(); while (at.hasMoreTokens()) { token = at.nextToken(); bt = new StringTokenizer(anotherStr, " "); token_count = bt.countTokens(); while (i < token_count) { String s = bt.nextToken(); if (token.equals(s)) { flag = true; break; } else { flag = false; } i++; } i = 0; if (flag == false) missingWords.add(token); } return missingWords; } /* * Transform XML file to objects and export the objects in XML file */ @Test void testXMLtoXML() throws SAXException, IOException, ParserConfigurationException { // READ JavaDOMReader dom = new JavaDOMReader(); dom.read("dtd/Satellite.xml"); Model model = dom.getModel(); assertTrue(model.getName().equals("projet")); assertTrue(model.getEntity(0).getName().equals("Satellite")); assertTrue(model.getEntity(0).getAttribute(0).getName().equals("name")); assertTrue(model.getEntity(0).getAttribute(0).getType().equals("String")); assertTrue(model.getEntity(0).getAttribute(1).getName().equals("id")); assertTrue(model.getEntity(0).getAttribute(1).getType().equals("Integer")); // WRITE String filename = "dtd/OUTPUTDOMTEST.xml"; dom.writeXML(filename, model); dom.writeJAVA(model); try (FileInputStream fis = new FileInputStream(filename)) { byte[] buf = new byte[10240]; int size = fis.read(buf); String test = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\r\n" + "<!DOCTYPE model PUBLIC \"model\" \"model.dtd\">\r\n" + "<model name=\"projet\">\r\n" + " <entity name=\"Satellite\">\r\n" + " <attribute name=\"name\" type=\"String\"/>\r\n" + " <attribute name=\"id\" type=\"Integer\"/>\r\n" + " </entity>\r\n" + "</model>\r\n"; String contents = new String(buf,0,size); // If you have some trouble with the test, // you can compare the test string and the output string thanks to the findNotMatching function //List<String> diff = findNotMatching(contents, test); //System.out.println(diff.get(0)); assertTrue(contents.equals(test)); } catch (FileNotFoundException e) { fail(""); } catch (IOException e) { fail(""); } } /* * Transform XML file to object and export objects in java sources files */ @Test void testXMLtoJava() throws SAXException, IOException, ParserConfigurationException { // READ JavaDOMReader dom = new JavaDOMReader(); dom.read("dtd/Satellite.xml"); Model model = dom.getModel(); assertTrue(model.getName().equals("projet")); assertTrue(model.getEntity(0).getName().equals("Satellite")); assertTrue(model.getEntity(0).getAttribute(0).getName().equals("name")); assertTrue(model.getEntity(0).getAttribute(0).getType().equals("String")); assertTrue(model.getEntity(0).getAttribute(1).getName().equals("id")); assertTrue(model.getEntity(0).getAttribute(1).getType().equals("Integer")); // WRITE String filename = "src/generated/projet/Satellite.java"; dom.writeJAVA(model); try (FileInputStream fis = new FileInputStream(filename)) { byte[] buf = new byte[10240]; int size = fis.read(buf); String test = "package generated.projet;\r\n\r\n" + "public class Satellite {\r\n\r\n" // Attributes + "\tString name;\r\n" + "\tInteger id;\r\n\r\n" // Constructor + "\tpublic Satellite() {}\r\n\r\n" // Getters and Setters + "\tpublic String getName() {\r\n\t\treturn this.name;\r\n\t}\r\n\r\n" + "\tpublic void setName(String name) {\r\n\t\tthis.name = name;\r\n\t}\r\n\r\n" + "\tpublic Integer getId() {\r\n\t\treturn this.id;\r\n\t}\r\n\r\n" + "\tpublic void setId(Integer id) {\r\n\t\tthis.id = id;\r\n\t}\r\n" + "}"; String contents = new String(buf,0,size); // If you have some trouble with the test, // you can compare the test string and the output string thanks to the findNotMatching function // List<String> diff = findNotMatching(contents, test); // System.out.println(diff.get(0)); assertTrue(contents.equals(test)); } catch (FileNotFoundException e) { fail(""); } catch (IOException e) { fail(""); } } /* * Transform XML file to object and export objects in java sources files using visitor model */ @Test void testXMLtoJavaVisitorSatelliteFile() throws SAXException, IOException, ParserConfigurationException { // READ JavaDOMReader dom = new JavaDOMReader(); dom.read("dtd/SatelliteVisitor.xml"); Model model = dom.getModel(); assertTrue(model.getName().equals("projet")); assertTrue(model.getEntity(0).getName().equals("Satellite")); assertTrue(model.getEntity(0).getAttribute(0).getName().equals("name")); assertTrue(model.getEntity(0).getAttribute(0).getType().equals("String")); assertTrue(model.getEntity(0).getAttribute(1).getName().equals("id")); assertTrue(model.getEntity(0).getAttribute(1).getType().equals("Integer")); // WRITE String filename = "src/generatedVisitor/projet/Satellite.java"; dom.writeVisitorJAVA(model); try (FileInputStream fis = new FileInputStream(filename)) { byte[] buf = new byte[10240]; int size = fis.read(buf); String test = "package generatedVisitor.projet;\r\n" + "\r\n" + "import java.util.Set;\r\n" + "import java.util.List;\r\n" + "\r\n" + "public class Satellite {\r\n" + "\r\n" + " String name;\r\n" + " Integer id;\r\n" + " Set<PanneauSolaire> PanneauxSolaires;\r\n" + " List<Flotte> Balises;\r\n" + "\r\n" + " public Satellite() {}\r\n" + "\r\n" + " public String getName() {\r\n" + " return this.name;\r\n" + " }\r\n" + "\r\n" + " public void setName(String name) {\r\n" + " this.name = name;\r\n" + " }\r\n" + "\r\n" + " public Integer getId() {\r\n" + " return this.id;\r\n" + " }\r\n" + "\r\n" + " public void setId(Integer id) {\r\n" + " this.id = id;\r\n" + " }\r\n" + "\r\n" + " public Set<PanneauSolaire> getPanneauxSolaires() {\r\n" + " return this.PanneauxSolaires;\r\n" + " }\r\n" + "\r\n" + " public void addPanneauxSolaires(PanneauSolaire PanneauxSolaires) {\r\n" + " this.PanneauxSolaires.add(PanneauxSolaires);\r\n" + " }\r\n" + "\r\n" + " public List<Flotte> getBalises() {\r\n" + " return this.Balises;\r\n" + " }\r\n" + "\r\n" + " public void addBalises(Flotte Balises) {\r\n" + " this.Balises.add(Balises);\r\n" + " }\r\n" + "}"; String contents = new String(buf,0,size); // If you have some trouble with the test, // you can compare the test string and the output string thanks to the findNotMatching function // List<String> diff = findNotMatching(contents, test); // System.out.println(diff.get(0)); assertTrue(contents.equals(test)); } catch (FileNotFoundException e) { fail(""); } catch (IOException e) { fail(""); } } /* * Transform XML file to object and export objects in java sources files using visitor model */ @Test void testXMLtoJavaVisitorFlotteFile() throws SAXException, IOException, ParserConfigurationException { // READ JavaDOMReader dom = new JavaDOMReader(); dom.read("dtd/SatelliteVisitor.xml"); Model model = dom.getModel(); assertTrue(model.getName().equals("projet")); assertTrue(model.getEntity(0).getName().equals("Satellite")); assertTrue(model.getEntity(0).getAttribute(0).getName().equals("name")); assertTrue(model.getEntity(0).getAttribute(0).getType().equals("String")); assertTrue(model.getEntity(0).getAttribute(1).getName().equals("id")); assertTrue(model.getEntity(0).getAttribute(1).getType().equals("Integer")); // WRITE String filename = "src/generatedVisitor/projet/Flotte.java"; dom.writeVisitorJAVA(model); try (FileInputStream fis = new FileInputStream(filename)) { byte[] buf = new byte[10240]; int size = fis.read(buf); String test = "package generatedVisitor.projet;\r\n" + "\r\n" + "public class Flotte {\r\n" + "\r\n" + " public Flotte() {}\r\n" + "}"; String contents = new String(buf,0,size); // If you have some trouble with the test, // you can compare the test string and the output string thanks to the findNotMatching function // List<String> diff = findNotMatching(contents, test); // System.out.println(diff.get(0)); assertTrue(contents.equals(test)); } catch (FileNotFoundException e) { fail(""); } catch (IOException e) { fail(""); } } /* * Transform XML file to object and export objects in java sources files using visitor model */ @Test void testXMLtoJavaVisitorPanneauSolaireFile() throws SAXException, IOException, ParserConfigurationException { // READ JavaDOMReader dom = new JavaDOMReader(); dom.read("dtd/SatelliteVisitor.xml"); Model model = dom.getModel(); assertTrue(model.getName().equals("projet")); assertTrue(model.getEntity(0).getName().equals("Satellite")); assertTrue(model.getEntity(0).getAttribute(0).getName().equals("name")); assertTrue(model.getEntity(0).getAttribute(0).getType().equals("String")); assertTrue(model.getEntity(0).getAttribute(1).getName().equals("id")); assertTrue(model.getEntity(0).getAttribute(1).getType().equals("Integer")); // WRITE String filename = "src/generatedVisitor/projet/PanneauSolaire.java"; dom.writeVisitorJAVA(model); try (FileInputStream fis = new FileInputStream(filename)) { byte[] buf = new byte[10240]; int size = fis.read(buf); String test = "package generatedVisitor.projet;\r\n" + "\r\n" + "public class PanneauSolaire {\r\n" + "\r\n" + " public PanneauSolaire() {}\r\n" + "}"; String contents = new String(buf,0,size); // If you have some trouble with the test, // you can compare the test string and the output string thanks to the findNotMatching function // List<String> diff = findNotMatching(contents, test); // System.out.println(diff.get(0)); assertTrue(contents.equals(test)); } catch (FileNotFoundException e) { fail(""); } catch (IOException e) { fail(""); } } }
UTF-8
Java
11,416
java
JavaGenerateTest.java
Java
[]
null
[]
package test; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; import javax.xml.parsers.ParserConfigurationException; import org.junit.jupiter.api.Test; import org.xml.sax.SAXException; import handler.JavaDOMReader; import model.Model; class JavaGenerateTest { /* * Find the differences between two string */ public static List<String> findNotMatching(String sourceStr, String anotherStr){ StringTokenizer at = new StringTokenizer(sourceStr, " "); StringTokenizer bt = null; int i = 0, token_count = 0; String token = null; boolean flag = false; List<String> missingWords = new ArrayList<String>(); while (at.hasMoreTokens()) { token = at.nextToken(); bt = new StringTokenizer(anotherStr, " "); token_count = bt.countTokens(); while (i < token_count) { String s = bt.nextToken(); if (token.equals(s)) { flag = true; break; } else { flag = false; } i++; } i = 0; if (flag == false) missingWords.add(token); } return missingWords; } /* * Transform XML file to objects and export the objects in XML file */ @Test void testXMLtoXML() throws SAXException, IOException, ParserConfigurationException { // READ JavaDOMReader dom = new JavaDOMReader(); dom.read("dtd/Satellite.xml"); Model model = dom.getModel(); assertTrue(model.getName().equals("projet")); assertTrue(model.getEntity(0).getName().equals("Satellite")); assertTrue(model.getEntity(0).getAttribute(0).getName().equals("name")); assertTrue(model.getEntity(0).getAttribute(0).getType().equals("String")); assertTrue(model.getEntity(0).getAttribute(1).getName().equals("id")); assertTrue(model.getEntity(0).getAttribute(1).getType().equals("Integer")); // WRITE String filename = "dtd/OUTPUTDOMTEST.xml"; dom.writeXML(filename, model); dom.writeJAVA(model); try (FileInputStream fis = new FileInputStream(filename)) { byte[] buf = new byte[10240]; int size = fis.read(buf); String test = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\r\n" + "<!DOCTYPE model PUBLIC \"model\" \"model.dtd\">\r\n" + "<model name=\"projet\">\r\n" + " <entity name=\"Satellite\">\r\n" + " <attribute name=\"name\" type=\"String\"/>\r\n" + " <attribute name=\"id\" type=\"Integer\"/>\r\n" + " </entity>\r\n" + "</model>\r\n"; String contents = new String(buf,0,size); // If you have some trouble with the test, // you can compare the test string and the output string thanks to the findNotMatching function //List<String> diff = findNotMatching(contents, test); //System.out.println(diff.get(0)); assertTrue(contents.equals(test)); } catch (FileNotFoundException e) { fail(""); } catch (IOException e) { fail(""); } } /* * Transform XML file to object and export objects in java sources files */ @Test void testXMLtoJava() throws SAXException, IOException, ParserConfigurationException { // READ JavaDOMReader dom = new JavaDOMReader(); dom.read("dtd/Satellite.xml"); Model model = dom.getModel(); assertTrue(model.getName().equals("projet")); assertTrue(model.getEntity(0).getName().equals("Satellite")); assertTrue(model.getEntity(0).getAttribute(0).getName().equals("name")); assertTrue(model.getEntity(0).getAttribute(0).getType().equals("String")); assertTrue(model.getEntity(0).getAttribute(1).getName().equals("id")); assertTrue(model.getEntity(0).getAttribute(1).getType().equals("Integer")); // WRITE String filename = "src/generated/projet/Satellite.java"; dom.writeJAVA(model); try (FileInputStream fis = new FileInputStream(filename)) { byte[] buf = new byte[10240]; int size = fis.read(buf); String test = "package generated.projet;\r\n\r\n" + "public class Satellite {\r\n\r\n" // Attributes + "\tString name;\r\n" + "\tInteger id;\r\n\r\n" // Constructor + "\tpublic Satellite() {}\r\n\r\n" // Getters and Setters + "\tpublic String getName() {\r\n\t\treturn this.name;\r\n\t}\r\n\r\n" + "\tpublic void setName(String name) {\r\n\t\tthis.name = name;\r\n\t}\r\n\r\n" + "\tpublic Integer getId() {\r\n\t\treturn this.id;\r\n\t}\r\n\r\n" + "\tpublic void setId(Integer id) {\r\n\t\tthis.id = id;\r\n\t}\r\n" + "}"; String contents = new String(buf,0,size); // If you have some trouble with the test, // you can compare the test string and the output string thanks to the findNotMatching function // List<String> diff = findNotMatching(contents, test); // System.out.println(diff.get(0)); assertTrue(contents.equals(test)); } catch (FileNotFoundException e) { fail(""); } catch (IOException e) { fail(""); } } /* * Transform XML file to object and export objects in java sources files using visitor model */ @Test void testXMLtoJavaVisitorSatelliteFile() throws SAXException, IOException, ParserConfigurationException { // READ JavaDOMReader dom = new JavaDOMReader(); dom.read("dtd/SatelliteVisitor.xml"); Model model = dom.getModel(); assertTrue(model.getName().equals("projet")); assertTrue(model.getEntity(0).getName().equals("Satellite")); assertTrue(model.getEntity(0).getAttribute(0).getName().equals("name")); assertTrue(model.getEntity(0).getAttribute(0).getType().equals("String")); assertTrue(model.getEntity(0).getAttribute(1).getName().equals("id")); assertTrue(model.getEntity(0).getAttribute(1).getType().equals("Integer")); // WRITE String filename = "src/generatedVisitor/projet/Satellite.java"; dom.writeVisitorJAVA(model); try (FileInputStream fis = new FileInputStream(filename)) { byte[] buf = new byte[10240]; int size = fis.read(buf); String test = "package generatedVisitor.projet;\r\n" + "\r\n" + "import java.util.Set;\r\n" + "import java.util.List;\r\n" + "\r\n" + "public class Satellite {\r\n" + "\r\n" + " String name;\r\n" + " Integer id;\r\n" + " Set<PanneauSolaire> PanneauxSolaires;\r\n" + " List<Flotte> Balises;\r\n" + "\r\n" + " public Satellite() {}\r\n" + "\r\n" + " public String getName() {\r\n" + " return this.name;\r\n" + " }\r\n" + "\r\n" + " public void setName(String name) {\r\n" + " this.name = name;\r\n" + " }\r\n" + "\r\n" + " public Integer getId() {\r\n" + " return this.id;\r\n" + " }\r\n" + "\r\n" + " public void setId(Integer id) {\r\n" + " this.id = id;\r\n" + " }\r\n" + "\r\n" + " public Set<PanneauSolaire> getPanneauxSolaires() {\r\n" + " return this.PanneauxSolaires;\r\n" + " }\r\n" + "\r\n" + " public void addPanneauxSolaires(PanneauSolaire PanneauxSolaires) {\r\n" + " this.PanneauxSolaires.add(PanneauxSolaires);\r\n" + " }\r\n" + "\r\n" + " public List<Flotte> getBalises() {\r\n" + " return this.Balises;\r\n" + " }\r\n" + "\r\n" + " public void addBalises(Flotte Balises) {\r\n" + " this.Balises.add(Balises);\r\n" + " }\r\n" + "}"; String contents = new String(buf,0,size); // If you have some trouble with the test, // you can compare the test string and the output string thanks to the findNotMatching function // List<String> diff = findNotMatching(contents, test); // System.out.println(diff.get(0)); assertTrue(contents.equals(test)); } catch (FileNotFoundException e) { fail(""); } catch (IOException e) { fail(""); } } /* * Transform XML file to object and export objects in java sources files using visitor model */ @Test void testXMLtoJavaVisitorFlotteFile() throws SAXException, IOException, ParserConfigurationException { // READ JavaDOMReader dom = new JavaDOMReader(); dom.read("dtd/SatelliteVisitor.xml"); Model model = dom.getModel(); assertTrue(model.getName().equals("projet")); assertTrue(model.getEntity(0).getName().equals("Satellite")); assertTrue(model.getEntity(0).getAttribute(0).getName().equals("name")); assertTrue(model.getEntity(0).getAttribute(0).getType().equals("String")); assertTrue(model.getEntity(0).getAttribute(1).getName().equals("id")); assertTrue(model.getEntity(0).getAttribute(1).getType().equals("Integer")); // WRITE String filename = "src/generatedVisitor/projet/Flotte.java"; dom.writeVisitorJAVA(model); try (FileInputStream fis = new FileInputStream(filename)) { byte[] buf = new byte[10240]; int size = fis.read(buf); String test = "package generatedVisitor.projet;\r\n" + "\r\n" + "public class Flotte {\r\n" + "\r\n" + " public Flotte() {}\r\n" + "}"; String contents = new String(buf,0,size); // If you have some trouble with the test, // you can compare the test string and the output string thanks to the findNotMatching function // List<String> diff = findNotMatching(contents, test); // System.out.println(diff.get(0)); assertTrue(contents.equals(test)); } catch (FileNotFoundException e) { fail(""); } catch (IOException e) { fail(""); } } /* * Transform XML file to object and export objects in java sources files using visitor model */ @Test void testXMLtoJavaVisitorPanneauSolaireFile() throws SAXException, IOException, ParserConfigurationException { // READ JavaDOMReader dom = new JavaDOMReader(); dom.read("dtd/SatelliteVisitor.xml"); Model model = dom.getModel(); assertTrue(model.getName().equals("projet")); assertTrue(model.getEntity(0).getName().equals("Satellite")); assertTrue(model.getEntity(0).getAttribute(0).getName().equals("name")); assertTrue(model.getEntity(0).getAttribute(0).getType().equals("String")); assertTrue(model.getEntity(0).getAttribute(1).getName().equals("id")); assertTrue(model.getEntity(0).getAttribute(1).getType().equals("Integer")); // WRITE String filename = "src/generatedVisitor/projet/PanneauSolaire.java"; dom.writeVisitorJAVA(model); try (FileInputStream fis = new FileInputStream(filename)) { byte[] buf = new byte[10240]; int size = fis.read(buf); String test = "package generatedVisitor.projet;\r\n" + "\r\n" + "public class PanneauSolaire {\r\n" + "\r\n" + " public PanneauSolaire() {}\r\n" + "}"; String contents = new String(buf,0,size); // If you have some trouble with the test, // you can compare the test string and the output string thanks to the findNotMatching function // List<String> diff = findNotMatching(contents, test); // System.out.println(diff.get(0)); assertTrue(contents.equals(test)); } catch (FileNotFoundException e) { fail(""); } catch (IOException e) { fail(""); } } }
11,416
0.630781
0.623248
314
35.356689
26.710411
111
false
false
0
0
0
0
0
0
2.914013
false
false
2
0aa96ac8d4a1d4f89bb34f1aaa47e3a5e57e6209
16,810,502,019,989
882e77219bce59ae57cbad7e9606507b34eebfcf
/mi2s_10_miui12/src/main/java/com/android/server/net/watchlist/NetworkWatchlistShellCommand.java
5e4f93e1ecfccf7d3aa89435ac7d1551773d0169
[]
no_license
CrackerCat/XiaomiFramework
https://github.com/CrackerCat/XiaomiFramework
17a12c1752296fa1a52f61b83ecf165f328f4523
0b7952df317dac02ebd1feea7507afb789cef2e3
refs/heads/master
2022-06-12T03:30:33.285000
2020-05-06T11:30:54
2020-05-06T11:30:54
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.android.server.net.watchlist; import android.content.Context; import android.os.Binder; import android.os.ParcelFileDescriptor; import android.os.RemoteException; import android.os.ShellCommand; import android.provider.Settings; import com.android.server.wm.ActivityTaskManagerService; import java.io.FileInputStream; import java.io.PrintWriter; class NetworkWatchlistShellCommand extends ShellCommand { final Context mContext; final NetworkWatchlistService mService; NetworkWatchlistShellCommand(NetworkWatchlistService service, Context context) { this.mContext = context; this.mService = service; } /* JADX WARNING: Removed duplicated region for block: B:18:0x0034 A[Catch:{ Exception -> 0x0045 }] */ /* JADX WARNING: Removed duplicated region for block: B:23:0x0040 A[Catch:{ Exception -> 0x0045 }] */ /* Code decompiled incorrectly, please refer to instructions dump. */ public int onCommand(java.lang.String r6) { /* r5 = this; if (r6 != 0) goto L_0x0007 int r0 = r5.handleDefaultCommands(r6) return r0 L_0x0007: java.io.PrintWriter r0 = r5.getOutPrintWriter() r1 = -1 int r2 = r6.hashCode() // Catch:{ Exception -> 0x0045 } r3 = 1757613042(0x68c30bf2, float:7.3686545E24) r4 = 1 if (r2 == r3) goto L_0x0026 r3 = 1854202282(0x6e84e1aa, float:2.0562416E28) if (r2 == r3) goto L_0x001c L_0x001b: goto L_0x0031 L_0x001c: java.lang.String r2 = "force-generate-report" boolean r2 = r6.equals(r2) // Catch:{ Exception -> 0x0045 } if (r2 == 0) goto L_0x001b r2 = r4 goto L_0x0032 L_0x0026: java.lang.String r2 = "set-test-config" boolean r2 = r6.equals(r2) // Catch:{ Exception -> 0x0045 } if (r2 == 0) goto L_0x001b r2 = 0 goto L_0x0032 L_0x0031: r2 = r1 L_0x0032: if (r2 == 0) goto L_0x0040 if (r2 == r4) goto L_0x003b int r1 = r5.handleDefaultCommands(r6) // Catch:{ Exception -> 0x0045 } return r1 L_0x003b: int r1 = r5.runForceGenerateReport() // Catch:{ Exception -> 0x0045 } return r1 L_0x0040: int r1 = r5.runSetTestConfig() // Catch:{ Exception -> 0x0045 } return r1 L_0x0045: r2 = move-exception java.lang.StringBuilder r3 = new java.lang.StringBuilder r3.<init>() java.lang.String r4 = "Exception: " r3.append(r4) r3.append(r2) java.lang.String r3 = r3.toString() r0.println(r3) return r1 */ throw new UnsupportedOperationException("Method not decompiled: com.android.server.net.watchlist.NetworkWatchlistShellCommand.onCommand(java.lang.String):int"); } private int runSetTestConfig() throws RemoteException { PrintWriter pw = getOutPrintWriter(); try { ParcelFileDescriptor pfd = openFileForSystem(getNextArgRequired(), ActivityTaskManagerService.DUMP_RECENTS_SHORT_CMD); if (pfd != null) { WatchlistConfig.getInstance().setTestMode(new FileInputStream(pfd.getFileDescriptor())); } pw.println("Success!"); return 0; } catch (Exception ex) { pw.println("Error: " + ex.toString()); return -1; } } private int runForceGenerateReport() throws RemoteException { PrintWriter pw = getOutPrintWriter(); long ident = Binder.clearCallingIdentity(); try { if (WatchlistConfig.getInstance().isConfigSecure()) { pw.println("Error: Cannot force generate report under production config"); return -1; } Settings.Global.putLong(this.mContext.getContentResolver(), "network_watchlist_last_report_time", 0); this.mService.forceReportWatchlistForTest(System.currentTimeMillis()); pw.println("Success!"); Binder.restoreCallingIdentity(ident); return 0; } catch (Exception ex) { pw.println("Error: " + ex); return -1; } finally { Binder.restoreCallingIdentity(ident); } } public void onHelp() { PrintWriter pw = getOutPrintWriter(); pw.println("Network watchlist manager commands:"); pw.println(" help"); pw.println(" Print this help text."); pw.println(" set-test-config your_watchlist_config.xml"); pw.println(" Set network watchlist test config file."); pw.println(" force-generate-report"); pw.println(" Force generate watchlist test report."); } }
UTF-8
Java
4,957
java
NetworkWatchlistShellCommand.java
Java
[]
null
[]
package com.android.server.net.watchlist; import android.content.Context; import android.os.Binder; import android.os.ParcelFileDescriptor; import android.os.RemoteException; import android.os.ShellCommand; import android.provider.Settings; import com.android.server.wm.ActivityTaskManagerService; import java.io.FileInputStream; import java.io.PrintWriter; class NetworkWatchlistShellCommand extends ShellCommand { final Context mContext; final NetworkWatchlistService mService; NetworkWatchlistShellCommand(NetworkWatchlistService service, Context context) { this.mContext = context; this.mService = service; } /* JADX WARNING: Removed duplicated region for block: B:18:0x0034 A[Catch:{ Exception -> 0x0045 }] */ /* JADX WARNING: Removed duplicated region for block: B:23:0x0040 A[Catch:{ Exception -> 0x0045 }] */ /* Code decompiled incorrectly, please refer to instructions dump. */ public int onCommand(java.lang.String r6) { /* r5 = this; if (r6 != 0) goto L_0x0007 int r0 = r5.handleDefaultCommands(r6) return r0 L_0x0007: java.io.PrintWriter r0 = r5.getOutPrintWriter() r1 = -1 int r2 = r6.hashCode() // Catch:{ Exception -> 0x0045 } r3 = 1757613042(0x68c30bf2, float:7.3686545E24) r4 = 1 if (r2 == r3) goto L_0x0026 r3 = 1854202282(0x6e84e1aa, float:2.0562416E28) if (r2 == r3) goto L_0x001c L_0x001b: goto L_0x0031 L_0x001c: java.lang.String r2 = "force-generate-report" boolean r2 = r6.equals(r2) // Catch:{ Exception -> 0x0045 } if (r2 == 0) goto L_0x001b r2 = r4 goto L_0x0032 L_0x0026: java.lang.String r2 = "set-test-config" boolean r2 = r6.equals(r2) // Catch:{ Exception -> 0x0045 } if (r2 == 0) goto L_0x001b r2 = 0 goto L_0x0032 L_0x0031: r2 = r1 L_0x0032: if (r2 == 0) goto L_0x0040 if (r2 == r4) goto L_0x003b int r1 = r5.handleDefaultCommands(r6) // Catch:{ Exception -> 0x0045 } return r1 L_0x003b: int r1 = r5.runForceGenerateReport() // Catch:{ Exception -> 0x0045 } return r1 L_0x0040: int r1 = r5.runSetTestConfig() // Catch:{ Exception -> 0x0045 } return r1 L_0x0045: r2 = move-exception java.lang.StringBuilder r3 = new java.lang.StringBuilder r3.<init>() java.lang.String r4 = "Exception: " r3.append(r4) r3.append(r2) java.lang.String r3 = r3.toString() r0.println(r3) return r1 */ throw new UnsupportedOperationException("Method not decompiled: com.android.server.net.watchlist.NetworkWatchlistShellCommand.onCommand(java.lang.String):int"); } private int runSetTestConfig() throws RemoteException { PrintWriter pw = getOutPrintWriter(); try { ParcelFileDescriptor pfd = openFileForSystem(getNextArgRequired(), ActivityTaskManagerService.DUMP_RECENTS_SHORT_CMD); if (pfd != null) { WatchlistConfig.getInstance().setTestMode(new FileInputStream(pfd.getFileDescriptor())); } pw.println("Success!"); return 0; } catch (Exception ex) { pw.println("Error: " + ex.toString()); return -1; } } private int runForceGenerateReport() throws RemoteException { PrintWriter pw = getOutPrintWriter(); long ident = Binder.clearCallingIdentity(); try { if (WatchlistConfig.getInstance().isConfigSecure()) { pw.println("Error: Cannot force generate report under production config"); return -1; } Settings.Global.putLong(this.mContext.getContentResolver(), "network_watchlist_last_report_time", 0); this.mService.forceReportWatchlistForTest(System.currentTimeMillis()); pw.println("Success!"); Binder.restoreCallingIdentity(ident); return 0; } catch (Exception ex) { pw.println("Error: " + ex); return -1; } finally { Binder.restoreCallingIdentity(ident); } } public void onHelp() { PrintWriter pw = getOutPrintWriter(); pw.println("Network watchlist manager commands:"); pw.println(" help"); pw.println(" Print this help text."); pw.println(" set-test-config your_watchlist_config.xml"); pw.println(" Set network watchlist test config file."); pw.println(" force-generate-report"); pw.println(" Force generate watchlist test report."); } }
4,957
0.58604
0.532378
127
38.031498
28.850397
168
false
false
0
0
0
0
0
0
0.393701
false
false
2
5c68bebd174833b6ad31ee31b51607b7ab6a6d17
12,601,434,081,255
34ace32d1621a5d50c0c3e719082e4c2130701fa
/myhellochild/src/main/java/com/own/myhello/Mythread.java
2ce83a1b408ac856121cfe3e48d52654be96db90
[]
no_license
a20124597/myhello
https://github.com/a20124597/myhello
b226686bbebbdd47ca882e8488d1ae6e3c76c0bd
ae868af9ad9e5bfa77360733fc04b105d4e63f2b
refs/heads/main
2023-02-10T18:08:30.753000
2021-01-01T08:04:04
2021-01-01T08:04:04
324,733,875
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.own.myhello; public class Mythread extends Thread { @Override public void run() { try { int i = 0; while (i < 1000000) { System.out.println("正在运行的线程名称:" + i + "\t" + this.currentThread().getName() + " 开始"); Thread.sleep(2000); //延时1秒 System.out.println("正在运行的线程名称:" + i + "\t" + this.currentThread().getName() + " 结束"); i += 1; } } catch (InterruptedException e) { e.printStackTrace(); } } }
UTF-8
Java
610
java
Mythread.java
Java
[]
null
[]
package com.own.myhello; public class Mythread extends Thread { @Override public void run() { try { int i = 0; while (i < 1000000) { System.out.println("正在运行的线程名称:" + i + "\t" + this.currentThread().getName() + " 开始"); Thread.sleep(2000); //延时1秒 System.out.println("正在运行的线程名称:" + i + "\t" + this.currentThread().getName() + " 结束"); i += 1; } } catch (InterruptedException e) { e.printStackTrace(); } } }
610
0.473022
0.447842
18
29.888889
28.284054
101
false
false
0
0
0
0
0
0
0.388889
false
false
2
6393006735d15e0818bb7615948ce7758a524ad0
12,601,434,081,409
6b36c48e12ebdbb4b1870271c89f0a8f8b5a35ff
/src/com/kirilo/task/repositories/AbstractFacadeRepository.java
7faaa117cd93c37f6fa0fc7293bd0ad388f61fbf
[]
no_license
Lozitsky/awesome_maven_project
https://github.com/Lozitsky/awesome_maven_project
688a1cc58ab155faa5295497c0b57a59a1afb009
c810ced4ae407c9231448a96819b5fb47a8c62dc
refs/heads/master
2023-03-05T07:41:30.372000
2021-02-12T19:24:36
2021-02-12T19:24:36
338,412,096
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.kirilo.task.repositories; import javax.inject.Inject; import javax.persistence.EntityManager; import javax.persistence.TypedQuery; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Root; import java.util.List; import java.util.Optional; import java.util.logging.Level; import java.util.logging.Logger; // https://github.com/eclipse-ee4j/jakartaee-tutorial-examples/tree/4f45630c81176895ce2a3cf414d79b9bdd5e640c/persistence/address-book/src/main/java/jakarta/tutorial/addressbook/ejb public abstract class AbstractFacadeRepository<T> { private final Class<T> entityClass; @Inject public AbstractFacadeRepository(Class<T> entityClass) { this.entityClass = entityClass; } protected abstract EntityManager getEntityManager(); public T save(T entity) { Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, "save: " + (entity) + "\n"); Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, "getEntityManager(): " + (null == getEntityManager() ? null : getEntityManager().getClass().getName()) + "\n"); getEntityManager().persist(entity); return entity; } public void update(T entity) { getEntityManager().merge(entity); } public void delete(T entity) { getEntityManager().remove(getEntityManager().merge(entity)); } public void deleteBy(Object param) { getEntityManager().remove(findBy(param)); } public T findBy(Object param) { return getEntityManager().find(entityClass, param); } public T findById(Long id) { final T entity = findBy(id); if (entity == null) { // throw new NotFoundException(String.format("post id:%s not found!", id)); } return entity; } public Optional<T> findOptionalById(Long id) { T task = getEntityManager().find(entityClass, id); return Optional.ofNullable(task); } public List<T> findBy(String param, Object obj) { final TypedQuery<T> query = getFindByTypedQuery(param, obj); return query.getResultList(); } public T findSingleBy(String param, Object obj) { final TypedQuery<T> query = getFindByTypedQuery(param, obj); return query.getSingleResult(); } private TypedQuery<T> getFindByTypedQuery(String param, Object o) { CriteriaBuilder cb = getEntityManager().getCriteriaBuilder(); CriteriaQuery<T> q = cb.createQuery(entityClass); Root<T> c = q.from(entityClass); if (null != param && null != o) { q.where(cb.equal(c.get(param), o)); } return getEntityManager().createQuery(q); } public List<T> findAll() { final CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery(); cq.select(cq.from(entityClass)); return getEntityManager().createQuery(cq).getResultList(); } }
UTF-8
Java
2,994
java
AbstractFacadeRepository.java
Java
[ { "context": " java.util.logging.Logger;\n\n// https://github.com/eclipse-ee4j/jakartaee-tutorial-examples/tree/4f45630c81176895", "end": 434, "score": 0.9987317323684692, "start": 422, "tag": "USERNAME", "value": "eclipse-ee4j" } ]
null
[]
package com.kirilo.task.repositories; import javax.inject.Inject; import javax.persistence.EntityManager; import javax.persistence.TypedQuery; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Root; import java.util.List; import java.util.Optional; import java.util.logging.Level; import java.util.logging.Logger; // https://github.com/eclipse-ee4j/jakartaee-tutorial-examples/tree/4f45630c81176895ce2a3cf414d79b9bdd5e640c/persistence/address-book/src/main/java/jakarta/tutorial/addressbook/ejb public abstract class AbstractFacadeRepository<T> { private final Class<T> entityClass; @Inject public AbstractFacadeRepository(Class<T> entityClass) { this.entityClass = entityClass; } protected abstract EntityManager getEntityManager(); public T save(T entity) { Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, "save: " + (entity) + "\n"); Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, "getEntityManager(): " + (null == getEntityManager() ? null : getEntityManager().getClass().getName()) + "\n"); getEntityManager().persist(entity); return entity; } public void update(T entity) { getEntityManager().merge(entity); } public void delete(T entity) { getEntityManager().remove(getEntityManager().merge(entity)); } public void deleteBy(Object param) { getEntityManager().remove(findBy(param)); } public T findBy(Object param) { return getEntityManager().find(entityClass, param); } public T findById(Long id) { final T entity = findBy(id); if (entity == null) { // throw new NotFoundException(String.format("post id:%s not found!", id)); } return entity; } public Optional<T> findOptionalById(Long id) { T task = getEntityManager().find(entityClass, id); return Optional.ofNullable(task); } public List<T> findBy(String param, Object obj) { final TypedQuery<T> query = getFindByTypedQuery(param, obj); return query.getResultList(); } public T findSingleBy(String param, Object obj) { final TypedQuery<T> query = getFindByTypedQuery(param, obj); return query.getSingleResult(); } private TypedQuery<T> getFindByTypedQuery(String param, Object o) { CriteriaBuilder cb = getEntityManager().getCriteriaBuilder(); CriteriaQuery<T> q = cb.createQuery(entityClass); Root<T> c = q.from(entityClass); if (null != param && null != o) { q.where(cb.equal(c.get(param), o)); } return getEntityManager().createQuery(q); } public List<T> findAll() { final CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery(); cq.select(cq.from(entityClass)); return getEntityManager().createQuery(cq).getResultList(); } }
2,994
0.674349
0.665331
91
31.901098
33.412525
181
false
false
0
0
0
0
74
0.024716
0.549451
false
false
2
b07a265c2c3b6edc16db88860e3ae7bdb33d8dcf
36,584,531,428,974
4c52e5acc0ff0abd09b0cbed33ea54e02c22def9
/src/resources/conexao/jpa_controler/MinisteriaisJpaController.java
84f6a359b1d353372c86faa68bc66a31ad4e2f84
[]
no_license
Lareas/EvedSysRefactory
https://github.com/Lareas/EvedSysRefactory
ed6e921b740f5cd5021ed74dadca44a8959381c5
eb632a6ecae131f322f5c459a533c9d53c9dabc7
refs/heads/main
2023-05-02T03:40:09.714000
2021-05-25T09:21:38
2021-05-25T09:21:38
370,633,798
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package jpa_controler; import static main.Login.gbDeOnde; import entities.Ministeriais; import java.io.Serializable; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Query; import javax.persistence.EntityNotFoundException; import javax.persistence.Persistence; import javax.persistence.TypedQuery; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Root; import jpa_controler.exceptions.NonexistentEntityException; import jpa_controler.exceptions.PreexistingEntityException; public class MinisteriaisJpaController implements Serializable { public MinisteriaisJpaController(EntityManagerFactory emf) { this.emf = emf; } private EntityManagerFactory emf = null; public EntityManager getEntityManager() { return emf.createEntityManager(); } public MinisteriaisJpaController() { emf = Persistence.createEntityManagerFactory(gbDeOnde); } public List<String> getNomeDosMinisteriosF() { EntityManager em = null; em = getEntityManager(); TypedQuery<String> qry = em.createQuery("select s.ministeriais from Ministeriais s order by s.ministeriais", String.class); return qry.getResultList(); } public List<Ministeriais> getMinisteriaisPesq(String pesq) { EntityManager em = null; em = getEntityManager(); TypedQuery<Ministeriais> qry = em.createQuery("select s from Ministeriais s WHERE s.ministeriais LIKE '%" + pesq +"%'", Ministeriais.class); return qry.getResultList(); } public List<Ministeriais> getMinisteriaisPesqExac(String pesq) { EntityManager em = null; em = getEntityManager(); TypedQuery<Ministeriais> qry = em.createQuery("select s from Ministeriais s WHERE s.ministeriais = '" + pesq +"'", Ministeriais.class); return qry.getResultList(); } public void create(Ministeriais ministeriais) throws PreexistingEntityException, Exception { EntityManager em = null; try { em = getEntityManager(); em.getTransaction().begin(); em.persist(ministeriais); em.getTransaction().commit(); } catch (Exception ex) { if (findMinisteriais(ministeriais.getMinisteriaisId()) != null) { throw new PreexistingEntityException("Ministeriais " + ministeriais + " already exists.", ex); } throw ex; } finally { if (em != null) { em.close(); } } } public void edit(Ministeriais ministeriais) throws NonexistentEntityException, Exception { EntityManager em = null; try { em = getEntityManager(); em.getTransaction().begin(); ministeriais = em.merge(ministeriais); em.getTransaction().commit(); } catch (Exception ex) { String msg = ex.getLocalizedMessage(); if (msg == null || msg.length() == 0) { Short id = ministeriais.getMinisteriaisId(); if (findMinisteriais(id) == null) { throw new NonexistentEntityException("The ministeriais with id " + id + " no longer exists."); } } throw ex; } finally { if (em != null) { em.close(); } } } public void destroy(Short id) throws NonexistentEntityException { EntityManager em = null; try { em = getEntityManager(); em.getTransaction().begin(); Ministeriais ministeriais; try { ministeriais = em.getReference(Ministeriais.class, id); ministeriais.getMinisteriaisId(); } catch (EntityNotFoundException enfe) { throw new NonexistentEntityException("The ministeriais with id " + id + " no longer exists.", enfe); } em.remove(ministeriais); em.getTransaction().commit(); } finally { if (em != null) { em.close(); } } } public List<Ministeriais> findMinisteriaisEntities() { return findMinisteriaisEntities(true, -1, -1); } public List<Ministeriais> findMinisteriaisEntities(int maxResults, int firstResult) { return findMinisteriaisEntities(false, maxResults, firstResult); } private List<Ministeriais> findMinisteriaisEntities(boolean all, int maxResults, int firstResult) { EntityManager em = getEntityManager(); try { CriteriaQuery cq = em.getCriteriaBuilder().createQuery(); cq.select(cq.from(Ministeriais.class)); Query q = em.createQuery(cq); if (!all) { q.setMaxResults(maxResults); q.setFirstResult(firstResult); } return q.getResultList(); } finally { em.close(); } } public Ministeriais findMinisteriais(Short id) { EntityManager em = getEntityManager(); try { return em.find(Ministeriais.class, id); } finally { em.close(); } } public int getMinisteriaisCount() { EntityManager em = getEntityManager(); try { CriteriaQuery cq = em.getCriteriaBuilder().createQuery(); Root<Ministeriais> rt = cq.from(Ministeriais.class); cq.select(em.getCriteriaBuilder().count(rt)); Query q = em.createQuery(cq); return ((Long) q.getSingleResult()).intValue(); } finally { em.close(); } } }
UTF-8
Java
5,753
java
MinisteriaisJpaController.java
Java
[]
null
[]
package jpa_controler; import static main.Login.gbDeOnde; import entities.Ministeriais; import java.io.Serializable; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Query; import javax.persistence.EntityNotFoundException; import javax.persistence.Persistence; import javax.persistence.TypedQuery; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Root; import jpa_controler.exceptions.NonexistentEntityException; import jpa_controler.exceptions.PreexistingEntityException; public class MinisteriaisJpaController implements Serializable { public MinisteriaisJpaController(EntityManagerFactory emf) { this.emf = emf; } private EntityManagerFactory emf = null; public EntityManager getEntityManager() { return emf.createEntityManager(); } public MinisteriaisJpaController() { emf = Persistence.createEntityManagerFactory(gbDeOnde); } public List<String> getNomeDosMinisteriosF() { EntityManager em = null; em = getEntityManager(); TypedQuery<String> qry = em.createQuery("select s.ministeriais from Ministeriais s order by s.ministeriais", String.class); return qry.getResultList(); } public List<Ministeriais> getMinisteriaisPesq(String pesq) { EntityManager em = null; em = getEntityManager(); TypedQuery<Ministeriais> qry = em.createQuery("select s from Ministeriais s WHERE s.ministeriais LIKE '%" + pesq +"%'", Ministeriais.class); return qry.getResultList(); } public List<Ministeriais> getMinisteriaisPesqExac(String pesq) { EntityManager em = null; em = getEntityManager(); TypedQuery<Ministeriais> qry = em.createQuery("select s from Ministeriais s WHERE s.ministeriais = '" + pesq +"'", Ministeriais.class); return qry.getResultList(); } public void create(Ministeriais ministeriais) throws PreexistingEntityException, Exception { EntityManager em = null; try { em = getEntityManager(); em.getTransaction().begin(); em.persist(ministeriais); em.getTransaction().commit(); } catch (Exception ex) { if (findMinisteriais(ministeriais.getMinisteriaisId()) != null) { throw new PreexistingEntityException("Ministeriais " + ministeriais + " already exists.", ex); } throw ex; } finally { if (em != null) { em.close(); } } } public void edit(Ministeriais ministeriais) throws NonexistentEntityException, Exception { EntityManager em = null; try { em = getEntityManager(); em.getTransaction().begin(); ministeriais = em.merge(ministeriais); em.getTransaction().commit(); } catch (Exception ex) { String msg = ex.getLocalizedMessage(); if (msg == null || msg.length() == 0) { Short id = ministeriais.getMinisteriaisId(); if (findMinisteriais(id) == null) { throw new NonexistentEntityException("The ministeriais with id " + id + " no longer exists."); } } throw ex; } finally { if (em != null) { em.close(); } } } public void destroy(Short id) throws NonexistentEntityException { EntityManager em = null; try { em = getEntityManager(); em.getTransaction().begin(); Ministeriais ministeriais; try { ministeriais = em.getReference(Ministeriais.class, id); ministeriais.getMinisteriaisId(); } catch (EntityNotFoundException enfe) { throw new NonexistentEntityException("The ministeriais with id " + id + " no longer exists.", enfe); } em.remove(ministeriais); em.getTransaction().commit(); } finally { if (em != null) { em.close(); } } } public List<Ministeriais> findMinisteriaisEntities() { return findMinisteriaisEntities(true, -1, -1); } public List<Ministeriais> findMinisteriaisEntities(int maxResults, int firstResult) { return findMinisteriaisEntities(false, maxResults, firstResult); } private List<Ministeriais> findMinisteriaisEntities(boolean all, int maxResults, int firstResult) { EntityManager em = getEntityManager(); try { CriteriaQuery cq = em.getCriteriaBuilder().createQuery(); cq.select(cq.from(Ministeriais.class)); Query q = em.createQuery(cq); if (!all) { q.setMaxResults(maxResults); q.setFirstResult(firstResult); } return q.getResultList(); } finally { em.close(); } } public Ministeriais findMinisteriais(Short id) { EntityManager em = getEntityManager(); try { return em.find(Ministeriais.class, id); } finally { em.close(); } } public int getMinisteriaisCount() { EntityManager em = getEntityManager(); try { CriteriaQuery cq = em.getCriteriaBuilder().createQuery(); Root<Ministeriais> rt = cq.from(Ministeriais.class); cq.select(em.getCriteriaBuilder().count(rt)); Query q = em.createQuery(cq); return ((Long) q.getSingleResult()).intValue(); } finally { em.close(); } } }
5,753
0.60664
0.606119
164
34.079269
28.888765
148
false
false
0
0
0
0
0
0
0.591463
false
false
2
788fff5720e0cd848f5983a69bccc356f9fedde5
36,584,531,427,968
719f6bc65ecd85e99e8d429da64beb4f98849b39
/src/main/java/com/concurrent/interrupt/InterruptApp.java
c0d237c84c62ab46f525d2c5736d8878695b53ab
[]
no_license
t734070824/JavaBasicByMaven
https://github.com/t734070824/JavaBasicByMaven
b73a75099b28453e049f0b2e48dec2095e379edf
9d7c7c7bbe22e678b2424d911356ba33057f8af8
refs/heads/master
2019-03-21T07:13:48.199000
2017-12-30T03:10:35
2017-12-30T03:10:35
35,396,510
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.concurrent.interrupt; import java.util.concurrent.TimeUnit; public class InterruptApp extends Thread{ public static void main(String[] args) throws InterruptedException { InterruptApp app = new InterruptApp(); app.start(); TimeUnit.SECONDS.sleep(1); app.interrupt(); } @Override public void run() { while (!Thread.interrupted()) { try { System.err.println("111"); TimeUnit.SECONDS.sleep(3); } catch (InterruptedException e) { System.err.println("InterruptApp"); // return; } } } }
UTF-8
Java
563
java
InterruptApp.java
Java
[]
null
[]
package com.concurrent.interrupt; import java.util.concurrent.TimeUnit; public class InterruptApp extends Thread{ public static void main(String[] args) throws InterruptedException { InterruptApp app = new InterruptApp(); app.start(); TimeUnit.SECONDS.sleep(1); app.interrupt(); } @Override public void run() { while (!Thread.interrupted()) { try { System.err.println("111"); TimeUnit.SECONDS.sleep(3); } catch (InterruptedException e) { System.err.println("InterruptApp"); // return; } } } }
563
0.657194
0.648313
27
18.851852
17.804918
69
false
false
0
0
0
0
0
0
1.814815
false
false
2
71aa334e1ea94de6cb596ced1d3a2f1cec5ea793
35,914,516,532,962
5a99ccef709daf01304efb1e5667d350c9d72543
/src/fr/ecp/is1220/MyFoodora/FoodItem.java
6d6c1e4c043811b0f39a5a73355aafa81cdae87c
[ "MIT" ]
permissive
ColasGael/MyFoodora
https://github.com/ColasGael/MyFoodora
7dcb26a2c939e9c7a110c2b2b9886e87975f33c1
45cc5062d3c071626efea308cfe6e723ad2986b4
refs/heads/master
2020-03-15T17:54:04.255000
2019-05-28T17:46:16
2019-05-28T17:46:16
132,271,850
5
2
null
null
null
null
null
null
null
null
null
null
null
null
null
package fr.ecp.is1220.MyFoodora; /** * this abstract class enables us to deal with both Dish and Meal objects in the sorter */ public abstract class FoodItem implements java.io.Serializable { private static final long serialVersionUID = -4013771930891098924L; /** * the total price of the food item */ protected double price = 0; /** * the number of times the food item has been shipped */ protected int counter = 0 ; public int getCounter(){ return counter ; } public void setPrice(double price) { this.price = price; } public double getPrice() { return price; } public void increaseCounter() { this.counter++ ; } }
UTF-8
Java
690
java
FoodItem.java
Java
[]
null
[]
package fr.ecp.is1220.MyFoodora; /** * this abstract class enables us to deal with both Dish and Meal objects in the sorter */ public abstract class FoodItem implements java.io.Serializable { private static final long serialVersionUID = -4013771930891098924L; /** * the total price of the food item */ protected double price = 0; /** * the number of times the food item has been shipped */ protected int counter = 0 ; public int getCounter(){ return counter ; } public void setPrice(double price) { this.price = price; } public double getPrice() { return price; } public void increaseCounter() { this.counter++ ; } }
690
0.665217
0.628986
33
18.90909
22.404495
87
false
false
0
0
0
0
0
0
1.060606
false
false
2
ef309cf4a57c2d0187ecb0d41ec1aab237221341
11,424,613,011,892
e336473ecdc8043480de6c5235bbab86dac588d0
/Contacts/src/com/android/contacts/AddSpeedDialActivity.java
a11452fc448814de1fab4cd646cb06fb032f6a58
[ "Apache-2.0" ]
permissive
wangyx0055/AZ8188-LOW13
https://github.com/wangyx0055/AZ8188-LOW13
509c96bf75b170be4d97c262be5c15286d77018a
7f430136afbd4c91af57dde3e43fb90a4ccaf9e1
refs/heads/master
2023-08-30T21:37:31.239000
2012-11-19T09:04:21
2012-11-19T09:04:21
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.android.contacts; import java.util.ArrayList; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.BaseAdapter; import android.widget.ListView; import android.widget.SimpleCursorAdapter; import android.widget.TextView; import android.widget.Collapser.Collapsible; import android.app.Activity; import android.app.AlertDialog; import android.app.AlertDialog.Builder; import android.content.ContentResolver; import android.content.ContentUris; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.content.res.Resources; import android.database.ContentObserver; import android.database.Cursor; import android.database.MatrixCursor; import android.graphics.BitmapFactory; import com.android.contacts.util.NotifyingAsyncQueryHandler; import com.android.internal.widget.ContactHeaderWidget; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.RemoteException; import android.os.ServiceManager; import android.provider.ContactsContract.CommonDataKinds; import android.provider.ContactsContract.Contacts; import android.provider.ContactsContract.PhoneLookup; import android.provider.ContactsContract.RawContacts; import android.provider.ContactsContract.RawContactsEntity; import android.provider.ContactsContract.CommonDataKinds.Phone; import android.telephony.PhoneNumberUtils; import android.telephony.TelephonyManager; import android.text.TextUtils; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Toast; import com.android.contacts.SpeedDialManageActivity; import android.provider.Telephony.SIMInfo;//gemini enhancement import com.android.internal.telephony.ITelephony; import com.mediatek.featureoption.FeatureOption; import com.mediatek.telephony.PhoneNumberFormatUtilEx; import com.mediatek.telephony.PhoneNumberFormattingTextWatcherEx; /** * AddSpeedDialActivity * @author mtk80909 * UI to add the current contact's phone number to certain keys as speed dials. */ public class AddSpeedDialActivity extends Activity implements DialogInterface.OnClickListener, AdapterView.OnItemClickListener, NotifyingAsyncQueryHandler.AsyncQueryListener, View.OnClickListener { private static final String TAG = "AddSpeedDialActivity"; /** * Query token for contact's phone numbers */ private static final int NUMBER_QUERY_TOKEN = 47; /** * Query token for confirming that phone numbers in speed dial preferences * are in Contacts database. */ private static final int SPEED_DIAL_QUERY_TOKEN = 48; private SharedPreferences mPref; private ListView mListView; private ContactHeaderWidget mHeaderWidget; private Cursor mContactCursor; private Cursor mPhoneCursor; private ITelephony mITel; private ContentObserver mObserver = new ContentObserver(new Handler()) { @Override public boolean deliverSelfNotifications() { return true; } @Override public void onChange(boolean selfChange) { if (mContactCursor != null && !mContactCursor.isClosed()) { startEntityQuery(); } } }; private NotifyingAsyncQueryHandler mHandler; private Uri mLookupUri; private ContentResolver mResolver; private static final int ASSIGNED_KEY_NOT_MODIFIED = 0; private static final int ASSIGNED_KEY_MODIFIED = 2; private int mTempIndex = 0; // used for save index of onclick of dialog //private int mTempKey = 0; // used for save assigned key which need to save private int mTempPrefMarkState = -1; private String mTempPrefNumState = ""; private boolean mIsFirstEnterAddSpeedDial = true; private boolean mIsClickSpeedDialDialog = false; private int mModified = ASSIGNED_KEY_NOT_MODIFIED; /** * Current values in the SharedPreferences -- Phone numbers. */ private String[] mPrefNumState = { "", // 0 "", // 1 "", // 2 "", // 3 "", // 4 "", // 5 "", // 6 "", // 7 "", // 8 "", // 9 }; /** * Current values in the SharedPreferences -- Phone/SIM indicators. * -1 -- Phone * 0 -- Single SIM * 1 -- SIM1 * 2 -- SIM2 */ private int[] mPrefMarkState = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }; /** * Projection and indices used to display (used by the MatrixCursor). */ static final String[] BIND_PROJECTION = { PhoneLookup._ID, // 0 PhoneLookup.DISPLAY_NAME, // 1 PhoneLookup.TYPE, // 2 PhoneLookup.NUMBER, // 3 }; static final int BIND_ID_INDEX = 0; static final int BIND_DISPLAY_NAME_INDEX = 1; static final int BIND_LABEL_INDEX = 2; static final int BIND_NUMBER_INDEX = 3; /* * ID's of views to bind. */ private static final int[] ADAPTER_TO = { R.id.sd_index, R.id.sd_name, R.id.sd_label, R.id.sd_number, }; private AddSpeedDialAdapter mAdapter; private ArrayList<NumberEntry> mNumberEntries; private int mPhoneSimIndicator; private AlertDialog mNumberDialog; private AlertDialog mKeyDialog; private String mDisplayName; private int mQueryTimes; private MatrixCursor mMatrixCursor; private SimpleCursorAdapter mKeyDialogAdapter; /** * Implementation follows ViewContactActivity.startEntityQuery(). */ private synchronized void startEntityQuery() { closeCursor(); mContactCursor = ViewContactActivity.setupContactCursor(mResolver, mLookupUri); if (mContactCursor == null) { mLookupUri = Contacts.getLookupUri(getContentResolver(), mLookupUri); mContactCursor = ViewContactActivity.setupContactCursor(mResolver, mLookupUri); } if (mContactCursor == null) { finish(); return; } mContactCursor.registerContentObserver(mObserver); final long contactId = ContentUris.parseId(mLookupUri); Uri uri = Contacts.lookupContact(mResolver, mLookupUri); mHeaderWidget.bindFromContactLookupUri(mLookupUri); if(uri == null)return ; Cursor tmpCursor = mResolver.query(uri, new String[] { RawContacts.INDICATE_PHONE_SIM, RawContacts.DISPLAY_NAME_PRIMARY }, null, null, null); if(tmpCursor != null){ tmpCursor.moveToFirst(); mPhoneSimIndicator = tmpCursor.getInt(0); mDisplayName = tmpCursor.getString(1); tmpCursor.close(); } // query the contact entity in the background // TODO: reduce the number of columns returned mHandler.startQuery(NUMBER_QUERY_TOKEN, null, RawContactsEntity.CONTENT_URI, null, RawContacts.CONTACT_ID + "=? AND " + Phone.MIMETYPE + "=?", new String[] {String.valueOf(contactId), Phone.CONTENT_ITEM_TYPE}, null); } /** * If the current contact is a SIM contact, * set SIM pictures as their photos */ private void setSimContactPhoto() { final ITelephony iTel = ITelephony.Stub.asInterface(ServiceManager .getService(Context.TELEPHONY_SERVICE)); if (null == iTel) { Log.d(TAG, "setSimContactPhoto(), call ITelephony failed!! "); return; } Resources res = getResources(); /*switch (mPhoneSimIndicator) { case RawContacts.INDICATE_SIM : mHeaderWidget.setPhoto(BitmapFactory.decodeResource( res, R.drawable.contact_icon_sim)); break; case RawContacts.INDICATE_SIM1 : mHeaderWidget.setPhoto(BitmapFactory.decodeResource( res, R.drawable.contact_icon_sim1)); break; case RawContacts.INDICATE_SIM2 : mHeaderWidget.setPhoto(BitmapFactory.decodeResource( res, R.drawable.contact_icon_sim2)); break; default: break; }*/ if (mPhoneSimIndicator >= RawContacts.INDICATE_SIM) { int slotId = SIMInfo.getSlotById(AddSpeedDialActivity.this, mPhoneSimIndicator); Log.d(TAG, "setSimContactPhoto(), slotId= "+ slotId +" ,mPhoneSimIndicator= "+ mPhoneSimIndicator); if (slotId >= 0) { try { if (com.mediatek.featureoption.FeatureOption.MTK_GEMINI_SUPPORT) { if (iTel.getIccCardTypeGemini(slotId).equals("USIM")) { if (null != mHeaderWidget) mHeaderWidget.setPhoto(BitmapFactory.decodeResource( res, R.drawable.contact_icon_usim)); } else { if (null != mHeaderWidget) mHeaderWidget.setPhoto(BitmapFactory.decodeResource( res, R.drawable.contact_icon_sim)); } } else { if (iTel.getIccCardType().equals("USIM")) { if (null != mHeaderWidget) mHeaderWidget.setPhoto(BitmapFactory.decodeResource( res, R.drawable.contact_icon_usim)); } else { if (null != mHeaderWidget) mHeaderWidget.setPhoto(BitmapFactory.decodeResource( res, R.drawable.contact_icon_sim)); } } } catch (Exception ex) { ex.printStackTrace(); } } } } private void closeCursor() { if (mContactCursor != null) { mContactCursor.unregisterContentObserver(mObserver); mContactCursor.close(); mContactCursor = null; } } public void onClick(DialogInterface dialog, int which) { // TODO Auto-generated method stub } public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // TODO Auto-generated method stub if (position == 0) { // phone number view showPhoneNumbers(); } else if (position == 1) { // assigned key view showAssignedKeys(); } else { throw new RuntimeException("This is not possible"); } } /** * Show the dialog of all phone numbers of the current contact. */ private void showPhoneNumbers() { if (mNumberEntries == null || mNumberEntries.isEmpty()) { Log.e(TAG, "Number entries empty!!"); return; } if (mNumberEntries.size() == 1) { Log.w(TAG, "Only one phone number here. We don't need a disambig dialog."); return; } // now, mNumberEntries must have at least 2 items. AlertDialog.Builder builder = new AlertDialog.Builder(this); ArrayAdapter<NumberEntry> adapter = new ArrayAdapter<NumberEntry>(this, R.layout.phone_disambig_item, android.R.id.text2, mNumberEntries) { @Override public View getView(int position, View convertView, ViewGroup parent) { View view = super.getView(position, convertView, parent); NumberEntry item = getItem(position); TextView typeView = (TextView)view.findViewById(android.R.id.text1); TextView numberView = (TextView)view.findViewById(android.R.id.text2); typeView.setText(item.label); numberView.setText(item.number); return view; } }; DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { // TODO Auto-generated method stub if (which < 0 || which >= mNumberEntries.size()) { dialog.dismiss(); return; } mAdapter.setNumberIndex(which); mAdapter.notifyDataSetChanged(); } }; mNumberDialog = builder.setTitle(mDisplayName).setAdapter(adapter, listener).create(); mNumberDialog.show(); } /** * show the dialog */ private void showAssignedKeys() { initMatrixCursor(); goOnQuery(); } /** * Searches the preferences, populates empty rows of the MatrixCursor, and starts real query for non-empty rows. */ private void goOnQuery() { int end; for (end = mQueryTimes; end < SpeedDialManageActivity.SPEED_DIAL_MAX + 1 && TextUtils.isEmpty(mPrefNumState[end]); ++end) { // empty loop body } SpeedDialManageActivity.populateMatrixCursorEmpty(this, mMatrixCursor, mQueryTimes - 1, end - 1); Log.i(TAG, "mQueryTimes = " + mQueryTimes + ", end = " + end); if (end > SpeedDialManageActivity.SPEED_DIAL_MAX) { Log.i(TAG, "queryComplete in goOnQuery()"); mKeyDialogAdapter.changeCursor(mMatrixCursor); showKeyDialog(); } else { mQueryTimes = end; Log.i(TAG, "startQuery at mQueryTimes = " + mQueryTimes); Log.i(TAG, "number = " + mPrefNumState[mQueryTimes]); Uri uri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(mPrefNumState[mQueryTimes])); Log.i(TAG, "uri = " + uri); mHandler.startQuery(SPEED_DIAL_QUERY_TOKEN, null, uri, SpeedDialManageActivity.QUERY_PROJECTION, null, null, null); //Cursor testCursor = getContentResolver().query(uri, QUERY_PROJECTION, null, null, null); } } private void initMatrixCursor() { if (mMatrixCursor != null) mMatrixCursor.close(); final int listCapacity = SpeedDialManageActivity.SPEED_DIAL_MAX - SpeedDialManageActivity.SPEED_DIAL_MIN + 1; mMatrixCursor = new MatrixCursor(SpeedDialManageActivity.BIND_PROJECTION, listCapacity); mQueryTimes = SpeedDialManageActivity.SPEED_DIAL_MIN; } public void onQueryComplete(int token, Object cookie, Cursor cursor) { // TODO Auto-generated method stub if (token == NUMBER_QUERY_TOKEN) { Log.i(TAG, "query complete"); Log.i(TAG, "cursor = " + cursor); Log.i(TAG, "cursor.getCount() = " + ((cursor == null) ? 0 : cursor.getCount())); String[] columnNames = cursor.getColumnNames(); String columnNamesToString = "["; for (int i = 0; i < columnNames.length; ++i) { columnNamesToString += columnNames[i] + ", "; } Log.i(TAG, columnNamesToString + "]"); setSimContactPhoto(); bindData(cursor); if (mPhoneCursor != null && !mPhoneCursor.isClosed()) { mPhoneCursor.close(); } mPhoneCursor = cursor; } else if (token == SPEED_DIAL_QUERY_TOKEN) { if (cursor != null && cursor.getCount() > 0) { populateMatrixCursorRow(mQueryTimes - 1, cursor); } else { SpeedDialManageActivity.populateMatrixCursorEmpty(this, mMatrixCursor, mQueryTimes - 1, mQueryTimes); clearPrefStateIfNecessary(mQueryTimes); } if (cursor != null) cursor.close(); ++mQueryTimes; Log.i(TAG, "mQueryTimes = " + mQueryTimes); if (mQueryTimes <= SpeedDialManageActivity.SPEED_DIAL_MAX) { goOnQuery(); } else { Log.i(TAG, "query stop in onQueryComplete"); mKeyDialogAdapter.changeCursor(mMatrixCursor); showKeyDialog(); } } else { Log.w(TAG, "onQueryComplete(): Should not reach here."); } } /** * Populates the indicated row of the MatrixCursor with the data in cursor. * @param row is the indicated row index of the MatrixCursor to populate * @param cursor is the data source */ private void populateMatrixCursorRow(int row, Cursor cursor) { cursor.moveToFirst(); String name = cursor.getString(SpeedDialManageActivity.QUERY_DISPLAY_NAME_INDEX); int type = cursor.getInt(SpeedDialManageActivity.QUERY_LABEL_INDEX);; String label = ""; if (type == 0) { label = cursor.getString(SpeedDialManageActivity.QUERY_CUSTOM_LABEL_INDEX); } else { label = (String)CommonDataKinds.Phone. getTypeLabel(getResources(), type, null); } String number = cursor.getString(SpeedDialManageActivity.QUERY_NUMBER_INDEX); long photoId = cursor.getLong(SpeedDialManageActivity.QUERY_PHOTO_ID_INDEX); int simId = -1; if (!cursor.isNull(SpeedDialManageActivity.QUERY_INDICATE_PHONE_SIM_INDEX)) { simId = cursor.getInt(SpeedDialManageActivity.QUERY_INDICATE_PHONE_SIM_INDEX); } Log.i(TAG, "name = " + name + ", label = " + label + ", number = " + number); if (TextUtils.isEmpty(number)) { SpeedDialManageActivity.populateMatrixCursorEmpty(this, mMatrixCursor, row, row + 1); mPrefNumState[row] = mPref.getString(String.valueOf(row), ""); mPrefMarkState[row] = mPref.getInt(String.valueOf(SpeedDialManageActivity.offset(row)), -1); return; } mMatrixCursor.addRow(new String[]{String.valueOf(row + 1), name, label, PhoneNumberFormatUtilEx.formatNumber(number) , String.valueOf(photoId), String.valueOf(simId)}); } /** * If the preference state stores a number * and the SIM card corresponding to its SIM indicator is not ready, * the cursor is populated with the empty value, * but the preference is not deleted. * @param queryTimes */ void clearPrefStateIfNecessary(int queryTimes) { int simId = mPrefMarkState[queryTimes]; // SIM state is ready if (simId == -1 || isSimReady(simId)) { mPrefMarkState[queryTimes] = -1; mPrefNumState[queryTimes] = ""; } } /** * Gets the present SIM state * @param simId is the SIM ID. Legal inputs include {0, 1, 2}; * @return true if SIM is ready. */ private boolean isSimReady(final int simId) { if (null == mITel) return false; Log.d(TAG, "isSimReady(), simId= "+simId); try { if (FeatureOption.MTK_GEMINI_SUPPORT) { int slotId = SIMInfo.getSlotById(AddSpeedDialActivity.this, simId); Log.d(TAG, "isSimReady(), slotId= "+slotId); if (-1 == slotId) { return true; } if (mITel.isRadioOnGemini(slotId)) { return !mITel.hasIccCardGemini(slotId) || (mITel.isRadioOnGemini(slotId) && !mITel.isFDNEnabledGemini(slotId) && TelephonyManager.SIM_STATE_READY == TelephonyManager .getDefault().getSimStateGemini(slotId) && !ContactsUtils.isServiceRunning[slotId]); } else { return !mITel.isSimInsert(slotId) || (mITel.isRadioOnGemini(slotId) && !mITel.isFDNEnabledGemini(slotId) && TelephonyManager.SIM_STATE_READY == TelephonyManager .getDefault().getSimStateGemini(slotId) && !ContactsUtils.isServiceRunning[slotId]); } } else { if(mITel.isRadioOn()) { return !mITel.hasIccCard() || (mITel.isRadioOn() && !mITel.isFDNEnabled() && TelephonyManager.SIM_STATE_READY == TelephonyManager .getDefault().getSimState() && !ContactsUtils.isServiceRunning[0]); } else { return !mITel.isSimInsert(0) || (mITel.isRadioOn() && !mITel.isFDNEnabled() && TelephonyManager.SIM_STATE_READY == TelephonyManager .getDefault().getSimState() && !ContactsUtils.isServiceRunning[0]); } } } catch (RemoteException e) { Log.w(TAG, "RemoteException!"); return false; } } /** * Bind the cursor to mAdapter so that the ListView will be updated * @param cursor */ private void bindData(Cursor cursor) { mNumberEntries.clear(); if (cursor == null || cursor.getCount() == 0) { return; } for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) { NumberEntry numberEntry = new NumberEntry(); int type = cursor.getInt(cursor.getColumnIndex(RawContactsEntity.DATA2)); if (type == 0) { numberEntry.label = cursor.getString(cursor.getColumnIndex(RawContactsEntity.DATA3)); } else { numberEntry.label = (String)CommonDataKinds.Phone.getTypeLabel(getResources(), cursor.getInt(cursor.getColumnIndex(RawContactsEntity.DATA2)), null); } numberEntry.number = cursor.getString(cursor.getColumnIndex(RawContactsEntity.DATA1)); mNumberEntries.add(numberEntry); } Collapser.collapseList(mNumberEntries); Log.i(TAG, "mNumberEntries in bindData: " + mNumberEntries); if (mAdapter == null) { mAdapter = new AddSpeedDialAdapter(this, mNumberEntries); mListView.setAdapter(mAdapter); } else { mAdapter.updateWith(mNumberEntries); } } /** * Responses 'ADD' and 'CANCEL' button */ public void onClick(View v) { // TODO Auto-generated method stub final int viewId = v.getId(); switch (viewId) { case R.id.add_button: saveChanges(); Log.i(TAG, "changes saved through 'add' button"); finish(); break; case R.id.cancel_button: Log.i(TAG, "canceled"); finish(); break; default: break; } } @Override public void onBackPressed() { // TODO Auto-generated method stub saveChanges(); Log.i(TAG, "changes saved through 'BACK' button"); super.onBackPressed(); } private void saveChanges() { Log.d(TAG, " saveChanges(), mModified= "+mModified); if (ASSIGNED_KEY_MODIFIED == mModified) { // user assign one key int index; for (int i = SpeedDialManageActivity.SPEED_DIAL_MIN; i < SpeedDialManageActivity.SPEED_DIAL_MAX + 1; ++i) { index = findKeyByNumber(mTempPrefNumState); Log.d(TAG, "findKeyByNumber is " + index); if (SpeedDialManageActivity.SPEED_DIAL_MIN <= index) { mPrefNumState[index] = ""; mPrefMarkState[index] = -1; } } Log.d(TAG, " saveChanges(), mTempPrefNumState="+mTempPrefNumState ); Log.d(TAG, " saveChanges(), mTempIndex="+mTempIndex ); mPrefNumState[mTempIndex] = mTempPrefNumState; mPrefMarkState[mTempIndex] = mTempPrefMarkState; } updatePreferences(); } private int findKeyByNumber(String number) { if (TextUtils.isEmpty(number)) { return -1; } for (int i = SpeedDialManageActivity.SPEED_DIAL_MIN; i < SpeedDialManageActivity.SPEED_DIAL_MAX + 1; ++i) { if (ContactsUtils.shouldCollapse(AddSpeedDialActivity.this, Phone.CONTENT_ITEM_TYPE, number, Phone.CONTENT_ITEM_TYPE, mPrefNumState[i])){ return i; } } return -1; } private void updatePreferences() { SharedPreferences.Editor editor = mPref.edit(); for (int i = SpeedDialManageActivity.SPEED_DIAL_MIN; i < SpeedDialManageActivity.SPEED_DIAL_MAX + 1; ++i) { editor.putString(String.valueOf(i), mPrefNumState[i]); editor.putInt(String.valueOf(SpeedDialManageActivity.offset(i)), mPrefMarkState[i]); } editor.apply(); } @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.add_speed_dial_layout); findViewById(R.id.add_button).setOnClickListener(this); findViewById(R.id.cancel_button).setOnClickListener(this); resolveIntent(); setHeaderWidget(); setupQueryHandler(); setupListView(); mResolver = getContentResolver(); mNumberEntries = new ArrayList<NumberEntry>(); Log.i(TAG, "mNumberEntries in onCreate(): " + mNumberEntries); mKeyDialogAdapter = new SimpleCursorAdapter(this, R.layout.speed_dial_simple_list_item, null, BIND_PROJECTION, ADAPTER_TO); mKeyDialogAdapter.setViewBinder(new SimpleCursorAdapter.ViewBinder() { // TODO use other adapter types. /** * what is called in bindView(). */ public boolean setViewValue(View view, Cursor cursor, int columnIndex) { // TODO Auto-generated method stub int viewId = view.getId(); boolean isNumberEmpty = TextUtils.isEmpty(cursor.getString(BIND_NUMBER_INDEX)); view.setEnabled(!isNumberEmpty); if (viewId == R.id.sd_index) { ((TextView)view).setText(cursor.getString(columnIndex) + ": "); } else if (viewId == R.id.sd_name) { if (isNumberEmpty) { ((TextView)view).setText(AddSpeedDialActivity. this.getResources().getString(R.string.available)); } else { ((TextView)view).setText(cursor.getString(columnIndex)); } } else if (viewId == R.id.sd_label) { view.setVisibility(isNumberEmpty ? View.GONE : View.VISIBLE); ((TextView)view).setText("(" + cursor.getString(columnIndex) + ")"); } else if (viewId == R.id.sd_number) { view.setVisibility(isNumberEmpty ? View.GONE : View.VISIBLE); ((TextView)view).setText(cursor.getString(columnIndex)); } return true; } }); } /** * Ensures that the URI obtained from the intent is not null. */ private void resolveIntent() { final Intent intent = getIntent(); mLookupUri = intent.getData(); if (mLookupUri == null) { finish(); } } private void setHeaderWidget() { mHeaderWidget = (ContactHeaderWidget) findViewById(R.id.contact_header_widget); mHeaderWidget.showStar(false); mHeaderWidget.setSelectedContactsAppTabIndex(StickyTabs.getTab(getIntent())); } private void setupListView() { mListView = (ListView) findViewById(R.id.contact_data); mListView.setOnItemClickListener(this); } private void setupQueryHandler() { mHandler = new NotifyingAsyncQueryHandler(this, this); } @Override protected void onDestroy() { // TODO Auto-generated method stub super.onDestroy(); closeCursor(); } @Override protected void onPause() { // TODO Auto-generated method stub super.onPause(); closeCursor(); } @Override protected void onResume() { // TODO Auto-generated method stub super.onResume(); getPrefStatus(); if (mNumberEntries == null) { mNumberEntries = new ArrayList<NumberEntry>(); } mITel = ITelephony.Stub.asInterface(ServiceManager .getService(Context.TELEPHONY_SERVICE)); startEntityQuery(); } private void getPrefStatus() { Log.i(TAG, "getPrefStatus()"); mPref = getSharedPreferences(SpeedDialManageActivity.PREF_NAME , Context.MODE_WORLD_READABLE | Context.MODE_WORLD_WRITEABLE); for (int i = SpeedDialManageActivity.SPEED_DIAL_MIN; i < SpeedDialManageActivity.SPEED_DIAL_MAX + 1; ++i) { mPrefNumState[i] = mPref.getString(String.valueOf(i), ""); mPrefMarkState[i] = mPref.getInt(String.valueOf(SpeedDialManageActivity.offset(i)), -1); } } /** * Adapter class intended for the display of a phone number and then the assigned key * of this phone number * @author mtk80909 * */ private final class AddSpeedDialAdapter extends BaseAdapter { ArrayList<NumberEntry> mNumberEntries; Context mContext; LayoutInflater mInflater; private int mNumberIndex; public AddSpeedDialAdapter(Context context, ArrayList<NumberEntry> numberEntries) { mContext = context; mNumberEntries = numberEntries; mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); mNumberIndex = 0; } public void updateWith(ArrayList<NumberEntry> numberEntries) { mNumberEntries = numberEntries; notifyDataSetChanged(); } public int getCount() { // TODO Auto-generated method stub return 2; } public Object getItem(int position) { // TODO Auto-generated method stub return null; } public long getItemId(int position) { // TODO Auto-generated method stub return 0; } public View getView(int position, View convertView, ViewGroup parent) { // TODO Auto-generated method stub Log.i(TAG, "getView(): position = " + position); if (mNumberIndex >= mNumberEntries.size()) { mNumberIndex = 0; return null; } Log.i(TAG, "mNumberIndex = " + mNumberIndex); NumberEntry numberEntry = mNumberEntries.get(mNumberIndex); View v; if (convertView != null) { v = convertView; } else { v = mInflater.inflate(R.layout.add_speed_dial_item, parent, false); } bindView(position, v, numberEntry); return v; } protected void bindView(int position, View v, NumberEntry numberEntry) { Log.i(TAG, "bindView(): position = " + position); TextView labelView = (TextView)v.findViewById(R.id.sd_label); TextView numberView = (TextView)v.findViewById(R.id.sd_number); View moreButton = v.findViewById(R.id.sd_more); if (position == 0) {// display the selected phone number labelView.setText(numberEntry.label); numberView.setText(numberEntry.number); moreButton.setVisibility( mNumberEntries.size() <= 1 ? View.GONE : View.VISIBLE ); } else if (position == 1) {// display the assigned key labelView.setText(AddSpeedDialActivity .this.getResources().getString(R.string.assigned_key)); Log.d(TAG, "bindView(), AddSpeedDialActivity.this.mIsFirstEnterAddSpeedDial= "+ AddSpeedDialActivity.this.mIsFirstEnterAddSpeedDial); if ( !AddSpeedDialActivity.this.mIsFirstEnterAddSpeedDial) { // update by showKeyDialog numberView.setText(AddSpeedDialActivity.this.getAssignedKeyExt((String)numberEntry.number)); } else { // first enter add speed dial numberView.setText(AddSpeedDialActivity.this.getAssignedKey((String)numberEntry.number)); } mTempPrefNumState = numberEntry.number.toString(); mTempPrefMarkState = mPhoneSimIndicator; if (mIsClickSpeedDialDialog) { mIsClickSpeedDialDialog = false; } } else { throw new RuntimeException("This is not possible"); } } public void setNumberIndex(int numberIndex) { mNumberIndex = numberIndex; } public int getNumberIndex() { return mNumberIndex; } } /** * Search the mPrefXXXState to find to which key number is assigned. * @param number is the input phone number. * @return */ private String getAssignedKey(String number) { for (int i = SpeedDialManageActivity.SPEED_DIAL_MIN; i <= SpeedDialManageActivity.SPEED_DIAL_MAX; ++i) { if (ContactsUtils.shouldCollapse(this, Phone.CONTENT_ITEM_TYPE, number, Phone.CONTENT_ITEM_TYPE, mPrefNumState[i])) { return String.valueOf(i); } } return getResources().getString(R.string.unassigned); } /** * Search the mPrefXXXState to find to which key number is assigned,if exist and want to * replace, then return new key, if not replace , return old key, if number not exist in mPrefXXXState. * return new key if assigned key or return unassigned if unassigned key * @param number is the input phone number. * @return */ private String getAssignedKeyExt(String number) { boolean hasNum = hasNumberByKey(mTempIndex); for (int i = SpeedDialManageActivity.SPEED_DIAL_MIN; i <= SpeedDialManageActivity.SPEED_DIAL_MAX; ++i) { if (ContactsUtils.shouldCollapse(this, Phone.CONTENT_ITEM_TYPE, number, Phone.CONTENT_ITEM_TYPE, mPrefNumState[i])) { //modify already assigned key to another key Log.d(TAG, "getAssignedKeyExt(), Find Same Number, mIsClickSpeedDialDialog= "+ mIsClickSpeedDialDialog); Log.d(TAG, "getAssignedKeyExt(), Find Same Number, mTempIndex= "+ mTempIndex); if (mIsClickSpeedDialDialog && (0 != mTempIndex) && (i != mTempIndex) && !hasNum) { mModified = ASSIGNED_KEY_MODIFIED; return String.valueOf(mTempIndex); } if (mIsClickSpeedDialDialog && (0 != mTempIndex) && hasNum) { Toast.makeText(AddSpeedDialActivity.this, getString(R.string.reselect_key), Toast.LENGTH_LONG).show(); } mModified = ASSIGNED_KEY_NOT_MODIFIED; return String.valueOf(i); } } if (0 != mTempIndex && !hasNum) { Log.d(TAG, "getAssignedKeyExt(), NOT Find Same Number and other number, mTempIndex= "+ mTempIndex); mModified = ASSIGNED_KEY_MODIFIED; return String.valueOf(mTempIndex); } if (mIsClickSpeedDialDialog && (0 != mTempIndex) && hasNum) { Toast.makeText(AddSpeedDialActivity.this, getString(R.string.reselect_key), Toast.LENGTH_LONG).show(); } mModified = ASSIGNED_KEY_NOT_MODIFIED; return getResources().getString(R.string.unassigned); } private boolean hasNumberByKey(int key) { Log.d(TAG, "hasNumberByKey(), mPrefNumState["+key+"]= " + mPrefNumState[key]); if (!TextUtils.isEmpty(mPrefNumState[key])){ Log.d(TAG, "hasNumberByKey(), find number by key!!!, key= "+ key); return true; } Log.d(TAG, "hasNumberByKey(), not find number by key!!! , key"+ key); return false; } /** * A simple collapsible class for the phone number entry. * @author mtk80909 * */ private final class NumberEntry implements Collapser.Collapsible<NumberEntry> { CharSequence label; CharSequence number; @Override public boolean collapseWith(NumberEntry t) { // TODO Auto-generated method stub if (!shouldCollapseWith(t)) { return false; } label = t.label; number = t.number; return true; } @Override public boolean shouldCollapseWith(NumberEntry t) { // TODO Auto-generated method stub if (t == null) return false; return ContactsUtils.shouldCollapse(AddSpeedDialActivity.this, Phone.CONTENT_ITEM_TYPE, number, Phone.CONTENT_ITEM_TYPE, t.number); } } /** * After query, initializes and shows the dialog of assigned keys. * The dialog is binded with mKeyDialogAdapter. */ private void showKeyDialog() { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle(getResources().getString(R.string.speed_dial_view)); DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { // TODO Auto-generated method stub which += 2; //mPrefNumState[which] = (String)mNumberEntries.get(mAdapter.mNumberIndex).number; //mPrefMarkState[which] = mPhoneSimIndicator; mTempIndex = which; Log.d(TAG, "showKeyDialog(), mTempIndex= "+mTempIndex); //mTempPrefNumState = (String)mNumberEntries.get(mAdapter.mNumberIndex).number; //mTempPrefMarkState = mPhoneSimIndicator; mIsFirstEnterAddSpeedDial = false; mIsClickSpeedDialDialog = true; mAdapter.notifyDataSetChanged(); } }; builder.setAdapter(mKeyDialogAdapter, listener); mKeyDialog = builder.create(); mKeyDialog.show(); } }
UTF-8
Java
33,534
java
AddSpeedDialActivity.java
Java
[ { "context": "atcherEx;\n\n\n/**\n * AddSpeedDialActivity\n * @author mtk80909\n * UI to add the current contact's phone number t", "end": 2085, "score": 0.9995091557502747, "start": 2077, "tag": "USERNAME", "value": "mtk80909" }, { "context": " assigned key\n\t * of this phone numbe...
null
[]
package com.android.contacts; import java.util.ArrayList; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.BaseAdapter; import android.widget.ListView; import android.widget.SimpleCursorAdapter; import android.widget.TextView; import android.widget.Collapser.Collapsible; import android.app.Activity; import android.app.AlertDialog; import android.app.AlertDialog.Builder; import android.content.ContentResolver; import android.content.ContentUris; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.content.res.Resources; import android.database.ContentObserver; import android.database.Cursor; import android.database.MatrixCursor; import android.graphics.BitmapFactory; import com.android.contacts.util.NotifyingAsyncQueryHandler; import com.android.internal.widget.ContactHeaderWidget; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.RemoteException; import android.os.ServiceManager; import android.provider.ContactsContract.CommonDataKinds; import android.provider.ContactsContract.Contacts; import android.provider.ContactsContract.PhoneLookup; import android.provider.ContactsContract.RawContacts; import android.provider.ContactsContract.RawContactsEntity; import android.provider.ContactsContract.CommonDataKinds.Phone; import android.telephony.PhoneNumberUtils; import android.telephony.TelephonyManager; import android.text.TextUtils; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Toast; import com.android.contacts.SpeedDialManageActivity; import android.provider.Telephony.SIMInfo;//gemini enhancement import com.android.internal.telephony.ITelephony; import com.mediatek.featureoption.FeatureOption; import com.mediatek.telephony.PhoneNumberFormatUtilEx; import com.mediatek.telephony.PhoneNumberFormattingTextWatcherEx; /** * AddSpeedDialActivity * @author mtk80909 * UI to add the current contact's phone number to certain keys as speed dials. */ public class AddSpeedDialActivity extends Activity implements DialogInterface.OnClickListener, AdapterView.OnItemClickListener, NotifyingAsyncQueryHandler.AsyncQueryListener, View.OnClickListener { private static final String TAG = "AddSpeedDialActivity"; /** * Query token for contact's phone numbers */ private static final int NUMBER_QUERY_TOKEN = 47; /** * Query token for confirming that phone numbers in speed dial preferences * are in Contacts database. */ private static final int SPEED_DIAL_QUERY_TOKEN = 48; private SharedPreferences mPref; private ListView mListView; private ContactHeaderWidget mHeaderWidget; private Cursor mContactCursor; private Cursor mPhoneCursor; private ITelephony mITel; private ContentObserver mObserver = new ContentObserver(new Handler()) { @Override public boolean deliverSelfNotifications() { return true; } @Override public void onChange(boolean selfChange) { if (mContactCursor != null && !mContactCursor.isClosed()) { startEntityQuery(); } } }; private NotifyingAsyncQueryHandler mHandler; private Uri mLookupUri; private ContentResolver mResolver; private static final int ASSIGNED_KEY_NOT_MODIFIED = 0; private static final int ASSIGNED_KEY_MODIFIED = 2; private int mTempIndex = 0; // used for save index of onclick of dialog //private int mTempKey = 0; // used for save assigned key which need to save private int mTempPrefMarkState = -1; private String mTempPrefNumState = ""; private boolean mIsFirstEnterAddSpeedDial = true; private boolean mIsClickSpeedDialDialog = false; private int mModified = ASSIGNED_KEY_NOT_MODIFIED; /** * Current values in the SharedPreferences -- Phone numbers. */ private String[] mPrefNumState = { "", // 0 "", // 1 "", // 2 "", // 3 "", // 4 "", // 5 "", // 6 "", // 7 "", // 8 "", // 9 }; /** * Current values in the SharedPreferences -- Phone/SIM indicators. * -1 -- Phone * 0 -- Single SIM * 1 -- SIM1 * 2 -- SIM2 */ private int[] mPrefMarkState = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }; /** * Projection and indices used to display (used by the MatrixCursor). */ static final String[] BIND_PROJECTION = { PhoneLookup._ID, // 0 PhoneLookup.DISPLAY_NAME, // 1 PhoneLookup.TYPE, // 2 PhoneLookup.NUMBER, // 3 }; static final int BIND_ID_INDEX = 0; static final int BIND_DISPLAY_NAME_INDEX = 1; static final int BIND_LABEL_INDEX = 2; static final int BIND_NUMBER_INDEX = 3; /* * ID's of views to bind. */ private static final int[] ADAPTER_TO = { R.id.sd_index, R.id.sd_name, R.id.sd_label, R.id.sd_number, }; private AddSpeedDialAdapter mAdapter; private ArrayList<NumberEntry> mNumberEntries; private int mPhoneSimIndicator; private AlertDialog mNumberDialog; private AlertDialog mKeyDialog; private String mDisplayName; private int mQueryTimes; private MatrixCursor mMatrixCursor; private SimpleCursorAdapter mKeyDialogAdapter; /** * Implementation follows ViewContactActivity.startEntityQuery(). */ private synchronized void startEntityQuery() { closeCursor(); mContactCursor = ViewContactActivity.setupContactCursor(mResolver, mLookupUri); if (mContactCursor == null) { mLookupUri = Contacts.getLookupUri(getContentResolver(), mLookupUri); mContactCursor = ViewContactActivity.setupContactCursor(mResolver, mLookupUri); } if (mContactCursor == null) { finish(); return; } mContactCursor.registerContentObserver(mObserver); final long contactId = ContentUris.parseId(mLookupUri); Uri uri = Contacts.lookupContact(mResolver, mLookupUri); mHeaderWidget.bindFromContactLookupUri(mLookupUri); if(uri == null)return ; Cursor tmpCursor = mResolver.query(uri, new String[] { RawContacts.INDICATE_PHONE_SIM, RawContacts.DISPLAY_NAME_PRIMARY }, null, null, null); if(tmpCursor != null){ tmpCursor.moveToFirst(); mPhoneSimIndicator = tmpCursor.getInt(0); mDisplayName = tmpCursor.getString(1); tmpCursor.close(); } // query the contact entity in the background // TODO: reduce the number of columns returned mHandler.startQuery(NUMBER_QUERY_TOKEN, null, RawContactsEntity.CONTENT_URI, null, RawContacts.CONTACT_ID + "=? AND " + Phone.MIMETYPE + "=?", new String[] {String.valueOf(contactId), Phone.CONTENT_ITEM_TYPE}, null); } /** * If the current contact is a SIM contact, * set SIM pictures as their photos */ private void setSimContactPhoto() { final ITelephony iTel = ITelephony.Stub.asInterface(ServiceManager .getService(Context.TELEPHONY_SERVICE)); if (null == iTel) { Log.d(TAG, "setSimContactPhoto(), call ITelephony failed!! "); return; } Resources res = getResources(); /*switch (mPhoneSimIndicator) { case RawContacts.INDICATE_SIM : mHeaderWidget.setPhoto(BitmapFactory.decodeResource( res, R.drawable.contact_icon_sim)); break; case RawContacts.INDICATE_SIM1 : mHeaderWidget.setPhoto(BitmapFactory.decodeResource( res, R.drawable.contact_icon_sim1)); break; case RawContacts.INDICATE_SIM2 : mHeaderWidget.setPhoto(BitmapFactory.decodeResource( res, R.drawable.contact_icon_sim2)); break; default: break; }*/ if (mPhoneSimIndicator >= RawContacts.INDICATE_SIM) { int slotId = SIMInfo.getSlotById(AddSpeedDialActivity.this, mPhoneSimIndicator); Log.d(TAG, "setSimContactPhoto(), slotId= "+ slotId +" ,mPhoneSimIndicator= "+ mPhoneSimIndicator); if (slotId >= 0) { try { if (com.mediatek.featureoption.FeatureOption.MTK_GEMINI_SUPPORT) { if (iTel.getIccCardTypeGemini(slotId).equals("USIM")) { if (null != mHeaderWidget) mHeaderWidget.setPhoto(BitmapFactory.decodeResource( res, R.drawable.contact_icon_usim)); } else { if (null != mHeaderWidget) mHeaderWidget.setPhoto(BitmapFactory.decodeResource( res, R.drawable.contact_icon_sim)); } } else { if (iTel.getIccCardType().equals("USIM")) { if (null != mHeaderWidget) mHeaderWidget.setPhoto(BitmapFactory.decodeResource( res, R.drawable.contact_icon_usim)); } else { if (null != mHeaderWidget) mHeaderWidget.setPhoto(BitmapFactory.decodeResource( res, R.drawable.contact_icon_sim)); } } } catch (Exception ex) { ex.printStackTrace(); } } } } private void closeCursor() { if (mContactCursor != null) { mContactCursor.unregisterContentObserver(mObserver); mContactCursor.close(); mContactCursor = null; } } public void onClick(DialogInterface dialog, int which) { // TODO Auto-generated method stub } public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // TODO Auto-generated method stub if (position == 0) { // phone number view showPhoneNumbers(); } else if (position == 1) { // assigned key view showAssignedKeys(); } else { throw new RuntimeException("This is not possible"); } } /** * Show the dialog of all phone numbers of the current contact. */ private void showPhoneNumbers() { if (mNumberEntries == null || mNumberEntries.isEmpty()) { Log.e(TAG, "Number entries empty!!"); return; } if (mNumberEntries.size() == 1) { Log.w(TAG, "Only one phone number here. We don't need a disambig dialog."); return; } // now, mNumberEntries must have at least 2 items. AlertDialog.Builder builder = new AlertDialog.Builder(this); ArrayAdapter<NumberEntry> adapter = new ArrayAdapter<NumberEntry>(this, R.layout.phone_disambig_item, android.R.id.text2, mNumberEntries) { @Override public View getView(int position, View convertView, ViewGroup parent) { View view = super.getView(position, convertView, parent); NumberEntry item = getItem(position); TextView typeView = (TextView)view.findViewById(android.R.id.text1); TextView numberView = (TextView)view.findViewById(android.R.id.text2); typeView.setText(item.label); numberView.setText(item.number); return view; } }; DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { // TODO Auto-generated method stub if (which < 0 || which >= mNumberEntries.size()) { dialog.dismiss(); return; } mAdapter.setNumberIndex(which); mAdapter.notifyDataSetChanged(); } }; mNumberDialog = builder.setTitle(mDisplayName).setAdapter(adapter, listener).create(); mNumberDialog.show(); } /** * show the dialog */ private void showAssignedKeys() { initMatrixCursor(); goOnQuery(); } /** * Searches the preferences, populates empty rows of the MatrixCursor, and starts real query for non-empty rows. */ private void goOnQuery() { int end; for (end = mQueryTimes; end < SpeedDialManageActivity.SPEED_DIAL_MAX + 1 && TextUtils.isEmpty(mPrefNumState[end]); ++end) { // empty loop body } SpeedDialManageActivity.populateMatrixCursorEmpty(this, mMatrixCursor, mQueryTimes - 1, end - 1); Log.i(TAG, "mQueryTimes = " + mQueryTimes + ", end = " + end); if (end > SpeedDialManageActivity.SPEED_DIAL_MAX) { Log.i(TAG, "queryComplete in goOnQuery()"); mKeyDialogAdapter.changeCursor(mMatrixCursor); showKeyDialog(); } else { mQueryTimes = end; Log.i(TAG, "startQuery at mQueryTimes = " + mQueryTimes); Log.i(TAG, "number = " + mPrefNumState[mQueryTimes]); Uri uri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(mPrefNumState[mQueryTimes])); Log.i(TAG, "uri = " + uri); mHandler.startQuery(SPEED_DIAL_QUERY_TOKEN, null, uri, SpeedDialManageActivity.QUERY_PROJECTION, null, null, null); //Cursor testCursor = getContentResolver().query(uri, QUERY_PROJECTION, null, null, null); } } private void initMatrixCursor() { if (mMatrixCursor != null) mMatrixCursor.close(); final int listCapacity = SpeedDialManageActivity.SPEED_DIAL_MAX - SpeedDialManageActivity.SPEED_DIAL_MIN + 1; mMatrixCursor = new MatrixCursor(SpeedDialManageActivity.BIND_PROJECTION, listCapacity); mQueryTimes = SpeedDialManageActivity.SPEED_DIAL_MIN; } public void onQueryComplete(int token, Object cookie, Cursor cursor) { // TODO Auto-generated method stub if (token == NUMBER_QUERY_TOKEN) { Log.i(TAG, "query complete"); Log.i(TAG, "cursor = " + cursor); Log.i(TAG, "cursor.getCount() = " + ((cursor == null) ? 0 : cursor.getCount())); String[] columnNames = cursor.getColumnNames(); String columnNamesToString = "["; for (int i = 0; i < columnNames.length; ++i) { columnNamesToString += columnNames[i] + ", "; } Log.i(TAG, columnNamesToString + "]"); setSimContactPhoto(); bindData(cursor); if (mPhoneCursor != null && !mPhoneCursor.isClosed()) { mPhoneCursor.close(); } mPhoneCursor = cursor; } else if (token == SPEED_DIAL_QUERY_TOKEN) { if (cursor != null && cursor.getCount() > 0) { populateMatrixCursorRow(mQueryTimes - 1, cursor); } else { SpeedDialManageActivity.populateMatrixCursorEmpty(this, mMatrixCursor, mQueryTimes - 1, mQueryTimes); clearPrefStateIfNecessary(mQueryTimes); } if (cursor != null) cursor.close(); ++mQueryTimes; Log.i(TAG, "mQueryTimes = " + mQueryTimes); if (mQueryTimes <= SpeedDialManageActivity.SPEED_DIAL_MAX) { goOnQuery(); } else { Log.i(TAG, "query stop in onQueryComplete"); mKeyDialogAdapter.changeCursor(mMatrixCursor); showKeyDialog(); } } else { Log.w(TAG, "onQueryComplete(): Should not reach here."); } } /** * Populates the indicated row of the MatrixCursor with the data in cursor. * @param row is the indicated row index of the MatrixCursor to populate * @param cursor is the data source */ private void populateMatrixCursorRow(int row, Cursor cursor) { cursor.moveToFirst(); String name = cursor.getString(SpeedDialManageActivity.QUERY_DISPLAY_NAME_INDEX); int type = cursor.getInt(SpeedDialManageActivity.QUERY_LABEL_INDEX);; String label = ""; if (type == 0) { label = cursor.getString(SpeedDialManageActivity.QUERY_CUSTOM_LABEL_INDEX); } else { label = (String)CommonDataKinds.Phone. getTypeLabel(getResources(), type, null); } String number = cursor.getString(SpeedDialManageActivity.QUERY_NUMBER_INDEX); long photoId = cursor.getLong(SpeedDialManageActivity.QUERY_PHOTO_ID_INDEX); int simId = -1; if (!cursor.isNull(SpeedDialManageActivity.QUERY_INDICATE_PHONE_SIM_INDEX)) { simId = cursor.getInt(SpeedDialManageActivity.QUERY_INDICATE_PHONE_SIM_INDEX); } Log.i(TAG, "name = " + name + ", label = " + label + ", number = " + number); if (TextUtils.isEmpty(number)) { SpeedDialManageActivity.populateMatrixCursorEmpty(this, mMatrixCursor, row, row + 1); mPrefNumState[row] = mPref.getString(String.valueOf(row), ""); mPrefMarkState[row] = mPref.getInt(String.valueOf(SpeedDialManageActivity.offset(row)), -1); return; } mMatrixCursor.addRow(new String[]{String.valueOf(row + 1), name, label, PhoneNumberFormatUtilEx.formatNumber(number) , String.valueOf(photoId), String.valueOf(simId)}); } /** * If the preference state stores a number * and the SIM card corresponding to its SIM indicator is not ready, * the cursor is populated with the empty value, * but the preference is not deleted. * @param queryTimes */ void clearPrefStateIfNecessary(int queryTimes) { int simId = mPrefMarkState[queryTimes]; // SIM state is ready if (simId == -1 || isSimReady(simId)) { mPrefMarkState[queryTimes] = -1; mPrefNumState[queryTimes] = ""; } } /** * Gets the present SIM state * @param simId is the SIM ID. Legal inputs include {0, 1, 2}; * @return true if SIM is ready. */ private boolean isSimReady(final int simId) { if (null == mITel) return false; Log.d(TAG, "isSimReady(), simId= "+simId); try { if (FeatureOption.MTK_GEMINI_SUPPORT) { int slotId = SIMInfo.getSlotById(AddSpeedDialActivity.this, simId); Log.d(TAG, "isSimReady(), slotId= "+slotId); if (-1 == slotId) { return true; } if (mITel.isRadioOnGemini(slotId)) { return !mITel.hasIccCardGemini(slotId) || (mITel.isRadioOnGemini(slotId) && !mITel.isFDNEnabledGemini(slotId) && TelephonyManager.SIM_STATE_READY == TelephonyManager .getDefault().getSimStateGemini(slotId) && !ContactsUtils.isServiceRunning[slotId]); } else { return !mITel.isSimInsert(slotId) || (mITel.isRadioOnGemini(slotId) && !mITel.isFDNEnabledGemini(slotId) && TelephonyManager.SIM_STATE_READY == TelephonyManager .getDefault().getSimStateGemini(slotId) && !ContactsUtils.isServiceRunning[slotId]); } } else { if(mITel.isRadioOn()) { return !mITel.hasIccCard() || (mITel.isRadioOn() && !mITel.isFDNEnabled() && TelephonyManager.SIM_STATE_READY == TelephonyManager .getDefault().getSimState() && !ContactsUtils.isServiceRunning[0]); } else { return !mITel.isSimInsert(0) || (mITel.isRadioOn() && !mITel.isFDNEnabled() && TelephonyManager.SIM_STATE_READY == TelephonyManager .getDefault().getSimState() && !ContactsUtils.isServiceRunning[0]); } } } catch (RemoteException e) { Log.w(TAG, "RemoteException!"); return false; } } /** * Bind the cursor to mAdapter so that the ListView will be updated * @param cursor */ private void bindData(Cursor cursor) { mNumberEntries.clear(); if (cursor == null || cursor.getCount() == 0) { return; } for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) { NumberEntry numberEntry = new NumberEntry(); int type = cursor.getInt(cursor.getColumnIndex(RawContactsEntity.DATA2)); if (type == 0) { numberEntry.label = cursor.getString(cursor.getColumnIndex(RawContactsEntity.DATA3)); } else { numberEntry.label = (String)CommonDataKinds.Phone.getTypeLabel(getResources(), cursor.getInt(cursor.getColumnIndex(RawContactsEntity.DATA2)), null); } numberEntry.number = cursor.getString(cursor.getColumnIndex(RawContactsEntity.DATA1)); mNumberEntries.add(numberEntry); } Collapser.collapseList(mNumberEntries); Log.i(TAG, "mNumberEntries in bindData: " + mNumberEntries); if (mAdapter == null) { mAdapter = new AddSpeedDialAdapter(this, mNumberEntries); mListView.setAdapter(mAdapter); } else { mAdapter.updateWith(mNumberEntries); } } /** * Responses 'ADD' and 'CANCEL' button */ public void onClick(View v) { // TODO Auto-generated method stub final int viewId = v.getId(); switch (viewId) { case R.id.add_button: saveChanges(); Log.i(TAG, "changes saved through 'add' button"); finish(); break; case R.id.cancel_button: Log.i(TAG, "canceled"); finish(); break; default: break; } } @Override public void onBackPressed() { // TODO Auto-generated method stub saveChanges(); Log.i(TAG, "changes saved through 'BACK' button"); super.onBackPressed(); } private void saveChanges() { Log.d(TAG, " saveChanges(), mModified= "+mModified); if (ASSIGNED_KEY_MODIFIED == mModified) { // user assign one key int index; for (int i = SpeedDialManageActivity.SPEED_DIAL_MIN; i < SpeedDialManageActivity.SPEED_DIAL_MAX + 1; ++i) { index = findKeyByNumber(mTempPrefNumState); Log.d(TAG, "findKeyByNumber is " + index); if (SpeedDialManageActivity.SPEED_DIAL_MIN <= index) { mPrefNumState[index] = ""; mPrefMarkState[index] = -1; } } Log.d(TAG, " saveChanges(), mTempPrefNumState="+mTempPrefNumState ); Log.d(TAG, " saveChanges(), mTempIndex="+mTempIndex ); mPrefNumState[mTempIndex] = mTempPrefNumState; mPrefMarkState[mTempIndex] = mTempPrefMarkState; } updatePreferences(); } private int findKeyByNumber(String number) { if (TextUtils.isEmpty(number)) { return -1; } for (int i = SpeedDialManageActivity.SPEED_DIAL_MIN; i < SpeedDialManageActivity.SPEED_DIAL_MAX + 1; ++i) { if (ContactsUtils.shouldCollapse(AddSpeedDialActivity.this, Phone.CONTENT_ITEM_TYPE, number, Phone.CONTENT_ITEM_TYPE, mPrefNumState[i])){ return i; } } return -1; } private void updatePreferences() { SharedPreferences.Editor editor = mPref.edit(); for (int i = SpeedDialManageActivity.SPEED_DIAL_MIN; i < SpeedDialManageActivity.SPEED_DIAL_MAX + 1; ++i) { editor.putString(String.valueOf(i), mPrefNumState[i]); editor.putInt(String.valueOf(SpeedDialManageActivity.offset(i)), mPrefMarkState[i]); } editor.apply(); } @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.add_speed_dial_layout); findViewById(R.id.add_button).setOnClickListener(this); findViewById(R.id.cancel_button).setOnClickListener(this); resolveIntent(); setHeaderWidget(); setupQueryHandler(); setupListView(); mResolver = getContentResolver(); mNumberEntries = new ArrayList<NumberEntry>(); Log.i(TAG, "mNumberEntries in onCreate(): " + mNumberEntries); mKeyDialogAdapter = new SimpleCursorAdapter(this, R.layout.speed_dial_simple_list_item, null, BIND_PROJECTION, ADAPTER_TO); mKeyDialogAdapter.setViewBinder(new SimpleCursorAdapter.ViewBinder() { // TODO use other adapter types. /** * what is called in bindView(). */ public boolean setViewValue(View view, Cursor cursor, int columnIndex) { // TODO Auto-generated method stub int viewId = view.getId(); boolean isNumberEmpty = TextUtils.isEmpty(cursor.getString(BIND_NUMBER_INDEX)); view.setEnabled(!isNumberEmpty); if (viewId == R.id.sd_index) { ((TextView)view).setText(cursor.getString(columnIndex) + ": "); } else if (viewId == R.id.sd_name) { if (isNumberEmpty) { ((TextView)view).setText(AddSpeedDialActivity. this.getResources().getString(R.string.available)); } else { ((TextView)view).setText(cursor.getString(columnIndex)); } } else if (viewId == R.id.sd_label) { view.setVisibility(isNumberEmpty ? View.GONE : View.VISIBLE); ((TextView)view).setText("(" + cursor.getString(columnIndex) + ")"); } else if (viewId == R.id.sd_number) { view.setVisibility(isNumberEmpty ? View.GONE : View.VISIBLE); ((TextView)view).setText(cursor.getString(columnIndex)); } return true; } }); } /** * Ensures that the URI obtained from the intent is not null. */ private void resolveIntent() { final Intent intent = getIntent(); mLookupUri = intent.getData(); if (mLookupUri == null) { finish(); } } private void setHeaderWidget() { mHeaderWidget = (ContactHeaderWidget) findViewById(R.id.contact_header_widget); mHeaderWidget.showStar(false); mHeaderWidget.setSelectedContactsAppTabIndex(StickyTabs.getTab(getIntent())); } private void setupListView() { mListView = (ListView) findViewById(R.id.contact_data); mListView.setOnItemClickListener(this); } private void setupQueryHandler() { mHandler = new NotifyingAsyncQueryHandler(this, this); } @Override protected void onDestroy() { // TODO Auto-generated method stub super.onDestroy(); closeCursor(); } @Override protected void onPause() { // TODO Auto-generated method stub super.onPause(); closeCursor(); } @Override protected void onResume() { // TODO Auto-generated method stub super.onResume(); getPrefStatus(); if (mNumberEntries == null) { mNumberEntries = new ArrayList<NumberEntry>(); } mITel = ITelephony.Stub.asInterface(ServiceManager .getService(Context.TELEPHONY_SERVICE)); startEntityQuery(); } private void getPrefStatus() { Log.i(TAG, "getPrefStatus()"); mPref = getSharedPreferences(SpeedDialManageActivity.PREF_NAME , Context.MODE_WORLD_READABLE | Context.MODE_WORLD_WRITEABLE); for (int i = SpeedDialManageActivity.SPEED_DIAL_MIN; i < SpeedDialManageActivity.SPEED_DIAL_MAX + 1; ++i) { mPrefNumState[i] = mPref.getString(String.valueOf(i), ""); mPrefMarkState[i] = mPref.getInt(String.valueOf(SpeedDialManageActivity.offset(i)), -1); } } /** * Adapter class intended for the display of a phone number and then the assigned key * of this phone number * @author mtk80909 * */ private final class AddSpeedDialAdapter extends BaseAdapter { ArrayList<NumberEntry> mNumberEntries; Context mContext; LayoutInflater mInflater; private int mNumberIndex; public AddSpeedDialAdapter(Context context, ArrayList<NumberEntry> numberEntries) { mContext = context; mNumberEntries = numberEntries; mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); mNumberIndex = 0; } public void updateWith(ArrayList<NumberEntry> numberEntries) { mNumberEntries = numberEntries; notifyDataSetChanged(); } public int getCount() { // TODO Auto-generated method stub return 2; } public Object getItem(int position) { // TODO Auto-generated method stub return null; } public long getItemId(int position) { // TODO Auto-generated method stub return 0; } public View getView(int position, View convertView, ViewGroup parent) { // TODO Auto-generated method stub Log.i(TAG, "getView(): position = " + position); if (mNumberIndex >= mNumberEntries.size()) { mNumberIndex = 0; return null; } Log.i(TAG, "mNumberIndex = " + mNumberIndex); NumberEntry numberEntry = mNumberEntries.get(mNumberIndex); View v; if (convertView != null) { v = convertView; } else { v = mInflater.inflate(R.layout.add_speed_dial_item, parent, false); } bindView(position, v, numberEntry); return v; } protected void bindView(int position, View v, NumberEntry numberEntry) { Log.i(TAG, "bindView(): position = " + position); TextView labelView = (TextView)v.findViewById(R.id.sd_label); TextView numberView = (TextView)v.findViewById(R.id.sd_number); View moreButton = v.findViewById(R.id.sd_more); if (position == 0) {// display the selected phone number labelView.setText(numberEntry.label); numberView.setText(numberEntry.number); moreButton.setVisibility( mNumberEntries.size() <= 1 ? View.GONE : View.VISIBLE ); } else if (position == 1) {// display the assigned key labelView.setText(AddSpeedDialActivity .this.getResources().getString(R.string.assigned_key)); Log.d(TAG, "bindView(), AddSpeedDialActivity.this.mIsFirstEnterAddSpeedDial= "+ AddSpeedDialActivity.this.mIsFirstEnterAddSpeedDial); if ( !AddSpeedDialActivity.this.mIsFirstEnterAddSpeedDial) { // update by showKeyDialog numberView.setText(AddSpeedDialActivity.this.getAssignedKeyExt((String)numberEntry.number)); } else { // first enter add speed dial numberView.setText(AddSpeedDialActivity.this.getAssignedKey((String)numberEntry.number)); } mTempPrefNumState = numberEntry.number.toString(); mTempPrefMarkState = mPhoneSimIndicator; if (mIsClickSpeedDialDialog) { mIsClickSpeedDialDialog = false; } } else { throw new RuntimeException("This is not possible"); } } public void setNumberIndex(int numberIndex) { mNumberIndex = numberIndex; } public int getNumberIndex() { return mNumberIndex; } } /** * Search the mPrefXXXState to find to which key number is assigned. * @param number is the input phone number. * @return */ private String getAssignedKey(String number) { for (int i = SpeedDialManageActivity.SPEED_DIAL_MIN; i <= SpeedDialManageActivity.SPEED_DIAL_MAX; ++i) { if (ContactsUtils.shouldCollapse(this, Phone.CONTENT_ITEM_TYPE, number, Phone.CONTENT_ITEM_TYPE, mPrefNumState[i])) { return String.valueOf(i); } } return getResources().getString(R.string.unassigned); } /** * Search the mPrefXXXState to find to which key number is assigned,if exist and want to * replace, then return new key, if not replace , return old key, if number not exist in mPrefXXXState. * return new key if assigned key or return unassigned if unassigned key * @param number is the input phone number. * @return */ private String getAssignedKeyExt(String number) { boolean hasNum = hasNumberByKey(mTempIndex); for (int i = SpeedDialManageActivity.SPEED_DIAL_MIN; i <= SpeedDialManageActivity.SPEED_DIAL_MAX; ++i) { if (ContactsUtils.shouldCollapse(this, Phone.CONTENT_ITEM_TYPE, number, Phone.CONTENT_ITEM_TYPE, mPrefNumState[i])) { //modify already assigned key to another key Log.d(TAG, "getAssignedKeyExt(), Find Same Number, mIsClickSpeedDialDialog= "+ mIsClickSpeedDialDialog); Log.d(TAG, "getAssignedKeyExt(), Find Same Number, mTempIndex= "+ mTempIndex); if (mIsClickSpeedDialDialog && (0 != mTempIndex) && (i != mTempIndex) && !hasNum) { mModified = ASSIGNED_KEY_MODIFIED; return String.valueOf(mTempIndex); } if (mIsClickSpeedDialDialog && (0 != mTempIndex) && hasNum) { Toast.makeText(AddSpeedDialActivity.this, getString(R.string.reselect_key), Toast.LENGTH_LONG).show(); } mModified = ASSIGNED_KEY_NOT_MODIFIED; return String.valueOf(i); } } if (0 != mTempIndex && !hasNum) { Log.d(TAG, "getAssignedKeyExt(), NOT Find Same Number and other number, mTempIndex= "+ mTempIndex); mModified = ASSIGNED_KEY_MODIFIED; return String.valueOf(mTempIndex); } if (mIsClickSpeedDialDialog && (0 != mTempIndex) && hasNum) { Toast.makeText(AddSpeedDialActivity.this, getString(R.string.reselect_key), Toast.LENGTH_LONG).show(); } mModified = ASSIGNED_KEY_NOT_MODIFIED; return getResources().getString(R.string.unassigned); } private boolean hasNumberByKey(int key) { Log.d(TAG, "hasNumberByKey(), mPrefNumState["+key+"]= " + mPrefNumState[key]); if (!TextUtils.isEmpty(mPrefNumState[key])){ Log.d(TAG, "hasNumberByKey(), find number by key!!!, key= "+ key); return true; } Log.d(TAG, "hasNumberByKey(), not find number by key!!! , key"+ key); return false; } /** * A simple collapsible class for the phone number entry. * @author mtk80909 * */ private final class NumberEntry implements Collapser.Collapsible<NumberEntry> { CharSequence label; CharSequence number; @Override public boolean collapseWith(NumberEntry t) { // TODO Auto-generated method stub if (!shouldCollapseWith(t)) { return false; } label = t.label; number = t.number; return true; } @Override public boolean shouldCollapseWith(NumberEntry t) { // TODO Auto-generated method stub if (t == null) return false; return ContactsUtils.shouldCollapse(AddSpeedDialActivity.this, Phone.CONTENT_ITEM_TYPE, number, Phone.CONTENT_ITEM_TYPE, t.number); } } /** * After query, initializes and shows the dialog of assigned keys. * The dialog is binded with mKeyDialogAdapter. */ private void showKeyDialog() { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle(getResources().getString(R.string.speed_dial_view)); DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { // TODO Auto-generated method stub which += 2; //mPrefNumState[which] = (String)mNumberEntries.get(mAdapter.mNumberIndex).number; //mPrefMarkState[which] = mPhoneSimIndicator; mTempIndex = which; Log.d(TAG, "showKeyDialog(), mTempIndex= "+mTempIndex); //mTempPrefNumState = (String)mNumberEntries.get(mAdapter.mNumberIndex).number; //mTempPrefMarkState = mPhoneSimIndicator; mIsFirstEnterAddSpeedDial = false; mIsClickSpeedDialDialog = true; mAdapter.notifyDataSetChanged(); } }; builder.setAdapter(mKeyDialogAdapter, listener); mKeyDialog = builder.create(); mKeyDialog.show(); } }
33,534
0.678535
0.674897
989
32.906979
27.214153
149
false
false
0
0
0
0
0
0
2.494439
false
false
2
b5299c9ec42085fb00818a8a266fe3ea66f7ad85
22,840,636,128,214
ae59264be2048047aa5597fb85120563616cb1ae
/src/main/java/com/kishore/client/rsocket/mappings/RequestResponseMapping.java
c5bb493480132a90b46025dce785efb0c364b177
[]
no_license
venkataramkishore/rsocket-client
https://github.com/venkataramkishore/rsocket-client
b8c6f9569a0d15bfb416f414a24e5c0df700a384
1a1b4b2ffea36d9ee37a9b794c6eee1ab3a61028
refs/heads/master
2023-05-30T18:04:50.138000
2021-06-04T19:18:20
2021-06-04T19:18:20
373,588,301
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.kishore.client.rsocket.mappings; import java.time.Duration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.messaging.handler.annotation.MessageMapping; import reactor.core.publisher.Flux; public class RequestResponseMapping { private static final Logger logger = LoggerFactory.getLogger(RequestResponseMapping.class); @MessageMapping("client-status") public Flux<String> statusUpdate(String status) { logger.info("Inside status Update client with status {}", status); return Flux.interval(Duration.ofSeconds(5)) .map(index -> String.valueOf(Runtime.getRuntime().freeMemory())); } }
UTF-8
Java
651
java
RequestResponseMapping.java
Java
[]
null
[]
package com.kishore.client.rsocket.mappings; import java.time.Duration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.messaging.handler.annotation.MessageMapping; import reactor.core.publisher.Flux; public class RequestResponseMapping { private static final Logger logger = LoggerFactory.getLogger(RequestResponseMapping.class); @MessageMapping("client-status") public Flux<String> statusUpdate(String status) { logger.info("Inside status Update client with status {}", status); return Flux.interval(Duration.ofSeconds(5)) .map(index -> String.valueOf(Runtime.getRuntime().freeMemory())); } }
651
0.788018
0.78341
22
28.59091
28.017298
92
false
false
0
0
0
0
0
0
1.045455
false
false
2
af77405becc739035d83d95b9b249275df545f40
17,497,696,785,475
a8e8d96ac8873c410eded13dae1f37cf3e42fe5b
/src/object/structure/Base.java
f653e233003d4f7b93f781257e564cdd84678948
[]
no_license
5731100221-WJ/LastWish
https://github.com/5731100221-WJ/LastWish
08ce2312455292599f1178487d35cd84b41d911a
0d365b54d1d68df3dab0ef99bef17b11d79dc395
refs/heads/master
2021-01-15T17:35:51.439000
2015-12-14T05:58:22
2015-12-14T05:58:22
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package object.structure; import java.util.ArrayList; import render.rendable.Rendable; import render.rendable.StaticImageRendable; public abstract class Base implements IUpgradable, IObjectWithSingleImage { protected StaticImageRendable image; protected int woodRequire; protected int farmRequire; protected int ironRequire; protected int currentLevel; protected int maxLevel; public Base() { woodRequire = farmRequire = ironRequire = 0; currentLevel = maxLevel = 1; } @Override public StaticImageRendable getImage() { return image; } @Override public int getCurrentLevel() { return currentLevel; } @Override public int getWoodRequire() { return woodRequire; } @Override public int getIronRequire() { return ironRequire; } @Override public int getFarmRequire() { return farmRequire; } @Override public boolean isMaxLevel() { return currentLevel == maxLevel; } }
UTF-8
Java
921
java
Base.java
Java
[]
null
[]
package object.structure; import java.util.ArrayList; import render.rendable.Rendable; import render.rendable.StaticImageRendable; public abstract class Base implements IUpgradable, IObjectWithSingleImage { protected StaticImageRendable image; protected int woodRequire; protected int farmRequire; protected int ironRequire; protected int currentLevel; protected int maxLevel; public Base() { woodRequire = farmRequire = ironRequire = 0; currentLevel = maxLevel = 1; } @Override public StaticImageRendable getImage() { return image; } @Override public int getCurrentLevel() { return currentLevel; } @Override public int getWoodRequire() { return woodRequire; } @Override public int getIronRequire() { return ironRequire; } @Override public int getFarmRequire() { return farmRequire; } @Override public boolean isMaxLevel() { return currentLevel == maxLevel; } }
921
0.751357
0.749186
50
17.42
16.032579
75
false
false
0
0
0
0
0
0
1.36
false
false
10
3b19b09dd11124930a42a2ad2d67c375d227685d
17,497,696,783,341
10a804bd40af218deb7dadc6234530c0d0616606
/transpool-gui/src/main/java/org/components/RequestsTable.java
84c741280117818358aedcfb292f32616ee4833e
[]
no_license
Shimon-ar/transpool
https://github.com/Shimon-ar/transpool
5d07bb44ab1c6c0a22df780ad71813ea2ae58656
3949dfe50d203263929e581f5e453fd400cd1f8b
refs/heads/master
2022-12-26T22:08:54.226000
2020-08-16T16:34:43
2020-08-16T16:34:43
254,069,690
0
0
null
false
2020-10-14T00:16:23
2020-04-08T11:33:33
2020-08-16T16:34:55
2020-10-14T00:16:22
579
0
0
1
Java
false
false
package org.components; import com.jfoenix.controls.JFXTreeTableColumn; import com.jfoenix.controls.JFXTreeTableView; import org.ds.RequestTripProperty; import org.fxUtilities.FxUtilities; public class RequestsTable { private JFXTreeTableView<RequestTripProperty> treeTableView; private JFXTreeTableColumn<RequestTripProperty,Integer> idColumn; private JFXTreeTableColumn sourceColumn; private JFXTreeTableColumn destinationColumn; private JFXTreeTableColumn nameColumn; private JFXTreeTableColumn checkArrival; private JFXTreeTableColumn<RequestTripProperty,Boolean> matchedColumn; private JFXTreeTableColumn dayColumn; private JFXTreeTableColumn timeColumn; public RequestsTable() { treeTableView = new JFXTreeTableView(); idColumn = new JFXTreeTableColumn("Id"); sourceColumn = new JFXTreeTableColumn("Source station"); destinationColumn = new JFXTreeTableColumn("Destination station"); timeColumn = new JFXTreeTableColumn("Time"); checkArrival = new JFXTreeTableColumn("Check-out/Arrival"); matchedColumn = new JFXTreeTableColumn("Matched"); nameColumn = new JFXTreeTableColumn("Name"); dayColumn = new JFXTreeTableColumn("Day"); treeTableView.getStylesheets().add("/org/css/scrollPane.css"); treeTableView.getColumns().addAll(idColumn,nameColumn,sourceColumn,destinationColumn,dayColumn,checkArrival,timeColumn,matchedColumn); treeTableView.setPrefSize(700,170); idColumn.setPrefWidth(70); dayColumn.setPrefWidth(70); sourceColumn.setPrefWidth(150); destinationColumn.setPrefWidth(150); checkArrival.setPrefWidth(150); timeColumn.setPrefWidth(120); matchedColumn.setPrefWidth(90); nameColumn.setPrefWidth(130); treeTableView.getStylesheets().add("/org/css/tableLignment.css"); } public void show(){ FxUtilities.openNewStage(treeTableView,""); } public JFXTreeTableView<RequestTripProperty> getTreeTableView() { return treeTableView; } public JFXTreeTableColumn<RequestTripProperty,Integer> getIdColumn() { return idColumn; } public JFXTreeTableColumn getSourceColumn() { return sourceColumn; } public JFXTreeTableColumn getDestinationColumn() { return destinationColumn; } public JFXTreeTableColumn getNameColumn() { return nameColumn; } public JFXTreeTableColumn getCheckArrival() { return checkArrival; } public JFXTreeTableColumn getMatchedColumn() { return matchedColumn; } public JFXTreeTableColumn getDayColumn() { return dayColumn; } public JFXTreeTableColumn getTimeColumn() { return timeColumn; } }
UTF-8
Java
2,802
java
RequestsTable.java
Java
[]
null
[]
package org.components; import com.jfoenix.controls.JFXTreeTableColumn; import com.jfoenix.controls.JFXTreeTableView; import org.ds.RequestTripProperty; import org.fxUtilities.FxUtilities; public class RequestsTable { private JFXTreeTableView<RequestTripProperty> treeTableView; private JFXTreeTableColumn<RequestTripProperty,Integer> idColumn; private JFXTreeTableColumn sourceColumn; private JFXTreeTableColumn destinationColumn; private JFXTreeTableColumn nameColumn; private JFXTreeTableColumn checkArrival; private JFXTreeTableColumn<RequestTripProperty,Boolean> matchedColumn; private JFXTreeTableColumn dayColumn; private JFXTreeTableColumn timeColumn; public RequestsTable() { treeTableView = new JFXTreeTableView(); idColumn = new JFXTreeTableColumn("Id"); sourceColumn = new JFXTreeTableColumn("Source station"); destinationColumn = new JFXTreeTableColumn("Destination station"); timeColumn = new JFXTreeTableColumn("Time"); checkArrival = new JFXTreeTableColumn("Check-out/Arrival"); matchedColumn = new JFXTreeTableColumn("Matched"); nameColumn = new JFXTreeTableColumn("Name"); dayColumn = new JFXTreeTableColumn("Day"); treeTableView.getStylesheets().add("/org/css/scrollPane.css"); treeTableView.getColumns().addAll(idColumn,nameColumn,sourceColumn,destinationColumn,dayColumn,checkArrival,timeColumn,matchedColumn); treeTableView.setPrefSize(700,170); idColumn.setPrefWidth(70); dayColumn.setPrefWidth(70); sourceColumn.setPrefWidth(150); destinationColumn.setPrefWidth(150); checkArrival.setPrefWidth(150); timeColumn.setPrefWidth(120); matchedColumn.setPrefWidth(90); nameColumn.setPrefWidth(130); treeTableView.getStylesheets().add("/org/css/tableLignment.css"); } public void show(){ FxUtilities.openNewStage(treeTableView,""); } public JFXTreeTableView<RequestTripProperty> getTreeTableView() { return treeTableView; } public JFXTreeTableColumn<RequestTripProperty,Integer> getIdColumn() { return idColumn; } public JFXTreeTableColumn getSourceColumn() { return sourceColumn; } public JFXTreeTableColumn getDestinationColumn() { return destinationColumn; } public JFXTreeTableColumn getNameColumn() { return nameColumn; } public JFXTreeTableColumn getCheckArrival() { return checkArrival; } public JFXTreeTableColumn getMatchedColumn() { return matchedColumn; } public JFXTreeTableColumn getDayColumn() { return dayColumn; } public JFXTreeTableColumn getTimeColumn() { return timeColumn; } }
2,802
0.7202
0.710564
86
31.581396
26.357323
142
false
false
0
0
0
0
0
0
0.662791
false
false
10
83071c7ffe5d95c03b64696546864aa99c0c70c6
2,052,994,415,694
196b14b9857af540c20add6b9cfefd877cf2fea1
/src/main/java/com/trforcex/mods/wallpapercraft/compatibility/ChiselCompatibility.java
cdf4f052059abada52f35b4269a140d00895afbb
[]
no_license
AlexanderLaptev/wallpaper-craft
https://github.com/AlexanderLaptev/wallpaper-craft
55b67dc740b44991de4059d6722ed955921b20a3
99f3b97550b42dfa6baa84790a71b5770f41cc83
refs/heads/master
2020-06-10T19:24:44.204000
2020-04-09T08:26:57
2020-04-09T08:26:57
193,720,857
1
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.trforcex.mods.wallpapercraft.compatibility; import com.trforcex.mods.wallpapercraft.blocks.base.BaseModBlock; import com.trforcex.mods.wallpapercraft.init.ModBlocks; import com.trforcex.mods.wallpapercraft.util.ModUtils; import com.trforcex.mods.wallpapercraft.util.RecipeHelper; import net.minecraft.block.Block; import net.minecraft.item.ItemStack; import org.apache.commons.lang3.Validate; import team.chisel.api.carving.CarvingUtils; import team.chisel.api.carving.ICarvingGroup; import team.chisel.api.carving.ICarvingRegistry; import team.chisel.api.carving.ICarvingVariation; public class ChiselCompatibility { private static final String[] PATTERNS = {"bricks", "stone_bricks", "colored_bricks", "dotted", "diagonally_dotted", "rippled", "striped", "damask", "floral", "fancy_tiles", "clay", "wool", "checkered_wool", "wool_carpet", "checkered_carpet", "wood_planks", "stone_lamp", "aura_lamp", "tinted_glass", "textured_glass", "frosted_glass", "solid"}; private static ICarvingRegistry chisel; public static void init() { chisel = CarvingUtils.getChiselRegistry(); Validate.notNull(chisel, "Carving registry mustn't be null at this point!"); registerPatterns(); } // private static void registerPatterns() // { // for(String pattern : PATTERNS) // { // for(String color : ModDataManager.COLORS) // { // ICarvingGroup group = CarvingUtils.getDefaultGroupFor(pattern + "_" + color); // chisel.addGroup(group); // // BaseModBlock patternedBlock = (BaseModBlock) RecipeHelper.getModBlock(pattern, color); // Validate.notNull(patternedBlock, "Registries are not initialized: patternedBlock is null"); // // for(int meta = 0; meta <= patternedBlock.getMaxMeta(); meta++) // { // ItemStack stack = RecipeHelper.getStack(patternedBlock, 1, meta); // ICarvingVariation variation = CarvingUtils.variationFor(stack, 0); // // chisel.addVariation(group.getName(), variation); // } // } // } // // // Register Jewel and Stamp blocks // ICarvingGroup jewelGroup = CarvingUtils.getDefaultGroupFor("jewel"); // ICarvingGroup stampGroup = CarvingUtils.getDefaultGroupFor("stamp"); // // chisel.addGroup(jewelGroup); // chisel.addGroup(stampGroup); // // Block jewelBlock = ModBlocks.blockJewel; // Block stampBlock = ModBlocks.blockStamp; // Validate.notNull(jewelBlock, "Registries are not initialized: jewelBlock is null"); // Validate.notNull(stampBlock, "Registries are not initialized: stampBlock is null"); // // for(int meta = 0; meta <= 15; meta++) // { // ItemStack jewelStack = RecipeHelper.getStack(jewelBlock, 1, meta); // ICarvingVariation jewelVariation = CarvingUtils.variationFor(jewelStack, 0); // // ItemStack stampStack = RecipeHelper.getStack(stampBlock, 1, meta); // ICarvingVariation stampVariation = CarvingUtils.variationFor(stampStack, 0); // // chisel.addVariation(jewelGroup.getName(), jewelVariation); // chisel.addVariation(stampGroup.getName(), stampVariation); // } // // } private static void registerPatterns() { for(Block modBlock: ModBlocks.BLOCKS) { if(modBlock instanceof BaseModBlock) { BaseModBlock block = (BaseModBlock) modBlock; ICarvingGroup group; if(chisel.getGroup(ModUtils.composeString(block.getPattern(), block.getColor())) == null) group = CarvingUtils.getDefaultGroupFor(ModUtils.composeString(block.getPattern(), block.getColor())); else group = chisel.getGroup(ModUtils.composeString(block.getPattern(), block.getColor())); for(int meta = 0; meta <= block.getMaxMeta(); meta++) { ItemStack stack = RecipeHelper.getStack(block, 1, meta); ICarvingVariation variation = CarvingUtils.variationFor(stack, meta); chisel.addVariation(group.getName(), variation); } } } } }
UTF-8
Java
4,481
java
ChiselCompatibility.java
Java
[]
null
[]
package com.trforcex.mods.wallpapercraft.compatibility; import com.trforcex.mods.wallpapercraft.blocks.base.BaseModBlock; import com.trforcex.mods.wallpapercraft.init.ModBlocks; import com.trforcex.mods.wallpapercraft.util.ModUtils; import com.trforcex.mods.wallpapercraft.util.RecipeHelper; import net.minecraft.block.Block; import net.minecraft.item.ItemStack; import org.apache.commons.lang3.Validate; import team.chisel.api.carving.CarvingUtils; import team.chisel.api.carving.ICarvingGroup; import team.chisel.api.carving.ICarvingRegistry; import team.chisel.api.carving.ICarvingVariation; public class ChiselCompatibility { private static final String[] PATTERNS = {"bricks", "stone_bricks", "colored_bricks", "dotted", "diagonally_dotted", "rippled", "striped", "damask", "floral", "fancy_tiles", "clay", "wool", "checkered_wool", "wool_carpet", "checkered_carpet", "wood_planks", "stone_lamp", "aura_lamp", "tinted_glass", "textured_glass", "frosted_glass", "solid"}; private static ICarvingRegistry chisel; public static void init() { chisel = CarvingUtils.getChiselRegistry(); Validate.notNull(chisel, "Carving registry mustn't be null at this point!"); registerPatterns(); } // private static void registerPatterns() // { // for(String pattern : PATTERNS) // { // for(String color : ModDataManager.COLORS) // { // ICarvingGroup group = CarvingUtils.getDefaultGroupFor(pattern + "_" + color); // chisel.addGroup(group); // // BaseModBlock patternedBlock = (BaseModBlock) RecipeHelper.getModBlock(pattern, color); // Validate.notNull(patternedBlock, "Registries are not initialized: patternedBlock is null"); // // for(int meta = 0; meta <= patternedBlock.getMaxMeta(); meta++) // { // ItemStack stack = RecipeHelper.getStack(patternedBlock, 1, meta); // ICarvingVariation variation = CarvingUtils.variationFor(stack, 0); // // chisel.addVariation(group.getName(), variation); // } // } // } // // // Register Jewel and Stamp blocks // ICarvingGroup jewelGroup = CarvingUtils.getDefaultGroupFor("jewel"); // ICarvingGroup stampGroup = CarvingUtils.getDefaultGroupFor("stamp"); // // chisel.addGroup(jewelGroup); // chisel.addGroup(stampGroup); // // Block jewelBlock = ModBlocks.blockJewel; // Block stampBlock = ModBlocks.blockStamp; // Validate.notNull(jewelBlock, "Registries are not initialized: jewelBlock is null"); // Validate.notNull(stampBlock, "Registries are not initialized: stampBlock is null"); // // for(int meta = 0; meta <= 15; meta++) // { // ItemStack jewelStack = RecipeHelper.getStack(jewelBlock, 1, meta); // ICarvingVariation jewelVariation = CarvingUtils.variationFor(jewelStack, 0); // // ItemStack stampStack = RecipeHelper.getStack(stampBlock, 1, meta); // ICarvingVariation stampVariation = CarvingUtils.variationFor(stampStack, 0); // // chisel.addVariation(jewelGroup.getName(), jewelVariation); // chisel.addVariation(stampGroup.getName(), stampVariation); // } // // } private static void registerPatterns() { for(Block modBlock: ModBlocks.BLOCKS) { if(modBlock instanceof BaseModBlock) { BaseModBlock block = (BaseModBlock) modBlock; ICarvingGroup group; if(chisel.getGroup(ModUtils.composeString(block.getPattern(), block.getColor())) == null) group = CarvingUtils.getDefaultGroupFor(ModUtils.composeString(block.getPattern(), block.getColor())); else group = chisel.getGroup(ModUtils.composeString(block.getPattern(), block.getColor())); for(int meta = 0; meta <= block.getMaxMeta(); meta++) { ItemStack stack = RecipeHelper.getStack(block, 1, meta); ICarvingVariation variation = CarvingUtils.variationFor(stack, meta); chisel.addVariation(group.getName(), variation); } } } } }
4,481
0.614372
0.611471
101
43.366337
36.790745
138
false
false
0
0
0
0
0
0
0.950495
false
false
10
a2aa1bc5f68adc666f92bcefa460c6e4e18015ac
27,565,100,173,689
774d36285e48bd429017b6901a59b8e3a51d6add
/sources/com/onesignal/GcmIntentJobService.java
adc71583e782d5541b2f437ffeafa6b62507ce14
[]
no_license
jorge-luque/hb
https://github.com/jorge-luque/hb
83c086851a409e7e476298ffdf6ba0c8d06911db
b467a9af24164f7561057e5bcd19cdbc8647d2e5
refs/heads/master
2023-08-25T09:32:18.793000
2020-10-02T11:02:01
2020-10-02T11:02:01
300,586,541
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.onesignal; import android.content.Context; import android.content.Intent; import com.onesignal.C4739z; public class GcmIntentJobService extends JobIntentService { /* access modifiers changed from: protected */ /* renamed from: a */ public void mo29635a(Intent intent) { C4528j a = C4540l.m15657a(); a.mo29792a(intent.getExtras().getParcelable("Bundle:Parcelable:Extras")); C4714x.m16405a((Context) this, a, (C4739z.C4740a) null); } /* renamed from: a */ public static void m15342a(Context context, Intent intent) { JobIntentService.m15346a(context, GcmIntentJobService.class, 123890, intent, false); } }
UTF-8
Java
679
java
GcmIntentJobService.java
Java
[]
null
[]
package com.onesignal; import android.content.Context; import android.content.Intent; import com.onesignal.C4739z; public class GcmIntentJobService extends JobIntentService { /* access modifiers changed from: protected */ /* renamed from: a */ public void mo29635a(Intent intent) { C4528j a = C4540l.m15657a(); a.mo29792a(intent.getExtras().getParcelable("Bundle:Parcelable:Extras")); C4714x.m16405a((Context) this, a, (C4739z.C4740a) null); } /* renamed from: a */ public static void m15342a(Context context, Intent intent) { JobIntentService.m15346a(context, GcmIntentJobService.class, 123890, intent, false); } }
679
0.703976
0.615611
20
32.950001
27.286398
92
false
false
0
0
0
0
0
0
0.75
false
false
10
8adfb8b5ca9feb0688e6f41b2b7168808b5b2fdf
27,565,100,173,237
f1e1db2cff1df83a944454490a9f093700471a3e
/ADAgioProject/src/com/adagio/language/musicnotes/octavealterations/OctaveAlteration.java
637b35645347e78b55c56a821adad5bd96f56cdf
[]
no_license
lquesada/ADAgio
https://github.com/lquesada/ADAgio
1b0b99b09de90a94c87bc8a063fcea760d293f9c
57430ad6c38b1b92f1aed93914b2fe238d787edd
refs/heads/master
2021-01-18T07:31:37.974000
2020-04-08T23:22:43
2020-04-08T23:22:43
20,588,069
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.adagio.language.musicnotes.octavealterations; import org.modelcc.IModel; public abstract class OctaveAlteration implements IModel { /** * The function calculates the number of octaves that increases or decreases * the alteration * @return An integer value. Positive to increase. Negative to decrease. */ public abstract int toInt(); public abstract String toString(); public abstract boolean equals(Object o); public abstract OctaveAlteration clone(); }
UTF-8
Java
502
java
OctaveAlteration.java
Java
[]
null
[]
package com.adagio.language.musicnotes.octavealterations; import org.modelcc.IModel; public abstract class OctaveAlteration implements IModel { /** * The function calculates the number of octaves that increases or decreases * the alteration * @return An integer value. Positive to increase. Negative to decrease. */ public abstract int toInt(); public abstract String toString(); public abstract boolean equals(Object o); public abstract OctaveAlteration clone(); }
502
0.747012
0.747012
17
27.529411
26.14016
77
false
false
0
0
0
0
0
0
1
false
false
10
d2521526a0b17b0da429c20dc15e683581463fe9
37,228,776,549,691
d384987af87f4f7547a2e4ff6c03957e2d8ac0f8
/src/main/java/org/xero1425/simulator/engine/SimulationModelEvent.java
0f7fc9baaa0c5ebb20343c3e05ef71e15a3e288e
[]
no_license
errorcodexero/droidjava
https://github.com/errorcodexero/droidjava
d26b63ead0c1dda612efc21a3eefacf4c500c3db
e67525ba4a8d6b3257a8c3cd6878e872d93561cc
refs/heads/master
2023-02-16T12:32:29.033000
2020-11-24T23:23:06
2020-11-24T23:27:02
254,918,324
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.xero1425.simulator.engine; import org.xero1425.misc.BadParameterTypeException; import org.xero1425.misc.MessageLogger; import org.xero1425.misc.MessageType; import org.xero1425.misc.SettingsValue; public class SimulationModelEvent extends SimulationEvent { public SimulationModelEvent(double t, String model, String instance, String name, SettingsValue v) { super(t); model_ = model; instance_ = instance; name_ = name; value_ = v; } public String getModel() { return model_; } public String getInstance() { return instance_; } public String getName() { return name_; } public SettingsValue getValue() { return value_; } public String toString() { String str = "SimulationModelEvent:"; str += " model=" + model_; str += " instance=" + instance_; str += " name=" + name_; str += " value=" + value_.toString(); return str; } public void run(SimulationEngine engine) { if (name_.equals("comment")) { MessageLogger logger = engine.getMessageLogger(); logger.startMessage(MessageType.Info); logger.add("simulation comment "); if (value_.isString()) { try { logger.addQuoted(value_.getString()); } catch (BadParameterTypeException e) { } } else { logger.addQuoted(value_.toString()) ; } logger.endMessage(); } else { SimulationModel model = engine.findModel(model_, instance_) ; if (model != null) model.processEvent(name_, value_) ; else { MessageLogger logger = engine.getMessageLogger() ; logger.startMessage(MessageType.Error) ; logger.add("cannot process event ").addQuoted(toString()) ; logger.add(" model ").addQuoted(model_).add(" instance ").addQuoted(instance_) ; logger.add(" does not exist") ; } } } private String model_ ; private String instance_ ; private String name_ ; private SettingsValue value_ ; }
UTF-8
Java
2,283
java
SimulationModelEvent.java
Java
[]
null
[]
package org.xero1425.simulator.engine; import org.xero1425.misc.BadParameterTypeException; import org.xero1425.misc.MessageLogger; import org.xero1425.misc.MessageType; import org.xero1425.misc.SettingsValue; public class SimulationModelEvent extends SimulationEvent { public SimulationModelEvent(double t, String model, String instance, String name, SettingsValue v) { super(t); model_ = model; instance_ = instance; name_ = name; value_ = v; } public String getModel() { return model_; } public String getInstance() { return instance_; } public String getName() { return name_; } public SettingsValue getValue() { return value_; } public String toString() { String str = "SimulationModelEvent:"; str += " model=" + model_; str += " instance=" + instance_; str += " name=" + name_; str += " value=" + value_.toString(); return str; } public void run(SimulationEngine engine) { if (name_.equals("comment")) { MessageLogger logger = engine.getMessageLogger(); logger.startMessage(MessageType.Info); logger.add("simulation comment "); if (value_.isString()) { try { logger.addQuoted(value_.getString()); } catch (BadParameterTypeException e) { } } else { logger.addQuoted(value_.toString()) ; } logger.endMessage(); } else { SimulationModel model = engine.findModel(model_, instance_) ; if (model != null) model.processEvent(name_, value_) ; else { MessageLogger logger = engine.getMessageLogger() ; logger.startMessage(MessageType.Error) ; logger.add("cannot process event ").addQuoted(toString()) ; logger.add(" model ").addQuoted(model_).add(" instance ").addQuoted(instance_) ; logger.add(" does not exist") ; } } } private String model_ ; private String instance_ ; private String name_ ; private SettingsValue value_ ; }
2,283
0.554972
0.546211
78
28.282051
22.842772
104
false
false
0
0
0
0
0
0
0.551282
false
false
10
6aef08fd05f84a02ff4092c2d2c76521f4175a5c
36,318,243,495,766
105fe6ca0998268c408b6d1b1e2233007cafdf8a
/src/main/java/org/example/App.java
9a7f4092cc453a7c36a0fad612d7340e70263642
[]
no_license
harminjeong/jeong-cop3330-ex07
https://github.com/harminjeong/jeong-cop3330-ex07
d3644f43fc547a92ee4728f612730ee6ba4ce6b0
7be5e256542ab2f87eb35555764ae1a9d9c31f6e
refs/heads/master
2023-07-26T23:58:56.681000
2021-09-14T01:32:38
2021-09-14T01:32:38
406,184,318
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * UCF COP3330 Fall 2021 Assignment 1 Solution * Copyright 2021 Harmin Jeong */ package org.example; import java.util.Scanner; public class App { public static void main( String[] args ) { Scanner input = new Scanner(System.in); System.out.print("What is the length of the room in feet? "); String inputLength = input.nextLine(); System.out.print("What is the width of the room in feet? "); String inputWidth = input.nextLine(); int length = Integer.parseInt(inputLength); int width = Integer.parseInt(inputWidth); int area = width*length; float meters = area * 0.09290304f; System.out.printf("You entered dimensions of %d feet by %d feet.\nThe area is\n%d square feet\n%.3f square meters",length,width,area,meters); } }
UTF-8
Java
826
java
App.java
Java
[ { "context": "Fall 2021 Assignment 1 Solution\n * Copyright 2021 Harmin Jeong\n */\npackage org.example;\nimport java.util.Scanner", "end": 82, "score": 0.9998587369918823, "start": 70, "tag": "NAME", "value": "Harmin Jeong" } ]
null
[]
/* * UCF COP3330 Fall 2021 Assignment 1 Solution * Copyright 2021 <NAME> */ package org.example; import java.util.Scanner; public class App { public static void main( String[] args ) { Scanner input = new Scanner(System.in); System.out.print("What is the length of the room in feet? "); String inputLength = input.nextLine(); System.out.print("What is the width of the room in feet? "); String inputWidth = input.nextLine(); int length = Integer.parseInt(inputLength); int width = Integer.parseInt(inputWidth); int area = width*length; float meters = area * 0.09290304f; System.out.printf("You entered dimensions of %d feet by %d feet.\nThe area is\n%d square feet\n%.3f square meters",length,width,area,meters); } }
820
0.650121
0.622276
27
29.592592
32.527206
149
false
false
0
0
0
0
0
0
0.592593
false
false
10
ee3cf2250b6b431b2265298dc52eab6958718304
36,318,243,498,225
f8152371962fbe7fd8b7268182385936b39d79fd
/projekt/VPTI_01/robots/sample/RobotTCPClient.java
d62cabcfce12d177c551c17801e303da129dbd5e
[]
no_license
Mysfrit/PDA_robocode
https://github.com/Mysfrit/PDA_robocode
2f1805e9688e813015970251dd0d21869c80da5a
56524d9ae8b4bfec00402d94cde808c0222984ed
refs/heads/main
2023-01-29T00:28:55.564000
2020-12-14T12:48:47
2020-12-14T12:48:47
310,685,652
0
0
null
false
2020-12-14T12:30:47
2020-11-06T19:14:56
2020-11-09T20:23:20
2020-12-14T12:30:46
30,869
0
0
0
Java
false
false
package sample; import robocode.AdvancedRobot; import robocode.HitByBulletEvent; import robocode.Robot; import robocode.ScannedRobotEvent; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.DataOutputStream; import java.io.InputStream; import java.io.InputStreamReader; import java.net.Socket; import java.nio.charset.StandardCharsets; class RobotTCPClient extends Robot { public static void main(String argv[]) throws Exception { String sentence; String responseFromIAServer; String dataToSendFromRobocode2 = "100;100;image_data"; String dataToSendFromRobocode = "hi"; System.out.println("Sending data: "+dataToSendFromRobocode); InputStream inStream = new ByteArrayInputStream(dataToSendFromRobocode.getBytes(StandardCharsets.UTF_8)); BufferedReader inFromUser = new BufferedReader(new InputStreamReader(inStream)); Socket clientSocket = new Socket("localhost", 5000); DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream()); BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); sentence = inFromUser.readLine(); outToServer.writeBytes(sentence + 'n'); responseFromIAServer = inFromServer.readLine(); System.out.println("Action to do from server: " + responseFromIAServer); clientSocket.close(); } }
UTF-8
Java
1,509
java
RobotTCPClient.java
Java
[]
null
[]
package sample; import robocode.AdvancedRobot; import robocode.HitByBulletEvent; import robocode.Robot; import robocode.ScannedRobotEvent; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.DataOutputStream; import java.io.InputStream; import java.io.InputStreamReader; import java.net.Socket; import java.nio.charset.StandardCharsets; class RobotTCPClient extends Robot { public static void main(String argv[]) throws Exception { String sentence; String responseFromIAServer; String dataToSendFromRobocode2 = "100;100;image_data"; String dataToSendFromRobocode = "hi"; System.out.println("Sending data: "+dataToSendFromRobocode); InputStream inStream = new ByteArrayInputStream(dataToSendFromRobocode.getBytes(StandardCharsets.UTF_8)); BufferedReader inFromUser = new BufferedReader(new InputStreamReader(inStream)); Socket clientSocket = new Socket("localhost", 5000); DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream()); BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); sentence = inFromUser.readLine(); outToServer.writeBytes(sentence + 'n'); responseFromIAServer = inFromServer.readLine(); System.out.println("Action to do from server: " + responseFromIAServer); clientSocket.close(); } }
1,509
0.718357
0.710404
36
40.944443
31.232056
117
false
false
0
0
0
0
0
0
0.833333
false
false
10
f207876074ae1deab3f42551501ccc7b13ea2b11
36,129,264,930,141
e06f352f3984538610c8d812637f40e97c436a65
/00-leetcode/src/合并两个有序数组/test.java
f500b6847009143c981ece88e24d0802a8d02d8a
[]
no_license
divisionblur/DataStructureLearning
https://github.com/divisionblur/DataStructureLearning
91d37ee01563f25659d20a13aa35b99f1ff46a41
3f70d02aa82c62c9b6a5906b9ba45d402dd02fc2
refs/heads/master
2023-01-06T17:22:34.649000
2020-11-08T14:08:13
2020-11-08T14:08:13
308,799,179
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package 合并两个有序数组; import java.util.function.Function; /** * @author joy division * @date 2020/10/26 21:49 */ public class test { public static void main(String[] args) { Function<Integer,Employee> fun = id -> new Employee(id); Employee instance = fun.apply(9090); System.out.println(instance); } }
UTF-8
Java
351
java
test.java
Java
[ { "context": "mport java.util.function.Function;\n\n/**\n * @author joy division\n * @date 2020/10/26 21:49\n */\npublic class test {", "end": 83, "score": 0.989401638507843, "start": 71, "tag": "USERNAME", "value": "joy division" } ]
null
[]
package 合并两个有序数组; import java.util.function.Function; /** * @author joy division * @date 2020/10/26 21:49 */ public class test { public static void main(String[] args) { Function<Integer,Employee> fun = id -> new Employee(id); Employee instance = fun.apply(9090); System.out.println(instance); } }
351
0.644776
0.597015
15
21.333334
19.293062
64
false
false
0
0
0
0
0
0
0.4
false
false
10
c38af15fdc7aedc43ecd1efe43307a210b0de67f
39,573,828,689,951
0834b331d13563e5a887df0011e44a0b20bb993b
/toolbar/SettingActivity.java
4e52afc68e1ec9e1752d5e6c6de6a7cb42717f8d
[]
no_license
farohainn/Kuantan-MySejahtera
https://github.com/farohainn/Kuantan-MySejahtera
06f9dc42d103b0820cf1550bbd2896d7568d0ded
beaca91c796cff99ccb5c0f1b8ac93129f1c8c4a
refs/heads/main
2023-04-19T17:24:45.175000
2021-05-16T07:41:03
2021-05-16T07:41:03
367,811,978
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.kuantansejahtera_a170567.toolbar; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.AppCompatActivity; import android.content.DialogInterface; import android.content.SharedPreferences; import android.os.Bundle; import android.view.View; import android.widget.CompoundButton; import android.widget.LinearLayout; import android.widget.Switch; import android.widget.TextView; import com.example.kuantansejahtera_a170567.R; public class SettingActivity extends AppCompatActivity { TextView tv_language; LinearLayout ll_setting_language, ll_setting_notificattion; Switch switch_notification; SharedPreferences sharedPref; SharedPreferences.Editor editor; String SP_LANGUAGE = " language"; String SP_NOTIFICATION = "notification"; String[] values = {"English", "Melayu", "Chinese", "Tamil"}; AlertDialog alertDialog; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_setting); tv_language = findViewById(R.id.tv_language); switch_notification = findViewById(R.id.switch_notification); ll_setting_language = findViewById(R.id.ll_profile_language); ll_setting_notificattion = findViewById(R.id.ll_profile_notification); sharedPref = getSharedPreferences("app.settings", MODE_PRIVATE); editor = sharedPref.edit(); switch_notification.setChecked(sharedPref.getBoolean(SP_NOTIFICATION,false)); tv_language.setText((values[sharedPref.getInt(SP_LANGUAGE, 0)])); switch_notification.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton compoundButton, boolean b) { editor.putBoolean(SP_NOTIFICATION,b); editor.commit(); } }); ll_setting_notificattion.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Boolean switchState = switch_notification.isChecked(); switch_notification.setChecked(!switchState); editor.putBoolean(SP_NOTIFICATION,!switchState); editor.commit(); } }); ll_setting_language.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { ShowLanguagaeOptions(); } }); } public void ShowLanguagaeOptions(){ AlertDialog.Builder builder = new AlertDialog.Builder(SettingActivity.this); builder.setTitle("Select your language"); builder.setSingleChoiceItems(values, sharedPref.getInt(SP_LANGUAGE, 0), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { switch (i){ case 0: editor.putInt(SP_LANGUAGE,0); editor.commit(); break; case 1: editor.putInt(SP_LANGUAGE,1); editor.commit(); break; case 2: editor.putInt(SP_LANGUAGE,2); editor.commit(); break; case 3: editor.putInt(SP_LANGUAGE,3); editor.commit(); break; } alertDialog.dismiss(); tv_language.setText((values[sharedPref.getInt(SP_LANGUAGE, 0)])); } }); alertDialog = builder.create(); alertDialog.show(); } }
UTF-8
Java
3,939
java
SettingActivity.java
Java
[]
null
[]
package com.example.kuantansejahtera_a170567.toolbar; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.AppCompatActivity; import android.content.DialogInterface; import android.content.SharedPreferences; import android.os.Bundle; import android.view.View; import android.widget.CompoundButton; import android.widget.LinearLayout; import android.widget.Switch; import android.widget.TextView; import com.example.kuantansejahtera_a170567.R; public class SettingActivity extends AppCompatActivity { TextView tv_language; LinearLayout ll_setting_language, ll_setting_notificattion; Switch switch_notification; SharedPreferences sharedPref; SharedPreferences.Editor editor; String SP_LANGUAGE = " language"; String SP_NOTIFICATION = "notification"; String[] values = {"English", "Melayu", "Chinese", "Tamil"}; AlertDialog alertDialog; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_setting); tv_language = findViewById(R.id.tv_language); switch_notification = findViewById(R.id.switch_notification); ll_setting_language = findViewById(R.id.ll_profile_language); ll_setting_notificattion = findViewById(R.id.ll_profile_notification); sharedPref = getSharedPreferences("app.settings", MODE_PRIVATE); editor = sharedPref.edit(); switch_notification.setChecked(sharedPref.getBoolean(SP_NOTIFICATION,false)); tv_language.setText((values[sharedPref.getInt(SP_LANGUAGE, 0)])); switch_notification.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton compoundButton, boolean b) { editor.putBoolean(SP_NOTIFICATION,b); editor.commit(); } }); ll_setting_notificattion.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Boolean switchState = switch_notification.isChecked(); switch_notification.setChecked(!switchState); editor.putBoolean(SP_NOTIFICATION,!switchState); editor.commit(); } }); ll_setting_language.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { ShowLanguagaeOptions(); } }); } public void ShowLanguagaeOptions(){ AlertDialog.Builder builder = new AlertDialog.Builder(SettingActivity.this); builder.setTitle("Select your language"); builder.setSingleChoiceItems(values, sharedPref.getInt(SP_LANGUAGE, 0), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { switch (i){ case 0: editor.putInt(SP_LANGUAGE,0); editor.commit(); break; case 1: editor.putInt(SP_LANGUAGE,1); editor.commit(); break; case 2: editor.putInt(SP_LANGUAGE,2); editor.commit(); break; case 3: editor.putInt(SP_LANGUAGE,3); editor.commit(); break; } alertDialog.dismiss(); tv_language.setText((values[sharedPref.getInt(SP_LANGUAGE, 0)])); } }); alertDialog = builder.create(); alertDialog.show(); } }
3,939
0.590505
0.584666
106
35.160378
26.100002
119
false
false
0
0
0
0
0
0
0.745283
false
false
10
ead2b0b776806ba6116b6fa7a5bdf6aff7c75278
24,721,831,823,354
5a927522c9a105378066859a37c13ac2be23e060
/order-feign-api/src/main/java/com/bit/mall/feign_apis/client/ProductServiceClient.java
59eefebb4e5b9d9c548ffd951bd681a9ce71bbf8
[]
no_license
chenwei9120/alicloudtest
https://github.com/chenwei9120/alicloudtest
8f4c7fb367be80d4c48309d3290eb42c30f1ce4e
9869dcf5e1241c608db47000ed2c9e5dde131774
refs/heads/master
2021-01-05T01:13:18.344000
2020-05-11T11:02:03
2020-05-11T11:02:03
240,824,768
0
0
null
false
2020-02-17T06:38:45
2020-02-16T03:24:33
2020-02-17T06:38:00
2020-02-17T06:37:57
129
0
0
0
Java
false
false
package com.bit.mall.feign_apis.client; import com.bit.mall.feign_apis.config.ProductServiceConfig; import com.bit.model.Product; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; /** * @author chenwei * @version 1.0.0 * @ClassName ProductServiceClient.java * @Description TODO * @createTime 2020年02月15日 21:27:00 */ @FeignClient(name = "product-service",configuration = ProductServiceConfig.class) public interface ProductServiceClient { @RequestMapping(value = "/product/get/{id}") Product getProductById(@PathVariable("id") Long id); @RequestMapping(value="/product/timeout") void timeoutAction(); }
UTF-8
Java
788
java
ProductServiceClient.java
Java
[ { "context": "bind.annotation.RequestMapping;\r\n\r\n/**\r\n * @author chenwei\r\n * @version 1.0.0\r\n * @ClassName ProductServiceC", "end": 343, "score": 0.9995260834693909, "start": 336, "tag": "USERNAME", "value": "chenwei" } ]
null
[]
package com.bit.mall.feign_apis.client; import com.bit.mall.feign_apis.config.ProductServiceConfig; import com.bit.model.Product; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; /** * @author chenwei * @version 1.0.0 * @ClassName ProductServiceClient.java * @Description TODO * @createTime 2020年02月15日 21:27:00 */ @FeignClient(name = "product-service",configuration = ProductServiceConfig.class) public interface ProductServiceClient { @RequestMapping(value = "/product/get/{id}") Product getProductById(@PathVariable("id") Long id); @RequestMapping(value="/product/timeout") void timeoutAction(); }
788
0.749361
0.727621
25
29.360001
24.25841
81
false
false
0
0
0
0
0
0
0.36
false
false
10
d4b03e881eec1a2247b7b063746deecb110eb2b1
18,038,862,684,703
5c66d9628bc036f087aa97c13422a31c0412e44d
/src/main/java/com/pedro/ecommerce/model/converter/BooleanToSimNaoConverter.java
e7ad8941e103b648524cc48dd32c2297e509cd5a
[]
no_license
legendbr94/ecommerce
https://github.com/legendbr94/ecommerce
7918ec67186db11dc099655238d15178fbebf486
0f1626be09453cd5da5d6e6624e9501542fc5146
refs/heads/master
2023-05-06T02:30:59.806000
2021-05-19T12:24:30
2021-05-19T12:24:30
368,165,323
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.pedro.ecommerce.model.converter; import javax.persistence.AttributeConverter; import javax.persistence.Converter; @Converter public class BooleanToSimNaoConverter implements AttributeConverter<Boolean, String> { @Override public String convertToDatabaseColumn(Boolean aBoolean) { return Boolean.TRUE.equals(aBoolean) ? "SIM" : "NAO"; } @Override public Boolean convertToEntityAttribute(String s) { return "SIM".equals(s) ? Boolean.TRUE : Boolean.FALSE; } }
UTF-8
Java
512
java
BooleanToSimNaoConverter.java
Java
[]
null
[]
package com.pedro.ecommerce.model.converter; import javax.persistence.AttributeConverter; import javax.persistence.Converter; @Converter public class BooleanToSimNaoConverter implements AttributeConverter<Boolean, String> { @Override public String convertToDatabaseColumn(Boolean aBoolean) { return Boolean.TRUE.equals(aBoolean) ? "SIM" : "NAO"; } @Override public Boolean convertToEntityAttribute(String s) { return "SIM".equals(s) ? Boolean.TRUE : Boolean.FALSE; } }
512
0.742188
0.742188
17
29.117647
27.525139
86
false
false
0
0
0
0
0
0
0.352941
false
false
10
d1a1eff8d0bc6e62806b76f2740e2715c166c4bb
25,520,695,729,261
8a041433a123421346f38dce210dc259025a0810
/everisSiteReliabilityEngineerEssentials/DesafiosAvancados/FibonacciArray.java
1c44f73efdd7d77b87cac0c53cff211e8d178f5a
[]
no_license
Raf98/Java-DIO
https://github.com/Raf98/Java-DIO
633d563a3856c5e3e52d34652d16c4fa1cde83b4
71b0f3f4ac62283d3f5be7dc5d372175ed8ef49e
refs/heads/master
2023-06-25T10:45:43.212000
2021-07-27T04:31:37
2021-07-27T04:31:37
300,448,085
14
2
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.io.IOException; import java.util.Scanner; public class FibonacciArray{ public static void main(String[] args) throws IOException { Scanner leitor = new Scanner(System.in); int T = leitor.nextInt(); for (int i = 0; i < T; ++i) { int N = leitor.nextInt(); long anterior = 0, atual = 1, auxiliar; for (int j = 0; j < N; ++j) { auxiliar = atual; atual = atual + anterior; anterior = auxiliar; } System.out.println("Fib("+ N +") = " + anterior); } } }
UTF-8
Java
580
java
FibonacciArray.java
Java
[]
null
[]
import java.io.IOException; import java.util.Scanner; public class FibonacciArray{ public static void main(String[] args) throws IOException { Scanner leitor = new Scanner(System.in); int T = leitor.nextInt(); for (int i = 0; i < T; ++i) { int N = leitor.nextInt(); long anterior = 0, atual = 1, auxiliar; for (int j = 0; j < N; ++j) { auxiliar = atual; atual = atual + anterior; anterior = auxiliar; } System.out.println("Fib("+ N +") = " + anterior); } } }
580
0.525862
0.518966
21
26.619047
18.793303
63
false
false
0
0
0
0
0
0
1.333333
false
false
10
139d9d368b1b2102864ab0748ba50da690e926df
25,520,695,725,739
97424df0eb537ed5a5f29f149dace6661db0b6d8
/bin/FreeMarker.d/FreeMarker.java
68445e7128e4a6c946ac945535a480b9e8708ca7
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
harrifeng/system-config
https://github.com/harrifeng/system-config
5cc39b756b201fe9263cb2eb388512c68e35517e
feb25f72a38b829ab5fa8bf739adb78c10a7a4f6
refs/heads/master
2022-06-11T14:46:35.164000
2020-05-04T04:11:00
2020-05-04T04:11:00
261,195,175
1
0
null
true
2020-05-04T13:57:12
2020-05-04T13:57:11
2020-05-04T04:11:20
2020-05-04T04:11:16
732,115
0
0
0
null
false
false
import com.android.tools.idea.templates.*; import freemarker.template.*; import java.util.*; import java.io.*; public class FreeMarker { public static void main(String[] args) throws Exception { if (args.length < 2) { System.out.println(String.format("%s Error: usage: FreeMarker dir ftl key val ...%s", "FreeMarker.java:10:", "")); } /* ----------------------------------------------------------------------- */ /* You should do this ONLY ONCE in the whole application life-cycle: */ /* Create and adjust the configuration */ Configuration cfg = new Configuration(); cfg.setDirectoryForTemplateLoading(new File(args[0])); cfg.setObjectWrapper(new DefaultObjectWrapper()); cfg.setDefaultEncoding("UTF-8"); cfg.setTemplateExceptionHandler(TemplateExceptionHandler.HTML_DEBUG_HANDLER); /* ----------------------------------------------------------------------- */ /* You usually do these for many times in the application life-cycle: */ /* Create a data-model */ Map root = new HashMap(); for (int i = 2; i < args.length; i += 2) { root.put(args[i], args[i+1]); if (args[i+1].equalsIgnoreCase("false!")) { root.put(args[i], false); } else if (args[i+1].equalsIgnoreCase("true!")) { root.put(args[i], true); } else if (args[i+1].matches("\\d+!")) { root.put(args[i], Integer.parseInt(args[i+1].substring(0, args[i+1].length() - 1))); } else if (args[i].matches("is.*")) { if (args[i+1].matches("true|false")) { root.put(args[i], args[i+1].matches("true") ? true : false); } } else if (args[i+1].matches("\\d+")) { root.put(args[i], Integer.parseInt(args[i+1].substring(0, args[i+1].length()))); } } root.put("slashedPackageName", new FmSlashedPackageNameMethod()); root.put("camelCaseToUnderscore", new FmCamelCaseToUnderscoreMethod()); root.put("underscoreToCamelCase", new FmUnderscoreToCamelCaseMethod()); root.put("activityToLayout", new FmActivityToLayoutMethod()); root.put("layoutToActivity", new FmLayoutToActivityMethod()); root.put("classToResource", new FmClassNameToResourceMethod()); root.put("escapeXmlAttribute", new FmEscapeXmlStringMethod()); root.put("escapeXmlText", new FmEscapeXmlStringMethod()); root.put("escapeXmlString", new FmEscapeXmlStringMethod()); root.put("extractLetters", new FmExtractLettersMethod()); /* Get the template */ Template temp = cfg.getTemplate(args[1]); /* Merge data-model with template */ Writer out = new OutputStreamWriter(System.out); temp.process(root, out); } }
UTF-8
Java
2,905
java
FreeMarker.java
Java
[]
null
[]
import com.android.tools.idea.templates.*; import freemarker.template.*; import java.util.*; import java.io.*; public class FreeMarker { public static void main(String[] args) throws Exception { if (args.length < 2) { System.out.println(String.format("%s Error: usage: FreeMarker dir ftl key val ...%s", "FreeMarker.java:10:", "")); } /* ----------------------------------------------------------------------- */ /* You should do this ONLY ONCE in the whole application life-cycle: */ /* Create and adjust the configuration */ Configuration cfg = new Configuration(); cfg.setDirectoryForTemplateLoading(new File(args[0])); cfg.setObjectWrapper(new DefaultObjectWrapper()); cfg.setDefaultEncoding("UTF-8"); cfg.setTemplateExceptionHandler(TemplateExceptionHandler.HTML_DEBUG_HANDLER); /* ----------------------------------------------------------------------- */ /* You usually do these for many times in the application life-cycle: */ /* Create a data-model */ Map root = new HashMap(); for (int i = 2; i < args.length; i += 2) { root.put(args[i], args[i+1]); if (args[i+1].equalsIgnoreCase("false!")) { root.put(args[i], false); } else if (args[i+1].equalsIgnoreCase("true!")) { root.put(args[i], true); } else if (args[i+1].matches("\\d+!")) { root.put(args[i], Integer.parseInt(args[i+1].substring(0, args[i+1].length() - 1))); } else if (args[i].matches("is.*")) { if (args[i+1].matches("true|false")) { root.put(args[i], args[i+1].matches("true") ? true : false); } } else if (args[i+1].matches("\\d+")) { root.put(args[i], Integer.parseInt(args[i+1].substring(0, args[i+1].length()))); } } root.put("slashedPackageName", new FmSlashedPackageNameMethod()); root.put("camelCaseToUnderscore", new FmCamelCaseToUnderscoreMethod()); root.put("underscoreToCamelCase", new FmUnderscoreToCamelCaseMethod()); root.put("activityToLayout", new FmActivityToLayoutMethod()); root.put("layoutToActivity", new FmLayoutToActivityMethod()); root.put("classToResource", new FmClassNameToResourceMethod()); root.put("escapeXmlAttribute", new FmEscapeXmlStringMethod()); root.put("escapeXmlText", new FmEscapeXmlStringMethod()); root.put("escapeXmlString", new FmEscapeXmlStringMethod()); root.put("extractLetters", new FmExtractLettersMethod()); /* Get the template */ Template temp = cfg.getTemplate(args[1]); /* Merge data-model with template */ Writer out = new OutputStreamWriter(System.out); temp.process(root, out); } }
2,905
0.563511
0.555938
67
42.358208
31.520523
126
false
false
0
0
0
0
0
0
0.80597
false
false
10
10e607f4f5166695a567644692e89bfef610d098
9,552,007,331,725
2d8fdcaed2bd8292e770e3864562d71505404862
/src/cn/itwx/leetcode31_40/Leetcode36.java
ebc62bdefe78fa161fe28da2fa80e3ad56de52ed
[]
no_license
wxvincent/leetcode
https://github.com/wxvincent/leetcode
4baa1faef3eafd671dbd60e60d60eef56649a1e9
1d5f0926b9b9670689ab0da91ada0a478eaba24a
refs/heads/master
2020-05-18T22:07:12.846000
2020-03-06T02:16:37
2020-03-06T02:16:37
184,682,300
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package cn.itwx.leetcode31_40; public class Leetcode36 { public boolean isValidSudoku(char[][] board) { for (int i = 0; i < board.length; i++) { for (int j = 0; j < board[0].length; j++) { if (!isValid(board, i, j)) return false; } } return true; } private boolean isValid(char[][] board, int row, int col) { if (board[row][col] == '.') return true; for (int i = 0; i < board.length; i++) { if (i != row && board[i][col] == board[row][col]) { return false; } } for (int i = 0; i < board[0].length; i++) { if (i != col && board[row][i] == board[row][col]) { return false; } } int rowOfB = row / 3; int colOfB = col / 3; for (int i = rowOfB * 3; i < rowOfB * 3 + 3; i++) { for (int j = colOfB * 3; j < colOfB * 3 + 3; j++) { //注意此时行和列都已经被判断过了 if (i != row && j != col && board[i][j] == board[row][col]) { return false; } } } return true; } }
UTF-8
Java
1,207
java
Leetcode36.java
Java
[]
null
[]
package cn.itwx.leetcode31_40; public class Leetcode36 { public boolean isValidSudoku(char[][] board) { for (int i = 0; i < board.length; i++) { for (int j = 0; j < board[0].length; j++) { if (!isValid(board, i, j)) return false; } } return true; } private boolean isValid(char[][] board, int row, int col) { if (board[row][col] == '.') return true; for (int i = 0; i < board.length; i++) { if (i != row && board[i][col] == board[row][col]) { return false; } } for (int i = 0; i < board[0].length; i++) { if (i != col && board[row][i] == board[row][col]) { return false; } } int rowOfB = row / 3; int colOfB = col / 3; for (int i = rowOfB * 3; i < rowOfB * 3 + 3; i++) { for (int j = colOfB * 3; j < colOfB * 3 + 3; j++) { //注意此时行和列都已经被判断过了 if (i != row && j != col && board[i][j] == board[row][col]) { return false; } } } return true; } }
1,207
0.408666
0.391674
40
28.424999
22.554255
77
false
false
0
0
0
0
0
0
0.65
false
false
10
02a1fd7dd15db65baefe17ee04662a44f7875847
9,552,007,331,479
8c47496eadb507c8c7357d46dfbbd197cc6cfb03
/examples/examples-kitchen-sink/src/main/java/com/digitalsanctum/mw/examples/kitchensink/handler/KitchenSinkRouteHandler.java
f792a18b0844d06603679fcb673bf4a09e19d58b
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
digitalsanctum/minimalist-web
https://github.com/digitalsanctum/minimalist-web
07c4511c4e1b551831c2b543716f128bfa3a26ac
1881d3757ea45dbc2545778dcc3ab6b063b37b5a
refs/heads/master
2016-07-26T13:52:33.833000
2014-07-04T14:10:46
2014-07-04T14:10:46
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.digitalsanctum.mw.examples.kitchensink.handler; import com.digitalsanctum.mw.api.Model; import com.digitalsanctum.mw.core.route.GetRouteHandler; import com.digitalsanctum.mw.data.DataSourceProviderFactory; import com.digitalsanctum.mw.examples.kitchensink.dao.PersonMapper; import com.digitalsanctum.mw.examples.kitchensink.model.Person; import com.digitalsanctum.mw.view.thymeleaf.Thymeleaf; import com.digitalsanctum.mw.views.Renderer; import com.google.inject.Inject; import org.skife.jdbi.v2.DBI; import org.skife.jdbi.v2.Handle; import org.skife.jdbi.v2.Query; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.sql.DataSource; import java.io.IOException; import java.util.List; public class KitchenSinkRouteHandler extends GetRouteHandler { @Inject @Thymeleaf private Renderer renderer; @javax.inject.Inject private DataSourceProviderFactory dataSourceProviderFactory; public KitchenSinkRouteHandler(String path) { super(path); } @Override public void handle(HttpServletRequest request, HttpServletResponse response) throws IOException { Model model = getModel() .add("people", getPeopleDbiFluentApi()) .add("title", "Kitchen Sink Example"); renderer.render("index", model, response.getWriter()); } private List<Person> getPeopleDbiFluentApi() { DataSource dataSource = dataSourceProviderFactory.get("hsqldb-ds").get(); DBI dbi = new DBI(dataSource); Handle h = dbi.open(); h.registerMapper(new PersonMapper()); Query<Person> results = h.createQuery("select * from person") .map(PersonMapper.class).mapTo(Person.class); List<Person> people = results.list(); h.close(); return people; } }
UTF-8
Java
1,854
java
KitchenSinkRouteHandler.java
Java
[]
null
[]
package com.digitalsanctum.mw.examples.kitchensink.handler; import com.digitalsanctum.mw.api.Model; import com.digitalsanctum.mw.core.route.GetRouteHandler; import com.digitalsanctum.mw.data.DataSourceProviderFactory; import com.digitalsanctum.mw.examples.kitchensink.dao.PersonMapper; import com.digitalsanctum.mw.examples.kitchensink.model.Person; import com.digitalsanctum.mw.view.thymeleaf.Thymeleaf; import com.digitalsanctum.mw.views.Renderer; import com.google.inject.Inject; import org.skife.jdbi.v2.DBI; import org.skife.jdbi.v2.Handle; import org.skife.jdbi.v2.Query; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.sql.DataSource; import java.io.IOException; import java.util.List; public class KitchenSinkRouteHandler extends GetRouteHandler { @Inject @Thymeleaf private Renderer renderer; @javax.inject.Inject private DataSourceProviderFactory dataSourceProviderFactory; public KitchenSinkRouteHandler(String path) { super(path); } @Override public void handle(HttpServletRequest request, HttpServletResponse response) throws IOException { Model model = getModel() .add("people", getPeopleDbiFluentApi()) .add("title", "Kitchen Sink Example"); renderer.render("index", model, response.getWriter()); } private List<Person> getPeopleDbiFluentApi() { DataSource dataSource = dataSourceProviderFactory.get("hsqldb-ds").get(); DBI dbi = new DBI(dataSource); Handle h = dbi.open(); h.registerMapper(new PersonMapper()); Query<Person> results = h.createQuery("select * from person") .map(PersonMapper.class).mapTo(Person.class); List<Person> people = results.list(); h.close(); return people; } }
1,854
0.727077
0.725458
54
33.333332
24.933245
101
false
false
0
0
0
0
0
0
0.648148
false
false
10
2fc9454eb369195c0eb561a233973436ad5f4b1f
13,950,053,835,489
94034dc0b041de296897385c8889793d7e488ea0
/justshopme-shop-cart/src/main/java/com/justshopme/shopping/models/PurchaseItem.java
4981a0852d6f705bd02aaf204c7acf085d45f349
[]
no_license
balakondepudi/springboot-microservices
https://github.com/balakondepudi/springboot-microservices
c14c65d214f3a00c447297a0eddd8e6893e77c33
1702f43798f7da13323b9e2f7a22f086febeea9c
refs/heads/main
2023-02-13T17:50:04.506000
2021-01-09T23:37:33
2021-01-09T23:37:33
327,946,517
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.justshopme.shopping.models; public class PurchaseItem { private int count; private Product product; public PurchaseItem(int count, Product product) { super(); this.count = count; this.product = product; } public int getCount() { return count; } public void setCount(int count) { this.count = count; } public Product getProduct() { return product; } public void setProduct(Product product) { this.product = product; } @Override public String toString() { return "Purchase [count=" + count + ", product=" + product + "]"; } }
UTF-8
Java
575
java
PurchaseItem.java
Java
[]
null
[]
package com.justshopme.shopping.models; public class PurchaseItem { private int count; private Product product; public PurchaseItem(int count, Product product) { super(); this.count = count; this.product = product; } public int getCount() { return count; } public void setCount(int count) { this.count = count; } public Product getProduct() { return product; } public void setProduct(Product product) { this.product = product; } @Override public String toString() { return "Purchase [count=" + count + ", product=" + product + "]"; } }
575
0.681739
0.681739
31
17.548388
16.730961
67
false
false
0
0
0
0
0
0
1.516129
false
false
10
3dbae432eee91b09231df92bb116751d37b18690
23,433,341,582,274
9242f20eead58a0f71b47504840a13b148f19245
/src/main/java/com/faforever/moderatorclient/ui/domain/MapFX.java
c3e69163012dfb0f708866c0ca1d44457bd9cc92
[ "MIT" ]
permissive
Rackover/faf-moderator-client
https://github.com/Rackover/faf-moderator-client
60df34a1d28d6d152f2f22fcb26e6767fc9966e8
c8bac1c592e5c7e3ac03e5f9319884415353c505
refs/heads/master
2020-05-27T00:29:06.612000
2019-02-20T21:02:51
2019-02-20T21:02:51
188,424,867
0
0
null
true
2019-05-24T13:17:17
2019-05-24T13:17:17
2019-02-20T21:03:18
2019-02-20T21:03:44
682
0
0
0
null
false
false
package com.faforever.moderatorclient.ui.domain; import javafx.beans.property.ObjectProperty; import javafx.beans.property.SimpleObjectProperty; import javafx.beans.property.SimpleStringProperty; import javafx.beans.property.StringProperty; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import java.time.OffsetDateTime; import java.util.List; public class MapFX extends AbstractEntityFX { private final StringProperty id; private final StringProperty battleType; private final ObjectProperty<OffsetDateTime> createTime; private final ObjectProperty<OffsetDateTime> updateTime; private final StringProperty displayName; private final ObjectProperty<PlayerFX> author; private final StringProperty mapType; private final ObjectProperty<MapVersionFX> latestVersion; private final ObservableList<MapVersionFX> versions; public MapFX() { id = new SimpleStringProperty(); battleType = new SimpleStringProperty(); createTime = new SimpleObjectProperty<>(); updateTime = new SimpleObjectProperty<>(); displayName = new SimpleStringProperty(); author = new SimpleObjectProperty<>(); mapType = new SimpleStringProperty(); latestVersion = new SimpleObjectProperty<>(); versions = FXCollections.observableArrayList(); } @Override public String getId() { return id.get(); } public void setId(String id) { this.id.set(id); } @Override public StringProperty idProperty() { return id; } public String getBattleType() { return battleType.get(); } public void setBattleType(String battleType) { this.battleType.set(battleType); } public StringProperty battleTypeProperty() { return battleType; } @Override public OffsetDateTime getCreateTime() { return createTime.get(); } public void setCreateTime(OffsetDateTime createTime) { this.createTime.set(createTime); } @Override public ObjectProperty<OffsetDateTime> createTimeProperty() { return createTime; } @Override public OffsetDateTime getUpdateTime() { return updateTime.get(); } public void setUpdateTime(OffsetDateTime updateTime) { this.updateTime.set(updateTime); } @Override public ObjectProperty<OffsetDateTime> updateTimeProperty() { return updateTime; } public String getDisplayName() { return displayName.get(); } public void setDisplayName(String displayName) { this.displayName.set(displayName); } public StringProperty displayNameProperty() { return displayName; } public PlayerFX getAuthor() { return author.get(); } public void setAuthor(PlayerFX author) { this.author.set(author); } public ObjectProperty<PlayerFX> authorProperty() { return author; } public String getMapType() { return mapType.get(); } public void setMapType(String mapType) { this.mapType.set(mapType); } public StringProperty mapTypeProperty() { return mapType; } public MapVersionFX getLatestVersion() { return latestVersion.get(); } public void setLatestVersion(MapVersionFX latestVersion) { this.latestVersion.set(latestVersion); } public ObjectProperty<MapVersionFX> latestVersionProperty() { return latestVersion; } public ObservableList<MapVersionFX> getVersions() { return versions; } public void setVersions(List<MapVersionFX> versionFXList) { versions.clear(); if (versionFXList != null) { versions.addAll(versionFXList); } } // @Relationship("author") // private Player author; // // @Relationship("statistics") // private MapStatistics statistics; }
UTF-8
Java
3,949
java
MapFX.java
Java
[]
null
[]
package com.faforever.moderatorclient.ui.domain; import javafx.beans.property.ObjectProperty; import javafx.beans.property.SimpleObjectProperty; import javafx.beans.property.SimpleStringProperty; import javafx.beans.property.StringProperty; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import java.time.OffsetDateTime; import java.util.List; public class MapFX extends AbstractEntityFX { private final StringProperty id; private final StringProperty battleType; private final ObjectProperty<OffsetDateTime> createTime; private final ObjectProperty<OffsetDateTime> updateTime; private final StringProperty displayName; private final ObjectProperty<PlayerFX> author; private final StringProperty mapType; private final ObjectProperty<MapVersionFX> latestVersion; private final ObservableList<MapVersionFX> versions; public MapFX() { id = new SimpleStringProperty(); battleType = new SimpleStringProperty(); createTime = new SimpleObjectProperty<>(); updateTime = new SimpleObjectProperty<>(); displayName = new SimpleStringProperty(); author = new SimpleObjectProperty<>(); mapType = new SimpleStringProperty(); latestVersion = new SimpleObjectProperty<>(); versions = FXCollections.observableArrayList(); } @Override public String getId() { return id.get(); } public void setId(String id) { this.id.set(id); } @Override public StringProperty idProperty() { return id; } public String getBattleType() { return battleType.get(); } public void setBattleType(String battleType) { this.battleType.set(battleType); } public StringProperty battleTypeProperty() { return battleType; } @Override public OffsetDateTime getCreateTime() { return createTime.get(); } public void setCreateTime(OffsetDateTime createTime) { this.createTime.set(createTime); } @Override public ObjectProperty<OffsetDateTime> createTimeProperty() { return createTime; } @Override public OffsetDateTime getUpdateTime() { return updateTime.get(); } public void setUpdateTime(OffsetDateTime updateTime) { this.updateTime.set(updateTime); } @Override public ObjectProperty<OffsetDateTime> updateTimeProperty() { return updateTime; } public String getDisplayName() { return displayName.get(); } public void setDisplayName(String displayName) { this.displayName.set(displayName); } public StringProperty displayNameProperty() { return displayName; } public PlayerFX getAuthor() { return author.get(); } public void setAuthor(PlayerFX author) { this.author.set(author); } public ObjectProperty<PlayerFX> authorProperty() { return author; } public String getMapType() { return mapType.get(); } public void setMapType(String mapType) { this.mapType.set(mapType); } public StringProperty mapTypeProperty() { return mapType; } public MapVersionFX getLatestVersion() { return latestVersion.get(); } public void setLatestVersion(MapVersionFX latestVersion) { this.latestVersion.set(latestVersion); } public ObjectProperty<MapVersionFX> latestVersionProperty() { return latestVersion; } public ObservableList<MapVersionFX> getVersions() { return versions; } public void setVersions(List<MapVersionFX> versionFXList) { versions.clear(); if (versionFXList != null) { versions.addAll(versionFXList); } } // @Relationship("author") // private Player author; // // @Relationship("statistics") // private MapStatistics statistics; }
3,949
0.675108
0.675108
156
24.314102
20.872263
65
false
false
0
0
0
0
0
0
0.358974
false
false
10
d7142d8ab684989d918eac096e2a84356b72742e
21,534,966,072,936
4e61c876b9ee3b98cf400c65a1bd87a3fc3b7bec
/src/main/java/pl/piomin/service/blockchain/service/BlockchainService.java
c0a52391465b28db764a71245e0ed54f57965cb0
[]
no_license
piomin/sample-spring-blockchain
https://github.com/piomin/sample-spring-blockchain
f2d2d26f73672a788eb19f18458247bf1ed44fbc
44e9061e13537ac02fed41439ea3fc1c10f0099e
refs/heads/master
2023-08-10T17:22:30.838000
2023-08-07T00:15:35
2023-08-07T05:08:02
137,475,287
98
79
null
false
2023-08-24T16:27:25
2018-06-15T10:34:59
2023-08-13T05:06:51
2023-08-24T16:27:24
33
91
79
2
Java
false
false
package pl.piomin.service.blockchain.service; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; import org.web3j.protocol.Web3j; import org.web3j.protocol.core.DefaultBlockParameterName; import org.web3j.protocol.core.methods.request.Transaction; import org.web3j.protocol.core.methods.response.EthAccounts; import org.web3j.protocol.core.methods.response.EthGetTransactionCount; import org.web3j.protocol.core.methods.response.EthGetTransactionReceipt; import org.web3j.protocol.core.methods.response.EthSendTransaction; import pl.piomin.service.blockchain.model.BlockchainTransaction; import java.io.IOException; import java.math.BigInteger; @Service public class BlockchainService { private static final Logger LOGGER = LoggerFactory.getLogger(BlockchainService.class); private final Web3j web3j; public BlockchainService(Web3j web3j) { this.web3j = web3j; } public BlockchainTransaction process(BlockchainTransaction trx) throws IOException { EthAccounts accounts = web3j.ethAccounts().send(); EthGetTransactionCount transactionCount = web3j.ethGetTransactionCount(accounts.getAccounts().get(trx.getFromId()), DefaultBlockParameterName.LATEST).send(); Transaction transaction = Transaction.createEtherTransaction( accounts.getAccounts().get(trx.getFromId()), transactionCount.getTransactionCount(), BigInteger.valueOf(trx.getValue()), BigInteger.valueOf(21_000), accounts.getAccounts().get(trx.getToId()), BigInteger.valueOf(trx.getValue())); EthSendTransaction response = web3j.ethSendTransaction(transaction).send(); if (response.getError() != null) { trx.setAccepted(false); LOGGER.info("Tx rejected: {}", response.getError().getMessage()); return trx; } trx.setAccepted(true); String txHash = response.getTransactionHash(); LOGGER.info("Tx hash: {}", txHash); trx.setId(txHash); EthGetTransactionReceipt receipt = web3j.ethGetTransactionReceipt(txHash).send(); receipt.getTransactionReceipt().ifPresent(transactionReceipt -> LOGGER.info("Tx receipt: {}", transactionReceipt.getCumulativeGasUsed().intValue())); return trx; } }
UTF-8
Java
2,311
java
BlockchainService.java
Java
[]
null
[]
package pl.piomin.service.blockchain.service; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; import org.web3j.protocol.Web3j; import org.web3j.protocol.core.DefaultBlockParameterName; import org.web3j.protocol.core.methods.request.Transaction; import org.web3j.protocol.core.methods.response.EthAccounts; import org.web3j.protocol.core.methods.response.EthGetTransactionCount; import org.web3j.protocol.core.methods.response.EthGetTransactionReceipt; import org.web3j.protocol.core.methods.response.EthSendTransaction; import pl.piomin.service.blockchain.model.BlockchainTransaction; import java.io.IOException; import java.math.BigInteger; @Service public class BlockchainService { private static final Logger LOGGER = LoggerFactory.getLogger(BlockchainService.class); private final Web3j web3j; public BlockchainService(Web3j web3j) { this.web3j = web3j; } public BlockchainTransaction process(BlockchainTransaction trx) throws IOException { EthAccounts accounts = web3j.ethAccounts().send(); EthGetTransactionCount transactionCount = web3j.ethGetTransactionCount(accounts.getAccounts().get(trx.getFromId()), DefaultBlockParameterName.LATEST).send(); Transaction transaction = Transaction.createEtherTransaction( accounts.getAccounts().get(trx.getFromId()), transactionCount.getTransactionCount(), BigInteger.valueOf(trx.getValue()), BigInteger.valueOf(21_000), accounts.getAccounts().get(trx.getToId()), BigInteger.valueOf(trx.getValue())); EthSendTransaction response = web3j.ethSendTransaction(transaction).send(); if (response.getError() != null) { trx.setAccepted(false); LOGGER.info("Tx rejected: {}", response.getError().getMessage()); return trx; } trx.setAccepted(true); String txHash = response.getTransactionHash(); LOGGER.info("Tx hash: {}", txHash); trx.setId(txHash); EthGetTransactionReceipt receipt = web3j.ethGetTransactionReceipt(txHash).send(); receipt.getTransactionReceipt().ifPresent(transactionReceipt -> LOGGER.info("Tx receipt: {}", transactionReceipt.getCumulativeGasUsed().intValue())); return trx; } }
2,311
0.739939
0.729122
59
38.169491
40.543407
165
false
false
0
0
0
0
0
0
0.677966
false
false
10
303718656cae412e0d63b9d790e19faaf3127e21
85,899,397,139
d33935ff514b1ab42c81a388ec464cd21c9349de
/src/main/java/com/lqx/service/user/UserService.java
0574e4a704788badb16ea31690ccc8dbc181805c
[]
no_license
gabylqx/game
https://github.com/gabylqx/game
e31750311119bd564b8a3168b2f11f363eb21139
36a0f3b0cc63f366645e075eda52603f0b166bac
refs/heads/master
2020-09-08T15:00:28.322000
2019-11-12T08:35:47
2019-11-12T08:35:47
221,166,663
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.lqx.service.user; import com.game.dao.user.model.User; import com.lqx.dao.user.req.UserReq; import java.util.List; import java.math.BigDecimal; import java.sql.Time; /** * user业务接口定义 * @author 李其璇 * @date 2019/11/12 15:28 */ public interface UserService { /** * 根据ID查询 * @author 李其璇 * @date 2019/11/12 15:28 */ User findById(Integer id); /** * 根据ID集查询 * @author 李其璇 * @date 2019/11/12 15:28 */ List<User> findByIds(List<Integer> ids); /** * 创建 * @author 李其璇 * @date 2019/11/12 15:28 */ Integer create(UserReq req); /** * 根据ID删除 * @author 李其璇 * @date 2019/11/12 15:28 */ void deleteById(Integer id); /** * 根据ID集删除 * @author 李其璇 * @date 2019/11/12 15:28 */ void deleteByIds(List<Integer> ids); /** * 根据ID更新 * @author 李其璇 * @date 2019/11/12 15:28 */ void updateById(UserReq req); }
UTF-8
Java
1,074
java
UserService.java
Java
[ { "context": "port java.sql.Time;\n\n/**\n * user业务接口定义\n * @author 李其璇\n * @date 2019/11/12 15:28\n */\npublic interface Us", "end": 213, "score": 0.9998756647109985, "start": 210, "tag": "NAME", "value": "李其璇" }, { "context": "erService {\n\n /**\n * 根据ID查询\n * @author 李...
null
[]
package com.lqx.service.user; import com.game.dao.user.model.User; import com.lqx.dao.user.req.UserReq; import java.util.List; import java.math.BigDecimal; import java.sql.Time; /** * user业务接口定义 * @author 李其璇 * @date 2019/11/12 15:28 */ public interface UserService { /** * 根据ID查询 * @author 李其璇 * @date 2019/11/12 15:28 */ User findById(Integer id); /** * 根据ID集查询 * @author 李其璇 * @date 2019/11/12 15:28 */ List<User> findByIds(List<Integer> ids); /** * 创建 * @author 李其璇 * @date 2019/11/12 15:28 */ Integer create(UserReq req); /** * 根据ID删除 * @author 李其璇 * @date 2019/11/12 15:28 */ void deleteById(Integer id); /** * 根据ID集删除 * @author 李其璇 * @date 2019/11/12 15:28 */ void deleteByIds(List<Integer> ids); /** * 根据ID更新 * @author 李其璇 * @date 2019/11/12 15:28 */ void updateById(UserReq req); }
1,074
0.552469
0.466049
59
15.491526
12.366402
44
false
false
0
0
0
0
0
0
0.20339
false
false
10
cbc5d1565129377b97cca5f8bc13f250cc0f9ff7
12,524,124,636,061
ec819f63d3a1ea44dbf647ceaaf42c2b684724de
/app/src/main/java/daluobo/insplash/adapter/vh/PhotoViewHolder.java
110e9efe0e06eb187387e46fd2b810e353c3105c
[]
no_license
daluobo/Insplash
https://github.com/daluobo/Insplash
bcfe96dc94b8e1b8fa86193b3925658ce6e09d19
1ba7699b9de4de52320fb6009cbb60ebf174a7b9
refs/heads/master
2021-09-04T19:01:24.803000
2018-01-21T12:09:22
2018-01-21T12:09:22
110,432,673
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package daluobo.insplash.adapter.vh; import android.content.Context; import android.graphics.Color; import android.graphics.drawable.Drawable; import android.support.v7.widget.RecyclerView; import android.view.Gravity; import android.view.View; import android.view.animation.AnimationUtils; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.TextSwitcher; import android.widget.TextView; import android.widget.ViewSwitcher; import butterknife.BindColor; import butterknife.BindDrawable; import butterknife.BindString; import butterknife.BindView; import butterknife.ButterKnife; import daluobo.insplash.R; import daluobo.insplash.adapter.listener.OnActionClickListener; import daluobo.insplash.model.net.Photo; import daluobo.insplash.util.ViewUtil; /** * Created by daluobo on 2017/12/29. */ public abstract class PhotoViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener { @BindView(R.id.photo_view) public ImageView mPhotoView; @BindView(R.id.progress_bar) public ProgressBar mProgressBar; @BindView(R.id.like_btn) public ImageView mLikeBtn; @BindView(R.id.likes) public TextSwitcher mLikes; @BindColor(R.color.colorAccent) public int mColorAccent; @BindColor(R.color.colorTitle) public int mColorTitle; @BindDrawable(R.drawable.ic_favorite_border) public Drawable mIcFavoriteBorder; @BindDrawable(R.drawable.ic_favorite) public Drawable mIcFavorite; @BindString(R.string.msg_please_login) public String mMsgPleaseLogin; TextView mLikeText; OnActionClickListener mOnActionClickListener; Context mContext; Photo mPhoto; int mPosition; public PhotoViewHolder(View itemView, Context context) { super(itemView); ButterKnife.bind(this, itemView); mContext = context; mIcFavorite = ViewUtil.tintDrawable(mIcFavorite, mColorAccent); mPhotoView.setOnClickListener(this); mLikes.setInAnimation(AnimationUtils.loadAnimation(mContext, R.anim.slide_form_bottom)); mLikes.setOutAnimation(AnimationUtils.loadAnimation(mContext, R.anim.slide_to_top)); mLikes.setFactory(new ViewSwitcher.ViewFactory() { @Override public View makeView() { mLikeText = new TextView(mContext); mLikeText.setLayoutParams(new TextSwitcher.LayoutParams(TextSwitcher.LayoutParams.MATCH_PARENT, TextSwitcher.LayoutParams.MATCH_PARENT)); mLikeText.setGravity(Gravity.CENTER); mLikeText.setBackgroundColor(Color.TRANSPARENT); mLikeText.setTextColor(mColorTitle); return mLikeText; } }); } }
UTF-8
Java
2,731
java
PhotoViewHolder.java
Java
[ { "context": "daluobo.insplash.util.ViewUtil;\n\n/**\n * Created by daluobo on 2017/12/29.\n */\n\npublic abstract class PhotoVi", "end": 817, "score": 0.9996654987335205, "start": 810, "tag": "USERNAME", "value": "daluobo" } ]
null
[]
package daluobo.insplash.adapter.vh; import android.content.Context; import android.graphics.Color; import android.graphics.drawable.Drawable; import android.support.v7.widget.RecyclerView; import android.view.Gravity; import android.view.View; import android.view.animation.AnimationUtils; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.TextSwitcher; import android.widget.TextView; import android.widget.ViewSwitcher; import butterknife.BindColor; import butterknife.BindDrawable; import butterknife.BindString; import butterknife.BindView; import butterknife.ButterKnife; import daluobo.insplash.R; import daluobo.insplash.adapter.listener.OnActionClickListener; import daluobo.insplash.model.net.Photo; import daluobo.insplash.util.ViewUtil; /** * Created by daluobo on 2017/12/29. */ public abstract class PhotoViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener { @BindView(R.id.photo_view) public ImageView mPhotoView; @BindView(R.id.progress_bar) public ProgressBar mProgressBar; @BindView(R.id.like_btn) public ImageView mLikeBtn; @BindView(R.id.likes) public TextSwitcher mLikes; @BindColor(R.color.colorAccent) public int mColorAccent; @BindColor(R.color.colorTitle) public int mColorTitle; @BindDrawable(R.drawable.ic_favorite_border) public Drawable mIcFavoriteBorder; @BindDrawable(R.drawable.ic_favorite) public Drawable mIcFavorite; @BindString(R.string.msg_please_login) public String mMsgPleaseLogin; TextView mLikeText; OnActionClickListener mOnActionClickListener; Context mContext; Photo mPhoto; int mPosition; public PhotoViewHolder(View itemView, Context context) { super(itemView); ButterKnife.bind(this, itemView); mContext = context; mIcFavorite = ViewUtil.tintDrawable(mIcFavorite, mColorAccent); mPhotoView.setOnClickListener(this); mLikes.setInAnimation(AnimationUtils.loadAnimation(mContext, R.anim.slide_form_bottom)); mLikes.setOutAnimation(AnimationUtils.loadAnimation(mContext, R.anim.slide_to_top)); mLikes.setFactory(new ViewSwitcher.ViewFactory() { @Override public View makeView() { mLikeText = new TextView(mContext); mLikeText.setLayoutParams(new TextSwitcher.LayoutParams(TextSwitcher.LayoutParams.MATCH_PARENT, TextSwitcher.LayoutParams.MATCH_PARENT)); mLikeText.setGravity(Gravity.CENTER); mLikeText.setBackgroundColor(Color.TRANSPARENT); mLikeText.setTextColor(mColorTitle); return mLikeText; } }); } }
2,731
0.737459
0.734163
82
32.304878
25.361143
153
false
false
0
0
0
0
0
0
0.682927
false
false
10