blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 4
410
| content_id
stringlengths 40
40
| detected_licenses
sequencelengths 0
51
| license_type
stringclasses 2
values | repo_name
stringlengths 5
132
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringlengths 4
80
| visit_date
timestamp[us] | revision_date
timestamp[us] | committer_date
timestamp[us] | github_id
int64 5.85k
689M
⌀ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 22
values | gha_event_created_at
timestamp[us] | gha_created_at
timestamp[us] | gha_language
stringclasses 131
values | src_encoding
stringclasses 34
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 2
classes | length_bytes
int64 3
9.45M
| extension
stringclasses 32
values | content
stringlengths 3
9.45M
| authors
sequencelengths 1
1
| author_id
stringlengths 0
313
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1d32a777e75bde6142ae1803e1d73eafa43bd871 | da96c59eec66a1ee89062cfd9d84089a0870c215 | /src/interviews/questions/amazon/PermutationsOfString.java | f2ff2e3b12f9b40ad1870e734a070db174640f5a | [] | no_license | jstrain668/Data-Structures-and-Algorithms--using-JAVA | aa1bb290c24f66ecc53d315027239ff1aea7e4df | fe8bc9c8f1e0def5cec0f2c6f7abd99dca062780 | refs/heads/master | 2023-07-31T19:08:22.989851 | 2021-09-10T17:56:52 | 2021-09-10T17:56:52 | 364,971,606 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 76 | java | package interviews.questions.amazon;
public class PermutationsOfString {
}
| [
"[email protected]"
] | |
c484448e945b327b875835c9601a2232738d663d | ef723d4bcf7906b4250ecf860356efefd6125169 | /src/main/com/parser/XmlWriter.java | 33a430635e0b697b5a43d13215a890d0bda33117 | [] | no_license | kluma007/GEDCOM_Parser_Coding_Challenge | 55857c942c4cd5d1e52f791f48f041ad4d426de0 | 45604d296bf97c9ba083793afd7c57f3735e889b | refs/heads/master | 2020-06-14T00:27:32.761412 | 2016-12-04T19:07:00 | 2016-12-04T19:07:00 | 75,538,972 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 5,669 | java | package main.com.parser;
import java.io.File;
import java.util.List;
import java.util.Map;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import main.com.model.ChildXmlNode;
import main.com.model.ParentXmlNode;
import main.com.util.GedComConstants;
import main.com.util.GedComUtil;
/**
* This Class is used to write the data into XML file
*
* @author Uma KL
*
*/
public class XmlWriter {
private File inputFile;
private File outputFile;
private Map<ParentXmlNode,List<ChildXmlNode>> xmlNodeMap;
/**
* Constructor for XmlWriter
* @param inputFile
* @param outputFile
*/
public XmlWriter(String inputFile, String outputFile) {
this.inputFile = new File(inputFile);
this.outputFile = new File(outputFile);
}
/**
* This method calls a Parser to parse the input data
* and writes it to the XML file.
* @throws ParserConfigurationException
*/
public void generateXmlFile() throws ParserConfigurationException
{
GedComParser gedComParser = new GedComParser(inputFile);
xmlNodeMap = gedComParser.generateXmlNodeMap();
writeToXmlFile(xmlNodeMap);
}
/**
* This method creates XML Document object, loads the XML document object
* with the XML Nodes and writes the XML document object to the output file.
*
* @param xmlNodeMap
* @throws ParserConfigurationException
*/
public void writeToXmlFile(Map<ParentXmlNode,List<ChildXmlNode>> xmlNodeMap) throws ParserConfigurationException
{
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = docFactory.newDocumentBuilder();
Document xmlDocument = builder.newDocument();
loadXmlDocument(xmlDocument,xmlNodeMap);
writeToFile(xmlDocument,outputFile);
}
/**
* This method loads the XML document object with the XML Nodes.
*
* @param xmlDocument
* @param xmlNodeMap
*/
private void loadXmlDocument(Document xmlDocument, Map<ParentXmlNode, List<ChildXmlNode>> xmlNodeMap) {
// TODO Auto-generated method stub
if(xmlNodeMap != null && xmlNodeMap.entrySet() != null && xmlNodeMap.entrySet().size() > 0 && xmlDocument != null){
Element rootElement = xmlDocument.createElement(GedComConstants.GEDCOM_TAG_NAME);
xmlDocument.appendChild(rootElement);
for (Map.Entry<ParentXmlNode, List<ChildXmlNode>> entry : xmlNodeMap.entrySet()) {
ParentXmlNode parentXmlNode = entry.getKey();
if(GedComUtil.isValidTag(parentXmlNode.getTagName()))
{
Element parentElement = xmlDocument.createElement(parentXmlNode.getTagName().toLowerCase());
if(GedComUtil.isValidAttribute(parentXmlNode.getAttributeName()))
{
parentElement.setAttribute(parentXmlNode.getAttributeName(), parentXmlNode.getAttributeValue());
}
if(entry.getValue() != null){
for (ChildXmlNode childXmlNode : entry.getValue()) {
addChildXmlNodes(parentElement, childXmlNode, xmlDocument);
}
}
rootElement.appendChild(parentElement);
}
}
}
}
/**
* This method is used to add the Child XML Nodes along with recursion
* if the child XML Node has children.
*
* @param parentElement
* @param childXmlNode
* @param xmlDocument
*/
private void addChildXmlNodes(Element parentElement, ChildXmlNode childXmlNode, Document xmlDocument) {
// TODO Auto-generated method stub
if(GedComUtil.isValidTag(childXmlNode.getTagName())){
Element childElement = xmlDocument.createElement(childXmlNode.getTagName().toLowerCase());
childElement.setTextContent(childXmlNode.getTagValue());
if(GedComUtil.isValidAttribute(childXmlNode.getAttributeName())){
childElement.setAttribute(childXmlNode.getAttributeName(), childXmlNode.getAttributeValue());
}
if (childXmlNode.hasChildren()) {
for (ChildXmlNode secondLevelChild : childXmlNode.getChildNodes()) {
addChildXmlNodes(childElement, secondLevelChild, xmlDocument);
}
}
parentElement.appendChild(childElement);
}
}
/**
* This method writes the XML document object to the output file.
*
* @param xmlDocument
* @param outputFile
*/
private void writeToFile(Document xmlDocument, File outputFile) {
// TODO Auto-generated method stub
if (xmlDocument == null || outputFile == null) {
throw new IllegalArgumentException("XmlDocument or the Output file is null.");
}
try {
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(xmlDocument);
StreamResult result = new StreamResult(outputFile);
transformer.transform(source, result);
} catch (TransformerConfigurationException e) {
e.printStackTrace();
} catch (TransformerException e) {
e.printStackTrace();
}
}
}
| [
"uma"
] | uma |
9cbd0ec590443a88e3bdbe5ac2078686d4458985 | 0038cf59c446e5085af4c519b9998fdb4b0fb4fe | /setsmaps/AbstractSet.java | 7613172270246301aac583451036c40ab6d5760b | [] | no_license | nicholas-d-alba/Algorithms-and-Data-Structures | 2889b3ab737e57ad7c136850e3d60a60dafae526 | 7f4bb25ef5973168cd5ed7c25f24cd6acadf4afe | refs/heads/master | 2021-08-03T09:50:48.613615 | 2017-04-26T03:46:27 | 2017-04-26T03:46:27 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 652 | java | package setsmaps;
import java.util.Collection;
public abstract class AbstractSet<E> implements Set<E> {
public void addAll(Collection<? extends E> source) throws NullPointerException {
for (E element: source)
add(element);
}
public boolean containsAll(Collection<? extends E> collection) throws NullPointerException {
for (E element: collection)
if (!contains(element))
return false;
return true;
}
public void removeAll(Collection<? extends E> collection) throws ClassCastException {
for (E element: collection)
remove(element);
}
public boolean isEmpty() {
return size() == 0;
}
}
| [
"[email protected]"
] | |
e1d2ecad794db9d1291f70b29243903eced98595 | 94093f14efa627b2fddf065d02a90624dd001d7e | /app/src/main/java/com/example/stephencao/findmylaptopfiles/PlayMediaFileActivity.java | 914dc63937fa85b4158078728b2974f7ead6280c | [] | no_license | rayray199085/FindMyLaptopFiles | 6b11c89587a2e146708498babf7e94201ce9e44c | 741509b646860a52702cb6fcddfb1689fc3b39e7 | refs/heads/master | 2020-04-07T06:35:40.064764 | 2018-11-19T00:51:42 | 2018-11-19T00:51:42 | 158,142,249 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 6,446 | java | package com.example.stephencao.findmylaptopfiles;
import android.content.Intent;
import android.graphics.Color;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Timer;
import java.util.TimerTask;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class PlayMediaFileActivity extends AppCompatActivity implements View.OnClickListener {
private Button playBtn, stopBtn,deleteBtn;
private TextView textView;
private String path;
private ProgressBar progressBar;
private String fileName;
private MediaPlayer mediaPlayer;
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
String mp3FilePath = (String) msg.obj;
try {
mediaPlayer.setDataSource(mp3FilePath);
mediaPlayer.prepare();
mediaPlayer.start();
progressBar.setMax(mediaPlayer.getDuration());
Timer timer = new Timer();
TimerTask timerTask = new TimerTask() {
@Override
public void run() {
if(mediaPlayer!=null&&mediaPlayer.isPlaying()){
new Thread(new SetProgressBarProgress()).start();
}
}
};
timer.schedule(timerTask,0,1000);
} catch (IOException e) {
e.printStackTrace();
}
}
};
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.music_view);
initView();
}
private void initView() {
mediaPlayer = new MediaPlayer();
progressBar = findViewById(R.id.progress_bar);
Intent intent = getIntent();
path = intent.getStringExtra("path");
String regex = "/[^/]+\\.mp3";
fileName = null;
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(path);
while (matcher.find()) {
fileName = matcher.group();
}
fileName = fileName.substring(1, fileName.length());
textView = findViewById(R.id.music_text_view);
textView.setText(fileName);
playBtn = findViewById(R.id.music_play_button);
playBtn.setOnClickListener(this);
stopBtn = findViewById(R.id.music_stop_btn);
stopBtn.setOnClickListener(this);
deleteBtn = findViewById(R.id.music_delete_file_button);
deleteBtn.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.music_play_button: {
new Thread(new GetMusicFile(path)).start();
playBtn.setVisibility(View.GONE);
break;
}
case R.id.music_stop_btn: {
if (mediaPlayer.isPlaying()) {
mediaPlayer.pause();
stopBtn.setText("Continue");
stopBtn.setTextColor(Color.YELLOW);
} else {
int position = mediaPlayer.getCurrentPosition();
mediaPlayer.seekTo(position);
mediaPlayer.start();
stopBtn.setText("Stop");
stopBtn.setTextColor(Color.RED);
}
break;
}
case R.id.music_delete_file_button:{
if(mediaPlayer.isPlaying()){
mediaPlayer.pause();
}
else{
mediaPlayer.stop();
}
File file = new File(Environment.getExternalStorageDirectory(),fileName);
if(file.exists()){
file.delete();
}
Toast.makeText(getApplicationContext(),"Delete Successfully",Toast.LENGTH_SHORT).show();
break;
}
}
}
class GetMusicFile implements Runnable {
private String urlPath;
public GetMusicFile(String urlPath) {
this.urlPath = urlPath;
String regex = "/";
this.urlPath = urlPath.replaceAll(regex, "%2F");
}
@Override
public void run() {
String linkPath = "http://192.168.0.3:8080/local_files_searching/my_delivery?path=" + urlPath;
HttpURLConnection httpURLConnection = null;
try {
URL url = new URL(linkPath);
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("GET");
httpURLConnection.setConnectTimeout(5000);
if (httpURLConnection.getResponseCode() == 200) {
InputStream inputStream = httpURLConnection.getInputStream();
File file = new File(Environment.getExternalStorageDirectory(), fileName);
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(file));
int len = 0;
byte[] buffer = new byte[1024];
while ((len = inputStream.read(buffer)) != -1) {
bufferedOutputStream.write(buffer, 0, len);
}
System.out.println(file.exists());
bufferedOutputStream.close();
inputStream.close();
Message message = Message.obtain();
message.obj = file.getAbsolutePath();
handler.sendMessage(message);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
class SetProgressBarProgress implements Runnable {
@Override
public void run() {
int location = mediaPlayer.getCurrentPosition();
progressBar.setProgress(location);
}
}
}
| [
"[email protected]"
] | |
6591611723a7e48e6bf8b73b917d76a56ccc3bdd | 57c6697e0e2df88b6987a70ea424a72d8564b358 | /src/main/java/com/study/test/lucene/LuceneManager.java | 2069603546241e06152ddb8094ea24fa12db490c | [] | no_license | wuhgogo/Tests | e7a97539417812660a7647b931f245b44132423f | f4599aeb4f6413b23564bc483317d624cfa18a4f | refs/heads/master | 2021-04-26T11:49:45.080705 | 2018-06-25T16:11:12 | 2018-06-25T16:11:12 | 124,005,467 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 6,470 | java | package com.study.test.lucene;
import static org.junit.Assert.*;
import java.io.File;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field.Store;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.Term;
import org.apache.lucene.queryparser.classic.MultiFieldQueryParser;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.BooleanClause.Occur;
import org.apache.lucene.search.BooleanQuery;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.MatchAllDocsQuery;
import org.apache.lucene.search.NumericRangeQuery;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;
import org.junit.Test;
import org.wltea.analyzer.lucene.IKAnalyzer;
/**
* 索引维护
* 添加 入门程序
* 删除
* 修改
* 查询 入门程序 精准查询
* @author lx
*
*/
public class LuceneManager {
//
public IndexWriter getIndexWriter() throws Exception{
// 第一步:创建一个java工程,并导入jar包。
// 第二步:创建一个indexwriter对象。
Directory directory = FSDirectory.open(new File("D:\\temp\\index"));
// Directory directory = new RAMDirectory();//保存索引到内存中 (内存索引库)
Analyzer analyzer = new StandardAnalyzer();// 官方推荐
IndexWriterConfig config = new IndexWriterConfig(Version.LATEST, analyzer);
return new IndexWriter(directory, config);
}
//全删除
@Test
public void testAllDelete() throws Exception {
IndexWriter indexWriter = getIndexWriter();
indexWriter.deleteAll();
indexWriter.close();
}
//根据条件删除
@Test
public void testDelete() throws Exception {
IndexWriter indexWriter = getIndexWriter();
Query query = new TermQuery(new Term("fileName","apache"));
indexWriter.deleteDocuments(query);
indexWriter.close();
}
//修改
@Test
public void testUpdate() throws Exception {
IndexWriter indexWriter = getIndexWriter();
Document doc = new Document();
doc.add(new TextField("fileN", "测试文件名",Store.YES));
doc.add(new TextField("fileC", "测试文件内容",Store.YES));
indexWriter.updateDocument(new Term("fileName","lucene"), doc, new IKAnalyzer());
indexWriter.close();
}
//IndexReader IndexSearcher
public IndexSearcher getIndexSearcher() throws Exception{
// 第一步:创建一个Directory对象,也就是索引库存放的位置。
Directory directory = FSDirectory.open(new File("D:\\temp\\index"));// 磁盘
// 第二步:创建一个indexReader对象,需要指定Directory对象。
IndexReader indexReader = DirectoryReader.open(directory);
// 第三步:创建一个indexsearcher对象,需要指定IndexReader对象
return new IndexSearcher(indexReader);
}
//执行查询的结果
public void printResult(IndexSearcher indexSearcher,Query query)throws Exception{
// 第五步:执行查询。
TopDocs topDocs = indexSearcher.search(query, 10);
// 第六步:返回查询结果。遍历查询结果并输出。
ScoreDoc[] scoreDocs = topDocs.scoreDocs;
for (ScoreDoc scoreDoc : scoreDocs) {
int doc = scoreDoc.doc;
Document document = indexSearcher.doc(doc);
// 文件名称
String fileName = document.get("fileName");
System.out.println(fileName);
// 文件内容
String fileContent = document.get("fileContent");
System.out.println(fileContent);
// 文件大小
String fileSize = document.get("fileSize");
System.out.println(fileSize);
// 文件路径
String filePath = document.get("filePath");
System.out.println(filePath);
System.out.println("------------");
}
}
//查询所有
@Test
public void testMatchAllDocsQuery() throws Exception {
IndexSearcher indexSearcher = getIndexSearcher();
Query query = new MatchAllDocsQuery();
System.out.println(query);
printResult(indexSearcher, query);
//关闭资源
indexSearcher.getIndexReader().close();
}
//根据数值范围查询
@Test
public void testNumericRangeQuery() throws Exception {
IndexSearcher indexSearcher = getIndexSearcher();
Query query = NumericRangeQuery.newLongRange("fileSize", 47L, 200L, false, true);
System.out.println(query);
printResult(indexSearcher, query);
//关闭资源
indexSearcher.getIndexReader().close();
}
//可以组合查询条件
@Test
public void testBooleanQuery() throws Exception {
IndexSearcher indexSearcher = getIndexSearcher();
BooleanQuery booleanQuery = new BooleanQuery();
Query query1 = new TermQuery(new Term("fileName","apache"));
Query query2 = new TermQuery(new Term("fileName","lucene"));
// select * from user where id =1 or name = 'safdsa'
booleanQuery.add(query1, Occur.MUST);
booleanQuery.add(query2, Occur.SHOULD);
System.out.println(booleanQuery);
printResult(indexSearcher, booleanQuery);
//关闭资源
indexSearcher.getIndexReader().close();
}
//条件解释的对象查询
@Test
public void testQueryParser() throws Exception {
IndexSearcher indexSearcher = getIndexSearcher();
//参数1: 默认查询的域
//参数2:采用的分析器
QueryParser queryParser = new QueryParser("fileName",new IKAnalyzer());
// *:* 域:值
Query query = queryParser.parse("fileName:lucene is apache OR fileContent:lucene is apache");
printResult(indexSearcher, query);
//关闭资源
indexSearcher.getIndexReader().close();
}
//条件解析的对象查询 多个默念域
@Test
public void testMultiFieldQueryParser() throws Exception {
IndexSearcher indexSearcher = getIndexSearcher();
String[] fields = {"fileName","fileContent"};
//参数1: 默认查询的域
//参数2:采用的分析器
MultiFieldQueryParser queryParser = new MultiFieldQueryParser(fields,new IKAnalyzer());
// *:* 域:值
Query query = queryParser.parse("lucene is apache");
printResult(indexSearcher, query);
//关闭资源
indexSearcher.getIndexReader().close();
}
}
| [
"guess what"
] | guess what |
96cce28ae1bc1d62216975e6bd1d756e4bf0e423 | 6eca8c8ed7a57d54f85525e05753216048e2a501 | /seidl_employeedb/src/bl/EmployeeTableModel.java | 9c769b2be004343483981cc797946b12934b7403 | [] | no_license | Ionas208/POS3 | 520d57c380580f1f363fe2f54ce21784fb418201 | 5f6b6e3f83986619d6c584573ceb56c01aab78ca | refs/heads/master | 2022-12-24T01:29:58.706611 | 2020-10-06T15:23:57 | 2020-10-06T15:23:57 | 271,790,211 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,920 | java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package bl;
import beans.Employee;
import database.DB_Access;
import java.sql.Date;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.LocalDate;
import java.time.Month;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.table.AbstractTableModel;
/**
*
* @author 10jon
*/
public class EmployeeTableModel extends AbstractTableModel {
private ResultSet rs;
private DB_Access dba = DB_Access.getInstance();
private List<String> colNames = Arrays.asList("Name", "Gender", "Birthdate", "Hiredate", "ID");
public boolean allowed = true;
public EmployeeTableModel() throws SQLException {
rs = dba.getEmployess(false, false, false, null, null, null);
}
@Override
public int getRowCount() {
try {
rs.last();
return rs.getRow();
} catch (SQLException ex) {
return 0;
}
}
@Override
public int getColumnCount() {
return colNames.size();
}
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
try {
rs.absolute(rowIndex + 1);
switch (columnIndex) {
case 0:
return rs.getString("last_name") + ", " + rs.getString("first_name");
case 1:
return rs.getString("gender");
case 2:
return rs.getDate("birth_date").toLocalDate().toString();
case 3:
return rs.getDate("hire_date").toLocalDate().toString();
case 4:
return rs.getInt("emp_no");
default:
return 0;
}
} catch (SQLException ex) {
ex.printStackTrace();
}
return "error";
}
public void filter(boolean filterByDept, boolean filterByGender, boolean filterByDate, String deptname, String gender, LocalDate dateBefore) throws SQLException {
rs = dba.getEmployess(filterByDept, filterByGender, filterByDate, deptname, gender, dateBefore);
allowed = false;
this.fireTableDataChanged();
allowed = true;
}
@Override
public String getColumnName(int column) {
return colNames.get(column);
}
@Override
public boolean isCellEditable(int row, int column) {
return !(column == 1);
}
@Override
public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
try {
rs.absolute(rowIndex + 1);
switch (columnIndex) {
case 0:
String[] parts = ((String) (aValue)).split(", ");
if (parts.length > 1) {
rs.updateString("last_name", parts[0]);
rs.updateString("first_name", parts[1]);
rs.updateRow();
}
case 1:
String gender = (String)aValue;
if((gender.toUpperCase()).equals("M") ||(gender.toUpperCase()).equals("F")){
/*rs.updateObject("gender", gender+"::gender");
rs.updateRow();*/
//How to update an enum???
}
case 2:
try{
parts = ((String)aValue).split("-");
LocalDate lDate = LocalDate.of(Integer.parseInt(parts[0]), Integer.parseInt(parts[1]), Integer.parseInt(parts[2]));
Date date = Date.valueOf(lDate);
rs.updateDate("birth_date", date);
rs.updateRow();
}
catch(NumberFormatException e){
}
catch(ArrayIndexOutOfBoundsException e){
}
case 3:
try{
parts = ((String)aValue).split("-");
LocalDate lDate = LocalDate.of(Integer.parseInt(parts[0]), Integer.parseInt(parts[1]), Integer.parseInt(parts[2]));
Date date = Date.valueOf(lDate);
rs.updateDate("hire_date", date);
rs.updateRow();
}
catch(NumberFormatException e){
}
catch(ArrayIndexOutOfBoundsException e){
}
}
} catch (SQLException ex) {
ex.printStackTrace();
}
this.fireTableCellUpdated(rowIndex, columnIndex);
}
}
| [
"[email protected]"
] | |
29d014400ec5ad8a74765bff65e6c579d84c2c58 | e2d9a5362db35d2e84168023302233400eaf768c | /base-use/spring/spring_base/src/main/java/com/crab/entity/Address.java | 2ce4966146bc3cd7a86f44c1c5d86e2f2d74fb2f | [] | no_license | kongxubihai/spring-family | ea782f6a3aa875be78f35d0e9ce0d63196a903c6 | 84ccc4192bd040fdf2160b21bc748f065abf2d3d | refs/heads/master | 2023-02-13T15:37:40.613654 | 2021-01-15T01:54:52 | 2021-01-15T01:54:52 | 290,968,551 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 197 | java | package com.crab.entity;
/**
* ClassName: com.crab.entity
* Function: TODO
* Reason: TODO
* Date: 2020/9/16
*
* @author zfd
* @version v0.0.1
* @since JDK 1.8
*/
public class Address {
}
| [
"[email protected]"
] | |
9ef1d87b4bc85fd68ca57702c47feba9652b32ca | 1f588848f39274ea1edfbf163e6258b2cd0d3577 | /app/src/main/java/com/jhonts/flutterduck/sprites/Background.java | 991bf4859bec02036e92d202d935685dc7755ca9 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | johnjce/flutterDuck | b10a7cdf2f366ac792c3a0e9d50d167238ddda11 | 30080a778aacdaa5890d3801b7199b8df65068a2 | refs/heads/master | 2021-01-20T14:47:10.593739 | 2017-05-14T13:39:40 | 2017-05-14T13:40:33 | 90,656,303 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,133 | java | /**
* Manages the Bitmap for the background
*
* @author John Jairo Castaño Echeverri
* Copyright (c) <2017> <jjce- ..::jhonts::..>
*/
package com.jhonts.flutterduck.sprites;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import com.jhonts.flutterduck.Game;
import com.jhonts.flutterduck.GameView;
import com.jhonts.flutterduck.R;
import com.jhonts.flutterduck.Util;
public class Background extends Sprite {
/** Static bitmap to reduce memory usage */
public static Bitmap globalBitmap;
public Background(GameView view, Game game) {
super(view, game);
if(globalBitmap == null){
globalBitmap = Util.getDownScaledBitmapAlpha8(game, R.drawable.bg);
}
this.bitmap = globalBitmap;
}
/**
* Draws the bitmap to the Canvas.
* The height of the bitmap will be scaled to the height of the canvas.
* When the bitmap is scrolled to far to the left, so it won't cover the whole screen,
* the bitmap will be drawn another time behind the first one.
*/
@Override
public void draw(Canvas canvas) {
double factor = (1.0 * canvas.getHeight()) / bitmap.getHeight();
if(-x > bitmap.getWidth()){
// The first bitmap is completely out of the screen
x += bitmap.getWidth();
}
int endBitmap = Math.min(-x + (int) (canvas.getWidth() / factor), bitmap.getWidth());
int endCanvas = (int) ((endBitmap + x) * factor) + 1;
src.set(-x, 0, endBitmap, bitmap.getHeight());
dst.set(0, 0, endCanvas, canvas.getHeight());
canvas.drawBitmap(this.bitmap, src, dst, null);
if(endBitmap == bitmap.getWidth()){
// draw second bitmap
src.set(0, 0, (int) (canvas.getWidth() / factor), bitmap.getHeight());
dst.set(endCanvas, 0, endCanvas + canvas.getWidth(), canvas.getHeight());
canvas.drawBitmap(this.bitmap, src, dst, null);
}
}
@Override
public void changeTheme(int s){
this.bitmap = Util.getDownScaledBitmapAlpha8(game,s);
}
}
| [
"[email protected]"
] | |
27af653c5d8ce48c1420993b11dcc86eac6eb0c9 | 5dc53def6de29c488bba3b30cc5b3615cdbf654a | /src/main/java/com/yummuu/mmysql/model/Navigation.java | 8164aadc2cbd1056be1668c2ac3cde5a6d0eca96 | [] | no_license | Yummuu/spring_study | bab441041ad3e31186c354d5086273bace8e752f | 98a579d059d71052cf341d421ab101ac6be86a0b | refs/heads/master | 2022-11-16T21:34:26.737406 | 2020-07-01T07:50:37 | 2020-07-01T07:50:37 | 276,312,417 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,960 | java | package com.yummuu.mmysql.model;
import javax.persistence.*;
import java.io.Serializable;
import java.util.Date;
@Entity
@Table(name = "navigation")
public class Navigation implements Serializable{
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name = "id")
private long id;
@Column(name = "title")
private String title;
@Column(name = "description")
private String description;
@Column(name = "images")
private String images;
@Column(name = "url")
private String url;
@Column(name = "sort")
private long sort;
@Column(name = "status")
private long status;
@Column(name = "deleted_at")
private Date deletedAt;
@Column(name = "created_at")
private Date createdAt;
@Column(name = "updated_at")
private Date updatedAt;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getImages() {
return images;
}
public void setImages(String images) {
this.images = images;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public long getSort() {
return sort;
}
public void setSort(long sort) {
this.sort = sort;
}
public long getStatus() {
return status;
}
public void setStatus(long status) {
this.status = status;
}
public Date getDeletedAt() {
return deletedAt;
}
public void setDeletedAt(Date deletedAt) {
this.deletedAt = deletedAt;
}
public Date getCreatedAt() {
return createdAt;
}
public void setCreatedAt(Date createdAt) {
this.createdAt = createdAt;
}
public Date getUpdatedAt() {
return updatedAt;
}
public void setUpdatedAt(Date updatedAt) {
this.updatedAt = updatedAt;
}
}
| [
"[email protected]"
] | |
fa300e7303fc81ec58d541834a33a046ed7445c5 | 0d048f4322c16e840263982ba14c220866e81eb1 | /src/com/chat/application/dao/daoImpl/ReportDaoImpl.java | 17027d92130ffa26ac2c7921c4666255cc685bca | [] | no_license | narendramohan/webchat | 7ddfc2f09c1fd75b7ef0271bba329080876bcc62 | b9bc0d9fb40e1f51a0b302ae19fb3a80ad2de19f | refs/heads/master | 2022-01-10T11:33:48.045251 | 2021-12-29T13:11:29 | 2021-12-29T13:11:29 | 28,664,187 | 1 | 0 | null | 2021-12-29T13:11:30 | 2014-12-31T11:12:27 | Java | UTF-8 | Java | false | false | 790 | java | package com.chat.application.dao.daoImpl;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import org.springframework.stereotype.Service;
import com.chat.application.dao.ReportDao;
import com.chat.application.domain.SybilAttack;
import com.chat.application.domain.User;
@Service("reportDao")
public class ReportDaoImpl implements ReportDao {
@PersistenceContext
private EntityManager entityManager;
public List<SybilAttack> getSybilAttackReport() {
Query query = entityManager.createQuery("FROM SybilAttack u");
List<SybilAttack> list = query.getResultList();
return list;
}
public void addReportData(SybilAttack s) {
entityManager.merge(s);
}
}
| [
"[email protected]"
] | |
e955c79ae9cc9f9b0d0055f32852dd339b3e1616 | 37efd3611e590276abd7546dfca4feb2fff274a9 | /mpreduce_workspace/HW3/src/hw3/FlightDelayAverager.java | 63a1de310d2d9d7e1e34db5c92e2459dfa854ac6 | [] | no_license | pengfanhust/mapreduce | 7ad7aee5573cfecdbe3827c973c826c62301ed47 | 7e2d782afb97bda6e3de4f0ceed986b7dbbe85d7 | refs/heads/master | 2021-01-20T00:58:21.505350 | 2014-04-29T17:12:54 | 2014-04-29T17:12:54 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,107 | java | package hw3;
import java.io.IOException;
import org.apache.hadoop.io.FloatWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
/**
* simple job, used to calculate the average.
* @author pengfan
*
*/
public class FlightDelayAverager {
public static class FlightDelayMapper extends
Mapper<Object, Text, Text, FloatWritable> {
private Text t = new Text("dummy");
private FloatWritable f = new FloatWritable();
public void map(Object key, Text value, Context context)
throws IOException, InterruptedException {
f.set(Float.valueOf(value.toString()));
context.write(t, f);
}
}
public static class FlightDelayReducer extends
Reducer<Text, FloatWritable, Text, FloatWritable> {
public void reduce(Text key, Iterable<FloatWritable> values,
Context context) throws IOException, InterruptedException {
int count = 0;
double sum = 0;
for (FloatWritable f : values) {
count++;
sum = sum + f.get();
}
context.write(null, new FloatWritable((float) (sum / count)));
}
}
}
| [
"pengfan@ubuntu.(none)"
] | pengfan@ubuntu.(none) |
f2e8d20cd606eddf83564a198ac79ceeb743eae1 | 339c3f3c7f880a995045420c9990bae2a8256a44 | /springboot_bind_prop/src/main/java/cn/hd/sboot/controller/TestController.java | a8b29656f8482e0ad62b438d8776a8b1b3b4ef87 | [] | no_license | hd9898/springboot | a94e475763c7387c01b8631eb2541598bf986ade | 6a2a14ff323df251e6f283c546e41364bbccaf8b | refs/heads/master | 2023-01-29T19:02:54.756542 | 2020-12-08T11:54:26 | 2020-12-08T11:54:26 | 316,422,675 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 772 | java | package cn.hd.sboot.controller;
import cn.hd.sboot.model.AcmeProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
//@EnableConfigurationProperties(AcmeProperties.class)
public class TestController {
// @Autowired
// public AcmeProperties properties ;
// public TestController(AcmeProperties properties) {
// this.properties = properties;
// }
@RequestMapping("test")
public String test(){
// System.out.println(properties);
//return properties;
return "trst";
}
}
| [
"[email protected]"
] | |
139353c7756518cb38965389bc0be2d2d540944a | 6252c165657baa6aa605337ebc38dd44b3f694e2 | /org.eclipse.epsilon.egl.sync/Scalability-Tests/boiler-To-Generate-600-Files/boiler-To-Generate-600-Files/syncregions-600Files/BoilerActuator1937.java | 9e82515307f890421943998e6729ea210fba2bd7 | [] | no_license | soha500/EglSync | 00fc49bcc73f7f7f7fb7641d0561ca2b9a8ea638 | 55101bc781349bb14fefc178bf3486e2b778aed6 | refs/heads/master | 2021-06-23T02:55:13.464889 | 2020-12-11T19:10:01 | 2020-12-11T19:10:01 | 139,832,721 | 0 | 1 | null | 2019-05-31T11:34:02 | 2018-07-05T10:20:00 | Java | UTF-8 | Java | false | false | 263 | java | package syncregions;
public class BoilerActuator1937 {
public execute(int temperatureDifference1937, boolean boilerStatus1937) {
//sync _bfpnGUbFEeqXnfGWlV1937, behaviour
Half Change - return temperature - targetTemperature;
//endSync
}
}
| [
"[email protected]"
] | |
57446ab10f1cc77de8f7dc4b38e8d7456e7c5252 | 58e84b4670fd64a63aad81da9af43601f141d573 | /src/builder/commonsolution/Client.java | c51b9144ad8c444b237d39c2fcbab6c8471051c5 | [] | no_license | wsy1983wsy/DesignPatterns | 4ef305ded3fb01a9a241a704e9c1b13a138f0fcc | 8c09affdd351a9ffad27c874d3eaa53d1648ed3a | refs/heads/master | 2020-03-15T02:30:40.372894 | 2017-11-24T10:28:00 | 2017-11-24T10:28:00 | null | 0 | 0 | null | null | null | null | GB18030 | Java | false | false | 1,110 | java | package builder.commonsolution;
import java.util.*;
public class Client {
public static void main(String[] args) {
//准备测试数据
ExportHeaderModel ehm = new ExportHeaderModel();
ehm.setDepId("一分公司");
ehm.setExportDate("2012-06-26");
Map<String,Collection<ExportDataModel>> mapData = new HashMap<String,Collection<ExportDataModel>>();
Collection<ExportDataModel> col = new ArrayList<ExportDataModel>();
ExportDataModel edm1 = new ExportDataModel();
edm1.setProductId("产品001号");
edm1.setPrice(100);
edm1.setAmount(80);
ExportDataModel edm2 = new ExportDataModel();
edm2.setProductId("产品002号");
edm2.setPrice(99);
edm2.setAmount(55);
//把数据组装起来
col.add(edm1);
col.add(edm2);
mapData.put("销售记录表", col);
ExportFooterModel efm = new ExportFooterModel();
efm.setExportUser("张三");
//测试输出到文本文件
ExportToTxt toTxt = new ExportToTxt();
toTxt.export(ehm, mapData, efm);
//测试输出到xml文件
ExportToXml toXml = new ExportToXml();
toXml.export(ehm, mapData, efm);
}
}
| [
"[email protected]"
] | |
bb0636d998c5007e82fb0d10d3f92e68dbe9d3fb | 2ad4e101b0f65c85e9a9fd6c1e77274179e82f5f | /juice-dynamic-datasource/src/main/java/juice/datasource/util/BeanRegistrarUtils.java | e0c58fb1adac5b3e182b7eb63c3baad81240f168 | [
"Apache-2.0"
] | permissive | rickykang-linux/juice | 3f64320173ea11dd54812a3df7ab0e16c120d333 | 855c502e8b0118aad15cee4157e60066d6e258b2 | refs/heads/master | 2023-06-06T03:57:47.682250 | 2021-06-23T11:23:01 | 2021-06-23T11:23:01 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,065 | java | package juice.datasource.util;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import java.util.Objects;
/**
* @author Ricky Fung
*/
public abstract class BeanRegistrarUtils {
public static boolean registerBeanDefinitionIfNotExists(BeanDefinitionRegistry registry, String beanName,
Class<?> beanClass) {
if (registry.containsBeanDefinition(beanName)) {
return false;
}
String[] candidates = registry.getBeanDefinitionNames();
for (String candidate : candidates) {
BeanDefinition beanDefinition = registry.getBeanDefinition(candidate);
if (Objects.equals(beanDefinition.getBeanClassName(), beanClass.getName())) {
return false;
}
}
BeanDefinition annotationProcessor = BeanDefinitionBuilder.genericBeanDefinition(beanClass).getBeanDefinition();
registry.registerBeanDefinition(beanName, annotationProcessor);
return true;
}
public static boolean registerBeanDefinitionIfNotExists(BeanDefinitionRegistry registry, String beanName,
BeanDefinition bd) {
if (registry.containsBeanDefinition(beanName)) {
return false;
}
String[] candidates = registry.getBeanDefinitionNames();
for (String candidate : candidates) {
BeanDefinition beanDefinition = registry.getBeanDefinition(candidate);
if (Objects.equals(beanDefinition.getBeanClassName(), bd.getBeanClassName())) {
return false;
}
}
registry.registerBeanDefinition(beanName, bd);
return true;
}
public static BeanDefinitionBuilder genericBeanDefinition(Class<?> beanClass) {
return BeanDefinitionBuilder.genericBeanDefinition(beanClass);
}
}
| [
"[email protected]"
] | |
89cbd2239dd526d6dc2126f2b8137f03065ac80a | 6f968ffc0222ddb37bd6d109909fa8d2d38dbd1a | /P11Smart.java | bc4fd703486fccf788899842727bd6d926b32c3e | [] | no_license | dameng58/leetcode | 87b8be39918202d6501ebe8f6ff1f2d3615b7a9c | a810de7e280390cf0b99d86ba509e56f323eb706 | refs/heads/main | 2022-12-31T16:15:32.843172 | 2020-10-22T00:59:49 | 2020-10-22T00:59:49 | 113,175,305 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 615 | java | /*
* Copyright (c) Huawei Technologies Co., Ltd. 2019-2020. All rights reserved.
*/
package lettcode.线性表;
public class P11Smart {
/*
经典双指针思路,有点意思
*/
public int maxArea(int[] height) {
int len = height.length;
int lk = 0, rk = len - 1;
int max = 0;
while (lk < rk){
max = Math.max(max, Math.min(height[lk], height[rk]) * (rk - lk));
if (height[lk] > height[rk]){
--rk;
}else{
++lk;
}
}
return max;
}
}
| [
"[email protected]"
] | |
cc5adbb758978eb135609e704b65b8553643503f | 1242c074537c20caf647420947d0f00b2c6c90cd | /src/main/java/com/xuyao/test/cache/LRU.java | 6b95abd27a8600b8f5e0b1fdee82d002fe24e1a0 | [] | no_license | xuyao8002/xytest | 92d3b6320edcc240ca778c3078a0d19536c2916c | 445df0593d22893b3b06465012e3d957786de083 | refs/heads/master | 2023-08-23T18:29:28.488787 | 2023-08-14T13:10:20 | 2023-08-14T13:10:20 | 95,776,351 | 1 | 0 | null | 2023-06-15T02:23:53 | 2017-06-29T12:42:15 | Java | UTF-8 | Java | false | false | 859 | java | package com.xuyao.test.cache;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
public class LRU<K, V> {
private int capacity;
private Map<K, V> map = new HashMap<>();
private LinkedList<K> list = new LinkedList<>();
public LRU(int capacity) {
this.capacity = capacity;
}
public void put(K key, V value){
if (map.containsKey(key)) {
list.remove(key);
}else{
if (list.size() == capacity) {
K k = list.removeLast();
map.remove(k);
}
}
list.addFirst(key);
map.put(key, value);
}
public V get(K key){
V v;
if (!map.containsKey(key)) {
return null;
}else{
v = map.get(key);
put(key, v);
}
return v;
}
} | [
"[email protected]"
] | |
abb30f11e3980003cd23060858f02f4c9d478d35 | f5eb9262ae9cb7cf150640c314144a917b20fa9d | /src/main/java/com/evacipated/cardcrawl/mod/hubris/cards/curses/Lust.java | 780d94c5ff4b12b1dd52623ba732e19d81d843de | [] | no_license | kiooeht/Hubris | 475e826d816a4cf33033feb5cacffa28d1b9390c | 7d3a0d1bff0ff6229542790c9ecbb1036c7b257a | refs/heads/master | 2023-05-13T19:07:45.388315 | 2023-05-04T03:43:46 | 2023-05-04T03:43:46 | 149,699,046 | 6 | 16 | null | 2019-03-17T23:34:35 | 2018-09-21T02:31:44 | Java | UTF-8 | Java | false | false | 2,100 | java | package com.evacipated.cardcrawl.mod.hubris.cards.curses;
import basemod.abstracts.CustomCard;
import com.evacipated.cardcrawl.mod.hubris.HubrisMod;
import com.evacipated.cardcrawl.mod.hubris.powers.LustTargetPower;
import com.evacipated.cardcrawl.mod.stslib.fields.cards.AbstractCard.AutoplayField;
import com.evacipated.cardcrawl.mod.stslib.fields.cards.AbstractCard.SoulboundField;
import com.megacrit.cardcrawl.actions.common.ApplyPowerAction;
import com.megacrit.cardcrawl.cards.AbstractCard;
import com.megacrit.cardcrawl.characters.AbstractPlayer;
import com.megacrit.cardcrawl.core.CardCrawlGame;
import com.megacrit.cardcrawl.dungeons.AbstractDungeon;
import com.megacrit.cardcrawl.localization.CardStrings;
import com.megacrit.cardcrawl.monsters.AbstractMonster;
public class Lust extends CustomCard
{
public static final String ID = "hubris:Lust";
public static final String IMG = HubrisMod.BETA_SKILL;
private static final CardStrings cardStrings = CardCrawlGame.languagePack.getCardStrings(ID);
public static final String NAME = cardStrings.NAME;
public static final String DESCRIPTION = cardStrings.DESCRIPTION;
private static final int COST = 0;
private static final int HP_LOSS = 3;
public Lust()
{
super(ID, NAME, IMG, COST, DESCRIPTION, CardType.SKILL, CardColor.CURSE, CardRarity.CURSE, CardTarget.ALL_ENEMY);
AutoplayField.autoplay.set(this, true);
magicNumber = baseMagicNumber = HP_LOSS;
}
@Override
public void use(AbstractPlayer p, AbstractMonster m)
{
m = AbstractDungeon.getCurrRoom().monsters.getRandomMonster(true);
AbstractDungeon.actionManager.addToBottom(new ApplyPowerAction(m, p, new LustTargetPower(m, -HP_LOSS), -HP_LOSS));
}
@Override
public boolean canUse(AbstractPlayer p , AbstractMonster m)
{
return true;
}
@Override
public boolean canUpgrade()
{
return false;
}
@Override
public void upgrade()
{
}
@Override
public AbstractCard makeCopy()
{
return new Lust();
}
}
| [
"[email protected]"
] | |
98764b74a27b611cab6346e57adf1d323cccaf74 | badbde68df5660c0d245df1ee347d2c64cba6cce | /app/src/main/java/cz/cvut/marekp11/feedreader/update/helpers/DataHolder.java | f93c0400bdd5b3012f6797cf915af350fe40e029 | [] | no_license | sangecz/feedreader | 4ebcbda02eb2d918a793e0cba55e167982f78045 | 58cc990b00a45620d02abdd9f4a888bbaafc2ae8 | refs/heads/master | 2021-01-11T14:34:44.879369 | 2017-01-26T23:26:40 | 2017-01-26T23:26:40 | 80,163,916 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 918 | java | package cz.cvut.marekp11.feedreader.update.helpers;
import java.lang.ref.WeakReference;
import java.util.HashMap;
import java.util.Map;
public class DataHolder {
public static final String LIST_FRAGMENT_ID = "LIST_FRAGMENT_ID";
private Map<String, WeakReference<Object>> data;
private static DataHolder instance;
public static DataHolder getInstance(){
if(instance == null) {
instance = new DataHolder();
}
return instance;
}
private DataHolder(){
data = new HashMap<String, WeakReference<Object>>();
}
public void save(String id, Object object) {
data.put(id, new WeakReference<Object>(object));
}
public Object retrieve(String id) {
WeakReference<Object> objectWeakReference = data.get(id);
if (objectWeakReference != null)
return objectWeakReference.get();
return null;
}
}
| [
"[email protected]"
] | |
c52e6420b278d49d0dda0345e0e6d10684e4c276 | e3e002da390bc06acd888e57eb28033b1c020ace | /JavaPrograms/RandomPrograms/PostfixConvertor.java | 53a25721b7dac00ecbe80630012c3abd98179cd9 | [] | no_license | Object-Oriented101/LearningProgrammingFundamentals | 0f468690f2a4d1319811dab27c9bab190dba0225 | 3334f6c819cea7f812dbcd08b466fbac77edb94a | refs/heads/master | 2021-06-16T07:31:46.437417 | 2019-12-01T00:53:25 | 2019-12-01T00:53:25 | 97,735,726 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,494 | java | package RandomPrograms;
public class PostfixConvertor {
public static void main(String args[]){
String infix = "((a+b)*(z+x))";
System.out.println("Postfix : " + printPostFix(infix));
System.out.println("Prefix : " + printPreFix(infix));
}
public static String printPostFix(String str){
Stack stack = new Stack();
String postfix = "";
for(int i=0;i<str.length();i++){
char c = str.charAt(i);
if(Character.isLetter(c)){
postfix = postfix + c;
}
else if(c == '('){
continue;
}
else if(c == ')'){
postfix = postfix + ((Character)stack.pop()).toString();
}
else{
stack.push(c);
}
}
return postfix;
}
public static String printPreFix(String str){
@SuppressWarnings("rawtypes")
Stack stack = new Stack();
String prefix = "";
for(int i=str.length()-1;i>=0;i--){
char c = str.charAt(i);
if(Character.isLetter(c)){
prefix = ((Character)c).toString() + prefix;
}
else if(c == '('){
prefix = ((Character)stack.pop()).toString() + prefix;
}
else if(c == ')'){
continue;
}
else{
stack.push(c);
}
}
return prefix;
}
}
| [
"[email protected]"
] | |
7d13b20096e57612f23af63c9e1a16ad95307d5a | 6adb6f50457103d9e35f96057a18b96a081afce1 | /src/main/java/com/example/xm/bean/Favorite.java | a7d7e524fc395fea4242d8c59ff16c17c6f4eb10 | [] | no_license | xiaos2000/shop | 783dd3341d6ffb196ffd62f86e93c4ca813c8132 | de3382fd984ddf79044613891ad8927b98a796ba | refs/heads/master | 2023-01-19T04:43:18.292336 | 2020-12-04T05:38:54 | 2020-12-04T05:38:54 | 258,478,147 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 979 | java | package com.example.xm.bean;
import java.io.Serializable;
/**
* 收藏实体类
*/
public class Favorite implements Serializable {
private Route route;//旅游线路对象
private String date;//收藏时间
private User user;//所属用户
/**
* 无参构造方法
*/
public Favorite() {
}
/**
* 有参构造方法
* @param route
* @param date
* @param user
*/
public Favorite(Route route, String date, User user) {
this.route = route;
this.date = date;
this.user = user;
}
public Route getRoute() {
return route;
}
public void setRoute(Route route) {
this.route = route;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}
| [
"[email protected]"
] | |
2b413b19b69166672073f79ba34cdeeb8194c6a0 | 833ae11bf55c706ba960bd1da54f2689b0e4cbf2 | /src/main/java/data/streaming/dto/KeywordDTO.java | 19c69e5894f76c1fd06fc68fa11a7a68ab395793 | [] | no_license | si1718/si1718-mha-streaming | a28e6efee8990eb4b7e99e2903d113f11ad35d5d | 30ca62a97a1a85ce3db6afe187951394203f8291 | refs/heads/master | 2021-05-13T18:37:54.541848 | 2018-01-05T23:05:52 | 2018-01-05T23:05:52 | 116,871,412 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,539 | java | package data.streaming.dto;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
public class KeywordDTO {
String key;
Double statistic;
String date;
public KeywordDTO(String key, Double statistic) {
super();
this.key = key;
this.statistic = statistic;
DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
this.date = formatter.format(new Date());
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public Double getStatistic() {
return statistic;
}
public void setStatistic(Double statistic) {
this.statistic = statistic;
}
public void addOneStatisticMore(Double statistic) {
this.statistic += statistic;
}
public void addOneStatisticMore() {
this.statistic += 1.0;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((key == null) ? 0 : key.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
KeywordDTO other = (KeywordDTO) obj;
if (key == null) {
if (other.key != null)
return false;
} else if (!key.equals(other.key))
return false;
return true;
}
@Override
public String toString() {
return "KeywordDTO [key=" + key + ", statistic=" + statistic + "]";
}
}
| [
"[email protected]"
] | |
313a753fdedd7773ab4cf6b9a774ee180a80dff2 | 1503d823ac30f1f1e9e0cef06e583570658f95d1 | /src/isel/leic/simul/elem/Elem.java | 3622dec4a399c6b87d239f7cce03d1232574c495 | [] | no_license | palex65/sim-dig | 0d3aa72222401352758fd27a52e834899387d0e2 | 56f534abf6e403fa76b7cf41d89d7a682b81ae6e | refs/heads/master | 2021-01-20T01:11:19.559652 | 2017-04-24T11:19:45 | 2017-04-24T11:19:45 | 89,228,679 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,710 | java | package isel.leic.simul.elem;
import isel.leic.simul.Simul;
import isel.leic.simul.bit.*;
import isel.leic.simul.dat.AbstractDat;
import isel.leic.simul.dat.InDat;
import isel.leic.simul.dat.OutDat;
import java.lang.reflect.Field;
import java.util.LinkedList;
import java.util.List;
public abstract class Elem {
public List<IBit> inputs = new LinkedList<>();
public List<OBit> outputs = new LinkedList<>();
public List<InDat> datInputs = new LinkedList<>();
public List<OutDat> datOutputs = new LinkedList<>();
public Object getField(String name) {
try {
Field f = this.getClass().getDeclaredField(name);
return f.get(this);
} catch (NoSuchFieldException | IllegalAccessException e) {
for (IBit bit : inputs)
if (((AbstractBit) bit).getName().equals(name)) return bit;
for (OBit bit : outputs)
if (((AbstractBit) bit).getName().equals(name)) return bit;
return null;
}
}
public String getStatus() {
List<String> in = new LinkedList<>();
List<String> out = new LinkedList<>();
for (IBit bit : inputs)
if (!(bit instanceof InDat.IBit)) {
AbstractBit b = (AbstractBit) bit;
in.add(b.getName() + " = " + bit.get().view);
}
for (InDat dat : datInputs)
in.add(dat.getName() + "["+dat.length()+"]=" + dat.read());
for (OBit bit : outputs)
if (!(bit instanceof OutDat.OBit)) {
AbstractBit b = (AbstractBit) bit;
out.add(b.getName() + " = " + bit.get().view);
}
for (OutDat dat : datOutputs)
out.add(dat.getName() + "["+dat.length()+"]=" + dat.read());
int n = Math.max(in.size(),out.size());
String txt = "";
for (int i = 0; i < n; i++) {
txt += "<tr><td>";
if (i<in.size()) txt += in.get(i);
txt += "</td><td>";
if (i<out.size()) txt += out.get(i);
txt += "</td></tr>";
}
return txt;
}
protected class Input extends InBit {
public Input() { this(""); }
public Input(String name) {
this(name,Elem.this::onInputChanged);
}
public Input(String name, InBit.BitChangedListener action) {
super(name,action);
inputs.add(this);
}
}
protected class InputDat extends InDat {
public InputDat(String name, int length) {
this(name,length,Elem.this::onInputChanged);
}
public InputDat(String name, int length, InBit.BitChangedListener action) {
super(name, length, action);
datInputs.add(this);
for(Bit bit : bits) inputs.add((IBit)bit);
}
}
protected class Output extends OutBit {
public Output() { this(""); }
public Output(String name) {
this(name,false);
}
public Output(String name, boolean value) {
super(name,value);
outputs.add(this);
}
}
protected class OutputDat extends OutDat {
public OutputDat(String name, int length) {
super(name, length);
datOutputs.add(this);
for(Bit bit : bits) outputs.add((OBit)bit);
}
}
protected final void initOutputs() {
for (OBit out : outputs)
if (out.isOpen()) out.reset();
}
protected abstract void onInputChanged(InBit bit);
private static Simul.UI simul;
public static void setSimul(Simul.UI s) { simul=s; }
protected final void doAction(Runnable action) { simul.doAction(action); }
}
| [
"[email protected]"
] | |
aae4f5a477011672c19c009f061e9449bde15b70 | 311891ee4364d36da9569eaeccd313b8b4ba9bd9 | /src/main/java/com/highdev/angularjs/srvc/controller/ServiceMgtCTR.java | 8b269b52b66d97927f30d14ad7a7041a5232a9a2 | [] | no_license | jiunan/Study | dea90834529de18db2f1dba2e8258878fdcfc981 | 04b9412892ab09285340ff6244ff19a3217a970c | refs/heads/master | 2021-01-19T08:42:49.132421 | 2013-08-25T15:36:15 | 2013-08-25T15:36:15 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 720 | java | package com.highdev.angularjs.srvc.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.highdev.angularjs.srvc.service.ServiceMgtSVC;
import com.highdev.angularjs.srvc.vo.ServiceMgtVO;
@Controller
@RequestMapping("/standard")
public class ServiceMgtCTR {
@Autowired
private ServiceMgtSVC serviceMgtSVC;
@RequestMapping("/services")
@ResponseBody
public List<ServiceMgtVO> getServiceList(ServiceMgtVO search){
return serviceMgtSVC.getList(search);
}
}
| [
"[email protected]"
] | |
322ac30afa52d7031c8369ec3a90a044d23e2fbc | 0225564168011dac281df29cdb2b4b7b1efad36a | /Kungsholmen/src/com/game/clean/Plane.java | 353dc28c63ae769e19348bec3721091f692cf976 | [] | no_license | TBthegr81/Game | d54178ac413eb9629131eafd3c4fa97a579ba7a4 | 6196a29ae2ca9877781d0c896c1e73b0fb58ee43 | refs/heads/master | 2021-01-01T19:42:18.833164 | 2014-04-08T08:50:34 | 2014-04-08T08:50:48 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 586 | java | package com.game.clean;
import com.badlogic.gdx.graphics.Texture;
public class Plane {
int width;
int height;
@SuppressWarnings("unused")
private double weight;
@SuppressWarnings("unused")
private int engine;
@SuppressWarnings("unused")
private int turnability;
@SuppressWarnings("unused")
private Texture Texture;
public Plane(Texture Texture, int width, int height, int weight, int engine, int turnability)
{
this.Texture = Texture;
this.width = width;
this.height = height;
this.weight = weight;
this.engine = engine;
this.turnability = turnability;
}
}
| [
"[email protected]"
] | |
10f1e45df373f9eeace4b7000dffd5e581585657 | 16773d5b4e0449ab6e3f6e1951d7303d0b4fcbae | /SatwikDesignPrinciplesTask-master/src/main/java/Operation.java | 98f236ee8212ff432c092b0abac505c8b34d4107 | [] | no_license | satwiktalluri/SatwikDesignPrinciplesTask-master | 1b9e97c4126806c54bf193cc3446cf22a6f00b0c | b5ac816dee833cf092700043646638fc8280ca1a | refs/heads/master | 2022-11-25T07:41:01.331870 | 2020-07-26T17:35:05 | 2020-07-26T17:35:05 | 282,700,437 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 115 | java | public abstract class Operation extends Compute
{
abstract int calculateValue(int firstInput,int secondInput);
} | [
"[email protected]"
] | |
cce6c3616ee4650d3dc6771adc965281c84b292a | 7eed5902e0853461fc9421315d9a3dbfb1a3968d | /HomeTask2/test/edu/epam/labs/hometask2/action/ArrayHandlerTest.java | a5659fb8097d25f1a19640f523a395994477f4a0 | [] | no_license | EX22/EpamLearning | 89af4c0d95e29a38af31354f17b36768e7382aeb | 663ac13256363e278e4d8abb0adab31e8192d4bc | refs/heads/master | 2020-04-11T15:42:54.303300 | 2018-12-20T22:56:57 | 2018-12-20T22:56:57 | 161,897,300 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,328 | java | package edu.epam.labs.hometask2.action;
import org.testng.annotations.Test;
import static org.testng.Assert.*;
public class ArrayHandlerTest {
/**
* Checks if ArrayHandler's swapOrSquare method properly swap elements in received array's
* or gets them into square according to conditions.
*/
@Test
public void testSwapOrSquare() {
ArrayHandler arrayHandler = new ArrayHandler();
double[] test = new double[]{3.0, 7.0, 8.0};
double[] template = new double[]{9.0, 49.0, 8.0};
arrayHandler.swapOrSquare(test);
assertEquals(test, template);
}
/**
* Checks if ArrayHandler's getBinaryLength method return proper binary number's length of decimal number.
*/
@Test
public void testGetBinaryLength() {
ArrayHandler arrayHandler = new ArrayHandler();
assertEquals(arrayHandler.getBinaryLength(8), 4);
}
/**
* Checks if ArrayHandler's round method properly rounding elements in received array.
*/
@Test
public void testRound() {
ArrayHandler arrayHandler = new ArrayHandler();
double[] test = new double[]{1.7, 3.46, 2.1, 5, 0.544};
double[] template = new double[]{2.0, 3.0, 2.0, 5.0, 1.0};
arrayHandler.round(test);
assertEquals(test, template);
}
} | [
"[email protected]"
] | |
c166e472470353be31292b6d9b098c836139dcd1 | 79bda5039426945dd459151cf510c8514bab2d4a | /src/main/java/com/banner/thirdServer/wechat/wechat4j/token/Tokens.java | 923744caf49a8176eca874ced1c37965bb55a95d | [] | no_license | daoos/banner | 2efb1d4e882af4f0e9c3b6094811001026b6683a | 48346ef6b295b9fcd2fac82f854db5d6a42c6510 | refs/heads/master | 2021-01-13T10:29:05.237201 | 2016-05-20T17:26:44 | 2016-05-20T17:26:44 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,116 | java | package com.banner.thirdServer.wechat.wechat4j.token;
import com.alibaba.fastjson.JSONObject;
import com.banner.thirdServer.quartz.TaskUtils;
import com.banner.thirdServer.wechat.lang.HttpUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
/**
* Created by admin on 2016/4/17.
*/
public class Tokens{
private static Logger logger = Logger.getLogger(AccessToken.class);
public static Map<String,String> tockenMap=new HashMap<>();
private static final String ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential";
@Resource
private TaskUtils taskUtils;
private String appId;
private String secret;
public Tokens(String appId,String secret){
this.appId=appId;
this.secret=secret;
}
private String getToken(String appId){
return tockenMap.get(appId).toString();
}
public String install(){
String url = accessTokenUrl();
String result = HttpUtils.get(url);
if(StringUtils.isNotBlank(result))
{
JSONObject jsonObject = JSONObject.parseObject(result);
String token = jsonObject.get("access_token")==null?"":jsonObject.get("access_token").toString();
if(StringUtils.isBlank(token)){
logger.error("token获取失败,获取结果" + result);
return "";
}
String expiresIn = jsonObject.get("expires_in")==null?"":jsonObject.get("expires_in").toString();
if(StringUtils.isBlank(expiresIn)){
logger.error("token获取失败,获取结果" + expiresIn);
return "";
}
tockenMap.put(appId,token);
logger.info("token获取成功");
return token;
}else{
logger.info("服务器响应异常");
}
return "";
}
private String accessTokenUrl(){
String url = ACCESS_TOKEN_URL + "&appid=" + appId + "&secret=" + secret;
return url;
}
}
| [
"[email protected]"
] | |
7e306b268bb243d8c1eae0d588852d85595e0b5d | e659e64bb115289847ca6df0636ff7481184d414 | /src/com/moressette/ordermanagement/servlet/AddOrderServlet.java | 3948b6665756c23fb013f29856676226a963e3fd | [] | no_license | Moressette/OrderManagement | ed71efa3ed0c4b914b3d96b0bfdfc4475a22d572 | f45c9ac6dcf03a933825ec371806488be2adfcd4 | refs/heads/master | 2021-01-17T18:18:12.626616 | 2016-10-19T10:12:31 | 2016-10-19T10:12:31 | 71,344,161 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,584 | java | package com.moressette.ordermanagement.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.moressette.ordermanagement.dao.OrderlistDao;
import com.moressette.ordermanagement.dao.impl.OrderlistDaoimpl;
import com.moressette.ordermanagment.entity.Order;
/**
* Servlet implementation class AddOrderServlet
*/
@WebServlet("/AddOrderServlet")
public class AddOrderServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public AddOrderServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("text/html;charset=utf-8");
response.setCharacterEncoding("UTF-8");
request.setCharacterEncoding("UTF-8");
PrintWriter out = response.getWriter();
String no = (String) request.getParameter("order_no");
String consignee_name = (String) request.getParameter("consignee_name");
String consignee_addr = (String) request.getParameter("consignee_addr");
String consignee_phone = (String) request.getParameter("consignee_phone");
double order_price = Double.valueOf(request.getParameter("order_price"));
int order_amount = Integer.parseInt(request.getParameter("order_amount"));
Order order = new Order();
order.setNo(no);
order.setConsignee_name(consignee_name);
order.setConsignee_addr(consignee_addr);
order.setConsignee_phone(consignee_phone);
order.setOrder_price(order_price);
order.setOrder_amount(order_amount);
OrderlistDao od = new OrderlistDaoimpl();
boolean flag = od.addOrder(order);
if (flag) {
out.print("<script>alert('订单添加成功');window.location.href=('AdminServlet');</script>");
} else {
out.print("<script>alert('该订单编号已存在');window.location.href=('AdminServlet');</script>");
}
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
| [
"[email protected]"
] | |
d09d822642b9ae1e7305bdb74a5084def5e245be | 6af2ba478c7a1ca2e68f75e385a0d9b1ff56cdc6 | /Day35_JDBC/src/com/tcwgq/jdbc/dao/impl/UserDaoJdbcImpl.java | 38aa8a2a0767aab5704de868771b0821cbc12f06 | [] | no_license | tcwgq/learn-java-base | 20f2a8c895cf8719730beada81b069d857a4ac37 | e483ba3cbe6353dc1e16fded257eecf59321331e | refs/heads/master | 2022-01-10T07:57:49.167924 | 2019-06-16T01:36:59 | 2019-06-16T01:36:59 | 104,757,290 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,476 | java | package com.tcwgq.jdbc.dao.impl;
import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import com.tcwgq.demo7.JDBCUtils;
import com.tcwgq.jdbc.dao.DaoException;
import com.tcwgq.jdbc.dao.UserDao;
import com.tcwgq.jdbc.domain.User;
public class UserDaoJdbcImpl implements UserDao {
@Override
public void addUser(User user) {
String sql = "insert into user (name, birthday, money) values (?, ?, ?)";
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
conn = JDBCUtils.getConnection();
ps = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
ps.setString(1, user.getName());
ps.setDate(2, new Date(user.getBirthday().getTime()));
ps.setFloat(3, user.getMoney());
int i = ps.executeUpdate();
System.out.println(i);
rs = ps.getGeneratedKeys();
while (rs.next()) {
user.setId(rs.getInt(1));
}
} catch (SQLException e) {
throw new DaoException(e.getMessage(), e);
} finally {
JDBCUtils.free(rs, ps, conn);
}
}
@Override
public User getUser(int userId) {
String sql = "select id, name, birthday, money from user where id = ?";
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
User user = null;
try {
conn = JDBCUtils.getConnection();
ps = conn.prepareStatement(sql);
ps.setInt(1, userId);
rs = ps.executeQuery();
while (rs.next()) {
user = new User(rs.getInt(1), rs.getString(2), rs.getDate(3), rs.getFloat(4));
}
} catch (SQLException e) {
throw new DaoException(e.getMessage(), e);
} finally {
JDBCUtils.free(rs, ps, conn);
}
return user;
}
@Override
public User findUser(String username, String password) {
String sql = "select id, name, birthday, money from user where name = ?";
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
User user = null;
try {
conn = JDBCUtils.getConnection();
ps = conn.prepareStatement(sql);
ps.setString(1, username);
rs = ps.executeQuery();
while (rs.next()) {
user = new User(rs.getInt(1), rs.getString(2), rs.getDate(3), rs.getFloat(4));
}
} catch (SQLException e) {
throw new DaoException(e.getMessage(), e);
} finally {
JDBCUtils.free(rs, ps, conn);
}
return user;
}
@Override
public void update(User user) {
String sql = "update user set name = ?, birthday = ?, money = ? where id = ?";
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
conn = JDBCUtils.getConnection();
ps = conn.prepareStatement(sql);
ps.setString(1, user.getName());
ps.setDate(2, new Date(user.getBirthday().getTime()));
ps.setFloat(3, user.getMoney());
ps.setInt(4, user.getId());
int i = ps.executeUpdate();
System.out.println(i);
} catch (SQLException e) {
throw new DaoException(e.getMessage(), e);
} finally {
JDBCUtils.free(rs, ps, conn);
}
}
@Override
public void delete(User user) {
String sql = "delete from user where id = ?";
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
conn = JDBCUtils.getConnection();
ps = conn.prepareStatement(sql);
ps.setInt(1, user.getId());
int i = ps.executeUpdate();
System.out.println(i);
} catch (SQLException e) {
throw new DaoException(e.getMessage(), e);
} finally {
JDBCUtils.free(rs, ps, conn);
}
}
}
| [
"[email protected]"
] | |
07151330f4b98aba9bf3cf6cc98b318a6f1fc001 | 253a9ebabf91a7046fc2733ca92f92fbe0613b61 | /Data Structures and Algorithms/src/com/company/SelectionSort.java | 9b526bd42aad2b594d9d173766152026f77cd1ea | [] | no_license | beccar97/training | 8694f0512dbca704c521df1ad61a858987a7e1ba | 4406e9c3afd2a2f1d492c48888a20e6b3de38ae9 | refs/heads/master | 2020-09-13T08:39:11.279257 | 2020-01-30T15:19:19 | 2020-01-30T15:19:19 | 222,715,099 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 961 | java | package com.company;
import java.util.List;
public class SelectionSort{
// Note this actually sorts the original list in place
public static List<Integer> sort(List<Integer> list) {
if (list.size() > 1) {
int indexOfSmallest = findSmallest(list);
Integer temp = list.get(indexOfSmallest);
list.set(indexOfSmallest, list.get(0));
list.set(0, temp);
sort(list.subList(1, list.size()));
}
return list;
};
private static int findSmallest(List<Integer> list) {
return list.stream().reduce(0, (index, item) -> {
if (item < list.get(index)) return list.indexOf(item);
return index;
});
}
public static double timeSort(List<Integer> list) {
long startTime = System.nanoTime();
sort(list);
long endTime = System.nanoTime();
return ((double)endTime - startTime) / 1_000_000;
}
}
| [
"[email protected]"
] | |
ceea788c9e863335d7fb3ac9ad08e70212086f96 | 4d373440acef5d28e898fb852a1918de4368b862 | /sport/src/main/java/cn/kanyun/phi_band/sport/ui/home/HomeADWebActivity.java | ac5519c2171b13953dc0645b746de65e65b30545 | [] | no_license | chenwuwen/phi_band | c07a4a612490da37afdeddeb59b70029c1c3999f | af3ca1cc19ff1acddb5ff716f7b48636dd12a4df | refs/heads/master | 2020-06-29T08:22:56.683535 | 2019-09-12T09:52:16 | 2019-09-12T09:52:16 | 200,484,785 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 125 | java | package cn.kanyun.phi_band.sport.ui.home;
import android.app.Activity;
public class HomeADWebActivity extends Activity {
}
| [
"git.123"
] | git.123 |
fff321e804502caf336d2b8d3e7e38a5efa1c371 | 35abfaa1a5bb90e0e19e56ce1b1371e3406594ca | /app/src/java/com/bios/utilities/ErrorMsgComparator.java | ee136f699f098e880d3c6e27479653ccaa3b387d | [] | no_license | MingYiTeh/BIOS | c1bfe2a74906bbdce570af32dcdebe034eb1147e | bd6b862c32019acf429ed221e3ce090ec38251c1 | refs/heads/master | 2021-01-12T06:10:37.029268 | 2016-12-27T16:23:45 | 2016-12-27T16:23:45 | 77,324,115 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 788 | java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.bios.utilities;
import java.util.Comparator;
/**
* Represents an Error Message Comparator object
* @author Teh Ming Yi
*/
public class ErrorMsgComparator implements Comparator<String>{
/**
* Makse a comparison between two error messages
*
* @param s1 the first error message
* @param s2 the second error message
* @return the higher error message after comparing
*/
@Override
public int compare(String s1, String s2) {
return s1.substring(s1.indexOf(" ")+1).compareToIgnoreCase(s2.substring(s2.indexOf(" ")+1));
}
}
| [
"mingyi.teh.2015"
] | mingyi.teh.2015 |
012d1da661d39b9f059c68ad78c4a95abd6270ae | 8cdf7cbb4865c93dc4fe16d9ef0e95861fcd45f4 | /eshop-product/src/main/java/com/hxm/eshop/product/service/SpuInfoService.java | 3badb1bebc26e767b2a8fe08cca505741961f9a1 | [] | no_license | z596593851/eshop | 698d7798e4c41fe6852abb23dfd189c884840f69 | 35e35b290859280621672209c06cc78534d8d0f9 | refs/heads/master | 2023-06-24T19:13:41.207294 | 2021-07-07T06:16:04 | 2021-07-07T06:16:04 | 361,741,550 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 662 | java | package com.hxm.eshop.product.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.hxm.common.utils.PageUtils;
import com.hxm.eshop.product.entity.SpuInfoEntity;
import com.hxm.eshop.product.vo.SpuSaveVo;
import java.util.Map;
/**
* spu信息
*
* @author xiaoming
* @email [email protected]
* @date 2021-04-26 21:30:08
*/
public interface SpuInfoService extends IService<SpuInfoEntity> {
PageUtils queryPage(Map<String, Object> params);
void saveSpuInfo(SpuSaveVo vo);
PageUtils queryPageByCondition(Map<String, Object> params);
void up(Long spuId);
SpuInfoEntity getSpuInfoBySkuId(Long skuId);
}
| [
"[email protected]"
] | |
17f10cf45667cdadd34e9a061b436d9351294864 | 542b91c2c44439a47e7d193aa0fa9901c5b25acd | /app/src/main/java/com/maxpetroleum/tmapp/Model/GradeInfo.java | bc7024407813e5ac2563d48c4e90ac09cf5a415f | [] | no_license | Abhinav-Mani/TMApp | 20ff29e2264c5ec86550ad7db111ec28cbcfb10b | 2bd19ae7413c17b31479fa84c597a3d083533646 | refs/heads/master | 2021-02-05T21:42:42.517386 | 2020-05-25T15:30:38 | 2020-05-25T15:30:38 | 243,837,169 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 616 | java | package com.maxpetroleum.tmapp.Model;
import java.io.Serializable;
public class GradeInfo implements Serializable {
private String grade_name,qnty,rate;
public GradeInfo(String grade_name, String qnty, String rate) {
this.grade_name = grade_name;
this.qnty = qnty;
this.rate = rate;
}
public GradeInfo() {
}
public String getGrade_name() {
return grade_name;
}
public String getQnty() {
return qnty;
}
public String getRate() {
return rate;
}
public void setRate(String rate) {
this.rate = rate;
}
}
| [
"[email protected]"
] | |
0312f332fc68f12376852b3c4f0b52a5d4012448 | 4b539f4f5c6d3fa99c6a2a1b0e6d199ea0745d4a | /service-b/src/test/java/withyuu/tutorial/b/BApplicationTests.java | 916e1e5c1f91b157e68ffebbac72f84ecbe3bb22 | [] | no_license | techguy0079/sleuth-baggage-programmatically | 1f8df975420de9e2b8607336528ceda3fad125bf | 51c0490e6c68dd47c308cd95b49ea8ccf8b0d26c | refs/heads/main | 2023-07-22T20:00:16.840966 | 2021-09-04T07:03:29 | 2021-09-04T07:03:29 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 208 | java | package withyuu.tutorial.b;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class BApplicationTests {
@Test
void contextLoads() {
}
}
| [
"[email protected]"
] | |
ffa7e8507dcd3cfa18e5a0416fed47eecea0ad06 | d3c4b9e8a20b30f6a64f9d7e4ab8c0d7e71bbd7b | /akka-essentials/Chapter3/ActorMessagingExample/src/main/java/org/akka/essentials/future/example/java/OrderActor.java | 6634ec915b77c8c6258c9f6b14e92518e0ee922b | [] | no_license | mo-open/tests | 105b1b36da07ded8800dadcaf7b1d8c3ec743735 | 741c9c65ceb0237905b8f31f00cb29a98a52550d | refs/heads/master | 2021-05-28T16:43:32.675631 | 2015-05-10T05:39:26 | 2015-05-10T05:39:26 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 627 | java | package org.akka.essentials.future.example.java;
import org.akka.essentials.future.example.messages.Order;
import akka.actor.UntypedActor;
public class OrderActor extends UntypedActor {
@Override
public void onReceive(Object message) throws Exception {
if (message instanceof Integer) {
Integer userId = (Integer) message;
// ideally we will get list of orders for given user id
Order order = new Order(Integer.valueOf(123), Float.valueOf(345),
Integer.valueOf(5));
getSender().tell(order, getSelf());
}
}
}
| [
"[email protected]"
] | |
a5c2b5321f0a0d0ea71c7a3bfdc3e6f3bc3bff63 | 3b1c0d695cddd82b60f9ab4c7e097ea350b18297 | /src/main/java/fr/enpermaculture/maferme/repository/PersistenceAuditEventRepository.java | 6ba27e52bda3ece0d27321e21682f0eac526c3a5 | [] | no_license | GwendalFermier/maFerme | d0febca4539bf6551269b5a9152fc1f42ed9d392 | 4ca6cdc5dc51eedefd9b0263313323495a572b6b | refs/heads/master | 2021-08-31T14:19:51.077937 | 2017-12-21T16:49:59 | 2017-12-21T16:49:59 | 115,022,275 | 0 | 0 | null | 2017-12-21T16:50:00 | 2017-12-21T15:50:44 | Java | UTF-8 | Java | false | false | 990 | java | package fr.enpermaculture.maferme.repository;
import fr.enpermaculture.maferme.domain.PersistentAuditEvent;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import java.time.Instant;
import java.util.List;
/**
* Spring Data JPA repository for the PersistentAuditEvent entity.
*/
public interface PersistenceAuditEventRepository extends JpaRepository<PersistentAuditEvent, Long> {
List<PersistentAuditEvent> findByPrincipal(String principal);
List<PersistentAuditEvent> findByAuditEventDateAfter(Instant after);
List<PersistentAuditEvent> findByPrincipalAndAuditEventDateAfter(String principal, Instant after);
List<PersistentAuditEvent> findByPrincipalAndAuditEventDateAfterAndAuditEventType(String principle, Instant after, String type);
Page<PersistentAuditEvent> findAllByAuditEventDateBetween(Instant fromDate, Instant toDate, Pageable pageable);
}
| [
"[email protected]"
] | |
e10b0baf14ec5dd08daa4e99723f16dc8037a1f4 | 68e467ec141b24e65a38aa9f4ced6d84919fe58c | /hunter_1.java | 7b4884f3bad3af58cd2d2bb1a3478863fc632173 | [] | no_license | Irfana14/hunter | 21d2a7809bc41e0fc871c3d7969e7021e36da2b2 | 9eeec9848a9198a0c12b65b6c44c72cb527e4aa0 | refs/heads/master | 2020-04-13T23:56:28.460264 | 2018-05-29T21:25:42 | 2018-05-29T21:25:42 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,269 | java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package repeated;
import java.util.*;
/**
*
* @author akil
*/
public class REPEATED {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Scanner scan = new Scanner(System.in);
ArrayList<Integer> obj=new ArrayList<Integer>();
ArrayList<Integer> obj2=new ArrayList<Integer>();
int n= scan.nextInt();
int [] a= new int[n];
int [] b=new int[n];
int count=0;
for(int i=0;i<n;i++)
{
a[i]=scan.nextInt();
}
//Arrays.sort(a);
for(int i=0;i<n;i++)
{
obj.add(a[i]);
}
int cnt=0;
for(int i=1;i<100000;i++)
{
int f= Collections.frequency(obj,i);
if(f>1)
{
obj2.add(i);
}
}
for(Integer doo:obj2)
{
System.out.println(doo);
}
}
}
| [
"[email protected]"
] | |
8c0f1fa8e653dd6f01c4552b997b7ce9fdca773f | 7f4d477d2dc3ae92ea4fb144540614572d75362c | /example/java类相关/静态常量与静态方法/dog.java | 14b13dc8dbd457737c2e17a906b69c109901ca92 | [] | no_license | syl-skty/myFirstRepository | 4269ae7bddd04500521b9d70ae75f527854f4935 | 1b6988042f580e0a2408da001ebb7d21505a60aa | refs/heads/master | 2020-03-26T10:22:33.762860 | 2018-09-13T13:17:33 | 2018-09-13T13:17:33 | 144,794,679 | 2 | 0 | null | null | null | null | GB18030 | Java | false | false | 920 | java | package 静态常量与静态方法;
public class dog {
static int age = 3;
String name;
public dog(String name) {
this.name = name;
}
public static void show() {
dog d1 = new dog("可乐");
System.out.println("my name is " + d1.name);// 静态方法使用同类中的非静态变量时不能直接使用,必须创建对象来调用
d1.cut();// 静态方法无法直接调用本类中的非静态方法。必须创建对象来调用
System.out.println("my age is " + age);// 静态方法可以直接使用本类中的静态变量
cut2();// 静态方法可以直接调用本类中的静态方法
System.out.println("新建对象d1年龄static的值为:" + dog.age);
}
public void cut() {
System.out
.println("....................................................");
}
public static void cut2() {
System.out
.println("****************************************************");
}
}
| [
"[email protected]"
] | |
a4d1c2d424c38a90b6f626b961c2044a9b411790 | cc8ba19e97a6226d1078a2e7c0e8abbe03f45930 | /src/main/java/com/namlh/bookstore/main/config/ObservableReturnValueHandler.java | 609c1a9497f3999e921c99c6fba4af812b187ec7 | [] | no_license | Namlh1912/bs-backend | 404d6be18c26c4973dd517dedd8bc1768d7e6897 | 6607de576325b8a0b6f4c8356b52c5afb9e92ce1 | refs/heads/master | 2020-03-23T09:29:05.061163 | 2018-07-24T14:21:25 | 2018-07-24T14:21:25 | 141,390,415 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,632 | java | package com.namlh.bookstore.main.config;
import io.reactivex.Observable;
import org.springframework.core.MethodParameter;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.async.DeferredResult;
import org.springframework.web.context.request.async.WebAsyncUtils;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.method.support.ModelAndViewContainer;
/**
* Created by app on 7/13/18.
*/
public class ObservableReturnValueHandler implements HandlerMethodReturnValueHandler {
@Override
public boolean supportsReturnType(MethodParameter returnType) {
Class parameterType = returnType.getParameterType();
return Observable.class.isAssignableFrom(parameterType);
}
@Override
public void handleReturnValue(Object returnValue,
MethodParameter returnType,
ModelAndViewContainer mavContainer,
NativeWebRequest webRequest) throws Exception {
if(returnValue == null) {
mavContainer.setRequestHandled(true);
return;
}
final DeferredResult<Object> deferredResult = new DeferredResult<>();
Observable observable = (Observable) returnValue;
observable.subscribe(
result -> deferredResult.setResult(result),
errors -> deferredResult.setErrorResult(errors)
);
WebAsyncUtils.getAsyncManager(webRequest).startDeferredResultProcessing(deferredResult, mavContainer);
}
}
| [
"[email protected]"
] | |
fdda40d8e1e0d0b97285e9d14762a30693d7b6ba | aa7e651a3eaaa25ddb6badcd2365183e99bcc9a5 | /Social/src/personnalite/Conscienciosite.java | 514636be7cb5882021a0411c7ab0c80704ded809 | [] | no_license | kbangard/Social | e4cec596c361457797a31b44464fe8f57f060ca5 | 16a2fd90dd6ce5ea23c95ed0f211d8b16e8a6009 | refs/heads/master | 2020-04-19T23:20:15.406338 | 2019-04-16T19:21:12 | 2019-04-16T19:21:12 | 168,492,985 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 390 | java | package personnalite;
public class Conscienciosite {
private String conscienciosite;
public Conscienciosite(String conscienciosite) {
this.conscienciosite = conscienciosite;
}
public String getConscienciosite() {
return conscienciosite;
}
@Override
public String toString() {
return "Conscienciosite [conscienciosite=" + conscienciosite + "]";
}
}
| [
"banga@LAPTOP-U8T5PF0J"
] | banga@LAPTOP-U8T5PF0J |
d3e5d84f5adb4e72a37dcdf17da175963c75dc70 | 2046318230ced92c189bcdd41c89f3b0ebd5016d | /app/src/main/java/com/azhar/couplecat/Adapter/KontakAdapter.java | 777b937f5293a80c82a32ce26834e84f1b2a60d2 | [] | no_license | azharsiddiq36/CoupleCat | db18bb9e5f14a6773da044a6c55ef7cd4957e62d | 7c95d7b5a6e78fdbb4a800af22301762b33689ba | refs/heads/master | 2021-07-18T20:40:50.537861 | 2020-09-07T23:29:21 | 2020-09-07T23:29:24 | 211,532,489 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 9,728 | java | package com.azhar.couplecat.Adapter;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.azhar.couplecat.Activity.MessageActivity;
import com.azhar.couplecat.Model.Kontak;
import com.azhar.couplecat.Model.ResponseKontak;
import com.azhar.couplecat.Model.ResponseLastMessage;
import com.azhar.couplecat.Model.ResponsePengguna;
import com.azhar.couplecat.R;
import com.azhar.couplecat.Rest.CombineApi;
import com.azhar.couplecat.Rest.CoupleCatInterface;
import com.azhar.couplecat.Utils.SessionManager;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import static com.azhar.couplecat.Rest.CombineApi.img_url;
public class KontakAdapter extends RecyclerView.Adapter<KontakAdapter.ViewHolder> implements Filterable {
private ArrayList<Kontak> rvData;
Context context;
Dialog myDialog;
CoupleCatInterface coupleCatInterface;
private ArrayList<Kontak> rvDataList;
SessionManager sessionManager;
private List<ResponseKontak> data;
HashMap<String, String> map;
String kontak_id,nama,foto;
String TAG = "Kambing";
public KontakAdapter(Context context, ArrayList<Kontak> inputData) {
this.context = context;
rvData = inputData;
rvDataList = new ArrayList<>(rvData);
sessionManager = new SessionManager(context);
map = sessionManager.getDetailsLoggin();
coupleCatInterface = CombineApi.getApiService();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView tvNama, tvLastMessage, tvTime;
public ImageView ivFoto, ivStatus;
public LinearLayout lyContainer;
public ViewHolder(View v) {
super(v);
lyContainer = (LinearLayout)v.findViewById(R.id.lyContainer);
tvNama = (TextView) v.findViewById(R.id.tvNama);
tvLastMessage = (TextView) v.findViewById(R.id.tvLastMessage);
tvTime = (TextView) v.findViewById(R.id.tvTime);
ivFoto = (ImageView) v.findViewById(R.id.ivFoto);
ivStatus = (ImageView) v.findViewById(R.id.ivStatus);
}
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_chat, parent, false);
ViewHolder vh = new ViewHolder(v);
return vh;
}
@Override
public void onBindViewHolder(final ViewHolder holder, int pofgdion) {
final Kontak Kontak = rvData.get(pofgdion);
//get last message
Call<ResponseLastMessage> getLastMessage = coupleCatInterface.getLastConversation(Kontak.getKontakId().toString());
getLastMessage.enqueue(new Callback<ResponseLastMessage>() {
@Override
public void onResponse(Call<ResponseLastMessage> call, Response<ResponseLastMessage> response) {
if (response.isSuccessful()) {
if (response.body().getStatus() == 200){
kontak_id = null;
if (Kontak.getKontakPenggunaId().equals(map.get(sessionManager.KEY_PENGGUNA_ID))) {
kontak_id = Kontak.getKontakPenggunaId2().toString();
} else {
kontak_id = Kontak.getKontakPenggunaId().toString();
}
//get info kontak
Call<ResponsePengguna> getInfoKontak = coupleCatInterface.detailAccount(kontak_id);
getInfoKontak.enqueue(new Callback<ResponsePengguna>() {
@Override
public void onResponse(Call<ResponsePengguna> call, Response<ResponsePengguna> response) {
if (response.isSuccessful()) {
nama = response.body().getData().getPenggunaNama();
foto = response.body().getData().getPenggunaFoto();
holder.tvNama.setText("" + response.body().getData().getPenggunaNama());
String gambar = response.body().getData().getPenggunaFoto();
if (gambar.equals("")) {
gambar = "assets/images/user.png";
}
Picasso.get()
.load(img_url + gambar)
.placeholder(android.R.drawable.sym_def_app_icon)
.error(android.R.drawable.sym_def_app_icon)
.into(holder.ivFoto);
}
}
@Override
public void onFailure(Call<ResponsePengguna> call, Throwable t) {
}
});
holder.tvLastMessage.setText(""+response.body().getData().getChattingText());
holder.tvTime.setText("" +response.body().getData().getChattingTanggal().substring(8,10)+"-"
+response.body().getData().getChattingTanggal().substring(5,7)+"-"
+response.body().getData().getChattingTanggal().substring(0,4)+" ("+response.body().getData().getChattingTanggal().substring(11,16)+")");
switch (response.body().getData().getChattingStatus()) {
case "delivered":
Picasso.get()
.load(R.drawable.check_delivered)
.error(android.R.drawable.sym_def_app_icon)
.into(holder.ivStatus);
break;
case "send":
Picasso.get()
.load(R.drawable.check_sent)
.error(android.R.drawable.sym_def_app_icon)
.into(holder.ivStatus);
break;
case "read":
Picasso.get()
.load(R.drawable.check_read)
.error(android.R.drawable.sym_def_app_icon)
.into(holder.ivStatus);
break;
default:
Picasso.get()
.load(R.drawable.check_delivered)
.error(android.R.drawable.sym_def_app_icon)
.into(holder.ivStatus);
break;
}
}
else{
holder.lyContainer.setVisibility(View.GONE);
}
}
holder.lyContainer.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent i = new Intent(context,MessageActivity.class);
i.putExtra("kontak_id",Kontak.getKontakId());
i.putExtra("pengguna_id",kontak_id);
i.putExtra("jenis","1");
i.putExtra("nama",nama);
i.putExtra("foto",foto);
context.startActivity(i);
}
});
}
@Override
public void onFailure(Call<ResponseLastMessage> call, Throwable t) {
}
});
}
@Override
public int getItemCount() {
return rvData.size();
}
@Override
public Filter getFilter() {
return exampleFilter;
}
public Filter exampleFilter = new Filter() {
@Override
protected FilterResults performFiltering(CharSequence constraint) {
ArrayList<Kontak> filteredList = new ArrayList<>();
if (constraint == null || constraint.length() == 0) {
filteredList.addAll(rvDataList);
} else {
String filterPattern = constraint.toString().toLowerCase().trim();
for (Kontak item : rvDataList) {
if (item.getKontakId().toLowerCase().contains(filterPattern)) {
filteredList.add(item);
} else if (item.getKontakId().toLowerCase().contains(filterPattern)) {
filteredList.add(item);
}
}
}
FilterResults filterResults = new FilterResults();
filterResults.values = filteredList;
return filterResults;
}
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
rvData.clear();
rvData.addAll((ArrayList) results.values);
notifyDataSetChanged();
}
};
}
| [
"[email protected]"
] | |
43ee439f6bec2a3aa0aed3caabe4d14df4371818 | c872d277ef3cbc491759ef8bbbdb68ba4baa1ee5 | /src/main/java/com/smkj/shiroAndJwt/shiro/JWTToken.java | a8583237dc64eaf23b6c357e03a6d07c80faad77 | [] | no_license | FCWS/shiroJwtDemo | 283d7b7d0e0829c170e53b022a9a834d2935a3c7 | 149e715d599b2b2189e34a89605ededda91e9df6 | refs/heads/master | 2022-06-26T10:55:41.559153 | 2020-02-01T12:38:40 | 2020-02-01T12:38:40 | 234,454,922 | 3 | 0 | null | 2022-06-17T02:52:36 | 2020-01-17T02:34:24 | Java | UTF-8 | Java | false | false | 416 | java | package com.smkj.shiroAndJwt.shiro;
import org.apache.shiro.authc.AuthenticationToken;
public class JWTToken implements AuthenticationToken {
// 密钥
private String token;
public JWTToken(String token) {
this.token = token;
}
@Override
public Object getPrincipal() {
return token;
}
@Override
public Object getCredentials() {
return token;
}
}
| [
"[email protected]"
] | |
c83ff2963360742b67907e062701b4ad4c64dfb0 | b5e05751cbec1a5c88d2c94e58c4673dd558b4ca | /PetSitter/src/main/java/com/spring/petsitter/PetsitterScheduleVO.java | e1d9bfb0052dc20d12413aacc9c3c5e218b61e94 | [] | no_license | cherryc0ck/PetSitter | 8226755c92db217873eaf6f625c604be6999e6d1 | c9682462d9661762514cc58c50b3682a9dbca157 | refs/heads/master | 2023-03-24T12:34:56.628867 | 2021-03-21T12:09:54 | 2021-03-21T12:09:54 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 661 | java | package com.spring.petsitter;
/*create table petsitter_schedule(
PETSITTER_ID varchar2(30),
START_DATE date,
END_DATE date);
*/
public class PetsitterScheduleVO {
private String PETSITTER_ID;
private String START_DATE;
private String END_DATE;
public String getPETSITTER_ID() {
return PETSITTER_ID;
}
public void setPETSITTER_ID(String pETSITTER_ID) {
PETSITTER_ID = pETSITTER_ID;
}
public String getSTART_DATE() {
return START_DATE;
}
public void setSTART_DATE(String sTART_DATE) {
START_DATE = sTART_DATE;
}
public String getEND_DATE() {
return END_DATE;
}
public void setEND_DATE(String eND_DATE) {
END_DATE = eND_DATE;
}
}
| [
"[email protected]"
] | |
5606d28d973083c70678645414cd32346271a8e0 | 15d8c018e46d3b24f38608f67d32f41af459f392 | /wangyi/app/src/test/java/cn/com/jmw/m/ExampleUnitTest.java | 93c9f81852ca2300ef73b8aaa45773aa23bbc43f | [] | no_license | MayDayzll/wangyin | 180b36ee09b686a227e2da835f7001d261292955 | 1c1891a487b7d5ec0358cd6a52784d2e28863b24 | refs/heads/master | 2022-11-27T21:24:39.488647 | 2020-07-23T09:24:07 | 2020-07-23T09:24:07 | 281,834,914 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 373 | java | package cn.com.jmw.m;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() {
assertEquals(4, 2 + 2);
}
} | [
"[email protected]"
] | |
28ba7f949fa4f8ecb306b403c7defe92d289716c | 357d2e3ba19886d0b8438089a604e2f880129b1f | /source/es/src/test/java/com/bfd/test/util/EsWriter.java | 45a2a34e992a5f78ab71e72bb6f04fde5b92d25d | [
"Apache-2.0"
] | permissive | zhifengMaBeijing/m0 | 1f8fe61f5eca4e9de5e1288ef89d5afe56b52987 | 9caa19dc138584e98b8774f294bf9546b19f69ea | refs/heads/master | 2021-01-20T09:24:28.169361 | 2017-09-26T00:56:25 | 2017-09-26T00:56:25 | 90,250,602 | 0 | 2 | null | 2017-05-04T13:48:25 | 2017-05-04T10:25:29 | null | UTF-8 | Java | false | false | 470 | java | package com.bfd.test.util;
import java.io.IOException;
import java.net.URISyntaxException;
/**
* Created by BFD-483 on 2017/6/9.
*/
public class EsWriter {
public static void prepareData() throws URISyntaxException, IOException {
String nodes = "172.24.5.149:9300";
String port = "9300";
String cluster = "";
String s = FileLoader.loadResourceAsString("story/entity_person-jack.json");
System.out.println(s);
}
}
| [
"[email protected]"
] | |
1c6c741d7c79dbcf9e612765a0f73a763da924c6 | 85c8b6f842dbe50d464258749c699896ed8765c9 | /app/src/androidTest/java/fbspiele/tsvneuensorgticker/ExampleInstrumentedTest.java | 8d9d7b54e624f2ce868e087456dd0b2e770f67a8 | [] | no_license | fbspiele/tsvNeuensorgTicker | e5e9eba291ccb7136f2200ad261dc07e83c0b062 | 2e8d19f2e88a65e5c66dadfee23a456acf6b6992 | refs/heads/master | 2023-06-23T23:53:34.738495 | 2021-07-27T18:13:06 | 2021-07-27T18:13:06 | 389,385,955 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 738 | java | package fbspiele.tsvneuensorgticker;
import android.content.Context;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumented test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("fbspiele.tsvneuensorgticker", appContext.getPackageName());
}
}
| [
"[email protected]"
] | |
3ef75941e64088461bcdcb8cbc90b4fa5e644162 | e26fe7e8ca4dc1506757ffc32e5614065b382dd3 | /ql/src/test/org/apache/hadoop/hive/ql/exec/vector/expressions/TestVectorSubStr.java | 62d296d6cd6f10594b7bb39c45e1aed985829a4c | [
"Apache-2.0",
"JSON",
"GPL-1.0-or-later",
"MIT",
"BSD-3-Clause",
"BSD-2-Clause",
"LicenseRef-scancode-unknown-license-reference",
"Python-2.0"
] | permissive | siddharthteotia/hive | 47b36c6b3e6b4ce4e70b072f0af9a48271daf2a0 | 6d15ce49a65ca673bdebf176d90a2accdaedbcaf | refs/heads/master | 2020-03-23T13:17:37.044981 | 2018-07-10T00:43:56 | 2018-07-19T15:53:26 | 141,610,498 | 0 | 1 | Apache-2.0 | 2018-07-19T17:21:39 | 2018-07-19T17:21:39 | null | UTF-8 | Java | false | false | 13,371 | java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hive.ql.exec.vector.expressions;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import org.apache.hadoop.hive.common.type.DataTypePhysicalVariation;
import org.apache.hadoop.hive.conf.HiveConf;
import org.apache.hadoop.hive.ql.exec.ExprNodeEvaluator;
import org.apache.hadoop.hive.ql.exec.ExprNodeEvaluatorFactory;
import org.apache.hadoop.hive.ql.exec.FunctionInfo;
import org.apache.hadoop.hive.ql.exec.FunctionRegistry;
import org.apache.hadoop.hive.ql.exec.vector.VectorExtractRow;
import org.apache.hadoop.hive.ql.exec.vector.VectorRandomBatchSource;
import org.apache.hadoop.hive.ql.exec.vector.VectorRandomRowSource;
import org.apache.hadoop.hive.ql.exec.vector.VectorizationContext;
import org.apache.hadoop.hive.ql.exec.vector.VectorizedRowBatch;
import org.apache.hadoop.hive.ql.exec.vector.VectorizedRowBatchCtx;
import org.apache.hadoop.hive.ql.exec.vector.VectorRandomRowSource.GenerationSpec;
import org.apache.hadoop.hive.ql.exec.vector.VectorRandomRowSource.StringGenerationOption;
import org.apache.hadoop.hive.ql.exec.vector.expressions.VectorExpression;
import org.apache.hadoop.hive.ql.metadata.HiveException;
import org.apache.hadoop.hive.ql.parse.SemanticException;
import org.apache.hadoop.hive.ql.plan.ExprNodeColumnDesc;
import org.apache.hadoop.hive.ql.plan.ExprNodeConstantDesc;
import org.apache.hadoop.hive.ql.plan.ExprNodeDesc;
import org.apache.hadoop.hive.ql.plan.ExprNodeGenericFuncDesc;
import org.apache.hadoop.hive.ql.udf.generic.GenericUDF;
import org.apache.hadoop.hive.ql.udf.generic.GenericUDFIf;
import org.apache.hadoop.hive.ql.udf.generic.GenericUDFWhen;
import org.apache.hadoop.hive.serde2.io.HiveDecimalWritable;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorUtils;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorUtils.ObjectInspectorCopyOption;
import org.apache.hadoop.hive.serde2.typeinfo.DecimalTypeInfo;
import org.apache.hadoop.hive.serde2.typeinfo.PrimitiveTypeInfo;
import org.apache.hadoop.hive.serde2.typeinfo.TypeInfo;
import org.apache.hadoop.hive.serde2.typeinfo.TypeInfoFactory;
import org.apache.hadoop.hive.serde2.typeinfo.TypeInfoUtils;
import org.apache.hadoop.io.IntWritable;
import junit.framework.Assert;
import org.junit.Test;
public class TestVectorSubStr {
@Test
public void testString() throws Exception {
Random random = new Random(83221);
doTests(random);
}
public enum SubStrTestMode {
ROW_MODE,
ADAPTOR,
VECTOR_EXPRESSION;
static final int count = values().length;
}
private void doTests(Random random)
throws Exception {
for (int i = 0; i < 50; i++) {
doTests(random, false);
doTests(random, true);
}
}
private void doTests(Random random, boolean useLength)
throws Exception {
String typeName = "string";
TypeInfo typeInfo = TypeInfoFactory.stringTypeInfo;
TypeInfo targetTypeInfo = typeInfo;
String functionName = "substr";
List<GenerationSpec> generationSpecList = new ArrayList<GenerationSpec>();
List<DataTypePhysicalVariation> explicitDataTypePhysicalVariationList =
new ArrayList<DataTypePhysicalVariation>();
List<String> columns = new ArrayList<String>();
int columnNum = 0;
ExprNodeDesc col1Expr;
StringGenerationOption stringGenerationOption =
new StringGenerationOption(true, true);
generationSpecList.add(
GenerationSpec.createStringFamily(
typeInfo, stringGenerationOption));
explicitDataTypePhysicalVariationList.add(DataTypePhysicalVariation.NONE);
String columnName = "col" + (columnNum++);
col1Expr = new ExprNodeColumnDesc(typeInfo, columnName, "table", false);
columns.add(columnName);
VectorRandomRowSource rowSource = new VectorRandomRowSource();
rowSource.initGenerationSpecSchema(
random, generationSpecList, /* maxComplexDepth */ 0, /* allowNull */ true,
explicitDataTypePhysicalVariationList);
List<ExprNodeDesc> children = new ArrayList<ExprNodeDesc>();
children.add(col1Expr);
final int position = 10 - random.nextInt(21);
Object scalar2Object =
Integer.valueOf(position);
ExprNodeDesc col2Expr = new ExprNodeConstantDesc(TypeInfoFactory.intTypeInfo, scalar2Object);
children.add(col2Expr);
if (useLength) {
Object scalar3Object = random.nextInt(12);
ExprNodeDesc col3Expr = new ExprNodeConstantDesc(TypeInfoFactory.intTypeInfo, scalar3Object);
children.add(col3Expr);
}
//----------------------------------------------------------------------------------------------
String[] columnNames = columns.toArray(new String[0]);
String[] outputScratchTypeNames = new String[] { targetTypeInfo.getTypeName() };
DataTypePhysicalVariation[] outputDataTypePhysicalVariations =
new DataTypePhysicalVariation[] { DataTypePhysicalVariation.NONE };
VectorizedRowBatchCtx batchContext =
new VectorizedRowBatchCtx(
columnNames,
rowSource.typeInfos(),
rowSource.dataTypePhysicalVariations(),
/* dataColumnNums */ null,
/* partitionColumnCount */ 0,
/* virtualColumnCount */ 0,
/* neededVirtualColumns */ null,
outputScratchTypeNames,
outputDataTypePhysicalVariations);
Object[][] randomRows = rowSource.randomRows(100000);
VectorRandomBatchSource batchSource =
VectorRandomBatchSource.createInterestingBatches(
random,
rowSource,
randomRows,
null);
GenericUDF genericUdf;
FunctionInfo funcInfo = null;
try {
funcInfo = FunctionRegistry.getFunctionInfo(functionName);
} catch (SemanticException e) {
Assert.fail("Failed to load " + functionName + " " + e);
}
genericUdf = funcInfo.getGenericUDF();
final int rowCount = randomRows.length;
Object[][] resultObjectsArray = new Object[SubStrTestMode.count][];
for (int i = 0; i < SubStrTestMode.count; i++) {
Object[] resultObjects = new Object[rowCount];
resultObjectsArray[i] = resultObjects;
SubStrTestMode subStrTestMode = SubStrTestMode.values()[i];
switch (subStrTestMode) {
case ROW_MODE:
doRowIfTest(
typeInfo, targetTypeInfo,
columns, children, randomRows, rowSource.rowStructObjectInspector(),
genericUdf, resultObjects);
break;
case ADAPTOR:
case VECTOR_EXPRESSION:
doVectorIfTest(
typeInfo,
targetTypeInfo,
columns,
rowSource.typeInfos(),
rowSource.dataTypePhysicalVariations(),
children,
subStrTestMode,
batchSource,
batchContext,
genericUdf,
resultObjects);
break;
default:
throw new RuntimeException("Unexpected STRING Unary test mode " + subStrTestMode);
}
}
for (int i = 0; i < rowCount; i++) {
// Row-mode is the expected value.
Object expectedResult = resultObjectsArray[0][i];
for (int v = 1; v < SubStrTestMode.count; v++) {
Object vectorResult = resultObjectsArray[v][i];
if (expectedResult == null || vectorResult == null) {
if (expectedResult != null || vectorResult != null) {
Assert.fail(
"Row " + i +
" " + SubStrTestMode.values()[v] +
" result is NULL " + (vectorResult == null ? "YES" : "NO result " + vectorResult.toString()) +
" does not match row-mode expected result is NULL " +
(expectedResult == null ? "YES" : "NO result " + expectedResult.toString()) +
" row values " + Arrays.toString(randomRows[i]));
}
} else {
if (!expectedResult.equals(vectorResult)) {
Assert.fail(
"Row " + i +
" " + SubStrTestMode.values()[v] +
" result " + vectorResult.toString() +
" (" + vectorResult.getClass().getSimpleName() + ")" +
" does not match row-mode expected result " + expectedResult.toString() +
" (" + expectedResult.getClass().getSimpleName() + ")" +
" row values " + Arrays.toString(randomRows[i]));
}
}
}
}
}
private void doRowIfTest(TypeInfo typeInfo, TypeInfo targetTypeInfo,
List<String> columns, List<ExprNodeDesc> children,
Object[][] randomRows, ObjectInspector rowInspector,
GenericUDF genericUdf, Object[] resultObjects) throws Exception {
ExprNodeGenericFuncDesc exprDesc =
new ExprNodeGenericFuncDesc(typeInfo, genericUdf, children);
HiveConf hiveConf = new HiveConf();
ExprNodeEvaluator evaluator =
ExprNodeEvaluatorFactory.get(exprDesc, hiveConf);
evaluator.initialize(rowInspector);
ObjectInspector objectInspector = TypeInfoUtils
.getStandardWritableObjectInspectorFromTypeInfo(targetTypeInfo);
final int rowCount = randomRows.length;
for (int i = 0; i < rowCount; i++) {
Object[] row = randomRows[i];
Object result = evaluator.evaluate(row);
Object copyResult =
ObjectInspectorUtils.copyToStandardObject(
result, objectInspector, ObjectInspectorCopyOption.WRITABLE);
resultObjects[i] = copyResult;
}
}
private void extractResultObjects(VectorizedRowBatch batch, int rowIndex,
VectorExtractRow resultVectorExtractRow, Object[] scrqtchRow,
TypeInfo targetTypeInfo, Object[] resultObjects) {
ObjectInspector objectInspector = TypeInfoUtils
.getStandardWritableObjectInspectorFromTypeInfo(targetTypeInfo);
boolean selectedInUse = batch.selectedInUse;
int[] selected = batch.selected;
for (int logicalIndex = 0; logicalIndex < batch.size; logicalIndex++) {
final int batchIndex = (selectedInUse ? selected[logicalIndex] : logicalIndex);
try {
resultVectorExtractRow.extractRow(batch, batchIndex, scrqtchRow);
} catch (Exception e) {
Assert.fail(e.toString());
}
Object copyResult =
ObjectInspectorUtils.copyToStandardObject(
scrqtchRow[0], objectInspector, ObjectInspectorCopyOption.WRITABLE);
resultObjects[rowIndex++] = copyResult;
}
}
private void doVectorIfTest(TypeInfo typeInfo, TypeInfo targetTypeInfo,
List<String> columns,
TypeInfo[] typeInfos, DataTypePhysicalVariation[] dataTypePhysicalVariations,
List<ExprNodeDesc> children,
SubStrTestMode subStrTestMode,
VectorRandomBatchSource batchSource, VectorizedRowBatchCtx batchContext,
GenericUDF genericUdf, Object[] resultObjects)
throws Exception {
ExprNodeGenericFuncDesc exprDesc =
new ExprNodeGenericFuncDesc(targetTypeInfo, genericUdf, children);
HiveConf hiveConf = new HiveConf();
if (subStrTestMode == SubStrTestMode.ADAPTOR) {
hiveConf.setBoolVar(HiveConf.ConfVars.HIVE_TEST_VECTOR_ADAPTOR_OVERRIDE, true);
}
VectorizationContext vectorizationContext =
new VectorizationContext(
"name",
columns,
Arrays.asList(typeInfos),
Arrays.asList(dataTypePhysicalVariations),
hiveConf);
VectorExpression vectorExpression = vectorizationContext.getVectorExpression(exprDesc);
VectorizedRowBatch batch = batchContext.createVectorizedRowBatch();
VectorExtractRow resultVectorExtractRow = new VectorExtractRow();
resultVectorExtractRow.init(new TypeInfo[] { targetTypeInfo }, new int[] { columns.size() });
Object[] scrqtchRow = new Object[1];
// System.out.println("*VECTOR EXPRESSION* " + vectorExpression.getClass().getSimpleName());
/*
System.out.println(
"*DEBUG* typeInfo " + typeInfo.toString() +
" targetTypeInfo " + targetTypeInfo.toString() +
" subStrTestMode " + subStrTestMode +
" vectorExpression " + vectorExpression.getClass().getSimpleName());
*/
batchSource.resetBatchIteration();
int rowIndex = 0;
while (true) {
if (!batchSource.fillNextBatch(batch)) {
break;
}
vectorExpression.evaluate(batch);
extractResultObjects(batch, rowIndex, resultVectorExtractRow, scrqtchRow,
targetTypeInfo, resultObjects);
rowIndex += batch.size;
}
}
}
| [
"[email protected]"
] | |
2d4ddc099351484d9ea8931186bf47f7c960be10 | 47b1eb6cdb39ab1b6ecdd3a3ccd8cb0e85932703 | /CP2406_Prac1/src/week9/ProgrammingExercisesChapter14/Question1Quote/JBookQuote2.java | 7de839814fb26fc4ee4e4f81d41023ce9e1a858a | [] | no_license | HarryHenricks/CP2406_2019_BasicJava | 4b5e16558afd257c8d33b50ca2dc3274c4ea0187 | d8020ca5b14cb1362286b9a2f50d27321d7320d4 | refs/heads/master | 2020-07-01T10:15:50.053133 | 2019-10-25T08:35:17 | 2019-10-25T08:35:17 | 201,141,864 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,303 | java | package week9.ProgrammingExercisesChapter14.Question1Quote;
import javax.swing.*;
public class JBookQuote2 {
public static void main(String[] args) {
JFrame frame = new JFrame("Favourite book quote");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton button = new JButton("Display book");
button.setBounds(125,75,150,100);
String quote = "<html>He who fights with monsters should look to it that he himself does not become a monster. " +
"And when you gaze long into an abyss the abyss also gazes into you.</html>";
JLabel quoteLabel = new JLabel("Quote");
quoteLabel.setText(quote);
quoteLabel.setBounds(0, 0, 400, 50);
frame.getContentPane().add(quoteLabel);
frame.getContentPane().add(button);
frame.setSize(400, 300);
frame.setLocationRelativeTo(null);
frame.setLayout(null);
frame.setVisible(true);
button.addActionListener(e -> {
String bookInfo = "Beyond Good and Evil by Friedrich Nietzsche";
JLabel bookLabel = new JLabel();
bookLabel.setText(bookInfo);
bookLabel.setBounds(0, 200, 400, 50);
frame.getContentPane().add(bookLabel);
frame.repaint();
});
}
}
| [
"[email protected]"
] | |
355dfa43195eee63a873c1d5d371e2c140ce4f3c | 3334bee9484db954c4508ad507f6de0d154a939f | /d3n/java-src/user-message-service/src/main/java/de/ascendro/f4m/server/session/GlobalClientSessionDao.java | afb3e8737aa148fe0120e9dfad656b960f675723 | [] | no_license | VUAN86/d3n | c2fc46fc1f188d08fa6862e33cac56762e006f71 | e5d6ac654821f89b7f4f653e2aaef3de7c621f8b | refs/heads/master | 2020-05-07T19:25:43.926090 | 2019-04-12T07:25:55 | 2019-04-12T07:25:55 | 180,806,736 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 300 | java | package de.ascendro.f4m.server.session;
public interface GlobalClientSessionDao {
/**
* Returns active session information for given user.
* null, if user has no active sessions.
* @param userId
* @return
*/
GlobalClientSessionInfo getGlobalClientSessionInfoByUserId(String userId);
}
| [
"[email protected]"
] | |
4b40bcf1363934b7cbd856bdc544b0471f3077eb | ce39f978efedfb9f29ee1ee6f13a9dbe8053d184 | /src/main/java/fr/royalpha/sheepwars/v1_9_R2/entity/firework/PH_PO_EntityMetadata.java | a5ab631460907770411f352f08e4c0ae7f619c45 | [] | no_license | YFPS/UltimateSheepWars | 24d729587053ae2bd1cb9b9960e64f245051e959 | e66d7dcb7cf6991049a17abcce1cbe09da378212 | refs/heads/master | 2023-03-31T08:32:16.276430 | 2021-04-12T09:59:03 | 2021-04-12T09:59:03 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,417 | java | package fr.royalpha.sheepwars.v1_9_R2.entity.firework;
import java.lang.reflect.Field;
import java.util.LinkedList;
import java.util.List;
public class PH_PO_EntityMetadata extends aPacketHandler{
public int entityId;
public List<jDataWatcherItem<?>> metadata;
private static Class<?> clazz;
private static Field field_entityid;
private static Field field_metadata;
static{
try{
PH_PO_EntityMetadata.clazz=ProtocolUtils.getMinecraftClass("PacketPlayOutEntityMetadata");
PH_PO_EntityMetadata.field_entityid=PH_PO_EntityMetadata.clazz.getDeclaredField("a");
PH_PO_EntityMetadata.field_entityid.setAccessible(true);
PH_PO_EntityMetadata.field_metadata=PH_PO_EntityMetadata.clazz.getDeclaredField("b");
PH_PO_EntityMetadata.field_metadata.setAccessible(true);
}catch(Exception e){
e.printStackTrace();
}
}
public PH_PO_EntityMetadata(int entityId, List<jDataWatcherItem<?>> metadata){
this.entityId=entityId;
this.metadata=metadata;
}
/**
* Build
*/
@SuppressWarnings({"rawtypes", "unchecked"})
@Override
public Object build()throws Exception{
Object packet=PH_PO_EntityMetadata.clazz.newInstance();
PH_PO_EntityMetadata.field_entityid.set(packet, this.entityId);
List list=new LinkedList<>();
for(jDataWatcherItem<?> item:this.metadata)list.add(item.build());
PH_PO_EntityMetadata.field_metadata.set(packet, list);
return packet;
}
} | [
"[email protected]"
] | |
e6dac72406e51359de035ddfbec922fef984e22f | 1606e3372af6c109c1aa7d38d7de10a600e07778 | /src/filozofi/Filozof.java | 8ce6de12ec467ddd1cc7d6f727af339f1ee1c7ae | [] | no_license | nsinfoPRO/PetFilozofa-github | 8b68ef6a280ae82a36a4dee913082c6f1bde8ead | 909127dc1a606a6b3e20209b07e5ce52456cfeff | refs/heads/master | 2020-03-21T10:42:46.858390 | 2018-07-04T08:57:09 | 2018-07-04T08:57:09 | 138,466,861 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,152 | java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package filozofi;
import static java.lang.Thread.yield;
/**
*
* @author Nenad
*/
public class Filozof extends Thread {
private int index;
private Stapic levi;
private Stapic desni;
private int statistikajela;
public Filozof(int index, Stapic left, Stapic right) {
this.index = index;
this.levi = left;
this.desni = right;
statistikajela = 0;
}
public void run() {
for (int i = 0; i < 1000; i++) {
levi.take();
desni.take();
statistikajela++;
levi.release();
desni.release();
yield(); //yield metoda postavlja thread koji se
} //trenutno izvrsava u sleep mod
}
public String toString() {
return ("[" + index + "] filozof je jeo [" + statistikajela + "]" + "puta");
}
}
| [
"Nenad@TrendSonic11"
] | Nenad@TrendSonic11 |
0b1b70868402d8e3344c2dcb9c4dd25d064f75ba | f6976554be41ea1fcccd745665307657e9b75b73 | /webmagic-core/src/main/java/cn/thu/info/mapper/ReginfoMapper.java | a1051dddfe12697ec2b2845623396f37123fe4c7 | [
"MIT"
] | permissive | strongman1995/company-info-system | ce75bda374f39f711137d232516cb1782c65b49b | f55d923c4914977d8cc46ee8026f43a10d2b2ca0 | refs/heads/master | 2020-05-24T10:26:49.762624 | 2019-05-18T05:08:23 | 2019-05-18T05:08:23 | 187,228,328 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 1,105 | java | package cn.thu.info.mapper;
import cn.thu.info.model.Reginfo;
import cn.thu.info.model.ReginfoExample;
import java.util.List;
import org.apache.ibatis.annotations.Param;
public interface ReginfoMapper {
int countByExample(ReginfoExample example);
int deleteByExample(ReginfoExample example);
int deleteByPrimaryKey(Integer rId);
int insert(Reginfo record);
int insertSelective(Reginfo record);
List<Reginfo> selectByExampleWithBLOBs(ReginfoExample example);
List<Reginfo> selectByExample(ReginfoExample example);
Reginfo selectByPrimaryKey(Integer rId);
int updateByExampleSelective(@Param("record") Reginfo record, @Param("example") ReginfoExample example);
int updateByExampleWithBLOBs(@Param("record") Reginfo record, @Param("example") ReginfoExample example);
int updateByExample(@Param("record") Reginfo record, @Param("example") ReginfoExample example);
int updateByPrimaryKeySelective(Reginfo record);
int updateByPrimaryKeyWithBLOBs(Reginfo record);
int updateByPrimaryKey(Reginfo record);
} | [
"[email protected]"
] | |
682643812258109832ee0e09a13640a212c957d2 | 89a2da6414afc1e7eacc250caff042b04dbc40f7 | /searchManager/src/main/java/com/search/manager/core/model/ImagePath.java | 249089ab70b47acefa45b5dff933e22c1bd6ac62 | [] | no_license | zelld0m/Smanager | 0d3dd88f227d83226ea6c1aa6bbbb478e57408fd | 805c9582c84b5db5e3f0693d38ba2f55f97e33d7 | refs/heads/Tempest-Update | 2022-12-28T12:14:26.961159 | 2015-09-23T06:23:03 | 2015-09-28T01:14:29 | 85,912,981 | 0 | 0 | null | 2022-12-15T23:45:13 | 2017-03-23T06:04:17 | HTML | UTF-8 | Java | false | false | 2,630 | java | package com.search.manager.core.model;
import org.directwebremoting.annotations.DataTransferObject;
import org.directwebremoting.convert.BeanConverter;
@DataTransferObject(converter = BeanConverter.class)
public class ImagePath extends ModelBean {
private static final long serialVersionUID = 716880772182956579L;
public String storeId;
public String id;
public String path;
public String size;
public ImagePathType pathType;
public String alias;
public ImagePath() {
}
public ImagePath(String storeId, String id, String path, String size, ImagePathType pathType, String alias,
String createdBy, String lastModifiedBy) {
super();
this.storeId = storeId;
this.id = id;
this.path = path;
this.size = size;
this.pathType = pathType;
this.alias = alias;
this.createdBy = createdBy;
this.lastModifiedBy = lastModifiedBy;
}
public ImagePath(String storeId, String id, String path, String size, ImagePathType pathType, String alias,
String createdBy) {
this(storeId, id, path, size, pathType, alias, createdBy, null);
}
public ImagePath(String storeId, String id, String path, String size, ImagePathType pathType, String alias) {
this(storeId, id, path, size, pathType, alias, null, null);
}
public ImagePath(String storeId, String id, String path) {
this(storeId, id, path, null, null, null, null);
}
public ImagePath(String storeId, String path) {
this(storeId, null, path, null, null, null, null);
}
public String getId() {
return id;
}
// @Field("imagePathId")
public void setId(String id) {
this.id = id;
}
public String getPath() {
return path;
}
// @Field
public void setPath(String path) {
this.path = path;
}
public ImagePathType getPathType() {
return pathType;
}
// @Field
public void setPathType(ImagePathType pathType) {
this.pathType = pathType;
}
public String getAlias() {
return alias;
}
// @Field
public void setAlias(String alias) {
this.alias = alias;
}
public String getStoreId() {
return storeId;
}
public void setStoreId(String storeId) {
this.storeId = storeId;
}
public String getSize() {
return size;
}
// @Field
public void setSize(String size) {
this.size = size;
}
} | [
"[email protected]"
] | |
7ff98edd9e592f714ae24eba2f1a568bad6974b1 | 0af8b92686a58eb0b64e319b22411432aca7a8f3 | /single-large-project/src/test/java/org/gradle/test/performancenull_136/Testnull_13597.java | fd46208b74c8617b9eb563dbcbc2c939a7c37171 | [] | no_license | gradle/performance-comparisons | b0d38db37c326e0ce271abebdb3c91769b860799 | e53dc7182fafcf9fedf07920cbbea8b40ee4eef4 | refs/heads/master | 2023-08-14T19:24:39.164276 | 2022-11-24T05:18:33 | 2022-11-24T05:18:33 | 80,121,268 | 17 | 15 | null | 2022-09-30T08:04:35 | 2017-01-26T14:25:33 | null | UTF-8 | Java | false | false | 308 | java | package org.gradle.test.performancenull_136;
import static org.junit.Assert.*;
public class Testnull_13597 {
private final Productionnull_13597 production = new Productionnull_13597("value");
@org.junit.Test
public void test() {
assertEquals(production.getProperty(), "value");
}
} | [
"[email protected]"
] | |
5685bf577684a5236f20ada10c06939fb72c0438 | a28c87191ed4be8570f03e56f93af685b250f57f | /src/main/java/com/cryptotool/cipher/MyCipher.java | 0ea4ff7a24ca2963ebe025b02ec6c8306a4fafb0 | [] | no_license | codemonkey2019/cryptotool | dff858bc60193546f0a897e94a7d7dbb60e43823 | 0dff712457eab3458842dd1c93a0e135f501995a | refs/heads/master | 2021-09-19T20:52:26.106035 | 2020-08-12T12:38:39 | 2020-08-12T12:38:39 | 214,769,257 | 1 | 0 | null | 2021-08-13T15:34:31 | 2019-10-13T06:02:17 | Java | UTF-8 | Java | false | false | 755 | java | package com.cryptotool.cipher;
/**
* 加解密算法的总接口
*/
public interface MyCipher {
/**
* 加密算法
*
* @param data 明文数据
* @return 密文数据
* @throws Exception
*/
byte[] encrypt(byte[] data);
/**
* 解密算法
*
* @param data 明文数据
* @return 密文数据
* @throws Exception
*/
byte[] decrypt(byte[] data);
/**
* 文件加密
*
* @param inPath
* @param outPath
* @throws Exception
*/
void encryptFile(String inPath, String outPath);
/**
* 文件解密
*
* @param inPath
* @param outPath
* @throws Exception
*/
void decryptFile(String inPath, String outPath);
}
| [
"[email protected]"
] | |
ee2b5549bae1b01e80bdbd944b8b2dc4ca006bcc | dda1c032fe9060c681b283cc57139e817fb3d591 | /src/test/java/com/ngn/bms/BmsLeadApplicationTests.java | 597dfbf83d3b62991d51f10b68d5ebd612871107 | [] | no_license | Prakriti-58/BMS_Tender | 76c5f35c6fbdfa631724858b7627a1b0babc2e95 | 64cdac4def3153de677a9841850a566fd2b2f948 | refs/heads/main | 2023-08-18T21:11:38.320956 | 2021-10-13T07:57:56 | 2021-10-13T07:57:56 | 387,992,216 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 204 | java | package com.ngn.bms;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class BmsLeadApplicationTests {
@Test
void contextLoads() {
}
}
| [
"[email protected]"
] | |
d701df13c33673ba68008a0b09c2f74ecfc51b45 | b3962c9b4858fce5a58f56018e45c5b0416e3743 | /ymall-web-admin/src/main/java/com/yuu/ymall/web/admin/web/controller/CountController.java | d094c09447cfeb89ab918605b4dc3b7e7a602bb6 | [] | no_license | tfei5/YMall | 1603db9b9211b91991b9f8fbcf7d1e132f8ebb9b | 73787a3f021bdb73ea3250c11021ba7e482e080e | refs/heads/master | 2022-12-14T00:04:04.398860 | 2020-09-06T05:53:30 | 2020-09-06T05:53:30 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,476 | java | package com.yuu.ymall.web.admin.web.controller;
import com.yuu.ymall.commons.dto.BaseResult;
import com.yuu.ymall.web.admin.service.CountService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
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;
/**
* 统计 Controler
*
* @author by Yuu
* @classname CountController
* @date 2019/6/21 10:56
*/
@RestController
@Api(description = "统计")
@RequestMapping("count")
public class CountController {
@Autowired
private CountService countService;
/**
* 订单销量
*
* @param type 类型
* @param startTime 开始时间
* @param endTime 结束时间
* @param year 年份
* @return
*/
@GetMapping("order")
@ApiOperation(value = "订单销量统计")
public BaseResult countOrder(@RequestParam int type,
@RequestParam(required = false) String startTime,
@RequestParam(required = false) String endTime,
@RequestParam(required = false) int year) {
BaseResult baseResult = countService.countOrder(type, startTime, endTime, year);
return baseResult;
}
}
| [
"[email protected]"
] | |
83bcf995cc6d0deeb43db37499a560186484da3f | 3eb5cdb6442569f401b4c29560bc8d1f55c65e3e | /api/src/main/java/io/strimzi/api/kafka/model/EntityUserOperatorSpec.java | 90d212449aa3f39b507a1a75a3f664ee93c3cdf6 | [
"Apache-2.0"
] | permissive | enterstudio/strimzi-kafka-operator | 56e33987140cd1dfc9ed8bde228a1b3eafebd87f | 15b471bfee1d6d19733e57ac312f4f2497da66c0 | refs/heads/master | 2020-04-12T16:54:44.558954 | 2018-12-20T09:56:43 | 2018-12-20T09:56:43 | 162,627,737 | 2 | 0 | Apache-2.0 | 2018-12-20T20:22:57 | 2018-12-20T20:22:56 | null | UTF-8 | Java | false | false | 4,390 | java | /*
* Copyright 2018, Strimzi authors.
* License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html).
*/
package io.strimzi.api.kafka.model;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import io.strimzi.crdgenerator.annotations.Description;
import io.strimzi.crdgenerator.annotations.Minimum;
import io.sundr.builder.annotations.Buildable;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
/**
* Representation of the User Operator.
*/
@Buildable(
editableEnabled = false,
generateBuilderPackage = false,
builderPackage = "io.fabric8.kubernetes.api.builder"
)
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({"watchedNamespace", "image",
"reconciliationIntervalSeconds", "zookeeperSessionTimeoutSeconds",
"resources", "logging", "jvmOptions"})
public class EntityUserOperatorSpec implements Serializable {
private static final long serialVersionUID = 1L;
public static final String DEFAULT_IMAGE =
System.getenv().getOrDefault("STRIMZI_DEFAULT_USER_OPERATOR_IMAGE", "strimzi/user-operator:latest");
public static final int DEFAULT_HEALTHCHECK_DELAY = 10;
public static final int DEFAULT_HEALTHCHECK_TIMEOUT = 5;
public static final int DEFAULT_ZOOKEEPER_PORT = 2181;
public static final long DEFAULT_FULL_RECONCILIATION_INTERVAL_SECONDS = 120;
public static final long DEFAULT_ZOOKEEPER_SESSION_TIMEOUT_SECONDS = 6;
private String watchedNamespace;
private String image = DEFAULT_IMAGE;
private long reconciliationIntervalSeconds = DEFAULT_FULL_RECONCILIATION_INTERVAL_SECONDS;
private long zookeeperSessionTimeoutSeconds = DEFAULT_ZOOKEEPER_SESSION_TIMEOUT_SECONDS;
private Resources resources;
private Logging logging;
private EntityOperatorJvmOptions jvmOptions;
private Map<String, Object> additionalProperties = new HashMap<>(0);
@Description("The namespace the User Operator should watch.")
public String getWatchedNamespace() {
return watchedNamespace;
}
public void setWatchedNamespace(String watchedNamespace) {
this.watchedNamespace = watchedNamespace;
}
@Description("The image to use for the User Operator")
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
@Description("Interval between periodic reconciliations.")
@Minimum(0)
public long getReconciliationIntervalSeconds() {
return reconciliationIntervalSeconds;
}
public void setReconciliationIntervalSeconds(long reconciliationIntervalSeconds) {
this.reconciliationIntervalSeconds = reconciliationIntervalSeconds;
}
@Description("Timeout for the Zookeeper session")
@Minimum(0)
public long getZookeeperSessionTimeoutSeconds() {
return zookeeperSessionTimeoutSeconds;
}
public void setZookeeperSessionTimeoutSeconds(long zookeeperSessionTimeoutSeconds) {
this.zookeeperSessionTimeoutSeconds = zookeeperSessionTimeoutSeconds;
}
@Description("Resource constraints (limits and requests).")
public Resources getResources() {
return resources;
}
@Description("Resource constraints (limits and requests).")
public void setResources(Resources resources) {
this.resources = resources;
}
@Description("Logging configuration")
@JsonInclude(value = JsonInclude.Include.NON_NULL)
public Logging getLogging() {
return logging;
}
public void setLogging(Logging logging) {
this.logging = logging;
}
@JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
@JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
@JsonInclude(JsonInclude.Include.NON_EMPTY)
@Description("JVM Options for pods")
public EntityOperatorJvmOptions getJvmOptions() {
return jvmOptions;
}
public void setJvmOptions(EntityOperatorJvmOptions jvmOptions) {
this.jvmOptions = jvmOptions;
}
}
| [
"[email protected]"
] | |
1566fd17aa068b8e954356175733766cf5ebdb3e | c42abe86bfced3072b3df7a551bce85eaa655353 | /source/ViewPagerDemo/app/src/main/java/com/enjoy/zero/viewpagerdemo/view/NoPreViewPager.java | b52374958c2552c0154f254b021b82ad0a7672fb | [] | no_license | fanzhangvip/enjoy01 | 97b36e16c5f8a18aad8cef8a04ddf037a64504b1 | 92f7e70f2b6e00b083d16eb72387665c924adaad | refs/heads/master | 2022-10-26T14:31:28.606166 | 2022-10-18T15:32:13 | 2022-10-18T15:32:13 | 183,878,032 | 2 | 6 | null | 2022-10-05T03:05:11 | 2019-04-28T08:15:08 | C++ | UTF-8 | Java | false | false | 125,641 | java | /*
* Copyright (C) 2011 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.enjoy.zero.viewpagerdemo.view;
import android.content.Context;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.database.DataSetObserver;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Parcel;
import android.os.Parcelable;
import android.os.SystemClock;
import android.support.annotation.CallSuper;
import android.support.annotation.DrawableRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v4.os.ParcelableCompat;
import android.support.v4.os.ParcelableCompatCreatorCallbacks;
import android.support.v4.view.AbsSavedState;
import android.support.v4.view.AccessibilityDelegateCompat;
import android.support.v4.view.MotionEventCompat;
import android.support.v4.view.PagerTitleStrip;
import android.support.v4.view.VelocityTrackerCompat;
import android.support.v4.view.ViewCompat;
import android.support.v4.view.WindowInsetsCompat;
import android.support.v4.view.accessibility.AccessibilityEventCompat;
import android.support.v4.view.accessibility.AccessibilityNodeInfoCompat;
import android.support.v4.view.accessibility.AccessibilityRecordCompat;
import android.support.v4.widget.EdgeEffectCompat;
import android.util.AttributeSet;
import android.util.Log;
import android.view.FocusFinder;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.SoundEffectConstants;
import android.view.VelocityTracker;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.view.accessibility.AccessibilityEvent;
import android.view.animation.Interpolator;
import android.widget.Scroller;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class NoPreViewPager extends ViewGroup {
private static final String TAG = "ViewPager";
private static final boolean DEBUG = false;
private static final boolean USE_CACHE = false;
private static final int DEFAULT_OFFSCREEN_PAGES = 0;//TODO: 源码默认值为1
private static final int MAX_SETTLE_DURATION = 600; // ms
private static final int MIN_DISTANCE_FOR_FLING = 25; // dips
private static final int DEFAULT_GUTTER_SIZE = 16; // dips
private static final int MIN_FLING_VELOCITY = 400; // dips
static final int[] LAYOUT_ATTRS = new int[]{
android.R.attr.layout_gravity
};
/**
* Used to track what the expected number of items in the adapter should be.
* If the app changes this when we don't expect it, we'll throw a big obnoxious exception.
*/
private int mExpectedAdapterCount;
static class ItemInfo {
Object object;
int position;
boolean scrolling;
float widthFactor;
float offset;
@Override
public String toString() {
return "ItemInfo{" +
"position=" + position +
", scrolling=" + scrolling +
", widthFactor=" + widthFactor +
", offset=" + offset +
", object=" + object +
'}';
}
}
private static final Comparator<ItemInfo> COMPARATOR = new Comparator<ItemInfo>() {
@Override
public int compare(ItemInfo lhs, ItemInfo rhs) {
return lhs.position - rhs.position;
}
};
private static final Interpolator sInterpolator = new Interpolator() {
@Override
public float getInterpolation(float t) {
t -= 1.0f;
return t * t * t * t * t + 1.0f;
}
};
private final ArrayList<ItemInfo> mItems = new ArrayList<ItemInfo>();
private final ItemInfo mTempItem = new ItemInfo();
private final Rect mTempRect = new Rect();
PagerAdapter mAdapter;
int mCurItem; // Index of currently displayed page.
private int mRestoredCurItem = -1;
private Parcelable mRestoredAdapterState = null;
private ClassLoader mRestoredClassLoader = null;
private Scroller mScroller;
private boolean mIsScrollStarted;
private PagerObserver mObserver;
private int mPageMargin;
private Drawable mMarginDrawable;
private int mTopPageBounds;
private int mBottomPageBounds;
// Offsets of the first and last items, if known.
// Set during population, used to determine if we are at the beginning
// or end of the pager data set during touch scrolling.
private float mFirstOffset = -Float.MAX_VALUE;
private float mLastOffset = Float.MAX_VALUE;
private int mChildWidthMeasureSpec;
private int mChildHeightMeasureSpec;
private boolean mInLayout;
private boolean mScrollingCacheEnabled;
private boolean mPopulatePending;
private int mOffscreenPageLimit = DEFAULT_OFFSCREEN_PAGES;
private boolean mIsBeingDragged;
private boolean mIsUnableToDrag;
private int mDefaultGutterSize;
private int mGutterSize;
private int mTouchSlop;
/**
* Position of the last motion event.
*/
private float mLastMotionX;
private float mLastMotionY;
private float mInitialMotionX;
private float mInitialMotionY;
/**
* ID of the active pointer. This is used to retain consistency during
* drags/flings if multiple pointers are used.
*/
private int mActivePointerId = INVALID_POINTER;
/**
* Sentinel value for no current active pointer.
* Used by {@link #mActivePointerId}.
*/
private static final int INVALID_POINTER = -1;
/**
* Determines speed during touch scrolling
*/
private VelocityTracker mVelocityTracker;
private int mMinimumVelocity;
private int mMaximumVelocity;
private int mFlingDistance;
private int mCloseEnough;
// If the pager is at least this close to its final position, complete the scroll
// on touch down and let the user interact with the content inside instead of
// "catching" the flinging pager.
private static final int CLOSE_ENOUGH = 2; // dp
private boolean mFakeDragging;
private long mFakeDragBeginTime;
private EdgeEffectCompat mLeftEdge;
private EdgeEffectCompat mRightEdge;
private boolean mFirstLayout = true;
private boolean mNeedCalculatePageOffsets = false;
private boolean mCalledSuper;
private int mDecorChildCount;
private List<OnPageChangeListener> mOnPageChangeListeners;
private OnPageChangeListener mOnPageChangeListener;
private OnPageChangeListener mInternalPageChangeListener;
private List<OnAdapterChangeListener> mAdapterChangeListeners;
private PageTransformer mPageTransformer;
private int mPageTransformerLayerType;
private Method mSetChildrenDrawingOrderEnabled;
private static final int DRAW_ORDER_DEFAULT = 0;
private static final int DRAW_ORDER_FORWARD = 1;
private static final int DRAW_ORDER_REVERSE = 2;
private int mDrawingOrder;
private ArrayList<View> mDrawingOrderedChildren;
private static final ViewPositionComparator sPositionComparator = new ViewPositionComparator();
/**
* Indicates that the pager is in an idle, settled state. The current page
* is fully in view and no animation is in progress.
*/
public static final int SCROLL_STATE_IDLE = 0;
/**
* Indicates that the pager is currently being dragged by the user.
*/
public static final int SCROLL_STATE_DRAGGING = 1;
/**
* Indicates that the pager is in the process of settling to a final position.
*/
public static final int SCROLL_STATE_SETTLING = 2;
private final Runnable mEndScrollRunnable = new Runnable() {
@Override
public void run() {
setScrollState(SCROLL_STATE_IDLE);
populate();
}
};
private int mScrollState = SCROLL_STATE_IDLE;
/**
* Callback interface for responding to changing state of the selected page.
*/
public interface OnPageChangeListener {
/**
* This method will be invoked when the current page is scrolled, either as part
* of a programmatically initiated smooth scroll or a user initiated touch scroll.
*
* @param position Position index of the first page currently being displayed.
* Page position+1 will be visible if positionOffset is nonzero.
* @param positionOffset Value from [0, 1) indicating the offset from the page at position.
* @param positionOffsetPixels Value in pixels indicating the offset from position.
*/
void onPageScrolled(int position, float positionOffset, int positionOffsetPixels);
/**
* This method will be invoked when a new page becomes selected. Animation is not
* necessarily complete.
*
* @param position Position index of the new selected page.
*/
void onPageSelected(int position);
/**
* Called when the scroll state changes. Useful for discovering when the user
* begins dragging, when the pager is automatically settling to the current page,
* or when it is fully stopped/idle.
*
* @param state The new scroll state.
* @see NoPreViewPager#SCROLL_STATE_IDLE
* @see NoPreViewPager#SCROLL_STATE_DRAGGING
* @see NoPreViewPager#SCROLL_STATE_SETTLING
*/
void onPageScrollStateChanged(int state);
}
/**
* Simple implementation of the {@link OnPageChangeListener} interface with stub
* implementations of each method. Extend this if you do not intend to override
* every method of {@link OnPageChangeListener}.
*/
public static class SimpleOnPageChangeListener implements OnPageChangeListener {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
// This space for rent
}
@Override
public void onPageSelected(int position) {
// This space for rent
}
@Override
public void onPageScrollStateChanged(int state) {
// This space for rent
}
}
/**
* A PageTransformer is invoked whenever a visible/attached page is scrolled.
* This offers an opportunity for the application to apply a custom transformation
* to the page views using animation properties.
*
* <p>As property animation is only supported as of Android 3.0 and forward,
* setting a PageTransformer on a ViewPager on earlier platform versions will
* be ignored.</p>
*/
public interface PageTransformer {
/**
* Apply a property transformation to the given page.
*
* @param page Apply the transformation to this page
* @param position Position of page relative to the current front-and-center
* position of the pager. 0 is front and center. 1 is one full
* page position to the right, and -1 is one page position to the left.
*/
void transformPage(View page, float position);
}
/**
* Callback interface for responding to adapter changes.
*/
public interface OnAdapterChangeListener {
/**
* Called when the adapter for the given view pager has changed.
*
* @param viewPager ViewPager where the adapter change has happened
* @param oldAdapter the previously set adapter
* @param newAdapter the newly set adapter
*/
void onAdapterChanged(@NonNull NoPreViewPager viewPager,
@Nullable PagerAdapter oldAdapter, @Nullable PagerAdapter newAdapter);
}
/**
* Annotation which allows marking of views to be decoration views when added to a view
* pager.
*
* <p>Views marked with this annotation can be added to the view pager with a layout resource.
* An example being {@link PagerTitleStrip}.</p>
*
* <p>You can also control whether a view is a decor view but setting
* {@link LayoutParams#isDecor} on the child's layout params.</p>
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Inherited
public @interface DecorView {
}
public NoPreViewPager(Context context) {
super(context);
initViewPager();
}
public NoPreViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
initViewPager();
}
void initViewPager() {
setWillNotDraw(false);
setDescendantFocusability(FOCUS_AFTER_DESCENDANTS);
setFocusable(true);
final Context context = getContext();
mScroller = new Scroller(context, sInterpolator);
final ViewConfiguration configuration = ViewConfiguration.get(context);
final float density = context.getResources().getDisplayMetrics().density;
mTouchSlop = configuration.getScaledPagingTouchSlop();
mMinimumVelocity = (int) (MIN_FLING_VELOCITY * density);
mMaximumVelocity = configuration.getScaledMaximumFlingVelocity();
mLeftEdge = new EdgeEffectCompat(context);
mRightEdge = new EdgeEffectCompat(context);
mFlingDistance = (int) (MIN_DISTANCE_FOR_FLING * density);
mCloseEnough = (int) (CLOSE_ENOUGH * density);
mDefaultGutterSize = (int) (DEFAULT_GUTTER_SIZE * density);
ViewCompat.setAccessibilityDelegate(this, new MyAccessibilityDelegate());
if (ViewCompat.getImportantForAccessibility(this)
== ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_AUTO) {
ViewCompat.setImportantForAccessibility(this,
ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_YES);
}
ViewCompat.setOnApplyWindowInsetsListener(this,
new android.support.v4.view.OnApplyWindowInsetsListener() {
private final Rect mTempRect = new Rect();
@Override
public WindowInsetsCompat onApplyWindowInsets(final View v,
final WindowInsetsCompat originalInsets) {
// First let the ViewPager itself try and consume them...
final WindowInsetsCompat applied =
ViewCompat.onApplyWindowInsets(v, originalInsets);
if (applied.isConsumed()) {
// If the ViewPager consumed all insets, return now
return applied;
}
// Now we'll manually dispatch the insets to our children. Since ViewPager
// children are always full-height, we do not want to use the standard
// ViewGroup dispatchApplyWindowInsets since if child 0 consumes them,
// the rest of the children will not receive any insets. To workaround this
// we manually dispatch the applied insets, not allowing children to
// consume them from each other. We do however keep track of any insets
// which are consumed, returning the union of our children's consumption
final Rect res = mTempRect;
res.left = applied.getSystemWindowInsetLeft();
res.top = applied.getSystemWindowInsetTop();
res.right = applied.getSystemWindowInsetRight();
res.bottom = applied.getSystemWindowInsetBottom();
for (int i = 0, count = getChildCount(); i < count; i++) {
final WindowInsetsCompat childInsets = ViewCompat
.dispatchApplyWindowInsets(getChildAt(i), applied);
// Now keep track of any consumed by tracking each dimension's min
// value
res.left = Math.min(childInsets.getSystemWindowInsetLeft(),
res.left);
res.top = Math.min(childInsets.getSystemWindowInsetTop(),
res.top);
res.right = Math.min(childInsets.getSystemWindowInsetRight(),
res.right);
res.bottom = Math.min(childInsets.getSystemWindowInsetBottom(),
res.bottom);
}
// Now return a new WindowInsets, using the consumed window insets
return applied.replaceSystemWindowInsets(
res.left, res.top, res.right, res.bottom);
}
});
}
@Override
protected void onDetachedFromWindow() {
removeCallbacks(mEndScrollRunnable);
// To be on the safe side, abort the scroller
if ((mScroller != null) && !mScroller.isFinished()) {
mScroller.abortAnimation();
}
super.onDetachedFromWindow();
}
void setScrollState(int newState) {
if (mScrollState == newState) {
return;
}
mScrollState = newState;
if (mPageTransformer != null) {
// PageTransformers can do complex things that benefit from hardware layers.
enableLayers(newState != SCROLL_STATE_IDLE);
}
dispatchOnScrollStateChanged(newState);
}
/**
* Set a PagerAdapter that will supply views for this pager as needed.
*
* @param adapter Adapter to use
*/
public void setAdapter(PagerAdapter adapter) {
if (mAdapter != null) {
mAdapter.setViewPagerObserver(null);
mAdapter.startUpdate(this);
for (int i = 0; i < mItems.size(); i++) {
final ItemInfo ii = mItems.get(i);
mAdapter.destroyItem(this, ii.position, ii.object);
}
mAdapter.finishUpdate(this);
mItems.clear();
removeNonDecorViews();
mCurItem = 0;
scrollTo(0, 0);
}
final PagerAdapter oldAdapter = mAdapter;
mAdapter = adapter;
mExpectedAdapterCount = 0;
if (mAdapter != null) {
if (mObserver == null) {
mObserver = new PagerObserver();
}
mAdapter.setViewPagerObserver(mObserver);
mPopulatePending = false;
final boolean wasFirstLayout = mFirstLayout;
mFirstLayout = true;
mExpectedAdapterCount = mAdapter.getCount();
if (mRestoredCurItem >= 0) {
mAdapter.restoreState(mRestoredAdapterState, mRestoredClassLoader);
setCurrentItemInternal(mRestoredCurItem, false, true);
mRestoredCurItem = -1;
mRestoredAdapterState = null;
mRestoredClassLoader = null;
} else if (!wasFirstLayout) {
populate();
} else {
requestLayout();
}
}
// Dispatch the change to any listeners
if (mAdapterChangeListeners != null && !mAdapterChangeListeners.isEmpty()) {
for (int i = 0, count = mAdapterChangeListeners.size(); i < count; i++) {
mAdapterChangeListeners.get(i).onAdapterChanged(this, oldAdapter, adapter);
}
}
}
private void removeNonDecorViews() {
for (int i = 0; i < getChildCount(); i++) {
final View child = getChildAt(i);
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
if (!lp.isDecor) {
removeViewAt(i);
i--;
}
}
}
/**
* Retrieve the current adapter supplying pages.
*
* @return The currently registered PagerAdapter
*/
public PagerAdapter getAdapter() {
return mAdapter;
}
/**
* Add a listener that will be invoked whenever the adapter for this ViewPager changes.
*
* @param listener listener to add
*/
public void addOnAdapterChangeListener(@NonNull OnAdapterChangeListener listener) {
if (mAdapterChangeListeners == null) {
mAdapterChangeListeners = new ArrayList<>();
}
mAdapterChangeListeners.add(listener);
}
/**
* Remove a listener that was previously added via
* {@link #addOnAdapterChangeListener(OnAdapterChangeListener)}.
*
* @param listener listener to remove
*/
public void removeOnAdapterChangeListener(@NonNull OnAdapterChangeListener listener) {
if (mAdapterChangeListeners != null) {
mAdapterChangeListeners.remove(listener);
}
}
private int getClientWidth() {
return getMeasuredWidth() - getPaddingLeft() - getPaddingRight();
}
/**
* Set the currently selected page. If the ViewPager has already been through its first
* layout with its current adapter there will be a smooth animated transition between
* the current item and the specified item.
*
* @param item Item index to select
*/
public void setCurrentItem(int item) {
mPopulatePending = false;
setCurrentItemInternal(item, !mFirstLayout, false);
}
/**
* Set the currently selected page.
*
* @param item Item index to select
* @param smoothScroll True to smoothly scroll to the new item, false to transition immediately
*/
public void setCurrentItem(int item, boolean smoothScroll) {
mPopulatePending = false;
setCurrentItemInternal(item, smoothScroll, false);
}
public int getCurrentItem() {
return mCurItem;
}
void setCurrentItemInternal(int item, boolean smoothScroll, boolean always) {
setCurrentItemInternal(item, smoothScroll, always, 0);
}
void setCurrentItemInternal(int item, boolean smoothScroll, boolean always, int velocity) {
if (mAdapter == null || mAdapter.getCount() <= 0) {
setScrollingCacheEnabled(false);
return;
}
if (!always && mCurItem == item && mItems.size() != 0) {
setScrollingCacheEnabled(false);
return;
}
if (item < 0) {
item = 0;
} else if (item >= mAdapter.getCount()) {
item = mAdapter.getCount() - 1;
}
final int pageLimit = mOffscreenPageLimit;
if (item > (mCurItem + pageLimit) || item < (mCurItem - pageLimit)) {
// We are doing a jump by more than one page. To avoid
// glitches, we want to keep all current pages in the view
// until the scroll ends.
for (int i = 0; i < mItems.size(); i++) {
mItems.get(i).scrolling = true;
}
}
final boolean dispatchSelected = mCurItem != item;
if (mFirstLayout) {
// We don't have any idea how big we are yet and shouldn't have any pages either.
// Just set things up and let the pending layout handle things.
mCurItem = item;
if (dispatchSelected) {
dispatchOnPageSelected(item);
}
requestLayout();
} else {
populate(item);
scrollToItem(item, smoothScroll, velocity, dispatchSelected);
}
}
private void scrollToItem(int item, boolean smoothScroll, int velocity,
boolean dispatchSelected) {
final ItemInfo curInfo = infoForPosition(item);
int destX = 0;
if (curInfo != null) {
final int width = getClientWidth();
destX = (int) (width * Math.max(mFirstOffset,
Math.min(curInfo.offset, mLastOffset)));
}
if (smoothScroll) {
smoothScrollTo(destX, 0, velocity);
if (dispatchSelected) {
dispatchOnPageSelected(item);
}
} else {
if (dispatchSelected) {
dispatchOnPageSelected(item);
}
completeScroll(false);
scrollTo(destX, 0);
pageScrolled(destX);
}
}
/**
* Set a listener that will be invoked whenever the page changes or is incrementally
* scrolled. See {@link OnPageChangeListener}.
*
* @param listener Listener to set
* @deprecated Use {@link #addOnPageChangeListener(OnPageChangeListener)}
* and {@link #removeOnPageChangeListener(OnPageChangeListener)} instead.
*/
@Deprecated
public void setOnPageChangeListener(OnPageChangeListener listener) {
mOnPageChangeListener = listener;
}
/**
* Add a listener that will be invoked whenever the page changes or is incrementally
* scrolled. See {@link OnPageChangeListener}.
*
* <p>Components that add a listener should take care to remove it when finished.
* Other components that take ownership of a view may call {@link #clearOnPageChangeListeners()}
* to remove all attached listeners.</p>
*
* @param listener listener to add
*/
public void addOnPageChangeListener(OnPageChangeListener listener) {
if (mOnPageChangeListeners == null) {
mOnPageChangeListeners = new ArrayList<>();
}
mOnPageChangeListeners.add(listener);
}
/**
* Remove a listener that was previously added via
* {@link #addOnPageChangeListener(OnPageChangeListener)}.
*
* @param listener listener to remove
*/
public void removeOnPageChangeListener(OnPageChangeListener listener) {
if (mOnPageChangeListeners != null) {
mOnPageChangeListeners.remove(listener);
}
}
/**
* Remove all listeners that are notified of any changes in scroll state or position.
*/
public void clearOnPageChangeListeners() {
if (mOnPageChangeListeners != null) {
mOnPageChangeListeners.clear();
}
}
/**
* Sets a {@link PageTransformer} that will be called for each attached page whenever
* the scroll position is changed. This allows the application to apply custom property
* transformations to each page, overriding the default sliding behavior.
*
* <p><em>Note:</em> Prior to Android 3.0 the property animation APIs did not exist.
* As a result, setting a PageTransformer prior to Android 3.0 (API 11) will have no effect.
* By default, calling this method will cause contained pages to use
* {@link ViewCompat#LAYER_TYPE_HARDWARE}. This layer type allows custom alpha transformations,
* but it will cause issues if any of your pages contain a {@link android.view.SurfaceView}
* and you have not called {@link android.view.SurfaceView#setZOrderOnTop(boolean)} to put that
* {@link android.view.SurfaceView} above your app content. To disable this behavior, call
* {@link #setPageTransformer(boolean, PageTransformer, int)} and pass
* {@link ViewCompat#LAYER_TYPE_NONE} for {@code pageLayerType}.</p>
*
* @param reverseDrawingOrder true if the supplied PageTransformer requires page views
* to be drawn from last to first instead of first to last.
* @param transformer PageTransformer that will modify each page's animation properties
*/
public void setPageTransformer(boolean reverseDrawingOrder, PageTransformer transformer) {
setPageTransformer(reverseDrawingOrder, transformer, ViewCompat.LAYER_TYPE_HARDWARE);
}
/**
* Sets a {@link PageTransformer} that will be called for each attached page whenever
* the scroll position is changed. This allows the application to apply custom property
* transformations to each page, overriding the default sliding behavior.
*
* <p><em>Note:</em> Prior to Android 3.0 ({@link Build.VERSION_CODES#HONEYCOMB API 11}),
* the property animation APIs did not exist. As a result, setting a PageTransformer prior
* to API 11 will have no effect.</p>
*
* @param reverseDrawingOrder true if the supplied PageTransformer requires page views
* to be drawn from last to first instead of first to last.
* @param transformer PageTransformer that will modify each page's animation properties
* @param pageLayerType View layer type that should be used for ViewPager pages. It should be
* either {@link ViewCompat#LAYER_TYPE_HARDWARE},
* {@link ViewCompat#LAYER_TYPE_SOFTWARE}, or
* {@link ViewCompat#LAYER_TYPE_NONE}.
*/
public void setPageTransformer(boolean reverseDrawingOrder, PageTransformer transformer,
int pageLayerType) {
if (Build.VERSION.SDK_INT >= 11) {
final boolean hasTransformer = transformer != null;
final boolean needsPopulate = hasTransformer != (mPageTransformer != null);
mPageTransformer = transformer;
setChildrenDrawingOrderEnabledCompat(hasTransformer);
if (hasTransformer) {
mDrawingOrder = reverseDrawingOrder ? DRAW_ORDER_REVERSE : DRAW_ORDER_FORWARD;
mPageTransformerLayerType = pageLayerType;
} else {
mDrawingOrder = DRAW_ORDER_DEFAULT;
}
if (needsPopulate) populate();
}
}
void setChildrenDrawingOrderEnabledCompat(boolean enable) {
if (Build.VERSION.SDK_INT >= 7) {
if (mSetChildrenDrawingOrderEnabled == null) {
try {
mSetChildrenDrawingOrderEnabled = ViewGroup.class.getDeclaredMethod(
"setChildrenDrawingOrderEnabled", new Class[]{Boolean.TYPE});
} catch (NoSuchMethodException e) {
Log.e(TAG, "Can't find setChildrenDrawingOrderEnabled", e);
}
}
try {
mSetChildrenDrawingOrderEnabled.invoke(this, enable);
} catch (Exception e) {
Log.e(TAG, "Error changing children drawing order", e);
}
}
}
@Override
protected int getChildDrawingOrder(int childCount, int i) {
final int index = mDrawingOrder == DRAW_ORDER_REVERSE ? childCount - 1 - i : i;
final int result =
((LayoutParams) mDrawingOrderedChildren.get(index).getLayoutParams()).childIndex;
return result;
}
/**
* Set a separate OnPageChangeListener for internal use by the support library.
*
* @param listener Listener to set
* @return The old listener that was set, if any.
*/
OnPageChangeListener setInternalPageChangeListener(OnPageChangeListener listener) {
OnPageChangeListener oldListener = mInternalPageChangeListener;
mInternalPageChangeListener = listener;
return oldListener;
}
/**
* Returns the number of pages that will be retained to either side of the
* current page in the view hierarchy in an idle state. Defaults to 1.
*
* @return How many pages will be kept offscreen on either side
* @see #setOffscreenPageLimit(int)
*/
public int getOffscreenPageLimit() {
return mOffscreenPageLimit;
}
/**
* Set the number of pages that should be retained to either side of the
* current page in the view hierarchy in an idle state. Pages beyond this
* limit will be recreated from the adapter when needed.
*
* <p>This is offered as an optimization. If you know in advance the number
* of pages you will need to support or have lazy-loading mechanisms in place
* on your pages, tweaking this setting can have benefits in perceived smoothness
* of paging animations and interaction. If you have a small number of pages (3-4)
* that you can keep active all at once, less time will be spent in layout for
* newly created view subtrees as the user pages back and forth.</p>
*
* <p>You should keep this limit low, especially if your pages have complex layouts.
* This setting defaults to 1.</p>
*
* @param limit How many pages will be kept offscreen in an idle state.
*/
public void setOffscreenPageLimit(int limit) {
// TODO: 2. 源码这里会对设置的limit进行校验,< 1的值 都会修改为默认值1
// if (limit < DEFAULT_OFFSCREEN_PAGES) {
// Log.w(TAG, "Requested offscreen page limit " + limit + " too small; defaulting to "
// + DEFAULT_OFFSCREEN_PAGES);
// limit = DEFAULT_OFFSCREEN_PAGES;
// }
if (limit != mOffscreenPageLimit) {
mOffscreenPageLimit = limit;
populate();
}
}
/**
* Set the margin between pages.
*
* @param marginPixels Distance between adjacent pages in pixels
* @see #getPageMargin()
* @see #setPageMarginDrawable(Drawable)
* @see #setPageMarginDrawable(int)
*/
public void setPageMargin(int marginPixels) {
final int oldMargin = mPageMargin;
mPageMargin = marginPixels;
final int width = getWidth();
recomputeScrollPosition(width, width, marginPixels, oldMargin);
requestLayout();
}
/**
* Return the margin between pages.
*
* @return The size of the margin in pixels
*/
public int getPageMargin() {
return mPageMargin;
}
/**
* Set a drawable that will be used to fill the margin between pages.
*
* @param d Drawable to display between pages
*/
public void setPageMarginDrawable(Drawable d) {
mMarginDrawable = d;
if (d != null) refreshDrawableState();
setWillNotDraw(d == null);
invalidate();
}
/**
* Set a drawable that will be used to fill the margin between pages.
*
* @param resId Resource ID of a drawable to display between pages
*/
public void setPageMarginDrawable(@DrawableRes int resId) {
setPageMarginDrawable(ContextCompat.getDrawable(getContext(), resId));
}
@Override
protected boolean verifyDrawable(Drawable who) {
return super.verifyDrawable(who) || who == mMarginDrawable;
}
@Override
protected void drawableStateChanged() {
super.drawableStateChanged();
final Drawable d = mMarginDrawable;
if (d != null && d.isStateful()) {
d.setState(getDrawableState());
}
}
// We want the duration of the page snap animation to be influenced by the distance that
// the screen has to travel, however, we don't want this duration to be effected in a
// purely linear fashion. Instead, we use this method to moderate the effect that the distance
// of travel has on the overall snap duration.
float distanceInfluenceForSnapDuration(float f) {
f -= 0.5f; // center the values about 0.
f *= 0.3f * Math.PI / 2.0f;
return (float) Math.sin(f);
}
/**
* Like {@link View#scrollBy}, but scroll smoothly instead of immediately.
*
* @param x the number of pixels to scroll by on the X axis
* @param y the number of pixels to scroll by on the Y axis
*/
void smoothScrollTo(int x, int y) {
smoothScrollTo(x, y, 0);
}
/**
* Like {@link View#scrollBy}, but scroll smoothly instead of immediately.
*
* @param x the number of pixels to scroll by on the X axis
* @param y the number of pixels to scroll by on the Y axis
* @param velocity the velocity associated with a fling, if applicable. (0 otherwise)
*/
void smoothScrollTo(int x, int y, int velocity) {
if (getChildCount() == 0) {
// Nothing to do.
setScrollingCacheEnabled(false);
return;
}
int sx;
boolean wasScrolling = (mScroller != null) && !mScroller.isFinished();
if (wasScrolling) {
// We're in the middle of a previously initiated scrolling. Check to see
// whether that scrolling has actually started (if we always call getStartX
// we can get a stale value from the scroller if it hadn't yet had its first
// computeScrollOffset call) to decide what is the current scrolling position.
sx = mIsScrollStarted ? mScroller.getCurrX() : mScroller.getStartX();
// And abort the current scrolling.
mScroller.abortAnimation();
setScrollingCacheEnabled(false);
} else {
sx = getScrollX();
}
int sy = getScrollY();
int dx = x - sx;
int dy = y - sy;
if (dx == 0 && dy == 0) {
completeScroll(false);
populate();
setScrollState(SCROLL_STATE_IDLE);
return;
}
setScrollingCacheEnabled(true);
setScrollState(SCROLL_STATE_SETTLING);
final int width = getClientWidth();
final int halfWidth = width / 2;
final float distanceRatio = Math.min(1f, 1.0f * Math.abs(dx) / width);
final float distance = halfWidth + halfWidth
* distanceInfluenceForSnapDuration(distanceRatio);
int duration;
velocity = Math.abs(velocity);
if (velocity > 0) {
duration = 4 * Math.round(1000 * Math.abs(distance / velocity));
} else {
final float pageWidth = width * mAdapter.getPageWidth(mCurItem);
final float pageDelta = (float) Math.abs(dx) / (pageWidth + mPageMargin);
duration = (int) ((pageDelta + 1) * 100);
}
duration = Math.min(duration, MAX_SETTLE_DURATION);
// Reset the "scroll started" flag. It will be flipped to true in all places
// where we call computeScrollOffset().
mIsScrollStarted = false;
mScroller.startScroll(sx, sy, dx, dy, duration);
ViewCompat.postInvalidateOnAnimation(this);
}
ItemInfo addNewItem(int position, int index) {
ItemInfo ii = new ItemInfo();
ii.position = position;
ii.object = mAdapter.instantiateItem(this, position);
ii.widthFactor = mAdapter.getPageWidth(position);
if (index < 0 || index >= mItems.size()) {
mItems.add(ii);
} else {
mItems.add(index, ii);
}
return ii;
}
void dataSetChanged() {
// This method only gets called if our observer is attached, so mAdapter is non-null.
final int adapterCount = mAdapter.getCount();
mExpectedAdapterCount = adapterCount;
boolean needPopulate = mItems.size() < mOffscreenPageLimit * 2 + 1
&& mItems.size() < adapterCount;
int newCurrItem = mCurItem;
boolean isUpdating = false;
for (int i = 0; i < mItems.size(); i++) {
final ItemInfo ii = mItems.get(i);
final int newPos = mAdapter.getItemPosition(ii.object);
if (newPos == PagerAdapter.POSITION_UNCHANGED) {
continue;
}
if (newPos == PagerAdapter.POSITION_NONE) {
mItems.remove(i);
i--;
if (!isUpdating) {
mAdapter.startUpdate(this);
isUpdating = true;
}
mAdapter.destroyItem(this, ii.position, ii.object);
needPopulate = true;
if (mCurItem == ii.position) {
// Keep the current item in the valid range
newCurrItem = Math.max(0, Math.min(mCurItem, adapterCount - 1));
needPopulate = true;
}
continue;
}
if (ii.position != newPos) {
if (ii.position == mCurItem) {
// Our current item changed position. Follow it.
newCurrItem = newPos;
}
ii.position = newPos;
needPopulate = true;
}
}
if (isUpdating) {
mAdapter.finishUpdate(this);
}
Collections.sort(mItems, COMPARATOR);
if (needPopulate) {
// Reset our known page widths; populate will recompute them.
final int childCount = getChildCount();
for (int i = 0; i < childCount; i++) {
final View child = getChildAt(i);
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
if (!lp.isDecor) {
lp.widthFactor = 0.f;
}
}
setCurrentItemInternal(newCurrItem, false, true);
requestLayout();
}
}
void populate() {
populate(mCurItem);
}
void populate(int newCurrentItem) {
ItemInfo oldCurInfo = null;
if (mCurItem != newCurrentItem) {
oldCurInfo = infoForPosition(mCurItem);
mCurItem = newCurrentItem;
}
if (mAdapter == null) {
sortChildDrawingOrder();
return;
}
// Bail now if we are waiting to populate. This is to hold off
// on creating views from the time the user releases their finger to
// fling to a new position until we have finished the scroll to
// that position, avoiding glitches from happening at that point.
if (mPopulatePending) {
if (DEBUG) Log.i(TAG, "populate is pending, skipping for now...");
sortChildDrawingOrder();
return;
}
// Also, don't populate until we are attached to a window. This is to
// avoid trying to populate before we have restored our view hierarchy
// state and conflicting with what is restored.
if (getWindowToken() == null) {
return;
}
mAdapter.startUpdate(this);
// TODO: 3. 缓存范围为[startPos ... endPos]
final int pageLimit = mOffscreenPageLimit;
final int startPos = Math.max(0, mCurItem - pageLimit);
final int N = mAdapter.getCount();
final int endPos = Math.min(N - 1, mCurItem + pageLimit);
if (N != mExpectedAdapterCount) {
String resName;
try {
resName = getResources().getResourceName(getId());
} catch (Resources.NotFoundException e) {
resName = Integer.toHexString(getId());
}
throw new IllegalStateException("The application's PagerAdapter changed the adapter's"
+ " contents without calling PagerAdapter#notifyDataSetChanged!"
+ " Expected adapter item count: " + mExpectedAdapterCount + ", found: " + N
+ " Pager id: " + resName
+ " Pager class: " + getClass()
+ " Problematic adapter: " + mAdapter.getClass());
}
// Locate the currently focused item or add it if needed.
int curIndex = -1;
ItemInfo curItem = null;
for (curIndex = 0; curIndex < mItems.size(); curIndex++) {
final ItemInfo ii = mItems.get(curIndex);
if (ii.position >= mCurItem) {
if (ii.position == mCurItem) curItem = ii;
break;
}
}
if (curItem == null && N > 0) {
curItem = addNewItem(mCurItem, curIndex);
}
// Fill 3x the available width or up to the number of offscreen
// pages requested to either side, whichever is larger.
// If we have no current item we have no work to do.
if (curItem != null) {
float extraWidthLeft = 0.f;
int itemIndex = curIndex - 1;
ItemInfo ii = itemIndex >= 0 ? mItems.get(itemIndex) : null;
final int clientWidth = getClientWidth();
final float leftWidthNeeded = clientWidth <= 0 ? 0 :
2.f - curItem.widthFactor + (float) getPaddingLeft() / (float) clientWidth;
for (int pos = mCurItem - 1; pos >= 0; pos--) {
if (extraWidthLeft >= leftWidthNeeded && pos < startPos) {
if (ii == null) {
break;
}
if (pos == ii.position && !ii.scrolling) {
mItems.remove(itemIndex);
mAdapter.destroyItem(this, pos, ii.object);
if (DEBUG) {
Log.i(TAG, "populate() - destroyItem() with pos: " + pos
+ " view: " + ((View) ii.object));
}
itemIndex--;
curIndex--;
ii = itemIndex >= 0 ? mItems.get(itemIndex) : null;
}
// TODO: 4. 就算你设置的limit是0,那么 startPos == endPos,这里还是会预加载左边的一个view
} else if (ii != null && pos == ii.position) {
// extraWidthLeft += ii.widthFactor;
// itemIndex--;
// ii = itemIndex >= 0 ? mItems.get(itemIndex) : null;
} else {
// ii = addNewItem(pos, itemIndex + 1);
// extraWidthLeft += ii.widthFactor;
// curIndex++;
// ii = itemIndex >= 0 ? mItems.get(itemIndex) : null;
}
}
float extraWidthRight = curItem.widthFactor;
itemIndex = curIndex + 1;
if (extraWidthRight < 2.f) {
ii = itemIndex < mItems.size() ? mItems.get(itemIndex) : null;
final float rightWidthNeeded = clientWidth <= 0 ? 0 :
(float) getPaddingRight() / (float) clientWidth + 2.f;
for (int pos = mCurItem + 1; pos < N; pos++) {
if (extraWidthRight >= rightWidthNeeded && pos > endPos) {
if (ii == null) {
break;
}
if (pos == ii.position && !ii.scrolling) {
mItems.remove(itemIndex);
mAdapter.destroyItem(this, pos, ii.object);
if (DEBUG) {
Log.i(TAG, "populate() - destroyItem() with pos: " + pos
+ " view: " + ((View) ii.object));
}
ii = itemIndex < mItems.size() ? mItems.get(itemIndex) : null;
}
// TODO: 5. 就算你设置的limit是0,那么 startPos == endPos,这里还是会预加载右边的一个view
} else if (ii != null && pos == ii.position) {
// extraWidthRight += ii.widthFactor;
// itemIndex++;
// ii = itemIndex < mItems.size() ? mItems.get(itemIndex) : null;
} else {
// ii = addNewItem(pos, itemIndex);
// itemIndex++;
// extraWidthRight += ii.widthFactor;
// ii = itemIndex < mItems.size() ? mItems.get(itemIndex) : null;
}
}
}
calculatePageOffsets(curItem, curIndex, oldCurInfo);
}
if (DEBUG) {
Log.i(TAG, "Current page list:");
for (int i = 0; i < mItems.size(); i++) {
Log.i(TAG, "#" + i + ": page " + mItems.get(i).position);
}
}
mAdapter.setPrimaryItem(this, mCurItem, curItem != null ? curItem.object : null);
mAdapter.finishUpdate(this);
// Check width measurement of current pages and drawing sort order.
// Update LayoutParams as needed.
final int childCount = getChildCount();
for (int i = 0; i < childCount; i++) {
final View child = getChildAt(i);
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
lp.childIndex = i;
if (!lp.isDecor && lp.widthFactor == 0.f) {
// 0 means requery the adapter for this, it doesn't have a valid width.
final ItemInfo ii = infoForChild(child);
if (ii != null) {
lp.widthFactor = ii.widthFactor;
lp.position = ii.position;
}
}
}
sortChildDrawingOrder();
if (hasFocus()) {
View currentFocused = findFocus();
ItemInfo ii = currentFocused != null ? infoForAnyChild(currentFocused) : null;
if (ii == null || ii.position != mCurItem) {
for (int i = 0; i < getChildCount(); i++) {
View child = getChildAt(i);
ii = infoForChild(child);
if (ii != null && ii.position == mCurItem) {
if (child.requestFocus(View.FOCUS_FORWARD)) {
break;
}
}
}
}
}
}
private void sortChildDrawingOrder() {
if (mDrawingOrder != DRAW_ORDER_DEFAULT) {
if (mDrawingOrderedChildren == null) {
mDrawingOrderedChildren = new ArrayList<View>();
} else {
mDrawingOrderedChildren.clear();
}
final int childCount = getChildCount();
for (int i = 0; i < childCount; i++) {
final View child = getChildAt(i);
mDrawingOrderedChildren.add(child);
}
Collections.sort(mDrawingOrderedChildren, sPositionComparator);
}
}
private void calculatePageOffsets(ItemInfo curItem, int curIndex, ItemInfo oldCurInfo) {
final int N = mAdapter.getCount();
final int width = getClientWidth();
final float marginOffset = width > 0 ? (float) mPageMargin / width : 0;
// Fix up offsets for later layout.
if (oldCurInfo != null) {
final int oldCurPosition = oldCurInfo.position;
// Base offsets off of oldCurInfo.
if (oldCurPosition < curItem.position) {
int itemIndex = 0;
ItemInfo ii = null;
float offset = oldCurInfo.offset + oldCurInfo.widthFactor + marginOffset;
for (int pos = oldCurPosition + 1;
pos <= curItem.position && itemIndex < mItems.size(); pos++) {
ii = mItems.get(itemIndex);
while (pos > ii.position && itemIndex < mItems.size() - 1) {
itemIndex++;
ii = mItems.get(itemIndex);
}
while (pos < ii.position) {
// We don't have an item populated for this,
// ask the adapter for an offset.
offset += mAdapter.getPageWidth(pos) + marginOffset;
pos++;
}
ii.offset = offset;
offset += ii.widthFactor + marginOffset;
}
} else if (oldCurPosition > curItem.position) {
int itemIndex = mItems.size() - 1;
ItemInfo ii = null;
float offset = oldCurInfo.offset;
for (int pos = oldCurPosition - 1;
pos >= curItem.position && itemIndex >= 0; pos--) {
ii = mItems.get(itemIndex);
while (pos < ii.position && itemIndex > 0) {
itemIndex--;
ii = mItems.get(itemIndex);
}
while (pos > ii.position) {
// We don't have an item populated for this,
// ask the adapter for an offset.
offset -= mAdapter.getPageWidth(pos) + marginOffset;
pos--;
}
offset -= ii.widthFactor + marginOffset;
ii.offset = offset;
}
}
}
// Base all offsets off of curItem.
final int itemCount = mItems.size();
float offset = curItem.offset;
int pos = curItem.position - 1;
mFirstOffset = curItem.position == 0 ? curItem.offset : -Float.MAX_VALUE;
mLastOffset = curItem.position == N - 1
? curItem.offset + curItem.widthFactor - 1 : Float.MAX_VALUE;
// Previous pages
for (int i = curIndex - 1; i >= 0; i--, pos--) {
final ItemInfo ii = mItems.get(i);
while (pos > ii.position) {
offset -= mAdapter.getPageWidth(pos--) + marginOffset;
}
offset -= ii.widthFactor + marginOffset;
ii.offset = offset;
if (ii.position == 0) mFirstOffset = offset;
}
offset = curItem.offset + curItem.widthFactor + marginOffset;
pos = curItem.position + 1;
// Next pages
for (int i = curIndex + 1; i < itemCount; i++, pos++) {
final ItemInfo ii = mItems.get(i);
while (pos < ii.position) {
offset += mAdapter.getPageWidth(pos++) + marginOffset;
}
if (ii.position == N - 1) {
mLastOffset = offset + ii.widthFactor - 1;
}
ii.offset = offset;
offset += ii.widthFactor + marginOffset;
}
mNeedCalculatePageOffsets = false;
}
/**
* This is the persistent state that is saved by ViewPager. Only needed
* if you are creating a sublass of ViewPager that must save its own
* state, in which case it should implement a subclass of this which
* contains that state.
*/
public static class SavedState extends AbsSavedState {
int position;
Parcelable adapterState;
ClassLoader loader;
public SavedState(Parcelable superState) {
super(superState);
}
@Override
public void writeToParcel(Parcel out, int flags) {
super.writeToParcel(out, flags);
out.writeInt(position);
out.writeParcelable(adapterState, flags);
}
@Override
public String toString() {
return "FragmentPager.SavedState{"
+ Integer.toHexString(System.identityHashCode(this))
+ " position=" + position + "}";
}
public static final Creator<SavedState> CREATOR = ParcelableCompat.newCreator(
new ParcelableCompatCreatorCallbacks<SavedState>() {
@Override
public SavedState createFromParcel(Parcel in, ClassLoader loader) {
return new SavedState(in, loader);
}
@Override
public SavedState[] newArray(int size) {
return new SavedState[size];
}
});
SavedState(Parcel in, ClassLoader loader) {
super(in, loader);
if (loader == null) {
loader = getClass().getClassLoader();
}
position = in.readInt();
adapterState = in.readParcelable(loader);
this.loader = loader;
}
}
@Override
public Parcelable onSaveInstanceState() {
Parcelable superState = super.onSaveInstanceState();
SavedState ss = new SavedState(superState);
ss.position = mCurItem;
if (mAdapter != null) {
ss.adapterState = mAdapter.saveState();
}
return ss;
}
@Override
public void onRestoreInstanceState(Parcelable state) {
if (!(state instanceof SavedState)) {
super.onRestoreInstanceState(state);
return;
}
SavedState ss = (SavedState) state;
super.onRestoreInstanceState(ss.getSuperState());
if (mAdapter != null) {
mAdapter.restoreState(ss.adapterState, ss.loader);
setCurrentItemInternal(ss.position, false, true);
} else {
mRestoredCurItem = ss.position;
mRestoredAdapterState = ss.adapterState;
mRestoredClassLoader = ss.loader;
}
}
@Override
public void addView(View child, int index, ViewGroup.LayoutParams params) {
if (!checkLayoutParams(params)) {
params = generateLayoutParams(params);
}
final LayoutParams lp = (LayoutParams) params;
// Any views added via inflation should be classed as part of the decor
lp.isDecor |= isDecorView(child);
if (mInLayout) {
if (lp != null && lp.isDecor) {
throw new IllegalStateException("Cannot add pager decor view during layout");
}
lp.needsMeasure = true;
addViewInLayout(child, index, params);
} else {
super.addView(child, index, params);
}
if (USE_CACHE) {
if (child.getVisibility() != GONE) {
child.setDrawingCacheEnabled(mScrollingCacheEnabled);
} else {
child.setDrawingCacheEnabled(false);
}
}
}
private static boolean isDecorView(@NonNull View view) {
Class<?> clazz = view.getClass();
return clazz.getAnnotation(DecorView.class) != null;
}
@Override
public void removeView(View view) {
if (mInLayout) {
removeViewInLayout(view);
} else {
super.removeView(view);
}
}
ItemInfo infoForChild(View child) {
for (int i = 0; i < mItems.size(); i++) {
ItemInfo ii = mItems.get(i);
if (mAdapter.isViewFromObject(child, ii.object)) {
return ii;
}
}
return null;
}
ItemInfo infoForAnyChild(View child) {
ViewParent parent;
while ((parent = child.getParent()) != this) {
if (parent == null || !(parent instanceof View)) {
return null;
}
child = (View) parent;
}
return infoForChild(child);
}
ItemInfo infoForPosition(int position) {
for (int i = 0; i < mItems.size(); i++) {
ItemInfo ii = mItems.get(i);
if (ii.position == position) {
return ii;
}
}
return null;
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
mFirstLayout = true;
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// For simple implementation, our internal size is always 0.
// We depend on the container to specify the layout size of
// our view. We can't really know what it is since we will be
// adding and removing different arbitrary views and do not
// want the layout to change as this happens.
setMeasuredDimension(getDefaultSize(0, widthMeasureSpec),
getDefaultSize(0, heightMeasureSpec));
final int measuredWidth = getMeasuredWidth();
final int maxGutterSize = measuredWidth / 10;
mGutterSize = Math.min(maxGutterSize, mDefaultGutterSize);
// Children are just made to fill our space.
int childWidthSize = measuredWidth - getPaddingLeft() - getPaddingRight();
int childHeightSize = getMeasuredHeight() - getPaddingTop() - getPaddingBottom();
/*
* Make sure all children have been properly measured. Decor views first.
* Right now we cheat and make this less complicated by assuming decor
* views won't intersect. We will pin to edges based on gravity.
*/
int size = getChildCount();
for (int i = 0; i < size; ++i) {
final View child = getChildAt(i);
if (child.getVisibility() != GONE) {
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
if (lp != null && lp.isDecor) {
final int hgrav = lp.gravity & Gravity.HORIZONTAL_GRAVITY_MASK;
final int vgrav = lp.gravity & Gravity.VERTICAL_GRAVITY_MASK;
int widthMode = MeasureSpec.AT_MOST;
int heightMode = MeasureSpec.AT_MOST;
boolean consumeVertical = vgrav == Gravity.TOP || vgrav == Gravity.BOTTOM;
boolean consumeHorizontal = hgrav == Gravity.LEFT || hgrav == Gravity.RIGHT;
if (consumeVertical) {
widthMode = MeasureSpec.EXACTLY;
} else if (consumeHorizontal) {
heightMode = MeasureSpec.EXACTLY;
}
int widthSize = childWidthSize;
int heightSize = childHeightSize;
if (lp.width != LayoutParams.WRAP_CONTENT) {
widthMode = MeasureSpec.EXACTLY;
if (lp.width != LayoutParams.MATCH_PARENT) {
widthSize = lp.width;
}
}
if (lp.height != LayoutParams.WRAP_CONTENT) {
heightMode = MeasureSpec.EXACTLY;
if (lp.height != LayoutParams.MATCH_PARENT) {
heightSize = lp.height;
}
}
final int widthSpec = MeasureSpec.makeMeasureSpec(widthSize, widthMode);
final int heightSpec = MeasureSpec.makeMeasureSpec(heightSize, heightMode);
child.measure(widthSpec, heightSpec);
if (consumeVertical) {
childHeightSize -= child.getMeasuredHeight();
} else if (consumeHorizontal) {
childWidthSize -= child.getMeasuredWidth();
}
}
}
}
mChildWidthMeasureSpec = MeasureSpec.makeMeasureSpec(childWidthSize, MeasureSpec.EXACTLY);
mChildHeightMeasureSpec = MeasureSpec.makeMeasureSpec(childHeightSize, MeasureSpec.EXACTLY);
// Make sure we have created all fragments that we need to have shown.
mInLayout = true;
populate();
mInLayout = false;
// Page views next.
size = getChildCount();
for (int i = 0; i < size; ++i) {
final View child = getChildAt(i);
if (child.getVisibility() != GONE) {
if (DEBUG) {
Log.v(TAG, "Measuring #" + i + " " + child + ": " + mChildWidthMeasureSpec);
}
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
if (lp == null || !lp.isDecor) {
final int widthSpec = MeasureSpec.makeMeasureSpec(
(int) (childWidthSize * lp.widthFactor), MeasureSpec.EXACTLY);
child.measure(widthSpec, mChildHeightMeasureSpec);
}
}
}
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
// Make sure scroll position is set correctly.
if (w != oldw) {
recomputeScrollPosition(w, oldw, mPageMargin, mPageMargin);
}
}
private void recomputeScrollPosition(int width, int oldWidth, int margin, int oldMargin) {
if (oldWidth > 0 && !mItems.isEmpty()) {
if (!mScroller.isFinished()) {
mScroller.setFinalX(getCurrentItem() * getClientWidth());
} else {
final int widthWithMargin = width - getPaddingLeft() - getPaddingRight() + margin;
final int oldWidthWithMargin = oldWidth - getPaddingLeft() - getPaddingRight()
+ oldMargin;
final int xpos = getScrollX();
final float pageOffset = (float) xpos / oldWidthWithMargin;
final int newOffsetPixels = (int) (pageOffset * widthWithMargin);
scrollTo(newOffsetPixels, getScrollY());
}
} else {
final ItemInfo ii = infoForPosition(mCurItem);
final float scrollOffset = ii != null ? Math.min(ii.offset, mLastOffset) : 0;
final int scrollPos =
(int) (scrollOffset * (width - getPaddingLeft() - getPaddingRight()));
if (scrollPos != getScrollX()) {
completeScroll(false);
scrollTo(scrollPos, getScrollY());
}
}
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
final int count = getChildCount();
int width = r - l;
int height = b - t;
int paddingLeft = getPaddingLeft();
int paddingTop = getPaddingTop();
int paddingRight = getPaddingRight();
int paddingBottom = getPaddingBottom();
final int scrollX = getScrollX();
int decorCount = 0;
// First pass - decor views. We need to do this in two passes so that
// we have the proper offsets for non-decor views later.
for (int i = 0; i < count; i++) {
final View child = getChildAt(i);
if (child.getVisibility() != GONE) {
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
int childLeft = 0;
int childTop = 0;
if (lp.isDecor) {
final int hgrav = lp.gravity & Gravity.HORIZONTAL_GRAVITY_MASK;
final int vgrav = lp.gravity & Gravity.VERTICAL_GRAVITY_MASK;
switch (hgrav) {
default:
childLeft = paddingLeft;
break;
case Gravity.LEFT:
childLeft = paddingLeft;
paddingLeft += child.getMeasuredWidth();
break;
case Gravity.CENTER_HORIZONTAL:
childLeft = Math.max((width - child.getMeasuredWidth()) / 2,
paddingLeft);
break;
case Gravity.RIGHT:
childLeft = width - paddingRight - child.getMeasuredWidth();
paddingRight += child.getMeasuredWidth();
break;
}
switch (vgrav) {
default:
childTop = paddingTop;
break;
case Gravity.TOP:
childTop = paddingTop;
paddingTop += child.getMeasuredHeight();
break;
case Gravity.CENTER_VERTICAL:
childTop = Math.max((height - child.getMeasuredHeight()) / 2,
paddingTop);
break;
case Gravity.BOTTOM:
childTop = height - paddingBottom - child.getMeasuredHeight();
paddingBottom += child.getMeasuredHeight();
break;
}
childLeft += scrollX;
child.layout(childLeft, childTop,
childLeft + child.getMeasuredWidth(),
childTop + child.getMeasuredHeight());
decorCount++;
}
}
}
final int childWidth = width - paddingLeft - paddingRight;
// Page views. Do this once we have the right padding offsets from above.
for (int i = 0; i < count; i++) {
final View child = getChildAt(i);
if (child.getVisibility() != GONE) {
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
ItemInfo ii;
if (!lp.isDecor && (ii = infoForChild(child)) != null) {
int loff = (int) (childWidth * ii.offset);
int childLeft = paddingLeft + loff;
int childTop = paddingTop;
if (lp.needsMeasure) {
// This was added during layout and needs measurement.
// Do it now that we know what we're working with.
lp.needsMeasure = false;
final int widthSpec = MeasureSpec.makeMeasureSpec(
(int) (childWidth * lp.widthFactor),
MeasureSpec.EXACTLY);
final int heightSpec = MeasureSpec.makeMeasureSpec(
(int) (height - paddingTop - paddingBottom),
MeasureSpec.EXACTLY);
child.measure(widthSpec, heightSpec);
}
if (DEBUG) {
Log.v(TAG, "Positioning #" + i + " " + child + " f=" + ii.object
+ ":" + childLeft + "," + childTop + " " + child.getMeasuredWidth()
+ "x" + child.getMeasuredHeight());
}
child.layout(childLeft, childTop,
childLeft + child.getMeasuredWidth(),
childTop + child.getMeasuredHeight());
}
}
}
mTopPageBounds = paddingTop;
mBottomPageBounds = height - paddingBottom;
mDecorChildCount = decorCount;
if (mFirstLayout) {
scrollToItem(mCurItem, false, 0, false);
}
mFirstLayout = false;
}
@Override
public void computeScroll() {
mIsScrollStarted = true;
if (!mScroller.isFinished() && mScroller.computeScrollOffset()) {
int oldX = getScrollX();
int oldY = getScrollY();
int x = mScroller.getCurrX();
int y = mScroller.getCurrY();
if (oldX != x || oldY != y) {
scrollTo(x, y);
if (!pageScrolled(x)) {
mScroller.abortAnimation();
scrollTo(0, y);
}
}
// Keep on drawing until the animation has finished.
ViewCompat.postInvalidateOnAnimation(this);
return;
}
// Done with scroll, clean up state.
completeScroll(true);
}
private boolean pageScrolled(int xpos) {
if (mItems.size() == 0) {
if (mFirstLayout) {
// If we haven't been laid out yet, we probably just haven't been populated yet.
// Let's skip this call since it doesn't make sense in this state
return false;
}
mCalledSuper = false;
onPageScrolled(0, 0, 0);
if (!mCalledSuper) {
throw new IllegalStateException(
"onPageScrolled did not call superclass implementation");
}
return false;
}
final ItemInfo ii = infoForCurrentScrollPosition();
final int width = getClientWidth();
final int widthWithMargin = width + mPageMargin;
final float marginOffset = (float) mPageMargin / width;
final int currentPage = ii.position;
final float pageOffset = (((float) xpos / width) - ii.offset)
/ (ii.widthFactor + marginOffset);
final int offsetPixels = (int) (pageOffset * widthWithMargin);
mCalledSuper = false;
onPageScrolled(currentPage, pageOffset, offsetPixels);
if (!mCalledSuper) {
throw new IllegalStateException(
"onPageScrolled did not call superclass implementation");
}
return true;
}
/**
* This method will be invoked when the current page is scrolled, either as part
* of a programmatically initiated smooth scroll or a user initiated touch scroll.
* If you override this method you must call through to the superclass implementation
* (e.g. super.onPageScrolled(position, offset, offsetPixels)) before onPageScrolled
* returns.
*
* @param position Position index of the first page currently being displayed.
* Page position+1 will be visible if positionOffset is nonzero.
* @param offset Value from [0, 1) indicating the offset from the page at position.
* @param offsetPixels Value in pixels indicating the offset from position.
*/
@CallSuper
protected void onPageScrolled(int position, float offset, int offsetPixels) {
// Offset any decor views if needed - keep them on-screen at all times.
if (mDecorChildCount > 0) {
final int scrollX = getScrollX();
int paddingLeft = getPaddingLeft();
int paddingRight = getPaddingRight();
final int width = getWidth();
final int childCount = getChildCount();
for (int i = 0; i < childCount; i++) {
final View child = getChildAt(i);
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
if (!lp.isDecor) continue;
final int hgrav = lp.gravity & Gravity.HORIZONTAL_GRAVITY_MASK;
int childLeft = 0;
switch (hgrav) {
default:
childLeft = paddingLeft;
break;
case Gravity.LEFT:
childLeft = paddingLeft;
paddingLeft += child.getWidth();
break;
case Gravity.CENTER_HORIZONTAL:
childLeft = Math.max((width - child.getMeasuredWidth()) / 2,
paddingLeft);
break;
case Gravity.RIGHT:
childLeft = width - paddingRight - child.getMeasuredWidth();
paddingRight += child.getMeasuredWidth();
break;
}
childLeft += scrollX;
final int childOffset = childLeft - child.getLeft();
if (childOffset != 0) {
child.offsetLeftAndRight(childOffset);
}
}
}
dispatchOnPageScrolled(position, offset, offsetPixels);
if (mPageTransformer != null) {
final int scrollX = getScrollX();
final int childCount = getChildCount();
for (int i = 0; i < childCount; i++) {
final View child = getChildAt(i);
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
if (lp.isDecor) continue;
final float transformPos = (float) (child.getLeft() - scrollX) / getClientWidth();
mPageTransformer.transformPage(child, transformPos);
}
}
mCalledSuper = true;
}
private void dispatchOnPageScrolled(int position, float offset, int offsetPixels) {
if (mOnPageChangeListener != null) {
mOnPageChangeListener.onPageScrolled(position, offset, offsetPixels);
}
if (mOnPageChangeListeners != null) {
for (int i = 0, z = mOnPageChangeListeners.size(); i < z; i++) {
OnPageChangeListener listener = mOnPageChangeListeners.get(i);
if (listener != null) {
listener.onPageScrolled(position, offset, offsetPixels);
}
}
}
if (mInternalPageChangeListener != null) {
mInternalPageChangeListener.onPageScrolled(position, offset, offsetPixels);
}
}
private void dispatchOnPageSelected(int position) {
if (mOnPageChangeListener != null) {
mOnPageChangeListener.onPageSelected(position);
}
if (mOnPageChangeListeners != null) {
for (int i = 0, z = mOnPageChangeListeners.size(); i < z; i++) {
OnPageChangeListener listener = mOnPageChangeListeners.get(i);
if (listener != null) {
listener.onPageSelected(position);
}
}
}
if (mInternalPageChangeListener != null) {
mInternalPageChangeListener.onPageSelected(position);
}
}
private void dispatchOnScrollStateChanged(int state) {
if (mOnPageChangeListener != null) {
mOnPageChangeListener.onPageScrollStateChanged(state);
}
if (mOnPageChangeListeners != null) {
for (int i = 0, z = mOnPageChangeListeners.size(); i < z; i++) {
OnPageChangeListener listener = mOnPageChangeListeners.get(i);
if (listener != null) {
listener.onPageScrollStateChanged(state);
}
}
}
if (mInternalPageChangeListener != null) {
mInternalPageChangeListener.onPageScrollStateChanged(state);
}
}
private void completeScroll(boolean postEvents) {
boolean needPopulate = mScrollState == SCROLL_STATE_SETTLING;
if (needPopulate) {
// Done with scroll, no longer want to cache view drawing.
setScrollingCacheEnabled(false);
boolean wasScrolling = !mScroller.isFinished();
if (wasScrolling) {
mScroller.abortAnimation();
int oldX = getScrollX();
int oldY = getScrollY();
int x = mScroller.getCurrX();
int y = mScroller.getCurrY();
if (oldX != x || oldY != y) {
scrollTo(x, y);
if (x != oldX) {
pageScrolled(x);
}
}
}
}
mPopulatePending = false;
for (int i = 0; i < mItems.size(); i++) {
ItemInfo ii = mItems.get(i);
if (ii.scrolling) {
needPopulate = true;
ii.scrolling = false;
}
}
if (needPopulate) {
if (postEvents) {
ViewCompat.postOnAnimation(this, mEndScrollRunnable);
} else {
mEndScrollRunnable.run();
}
}
}
private boolean isGutterDrag(float x, float dx) {
return (x < mGutterSize && dx > 0) || (x > getWidth() - mGutterSize && dx < 0);
}
private void enableLayers(boolean enable) {
final int childCount = getChildCount();
for (int i = 0; i < childCount; i++) {
final int layerType = enable
? mPageTransformerLayerType : ViewCompat.LAYER_TYPE_NONE;
ViewCompat.setLayerType(getChildAt(i), layerType, null);
}
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
/*
* This method JUST determines whether we want to intercept the motion.
* If we return true, onMotionEvent will be called and we do the actual
* scrolling there.
*/
final int action = ev.getAction() & MotionEventCompat.ACTION_MASK;
// Always take care of the touch gesture being complete.
if (action == MotionEvent.ACTION_CANCEL || action == MotionEvent.ACTION_UP) {
// Release the drag.
if (DEBUG) Log.v(TAG, "Intercept done!");
resetTouch();
return false;
}
// Nothing more to do here if we have decided whether or not we
// are dragging.
if (action != MotionEvent.ACTION_DOWN) {
if (mIsBeingDragged) {
if (DEBUG) Log.v(TAG, "Intercept returning true!");
return true;
}
if (mIsUnableToDrag) {
if (DEBUG) Log.v(TAG, "Intercept returning false!");
return false;
}
}
switch (action) {
case MotionEvent.ACTION_MOVE: {
/*
* mIsBeingDragged == false, otherwise the shortcut would have caught it. Check
* whether the user has moved far enough from his original down touch.
*/
/*
* Locally do absolute value. mLastMotionY is set to the y value
* of the down event.
*/
final int activePointerId = mActivePointerId;
if (activePointerId == INVALID_POINTER) {
// If we don't have a valid id, the touch down wasn't on content.
break;
}
final int pointerIndex = ev.findPointerIndex(activePointerId);
final float x = ev.getX(pointerIndex);
final float dx = x - mLastMotionX;
final float xDiff = Math.abs(dx);
final float y = ev.getY(pointerIndex);
final float yDiff = Math.abs(y - mInitialMotionY);
if (DEBUG) Log.v(TAG, "Moved x to " + x + "," + y + " diff=" + xDiff + "," + yDiff);
if (dx != 0 && !isGutterDrag(mLastMotionX, dx)
&& canScroll(this, false, (int) dx, (int) x, (int) y)) {
// Nested view has scrollable area under this point. Let it be handled there.
mLastMotionX = x;
mLastMotionY = y;
mIsUnableToDrag = true;
return false;
}
if (xDiff > mTouchSlop && xDiff * 0.5f > yDiff) {
if (DEBUG) Log.v(TAG, "Starting drag!");
mIsBeingDragged = true;
requestParentDisallowInterceptTouchEvent(true);
setScrollState(SCROLL_STATE_DRAGGING);
mLastMotionX = dx > 0
? mInitialMotionX + mTouchSlop : mInitialMotionX - mTouchSlop;
mLastMotionY = y;
setScrollingCacheEnabled(true);
} else if (yDiff > mTouchSlop) {
// The finger has moved enough in the vertical
// direction to be counted as a drag... abort
// any attempt to drag horizontally, to work correctly
// with children that have scrolling containers.
if (DEBUG) Log.v(TAG, "Starting unable to drag!");
mIsUnableToDrag = true;
}
if (mIsBeingDragged) {
// Scroll to follow the motion event
if (performDrag(x)) {
ViewCompat.postInvalidateOnAnimation(this);
}
}
break;
}
case MotionEvent.ACTION_DOWN: {
/*
* Remember location of down touch.
* ACTION_DOWN always refers to pointer index 0.
*/
mLastMotionX = mInitialMotionX = ev.getX();
mLastMotionY = mInitialMotionY = ev.getY();
mActivePointerId = ev.getPointerId(0);
mIsUnableToDrag = false;
mIsScrollStarted = true;
mScroller.computeScrollOffset();
if (mScrollState == SCROLL_STATE_SETTLING
&& Math.abs(mScroller.getFinalX() - mScroller.getCurrX()) > mCloseEnough) {
// Let the user 'catch' the pager as it animates.
mScroller.abortAnimation();
mPopulatePending = false;
populate();
mIsBeingDragged = true;
requestParentDisallowInterceptTouchEvent(true);
setScrollState(SCROLL_STATE_DRAGGING);
} else {
completeScroll(false);
mIsBeingDragged = false;
}
if (DEBUG) {
Log.v(TAG, "Down at " + mLastMotionX + "," + mLastMotionY
+ " mIsBeingDragged=" + mIsBeingDragged
+ "mIsUnableToDrag=" + mIsUnableToDrag);
}
break;
}
case MotionEventCompat.ACTION_POINTER_UP:
onSecondaryPointerUp(ev);
break;
}
if (mVelocityTracker == null) {
mVelocityTracker = VelocityTracker.obtain();
}
mVelocityTracker.addMovement(ev);
/*
* The only time we want to intercept motion events is if we are in the
* drag mode.
*/
return mIsBeingDragged;
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
if (mFakeDragging) {
// A fake drag is in progress already, ignore this real one
// but still eat the touch events.
// (It is likely that the user is multi-touching the screen.)
return true;
}
if (ev.getAction() == MotionEvent.ACTION_DOWN && ev.getEdgeFlags() != 0) {
// Don't handle edge touches immediately -- they may actually belong to one of our
// descendants.
return false;
}
if (mAdapter == null || mAdapter.getCount() == 0) {
// Nothing to present or scroll; nothing to touch.
return false;
}
if (mVelocityTracker == null) {
mVelocityTracker = VelocityTracker.obtain();
}
mVelocityTracker.addMovement(ev);
final int action = ev.getAction();
boolean needsInvalidate = false;
switch (action & MotionEventCompat.ACTION_MASK) {
case MotionEvent.ACTION_DOWN: {
mScroller.abortAnimation();
mPopulatePending = false;
populate();
// Remember where the motion event started
mLastMotionX = mInitialMotionX = ev.getX();
mLastMotionY = mInitialMotionY = ev.getY();
mActivePointerId = ev.getPointerId(0);
break;
}
case MotionEvent.ACTION_MOVE:
if (!mIsBeingDragged) {
final int pointerIndex = ev.findPointerIndex(mActivePointerId);
if (pointerIndex == -1) {
// A child has consumed some touch events and put us into an inconsistent
// state.
needsInvalidate = resetTouch();
break;
}
final float x = ev.getX(pointerIndex);
final float xDiff = Math.abs(x - mLastMotionX);
final float y = ev.getY(pointerIndex);
final float yDiff = Math.abs(y - mLastMotionY);
if (DEBUG) {
Log.v(TAG, "Moved x to " + x + "," + y + " diff=" + xDiff + "," + yDiff);
}
if (xDiff > mTouchSlop && xDiff > yDiff) {
if (DEBUG) Log.v(TAG, "Starting drag!");
mIsBeingDragged = true;
requestParentDisallowInterceptTouchEvent(true);
mLastMotionX = x - mInitialMotionX > 0 ? mInitialMotionX + mTouchSlop :
mInitialMotionX - mTouchSlop;
mLastMotionY = y;
setScrollState(SCROLL_STATE_DRAGGING);
setScrollingCacheEnabled(true);
// Disallow Parent Intercept, just in case
ViewParent parent = getParent();
if (parent != null) {
parent.requestDisallowInterceptTouchEvent(true);
}
}
}
// Not else! Note that mIsBeingDragged can be set above.
if (mIsBeingDragged) {
// Scroll to follow the motion event
final int activePointerIndex = ev.findPointerIndex(mActivePointerId);
final float x = ev.getX(activePointerIndex);
needsInvalidate |= performDrag(x);
}
break;
case MotionEvent.ACTION_UP:
if (mIsBeingDragged) {
final VelocityTracker velocityTracker = mVelocityTracker;
velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity);
int initialVelocity = (int) VelocityTrackerCompat.getXVelocity(
velocityTracker, mActivePointerId);
mPopulatePending = true;
final int width = getClientWidth();
final int scrollX = getScrollX();
final ItemInfo ii = infoForCurrentScrollPosition();
final float marginOffset = (float) mPageMargin / width;
final int currentPage = ii.position;
final float pageOffset = (((float) scrollX / width) - ii.offset)
/ (ii.widthFactor + marginOffset);
final int activePointerIndex = ev.findPointerIndex(mActivePointerId);
final float x = ev.getX(activePointerIndex);
final int totalDelta = (int) (x - mInitialMotionX);
int nextPage = determineTargetPage(currentPage, pageOffset, initialVelocity,
totalDelta);
setCurrentItemInternal(nextPage, true, true, initialVelocity);
needsInvalidate = resetTouch();
}
break;
case MotionEvent.ACTION_CANCEL:
if (mIsBeingDragged) {
scrollToItem(mCurItem, true, 0, false);
needsInvalidate = resetTouch();
}
break;
case MotionEventCompat.ACTION_POINTER_DOWN: {
final int index = MotionEventCompat.getActionIndex(ev);
final float x = ev.getX(index);
mLastMotionX = x;
mActivePointerId = ev.getPointerId(index);
break;
}
case MotionEventCompat.ACTION_POINTER_UP:
onSecondaryPointerUp(ev);
mLastMotionX = ev.getX(ev.findPointerIndex(mActivePointerId));
break;
}
if (needsInvalidate) {
ViewCompat.postInvalidateOnAnimation(this);
}
return true;
}
private boolean resetTouch() {
boolean needsInvalidate;
mActivePointerId = INVALID_POINTER;
endDrag();
needsInvalidate = mLeftEdge.onRelease() | mRightEdge.onRelease();
return needsInvalidate;
}
private void requestParentDisallowInterceptTouchEvent(boolean disallowIntercept) {
final ViewParent parent = getParent();
if (parent != null) {
parent.requestDisallowInterceptTouchEvent(disallowIntercept);
}
}
private boolean performDrag(float x) {
boolean needsInvalidate = false;
final float deltaX = mLastMotionX - x;
mLastMotionX = x;
float oldScrollX = getScrollX();
float scrollX = oldScrollX + deltaX;
final int width = getClientWidth();
float leftBound = width * mFirstOffset;
float rightBound = width * mLastOffset;
boolean leftAbsolute = true;
boolean rightAbsolute = true;
final ItemInfo firstItem = mItems.get(0);
final ItemInfo lastItem = mItems.get(mItems.size() - 1);
if (firstItem.position != 0) {
leftAbsolute = false;
leftBound = firstItem.offset * width;
}
if (lastItem.position != mAdapter.getCount() - 1) {
rightAbsolute = false;
rightBound = lastItem.offset * width;
}
if (scrollX < leftBound) {
// TODO: 7. 滑动的时候再加载左边的view
if (mCurItem - 1 >= 0) {
populate(mCurItem - 1);
}
if (leftAbsolute) {
float over = leftBound - scrollX;
needsInvalidate = mLeftEdge.onPull(Math.abs(over) / width);
}
scrollX = leftBound;
} else if (scrollX > rightBound) {
// TODO: 8. 滑动的时候再加载右边的view,这两处地方还有优化的空间,应当根据滑动的速率来计算
if (mAdapter != null && mCurItem + 1 < mAdapter.getCount())
populate(mCurItem + 1);
if (rightAbsolute) {
float over = scrollX - rightBound;
needsInvalidate = mRightEdge.onPull(Math.abs(over) / width);
}
scrollX = rightBound;
}
// Don't lose the rounded component
mLastMotionX += scrollX - (int) scrollX;
scrollTo((int) scrollX, getScrollY());
pageScrolled((int) scrollX);
return needsInvalidate;
}
/**
* @return Info about the page at the current scroll position.
* This can be synthetic for a missing middle page; the 'object' field can be null.
*/
private ItemInfo infoForCurrentScrollPosition() {
final int width = getClientWidth();
final float scrollOffset = width > 0 ? (float) getScrollX() / width : 0;
final float marginOffset = width > 0 ? (float) mPageMargin / width : 0;
int lastPos = -1;
float lastOffset = 0.f;
float lastWidth = 0.f;
boolean first = true;
ItemInfo lastItem = null;
for (int i = 0; i < mItems.size(); i++) {
ItemInfo ii = mItems.get(i);
float offset;
if (!first && ii.position != lastPos + 1) {
// Create a synthetic item for a missing page.
ii = mTempItem;
ii.offset = lastOffset + lastWidth + marginOffset;
ii.position = lastPos + 1;
ii.widthFactor = mAdapter.getPageWidth(ii.position);
i--;
}
offset = ii.offset;
final float leftBound = offset;
final float rightBound = offset + ii.widthFactor + marginOffset;
if (first || scrollOffset >= leftBound) {
if (scrollOffset < rightBound || i == mItems.size() - 1) {
return ii;
}
} else {
return lastItem;
}
first = false;
lastPos = ii.position;
lastOffset = offset;
lastWidth = ii.widthFactor;
lastItem = ii;
}
return lastItem;
}
private int determineTargetPage(int currentPage, float pageOffset, int velocity, int deltaX) {
int targetPage;
if (Math.abs(deltaX) > mFlingDistance && Math.abs(velocity) > mMinimumVelocity) {
targetPage = velocity > 0 ? currentPage : currentPage + 1;
} else {
final float truncator = currentPage >= mCurItem ? 0.4f : 0.6f;
targetPage = currentPage + (int) (pageOffset + truncator);
}
if (mItems.size() > 0) {
final ItemInfo firstItem = mItems.get(0);
final ItemInfo lastItem = mItems.get(mItems.size() - 1);
// Only let the user target pages we have items for
targetPage = Math.max(firstItem.position, Math.min(targetPage, lastItem.position));
}
return targetPage;
}
@Override
public void draw(Canvas canvas) {
super.draw(canvas);
boolean needsInvalidate = false;
final int overScrollMode = getOverScrollMode();
if (overScrollMode == View.OVER_SCROLL_ALWAYS
|| (overScrollMode == View.OVER_SCROLL_IF_CONTENT_SCROLLS
&& mAdapter != null && mAdapter.getCount() > 1)) {
if (!mLeftEdge.isFinished()) {
final int restoreCount = canvas.save();
final int height = getHeight() - getPaddingTop() - getPaddingBottom();
final int width = getWidth();
canvas.rotate(270);
canvas.translate(-height + getPaddingTop(), mFirstOffset * width);
mLeftEdge.setSize(height, width);
needsInvalidate |= mLeftEdge.draw(canvas);
canvas.restoreToCount(restoreCount);
}
if (!mRightEdge.isFinished()) {
final int restoreCount = canvas.save();
final int width = getWidth();
final int height = getHeight() - getPaddingTop() - getPaddingBottom();
canvas.rotate(90);
canvas.translate(-getPaddingTop(), -(mLastOffset + 1) * width);
mRightEdge.setSize(height, width);
needsInvalidate |= mRightEdge.draw(canvas);
canvas.restoreToCount(restoreCount);
}
} else {
mLeftEdge.finish();
mRightEdge.finish();
}
if (needsInvalidate) {
// Keep animating
ViewCompat.postInvalidateOnAnimation(this);
}
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// Draw the margin drawable between pages if needed.
if (mPageMargin > 0 && mMarginDrawable != null && mItems.size() > 0 && mAdapter != null) {
final int scrollX = getScrollX();
final int width = getWidth();
final float marginOffset = (float) mPageMargin / width;
int itemIndex = 0;
ItemInfo ii = mItems.get(0);
float offset = ii.offset;
final int itemCount = mItems.size();
final int firstPos = ii.position;
final int lastPos = mItems.get(itemCount - 1).position;
for (int pos = firstPos; pos < lastPos; pos++) {
while (pos > ii.position && itemIndex < itemCount) {
ii = mItems.get(++itemIndex);
}
float drawAt;
if (pos == ii.position) {
drawAt = (ii.offset + ii.widthFactor) * width;
offset = ii.offset + ii.widthFactor + marginOffset;
} else {
float widthFactor = mAdapter.getPageWidth(pos);
drawAt = (offset + widthFactor) * width;
offset += widthFactor + marginOffset;
}
if (drawAt + mPageMargin > scrollX) {
mMarginDrawable.setBounds(Math.round(drawAt), mTopPageBounds,
Math.round(drawAt + mPageMargin), mBottomPageBounds);
mMarginDrawable.draw(canvas);
}
if (drawAt > scrollX + width) {
break; // No more visible, no sense in continuing
}
}
}
}
/**
* Start a fake drag of the pager.
*
* <p>A fake drag can be useful if you want to synchronize the motion of the ViewPager
* with the touch scrolling of another view, while still letting the ViewPager
* control the snapping motion and fling behavior. (e.g. parallax-scrolling tabs.)
* Call {@link #fakeDragBy(float)} to simulate the actual drag motion. Call
* {@link #endFakeDrag()} to complete the fake drag and fling as necessary.
*
* <p>During a fake drag the ViewPager will ignore all touch events. If a real drag
* is already in progress, this method will return false.
*
* @return true if the fake drag began successfully, false if it could not be started.
* @see #fakeDragBy(float)
* @see #endFakeDrag()
*/
public boolean beginFakeDrag() {
if (mIsBeingDragged) {
return false;
}
mFakeDragging = true;
setScrollState(SCROLL_STATE_DRAGGING);
mInitialMotionX = mLastMotionX = 0;
if (mVelocityTracker == null) {
mVelocityTracker = VelocityTracker.obtain();
} else {
mVelocityTracker.clear();
}
final long time = SystemClock.uptimeMillis();
final MotionEvent ev = MotionEvent.obtain(time, time, MotionEvent.ACTION_DOWN, 0, 0, 0);
mVelocityTracker.addMovement(ev);
ev.recycle();
mFakeDragBeginTime = time;
return true;
}
/**
* End a fake drag of the pager.
*
* @see #beginFakeDrag()
* @see #fakeDragBy(float)
*/
public void endFakeDrag() {
if (!mFakeDragging) {
throw new IllegalStateException("No fake drag in progress. Call beginFakeDrag first.");
}
if (mAdapter != null) {
final VelocityTracker velocityTracker = mVelocityTracker;
velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity);
int initialVelocity = (int) VelocityTrackerCompat.getXVelocity(
velocityTracker, mActivePointerId);
mPopulatePending = true;
final int width = getClientWidth();
final int scrollX = getScrollX();
final ItemInfo ii = infoForCurrentScrollPosition();
final int currentPage = ii.position;
final float pageOffset = (((float) scrollX / width) - ii.offset) / ii.widthFactor;
final int totalDelta = (int) (mLastMotionX - mInitialMotionX);
int nextPage = determineTargetPage(currentPage, pageOffset, initialVelocity,
totalDelta);
setCurrentItemInternal(nextPage, true, true, initialVelocity);
}
endDrag();
mFakeDragging = false;
}
/**
* Fake drag by an offset in pixels. You must have called {@link #beginFakeDrag()} first.
*
* @param xOffset Offset in pixels to drag by.
* @see #beginFakeDrag()
* @see #endFakeDrag()
*/
public void fakeDragBy(float xOffset) {
if (!mFakeDragging) {
throw new IllegalStateException("No fake drag in progress. Call beginFakeDrag first.");
}
if (mAdapter == null) {
return;
}
mLastMotionX += xOffset;
float oldScrollX = getScrollX();
float scrollX = oldScrollX - xOffset;
final int width = getClientWidth();
float leftBound = width * mFirstOffset;
float rightBound = width * mLastOffset;
final ItemInfo firstItem = mItems.get(0);
final ItemInfo lastItem = mItems.get(mItems.size() - 1);
if (firstItem.position != 0) {
leftBound = firstItem.offset * width;
}
if (lastItem.position != mAdapter.getCount() - 1) {
rightBound = lastItem.offset * width;
}
if (scrollX < leftBound) {
scrollX = leftBound;
} else if (scrollX > rightBound) {
scrollX = rightBound;
}
// Don't lose the rounded component
mLastMotionX += scrollX - (int) scrollX;
scrollTo((int) scrollX, getScrollY());
pageScrolled((int) scrollX);
// Synthesize an event for the VelocityTracker.
final long time = SystemClock.uptimeMillis();
final MotionEvent ev = MotionEvent.obtain(mFakeDragBeginTime, time, MotionEvent.ACTION_MOVE,
mLastMotionX, 0, 0);
mVelocityTracker.addMovement(ev);
ev.recycle();
}
/**
* Returns true if a fake drag is in progress.
*
* @return true if currently in a fake drag, false otherwise.
* @see #beginFakeDrag()
* @see #fakeDragBy(float)
* @see #endFakeDrag()
*/
public boolean isFakeDragging() {
return mFakeDragging;
}
private void onSecondaryPointerUp(MotionEvent ev) {
final int pointerIndex = MotionEventCompat.getActionIndex(ev);
final int pointerId = ev.getPointerId(pointerIndex);
if (pointerId == mActivePointerId) {
// This was our active pointer going up. Choose a new
// active pointer and adjust accordingly.
final int newPointerIndex = pointerIndex == 0 ? 1 : 0;
mLastMotionX = ev.getX(newPointerIndex);
mActivePointerId = ev.getPointerId(newPointerIndex);
if (mVelocityTracker != null) {
mVelocityTracker.clear();
}
}
}
private void endDrag() {
mIsBeingDragged = false;
mIsUnableToDrag = false;
if (mVelocityTracker != null) {
mVelocityTracker.recycle();
mVelocityTracker = null;
}
}
private void setScrollingCacheEnabled(boolean enabled) {
if (mScrollingCacheEnabled != enabled) {
mScrollingCacheEnabled = enabled;
if (USE_CACHE) {
final int size = getChildCount();
for (int i = 0; i < size; ++i) {
final View child = getChildAt(i);
if (child.getVisibility() != GONE) {
child.setDrawingCacheEnabled(enabled);
}
}
}
}
}
/**
* Check if this ViewPager can be scrolled horizontally in a certain direction.
*
* @param direction Negative to check scrolling left, positive to check scrolling right.
* @return Whether this ViewPager can be scrolled in the specified direction. It will always
* return false if the specified direction is 0.
*/
public boolean canScrollHorizontally(int direction) {
if (mAdapter == null) {
return false;
}
final int width = getClientWidth();
final int scrollX = getScrollX();
if (direction < 0) {
return (scrollX > (int) (width * mFirstOffset));
} else if (direction > 0) {
return (scrollX < (int) (width * mLastOffset));
} else {
return false;
}
}
/**
* Tests scrollability within child views of v given a delta of dx.
*
* @param v View to test for horizontal scrollability
* @param checkV Whether the view v passed should itself be checked for scrollability (true),
* or just its children (false).
* @param dx Delta scrolled in pixels
* @param x X coordinate of the active touch point
* @param y Y coordinate of the active touch point
* @return true if child views of v can be scrolled by delta of dx.
*/
protected boolean canScroll(View v, boolean checkV, int dx, int x, int y) {
if (v instanceof ViewGroup) {
final ViewGroup group = (ViewGroup) v;
final int scrollX = v.getScrollX();
final int scrollY = v.getScrollY();
final int count = group.getChildCount();
// Count backwards - let topmost views consume scroll distance first.
for (int i = count - 1; i >= 0; i--) {
// TODO: Add versioned support here for transformed views.
// This will not work for transformed views in Honeycomb+
final View child = group.getChildAt(i);
if (x + scrollX >= child.getLeft() && x + scrollX < child.getRight()
&& y + scrollY >= child.getTop() && y + scrollY < child.getBottom()
&& canScroll(child, true, dx, x + scrollX - child.getLeft(),
y + scrollY - child.getTop())) {
return true;
}
}
}
return checkV && ViewCompat.canScrollHorizontally(v, -dx);
}
@Override
public boolean dispatchKeyEvent(KeyEvent event) {
// Let the focused view and/or our descendants get the key first
return super.dispatchKeyEvent(event) || executeKeyEvent(event);
}
/**
* You can call this function yourself to have the scroll view perform
* scrolling from a key event, just as if the event had been dispatched to
* it by the view hierarchy.
*
* @param event The key event to execute.
* @return Return true if the event was handled, else false.
*/
public boolean executeKeyEvent(KeyEvent event) {
boolean handled = false;
if (event.getAction() == KeyEvent.ACTION_DOWN) {
switch (event.getKeyCode()) {
case KeyEvent.KEYCODE_DPAD_LEFT:
handled = arrowScroll(FOCUS_LEFT);
break;
case KeyEvent.KEYCODE_DPAD_RIGHT:
handled = arrowScroll(FOCUS_RIGHT);
break;
case KeyEvent.KEYCODE_TAB:
if (Build.VERSION.SDK_INT >= 11) {
// The focus finder had a bug handling FOCUS_FORWARD and FOCUS_BACKWARD
// before Android 3.0. Ignore the tab key on those devices.
// if (KeyEventCompat.hasNoModifiers(event)) {
// handled = arrowScroll(FOCUS_FORWARD);
// } else if (KeyEventCompat.hasModifiers(event, KeyEvent.META_SHIFT_ON)) {
// handled = arrowScroll(FOCUS_BACKWARD);
// }
}
break;
}
}
return handled;
}
/**
* Handle scrolling in response to a left or right arrow click.
*
* @param direction The direction corresponding to the arrow key that was pressed. It should be
* either {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}.
* @return Whether the scrolling was handled successfully.
*/
public boolean arrowScroll(int direction) {
View currentFocused = findFocus();
if (currentFocused == this) {
currentFocused = null;
} else if (currentFocused != null) {
boolean isChild = false;
for (ViewParent parent = currentFocused.getParent(); parent instanceof ViewGroup;
parent = parent.getParent()) {
if (parent == this) {
isChild = true;
break;
}
}
if (!isChild) {
// This would cause the focus search down below to fail in fun ways.
final StringBuilder sb = new StringBuilder();
sb.append(currentFocused.getClass().getSimpleName());
for (ViewParent parent = currentFocused.getParent(); parent instanceof ViewGroup;
parent = parent.getParent()) {
sb.append(" => ").append(parent.getClass().getSimpleName());
}
Log.e(TAG, "arrowScroll tried to find focus based on non-child "
+ "current focused view " + sb.toString());
currentFocused = null;
}
}
boolean handled = false;
View nextFocused = FocusFinder.getInstance().findNextFocus(this, currentFocused,
direction);
if (nextFocused != null && nextFocused != currentFocused) {
if (direction == View.FOCUS_LEFT) {
// If there is nothing to the left, or this is causing us to
// jump to the right, then what we really want to do is page left.
final int nextLeft = getChildRectInPagerCoordinates(mTempRect, nextFocused).left;
final int currLeft = getChildRectInPagerCoordinates(mTempRect, currentFocused).left;
if (currentFocused != null && nextLeft >= currLeft) {
handled = pageLeft();
} else {
handled = nextFocused.requestFocus();
}
} else if (direction == View.FOCUS_RIGHT) {
// If there is nothing to the right, or this is causing us to
// jump to the left, then what we really want to do is page right.
final int nextLeft = getChildRectInPagerCoordinates(mTempRect, nextFocused).left;
final int currLeft = getChildRectInPagerCoordinates(mTempRect, currentFocused).left;
if (currentFocused != null && nextLeft <= currLeft) {
handled = pageRight();
} else {
handled = nextFocused.requestFocus();
}
}
} else if (direction == FOCUS_LEFT || direction == FOCUS_BACKWARD) {
// Trying to move left and nothing there; try to page.
handled = pageLeft();
} else if (direction == FOCUS_RIGHT || direction == FOCUS_FORWARD) {
// Trying to move right and nothing there; try to page.
handled = pageRight();
}
if (handled) {
playSoundEffect(SoundEffectConstants.getContantForFocusDirection(direction));
}
return handled;
}
private Rect getChildRectInPagerCoordinates(Rect outRect, View child) {
if (outRect == null) {
outRect = new Rect();
}
if (child == null) {
outRect.set(0, 0, 0, 0);
return outRect;
}
outRect.left = child.getLeft();
outRect.right = child.getRight();
outRect.top = child.getTop();
outRect.bottom = child.getBottom();
ViewParent parent = child.getParent();
while (parent instanceof ViewGroup && parent != this) {
final ViewGroup group = (ViewGroup) parent;
outRect.left += group.getLeft();
outRect.right += group.getRight();
outRect.top += group.getTop();
outRect.bottom += group.getBottom();
parent = group.getParent();
}
return outRect;
}
boolean pageLeft() {
if (mCurItem > 0) {
setCurrentItem(mCurItem - 1, true);
return true;
}
return false;
}
boolean pageRight() {
if (mAdapter != null && mCurItem < (mAdapter.getCount() - 1)) {
setCurrentItem(mCurItem + 1, true);
return true;
}
return false;
}
/**
* We only want the current page that is being shown to be focusable.
*/
@Override
public void addFocusables(ArrayList<View> views, int direction, int focusableMode) {
final int focusableCount = views.size();
final int descendantFocusability = getDescendantFocusability();
if (descendantFocusability != FOCUS_BLOCK_DESCENDANTS) {
for (int i = 0; i < getChildCount(); i++) {
final View child = getChildAt(i);
if (child.getVisibility() == VISIBLE) {
ItemInfo ii = infoForChild(child);
if (ii != null && ii.position == mCurItem) {
child.addFocusables(views, direction, focusableMode);
}
}
}
}
// we add ourselves (if focusable) in all cases except for when we are
// FOCUS_AFTER_DESCENDANTS and there are some descendants focusable. this is
// to avoid the focus search finding layouts when a more precise search
// among the focusable children would be more interesting.
if (descendantFocusability != FOCUS_AFTER_DESCENDANTS
|| (focusableCount == views.size())) { // No focusable descendants
// Note that we can't call the superclass here, because it will
// add all views in. So we need to do the same thing View does.
if (!isFocusable()) {
return;
}
if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE
&& isInTouchMode() && !isFocusableInTouchMode()) {
return;
}
if (views != null) {
views.add(this);
}
}
}
/**
* We only want the current page that is being shown to be touchable.
*/
@Override
public void addTouchables(ArrayList<View> views) {
// Note that we don't call super.addTouchables(), which means that
// we don't call View.addTouchables(). This is okay because a ViewPager
// is itself not touchable.
for (int i = 0; i < getChildCount(); i++) {
final View child = getChildAt(i);
if (child.getVisibility() == VISIBLE) {
ItemInfo ii = infoForChild(child);
if (ii != null && ii.position == mCurItem) {
child.addTouchables(views);
}
}
}
}
/**
* We only want the current page that is being shown to be focusable.
*/
@Override
protected boolean onRequestFocusInDescendants(int direction,
Rect previouslyFocusedRect) {
int index;
int increment;
int end;
int count = getChildCount();
if ((direction & FOCUS_FORWARD) != 0) {
index = 0;
increment = 1;
end = count;
} else {
index = count - 1;
increment = -1;
end = -1;
}
for (int i = index; i != end; i += increment) {
View child = getChildAt(i);
if (child.getVisibility() == VISIBLE) {
ItemInfo ii = infoForChild(child);
if (ii != null && ii.position == mCurItem) {
if (child.requestFocus(direction, previouslyFocusedRect)) {
return true;
}
}
}
}
return false;
}
@Override
public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
// Dispatch scroll events from this ViewPager.
if (event.getEventType() == AccessibilityEventCompat.TYPE_VIEW_SCROLLED) {
return super.dispatchPopulateAccessibilityEvent(event);
}
// Dispatch all other accessibility events from the current page.
final int childCount = getChildCount();
for (int i = 0; i < childCount; i++) {
final View child = getChildAt(i);
if (child.getVisibility() == VISIBLE) {
final ItemInfo ii = infoForChild(child);
if (ii != null && ii.position == mCurItem
&& child.dispatchPopulateAccessibilityEvent(event)) {
return true;
}
}
}
return false;
}
@Override
protected ViewGroup.LayoutParams generateDefaultLayoutParams() {
return new LayoutParams();
}
@Override
protected ViewGroup.LayoutParams generateLayoutParams(ViewGroup.LayoutParams p) {
return generateDefaultLayoutParams();
}
@Override
protected boolean checkLayoutParams(ViewGroup.LayoutParams p) {
return p instanceof LayoutParams && super.checkLayoutParams(p);
}
@Override
public ViewGroup.LayoutParams generateLayoutParams(AttributeSet attrs) {
return new LayoutParams(getContext(), attrs);
}
class MyAccessibilityDelegate extends AccessibilityDelegateCompat {
@Override
public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) {
super.onInitializeAccessibilityEvent(host, event);
event.setClassName(NoPreViewPager.class.getName());
final AccessibilityRecordCompat recordCompat =
AccessibilityEventCompat.asRecord(event);
recordCompat.setScrollable(canScroll());
if (event.getEventType() == AccessibilityEventCompat.TYPE_VIEW_SCROLLED
&& mAdapter != null) {
recordCompat.setItemCount(mAdapter.getCount());
recordCompat.setFromIndex(mCurItem);
recordCompat.setToIndex(mCurItem);
}
}
@Override
public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfoCompat info) {
super.onInitializeAccessibilityNodeInfo(host, info);
info.setClassName(NoPreViewPager.class.getName());
info.setScrollable(canScroll());
if (canScrollHorizontally(1)) {
info.addAction(AccessibilityNodeInfoCompat.ACTION_SCROLL_FORWARD);
}
if (canScrollHorizontally(-1)) {
info.addAction(AccessibilityNodeInfoCompat.ACTION_SCROLL_BACKWARD);
}
}
@Override
public boolean performAccessibilityAction(View host, int action, Bundle args) {
if (super.performAccessibilityAction(host, action, args)) {
return true;
}
switch (action) {
case AccessibilityNodeInfoCompat.ACTION_SCROLL_FORWARD: {
if (canScrollHorizontally(1)) {
setCurrentItem(mCurItem + 1);
return true;
}
}
return false;
case AccessibilityNodeInfoCompat.ACTION_SCROLL_BACKWARD: {
if (canScrollHorizontally(-1)) {
setCurrentItem(mCurItem - 1);
return true;
}
}
return false;
}
return false;
}
private boolean canScroll() {
return (mAdapter != null) && (mAdapter.getCount() > 1);
}
}
private class PagerObserver extends DataSetObserver {
PagerObserver() {
}
@Override
public void onChanged() {
dataSetChanged();
}
@Override
public void onInvalidated() {
dataSetChanged();
}
}
/**
* Layout parameters that should be supplied for views added to a
* ViewPager.
*/
public static class LayoutParams extends ViewGroup.LayoutParams {
/**
* true if this view is a decoration on the pager itself and not
* a view supplied by the adapter.
*/
public boolean isDecor;
/**
* Gravity setting for use on decor views only:
* Where to position the view page within the overall ViewPager
* container; constants are defined in {@link Gravity}.
*/
public int gravity;
/**
* Width as a 0-1 multiplier of the measured pager width
*/
float widthFactor = 0.f;
/**
* true if this view was added during layout and needs to be measured
* before being positioned.
*/
boolean needsMeasure;
/**
* Adapter position this view is for if !isDecor
*/
int position;
/**
* Current child index within the ViewPager that this view occupies
*/
int childIndex;
public LayoutParams() {
super(MATCH_PARENT, MATCH_PARENT);
}
public LayoutParams(Context context, AttributeSet attrs) {
super(context, attrs);
final TypedArray a = context.obtainStyledAttributes(attrs, LAYOUT_ATTRS);
gravity = a.getInteger(0, Gravity.TOP);
a.recycle();
}
}
static class ViewPositionComparator implements Comparator<View> {
@Override
public int compare(View lhs, View rhs) {
final LayoutParams llp = (LayoutParams) lhs.getLayoutParams();
final LayoutParams rlp = (LayoutParams) rhs.getLayoutParams();
if (llp.isDecor != rlp.isDecor) {
return llp.isDecor ? 1 : -1;
}
return llp.position - rlp.position;
}
}
}
| [
"[email protected]"
] | |
226d7c3a94d222355973d5e73ade51d3a5094f90 | ed5159d056e98d6715357d0d14a9b3f20b764f89 | /src/irvine/oeis/a271/A271269.java | 9d023172763a47ef651604e28b358fc77fe8ecba | [] | no_license | flywind2/joeis | c5753169cf562939b04dd246f8a2958e97f74558 | e5efd6971a0062ac99f4fae21a7c78c9f9e74fea | refs/heads/master | 2020-09-13T18:34:35.080552 | 2019-11-19T05:40:55 | 2019-11-19T05:40:55 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 411 | java | package irvine.oeis.a271;
// Generated by gen_seq4.pl pfprime 1 8 10 -49 0 at 2019-07-30 14:36
// DO NOT EDIT here!
import irvine.oeis.PowerFactorPrimeSequence;
/**
* A271269 Numbers k such that <code>8*10^k - 49</code> is prime.
* @author Georg Fischer
*/
public class A271269 extends PowerFactorPrimeSequence {
/** Construct the sequence. */
public A271269() {
super(1, 1, 8, 10, -49, 0);
}
}
| [
"[email protected]"
] | |
6f9b705da4740372d125b8bf731b09dfac3ee30f | b2d97d1627517b662af40d408164327332d8a688 | /Project SourceCode/src/main/java/com/kh/tworavel/controller/WeatherController.java | 0d22f3a328a122f2790465737f6aac0d748877de | [] | no_license | JungCG/TworavelOfficial | 9f6ec31598b2342a839c039fc984a4e52e901007 | 1f83d8e02738c710b37acda0301214b32ad1c306 | refs/heads/main | 2023-02-23T02:50:23.094010 | 2021-01-29T14:01:40 | 2021-01-29T14:01:40 | 323,506,614 | 0 | 5 | null | null | null | null | UTF-8 | Java | false | false | 1,307 | java | package com.kh.tworavel.controller;
import java.util.Map;
import org.json.simple.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.kh.tworavel.common.VillageWeatherParsing;
@Controller
public class WeatherController {
@Autowired
private VillageWeatherParsing weatherparsing;
//지역 날씨 메소드 ajax
@ResponseBody
@RequestMapping(value = "/Weather.do", method = RequestMethod.POST, produces = "application/json; charset=utf8")
public String getVillageWeather(@RequestParam Map<String, String> param) {
JSONObject job = new JSONObject();
String weatherArr[] = new String[4];
try {
weatherArr = weatherparsing.WeatherParsing(param.get("nx"),param.get("ny"));
job.put("SKY", weatherArr[0]);
job.put("T3H", weatherArr[1]);
job.put("REH", weatherArr[2]);
job.put("VEC", weatherArr[3]);
job.put("region", param.get("region"));
} catch (Exception e) {
job.put("result", -1);
} finally {
}
return job.toJSONString();
}
}
| [
"[email protected]"
] | |
1797aefef82247d7ad563a3e9117b12de0a1d772 | 76975a8abb3ac29f6d19b7bc301ff203c0c115cf | /dictionary/src/dictionary/Dictionary.java | 7d31029bc625285e40ab187f3983093398852d07 | [] | no_license | Ballinger1215/dictionary | 145fa41ab75f260e8e5878d7c80fc6dc699a21c3 | 5b199969c1262e2958304b6d895d6873bd3fb408 | refs/heads/master | 2021-01-13T00:56:56.813030 | 2016-03-01T02:34:10 | 2016-03-01T02:34:10 | 52,841,604 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,463 | java | package dictionary;
/**
*
* @author Mark
*/
public class Dictionary {
dictionaryItem[] Items = new dictionaryItem[10];
int numItems = 0;
public static void main(String[] args) {
Dictionary dictionary = new Dictionary();
dictionary.add(new dictionaryItem("scop", "an old enlgish bard"));
dictionary.add(new dictionaryItem("fragile", "easy to break"));
dictionary.add(new dictionaryItem("Abibliophobia", "The fear of running out of reading material."));
dictionary.add(new dictionaryItem("Batrachomyomachy", "Making a mountain out of a molehill."));
System.out.println(dictionary);
dictionary.remove("scop");
System.out.println(dictionary);
//dictionary.removeAll();
}
public String toString()
{
String str = "";
for(int i = 0; i < numItems; i++)
{
str = str + Items[i] + "\n";
}
return str;
}
void add(dictionaryItem item){
if(numItems == 10)
{
System.out.println("Dictionary is full");
}
Items[numItems] = item;
numItems++;
}
void remove(String Key){
for(int i = 0; i < numItems; i++)
if(Items[i].Key == Key)
{
//clear out the item at the location of Key
Items[i] = null;
//move everything up
for(int j = i; j < numItems-1; j++){
Items[j] = Items[j+1];
}
//get rid of one of the number of items
numItems--;
//were done so exit
return;
}
//if we reach here, we did not find the key
System.out.println("Tried to remove. Could not find the key: "+ Key + "\n");
}
String getValue(String Key){
for(int i = 0; i < numItems; i++)
if(Items[i].Key == Key)
{
return Items[i].Value;
}
return "Could not find value for key: " + Key;
}
void removeAll(String Key){
for(int i = 0; i < numItems; i++)
{
Items[i] = null;
}
numItems = 0;
System.out.println("Deleted all the items");
}
}
| [
"[email protected]"
] | |
fd1eba0d13a23ddde7fb850070d41a2cce8be484 | f0f0d7304f60d67daf6554b81f14f65767f21c0d | /src/test/java/com/udacity/jwdnd/course1/cloudstorage/pages/NotesPage.java | eea6bd67e0d3e31ec95ad1e8740fb0b3c79b4897 | [] | no_license | VictorMOchoa/SuperDuperDrive | 69d4d715c46fd530831af1f42d077ac8879a05d1 | 69cb799f28b07e43a4a2eeec7a6285fabc1879f3 | refs/heads/main | 2023-03-19T02:04:54.968620 | 2021-03-22T05:23:48 | 2021-03-22T05:23:48 | 346,902,476 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,741 | java | package com.udacity.jwdnd.course1.cloudstorage.pages;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import org.openqa.selenium.support.ui.WebDriverWait;
import java.util.List;
public class NotesPage {
@FindBy(css = "#nav-notes-tab")
private WebElement notesTabField;
@FindBy(css = "#userTable")
private WebElement notesTable;
@FindBy (css="#submitNoteBtn")
private WebElement addButton;
@FindBy(css = "#note-id")
private WebElement noteId;
@FindBy(css = "#note-title")
private WebElement noteTitle;
@FindBy(css="#note-description")
private WebElement noteDescription;
@FindBy(css="#noteSubmit")
private WebElement noteSubmit;
@FindBy (css="#editNoteBtn")
private WebElement editButton;
@FindBy (css="#deleteNoteBtn")
private WebElement deleteButton;
@FindBy(css="#deleteNoteSubmit")
private WebElement deleteSubmit;
private final WebDriver driver;
private final WebDriverWait wait;
public NotesPage(WebDriver webDriver) {
this.driver = webDriver;
PageFactory.initElements(webDriver, this);
wait = new WebDriverWait(driver, 1000);
}
public void openNotesTab() {
((JavascriptExecutor) driver).executeScript("arguments[0].click();", notesTabField);
}
public void addNote(String title, String description){
openNotesTab();
((JavascriptExecutor) driver).executeScript("arguments[0].click();", addButton);
((JavascriptExecutor) driver).executeScript("arguments[0].value='" + title + "';", noteTitle);
((JavascriptExecutor) driver).executeScript("arguments[0].value='" + description + "';", noteDescription);
((JavascriptExecutor) driver).executeScript("arguments[0].click();", noteSubmit);
}
public void editNote(String title, String desc){
((JavascriptExecutor) driver).executeScript("arguments[0].click();", editButton);
((JavascriptExecutor) driver).executeScript("arguments[0].value='" + title + "';", noteTitle);
((JavascriptExecutor) driver).executeScript("arguments[0].value='" + desc + "';", noteDescription);
((JavascriptExecutor) driver).executeScript("arguments[0].click();", noteSubmit);
}
public void deleteNote(){
((JavascriptExecutor) driver).executeScript("arguments[0].click();", deleteButton);
}
public boolean notesExist() {
List<WebElement> allNotesForUser = notesTable.findElements(By.id("noteTitle"));
return allNotesForUser.size() != 0;
}
} | [
"[email protected]"
] | |
d29ca87102f4b28255f729493e66e7bba240edda | dd18ae3092a753d6edaea53013ee53145ddc8a13 | /MyApplication/src/main/java/com/vikash/controller/RestController.java | 3354594fd588a5f2b5b14bb0c40c6e7485863a37 | [] | no_license | prashant2668/YouTube | 79f6b5c7e127eb10cdfe3193c76cc0741e3a9fc4 | 6224898816757b925c8fc03b82bd01682167d021 | refs/heads/main | 2023-02-02T11:22:08.622200 | 2020-12-23T13:29:46 | 2020-12-23T13:29:46 | 311,270,117 | 0 | 0 | null | 2020-11-09T09:51:44 | 2020-11-09T08:24:05 | null | UTF-8 | Java | false | false | 857 | java | package com.vikash.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import com.vikash.modal.User;
import com.vikash.services.UserService;
@org.springframework.web.bind.annotation.RestController
public class RestController {
@Autowired
private UserService userService;
@GetMapping("/")
public String hello() {
return "This is Home page";
}
@GetMapping("/saveuser")
public String saveUser(@RequestParam String username, @RequestParam String firstname, @RequestParam String lastname, @RequestParam int age, @RequestParam String password) {
User user = new User(username, firstname, lastname, age, password);
userService.saveMyUser(user);
return "User Saved";
}
}
| [
"[email protected]"
] | |
14d76cbe7c9658ca6f7cb65b0577235b3f56ebc3 | be44d51541fd45102b9c928fe6667a375c65b8ce | /jk28_service/src/main/java/cn/itcast/jk/service/ContractProductService.java | e28aab64001fc55499b2fc0778f52c0cc9e742fa | [] | no_license | linmt/jk28_parent | 34ee14461e2f310d231d0914b26ca1f3f9e26d43 | f1be5442f072a77713a6468763f8934de3974e67 | refs/heads/master | 2022-12-22T22:14:36.188114 | 2019-08-25T11:29:05 | 2019-08-25T11:29:07 | 182,548,318 | 0 | 0 | null | 2022-12-16T02:34:41 | 2019-04-21T15:08:19 | JavaScript | UTF-8 | Java | false | false | 1,197 | java | package cn.itcast.jk.service;
import cn.itcast.jk.domain.ContractProduct;
import cn.itcast.jk.utils.Page;
import java.io.Serializable;
import java.util.Collection;
import java.util.List;
public interface ContractProductService {
//查询所有,带条件查询
public List<ContractProduct> find(String hql, Class<ContractProduct> entityClass, Object[] params);
//获取一条记录
public ContractProduct get(Class<ContractProduct> entityClass, Serializable id);
//分页查询,将数据封装到一个page分页工具类对象
public Page<ContractProduct> findPage(String hql, Page<ContractProduct> page, Class<ContractProduct> entityClass, Object[] params);
//新增和修改保存
public void saveOrUpdate(ContractProduct entity);
//批量新增和修改保存
public void saveOrUpdateAll(Collection<ContractProduct> entitys);
//单条删除,按id
public void deleteById(Class<ContractProduct> entityClass, Serializable id);
//批量删除
public void delete(Class<ContractProduct> entityClass, Serializable[] ids);
/**
* 删除指定的货物对象
*/
public void delete(Class<ContractProduct> entityClass, ContractProduct model);
}
| [
"[email protected]"
] | |
871746d086819392fcaa49218b5d343402cc3582 | 1d1cdccfd43887cb51656fe29c696f3b4be97fcd | /src/core04/task5/Portable.java | 1c3e67d7ce888ef9028fac4df2e740f18c3caecb | [] | no_license | annkarpenko/TA | d9fea1db4fe9da159fb9058284189a0c98472288 | cd59e9a38b0839f93058ab43e560e3cd17479181 | refs/heads/main | 2023-03-12T09:03:10.474224 | 2021-03-02T19:53:07 | 2021-03-02T19:53:07 | 332,288,323 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 393 | java | package src.core04.task5;
public class Portable extends Electronics {
private int battery;
public Portable (String brand, String model, double price, int battery){
super(brand, model, price);
this.battery = battery;
}
@Override
public void printData() {
super.printData();
System.out.print(" Battery: " + this.battery + "\n");
}
}
| [
"[email protected]"
] | |
a9275b4a893491815210758efb4fdf722da4b17e | 0b55e544bb6c9f3558021881c75e0a586e838fda | /app/src/main/java/com/example/api/view/fragment/OwnedGamesFragment.java | 0f5aae0beb2b3c36d6c121376f10681e3294b17e | [] | no_license | RedWolf3121/API_dpando | 21cba3d9f34ced6a928236f935bb07104e90a1f4 | 806de048a0cd283924097d0c062e2e2d3fafd346 | refs/heads/master | 2020-04-28T15:39:13.806237 | 2019-03-13T08:57:37 | 2019-03-13T08:57:37 | 175,307,691 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,155 | java | package com.example.api.view.fragment;
import android.arch.lifecycle.Observer;
import android.arch.lifecycle.ViewModelProviders;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.example.api.MainViewModel;
import com.example.api.R;
import com.example.api.model.Game;
import java.util.ArrayList;
import java.util.List;
/**
* A simple {@link Fragment} subclass.
*/
public class OwnedGamesFragment extends Fragment {
private MainViewModel mViewModel;
private RecyclerView mRecyclerView;
private OwnedGamesFragment.OwnedGamesAdapter mOwnedGamesAdapter;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_owned_games, container, false);
mRecyclerView = view.findViewById(R.id.ownedGamesList);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
mOwnedGamesAdapter = new OwnedGamesFragment.OwnedGamesAdapter();
mRecyclerView.setAdapter(mOwnedGamesAdapter);
mViewModel = ViewModelProviders.of(this).get(MainViewModel.class);
mViewModel.getOwnedGames().observe(this, new Observer<List<Game>>() {
@Override
public void onChanged(@Nullable List<Game> games) {
mOwnedGamesAdapter.gameList = games;
mOwnedGamesAdapter.notifyDataSetChanged();
}
});
return view;
}
public class OwnedGamesAdapter extends RecyclerView.Adapter<OwnedGamesAdapter.OwnedGamesViewHolder>{
public List<Game> gameList = new ArrayList<>();
@NonNull
@Override
public OwnedGamesViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_games, parent, false);
return new OwnedGamesViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull OwnedGamesViewHolder holder, int position) {
Game game = gameList.get(position);
holder.appid.setText(String.valueOf(game.appid));
holder.playtime_forever.setText(String.valueOf(game.playtime_forever));
}
@Override
public int getItemCount() {
return gameList.size();
}
class OwnedGamesViewHolder extends RecyclerView.ViewHolder {
TextView appid;
TextView playtime_forever;
public OwnedGamesViewHolder(View itemView) {
super(itemView);
appid = itemView.findViewById(R.id.appid);
playtime_forever = itemView.findViewById(R.id.playtime_forever);
}
}
}
}
| [
"[email protected]"
] | |
fb7be33ef3456e7aedbfafa5dda9d709d643a2f2 | 166aea0f5909d2d541bcbbdb96f945bade7e8fc3 | /src/main/java/com/cit/its/messageStruct/DriveMotorData.java | 8a22d2cbf7caac663834131239d24519cfb238e2 | [] | no_license | zqingxi/vehicleNet | 85d43e9b3511e1b68ed7f08fd39bec9998d439d9 | 0d9f8f8a7eefaba70e31ded402b552e5c2a0bb67 | refs/heads/master | 2021-06-12T14:36:33.429731 | 2017-03-20T03:07:38 | 2017-03-20T03:07:38 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,418 | java | package com.cit.its.messageStruct;
public class DriveMotorData {
private String vehicleVIN; // 车辆VIN码
private short numberOfDriveMotors; // 驱动电机个数
// Drive the motor assembly information list
// 驱动电机总成信息列表
// 存疑,是否使用list效率更佳?
private DriveMotor[] driMotorInfoList;
// set, get方法
public void setVehicleVIN(String vehicleVIN) {
this.vehicleVIN = vehicleVIN;
}
public String getVehicleVIN() {
return vehicleVIN;
}
public void setNumberOfDriveMotors(short numberOfDriveMotors) {
this.numberOfDriveMotors = numberOfDriveMotors;
}
public short getNumberOfDriveMotors() {
return numberOfDriveMotors;
}
public void setDriMotorInfoList(DriveMotor[] driMotorInfoList) {
this.driMotorInfoList = driMotorInfoList;
}
public DriveMotor[] getDriMotorInfoList() {
return driMotorInfoList;
}
// 重写toString()方法
public String toString() {
System.out.println("车辆VIN码 : " + vehicleVIN);
System.out.println("驱动电机个数 : " + numberOfDriveMotors);
System.out.println("驱动电机总成信息列表 : ");
for (int i = 0; i < numberOfDriveMotors; i++) {
System.out.println(driMotorInfoList[i]);
}
return "Drive Motor Data is over !";
}
/*
public static void main(String[] args) {
DriveMotorData driveMotorData = new DriveMotorData();
short number = (short) (Math.random() * 25 + 1);
short[] driveMotorState = {0x01, 0x02, 0x03, 0x04, 0xFE, 0xFF};
driveMotorData.setVehicleVIN("12345678901234567");
driveMotorData.setNumberOfDriveMotors(number);
DriveMotor[] driveMotorList = new DriveMotor[number];
for (int i = 0; i < number; i++) {
driveMotorList[i] = new DriveMotor();
}
for (int i = 0; i < number; i++) {
driveMotorList[i].setDriveMotorSerialNumber((short) (i+1));
driveMotorList[i].setDriveMotorState(driveMotorState[(int) (Math.random() * driveMotorState.length)]);
driveMotorList[i].setDriveMotorControllerTemperature((short) (Math.random() * 250));
driveMotorList[i].setDriveMotorSpeed((int) (Math.random() * 65531));
driveMotorList[i].setDriveMotorTorque((int) (Math.random() * 65531));
driveMotorList[i].setDriveMotorTemperature((short) (Math.random() * 250));
driveMotorList[i].setMotorControllerInputVoltage((int) (Math.random() * 60000));
driveMotorList[i].setMotorControllerDCBusCurrent((int) (Math.random() * 20000));
}
for (int i = 0; i < number; i++) {
System.out.println("driveMotorList[" + i + "]" + driveMotorList[i]);
}
driveMotorData.setDriMotorInfoList(driveMotorList);
System.out.println(driveMotorData);
DriveMotor driveMotor = new DriveMotor();
driveMotor.setDriveMotorSerialNumber((short) (1));
driveMotor.setDriveMotorState(driveMotorState[(int) (Math.random() * driveMotorState.length)]);
driveMotor.setDriveMotorControllerTemperature((short) (Math.random() * 250));
driveMotor.setDriveMotorSpeed((int) (Math.random() * 65531));
driveMotor.setDriveMotorTorque((int) (Math.random() * 65531));
driveMotor.setDriveMotorTemperature((short) (Math.random() * 250));
driveMotor.setMotorControllerInputVoltage((int) (Math.random() * 60000));
driveMotor.setMotorControllerDCBusCurrent((int) (Math.random() * 20000));
System.out.println(driveMotor);
}
*/
}
| [
"QingXi@DESKTOP-U057NMS"
] | QingXi@DESKTOP-U057NMS |
8e739bef7d25fdfb3bcb7eb208d57672be5a3dd3 | cc416afd04b8526a696fdf11260e478fa2be0529 | /collectiontesting/src/TelephoneBook/Address.java | ad2b8648065484a3133c015c6a2459b392f91958 | [] | no_license | PR2-SS13/prp | c869d565b6b38f79c1f2de6ee95772060d0e68a3 | f65ca99976e8936e463a200e8ac78374bb39206b | refs/heads/master | 2021-01-13T01:44:56.837905 | 2013-06-29T14:29:59 | 2013-06-29T14:29:59 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,760 | java | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package TelephoneBook;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Objects;
/**
*
* @author sacry
*/
public class Address extends AbstractUtils {
private String street, country, state;
private Integer postal, streetnum;
public Address(String country, String state, Integer postal, String street, Integer streetnum) {
this.country = country;
this.state = state;
this.postal = postal;
this.street = street;
this.streetnum = streetnum;
}
public ArrayList<Object> getAddress() {
return new ArrayList<Object>(Arrays.asList(country, state, postal, street, streetnum));
}
public String getStreet() {
return street;
}
public String getCountry() {
return country;
}
public String getState() {
return state;
}
public int getPostal() {
return postal;
}
public int getStreetnum() {
return streetnum;
}
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof Address)) {
return false;
}
Address addr = (Address) obj;
if (addr.getAddress().containsAll(this.getAddress())) {
return true;
}
return false;
}
@Override
public int hashCode() {
return hashDouble(this.street + this.country + this.postal.toString() + this.street + this.streetnum.toString());
}
@Override
public String toString() {
return state + ", " + postal.toString() + ", " + street + ", " + streetnum.toString();
}
}
| [
"[email protected]"
] | |
0e1ebed0075b356312c2f9d49352558e869aaa76 | b4dba1c8fe98a8ac79b0bf2b1c2eb4a561fe0cac | /src/main/java/com/funny/admin/system/service/impl/ScheduleJobServiceImpl.java | b55dc36bb8a72902643859df6e0aeb8606fe3faf | [] | no_license | weichanchan/funny-deposit | 0410f42be149db6e40c962e864c865fa29e7a0bc | f8c91c53deb9f45dee5433a3c72447ddcb097433 | refs/heads/master | 2022-07-11T02:53:04.849596 | 2019-03-22T09:00:18 | 2019-03-22T09:00:18 | 146,894,368 | 1 | 0 | null | 2022-07-06T20:09:11 | 2018-08-31T13:16:50 | Java | UTF-8 | Java | false | false | 3,430 | java | package com.funny.admin.system.service.impl;
import com.funny.admin.system.dao.ScheduleJobDao;
import com.funny.utils.Constant;
import com.funny.utils.ScheduleUtils;
import com.funny.admin.system.entity.ScheduleJobEntity;
import com.funny.admin.system.service.ScheduleJobService;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.PostConstruct;
import org.quartz.CronTrigger;
import org.quartz.Scheduler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service("scheduleJobService")
public class ScheduleJobServiceImpl implements ScheduleJobService {
@Autowired
private Scheduler scheduler;
@Autowired
private ScheduleJobDao schedulerJobDao;
/**
* 项目启动时,初始化定时器
*/
@PostConstruct
public void init(){
List<ScheduleJobEntity> scheduleJobList = schedulerJobDao.queryList(new HashMap<>());
for(ScheduleJobEntity scheduleJob : scheduleJobList){
CronTrigger cronTrigger = ScheduleUtils.getCronTrigger(scheduler, scheduleJob.getJobId());
//如果不存在,则创建
if(cronTrigger == null) {
ScheduleUtils.createScheduleJob(scheduler, scheduleJob);
}else {
ScheduleUtils.updateScheduleJob(scheduler, scheduleJob);
}
}
}
@Override
public ScheduleJobEntity queryObject(Long jobId) {
return schedulerJobDao.queryObject(jobId);
}
@Override
public List<ScheduleJobEntity> queryList(Map<String, Object> map) {
return schedulerJobDao.queryList(map);
}
@Override
public int queryTotal(Map<String, Object> map) {
return schedulerJobDao.queryTotal(map);
}
@Override
@Transactional
public void save(ScheduleJobEntity scheduleJob) {
scheduleJob.setCreateTime(new Date());
scheduleJob.setStatus(Constant.ScheduleStatus.NORMAL.getValue());
schedulerJobDao.save(scheduleJob);
ScheduleUtils.createScheduleJob(scheduler, scheduleJob);
}
@Override
@Transactional
public void update(ScheduleJobEntity scheduleJob) {
ScheduleUtils.updateScheduleJob(scheduler, scheduleJob);
schedulerJobDao.update(scheduleJob);
}
@Override
@Transactional
public void deleteBatch(Long[] jobIds) {
for(Long jobId : jobIds){
ScheduleUtils.deleteScheduleJob(scheduler, jobId);
}
//删除数据
schedulerJobDao.deleteBatch(jobIds);
}
@Override
public int updateBatch(Long[] jobIds, int status){
Map<String, Object> map = new HashMap<>();
map.put("list", jobIds);
map.put("status", status);
return schedulerJobDao.updateBatch(map);
}
@Override
@Transactional
public void run(Long[] jobIds) {
for(Long jobId : jobIds){
ScheduleUtils.run(scheduler, queryObject(jobId));
}
}
@Override
@Transactional
public void pause(Long[] jobIds) {
for(Long jobId : jobIds){
ScheduleUtils.pauseJob(scheduler, jobId);
}
updateBatch(jobIds, Constant.ScheduleStatus.PAUSE.getValue());
}
@Override
@Transactional
public void resume(Long[] jobIds) {
for(Long jobId : jobIds){
ScheduleUtils.resumeJob(scheduler, jobId);
}
updateBatch(jobIds, Constant.ScheduleStatus.NORMAL.getValue());
}
}
| [
"[email protected]"
] | |
e3d2bca25d6a9c60836af7485a6c1e58c2ad6c9c | aa2cd49a57c043d5aa5429728c657da105e22c46 | /app/src/main/java/com/lianxi/dingtu/newsnfc/mvp/model/entity/UserInfoTo.java | cfa229c78cf49d945dbf1adb73256a6046fa3550 | [] | no_license | scygh/NEW_NFC | 3718ebbe22b89f7e8d31e952b575d0dc44ed8fdf | 61df95fbd7a2c779853edebc0b0d1b4299c8757f | refs/heads/master | 2020-09-08T10:06:52.128400 | 2020-04-18T08:36:17 | 2020-04-18T08:36:17 | 221,102,822 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,530 | java | package com.lianxi.dingtu.newsnfc.mvp.model.entity;
import java.io.Serializable;
public class UserInfoTo implements Serializable {
/**
* AccessToken : ae879ba3-260e-4797-906a-48b862f77292
* CompanyCode : 1001
* UserID : c883048c-dec8-4bbc-bb4b-1d29594d87fd
* Account : 1001
* ExpirationTime : 2018-11-15 13:34:48
* PassWord : 100
*/
private String AccessToken;
private int CompanyCode;
private String UserID;
private String Account;
private String ExpirationTime;
private String PassWord;
public String getAccessToken() {
return AccessToken;
}
public void setAccessToken(String AccessToken) {
this.AccessToken = AccessToken;
}
public int getCompanyCode() {
return CompanyCode;
}
public void setCompanyCode(int CompanyCode) {
this.CompanyCode = CompanyCode;
}
public String getUserID() {
return UserID;
}
public void setUserID(String UserID) {
this.UserID = UserID;
}
public String getAccount() {
return Account;
}
public void setAccount(String Account) {
this.Account = Account;
}
public String getExpirationTime() {
return ExpirationTime;
}
public void setExpirationTime(String ExpirationTime) {
this.ExpirationTime = ExpirationTime;
}
public String getPassWord() {
return PassWord;
}
public void setPassWord(String PassWord) {
this.PassWord = PassWord;
}
}
| [
"[email protected]"
] | |
c5f11a07fd6755253e80616b05f615413087fa25 | 31e6b35084d827faab137cb9f25fac9c5ea6d132 | /IANEW/src/uow/ia/search/TokenAnalyzer.java | 60f6cf97989a5a0da93e28775d1387b27768f121 | [] | no_license | IATeam/IANEW | 560a7d79c544d669c6fc8df3c06db514ac06d9a7 | 626b11a4e9a2b2d433bcd9b291ff7e8b3d249ec0 | refs/heads/master | 2021-01-13T02:14:46.670571 | 2014-10-22T23:31:52 | 2014-10-22T23:31:52 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 11,591 | java | package uow.ia.search;
import java.io.InputStream;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import javax.servlet.ServletContext;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.springframework.context.ApplicationContext;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import com.opensymphony.xwork2.ActionContext;
import com.sun.research.ws.wadl.Request;
public class TokenAnalyzer {
private String searchString;
private Class<?> entity;
private Set<String> fullPathSet = new HashSet<String>();
public TokenAnalyzer(Class<?> entity, String searchString) {
this.entity = entity;
this.searchString = lowerCasing(searchString);
}
public String xpathing(Document doc) throws Exception {
// DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
// factory.setNamespaceAware(true);
// DocumentBuilder builder = factory.newDocumentBuilder();
//
// String path = "ianewPathDictionary.xml";
//
// //ApplicationContext appContext;
// //appContext.getResource("classpath:uow/ia/search/ianewPathDictionary.xml");
// //InputStream is =
//
//
//
// Document doc = builder.parse(getClass().getResourceAsStream(path));
XPathFactory xpathfactory = XPathFactory.newInstance();
XPath xpath = xpathfactory.newXPath();
try {
dddd(doc, xpath);
return this.searchString;
} catch (NullPointerException e) {
}
return this.searchString;
}
private String lowerCasing(String string) {
if ((string.length() < 1) || (string.contains("[^a-zA-Z/d]")))
return this.searchString;
String[] split = string.split(" ");
String returnString = "";
for (String s : split) {
if (!isReservedWord(s))
returnString += s.toLowerCase() + " ";
else {
returnString += s + " ";
}
}
return returnString;
}
private ArrayList<String> getAsterizedSearchStringAsList() {
ArrayList<String> modifiedSearchStringList = new ArrayList<String>();
String[] colonSplit = this.searchString.trim().split(":");
int colonSize = colonSplit.length;
if (colonSize > 1) {
for (int i = 0; i < colonSize; i++) {
if (i < colonSize - 1)
modifiedSearchStringList.add(assignAsterixes(colonSplit[i],true));
else
modifiedSearchStringList.add(assignAsterixes(colonSplit[i],false));
}
} else {
modifiedSearchStringList.add(assignAsterixes(colonSplit[0], false));
}
return modifiedSearchStringList;
}
private void updateSearchString(ArrayList<String> searchStringList) {
System.out.println(searchString);
searchString = "";
for (int i = 0; i < searchStringList.size(); i++)
searchString += searchStringList.get(i) + " ";
System.out.println(searchString);
}
private Map<String, ArrayList<String>> getMappedQuery() {
Map<String, ArrayList<String>> mappedQuery = new HashMap<String, ArrayList<String>>();
String[] whiteSplit = null;
ArrayList<String> asterizedList = getAsterizedSearchStringAsList();
updateSearchString(asterizedList);
if (asterizedList.size() > 1) {
for (int i = 0; i < asterizedList.size(); i++) {
whiteSplit = ((String) asterizedList.get(i)).split(" ");
int end = whiteSplit.length - 1;
if (i < asterizedList.size() - 1) {
String key = whiteSplit[end];
String value = null;
int grpIndex = getGroupTokenPosition(asterizedList.get(i + 1).trim());
if (grpIndex > 0)
value = asterizedList.get(i + 1).trim().substring(0, grpIndex);
else {
value = asterizedList.get(i + 1).trim().split(" ")[0];
}
if (!mappedQuery.containsKey(key))
mappedQuery.put(key, new ArrayList<String>());
mappedQuery.get(key).add(value);
}
}
return mappedQuery;
}
return null;
}
public String assignAsterixes(String string, boolean ignore)
{
String[] whiteSplit = string.trim().split(" ");
int lastSplitIndex = whiteSplit.length - 1;
String returnString = "";
for (int i = 0; i < whiteSplit.length; i++)
{
if (!whiteSplit[i].contains("*") && ((i == lastSplitIndex && !ignore) || i != lastSplitIndex)){
int lastIndex = whiteSplit[i].length() - 1;
char lastChar = whiteSplit[i].charAt(lastIndex);
switch (lastChar) {
case '"':
case '\'':
case '(':
case ')':
case '/':
case '[':
case ']':
case '{':
case '}':
if (whiteSplit[i].length() > 1) {
String substring = whiteSplit[i].substring(0, lastIndex);
if (!isReservedWord(substring))
whiteSplit[i] = whiteSplit[i].replace(substring, substring + "*");
returnString = returnString + whiteSplit[i] + " ";
}
break;
default:
if (!isReservedWord(whiteSplit[i])) {
returnString += whiteSplit[i] + "* ";
} else {
returnString += whiteSplit[i] + " ";
}
}
}else {
returnString = returnString + whiteSplit[i];
}
}
return returnString;
}
private void dddd(Document doc, XPath xpath) {
String[] whiteSplit = null;
int indexPtr = 0;
ArrayList<String> asterizedList = getAsterizedSearchStringAsList();
updateSearchString(asterizedList);
Map<String, ArrayList<SearchNode>> pathList = null;
if (asterizedList.size() > 1) {
for (int i = 0; i < asterizedList.size(); i++) {
whiteSplit = asterizedList.get(i).split(" ");
int end = whiteSplit.length - 1;
String transformedString = "";
if (i < asterizedList.size() - 1) {
String key = whiteSplit[end];
String queryValue = asterizedList.get(i + 1).trim();
String originalValue = null;
int grpIndex = getGroupTokenPosition(asterizedList.get(i + 1).trim());
String newValue = null;
if (grpIndex > 0) {
newValue = queryValue.substring(0, grpIndex);
originalValue = newValue;
} else {
newValue = originalValue = queryValue.split(" ")[0];
}
pathList = getAliasName(doc, xpath, key, newValue);
for (String operator : pathList.keySet()) {
if (pathList.get(operator).size() > 0) {
for (SearchNode snode : pathList.get(operator)) {
ArrayList<String> paths = getPathWithRef(doc, xpath, snode.getRef(), operator);
if (paths.size() == 1)
transformedString = (String) paths.get(0) + ":" + snode.getValue() + " ";
else {
for (int k = 0; k < paths.size(); k++) {
if (k == 0)
transformedString = transformedString
+ " ("
+ (String) paths.get(k)
+ ":"
+ snode.getValue()
+ " OR ";
else if (k == paths.size() - 1)
transformedString = transformedString
+ (String) paths.get(k)
+ ":"
+ snode.getValue()
+ ") ";
else
transformedString = transformedString
+ (String) paths.get(k)
+ ":"
+ snode.getValue()
+ " OR ";
}
}
SearchNode lastNode = pathList.get(operator).get(pathList.get(operator).size() - 1);
if (!isEqualNode(snode, lastNode)) {
switch (operator) {
case "AND": transformedString = transformedString + " AND "; break;
case "OR":
default: transformedString = transformedString + " OR "; break; /*includes null*/
}
}
}
}
}
int beginIndex = this.searchString.indexOf(key, indexPtr);
int endIndex = this.searchString.indexOf(originalValue, beginIndex) + originalValue.length();
this.searchString = this.searchString.replace(this.searchString.substring(beginIndex, endIndex), transformedString);
indexPtr = beginIndex + transformedString.length();
}
}
}
}
private boolean isEqualNode(SearchNode n1, SearchNode n2) {
if (n1 == n2) {
return true;
}
return false;
}
private int getGroupTokenPosition(String string) {
char grpToken = string.charAt(0);
switch (grpToken) {
case '"':
return string.indexOf('"', 1) + 1;
case '\'':
return string.indexOf('\'', 1) + 1;
case '[':
return string.indexOf(']', 1) + 1;
case '(':
return string.indexOf(')', 1) + 1;
case '{':
return string.indexOf('}', 1) + 1;
case '/':
return string.indexOf('/', 1) + 1;
}
return 0;
}
private boolean isReservedWord(String word) {
if ((word.equals("TO")) || (word.equals("AND")) || (word.equals("OR")) || (word.equals("NOT"))) {
return true;
}
return false;
}
private Map<String, ArrayList<SearchNode>> getAliasName(Document doc, XPath xpath, String key, String value) {
Map<String, ArrayList<SearchNode>> aliasNames = new HashMap<String, ArrayList<SearchNode>>();
aliasNames.put("AND", new ArrayList<SearchNode>());
aliasNames.put("OR", new ArrayList<SearchNode>());
aliasNames.put("NULL", new ArrayList<SearchNode>());
XPathExpression expr = null;
NodeList nodes = null;
try {
expr = xpath.compile("//afield[@alias='" + key + "']");
nodes = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
if (nodes.getLength() > 0) {
expr = xpath.compile("//afield[@alias='" + key + "']/grp[@operator='AND']/ref");
nodes = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
if (nodes.getLength() > 0) {
mapOperator("AND", nodes, aliasNames, value);
}
expr = xpath.compile("//afield[@alias='" + key + "']/grp[@operator='OR']/ref");
nodes = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
if (nodes.getLength() > 0) {
mapOperator("OR", nodes, aliasNames, value);
}
} else {
aliasNames.get("NULL").add(new SearchNode(key, value));
}
} catch (XPathExpressionException e) {
e.printStackTrace();
}
return aliasNames;
}
private void mapOperator(String operator, NodeList nodes,
Map<String, ArrayList<SearchNode>> pathList, String value) {
for (int i = 0; i < nodes.getLength(); i++) {
SearchNode snode = null;
try {
snode = new SearchNode(nodes.item(i).getFirstChild()
.getNodeValue(), nodes.item(i).getAttributes()
.getNamedItem("value").getTextContent());
} catch (NullPointerException np) {
snode = new SearchNode(nodes.item(i).getFirstChild()
.getNodeValue(), value);
}
pathList.get(operator).add(snode);
}
}
private ArrayList<String> getPathWithRef(Document doc, XPath xpath,
String ref, String operator) {
ArrayList<String> pathList = new ArrayList<String>();
XPathExpression expr = null;
try {
String entityName = "";
if (this.entity != null) {
entityName = "='" + this.entity.getSimpleName() + "'";
}
expr = xpath.compile("//field[@id='" + ref + "']/entity[@name" + entityName + "]/path/text() | //entity[@name" + entityName + "]/path[@id='" + ref + "']/text()");
NodeList nodes = (NodeList) expr.evaluate(doc,
XPathConstants.NODESET);
if (nodes.getLength() > 0) {
for (int i = 0; i < nodes.getLength(); i++)
if (!this.fullPathSet.contains(nodes.item(i).getNodeValue()
.toString())) {
this.fullPathSet.add(nodes.item(i).getNodeValue()
.toString());
pathList.add(nodes.item(i).getNodeValue().toString());
}
} else
pathList.add(ref);
} catch (XPathExpressionException e) {
e.printStackTrace();
}
return pathList;
}
} | [
"[email protected]"
] | |
1c31f4c41aeadec3166b545c95d60a1f08560e33 | 072951a21157d4682c2fab6e01928b6550752373 | /csharp/src/main/java/org/codehaus/enunciate/modules/csharp/CSharpDeploymentModule.java | 57482e00fdc44f66b231320502bf4fe03c8ca650 | [
"Apache-2.0"
] | permissive | martin-magakian/enunciate | 05356fef1d5b02a41b76ac4cf2071a67b52a5ad5 | b6e5c1bba9d1f847bf53d7d0c902f5abbf25b8b3 | refs/heads/master | 2020-12-25T03:42:43.190981 | 2013-09-20T17:58:52 | 2013-09-20T18:12:39 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 26,370 | java | /*
* Copyright 2006-2008 Web Cohesion
*
* 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.codehaus.enunciate.modules.csharp;
import freemarker.template.*;
import net.sf.jelly.apt.decorations.JavaDoc;
import net.sf.jelly.apt.freemarker.FreemarkerJavaDoc;
import org.apache.commons.digester.RuleSet;
import org.codehaus.enunciate.EnunciateException;
import org.codehaus.enunciate.apt.EnunciateFreemarkerModel;
import org.codehaus.enunciate.config.SchemaInfo;
import org.codehaus.enunciate.config.WsdlInfo;
import org.codehaus.enunciate.contract.jaxb.TypeDefinition;
import org.codehaus.enunciate.contract.jaxws.EndpointInterface;
import org.codehaus.enunciate.contract.jaxws.WebFault;
import org.codehaus.enunciate.contract.jaxws.WebMethod;
import org.codehaus.enunciate.contract.validation.Validator;
import org.codehaus.enunciate.main.*;
import org.codehaus.enunciate.modules.FacetAware;
import org.codehaus.enunciate.modules.FreemarkerDeploymentModule;
import org.codehaus.enunciate.modules.csharp.config.CSharpRuleSet;
import org.codehaus.enunciate.modules.csharp.config.PackageNamespaceConversion;
import org.codehaus.enunciate.template.freemarker.AccessorOverridesAnotherMethod;
import org.codehaus.enunciate.template.freemarker.ClientPackageForMethod;
import org.codehaus.enunciate.template.freemarker.SimpleNameWithParamsMethod;
import org.codehaus.enunciate.util.TypeDeclarationComparator;
import java.io.*;
import java.net.URL;
import java.util.*;
/**
* <h1>C# Module</h1>
*
* <p>The C# module generates C# client code for accessing the SOAP endpoints and makes an attempt at compiling the code in a .NET assembly. If the the compile
* attempt is to be successful, then you must have a C# compiler available on your system path, or specify a "compileExecutable" attribute in the Enunciate
* configuration file. If the compile attempt fails, only the C# source code will be made available as a client artifact.</p>
*
* <p>The order of the C# deployment module is 0, as it doesn't depend on any artifacts exported by any other module.</p>
*
* <ul>
* <li><a href="#config">configuration</a></li>
* </ul>
*
* <h1><a name="config">Configuration</a></h1>
*
* <p>The C# module is configured with the "csharp" element under the "modules" element of the enunciate configuration file. It supports the following
* attributes:</p>
*
* <ul>
* <li>The "label" attribute is the label for the C# API. This is the name by which the files will be identified, producing [label].cs and [label].dll.
* By default the label is the same as the Enunciate project label. For a more custom configuration of the generated file names, use the
* "bundleFileName", "DLLFileName", "docXmlFileName", and "sourceFileName" attributes.</li>
* <li>The "compileExecutable" attribute is the executable for invoking the C# compiler. If not supplied, an attempt will be made to find a C# compiler on the
* system path. If the attempt fails, the C# code will not be compiled (but the source code will still be made available as a download artifact).</li>
* <li>The "compileCommand" is a <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/Formatter.html#syntax">Java format string</a> that represents the
* full command that is used to invoke the C# compiler. The string will be formatted with the following arguments: compile executable, assembly path,
* doc xml path, source doc path. The default value is "%s /target:library /out:%s /r:System.Web.Services /doc:%s %s"</li>
* <li>The "singleFilePerClass" allows you to specify that Enunciate should generate a file for each C# class. By default (<tt>false</tt>), Enunciate
* puts all C# classes into a single file.</li>
* </ul>
*
* <h3>The "package-conversions" element</h3>
*
* <p>The "package-conversions" subelement of the "csharp" element is used to map packages from
* the original API packages to C# namespaces. This element supports an arbitrary number of
* "convert" child elements that are used to specify the conversions. These "convert" elements support
* the following attributes:</p>
*
* <ul>
* <li>The "from" attribute specifies the package that is to be converted. This package will match
* all classes in the package as well as any subpackages of the package. This means that if "org.enunciate"
* were specified, it would match "org.enunciate", "org.enunciate.api", and "org.enunciate.api.impl".</li>
* <li>The "to" attribute specifies what the package is to be converted to. Only the part of the package
* that matches the "from" attribute will be converted.</li>
* </ul>
*
* <h3>The "facets" element</h3>
*
* <p>The "facets" element is applicable to the C# module to configure which facets are to be included/excluded from the C# artifacts. For
* more information, see <a href="http://docs.codehaus.org/display/ENUNCIATE/Enunciate+API+Facets">API Facets</a></p>
*
* @author Ryan Heaton
* @docFileName module_csharp.html
*/
public class CSharpDeploymentModule extends FreemarkerDeploymentModule implements FacetAware {
private boolean require = false;
private boolean disableCompile = true;
private String label = null;
private String compileExecutable = null;
private String compileCommand = "%s /target:library /out:%s /r:System.Web.Services /doc:%s %s";
private final Map<String, String> packageToNamespaceConversions = new HashMap<String, String>();
private String bundleFileName = null;
private String DLLFileName = null;
private String docXmlFileName = null;
private String sourceFileName = null;
private boolean singleFilePerClass = false;
private Set<String> facetIncludes = new TreeSet<String>();
private Set<String> facetExcludes = new TreeSet<String>();
public CSharpDeploymentModule() {
}
/**
* @return "csharp"
*/
@Override
public String getName() {
return "csharp";
}
@Override
public void init(Enunciate enunciate) throws EnunciateException {
super.init(enunciate);
if (!super.isDisabled()) { //if we're explicitly disabled, we can ignore this...
if (isDisableCompile()) {
info("C# compilation is disabled, but the source code will still be generated.");
setCompileExecutable(null);
}
else {
String compileExectuable = getCompileExecutable();
if (compileExectuable == null) {
String osName = System.getProperty("os.name");
if (osName != null && osName.toUpperCase().contains("WINDOWS")) {
//try the "csc" command on Windows environments.
debug("Attempting to execute command \"csc /help\" for the current environment (%s).", osName);
try {
Process process = new ProcessBuilder("csc", "/help").redirectErrorStream(true).start();
InputStream in = process.getInputStream();
byte[] buffer = new byte[1024];
int len = in.read(buffer);
while (len >- 0) {
len = in.read(buffer);
}
int exitCode = process.waitFor();
if (exitCode != 0) {
debug("Command \"csc /help\" failed with exit code " + exitCode + ".");
}
else {
compileExectuable = "csc";
debug("C# compile executable to be used: csc");
}
}
catch (Throwable e) {
debug("Command \"csc /help\" failed (" + e.getMessage() + ").");
}
}
if (compileExectuable == null) {
//try the "gmcs" command (Mono)
debug("Attempting to execute command \"gmcs /help\" for the current environment (%s).", osName);
try {
Process process = new ProcessBuilder("gmcs", "/help").redirectErrorStream(true).start();
InputStream in = process.getInputStream();
byte[] buffer = new byte[1024];
int len = in.read(buffer);
while (len >- 0) {
len = in.read(buffer);
}
int exitCode = process.waitFor();
if (exitCode != 0) {
debug("Command \"gmcs /help\" failed with exit code " + exitCode + ".");
}
else {
compileExectuable = "gmcs";
debug("C# compile executable to be used: %s", compileExectuable);
}
}
catch (Throwable e) {
debug("Command \"gmcs /help\" failed (" + e.getMessage() + ").");
}
}
if (compileExectuable == null && isRequire()) {
throw new EnunciateException("C# client code generation is required, but there was no valid compile executable found. " +
"Please supply one in the configuration file, or set it up on your system path.");
}
setCompileExecutable(compileExectuable);
}
}
}
}
@Override
public void initModel(EnunciateFreemarkerModel model) {
super.initModel(model);
if (!isDisabled()) {
TreeSet<WebFault> allFaults = new TreeSet<WebFault>(new TypeDeclarationComparator());
for (WsdlInfo wsdlInfo : model.getNamespacesToWSDLs().values()) {
for (EndpointInterface ei : wsdlInfo.getEndpointInterfaces()) {
String pckg = ei.getPackage().getQualifiedName();
if (!this.packageToNamespaceConversions.containsKey(pckg)) {
this.packageToNamespaceConversions.put(pckg, packageToNamespace(pckg));
}
for (WebMethod webMethod : ei.getWebMethods()) {
for (WebFault webFault : webMethod.getWebFaults()) {
allFaults.add(webFault);
}
}
}
}
for (WebFault webFault : allFaults) {
String pckg = webFault.getPackage().getQualifiedName();
if (!this.packageToNamespaceConversions.containsKey(pckg)) {
this.packageToNamespaceConversions.put(pckg, packageToNamespace(pckg));
}
}
for (SchemaInfo schemaInfo : model.getNamespacesToSchemas().values()) {
for (TypeDefinition typeDefinition : schemaInfo.getTypeDefinitions()) {
String pckg = typeDefinition.getPackage().getQualifiedName();
if (!this.packageToNamespaceConversions.containsKey(pckg)) {
this.packageToNamespaceConversions.put(pckg, packageToNamespace(pckg));
}
}
}
}
}
protected String packageToNamespace(String pckg) {
if (pckg == null) {
return null;
}
else {
StringBuilder ns = new StringBuilder();
for (StringTokenizer toks = new StringTokenizer(pckg, "."); toks.hasMoreTokens();) {
String tok = toks.nextToken();
ns.append(Character.toString(tok.charAt(0)).toUpperCase());
if (tok.length() > 1) {
ns.append(tok.substring(1));
}
if (toks.hasMoreTokens()) {
ns.append('.');
}
}
return ns.toString();
}
}
@Override
public void doFreemarkerGenerate() throws IOException, TemplateException {
File genDir = getGenerateDir();
if (!enunciate.isUpToDateWithSources(genDir)) {
EnunciateFreemarkerModel model = getModel();
ClientPackageForMethod namespaceFor = new ClientPackageForMethod(this.packageToNamespaceConversions);
namespaceFor.setUseClientNameConversions(true);
model.put("namespaceFor", namespaceFor);
model.put("findRootElement", new FindRootElementMethod());
model.put("requestDocumentQName", new RequestDocumentQNameMethod());
model.put("responseDocumentQName", new ResponseDocumentQNameMethod());
ClientClassnameForMethod classnameFor = new ClientClassnameForMethod(this.packageToNamespaceConversions);
classnameFor.setUseClientNameConversions(true);
model.put("classnameFor", classnameFor);
model.put("listsAsArraysClassnameFor", new ListsAsArraysClientClassnameForMethod(this.packageToNamespaceConversions));
model.put("simpleNameFor", new SimpleNameWithParamsMethod(classnameFor));
model.put("csFileName", getSourceFileName());
model.put("accessorOverridesAnother", new AccessorOverridesAnotherMethod());
debug("Generating the C# client classes...");
URL apiTemplate = isSingleFilePerClass() ? getTemplateURL("api-multiple-files.fmt") : getTemplateURL("api.fmt");
processTemplate(apiTemplate, model);
}
else {
info("Skipping C# code generation because everything appears up-to-date.");
}
}
@Override
protected void doCompile() throws EnunciateException, IOException {
File compileDir = getCompileDir();
Enunciate enunciate = getEnunciate();
String compileExecutable = getCompileExecutable();
if (getCompileExecutable() != null) {
if (!enunciate.isUpToDateWithSources(compileDir)) {
compileDir.mkdirs();
String compileCommand = getCompileCommand();
if (compileCommand == null) {
throw new IllegalStateException("Somehow the \"compile\" step was invoked on the C# module without a valid compile command.");
}
compileCommand = compileCommand.replace(' ', '\0'); //replace all spaces with the null character, so the command can be tokenized later.
File dll = new File(compileDir, getDLLFileName());
File docXml = new File(compileDir, getDocXmlFileName());
File sourceFile = new File(getGenerateDir(), getSourceFileName());
compileCommand = String.format(compileCommand, compileExecutable,
dll.getAbsolutePath(),
docXml.getAbsolutePath(),
sourceFile.getAbsolutePath());
StringTokenizer tokenizer = new StringTokenizer(compileCommand, "\0"); //tokenize on the null character to preserve the spaces in the command.
List<String> command = new ArrayList<String>();
while (tokenizer.hasMoreElements()) {
command.add((String) tokenizer.nextElement());
}
Process process = new ProcessBuilder(command).redirectErrorStream(true).directory(compileDir).start();
BufferedReader procReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = procReader.readLine();
while (line != null) {
info(line);
line = procReader.readLine();
}
int procCode;
try {
procCode = process.waitFor();
}
catch (InterruptedException e1) {
throw new EnunciateException("Unexpected inturruption of the C# compile process.");
}
if (procCode != 0) {
throw new EnunciateException("C# compile failed.");
}
enunciate.addArtifact(new FileArtifact(getName(), "csharp.assembly", dll));
if (docXml.exists()) {
enunciate.addArtifact(new FileArtifact(getName(), "csharp.docs.xml", docXml));
}
}
else {
info("Skipping C# compile because everything appears up-to-date.");
}
}
else {
debug("Skipping C# compile because a compile executale was neither found nor provided. The C# bundle will only include the sources.");
}
}
@Override
protected void doBuild() throws EnunciateException, IOException {
Enunciate enunciate = getEnunciate();
File buildDir = getBuildDir();
if (!enunciate.isUpToDateWithSources(buildDir)) {
File compileDir = getCompileDir();
compileDir.mkdirs(); //might not exist if we couldn't actually compile.
//we want to zip up the source file, too, so we'll just copy it to the compile dir.
enunciate.copyDir(getGenerateDir(), compileDir);
buildDir.mkdirs();
File bundle = new File(buildDir, getBundleFileName());
enunciate.zip(bundle, compileDir);
ClientLibraryArtifact artifactBundle = new ClientLibraryArtifact(getName(), "csharp.client.library", ".NET Client Library");
artifactBundle.setPlatform(".NET 2.0");
StringBuilder builder = new StringBuilder("C# source code");
boolean docsExist = new File(compileDir, getDocXmlFileName()).exists();
boolean dllExists = new File(compileDir, getDLLFileName()).exists();
if (docsExist && dllExists) {
builder.append(", the assembly, and the XML docs");
}
else if (dllExists) {
builder.append("and the assembly");
}
//read in the description from file:
String description = readResource("library_description.fmt", builder.toString());
artifactBundle.setDescription(description);
NamedFileArtifact binariesJar = new NamedFileArtifact(getName(), "dotnet.client.bundle", bundle);
binariesJar.setArtifactType(ArtifactType.binaries);
binariesJar.setDescription(String.format("The %s for the .NET client library.", builder.toString()));
binariesJar.setPublic(false);
artifactBundle.addArtifact(binariesJar);
enunciate.addArtifact(artifactBundle);
}
}
/**
* Reads a resource into string form.
*
* @param resource The resource to read.
* @param contains The description of what the bundle contains.
* @return The string form of the resource.
*/
protected String readResource(String resource, String contains) throws IOException, EnunciateException {
HashMap<String, Object> model = new HashMap<String, Object>();
model.put("sample_service_method", getModelInternal().findExampleWebMethod());
model.put("sample_resource", getModelInternal().findExampleResourceMethod());
model.put("bundle_contains", contains);
URL res = CSharpDeploymentModule.class.getResource(resource);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
PrintStream out = new PrintStream(bytes);
try {
processTemplate(res, model, out);
out.flush();
bytes.flush();
return bytes.toString("utf-8");
}
catch (TemplateException e) {
throw new EnunciateException(e);
}
}
/**
* The name of the bundle file.
*
* @return The name of the bundle file.
*/
protected String getBundleFileName() {
if (this.bundleFileName != null) {
return this.bundleFileName;
}
String label = getLabel();
if (label == null) {
label = getEnunciate().getConfig().getLabel();
}
return label + "-dotnet.zip";
}
/**
* The name of the bundle file.
*
* @param bundleFileName The name of the bundle file.
*/
public void setBundleFileName(String bundleFileName) {
this.bundleFileName = bundleFileName;
}
/**
* The name of the generated C# dll.
*
* @return The name of the generated C# file.
*/
protected String getDLLFileName() {
if (this.DLLFileName != null) {
return this.DLLFileName;
}
String label = getLabel();
if (label == null) {
label = getEnunciate().getConfig().getLabel();
}
return label + ".dll";
}
/**
* The name of the generated C# dll.
*
* @param DLLFileName The name of the generated C# dll.
*/
public void setDLLFileName(String DLLFileName) {
this.DLLFileName = DLLFileName;
}
/**
* The name of the generated C# xml documentation.
*
* @return The name of the generated C# xml documentation.
*/
protected String getDocXmlFileName() {
if (this.docXmlFileName != null) {
return this.docXmlFileName;
}
String label = getLabel();
if (label == null) {
label = getEnunciate().getConfig().getLabel();
}
return label + "-docs.xml";
}
/**
* The name of the generated C# xml documentation.
*
* @param docXmlFileName The name of the generated C# xml documentation.
*/
public void setDocXmlFileName(String docXmlFileName) {
this.docXmlFileName = docXmlFileName;
}
/**
* The name of the generated C# source file.
*
* @return The name of the generated C# source file.
*/
protected String getSourceFileName() {
if (this.sourceFileName != null) {
return this.sourceFileName;
}
String label = getLabel();
if (label == null) {
label = getEnunciate().getConfig().getLabel();
}
return label + ".cs";
}
/**
* The name of the generated C# source file.
*
* @param sourceFileName The name of the generated C# source file.
*/
public void setSourceFileName(String sourceFileName) {
this.sourceFileName = sourceFileName;
}
@Override
protected ObjectWrapper getObjectWrapper() {
return new DefaultObjectWrapper() {
@Override
public TemplateModel wrap(Object obj) throws TemplateModelException {
if (obj instanceof JavaDoc) {
return new FreemarkerJavaDoc((JavaDoc) obj);
}
return super.wrap(obj);
}
};
}
/**
* Get a template URL for the template of the given name.
*
* @param template The specified template.
* @return The URL to the specified template.
*/
protected URL getTemplateURL(String template) {
return CSharpDeploymentModule.class.getResource(template);
}
/**
* Whether the generate dir is up-to-date.
*
* @param genDir The generate dir.
* @return Whether the generate dir is up-to-date.
*/
protected boolean isUpToDate(File genDir) {
return enunciate.isUpToDateWithSources(genDir);
}
/**
* Whether to require the C# client code.
*
* @return Whether to require the C# client code.
*/
public boolean isRequire() {
return require;
}
/**
* Whether to require the C# client code.
*
* @param require Whether to require the C# client code.
*/
public void setRequire(boolean require) {
this.require = require;
}
/**
* The label for the C# API.
*
* @return The label for the C# API.
*/
public String getLabel() {
return label;
}
/**
* The label for the C# API.
*
* @param label The label for the C# API.
*/
public void setLabel(String label) {
this.label = label;
}
/**
* The path to the compile executable.
*
* @return The path to the compile executable.
*/
public String getCompileExecutable() {
return compileExecutable;
}
/**
* The path to the compile executable.
*
* @param compileExecutable The path to the compile executable.
*/
public void setCompileExecutable(String compileExecutable) {
this.compileExecutable = compileExecutable;
}
/**
* The C# compile command.
*
* @return The C# compile command.
*/
public String getCompileCommand() {
return compileCommand;
}
/**
* The C# compile command.
*
* @param compileCommand The C# compile command.
*/
public void setCompileCommand(String compileCommand) {
this.compileCommand = compileCommand;
}
/**
* The package-to-namespace conversions.
*
* @return The package-to-namespace conversions.
*/
public Map<String, String> getPackageToNamespaceConversions() {
return packageToNamespaceConversions;
}
/**
* Whether to disable the compile step.
*
* @return Whether to disable the compile step.
*/
public boolean isDisableCompile() {
return disableCompile;
}
/**
* Whether to disable the compile step.
*
* @param disableCompile Whether to disable the compile step.
*/
public void setDisableCompile(boolean disableCompile) {
this.disableCompile = disableCompile;
}
/**
* Whether there should be a single file per class. Default: false (all classes are contained in a single file).
*
* @return Whether there should be a single file per class.
*/
public boolean isSingleFilePerClass() {
return singleFilePerClass;
}
/**
* Whether there should be a single file per class.
*
* @param singleFilePerClass Whether there should be a single file per class.
*/
public void setSingleFilePerClass(boolean singleFilePerClass) {
this.singleFilePerClass = singleFilePerClass;
}
/**
* The set of facets to include.
*
* @return The set of facets to include.
*/
public Set<String> getFacetIncludes() {
return facetIncludes;
}
/**
* Add a facet include.
*
* @param name The name.
*/
public void addFacetInclude(String name) {
if (name != null) {
this.facetIncludes.add(name);
}
}
/**
* The set of facets to exclude.
*
* @return The set of facets to exclude.
*/
public Set<String> getFacetExcludes() {
return facetExcludes;
}
/**
* Add a facet exclude.
*
* @param name The name.
* @param value The value.
*/
public void addFacetExclude(String name, String value) {
if (name != null) {
this.facetExcludes.add(name);
}
}
/**
* Add a client package conversion.
*
* @param conversion The conversion to add.
*/
public void addClientPackageConversion(PackageNamespaceConversion conversion) {
String from = conversion.getFrom();
String to = conversion.getTo();
if (from == null) {
throw new IllegalArgumentException("A 'from' attribute must be specified on a package-conversion element.");
}
if (to == null) {
throw new IllegalArgumentException("A 'to' attribute must be specified on a package-conversion element.");
}
this.packageToNamespaceConversions.put(from, to);
}
@Override
public RuleSet getConfigurationRules() {
return new CSharpRuleSet();
}
@Override
public Validator getValidator() {
return new CSharpValidator();
}
// Inherited.
@Override
public boolean isDisabled() {
if (super.isDisabled()) {
return true;
}
else if (getModelInternal() != null && getModelInternal().getNamespacesToWSDLs().isEmpty() && getModelInternal().getNamespacesToSchemas().isEmpty()) {
debug("C# module is disabled because there are no endpoint interfaces, nor any XML types.");
return true;
}
return false;
}
}
| [
"[email protected]"
] | |
e5aedc0c6926fca1df6145dffd1fef49cda337d2 | 3f191c357d052294c96a9d0efbd4f2fae9f1512b | /loginapp/src/main/java/com/saq/loginapp/exception/SaqExceptionHandler.java | 90af150f54ea9572493c3207f312c1e33b5b176a | [] | no_license | saquibislam/loginapp | 789e5874cb35649c31a9a7a20730a5dea211a411 | 507b74210738a4a69ab0169310ae6c12371320ca | refs/heads/master | 2020-03-25T12:14:42.697415 | 2018-08-06T18:06:33 | 2018-08-06T18:06:33 | 143,737,204 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 716 | java | package com.saq.loginapp.exception;
import javax.servlet.http.HttpServletRequest;
import org.apache.log4j.Logger;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
@ControllerAdvice
public class SaqExceptionHandler {
Logger logger = Logger.getLogger(SaqExceptionHandler.class);
@ExceptionHandler(value=Exception.class)
public String handleException(HttpServletRequest request, Exception e, Model model) {
logger.error("Request " + request.getRequestURL() + " threw an exception: " + e);
model.addAttribute("exception", e.getMessage());
return "error/error";
}
}
| [
"saquib.islam@Saquib-PC"
] | saquib.islam@Saquib-PC |
4ba7cc91561b248a85688f267dfad37794b89c87 | 60b77d57f3e163f3f89b5587225438812b00c25e | /decompile/output/app/src/main/java/android/support/v4/internal/view/SupportMenu.java | 7f767f576f18a9e44d519ef6d9f6c2aeef9c51fa | [
"MIT"
] | permissive | mio4kon/AspectMahou | 5e2afd654a69ecfbb2e70430ee4f15d5f5a30917 | 4b33acb83801c88d918a854dd6831e2cce35f868 | refs/heads/master | 2020-06-26T20:27:52.677150 | 2016-11-23T05:18:24 | 2016-11-23T05:18:24 | 74,539,729 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 371 | java | package android.support.v4.internal.view;
import android.view.Menu;
public abstract interface SupportMenu
extends Menu
{
public static final int CATEGORY_MASK = -65536;
public static final int CATEGORY_SHIFT = 16;
public static final int FLAG_KEEP_OPEN_ON_SUBMENU_OPENED = 4;
public static final int USER_MASK = 65535;
public static final int USER_SHIFT;
}
| [
"[email protected]"
] | |
ffb175c10d09461e626eb24815ea2d4fd85bad8a | fa91450deb625cda070e82d5c31770be5ca1dec6 | /Diff-Raw-Data/2/2_5e152b0ea57e3f216903635708b912cfb4c1f759/ExprConstraintGenerator/2_5e152b0ea57e3f216903635708b912cfb4c1f759_ExprConstraintGenerator_s.java | 718c56e60d5c2d662cc61bdb274b615598ffc8eb | [] | no_license | zhongxingyu/Seer | 48e7e5197624d7afa94d23f849f8ea2075bcaec0 | c11a3109fdfca9be337e509ecb2c085b60076213 | refs/heads/master | 2023-07-06T12:48:55.516692 | 2023-06-22T07:55:56 | 2023-06-22T07:55:56 | 259,613,157 | 6 | 2 | null | 2023-06-22T07:55:57 | 2020-04-28T11:07:49 | null | UTF-8 | Java | false | false | 11,076 | java | package cd.semantic.ti;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import cd.ir.ExprVisitorWithoutArg;
import cd.ir.ast.BinaryOp;
import cd.ir.ast.BooleanConst;
import cd.ir.ast.BuiltInRead;
import cd.ir.ast.BuiltInReadFloat;
import cd.ir.ast.Cast;
import cd.ir.ast.Expr;
import cd.ir.ast.Field;
import cd.ir.ast.FloatConst;
import cd.ir.ast.Index;
import cd.ir.ast.IntConst;
import cd.ir.ast.MethodCallExpr;
import cd.ir.ast.NewArray;
import cd.ir.ast.NewObject;
import cd.ir.ast.NullConst;
import cd.ir.ast.ThisRef;
import cd.ir.ast.UnaryOp;
import cd.ir.ast.Var;
import cd.ir.ast.BinaryOp.BOp;
import cd.ir.ast.UnaryOp.UOp;
import cd.ir.symbols.ArrayTypeSymbol;
import cd.ir.symbols.ClassSymbol;
import cd.ir.symbols.MethodSymbol;
import cd.ir.symbols.PrimitiveTypeSymbol;
import cd.ir.symbols.TypeSymbol;
import cd.ir.symbols.VariableSymbol;
import cd.semantic.TypeSymbolTable;
import cd.semantic.ti.constraintSolving.ConstantTypeSet;
import cd.semantic.ti.constraintSolving.ConstantTypeSetFactory;
import cd.semantic.ti.constraintSolving.ConstraintSystem;
import cd.semantic.ti.constraintSolving.TypeSet;
import cd.semantic.ti.constraintSolving.TypeVariable;
import cd.semantic.ti.constraintSolving.constraints.ConstraintCondition;
import com.google.common.base.Optional;
import com.google.common.collect.ImmutableSet;
/**
* Recursively generates the type set for a expressions and potentially adds
* type constraints to the constraint system.
*
* The type sets associated with fields, parameters, local variables and return
* values are looked up in the context.
*/
public class ExprConstraintGenerator extends ExprVisitorWithoutArg<TypeSet> {
private final MethodSymbol method;
private final ConstraintGeneratorContext context;
public ExprConstraintGenerator(MethodSymbol method,
ConstraintGeneratorContext context) {
this.method = method;
this.context = context;
}
/**
* Convenience shortcut for {@code context.getConstantTypeSetFactory()}.
*/
private ConstantTypeSetFactory getTypeSetFactory() {
return context.getConstantTypeSetFactory();
}
/**
* Convenience shortcut for {@code context.getConstraintSystem()}.
*/
private ConstraintSystem getSystem() {
return context.getConstraintSystem();
}
/**
* Convenience shortcut for {@link context.getTypeSymbolTable()}.
*/
private TypeSymbolTable getTypeSymbols() {
return context.getTypeSymbolTable();
}
@Override
public TypeSet var(Var ast) {
return context.getVariableTypeSet(ast.getSymbol());
}
@Override
public TypeSet intConst(IntConst ast) {
return getTypeSetFactory().makeInt();
}
@Override
public TypeSet floatConst(FloatConst ast) {
return getTypeSetFactory().makeFloat();
}
@Override
public TypeSet booleanConst(BooleanConst ast) {
return getTypeSetFactory().makeBoolean();
}
@Override
public TypeSet nullConst(NullConst ast) {
return getTypeSetFactory().makeNull();
}
@Override
public TypeSet newObject(NewObject ast) {
return getTypeSetFactory().make(ast.typeName);
}
@Override
public TypeSet newArray(NewArray ast) {
return getTypeSetFactory().make(ast.typeName);
}
@Override
public TypeSet thisRef(ThisRef ast) {
return getTypeSetFactory().make(method.getOwner());
}
@Override
public TypeSet cast(Cast ast) {
TypeSet exprTypeSet = visit(ast.arg());
// only reference types can be cast
ConstantTypeSet allRefTyes = getTypeSetFactory().makeReferenceTypeSet();
getSystem().addUpperBound(exprTypeSet, allRefTyes);
TypeSymbol castResultType = getTypeSymbols().getType(ast.typeName);
return getTypeSetFactory().makeDeclarableSubtypes(castResultType);
}
@Override
public TypeSet field(Field ast) {
String fieldName = ast.fieldName;
TypeSet receiverTypeSet = visit(ast.arg());
Collection<ClassSymbol> declaringClassSymbols = context
.getClassesDeclaringField(fieldName);
Set<ClassSymbol> possibleClassSymbols = new HashSet<>();
TypeVariable resultType = getSystem().addTypeVariable();
for (ClassSymbol classSym : declaringClassSymbols) {
possibleClassSymbols.addAll(getTypeSymbols()
.getClassSymbolSubtypes(classSym));
VariableSymbol fieldSymbol = classSym.getField(fieldName);
TypeSet fieldTypeSet = context.getVariableTypeSet(fieldSymbol);
ConstraintCondition condition = new ConstraintCondition(classSym,
receiverTypeSet);
getSystem().addEquality(resultType, fieldTypeSet, condition);
}
// The receiver *must* be a subtype of any class that has a
// field with the right name
ConstantTypeSet possibleClassTypeSet = new ConstantTypeSet(
possibleClassSymbols);
getSystem().addUpperBound(receiverTypeSet, possibleClassTypeSet);
return resultType;
}
@Override
public TypeSet index(Index index) {
TypeSet arrayExprTypeSet = visit(index.left());
TypeSet indexTypeSet = visit(index.right());
TypeVariable resultVar = getSystem().addTypeVariable();
getSystem().addEquality(indexTypeSet, getTypeSetFactory().makeInt());
ConstantTypeSet arrayTypesSet = getTypeSetFactory().makeArrayTypeSet();
getSystem().addUpperBound(arrayExprTypeSet, arrayTypesSet);
for (ArrayTypeSymbol arrayType : getTypeSymbols().getArrayTypeSymbols()) {
ConstraintCondition condition = new ConstraintCondition(arrayType,
arrayExprTypeSet);
// Also allow objects in the array whose type is a subtype of the
// declared array element type
ConstantTypeSet arrayElementTypeSet = getTypeSetFactory()
.makeDeclarableSubtypes(arrayType.elementType);
getSystem().addEquality(resultVar, arrayElementTypeSet, condition);
}
return resultVar;
}
@Override
public TypeSet builtInRead(BuiltInRead ast) {
return getTypeSetFactory().makeInt();
}
@Override
public TypeSet builtInReadFloat(BuiltInReadFloat ast) {
return getTypeSetFactory().makeFloat();
}
@Override
public TypeSet binaryOp(BinaryOp binaryOp) {
BOp op = binaryOp.operator;
TypeSet leftTypeSet = visit(binaryOp.left());
TypeSet rightTypeSet = visit(binaryOp.right());
ConstantTypeSet booleanTypeSet, numTypeSet;
numTypeSet = getTypeSetFactory().makeNumericalTypeSet();
booleanTypeSet = getTypeSetFactory().makeBoolean();
switch (op) {
case B_TIMES:
case B_DIV:
case B_MOD:
case B_PLUS:
case B_MINUS:
getSystem().addUpperBound(leftTypeSet, numTypeSet);
getSystem().addEquality(leftTypeSet, rightTypeSet);
return leftTypeSet;
case B_AND:
case B_OR:
getSystem().addEquality(leftTypeSet, rightTypeSet);
getSystem().addEquality(leftTypeSet, booleanTypeSet);
return booleanTypeSet;
case B_EQUAL:
case B_NOT_EQUAL:
// The following only prevents primitive types from being
// compared with reference types and different primitive
// types. However, it is possible to compare references of
// any type, even if neither is a subtype of the other.
for (PrimitiveTypeSymbol primitiveType : getTypeSymbols()
.getPrimitiveTypeSymbols()) {
ConstraintCondition leftCondition = new ConstraintCondition(
primitiveType, leftTypeSet);
ConstraintCondition rightCondition = new ConstraintCondition(
primitiveType, rightTypeSet);
ConstantTypeSet primitiveTypeSet = getTypeSetFactory().make(
primitiveType);
getSystem().addEquality(rightTypeSet, primitiveTypeSet,
leftCondition);
getSystem().addEquality(leftTypeSet, primitiveTypeSet,
rightCondition);
}
return booleanTypeSet;
case B_LESS_THAN:
case B_LESS_OR_EQUAL:
case B_GREATER_THAN:
case B_GREATER_OR_EQUAL:
getSystem().addUpperBound(leftTypeSet, numTypeSet);
getSystem().addEquality(leftTypeSet, rightTypeSet);
return booleanTypeSet;
default:
throw new IllegalStateException("no such binary operator");
}
}
public void createMethodCallConstraints(String methodName, Expr receiver,
List<Expr> arguments, Optional<TypeVariable> methodCallResultTypeVar) {
// The canonical (non-overriding) method symbols with that name and
// number of parameters
Collection<MethodSymbol> methodSymbols = context.getMatchingMethods(
methodName, arguments.size());
TypeSet receiverTypeSet = visit(receiver);
Set<ClassSymbol> possibleReceiverTypes = new HashSet<>();
for (MethodSymbol msym : methodSymbols) {
ImmutableSet<ClassSymbol> msymClassSubtypes = getTypeSymbols()
.getClassSymbolSubtypes(msym.getOwner());
possibleReceiverTypes.addAll(msymClassSubtypes);
for (ClassSymbol msymClassSubtype : msymClassSubtypes) {
// Generate a conditional constraint for each of the subtypes of
// the method's owner. The receiver type set may only contain a
// subtype of the method's owner that does NOT override the
// method. Thus, if we only created a constraint whose condition
// only checks if the method's owner is in the receiver type
// set, the condition would never be satisfied.
ConstraintCondition condition = new ConstraintCondition(
msymClassSubtype, receiverTypeSet);
for (int argNum = 0; argNum < arguments.size(); argNum++) {
Expr argument = arguments.get(argNum);
TypeSet argTypeSet = visit(argument);
VariableSymbol paramSym = msym.getParameter(argNum);
TypeSet parameterTypeSet = context
.getVariableTypeSet(paramSym);
getSystem().addInequality(argTypeSet, parameterTypeSet,
condition);
}
if (methodCallResultTypeVar.isPresent()) {
TypeSet resultTypeSet = context.getReturnTypeSet(msym);
TypeSet lhsTypeSet = methodCallResultTypeVar.get();
getSystem().addInequality(resultTypeSet, lhsTypeSet,
condition);
}
}
}
// the receiver _must_ be a subtype of any class that has a
// method with the right name and number of arguments
ConstantTypeSet possibleReceiverTypeSet = new ConstantTypeSet(
possibleReceiverTypes);
getSystem().addUpperBound(receiverTypeSet, possibleReceiverTypeSet);
}
@Override
public TypeSet methodCall(MethodCallExpr call) {
TypeVariable methodCallResultTypeVar = getSystem().addTypeVariable();
createMethodCallConstraints(call.methodName, call.receiver(),
call.argumentsWithoutReceiver(),
Optional.of(methodCallResultTypeVar));
return methodCallResultTypeVar;
}
@Override
public TypeSet unaryOp(UnaryOp unaryOp) {
UOp op = unaryOp.operator;
TypeSet subExprTypeSet = visit(unaryOp.arg());
ConstantTypeSet numTypes = getTypeSetFactory().makeNumericalTypeSet();
ConstantTypeSet booleanType = getTypeSetFactory().makeBoolean();
switch (op) {
case U_BOOL_NOT:
getSystem().addEquality(subExprTypeSet, booleanType);
return booleanType;
case U_MINUS:
case U_PLUS:
getSystem().addUpperBound(subExprTypeSet, numTypes);
break;
}
return subExprTypeSet;
}
}
| [
"[email protected]"
] | |
a71f2bd8d74c25f608178b30f34ff5bb74e6a615 | b0cdac3ff6aa9df3764ed020b3eb7f916d4e8b70 | /CSMModules/src/Modules/JFrameAssignLog.java | bf2f9c1990b50f565cd504bc3928e98a3a246ab6 | [] | no_license | superwangvip/csm | 140e78114f3195b79635bb3bfffb4a267bc452ea | 7e03333602a749174a0aa4e586e34bd2c3e1554f | refs/heads/master | 2021-01-16T20:55:39.822622 | 2015-03-09T03:00:10 | 2015-03-09T03:00:10 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 14,340 | java | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/*
* JFrameAssignLog.java
*
* Created on 2011-9-9, 20:23:31
*/
package Modules;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
/**
*
* @author Administrator
*/
public class JFrameAssignLog extends javax.swing.JFrame {
/** Creates new form JFrameAssignLog */
public JFrameAssignLog() {
initComponents();
int iThisWidth = 740;
int iThisHight = 584;
Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
int x = (screen.width - iThisWidth) / 2;
int y = (screen.height - iThisHight) / 2;
this.setBounds(x, y, iThisWidth, iThisHight);
getDateRange();//初始化查询日期范围
//注册键盘监听器,监听键盘动作,把系统无操作等待计时器置0;对非管理员屏蔽批量数据复制
MainMenu.registerKeyListener(jTable1);
//注册鼠标动作监听器,监听鼠标动作,把系统无操作等待计时器置0
MainMenu.registerMouseListener(this);
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jScrollPane1 = new javax.swing.JScrollPane();
jTable1 = new javax.swing.JTable();
jLabel3 = new javax.swing.JLabel();
jTextFieldFundAccount = new javax.swing.JTextField();
jButton3 = new javax.swing.JButton();
jButton1 = new javax.swing.JButton();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jTextFieldEndDate = new javax.swing.JTextField();
jLabel4 = new javax.swing.JLabel();
jTextFieldStrtDate = new javax.swing.JTextField();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setTitle("查询服务安排日志");
jPanel1.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.LOWERED));
jTable1.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null}
},
new String [] {
"Title 1", "Title 2", "Title 3", "Title 4"
}
));
jTable1.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_OFF);
jTable1.setColumnSelectionAllowed(true);
jScrollPane1.setViewportView(jTable1);
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 696, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(18, 18, 18)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 374, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(18, Short.MAX_VALUE))
);
jLabel3.setFont(new java.awt.Font("宋体", 0, 18));
jLabel3.setForeground(new java.awt.Color(0, 0, 153));
jLabel3.setText("资金帐号(不输则全查)");
jTextFieldFundAccount.setFont(new java.awt.Font("宋体", 0, 18));
jButton3.setText("查询");
jButton3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton3ActionPerformed(evt);
}
});
jButton1.setText("取消");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jLabel1.setFont(new java.awt.Font("宋体", 0, 14));
jLabel1.setForeground(new java.awt.Color(51, 0, 255));
jLabel1.setText("服务安排(客户分配)日志");
jLabel2.setText("终止日期(YYYYMMDD)");
jTextFieldEndDate.setText("jTextField1");
jLabel4.setText("起始日期(YYYYMMDD)");
jTextFieldStrtDate.setText("jTextField1");
jTextFieldStrtDate.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jTextFieldStrtDateActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(345, 345, 345)
.addComponent(jLabel1))
.addGroup(layout.createSequentialGroup()
.addGap(33, 33, 33)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel4)
.addComponent(jLabel2))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jTextFieldStrtDate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jTextFieldEndDate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel3)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jTextFieldFundAccount, javax.swing.GroupLayout.PREFERRED_SIZE, 124, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jButton3)
.addGap(10, 10, 10)
.addComponent(jButton1))
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(18, 18, 18)
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(20, 20, 20)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel4)
.addGap(21, 21, 21)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(jTextFieldEndDate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addComponent(jTextFieldStrtDate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createSequentialGroup()
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jTextFieldFundAccount, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel3)
.addComponent(jButton3)
.addComponent(jButton1))))
.addGap(53, 53, 53))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
String sql = "";
String start_date = jTextFieldStrtDate.getText().toString().trim();
String end_date = jTextFieldEndDate.getText().toString().trim();
long base = 0L;
long fund_account = 0L;
String FundAccount = jTextFieldFundAccount.getText().trim();
String WholeAccount = null;
if (!FundAccount.equals("")) {
if (Main.branchID >= 10) {
base = Main.branchID * 10000000000L;
try {
fund_account = Long.valueOf(FundAccount).longValue();
if (fund_account < 1000000000L) {
fund_account = base + fund_account;
WholeAccount = Long.valueOf(fund_account).toString();
} else {
WholeAccount = FundAccount;
}
} catch (NumberFormatException e) {
JOptionPane.showMessageDialog(this, "输入数据格式错!");
return;
}
} else {
base = Main.branchID * 10000000000L;
try {
fund_account = Long.valueOf(FundAccount).longValue();
if (fund_account < 10000000000L) {
fund_account = base + fund_account;
WholeAccount = "0" + Long.valueOf(fund_account).toString();
} else {
WholeAccount = FundAccount;
}
} catch (NumberFormatException e) {
JOptionPane.showMessageDialog(this, "输入数据格式错!");
return;
}
}
jTextFieldFundAccount.setText(WholeAccount);
sql = "execute get_assign_log '" + start_date + "','" + end_date + "'," + fund_account;
} else {
sql = "execute get_assign_log '" + start_date + "','" + end_date + "'";
}
//System.out.println(sql);
JDBTableModel dm = new JDBTableModel(jTable1);
Vector columnType = new Vector();
boolean addSerial = true;
dm.fetchDataToTable(Main.conn, sql, columnType, addSerial);
}//GEN-LAST:event_jButton3ActionPerformed
private void getDateRange() {
String start_date = "19000101";
String end_date = "2020128";
String sql = "select convert(char(8),min(assign_time),112), convert(char(8),max(assign_time),112) from assign_log";
try {
PreparedStatement SqlStatement = Main.conn.prepareStatement(sql);
Boolean HasResult = SqlStatement.execute();
while (!HasResult) {
HasResult = SqlStatement.getMoreResults();
}
if (HasResult) {
ResultSet SqlResult = SqlStatement.getResultSet();
while (SqlResult.next()) {
start_date = SqlResult.getString(1);
end_date = SqlResult.getString(2);
}
}
} catch (SQLException ex) {
Logger.getLogger(JFrameAssetIncrement.class.getName()).log(Level.SEVERE, null, ex);
}
jTextFieldStrtDate.setText(start_date);
jTextFieldEndDate.setText(end_date);
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
// TODO add your handling code here:
this.dispose();
}//GEN-LAST:event_jButton1ActionPerformed
private void jTextFieldStrtDateActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextFieldStrtDateActionPerformed
}//GEN-LAST:event_jTextFieldStrtDateActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new JFrameAssignLog().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton3;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JPanel jPanel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable jTable1;
private javax.swing.JTextField jTextFieldEndDate;
private javax.swing.JTextField jTextFieldFundAccount;
private javax.swing.JTextField jTextFieldStrtDate;
// End of variables declaration//GEN-END:variables
}
| [
"[email protected]"
] | |
de7f01801f04680c06af4ec3b47ee0457f1059cf | b6fb9d6d02ee7124b5a5109ba3e207a71528efb5 | /lab11/Array.java | e5fe24724e1ee2b9b394bd9174e4c2b8de6675ff | [] | no_license | suzychen/CSE2 | b7de02ec9b706d11e7ac4cbe3adfcbd4ea477a1a | d06f73202e2aba475ada7b51c37e715a3622fbe8 | refs/heads/master | 2021-01-25T05:16:37.840613 | 2014-12-06T01:35:27 | 2014-12-06T01:35:27 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,025 | java | ////
import java.util.Scanner;
public class Array{
public static void main(String[] args){
final int NUMBER_OF_ELEMENTS=10;
int[] numbers=new int[NUMBER_OF_ELEMENTS];
Scanner scan=new Scanner(System.in);
System.out.print("Enter 10 ints- ");
int sum=0;
for (int i=0;i<NUMBER_OF_ELEMENTS;i++){
numbers[i]=scan.nextInt();
sum+=numbers[i];
}
int min=numbers[0];
for (int k=1;k<numbers.length;k++){
if (numbers[k]<min){
min=numbers[k];
}
}
System.out.println("The lowest entry is "+min);
int max=numbers[0];
for (int j=1;j<numbers.length;j++){
if(numbers[j]>max){
max=numbers[j];
}
}
System.out.println("The highest entry is "+max);
System.out.println("The sum is "+sum);
for (int g=0;g<numbers.length;g++){
System.out.println(numbers[g]+" "+numbers[9-g]);
}
}
} | [
"[email protected]"
] | |
664c127f4c6dd8e34d37d3bd042f156ccfe8373a | 603769fe111437905b894654e9b810e5f5c7e3c2 | /thirdFile/src/PracticeWithIOPackage/Example2/ReceiveDataThread.java | 4ffaff01682bce7af0fb39972e6294d096b41ae1 | [] | no_license | Woosang77/JAVA | ffb809db3ffae4f8b1f3ed1e3a6894fbaa5d6182 | 36ee8704760bd1037501ac0072f35c1c6eef3fe5 | refs/heads/main | 2023-03-10T03:56:12.589361 | 2021-03-05T15:07:08 | 2021-03-05T15:07:08 | 316,170,855 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 681 | java | package PracticeWithIOPackage.Example2;
import java.io.BufferedReader;
import java.io.PrintWriter;
import java.net.Socket;
public class ReceiveDataThread implements Runnable{
Socket client;
BufferedReader ois;
String receiveData;
public ReceiveDataThread(Socket s, BufferedReader ois) {
client = s;
this.ois = ois;
}
@Override
public void run() {
try {
while ((receiveData = ois.readLine()) != null) {
System.out.println(receiveData);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
ois.close();
client.close();
} catch (Exception e2) {
e2.printStackTrace();
}
}
}
}
| [
"[email protected]"
] | |
3f1ff9deb0e725145d90c39daa7d4d2780393992 | f2740cb6c3e47d362ba7b8275a23f5b1e4e21c01 | /spring-stream/rabbitmq-barista-service/src/main/java/com/spring/springbucks/barista/model/CoffeeOrder.java | c07acca84de96dc97b8f38f2a954c9e9bd46819a | [] | no_license | peterlxb/coding-demo | dd94a8a5471309e075c729e5ab85d970c8d8b705 | c5d52d03dcefe4a2663a5055621afcd889e2f4d9 | refs/heads/master | 2023-03-05T18:15:07.499938 | 2021-02-04T14:13:26 | 2021-02-04T14:13:26 | 257,637,242 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 992 | java | package com.spring.springbucks.barista.model;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.hibernate.annotations.CreationTimestamp;
import org.hibernate.annotations.UpdateTimestamp;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import java.util.Date;
@Entity
@Table(name = "T_ORDER")
@Data
@NoArgsConstructor
@AllArgsConstructor
public class CoffeeOrder {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String customer;
private String waiter;
private String barista;
@Enumerated
@Column(nullable = false)
private OrderState state;
@Column(updatable = false)
@CreationTimestamp
private Date createTime;
@UpdateTimestamp
private Date updateTime;
}
| [
"[email protected]"
] | |
bf3f487a94b56c2f20d0d4af10fbe9e8a501b0c7 | 421f0a75a6b62c5af62f89595be61f406328113b | /generated_tests/model_seeding/27_gangup-module.MessageDeliveryException-1.0-1/module/MessageDeliveryException_ESTest.java | 9a223fc6a1fb492f9838ce90de45d805d7bab894 | [] | no_license | tigerqiu712/evosuite-model-seeding-empirical-evaluation | c78c4b775e5c074aaa5e6ca56bc394ec03c2c7c6 | 11a920b8213d9855082d3946233731c843baf7bc | refs/heads/master | 2020-12-23T21:04:12.152289 | 2019-10-30T08:02:29 | 2019-10-30T08:02:29 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,609 | java | /*
* This file was automatically generated by EvoSuite
* Fri Oct 25 10:59:26 GMT 2019
*/
package module;
import org.junit.Test;
import static org.junit.Assert.*;
import java.sql.SQLDataException;
import module.Message;
import module.MessageDeliveryException;
import module.Module;
import org.evosuite.runtime.EvoRunner;
import org.evosuite.runtime.EvoRunnerParameters;
import org.junit.runner.RunWith;
@RunWith(EvoRunner.class) @EvoRunnerParameters(mockJVMNonDeterminism = true, useVFS = true, useVNET = true, resetStaticState = true, separateClassLoader = true, useJEE = true)
public class MessageDeliveryException_ESTest extends MessageDeliveryException_ESTest_scaffolding {
@Test(timeout = 4000)
public void test0() throws Throwable {
Message message0 = new Message("|", "|", "|");
MessageDeliveryException messageDeliveryException0 = new MessageDeliveryException((Module) null, message0, "");
}
@Test(timeout = 4000)
public void test1() throws Throwable {
MessageDeliveryException messageDeliveryException0 = new MessageDeliveryException((Throwable) null);
}
@Test(timeout = 4000)
public void test2() throws Throwable {
SQLDataException sQLDataException0 = new SQLDataException("3u");
MessageDeliveryException messageDeliveryException0 = new MessageDeliveryException("3u", sQLDataException0);
}
@Test(timeout = 4000)
public void test3() throws Throwable {
Message message0 = new Message();
MessageDeliveryException messageDeliveryException0 = new MessageDeliveryException((Module) null, message0, (Throwable) null);
}
}
| [
"[email protected]"
] | |
f0aaa70b93156f898ef894e85083b42d29df8ea1 | 6ec8e8eb14f0aeccbd3a440e9eec1d4effc57497 | /src/com/nisovin/shopkeepers/events/OpenTradeEvent.java | 70776a6751efb8d2d0990934821d5831e64f35c4 | [] | no_license | CubixCraft/Shopkeepers | ba80e169a8ed1b76e1898cd049849ea287e65dbb | f3e6d77006d2c040c9f17f9e01311a9aedd071ee | refs/heads/master | 2020-08-10T16:10:46.613320 | 2012-08-10T23:51:55 | 2012-08-10T23:51:55 | 5,375,472 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,353 | java | package com.nisovin.shopkeepers.events;
import org.bukkit.entity.Player;
import org.bukkit.event.Cancellable;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
import com.nisovin.shopkeepers.Shopkeeper;
/**
* This event is called when a player attempts to open trade with a shopkeeper villager.
* If the event is cancelled, the trade window will not open.
*
*/
public class OpenTradeEvent extends Event implements Cancellable {
private Player player;
private Shopkeeper shopkeeper;
private boolean cancelled;
public OpenTradeEvent(Player player, Shopkeeper shopkeeper) {
this.player = player;
this.shopkeeper = shopkeeper;
}
/**
* Gets the player attempting to trade.
* @return the player
*/
public Player getPlayer() {
return player;
}
/**
* Gets the shopkeeper the player is attempting to trade with.
* @return the shopkeeper
*/
public Shopkeeper getShopkeeper() {
return shopkeeper;
}
@Override
public boolean isCancelled() {
return cancelled;
}
@Override
public void setCancelled(boolean cancelled) {
this.cancelled = cancelled;
}
private static final HandlerList handlers = new HandlerList();
@Override
public HandlerList getHandlers() {
return handlers;
}
public static HandlerList getHandlerList() {
return handlers;
}
}
| [
"[email protected]"
] | |
126e3131066312de655860321c392518f52d3277 | 173fd547d0abffece52ff3d7c82d52b2d7a9ad1e | /1.7.10-Code/common/doggytalents/lib/Reference.java | e7561a31ec2f23a4483743fab985424c7cbcc4a5 | [] | no_license | ashillion/DoggyTalents | 95e6fb455926e70a9d7b8147151d68fe37aea22a | 1716ba36f82cfd67d625f951cc3afd7a4e4ccbb0 | refs/heads/master | 2020-12-25T05:03:25.848973 | 2015-03-19T07:52:27 | 2015-03-19T07:52:27 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 673 | java | package doggytalents.lib;
/**
* @author ProPercivalalb
*/
public class Reference {
//Mod Related Constants
public static final String MOD_ID = "doggytalents";
public static final String MOD_NAME = "Doggy Talents";
public static final String MOD_VERSION = "v1.8.3a";
public static final String MOD_DEPENDENCIES = "required-after:Forge@[9.10.1.850,)";
public static final String SP_CLIENT = "doggytalents.core.proxy.ClientProxy";
public static final String SP_SERVER = "doggytalents.core.proxy.CommonProxy";
public static final String CHANNEL_NAME = "DOGGY";
public static final boolean DEBUG = false;
}
| [
"[email protected]"
] | |
c361fc890cdda171d4c57598f6b89f176ec02ee8 | f2f1b88537b587ee0b6d4e9bf9ff65edc1dfa441 | /projects/simple_loanApp/src/java/foo/bar/site/controller/DeleteUserCommandControllerCommand.java | e1f0a50895a48b299e7310cf057d89f9c51b34d0 | [] | no_license | BackupTheBerlios/miniwiki-svn | f04c8d4d5e26393ed9f23478409cfb347b7a809e | 4ba24213f3091705e2ab80aea2af4f91a77a6715 | refs/heads/master | 2021-01-22T03:39:47.810642 | 2008-10-18T09:58:10 | 2008-10-18T09:58:10 | 40,774,808 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 821 | java | package foo.bar.site.controller;
import foo.bar.site.domain.User;
import java.util.List;
import java.util.ArrayList;
/**
* @author tmjee
* @version $Date$ $Id$
*/
public class DeleteUserCommandControllerCommand {
private int id;
private List<User> users = new ArrayList<User>();
private List<Integer> userIds = new ArrayList<Integer>();
public List<Integer> getUserIds() {
return userIds;
}
public void setUserIds(List<Integer> userIds) {
this.userIds = userIds;
}
public List<User> getUsers() {
return users;
}
public void setUsers(List<User> users) {
this.users = users;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
| [
"tmjee@dd44553c-9e4f-0410-8d3a-95608e80f3cc"
] | tmjee@dd44553c-9e4f-0410-8d3a-95608e80f3cc |
8c144b68666269056949618c6ef44e4b331fe71e | 4b4718718804e93a25994c27b319350086b55413 | /src/main/java/com/lactusinc/java/App.java | 5ede127464badee01b9d38972bf1e010e3c00051 | [] | no_license | samirshaik/mvn-dep-mgmt-java | d95604bfbf07ec3a4437fe40e4d0c1d74ceca0bf | 7bb9835728dda0d6f67d2743b3184e83b445cf78 | refs/heads/main | 2023-02-28T05:38:46.316943 | 2021-01-31T02:27:51 | 2021-01-31T02:27:51 | 334,555,549 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 181 | java | package com.lactusinc.java;
/**
* Hello world!
*
*/
public class App
{
public static void main( String[] args )
{
System.out.println( "Hello World!" );
}
}
| [
"[email protected]"
] | |
33322c1fa7a35916e00c830f12b0e97747ee29bd | 83c6bfa1c4ec5aee9bcb5b2608f7e816489efa46 | /app/src/main/java/com/example/trianaandaluciaprietogalvan/helloworldsupport/message/FileEvent.java | 87ab3695bffbdfa8f6d922c08c67b8fe46386abf | [] | no_license | TrianaGalvan/MonitorECGMovil | 767b3d3985a9a739aad77063be2bcb50d6e3f912 | c4f51cfca89b352fa169b5c8ef7fab208d2be04a | refs/heads/master | 2021-05-31T11:46:52.840138 | 2016-05-25T03:40:25 | 2016-05-25T03:40:25 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 289 | java | package com.example.trianaandaluciaprietogalvan.helloworldsupport.message;
/**
* Created by trianaandaluciaprietogalvan on 25/04/16.
*/
public class FileEvent {
public final String nombreArchivo;
public FileEvent(String nombre) {
this.nombreArchivo = nombre;
}
}
| [
"[email protected]"
] | |
15fc05ee5288708b9104b88bbc2804b144837581 | a305a77c4d4428b26ebe112e174bc7076ec765e6 | /Java_Labor/src/BirthdayCalendar/Person.java | 4a648d3423dcf4bb024993af15d1c54420ec61b1 | [] | no_license | schadinski/Studium | c50b7813b26564707445d1da3d2f08815c1cab39 | eba367b79ee81b296ecad3b1cb53f625a9b7d4f9 | refs/heads/master | 2022-11-30T19:49:39.501517 | 2020-08-11T04:41:22 | 2020-08-11T04:41:22 | 284,707,607 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,039 | java | package BirthdayCalendar;
public class Person implements Comparable<Person>{
private String name;
private BirthdayCalender_Date birthDate;
public Person(String aName, BirthdayCalender_Date aDateOfBirth){
this.name = aName;
this.birthDate = aDateOfBirth;
}
public String getName() {
return name;
}
public void setName(String newName) {
this.name = newName;
}
public BirthdayCalender_Date getDateOfBirthday() {
return birthDate;
}
public void setDateOfBirthday(BirthdayCalender_Date newDateOfBirth) {
this.birthDate = newDateOfBirth;
}
@Override
public int compareTo(Person other) {
int result = 0;
if(birthDate.month < other.birthDate.month){
result = -1;
}
else if(birthDate.month > other.birthDate.month){
result = 1;
}
else if (birthDate.month == other.birthDate.month && birthDate.day < other.birthDate.day ){
result = -1;
}
else if( birthDate.month== other.birthDate.month&& birthDate.day > other.birthDate.day){
result = 1;
}
else if( birthDate.month == other.birthDate.month && birthDate.day == other.birthDate.day){
int temp = name.compareToIgnoreCase(other.name);
if(temp == 0){
if(birthDate.year == other.birthDate.year){
result = 0;
}
else if(birthDate.year < other.birthDate.year){
result = 1;
}
else if(birthDate.year > other.birthDate.year){
result = -1;
}
}
else if(temp == -1){
result = -1;
}
else if(temp == 1){
result = 1;
}
}
return result;
}
@Override
public boolean equals(Object o){
if(o == null){
return false;
}
if(this== o){
return true;
}
if(! (o instanceof Person)){
return false;
}
Person other = (Person) o;
return name.compareToIgnoreCase(other.name) == 0
&& birthDate.equals(other);
}
@Override
public String toString(){
String result = name.toString()+" "+birthDate.toString();
return result;
}
}
| [
"[email protected]"
] | |
ecc5a483616e3d377371fae212b96e5f87ea2553 | 79cb80a6f6e67ace5b878f188272d548f8d3f3b8 | /src/main/java/ProgrPo16Luty/zad2ConfigLoader/baseConnectionService.java | f379737d972823755fcfafa2aa5ac136daead849 | [] | no_license | RafalBrendanWelz/SDAZadania2020 | 0ebb06ffa3a76530191004201909aa049bb0f7ed | 6eae6a85ef48714229fb5fed064ec78a433957dc | refs/heads/master | 2021-01-26T03:18:19.853565 | 2020-02-29T08:22:35 | 2020-02-29T08:22:35 | 243,286,865 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,267 | java | package ProgrPo16Luty.zad2ConfigLoader;
import lombok.Getter;
import java.util.*;
@Getter
public class baseConnectionService {
private static Map<String, String> serwers;
private static baseConnectionService INSTANCE;
private static final int DLUGOSC_CONFIG = 10;
private baseConnectionService() {
serwers = new HashMap<>();
}
public static baseConnectionService getINSTANCE() {
if (INSTANCE == null){
INSTANCE = new baseConnectionService();
}
return INSTANCE;
}
static int getDLUGOSC_CONFIG() {
return DLUGOSC_CONFIG;
}
void dodajSerwer (final String url){
Random fakeConfigs = new Random();
StringBuilder znakiDoConfig = new StringBuilder();
for (int i = 0; i < DLUGOSC_CONFIG; i++) {
znakiDoConfig.append( (char)(fakeConfigs.nextInt(127) + 48) );
}
serwers.put(url, znakiDoConfig.toString());
}
String polaczDoSerwera(final String URL ){
Random losowyCzasPol = new Random();
try {
Thread.sleep(losowyCzasPol.nextInt(3000) + 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return serwers.getOrDefault(URL, "");
}
}
| [
"[email protected]"
] | |
941a64567708c52abd0a001e834f60bab6ae55d0 | c603486d8a966773019be578b389b39a6cd1e9ff | /URI/Atividade 02/Everton/1035.java | 9cbf71441b0c07b5233ef34d4104100c7704ec24 | [
"MIT"
] | permissive | GOOOL-UFMS/Linguagem-de-Programacao-Orientada-a-Objetos | f798bb16339c05cc96b695854187c352789b2d35 | c6fb198e24b052eec7ead9aaf35e26e0087de1fd | refs/heads/main | 2023-07-28T21:19:13.809976 | 2021-09-10T21:03:44 | 2021-09-10T21:03:44 | 395,465,562 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 540 | java | import java.io.IOException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws IOException {
Scanner input = new Scanner(System.in);
int a, b, c, d;
a = input.nextInt();
b = input.nextInt();
c = input.nextInt();
d = input.nextInt();
if (b>c && d>a && c+d > a+b && c>0 && d>0 && a%2==0) {
System.out.println("Valores aceitos");
}else{
System.out.println("Valores nao aceitos");
}
}
}
| [
"[email protected]"
] | |
c591da76c3be396de8726bd6bfd0095ad0a16883 | 29ce3a5ea0928b1c77a30be3c2c72013976615db | /syncer-core/src/main/java/com/github/zzt93/syncer/common/network/NettyServer.java | ef6bee059bc4f3f5cd3a9bad5d8d2083d3a2b7b7 | [
"BSD-3-Clause"
] | permissive | jiena-2606/syncer | 664cae0ae60d429ee2c7e89e3f067d102eca464a | 36c278e17d087f40a22326b77588d94843d3a475 | refs/heads/master | 2023-07-17T16:58:16.509499 | 2021-09-05T05:41:47 | 2021-09-05T05:41:47 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,313 | java | package com.github.zzt93.syncer.common.network;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
/**
* @author zzt
*/
public class NettyServer {
public static void startAndSync(ChannelInitializer<SocketChannel> initializer, int port) throws InterruptedException {
EventLoopGroup bossGroup = new NioEventLoopGroup(1);
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.option(ChannelOption.SO_BACKLOG, 100)
.handler(new LoggingHandler(LogLevel.DEBUG))
.childHandler(initializer);
ChannelFuture f = b.bind(port).sync();
// wait until the server socket is closed
f.channel().closeFuture().sync();
} finally {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
}
| [
"[email protected]"
] | |
821154e065fb2f41be4beed6cdcfde65692873e3 | 6cef0b70fd08346b2e53107ff55741fab70fb94f | /demo-and-case/src/main/java/io/github/frapples/javademoandcookbook/demoandcase/demo/bio/Main.java | 18010d1fb6846675b04ace060b8cacdc21f246f9 | [] | no_license | atkins126/java-demo-and-cookbook | 414e50800112144209436f8fbe00644b525c6659 | e743aea7dd187854b119bf13ae1d175ee84a61ff | refs/heads/master | 2023-05-23T09:37:53.529772 | 2020-05-17T15:08:32 | 2020-05-17T15:09:43 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 723 | java | package io.github.frapples.javademoandcookbook.demoandcase.demo.bio;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) throws InterruptedException, IOException {
final int PORT = 4040;
Thread serverThread = new Thread(new Server(PORT));
serverThread.start();
Client client = new Client("127.0.0.1", PORT);
Thread.sleep(1000);
while (true) {
BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
String s = stdin.readLine();
String r = client.send(s);
System.out.println(r);
}
}
}
| [
"[email protected]"
] | |
d099fa0b11ea3226f2448918268b10a5978f40fd | 3158c12da679bde1b4e71297f26bcc6b448dda34 | /BioskopAplikacija/src/constants/Constants.java | f4cf32fdd886f7c28f88f53fbb1058523f1bbece | [] | no_license | NikolaRakic/OsnoveWebProgramiranja | daef9c16e9fe2ce305195ef2646bfbda29a3637c | f653087a00d6d022e401acc1f3d0d5e4c9cf8444 | refs/heads/master | 2022-04-04T08:44:15.573461 | 2020-02-11T09:05:27 | 2020-02-11T09:05:27 | 221,250,238 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 122 | java | package constants;
public class Constants {
public final static String DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
}
| [
"Nikola@DESKTOP-J9436IF"
] | Nikola@DESKTOP-J9436IF |
7540db08112fbed573c4cec072c4abc4d530e373 | 2f4a058ab684068be5af77fea0bf07665b675ac0 | /app/com/facebook/contacts/contactcard/entry/CreatePhoneEntryView$2.java | e541c2712c5f9961ea50fb4fe7103b0759f232f9 | [] | no_license | cengizgoren/facebook_apk_crack | ee812a57c746df3c28fb1f9263ae77190f08d8d2 | a112d30542b9f0bfcf17de0b3a09c6e6cfe1273b | refs/heads/master | 2021-05-26T14:44:04.092474 | 2013-01-16T08:39:00 | 2013-01-16T08:39:00 | 8,321,708 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 534 | java | package com.facebook.contacts.contactcard.entry;
import android.view.View;
import android.view.View.OnClickListener;
class CreatePhoneEntryView$2
implements View.OnClickListener
{
public void onClick(View paramView)
{
if (CreatePhoneEntryView.a(this.a) != null)
CreatePhoneEntryView.a(this.a).b();
}
}
/* Location: /data1/software/jd-gui/com.facebook.katana_2.0_liqucn.com-dex2jar.jar
* Qualified Name: com.facebook.contacts.contactcard.entry.CreatePhoneEntryView.2
* JD-Core Version: 0.6.0
*/ | [
"[email protected]"
] | |
24a3ca019f18dcf4833588d25c865a63b9c7d100 | 123f4dba79c550e48fef220bbc4f22e5aaeaa8fe | /app/src/main/java/com/example/sarah/alkosh/OrdersFragment.java | 4c93b0931c9d8814452dd3095186335df7d8e214 | [] | no_license | blackrose9/goldensilverfish | 4b0e82c647059555068e434ee627ff5b8187512f | d98b806f5bbb9a554292693275f5ff062bc32176 | refs/heads/master | 2021-09-03T14:44:26.972530 | 2018-01-09T21:42:12 | 2018-01-09T21:42:12 | 114,478,969 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,045 | java | package com.example.sarah.alkosh;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.example.sarah.alkosh.common.Common;
import com.example.sarah.alkosh.model.OrderRequest;
import com.example.sarah.alkosh.viewholder.OrderViewHolder;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.rey.material.widget.FloatingActionButton;
/**
* Created by Sarah on 11/30/2017.
*/
public class OrdersFragment extends Fragment{
RecyclerView mOrderList;
DatabaseReference mDatabase;
FirebaseRecyclerAdapter<OrderRequest,OrderViewHolder> firebaseRecyclerAdapter;
android.support.design.widget.FloatingActionButton fabChat;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
//return inflater.inflate(R.layout.fragment_orders, container, false);
View view = inflater.inflate(R.layout.fragment_orders, container, false);
fabChat = (android.support.design.widget.FloatingActionButton) view.findViewById(R.id.fabChat);
fabChat.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view) {
Intent intent = new Intent(getActivity(), ChatAct.class);
startActivity(intent);
}
});
return view;
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
getActivity().setTitle("My Orders");
initViews(view);
mOrderList.setHasFixedSize(true);
mOrderList.setLayoutManager(new LinearLayoutManager(getContext()));
mDatabase= FirebaseDatabase.getInstance().getReference("OrderRequests");
}
@Override
public void onStart() {
super.onStart();
firebaseRecyclerAdapter=new FirebaseRecyclerAdapter<OrderRequest, OrderViewHolder>(
OrderRequest.class,
R.layout.order_layout,
OrderViewHolder.class,
mDatabase.orderByChild("phone").equalTo(Common.userPhoneNo)
) {
@Override
protected void populateViewHolder(OrderViewHolder viewHolder, OrderRequest model, int position) {
viewHolder.txtOrderAddress.setText(model.getAddress());
viewHolder.txtOrderStatus.setText(model.getStatus());
viewHolder.txtOrderStatus.setTextColor(setColor(model.getStatus()));
viewHolder.txtOrderId.setText(firebaseRecyclerAdapter.getRef(position).getKey());
viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
}
});
}
};
mOrderList.setAdapter(firebaseRecyclerAdapter);
}
private int setColor(String status) {
if(status.equals("0"))
{
return android.R.color.holo_blue_dark;
}
else if(status.equals("1"))
{
return R.color.colorAccent;
}
else
{
return android.R.color.holo_green_light;
}
}
private String convertCodeToStatus(String status) {
if(status.equals("0"))
{
return "Shipped";
}
else if(status.equals("1"))
{
return "On its way";
}
else
{
return "Arrived";
}
}
private void initViews(View view) {
mOrderList=view.findViewById(R.id.listOrders);
}
}
| [
"[email protected]"
] | |
15dbf583f5bc5e81e153c46af70486dd54f8a60f | 6cde3d1a8b8fefe71e48531f13e1d545976d12fa | /java/数据结构/07_AVL树/src/tree/BinaryTree.java | 66738120475059cb68206133f22db1a3f3f0140c | [] | no_license | Alan-FLX/code | 98d773ffed7e755e5c393d44b07d173febcaa22d | 283cd2ed3252a0096d0c7f62f5a7c664415a34f8 | refs/heads/main | 2023-01-21T17:41:24.583042 | 2020-11-30T14:29:09 | 2020-11-30T14:29:09 | 317,408,975 | 1 | 0 | null | 2020-12-01T03:01:45 | 2020-12-01T03:01:44 | null | UTF-8 | Java | false | false | 6,302 | java | package tree;
import java.util.LinkedList;
import java.util.Queue;
public class BinaryTree<E> {
protected int size;
protected Node<E> root;
// 返回二叉搜索树的大小
public int size(){
return size;
}
// 判断二叉搜索树是否为空
public boolean isEmpty(){
return size == 0;
}
// 清空二叉搜索树
public void clear(){
root = null;
size = 0;
}
// 二叉树节点操作虚构类
public static abstract class Visitor<E>{
// 返回true,代表停止遍历
boolean stop = false;
abstract boolean visit(E element);
}
// 层次遍历操作
public void levelOrder(Visitor<E> visitor) {
if(root == null || visitor == null) return;
Queue<Node<E>> queue = new LinkedList<>();
queue.add(root);
while(!queue.isEmpty()){
Node<E> node = queue.poll();
if(visitor.visit(node.element)) return;
if(node.left != null) {
queue.offer(node.left);
}
if(node.right != null){
queue.offer(node.right);
}
}
}
// 前序遍历操作
public void preOrder(Visitor<E> visitor) {
if(visitor == null) return;
preOrder(root, visitor);
}
public void preOrder(Node<E> node, Visitor<E> visitor){
if(node == null || visitor.stop) return;
visitor.stop = visitor.visit(node.element);
preOrder(node.left, visitor);
preOrder(node.right, visitor);
}
// 中序遍历操作
public void inOrder(Visitor<E> visitor) {
if(visitor == null) return;
inOrder(root, visitor);
}
public void inOrder(Node<E> node, Visitor<E> visitor){
if(node == null || visitor.stop) return;
inOrder(node.left, visitor);
if(visitor.stop) return;
visitor.stop = visitor.visit(node.element);
inOrder(node.right, visitor);
}
// 后序遍历操作
public void postOrder(Visitor<E> visitor) {
if(visitor == null) return;
postOrder(root, visitor);
}
public void postOrder(Node<E> node, Visitor<E> visitor){
if(node == null || visitor.stop) return;
postOrder(node.left, visitor);
postOrder(node.right, visitor);
if(visitor.stop) return;
visitor.stop = visitor.visit(node.element);
}
// 判断是否是完全二叉树
public boolean isComplete(){
if(root == null) return false;
Queue<Node<E>> queue = new LinkedList<>();
queue.offer(root);
boolean leaf = false;
while(!queue.isEmpty()) {
Node<E> node = queue.poll();
if(leaf && !node.isLeaf()) return false;
if(node.left != null) {
queue.offer(node.left);
} else if(node.right != null) {
return false;
}
if(node.right != null) {
queue.offer(node.right);
} else {
// 是叶子节点
leaf = true;
}
}
return true;
}
protected static class Node<E>{
E element;
Node<E> left;
Node<E> right;
Node<E> parent;
public Node(E element, Node<E> parent) {
this.element = element;
this.parent = parent;
}
// 判断是否为叶子节点
public boolean isLeaf(){
return left == null && right == null;
}
// 判断是否是度为2的节点
public boolean hasTwoChildren(){
return left != null && right != null;
}
// 判断当前节点是不是父节点的左孩子
public boolean isLeftChild(){
return parent != null && this == this.parent.left;
}
// 判断当前节点是不是父节点的右孩子
public boolean isRightChild(){
return parent != null && this == this.parent.right;
}
}
// 寻找某一节点的前驱节点
// 即它中序遍历的前一个节点
protected Node<E> predecessor(Node<E> node){
if(node == null) return null;
// 前驱节点在左子树中
Node<E> p = node.left;
if(p != null) {
while(p.right != null) {
p = p.right;
}
return p;
}
// 从父节点、祖父节点中寻找前驱节点
while(node.parent != null && node == node.parent.left) {
node = node.parent;
}
// 如果父节点为null 则前驱节点为null
// 如果当前节点为父节点的右节点,则前驱节点为它的父节点
return node.parent;
}
// 寻找某一节点的后继节点
// 即中序遍历的后一个节点
protected Node<E> successor(Node<E> node){
if(node == null) return null;
// 后继节点在右子树中
Node<E> p = node.right;
if(p != null) {
while(p.left != null) {
p = p.left;
}
return p;
}
// 从父节点、祖父节点中寻找后继节点
while(node.parent != null && node == node.parent.right) {
node = node.parent;
}
// 如果父节点为null 则后继节点为null
// 如果当前节点为父节点的左节点,则后继节点为它的父节点
return node.parent;
}
// 计算二叉树的高度(迭代)
public int height(){
if(root == null) return 0;
int height = 0;
int levelSize = 1;
Queue<Node<E>> queue = new LinkedList<>();
queue.add(root);
while(!queue.isEmpty()){
Node<E> node = queue.poll();
levelSize--;
if(node.left != null) {
queue.offer(node.left);
}
if(node.right != null){
queue.offer(node.right);
}
// 访问下一层
if(levelSize == 0) {
levelSize = queue.size();
height++;
}
}
return height;
}
protected Node<E> createNode(E element, Node<E> parent) {
return new Node<>(element, parent);
}
}
| [
"[email protected]"
] | |
331ecba1c24833e0bb3aef32da002f97efec4238 | 462b9598f08a48ab835f0b189d4d344560965227 | /src/main/java/csheets/ext/agenda/domain/IAgenda.java | 61c6e3d49859959acd56489a49a2efb07769b63c | [] | no_license | VitorMascarenhas/LAPR4-2016 | 19f5593b98b81763f77021fb04278ed231337028 | e53a5a46c0e09fbc155fb91f2010d50532de85d2 | refs/heads/master | 2020-03-19T10:31:05.321699 | 2018-06-06T19:49:19 | 2018-06-06T19:49:19 | 136,027,190 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 342 | java | package csheets.ext.agenda.domain;
import java.io.Serializable;
import java.util.List;
/**
* Defines Agenda contract.
*/
public interface IAgenda extends Serializable
{
List<IEvent> allEvents();
boolean addEvent(IEvent event);
boolean removeEvent(IEvent event);
boolean updateEvent(IEvent event);
boolean isValid();
}
| [
"[email protected]"
] | |
9b5ac2be2b8f5a89c330a54ab1975259e1d3f281 | 3b0c74fd8694b870a6f3b688143e7ff80e42ae60 | /myproject10/src/myproject10/hashmapwithoutgenerics.java | 44cbb50ccdada9cb7305bd1a8682dda24735a78a | [] | no_license | mahaboob-roshini/Generics-and-maps | 93e5aedc792177691f2ab251280b7435bead5b89 | ff023131ab473f7d7e911d55f95b2945a2c36710 | refs/heads/master | 2020-06-03T18:55:44.436147 | 2019-06-13T04:38:45 | 2019-06-13T04:38:45 | 189,355,689 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 477 | java | package myproject10;
import java.util.HashMap;
import java.util.Iterator;
public class hashmapwithoutgenerics {
public static void main(String args[]) {
HashMap h=new HashMap<>();
h.put("a","array");
h.put("b","link");
h.put("c","vector");
h.put("d","stack");
h.put("e","queue");
h.put("f","enqueue");
h.put("g","arrayqueue");
h.put("i","map");
h.put("k","array");
h.put("k","list");
System.out.println("the hashmap is"+h);
}
}
| [
"vsm sys@vsmsys-PC"
] | vsm sys@vsmsys-PC |
4fdbf15ab109de1c196ff7eedcd90e6cf1e4d31e | 6aca77afca15158a7d761e9512c61ae3ec9429e8 | /rebatch-jbatch/src/main/java/info/bitcrate/rebatch/jmx/Rebatch.java | 01d610f4665c77fdb571b4f2006fd4ea42f9bd2a | [] | no_license | mgae/rebatch | 06075540a5fa3dff6df2f83662dce22347e46540 | 16fafab76ea4b24130cf27addee1297c867395b8 | refs/heads/master | 2021-01-22T14:02:42.107796 | 2014-01-24T05:11:49 | 2014-01-24T05:11:49 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,794 | java | /*
* Copyright 2012 International Business Machines Corp.
*
* See the NOTICE file distributed with this work for additional information
* regarding copyright ownership. 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 info.bitcrate.rebatch.jmx;
import javax.management.openmbean.TabularData;
public class Rebatch implements RebatchMBean {
private final RebatchMBean delegate;
public Rebatch(final RebatchMBean delegate) {
this.delegate = delegate;
}
@Override
public String[] getJobNames() {
return delegate.getJobNames();
}
@Override
public int getJobInstanceCount(final String jobName) {
return delegate.getJobInstanceCount(jobName);
}
@Override
public TabularData getJobInstances(final String jobName, final int start, final int count) {
return delegate.getJobInstances(jobName, start, count);
}
@Override
public Long[] getRunningExecutions(final String jobName) {
return delegate.getRunningExecutions(jobName);
}
@Override
public TabularData getParameters(final long executionId) {
return delegate.getParameters(executionId);
}
@Override
public TabularData getJobInstance(final long executionId) {
return delegate.getJobInstance(executionId);
}
@Override
public TabularData getJobExecutions(final long id, final String name) {
return delegate.getJobExecutions(id, name);
}
@Override
public TabularData getJobExecution(final long executionId) {
return delegate.getJobExecution(executionId);
}
@Override
public TabularData getStepExecutions(final long jobExecutionId) {
return delegate.getStepExecutions(jobExecutionId);
}
@Override
public long start(final String jobXMLName, final String jobParameters) {
return delegate.start(jobXMLName, jobParameters);
}
@Override
public long restart(final long executionId, final String restartParameters) {
return delegate.restart(executionId, restartParameters);
}
@Override
public void stop(final long executionId) {
delegate.stop(executionId);
}
@Override
public void abandon(final long executionId) {
delegate.abandon(executionId);
}
}
| [
"[email protected]"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.