blob_id
stringlengths
40
40
__id__
int64
225
39,780B
directory_id
stringlengths
40
40
path
stringlengths
6
313
content_id
stringlengths
40
40
detected_licenses
list
license_type
stringclasses
2 values
repo_name
stringlengths
6
132
repo_url
stringlengths
25
151
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
70
visit_date
timestamp[ns]
revision_date
timestamp[ns]
committer_date
timestamp[ns]
github_id
int64
7.28k
689M
star_events_count
int64
0
131k
fork_events_count
int64
0
48k
gha_license_id
stringclasses
23 values
gha_fork
bool
2 classes
gha_event_created_at
timestamp[ns]
gha_created_at
timestamp[ns]
gha_updated_at
timestamp[ns]
gha_pushed_at
timestamp[ns]
gha_size
int64
0
40.4M
gha_stargazers_count
int32
0
112k
gha_forks_count
int32
0
39.4k
gha_open_issues_count
int32
0
11k
gha_language
stringlengths
1
21
gha_archived
bool
2 classes
gha_disabled
bool
1 class
content
stringlengths
7
4.37M
src_encoding
stringlengths
3
16
language
stringclasses
1 value
length_bytes
int64
7
4.37M
extension
stringclasses
24 values
filename
stringlengths
4
174
language_id
stringclasses
1 value
entities
list
contaminating_dataset
stringclasses
0 values
malware_signatures
list
redacted_content
stringlengths
7
4.37M
redacted_length_bytes
int64
7
4.37M
alphanum_fraction
float32
0.25
0.94
alpha_fraction
float32
0.25
0.94
num_lines
int32
1
84k
avg_line_length
float32
0.76
99.9
std_line_length
float32
0
220
max_line_length
int32
5
998
is_vendor
bool
2 classes
is_generated
bool
1 class
max_hex_length
int32
0
319
hex_fraction
float32
0
0.38
max_unicode_length
int32
0
408
unicode_fraction
float32
0
0.36
max_base64_length
int32
0
506
base64_fraction
float32
0
0.5
avg_csv_sep_count
float32
0
4
is_autogen_header
bool
1 class
is_empty_html
bool
1 class
shard
stringclasses
16 values
6139321e115b01761d391f2efdb071fc63e783c5
24,773,371,405,364
f40e466c35974c9ff3c2953e928ca81f1f0d3064
/src/main/java/com/jazzchris/musicchallenge/service/MainServiceImpl.java
ee95ca722e323dfcae0ba561ae2fefcdd9954c79
[]
no_license
jazzchris/music-challenge
https://github.com/jazzchris/music-challenge
bd93c300d31fd1afd5a384c84f055a478a900002
fab580920ee6895f82ca35fe5b0057686c5f133e
refs/heads/master
2020-05-24T00:41:52.732000
2019-05-21T12:07:45
2019-05-21T12:07:45
187,020,916
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.jazzchris.musicchallenge.service; import java.io.IOException; import java.io.InputStream; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.multipart.MultipartFile; import com.dropbox.core.DbxException; import com.dropbox.core.v2.files.DeleteErrorException; import com.dropbox.core.v2.files.RestoreErrorException; import com.dropbox.core.v2.files.UploadErrorException; import com.jazzchris.musicchallenge.dao.ComposerDAO; import com.jazzchris.musicchallenge.dao.PieceDAO; import com.jazzchris.musicchallenge.entity.Composer; import com.jazzchris.musicchallenge.entity.Piece; @Service public class MainServiceImpl implements MainService { @Autowired private ComposerDAO composerDAO; @Autowired private PieceDAO pieceDAO; @Autowired private FileService fileService; @Override @Transactional public List<Composer> getComposers() { return composerDAO.getComposers(); } @Override @Transactional public Composer getComposer(int theId) { return composerDAO.getComposer(theId); } @Override @Transactional public void saveComposer(Composer comp) { composerDAO.saveComposer(comp); } @Override @Transactional public void deleteComposer(int id) { composerDAO.deleteComposer(id); } @Override @Transactional public List<Piece> getPieces() { return pieceDAO.getPieces(); } @Override @Transactional public List<Piece> getPiecesByComposer(int theId) { return pieceDAO.getPiecesByComposer(theId); } @Override @Transactional public Piece getPiece(int id) { return pieceDAO.getPiece(id); } @Override @Transactional public void savePiece(Piece piece) { pieceDAO.savePiece(piece); } @Override @Transactional public void deletePiece(int id) { pieceDAO.deletePiece(id); } @Override public InputStream streamFile(String title) { return fileService.streamFile(title); } @Override public void uploadFile(MultipartFile file, String title) throws UploadErrorException, DbxException, IOException { fileService.uploadFile(file, title); } @Override public void renameFile(String oldTitle, String newTitle) throws RestoreErrorException, DbxException { fileService.renameFile(oldTitle, newTitle); } @Override public void deleteFile(String title) throws DeleteErrorException, DbxException { fileService.deleteFile(title); } @Override public List<String> listFile() { return fileService.listFile(); } }
UTF-8
Java
2,572
java
MainServiceImpl.java
Java
[]
null
[]
package com.jazzchris.musicchallenge.service; import java.io.IOException; import java.io.InputStream; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.multipart.MultipartFile; import com.dropbox.core.DbxException; import com.dropbox.core.v2.files.DeleteErrorException; import com.dropbox.core.v2.files.RestoreErrorException; import com.dropbox.core.v2.files.UploadErrorException; import com.jazzchris.musicchallenge.dao.ComposerDAO; import com.jazzchris.musicchallenge.dao.PieceDAO; import com.jazzchris.musicchallenge.entity.Composer; import com.jazzchris.musicchallenge.entity.Piece; @Service public class MainServiceImpl implements MainService { @Autowired private ComposerDAO composerDAO; @Autowired private PieceDAO pieceDAO; @Autowired private FileService fileService; @Override @Transactional public List<Composer> getComposers() { return composerDAO.getComposers(); } @Override @Transactional public Composer getComposer(int theId) { return composerDAO.getComposer(theId); } @Override @Transactional public void saveComposer(Composer comp) { composerDAO.saveComposer(comp); } @Override @Transactional public void deleteComposer(int id) { composerDAO.deleteComposer(id); } @Override @Transactional public List<Piece> getPieces() { return pieceDAO.getPieces(); } @Override @Transactional public List<Piece> getPiecesByComposer(int theId) { return pieceDAO.getPiecesByComposer(theId); } @Override @Transactional public Piece getPiece(int id) { return pieceDAO.getPiece(id); } @Override @Transactional public void savePiece(Piece piece) { pieceDAO.savePiece(piece); } @Override @Transactional public void deletePiece(int id) { pieceDAO.deletePiece(id); } @Override public InputStream streamFile(String title) { return fileService.streamFile(title); } @Override public void uploadFile(MultipartFile file, String title) throws UploadErrorException, DbxException, IOException { fileService.uploadFile(file, title); } @Override public void renameFile(String oldTitle, String newTitle) throws RestoreErrorException, DbxException { fileService.renameFile(oldTitle, newTitle); } @Override public void deleteFile(String title) throws DeleteErrorException, DbxException { fileService.deleteFile(title); } @Override public List<String> listFile() { return fileService.listFile(); } }
2,572
0.789269
0.788103
115
21.365217
22.645214
114
false
false
0
0
0
0
0
0
1.130435
false
false
2
9aa49907c9232d089aaaf791a6f97f86bd2680b0
31,344,671,358,095
b2672abaa47038329d91b1a3762015200ad02a5a
/src/au/edu/rmit/trajectory/clustering/kmeans/plotData.java
221cb8fe9865116c602ee7bf9c74508dafcba89a
[]
no_license
rp4ps/pick-means
https://github.com/rp4ps/pick-means
5272075e5df07b131b9e257dbd6da5e83a66f8c0
62810efbc7b9338886f63f8523d8b389534b786f
refs/heads/main
2023-02-23T16:08:28.974000
2021-08-29T08:44:52
2021-08-29T08:44:52
332,098,166
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package au.edu.rmit.trajectory.clustering.kmeans; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import au.edu.rmit.trajectory.clustering.kpaths.Util; import au.edu.rmit.trajectory.clustering.streaming.DataReading; import edu.wlu.cs.levy.cg.KeyDuplicateException; import edu.wlu.cs.levy.cg.KeySizeException; public class plotData { public plotData() { // TODO Auto-generated constructor stub } public static void savePlotDataFile(String folderName, int option, int k, String indexType, String output) throws IOException { File folder = new File(folderName); int datasetnum = 11; String []content = new String[datasetnum];// dataset int dataCounter = 0; for (final File fileEntry : folder.listFiles()) { if (!fileEntry.isDirectory()) { String fileName = fileEntry.getName(); if(fileName.contains("_"+Integer.toString(k)+"_"+indexType)) { if(fileName.contains("Bigcross")) { dataCounter = 0; System.out.println(readContent(fileEntry, option)); content[dataCounter] = readContent(fileEntry, option); // System.out.println(fileName); }else if(fileName.contains("conf")){ dataCounter = 1; content[dataCounter] = readContent(fileEntry, option); }else if(fileName.contains("covt")) { dataCounter = 2; content[dataCounter] = readContent(fileEntry, option); }else if(fileName.contains("euro")) { dataCounter = 3; content[dataCounter] = readContent(fileEntry, option); }else if(fileName.contains("KeggDirect")) { dataCounter = 4; content[dataCounter] = readContent(fileEntry, option); }else if(fileName.contains("KeggUndirect")) { dataCounter = 5; content[dataCounter] = readContent(fileEntry, option); }else if(fileName.contains("NYC")) { dataCounter = 6; content[dataCounter] = readContent(fileEntry, option); }else if(fileName.contains("Skin")) { dataCounter = 7; content[dataCounter] = readContent(fileEntry, option); }else if(fileName.contains("power")) { dataCounter = 8; content[dataCounter] = readContent(fileEntry, option); }else if(fileName.contains("Spatial")) { dataCounter = 9; content[dataCounter] = readContent(fileEntry, option); }else if(fileName.contains("USCensus")) { dataCounter = 10; content[dataCounter] = readContent(fileEntry, option); } // content[dataCounter] = readContent(fileEntry, option); } // System.out.println(fileEntry.getName()); } } System.out.println(content[0]); System.out.println(); for(int i = 1; i<=datasetnum; i++) Util.write(folderName+"/plot/"+output, Integer.toString(i)+ "\t"+ content[i-1]+"\n"); } //read the lines public static String readContent(File file, int lineCountre) throws IOException{ // System.out.println("read file " + file.getCanonicalPath() ); String content = ""; try(BufferedReader br = new BufferedReader(new FileReader(file))){ String strLine; int counter = 0; while((strLine = br.readLine()) != null){ if(counter++ == lineCountre) { content = strLine; break; } } } // System.out.println(content); return content; } //read the specific column in lines public static String readContent(File file, int lineCountre, int start, int end) throws IOException{ // System.out.println("read file " + file.getCanonicalPath() ); String content = ""; try(BufferedReader br = new BufferedReader(new FileReader(file))){ String strLine; int counter = 0; while((strLine = br.readLine()) != null){ if(counter++ == lineCountre) { String columns[] = strLine.split("\t"); for(int i = start; i<=end; i++) content += columns[i-1]+"\t"; break; } } } return content; } // export the value that change with k. static void extractk(String folderName, String datasetName, int option) throws IOException { File folder = new File(folderName); int kvaluenum = 3; String []content = new String[kvaluenum];// dataset for (final File fileEntry : folder.listFiles()) { if (!fileEntry.isDirectory()) { String fileName = fileEntry.getName(); if(fileName.contains(datasetName)) { if(fileName.contains("10_Ball")) { content[0] = readContent(fileEntry, option); }else if(fileName.contains("100_Ball")) { content[1] = readContent(fileEntry, option); }else if(fileName.contains("1000_Ball")) { content[2] = readContent(fileEntry, option); } } } } for(int i = 1; i<=kvaluenum; i++) Util.write(folderName+"/plot/"+datasetName+"IncreasingK.txt", Integer.toString(i)+ "\t"+ content[i-1]+"\n"); } // export the value that change with k. static void extractDataScale(String folderName, String datasetName, int option, int k) throws IOException { File folder = new File(folderName); int kvaluenum = 5; String []content = new String[kvaluenum];// dataset for (final File fileEntry : folder.listFiles()) { if (!fileEntry.isDirectory()) { String fileName = fileEntry.getName(); String scaleset[] = fileName.split("_"); if(fileName.contains(datasetName) && !fileName.contains("index") && scaleset.length>1) { String scale = scaleset[1]; if(scale.equals("100")) { content[0] = readContent(fileEntry, option); }else if(scale.equals("1000")) { content[1] = readContent(fileEntry, option); }else if(scale.equals("10000")) { content[2] = readContent(fileEntry, option); }else if(scale.equals("100000")) { content[3] = readContent(fileEntry, option); }else if(scale.equals("1000000")) { content[4] = readContent(fileEntry, option); } } } } for(int i = 1; i<=kvaluenum; i++) Util.write(folderName+"/plot/"+datasetName+"IncreasingData"+Integer.valueOf(k)+".txt", Integer.toString(i)+ "\t"+ content[i-1]+"\n"); } /* * */ static void extrackIndex(String folderName, String datasetName, int option, int k) throws IOException { File folder = new File(folderName); int kvaluenum = 3; String []content = new String[kvaluenum];// dataset for (final File fileEntry : folder.listFiles()) { if (!fileEntry.isDirectory()) { String fileName = fileEntry.getName(); String scaleset[] = fileName.split("_"); if(fileName.contains(datasetName) && scaleset.length>2) { String scale = scaleset[4]; if(scaleset[3].equals(Integer.toString(k))) { if(scale.equals("BallMetric")) { content[0] = readContent(fileEntry, option); }else if(scale.equals("Mtree")) { content[1] = readContent(fileEntry, option); }else if(scale.equals("hkmtree")) { content[2] = readContent(fileEntry, option); } } } } } for(int i = 1; i<=kvaluenum; i++) Util.write(folderName+"/plot/"+datasetName+"IndexType"+Integer.valueOf(k)+".txt", Integer.toString(i)+ "\t"+ content[i-1]+"\n"); } /* * test */ static void extracDimension(String folderName, String datasetName, int option, int k) throws IOException { File folder = new File(folderName); int kvaluenum = 5; String []content = new String[kvaluenum];// dataset for (final File fileEntry : folder.listFiles()) { if (!fileEntry.isDirectory()) { String fileName = fileEntry.getName(); String scaleset[] = fileName.split("_"); if(fileName.contains(datasetName) && scaleset.length>2) { String scale = scaleset[2]; if (scaleset[3].equals(Integer.toString(k))) { if (scale.equals("10")) { content[0] = readContent(fileEntry, option); } else if (scale.equals("20")) { content[1] = readContent(fileEntry, option); } else if (scale.equals("30")) { content[2] = readContent(fileEntry, option); } else if (scale.equals("40")) { content[3] = readContent(fileEntry, option); } else if (scale.equals("50")) { content[4] = readContent(fileEntry, option); } } } } } for(int i = 1; i<=kvaluenum; i++) Util.write(folderName+"/plot/"+datasetName+"Dimension"+Integer.valueOf(k)+".txt", Integer.toString(i)+ "\t"+ content[i-1]+"\n"); } /* * extract the running time of different index with the increasing of capacity, */ static void extrackIndexCapacity(String folderName, String datasetName, int option, int k) throws IOException { File folder = new File(folderName); int kvaluenum = 6; // capacity number String []content = new String[kvaluenum];// dataset String []content_ball = new String[kvaluenum];// dataset for (final File fileEntry : folder.listFiles()) { if (!fileEntry.isDirectory()) { String fileName = fileEntry.getName(); String scaleset[] = fileName.split("_"); if(fileName.contains(datasetName) && scaleset.length>2) { String scale = scaleset[4]; if(scaleset[3].equals(Integer.toString(k))) { if (fileName.contains("10.log")) { if (scale.equals("HKT")) content[0] = readContent(fileEntry, option, 14, 16); else if (scale.equals("BallMetric")) { content_ball[0] = readContent(fileEntry, option, 14, 16); } } else if (fileName.contains("20.log")) { if (scale.equals("HKT")) content[1] = readContent(fileEntry, option, 14, 16); else if (scale.equals("BallMetric")) { content_ball[1] = readContent(fileEntry, option, 14, 16); } }else if (fileName.contains("30.log")) { if (scale.equals("HKT")) content[2] = readContent(fileEntry, option, 14, 16); else if (scale.equals("BallMetric")) { content_ball[2] = readContent(fileEntry, option, 14, 16); } }else if (fileName.contains("40.log")) { if (scale.equals("HKT")) content[3] = readContent(fileEntry, option, 14, 16); else if (scale.equals("BallMetric")) { content_ball[3] = readContent(fileEntry, option, 14, 16); } }else if (fileName.contains("50.log")) { if (scale.equals("HKT")) content[4] = readContent(fileEntry, option, 14, 16); else if (scale.equals("BallMetric")) { content_ball[4] = readContent(fileEntry, option, 14, 16); } }else if (fileName.contains("60.log")) { if (scale.equals("HKT")) content[5] = readContent(fileEntry, option, 14, 16); else if (scale.equals("BallMetric")) { content_ball[5] = readContent(fileEntry, option, 14, 16); } } } } } } for(int i = 1; i<=kvaluenum; i++) Util.write(folderName+"\\plot\\"+datasetName+"Capacity"+Integer.valueOf(k)+".txt", Integer.toString(i)+ "\t"+ content[i-1]+content_ball[i-1]+"\n"); } // option 0: total running time, 1: ratio, // 3: assignment time, 4, ratio // 6: refinement, 7, raito // 9: computations, 10, ratio // 12: boundCompares, 14: dataAccess, 16: boundUpdates, 18: memoryUsage //read existing files and store the data in a folder, then add the new ran data to update the score. public static void main(String[] args) throws IOException, KeySizeException, KeyDuplicateException { for (int kvalue = 10; kvalue <= 100; kvalue = kvalue * 10) { savePlotDataFile(args[0], 0, kvalue, "Ball", "runingtime" +Integer.valueOf(kvalue)+ ".txt"); savePlotDataFile(args[0], 1, kvalue, "Ball", "runingtimeratio" + Integer.valueOf(kvalue)+".txt"); savePlotDataFile(args[0], 3, kvalue, "Ball", "assigntime" +Integer.valueOf(kvalue)+ ".txt"); savePlotDataFile(args[0], 4, kvalue, "Ball", "assigntimeratio" + Integer.valueOf(kvalue)+".txt"); savePlotDataFile(args[0], 6, kvalue, "Ball", "refinetime" + Integer.valueOf(kvalue)+".txt"); savePlotDataFile(args[0], 7, kvalue, "Ball", "refineratio" + Integer.valueOf(kvalue)+".txt"); savePlotDataFile(args[0], 9, kvalue, "Ball", "computation" + Integer.valueOf(kvalue)+".txt"); savePlotDataFile(args[0], 10, kvalue, "Ball", "computationratio" + Integer.valueOf(kvalue)+".txt"); savePlotDataFile(args[0], 12, kvalue, "Ball", "boundCompares" + Integer.valueOf(kvalue)+".txt"); savePlotDataFile(args[0], 14, kvalue, "Ball", "dataAccess" + Integer.valueOf(kvalue)+".txt"); savePlotDataFile(args[0], 16, kvalue, "Ball", "boundUpdates" + Integer.valueOf(kvalue)+".txt"); savePlotDataFile(args[0], 18, kvalue, "Ball", "memoryUsage" + Integer.valueOf(kvalue)+".txt"); } /* extractk(args[0], "road", 1); extractDataScale(args[0], "NYC", 0, 100); extrackIndex(args[0], "road", 1, 100); extrackIndexCapacity(args[0], "NYC", 0, 10);// get the running time, all the index method. extracDimension(args[0], "covt", 0, 10);// get the running time, all the index method. extracDimension(args[0], "bigcross", 0, 10);// get the running time, all the index method. */ } }
UTF-8
Java
14,198
java
plotData.java
Java
[]
null
[]
package au.edu.rmit.trajectory.clustering.kmeans; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import au.edu.rmit.trajectory.clustering.kpaths.Util; import au.edu.rmit.trajectory.clustering.streaming.DataReading; import edu.wlu.cs.levy.cg.KeyDuplicateException; import edu.wlu.cs.levy.cg.KeySizeException; public class plotData { public plotData() { // TODO Auto-generated constructor stub } public static void savePlotDataFile(String folderName, int option, int k, String indexType, String output) throws IOException { File folder = new File(folderName); int datasetnum = 11; String []content = new String[datasetnum];// dataset int dataCounter = 0; for (final File fileEntry : folder.listFiles()) { if (!fileEntry.isDirectory()) { String fileName = fileEntry.getName(); if(fileName.contains("_"+Integer.toString(k)+"_"+indexType)) { if(fileName.contains("Bigcross")) { dataCounter = 0; System.out.println(readContent(fileEntry, option)); content[dataCounter] = readContent(fileEntry, option); // System.out.println(fileName); }else if(fileName.contains("conf")){ dataCounter = 1; content[dataCounter] = readContent(fileEntry, option); }else if(fileName.contains("covt")) { dataCounter = 2; content[dataCounter] = readContent(fileEntry, option); }else if(fileName.contains("euro")) { dataCounter = 3; content[dataCounter] = readContent(fileEntry, option); }else if(fileName.contains("KeggDirect")) { dataCounter = 4; content[dataCounter] = readContent(fileEntry, option); }else if(fileName.contains("KeggUndirect")) { dataCounter = 5; content[dataCounter] = readContent(fileEntry, option); }else if(fileName.contains("NYC")) { dataCounter = 6; content[dataCounter] = readContent(fileEntry, option); }else if(fileName.contains("Skin")) { dataCounter = 7; content[dataCounter] = readContent(fileEntry, option); }else if(fileName.contains("power")) { dataCounter = 8; content[dataCounter] = readContent(fileEntry, option); }else if(fileName.contains("Spatial")) { dataCounter = 9; content[dataCounter] = readContent(fileEntry, option); }else if(fileName.contains("USCensus")) { dataCounter = 10; content[dataCounter] = readContent(fileEntry, option); } // content[dataCounter] = readContent(fileEntry, option); } // System.out.println(fileEntry.getName()); } } System.out.println(content[0]); System.out.println(); for(int i = 1; i<=datasetnum; i++) Util.write(folderName+"/plot/"+output, Integer.toString(i)+ "\t"+ content[i-1]+"\n"); } //read the lines public static String readContent(File file, int lineCountre) throws IOException{ // System.out.println("read file " + file.getCanonicalPath() ); String content = ""; try(BufferedReader br = new BufferedReader(new FileReader(file))){ String strLine; int counter = 0; while((strLine = br.readLine()) != null){ if(counter++ == lineCountre) { content = strLine; break; } } } // System.out.println(content); return content; } //read the specific column in lines public static String readContent(File file, int lineCountre, int start, int end) throws IOException{ // System.out.println("read file " + file.getCanonicalPath() ); String content = ""; try(BufferedReader br = new BufferedReader(new FileReader(file))){ String strLine; int counter = 0; while((strLine = br.readLine()) != null){ if(counter++ == lineCountre) { String columns[] = strLine.split("\t"); for(int i = start; i<=end; i++) content += columns[i-1]+"\t"; break; } } } return content; } // export the value that change with k. static void extractk(String folderName, String datasetName, int option) throws IOException { File folder = new File(folderName); int kvaluenum = 3; String []content = new String[kvaluenum];// dataset for (final File fileEntry : folder.listFiles()) { if (!fileEntry.isDirectory()) { String fileName = fileEntry.getName(); if(fileName.contains(datasetName)) { if(fileName.contains("10_Ball")) { content[0] = readContent(fileEntry, option); }else if(fileName.contains("100_Ball")) { content[1] = readContent(fileEntry, option); }else if(fileName.contains("1000_Ball")) { content[2] = readContent(fileEntry, option); } } } } for(int i = 1; i<=kvaluenum; i++) Util.write(folderName+"/plot/"+datasetName+"IncreasingK.txt", Integer.toString(i)+ "\t"+ content[i-1]+"\n"); } // export the value that change with k. static void extractDataScale(String folderName, String datasetName, int option, int k) throws IOException { File folder = new File(folderName); int kvaluenum = 5; String []content = new String[kvaluenum];// dataset for (final File fileEntry : folder.listFiles()) { if (!fileEntry.isDirectory()) { String fileName = fileEntry.getName(); String scaleset[] = fileName.split("_"); if(fileName.contains(datasetName) && !fileName.contains("index") && scaleset.length>1) { String scale = scaleset[1]; if(scale.equals("100")) { content[0] = readContent(fileEntry, option); }else if(scale.equals("1000")) { content[1] = readContent(fileEntry, option); }else if(scale.equals("10000")) { content[2] = readContent(fileEntry, option); }else if(scale.equals("100000")) { content[3] = readContent(fileEntry, option); }else if(scale.equals("1000000")) { content[4] = readContent(fileEntry, option); } } } } for(int i = 1; i<=kvaluenum; i++) Util.write(folderName+"/plot/"+datasetName+"IncreasingData"+Integer.valueOf(k)+".txt", Integer.toString(i)+ "\t"+ content[i-1]+"\n"); } /* * */ static void extrackIndex(String folderName, String datasetName, int option, int k) throws IOException { File folder = new File(folderName); int kvaluenum = 3; String []content = new String[kvaluenum];// dataset for (final File fileEntry : folder.listFiles()) { if (!fileEntry.isDirectory()) { String fileName = fileEntry.getName(); String scaleset[] = fileName.split("_"); if(fileName.contains(datasetName) && scaleset.length>2) { String scale = scaleset[4]; if(scaleset[3].equals(Integer.toString(k))) { if(scale.equals("BallMetric")) { content[0] = readContent(fileEntry, option); }else if(scale.equals("Mtree")) { content[1] = readContent(fileEntry, option); }else if(scale.equals("hkmtree")) { content[2] = readContent(fileEntry, option); } } } } } for(int i = 1; i<=kvaluenum; i++) Util.write(folderName+"/plot/"+datasetName+"IndexType"+Integer.valueOf(k)+".txt", Integer.toString(i)+ "\t"+ content[i-1]+"\n"); } /* * test */ static void extracDimension(String folderName, String datasetName, int option, int k) throws IOException { File folder = new File(folderName); int kvaluenum = 5; String []content = new String[kvaluenum];// dataset for (final File fileEntry : folder.listFiles()) { if (!fileEntry.isDirectory()) { String fileName = fileEntry.getName(); String scaleset[] = fileName.split("_"); if(fileName.contains(datasetName) && scaleset.length>2) { String scale = scaleset[2]; if (scaleset[3].equals(Integer.toString(k))) { if (scale.equals("10")) { content[0] = readContent(fileEntry, option); } else if (scale.equals("20")) { content[1] = readContent(fileEntry, option); } else if (scale.equals("30")) { content[2] = readContent(fileEntry, option); } else if (scale.equals("40")) { content[3] = readContent(fileEntry, option); } else if (scale.equals("50")) { content[4] = readContent(fileEntry, option); } } } } } for(int i = 1; i<=kvaluenum; i++) Util.write(folderName+"/plot/"+datasetName+"Dimension"+Integer.valueOf(k)+".txt", Integer.toString(i)+ "\t"+ content[i-1]+"\n"); } /* * extract the running time of different index with the increasing of capacity, */ static void extrackIndexCapacity(String folderName, String datasetName, int option, int k) throws IOException { File folder = new File(folderName); int kvaluenum = 6; // capacity number String []content = new String[kvaluenum];// dataset String []content_ball = new String[kvaluenum];// dataset for (final File fileEntry : folder.listFiles()) { if (!fileEntry.isDirectory()) { String fileName = fileEntry.getName(); String scaleset[] = fileName.split("_"); if(fileName.contains(datasetName) && scaleset.length>2) { String scale = scaleset[4]; if(scaleset[3].equals(Integer.toString(k))) { if (fileName.contains("10.log")) { if (scale.equals("HKT")) content[0] = readContent(fileEntry, option, 14, 16); else if (scale.equals("BallMetric")) { content_ball[0] = readContent(fileEntry, option, 14, 16); } } else if (fileName.contains("20.log")) { if (scale.equals("HKT")) content[1] = readContent(fileEntry, option, 14, 16); else if (scale.equals("BallMetric")) { content_ball[1] = readContent(fileEntry, option, 14, 16); } }else if (fileName.contains("30.log")) { if (scale.equals("HKT")) content[2] = readContent(fileEntry, option, 14, 16); else if (scale.equals("BallMetric")) { content_ball[2] = readContent(fileEntry, option, 14, 16); } }else if (fileName.contains("40.log")) { if (scale.equals("HKT")) content[3] = readContent(fileEntry, option, 14, 16); else if (scale.equals("BallMetric")) { content_ball[3] = readContent(fileEntry, option, 14, 16); } }else if (fileName.contains("50.log")) { if (scale.equals("HKT")) content[4] = readContent(fileEntry, option, 14, 16); else if (scale.equals("BallMetric")) { content_ball[4] = readContent(fileEntry, option, 14, 16); } }else if (fileName.contains("60.log")) { if (scale.equals("HKT")) content[5] = readContent(fileEntry, option, 14, 16); else if (scale.equals("BallMetric")) { content_ball[5] = readContent(fileEntry, option, 14, 16); } } } } } } for(int i = 1; i<=kvaluenum; i++) Util.write(folderName+"\\plot\\"+datasetName+"Capacity"+Integer.valueOf(k)+".txt", Integer.toString(i)+ "\t"+ content[i-1]+content_ball[i-1]+"\n"); } // option 0: total running time, 1: ratio, // 3: assignment time, 4, ratio // 6: refinement, 7, raito // 9: computations, 10, ratio // 12: boundCompares, 14: dataAccess, 16: boundUpdates, 18: memoryUsage //read existing files and store the data in a folder, then add the new ran data to update the score. public static void main(String[] args) throws IOException, KeySizeException, KeyDuplicateException { for (int kvalue = 10; kvalue <= 100; kvalue = kvalue * 10) { savePlotDataFile(args[0], 0, kvalue, "Ball", "runingtime" +Integer.valueOf(kvalue)+ ".txt"); savePlotDataFile(args[0], 1, kvalue, "Ball", "runingtimeratio" + Integer.valueOf(kvalue)+".txt"); savePlotDataFile(args[0], 3, kvalue, "Ball", "assigntime" +Integer.valueOf(kvalue)+ ".txt"); savePlotDataFile(args[0], 4, kvalue, "Ball", "assigntimeratio" + Integer.valueOf(kvalue)+".txt"); savePlotDataFile(args[0], 6, kvalue, "Ball", "refinetime" + Integer.valueOf(kvalue)+".txt"); savePlotDataFile(args[0], 7, kvalue, "Ball", "refineratio" + Integer.valueOf(kvalue)+".txt"); savePlotDataFile(args[0], 9, kvalue, "Ball", "computation" + Integer.valueOf(kvalue)+".txt"); savePlotDataFile(args[0], 10, kvalue, "Ball", "computationratio" + Integer.valueOf(kvalue)+".txt"); savePlotDataFile(args[0], 12, kvalue, "Ball", "boundCompares" + Integer.valueOf(kvalue)+".txt"); savePlotDataFile(args[0], 14, kvalue, "Ball", "dataAccess" + Integer.valueOf(kvalue)+".txt"); savePlotDataFile(args[0], 16, kvalue, "Ball", "boundUpdates" + Integer.valueOf(kvalue)+".txt"); savePlotDataFile(args[0], 18, kvalue, "Ball", "memoryUsage" + Integer.valueOf(kvalue)+".txt"); } /* extractk(args[0], "road", 1); extractDataScale(args[0], "NYC", 0, 100); extrackIndex(args[0], "road", 1, 100); extrackIndexCapacity(args[0], "NYC", 0, 10);// get the running time, all the index method. extracDimension(args[0], "covt", 0, 10);// get the running time, all the index method. extracDimension(args[0], "bigcross", 0, 10);// get the running time, all the index method. */ } }
14,198
0.581983
0.563882
325
41.686153
29.387594
150
false
false
0
0
0
0
0
0
3.664615
false
false
2
f81bc92e83820be922dc64bb138ac79709a964f5
10,960,756,540,550
2aa338f1c0f2513e0dc56d11c8371bc042035803
/newffms2-domain/src/main/java/com/personal/oyl/newffms/common/PaginationParameter.java
e3da7f0b58c4353d42682cae03180e05cf14d267
[]
no_license
OuYangLiang/newffms2
https://github.com/OuYangLiang/newffms2
5a5bf2492f237bdfcab70bb9b12f983aa2bc1714
e21db1ee420699864d8c3dbf9b8488ef4c970622
refs/heads/master
2021-01-20T22:12:09.556000
2019-02-20T14:19:28
2019-02-20T14:19:28
63,246,726
0
2
null
false
2019-02-20T14:19:29
2016-07-13T13:09:37
2018-10-20T08:40:42
2019-02-20T14:19:29
6,158
0
1
0
JavaScript
false
null
package com.personal.oyl.newffms.common; import java.util.Map; public class PaginationParameter { private int requestPage; private int sizePerPage; private String sortField; private String sortDir; public PaginationParameter(int requestPage, int sizePerPage) { super(); this.requestPage = requestPage; this.sizePerPage = sizePerPage; } public PaginationParameter(int requestPage, int sizePerPage, String sortField, String sortDir) { super(); this.requestPage = requestPage; this.sizePerPage = sizePerPage; this.sortField = sortField; this.sortDir = sortDir; } public int getRequestPage() { return requestPage; } public void setRequestPage(int requestPage) { this.requestPage = requestPage; } public int getSizePerPage() { return sizePerPage; } public void setSizePerPage(int sizePerPage) { this.sizePerPage = sizePerPage; } public String getSortField() { return sortField; } public void setSortField(String sortField) { this.sortField = sortField; } public String getSortDir() { return sortDir; } public void setSortDir(String sortDir) { this.sortDir = sortDir; } public void fillMap(Map<String, Object> target) { target.put("start", (requestPage - 1) * sizePerPage); target.put("sizePerPage", sizePerPage); target.put("sortField", sortField); target.put("sortDir", sortDir); } }
UTF-8
Java
1,557
java
PaginationParameter.java
Java
[]
null
[]
package com.personal.oyl.newffms.common; import java.util.Map; public class PaginationParameter { private int requestPage; private int sizePerPage; private String sortField; private String sortDir; public PaginationParameter(int requestPage, int sizePerPage) { super(); this.requestPage = requestPage; this.sizePerPage = sizePerPage; } public PaginationParameter(int requestPage, int sizePerPage, String sortField, String sortDir) { super(); this.requestPage = requestPage; this.sizePerPage = sizePerPage; this.sortField = sortField; this.sortDir = sortDir; } public int getRequestPage() { return requestPage; } public void setRequestPage(int requestPage) { this.requestPage = requestPage; } public int getSizePerPage() { return sizePerPage; } public void setSizePerPage(int sizePerPage) { this.sizePerPage = sizePerPage; } public String getSortField() { return sortField; } public void setSortField(String sortField) { this.sortField = sortField; } public String getSortDir() { return sortDir; } public void setSortDir(String sortDir) { this.sortDir = sortDir; } public void fillMap(Map<String, Object> target) { target.put("start", (requestPage - 1) * sizePerPage); target.put("sizePerPage", sizePerPage); target.put("sortField", sortField); target.put("sortDir", sortDir); } }
1,557
0.642903
0.642261
63
23.714285
20.956818
100
false
false
0
0
0
0
0
0
0.555556
false
false
2
2df65904f28313e1f766946be1b90476bc63b014
15,685,220,609,536
b9bf02c01cddaa489a22cabc327f3f2b473adcce
/src/org/stepic/java/Piece.java
8f32cfc25cd56131629116818e765b67c239e52b
[]
no_license
valeyko/stepic
https://github.com/valeyko/stepic
84436004bdd4e7c23df84dc932b65e79581fa6d6
249ff628fa396b43d86f458bdebbf3769551b434
refs/heads/master
2021-05-04T11:52:45.189000
2015-11-05T16:46:03
2015-11-05T16:46:03
43,697,754
0
2
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.stepic.java; public class Piece { private static String[] roles = {"Городничий", "Аммос Федорович", "Артемий Филиппович", "Лука Лукич"}; private static String[] textLines = { "Городничий: Я пригласил вас, господа, с тем, чтобы сообщить вам пренеприятное известие: к нам едет ревизор.", "Аммос Федорович: Как ревизор?", "Артемий Филиппович: Как ревизор?", "Городничий: Ревизор из Петербурга, инкогнито. И еще с секретным предписаньем.", "Аммос Федорович: Вот те на!", "Артемий Филиппович: Вот не было заботы, так подай!", "Лука Лукич: Господи боже! еще и с секретным предписаньем!" }; private static String printTextPerRole(String[] roles, String[] textLines) { StringBuilder[] textByRoles = new StringBuilder[roles.length]; for (int i = 0; i < roles.length; i++) { textByRoles[i] = new StringBuilder(roles[i] + ":"); } for (int i = 0; i < textLines.length; i++) { String[] splitLine = textLines[i].split(": ", 2); String role = splitLine[0]; String text = splitLine[1]; int j = 0; while (!roles[j].equals(role)) { j++; } textByRoles[j].append("\n" + (i + 1) + ") " + text); } String result = ""; for (StringBuilder line : textByRoles) { result += line + "\n\n"; } return result; } public static void main(String[] args) { System.out.println(printTextPerRole(roles, textLines)); } }
UTF-8
Java
1,974
java
Piece.java
Java
[ { "context": " private static String[] roles = {\"Городничий\", \"Аммос Федорович\", \"Артемий Филиппович\", \"Лука Лукич\"};\n privat", "end": 114, "score": 0.999858021736145, "start": 99, "tag": "NAME", "value": "Аммос Федорович" }, { "context": "ring[] roles = {\"Городничий\", \"Аммос Федорович\", \"Артемий Филиппович\", \"Лука Лукич\"};\n private static String[] text", "end": 136, "score": 0.9998337626457214, "start": 118, "tag": "NAME", "value": "Артемий Филиппович" }, { "context": "ничий\", \"Аммос Федорович\", \"Артемий Филиппович\", \"Лука Лукич\"};\n private static String[] textLines = {\n ", "end": 150, "score": 0.9996323585510254, "start": 140, "tag": "NAME", "value": "Лука Лукич" }, { "context": "тное известие: к нам едет ревизор.\",\n \"Аммос Федорович: Как ревизор?\",\n \"Артемий Филиппович: ", "end": 347, "score": 0.999850869178772, "start": 332, "tag": "NAME", "value": "Аммос Федорович" }, { "context": " \"Аммос Федорович: Как ревизор?\",\n \"Артемий Филиппович: Как ревизор?\",\n \"Городничий: Ревизор ", "end": 395, "score": 0.9997794032096863, "start": 377, "tag": "NAME", "value": "Артемий Филиппович" }, { "context": "о. И еще с секретным предписаньем.\",\n \"Аммос Федорович: Вот те на!\",\n \"Артемий Филиппович: Во", "end": 533, "score": 0.9998672604560852, "start": 518, "tag": "NAME", "value": "Аммос Федорович" }, { "context": " \"Аммос Федорович: Вот те на!\",\n \"Артемий Филиппович: Вот не было заботы, так подай!\",\n \"Лу", "end": 579, "score": 0.9997914433479309, "start": 561, "tag": "NAME", "value": "Артемий Филиппович" }, { "context": "ич: Вот не было заботы, так подай!\",\n \"Лука Лукич: Господи боже! еще и с секретным предписаньем!\"\n ", "end": 637, "score": 0.9994799494743347, "start": 627, "tag": "NAME", "value": "Лука Лукич" } ]
null
[]
package org.stepic.java; public class Piece { private static String[] roles = {"Городничий", "<NAME>", "<NAME>", "<NAME>"}; private static String[] textLines = { "Городничий: Я пригласил вас, господа, с тем, чтобы сообщить вам пренеприятное известие: к нам едет ревизор.", "<NAME>: Как ревизор?", "<NAME>: Как ревизор?", "Городничий: Ревизор из Петербурга, инкогнито. И еще с секретным предписаньем.", "<NAME>: Вот те на!", "<NAME>: Вот не было заботы, так подай!", "<NAME>: Господи боже! еще и с секретным предписаньем!" }; private static String printTextPerRole(String[] roles, String[] textLines) { StringBuilder[] textByRoles = new StringBuilder[roles.length]; for (int i = 0; i < roles.length; i++) { textByRoles[i] = new StringBuilder(roles[i] + ":"); } for (int i = 0; i < textLines.length; i++) { String[] splitLine = textLines[i].split(": ", 2); String role = splitLine[0]; String text = splitLine[1]; int j = 0; while (!roles[j].equals(role)) { j++; } textByRoles[j].append("\n" + (i + 1) + ") " + text); } String result = ""; for (StringBuilder line : textByRoles) { result += line + "\n\n"; } return result; } public static void main(String[] args) { System.out.println(printTextPerRole(roles, textLines)); } }
1,792
0.559406
0.555074
43
36.581394
30.517424
122
false
false
0
0
0
0
0
0
0.837209
false
false
2
ba6a2d78f3983ffd56e0696eece5b19538d7f0ff
9,216,999,872,171
39b856c90b989cdbe48aa30171dd61baeb0ef6aa
/src/ru/geekbrains/competition/competitors/Competitor.java
1c15236c98722d94332cb4b85b6efed0238e4b18
[]
no_license
smeleyka/GeekbrainsJava2Lesson1-test
https://github.com/smeleyka/GeekbrainsJava2Lesson1-test
d8e0f5eea53ac88d6dd60de4b883ce109b60d3ba
ea17855ad219534cbf960be48adb4fd06258a769
refs/heads/master
2021-01-20T01:17:20.592000
2017-04-24T14:30:41
2017-04-24T14:30:41
89,250,480
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ru.geekbrains.competition.competitors; /** * Created by smeleyka on 24.04.17. */ public interface Competitor { String getName(); boolean isOnDistance(); void run(int runDist); void jump(int jumpDist); void swim(int swimDist); }
UTF-8
Java
259
java
Competitor.java
Java
[ { "context": "brains.competition.competitors;\n\n/**\n * Created by smeleyka on 24.04.17.\n */\npublic interface Competitor {\n ", "end": 74, "score": 0.9996748566627502, "start": 66, "tag": "USERNAME", "value": "smeleyka" } ]
null
[]
package ru.geekbrains.competition.competitors; /** * Created by smeleyka on 24.04.17. */ public interface Competitor { String getName(); boolean isOnDistance(); void run(int runDist); void jump(int jumpDist); void swim(int swimDist); }
259
0.687259
0.664093
12
20.583334
14.522731
46
false
false
0
0
0
0
0
0
0.5
false
false
2
827d4197063152b65408ca863ed485dcfff7c406
31,086,973,300,062
9c811483431c1a7b77f712af7f06ff017cc4ab75
/mainModule/src/main/java/by/azmd/mapper/UserMapper.java
9da85eb9df8f2b129bb63e31a276d7f2cdc14760
[]
no_license
araz99/bookroom
https://github.com/araz99/bookroom
8c309d72faad05818d7196d09186b712797f92e5
17abb5bce00835f9eaa9ccfdd8f91df2b25fbd43
refs/heads/master
2023-07-11T00:03:02.341000
2021-08-20T00:16:05
2021-08-20T00:16:05
342,847,797
0
0
null
false
2021-03-11T15:16:48
2021-02-27T12:08:05
2021-03-10T19:46:59
2021-03-11T15:16:47
28
0
0
0
Java
false
false
package by.azmd.mapper; import by.azmd.dto.UserDTO; import by.azmd.entity.User; import com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.stereotype.Component; import java.util.Map; @Component public class UserMapper implements DtoMapper<UserDTO, User> { private final ObjectMapper mapper; Map public UserMapper(ObjectMapper mapper) { this.mapper = mapper; } @Override public UserDTO toDTO(User entity) { return mapper.convertValue(entity, UserDTO.class); } @Override public User toEntity(UserDTO dto) { return mapper.convertValue(dto, User.class); } }
UTF-8
Java
644
java
UserMapper.java
Java
[]
null
[]
package by.azmd.mapper; import by.azmd.dto.UserDTO; import by.azmd.entity.User; import com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.stereotype.Component; import java.util.Map; @Component public class UserMapper implements DtoMapper<UserDTO, User> { private final ObjectMapper mapper; Map public UserMapper(ObjectMapper mapper) { this.mapper = mapper; } @Override public UserDTO toDTO(User entity) { return mapper.convertValue(entity, UserDTO.class); } @Override public User toEntity(UserDTO dto) { return mapper.convertValue(dto, User.class); } }
644
0.715838
0.715838
28
22
20.17424
61
false
false
0
0
0
0
0
0
0.464286
false
false
2
aaf93cdba0187c7f83a1bae483468479462c3b7f
29,721,173,711,983
7c4ece985a9b727e551d51b4a63bd919fc938ac0
/RxTools-library/src/main/java/com/vondear/rxtools/view/RxTitle.java
e51ecf8646de788de8302c52d249dd2231e0da32
[ "Apache-2.0" ]
permissive
duboAndroid/RxTools-master
https://github.com/duboAndroid/RxTools-master
caf57dbd9ae6a7d2463b2a79012dc0a859de2b6a
dfa9549ce577dac661d0360af7f90a4dd16fa232
refs/heads/master
2021-07-17T13:54:48.816000
2017-10-25T10:37:48
2017-10-25T10:37:48
108,255,984
166
41
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.vondear.rxtools.view; import android.app.Activity; import android.content.Context; import android.content.res.TypedArray; import android.util.AttributeSet; import android.util.TypedValue; import android.view.LayoutInflater; import android.view.View; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; import com.vondear.rxtools.R; import com.vondear.rxtools.RxDataTool; import com.vondear.rxtools.RxImageTool; import com.vondear.rxtools.RxKeyboardTool; /** * @author by vondear on 2017/1/2. */ public class RxTitle extends FrameLayout { //*******************************************控件start****************************************** private RelativeLayout mRootLayout;//根布局 private RxTextAutoZoom mTvTitle;//Title的TextView控件 private LinearLayout mLlLeft;//左边布局 private ImageView mIvLeft;//左边ImageView控件 private TextView mTvLeft;//左边TextView控件 private LinearLayout mLlRight;//右边布局 private ImageView mIvRight;//右边ImageView控件 private TextView mTvRight;//右边TextView控件 //===========================================控件end============================================= //*******************************************属性start******************************************* private String mTitle;//Title文字 private int mTitleColor;//Title字体颜色 private int mTitleSize;//Title字体大小 private boolean mTitleVisibility;//Title是否显示 private int mLeftIcon;//左边 ICON 引用的资源ID private int mRightIcon;//右边 ICON 引用的资源ID private boolean mLeftIconVisibility;//左边 ICON 是否显示 private boolean mRightIconVisibility;//右边 ICON 是否显示 private String mLeftText;//左边文字 private int mLeftTextColor;//左边字体颜色 private int mLeftTextSize;//左边字体大小 private boolean mLeftTextVisibility;//左边文字是否显示 private String mRightText;//右边文字 private int mRightTextColor;//右边字体颜色 private int mRightTextSize;//右边字体大小 private boolean mRightTextVisibility;//右边文字是否显示 //===========================================属性end============================================= public RxTitle(Context context) { super(context); } public RxTitle(Context context, AttributeSet attrs) { super(context, attrs); //导入布局 initView(context, attrs); } private void initView(final Context context, AttributeSet attrs) { LayoutInflater.from(context).inflate(R.layout.include_rx_title, this); mRootLayout = (RelativeLayout) findViewById(R.id.root_layout); mTvTitle = (RxTextAutoZoom) findViewById(R.id.tv_rx_title); mLlLeft = (LinearLayout) findViewById(R.id.ll_left); mIvLeft = (ImageView) findViewById(R.id.iv_left); mIvRight = (ImageView) findViewById(R.id.iv_right); mLlRight = (LinearLayout) findViewById(R.id.ll_right); mTvLeft = (TextView) findViewById(R.id.tv_left); mTvRight = (TextView) findViewById(R.id.tv_right); //获得这个控件对应的属性。 TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.RxTitle); try { //获得属性值 //getColor(R.styleable.RxTitle_RxBackground, getResources().getColor(R.color.transparent)) mTitle = a.getString(R.styleable.RxTitle_title);//标题 mTitleColor = a.getColor(R.styleable.RxTitle_titleColor, getResources().getColor(R.color.white));//标题颜色 mTitleSize = a.getDimensionPixelSize(R.styleable.RxTitle_titleSize, RxImageTool.dip2px(20));//标题字体大小 //TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 16, getResources().getDisplayMetrics()) mTitleVisibility = a.getBoolean(R.styleable.RxTitle_titleVisibility, true); mLeftIcon = a.getResourceId(R.styleable.RxTitle_leftIcon, R.drawable.previous_icon);//左边图标 mRightIcon = a.getResourceId(R.styleable.RxTitle_rightIcon, R.drawable.set);//右边图标 mLeftIconVisibility = a.getBoolean(R.styleable.RxTitle_leftIconVisibility, true);//左边图标是否显示 mRightIconVisibility = a.getBoolean(R.styleable.RxTitle_rightIconVisibility, false);//右边图标是否显示 mLeftText = a.getString(R.styleable.RxTitle_leftText); mLeftTextColor = a.getColor(R.styleable.RxTitle_leftTextColor, getResources().getColor(R.color.white));//左边字体颜色 mLeftTextSize = a.getDimensionPixelSize(R.styleable.RxTitle_leftTextSize, RxImageTool.dip2px(8));//标题字体大小 mLeftTextVisibility = a.getBoolean(R.styleable.RxTitle_leftTextVisibility, false); mRightText = a.getString(R.styleable.RxTitle_rightText); mRightTextColor = a.getColor(R.styleable.RxTitle_rightTextColor, getResources().getColor(R.color.white));//右边字体颜色 mRightTextSize = a.getDimensionPixelSize(R.styleable.RxTitle_rightTextSize, RxImageTool.dip2px(8));//标题字体大小 mRightTextVisibility = a.getBoolean(R.styleable.RxTitle_rightTextVisibility, false); } finally { //回收这个对象 a.recycle(); } //******************************************************************************************以下属性初始化 if (!RxDataTool.isNullString(mTitle)) { setTitle(mTitle); } if (mTitleColor != 0) { setTitleColor(mTitleColor); } if (mTitleSize != 0) { setTitleSize(mTitleSize); } if (mLeftIcon != 0) { setLeftIcon(mLeftIcon); } if (mRightIcon != 0) { setRightIcon(mRightIcon); } setTitleVisibility(mTitleVisibility); setLeftText(mLeftText); setLeftTextColor(mLeftTextColor); setLeftTextSize(mLeftTextSize); setLeftTextVisibility(mLeftTextVisibility); setRightText(mRightText); setRightTextColor(mRightTextColor); setRightTextSize(mRightTextSize); setRightTextVisibility(mRightTextVisibility); setLeftIconVisibility(mLeftIconVisibility); setRightIconVisibility(mRightIconVisibility); initAutoFitEditText(); //==========================================================================================以上为属性初始化 } private void initAutoFitEditText() { mTvTitle.clearFocus(); mTvTitle.setEnabled(false); mTvTitle.setFocusableInTouchMode(false); mTvTitle.setFocusable(false); mTvTitle.setEnableSizeCache(false); //might cause crash on some devices mTvTitle.setMovementMethod(null); // can be added after layout inflation; mTvTitle.setMaxHeight(RxImageTool.dip2px(55f)); //don't forget to add min text size programmatically mTvTitle.setMinTextSize(37f); try { RxTextAutoZoom.setNormalization((Activity) getContext(), mRootLayout, mTvTitle); RxKeyboardTool.hideSoftInput((Activity) getContext()); } catch (Exception e) { } } //**********************************************************************************************以下为get方法 public RelativeLayout getRootLayout() { return mRootLayout; } public RxTextAutoZoom getTvTitle() { return mTvTitle; } public LinearLayout getLlLeft() { return mLlLeft; } public ImageView getIvLeft() { return mIvLeft; } public TextView getTvLeft() { return mTvLeft; } public LinearLayout getLlRight() { return mLlRight; } public ImageView getIvRight() { return mIvRight; } public TextView getTvRight() { return mTvRight; } public boolean isTitleVisibility() { return mTitleVisibility; } public void setTitleVisibility(boolean titleVisibility) { mTitleVisibility = titleVisibility; if (mTitleVisibility) { mTvTitle.setVisibility(VISIBLE); } else { mTvTitle.setVisibility(GONE); } } public String getLeftText() { return mLeftText; } //**********************************************************************************************以下为 左边文字 相关方法 public void setLeftText(String leftText) { mLeftText = leftText; mTvLeft.setText(mLeftText); } public int getLeftTextColor() { return mLeftTextColor; } public void setLeftTextColor(int leftTextColor) { mLeftTextColor = leftTextColor; mTvLeft.setTextColor(mLeftTextColor); } public int getLeftTextSize() { return mLeftTextSize; } public void setLeftTextSize(int leftTextSize) { mLeftTextSize = leftTextSize; mTvLeft.setTextSize(TypedValue.COMPLEX_UNIT_PX, mLeftTextSize); } public boolean isLeftTextVisibility() { return mLeftTextVisibility; } public void setLeftTextVisibility(boolean leftTextVisibility) { mLeftTextVisibility = leftTextVisibility; if (mLeftTextVisibility) { mTvLeft.setVisibility(VISIBLE); } else { mTvLeft.setVisibility(GONE); } } public String getRightText() { return mRightText; } //**********************************************************************************************以下为 右边文字 相关方法 public void setRightText(String rightText) { mRightText = rightText; mTvRight.setText(mRightText); } public int getRightTextColor() { return mRightTextColor; } public void setRightTextColor(int rightTextColor) { mRightTextColor = rightTextColor; mTvRight.setTextColor(mRightTextColor); } public int getRightTextSize() { return mRightTextSize; } public void setRightTextSize(int rightTextSize) { mRightTextSize = rightTextSize; mTvRight.setTextSize(TypedValue.COMPLEX_UNIT_PX, mRightTextSize); } //==============================================================================================以上为get方法 //**********************************************************************************************以下为set方法 public boolean isRightTextVisibility() { return mRightTextVisibility; } public void setRightTextVisibility(boolean rightTextVisibility) { mRightTextVisibility = rightTextVisibility; if (mRightTextVisibility) { mTvRight.setVisibility(VISIBLE); if (isRightIconVisibility()) { mTvRight.setPadding(0, 0, 0, 0); } } else { mTvRight.setVisibility(GONE); } } public String getTitle() { return mTitle; } //**********************************************************************************************以下为Title相关方法 public void setTitle(String title) { mTitle = title; mTvTitle.setText(mTitle); } public int getTitleColor() { return mTitleColor; } public void setTitleColor(int titleColor) { mTitleColor = titleColor; mTvTitle.setTextColor(mTitleColor); } public int getTitleSize() { return mTitleSize; } public void setTitleSize(int titleSize) { mTitleSize = titleSize; mTvTitle.setTextSize(TypedValue.COMPLEX_UNIT_PX, mTitleSize); } public int getLeftIcon() { return mLeftIcon; } public void setLeftIcon(int leftIcon) { mLeftIcon = leftIcon; mIvLeft.setImageResource(mLeftIcon); } public int getRightIcon() { return mRightIcon; } //==============================================================================================以上为 Title 相关方法 public void setRightIcon(int rightIcon) { mRightIcon = rightIcon; mIvRight.setImageResource(mRightIcon); } public boolean isLeftIconVisibility() { return mLeftIconVisibility; } public void setLeftIconVisibility(boolean leftIconVisibility) { mLeftIconVisibility = leftIconVisibility; if (mLeftIconVisibility) { mIvLeft.setVisibility(VISIBLE); } else { mIvLeft.setVisibility(GONE); } } public boolean isRightIconVisibility() { return mRightIconVisibility; } //==============================================================================================以上为 左边文字 相关方法 public void setRightIconVisibility(boolean rightIconVisibility) { mRightIconVisibility = rightIconVisibility; if (mRightIconVisibility) { mIvRight.setVisibility(VISIBLE); } else { mIvRight.setVisibility(GONE); } } public void setLeftFinish(final Activity activity) { mLlLeft.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { activity.finish(); } }); } public void setLeftOnClickListener(OnClickListener onClickListener) { mLlLeft.setOnClickListener(onClickListener); } public void setRightOnClickListener(OnClickListener onClickListener) { mLlRight.setOnClickListener(onClickListener); } //==============================================================================================以上为 右边文字 相关方法 public void setLeftTextOnClickListener(OnClickListener onClickListener) { mTvLeft.setOnClickListener(onClickListener); } public void setRightTextOnClickListener(OnClickListener onClickListener) { mTvRight.setOnClickListener(onClickListener); } public void setLeftIconOnClickListener(OnClickListener onClickListener) { mIvLeft.setOnClickListener(onClickListener); } public void setRightIconOnClickListener(OnClickListener onClickListener) { mIvRight.setOnClickListener(onClickListener); } //==============================================================================================以上为set方法 }
UTF-8
Java
14,571
java
RxTitle.java
Java
[ { "context": "vondear.rxtools.RxKeyboardTool;\n\n/**\n * @author by vondear on 2017/1/2.\n */\n\npublic class RxTitle extends Fr", "end": 616, "score": 0.9994867444038391, "start": 609, "tag": "USERNAME", "value": "vondear" } ]
null
[]
package com.vondear.rxtools.view; import android.app.Activity; import android.content.Context; import android.content.res.TypedArray; import android.util.AttributeSet; import android.util.TypedValue; import android.view.LayoutInflater; import android.view.View; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; import com.vondear.rxtools.R; import com.vondear.rxtools.RxDataTool; import com.vondear.rxtools.RxImageTool; import com.vondear.rxtools.RxKeyboardTool; /** * @author by vondear on 2017/1/2. */ public class RxTitle extends FrameLayout { //*******************************************控件start****************************************** private RelativeLayout mRootLayout;//根布局 private RxTextAutoZoom mTvTitle;//Title的TextView控件 private LinearLayout mLlLeft;//左边布局 private ImageView mIvLeft;//左边ImageView控件 private TextView mTvLeft;//左边TextView控件 private LinearLayout mLlRight;//右边布局 private ImageView mIvRight;//右边ImageView控件 private TextView mTvRight;//右边TextView控件 //===========================================控件end============================================= //*******************************************属性start******************************************* private String mTitle;//Title文字 private int mTitleColor;//Title字体颜色 private int mTitleSize;//Title字体大小 private boolean mTitleVisibility;//Title是否显示 private int mLeftIcon;//左边 ICON 引用的资源ID private int mRightIcon;//右边 ICON 引用的资源ID private boolean mLeftIconVisibility;//左边 ICON 是否显示 private boolean mRightIconVisibility;//右边 ICON 是否显示 private String mLeftText;//左边文字 private int mLeftTextColor;//左边字体颜色 private int mLeftTextSize;//左边字体大小 private boolean mLeftTextVisibility;//左边文字是否显示 private String mRightText;//右边文字 private int mRightTextColor;//右边字体颜色 private int mRightTextSize;//右边字体大小 private boolean mRightTextVisibility;//右边文字是否显示 //===========================================属性end============================================= public RxTitle(Context context) { super(context); } public RxTitle(Context context, AttributeSet attrs) { super(context, attrs); //导入布局 initView(context, attrs); } private void initView(final Context context, AttributeSet attrs) { LayoutInflater.from(context).inflate(R.layout.include_rx_title, this); mRootLayout = (RelativeLayout) findViewById(R.id.root_layout); mTvTitle = (RxTextAutoZoom) findViewById(R.id.tv_rx_title); mLlLeft = (LinearLayout) findViewById(R.id.ll_left); mIvLeft = (ImageView) findViewById(R.id.iv_left); mIvRight = (ImageView) findViewById(R.id.iv_right); mLlRight = (LinearLayout) findViewById(R.id.ll_right); mTvLeft = (TextView) findViewById(R.id.tv_left); mTvRight = (TextView) findViewById(R.id.tv_right); //获得这个控件对应的属性。 TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.RxTitle); try { //获得属性值 //getColor(R.styleable.RxTitle_RxBackground, getResources().getColor(R.color.transparent)) mTitle = a.getString(R.styleable.RxTitle_title);//标题 mTitleColor = a.getColor(R.styleable.RxTitle_titleColor, getResources().getColor(R.color.white));//标题颜色 mTitleSize = a.getDimensionPixelSize(R.styleable.RxTitle_titleSize, RxImageTool.dip2px(20));//标题字体大小 //TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 16, getResources().getDisplayMetrics()) mTitleVisibility = a.getBoolean(R.styleable.RxTitle_titleVisibility, true); mLeftIcon = a.getResourceId(R.styleable.RxTitle_leftIcon, R.drawable.previous_icon);//左边图标 mRightIcon = a.getResourceId(R.styleable.RxTitle_rightIcon, R.drawable.set);//右边图标 mLeftIconVisibility = a.getBoolean(R.styleable.RxTitle_leftIconVisibility, true);//左边图标是否显示 mRightIconVisibility = a.getBoolean(R.styleable.RxTitle_rightIconVisibility, false);//右边图标是否显示 mLeftText = a.getString(R.styleable.RxTitle_leftText); mLeftTextColor = a.getColor(R.styleable.RxTitle_leftTextColor, getResources().getColor(R.color.white));//左边字体颜色 mLeftTextSize = a.getDimensionPixelSize(R.styleable.RxTitle_leftTextSize, RxImageTool.dip2px(8));//标题字体大小 mLeftTextVisibility = a.getBoolean(R.styleable.RxTitle_leftTextVisibility, false); mRightText = a.getString(R.styleable.RxTitle_rightText); mRightTextColor = a.getColor(R.styleable.RxTitle_rightTextColor, getResources().getColor(R.color.white));//右边字体颜色 mRightTextSize = a.getDimensionPixelSize(R.styleable.RxTitle_rightTextSize, RxImageTool.dip2px(8));//标题字体大小 mRightTextVisibility = a.getBoolean(R.styleable.RxTitle_rightTextVisibility, false); } finally { //回收这个对象 a.recycle(); } //******************************************************************************************以下属性初始化 if (!RxDataTool.isNullString(mTitle)) { setTitle(mTitle); } if (mTitleColor != 0) { setTitleColor(mTitleColor); } if (mTitleSize != 0) { setTitleSize(mTitleSize); } if (mLeftIcon != 0) { setLeftIcon(mLeftIcon); } if (mRightIcon != 0) { setRightIcon(mRightIcon); } setTitleVisibility(mTitleVisibility); setLeftText(mLeftText); setLeftTextColor(mLeftTextColor); setLeftTextSize(mLeftTextSize); setLeftTextVisibility(mLeftTextVisibility); setRightText(mRightText); setRightTextColor(mRightTextColor); setRightTextSize(mRightTextSize); setRightTextVisibility(mRightTextVisibility); setLeftIconVisibility(mLeftIconVisibility); setRightIconVisibility(mRightIconVisibility); initAutoFitEditText(); //==========================================================================================以上为属性初始化 } private void initAutoFitEditText() { mTvTitle.clearFocus(); mTvTitle.setEnabled(false); mTvTitle.setFocusableInTouchMode(false); mTvTitle.setFocusable(false); mTvTitle.setEnableSizeCache(false); //might cause crash on some devices mTvTitle.setMovementMethod(null); // can be added after layout inflation; mTvTitle.setMaxHeight(RxImageTool.dip2px(55f)); //don't forget to add min text size programmatically mTvTitle.setMinTextSize(37f); try { RxTextAutoZoom.setNormalization((Activity) getContext(), mRootLayout, mTvTitle); RxKeyboardTool.hideSoftInput((Activity) getContext()); } catch (Exception e) { } } //**********************************************************************************************以下为get方法 public RelativeLayout getRootLayout() { return mRootLayout; } public RxTextAutoZoom getTvTitle() { return mTvTitle; } public LinearLayout getLlLeft() { return mLlLeft; } public ImageView getIvLeft() { return mIvLeft; } public TextView getTvLeft() { return mTvLeft; } public LinearLayout getLlRight() { return mLlRight; } public ImageView getIvRight() { return mIvRight; } public TextView getTvRight() { return mTvRight; } public boolean isTitleVisibility() { return mTitleVisibility; } public void setTitleVisibility(boolean titleVisibility) { mTitleVisibility = titleVisibility; if (mTitleVisibility) { mTvTitle.setVisibility(VISIBLE); } else { mTvTitle.setVisibility(GONE); } } public String getLeftText() { return mLeftText; } //**********************************************************************************************以下为 左边文字 相关方法 public void setLeftText(String leftText) { mLeftText = leftText; mTvLeft.setText(mLeftText); } public int getLeftTextColor() { return mLeftTextColor; } public void setLeftTextColor(int leftTextColor) { mLeftTextColor = leftTextColor; mTvLeft.setTextColor(mLeftTextColor); } public int getLeftTextSize() { return mLeftTextSize; } public void setLeftTextSize(int leftTextSize) { mLeftTextSize = leftTextSize; mTvLeft.setTextSize(TypedValue.COMPLEX_UNIT_PX, mLeftTextSize); } public boolean isLeftTextVisibility() { return mLeftTextVisibility; } public void setLeftTextVisibility(boolean leftTextVisibility) { mLeftTextVisibility = leftTextVisibility; if (mLeftTextVisibility) { mTvLeft.setVisibility(VISIBLE); } else { mTvLeft.setVisibility(GONE); } } public String getRightText() { return mRightText; } //**********************************************************************************************以下为 右边文字 相关方法 public void setRightText(String rightText) { mRightText = rightText; mTvRight.setText(mRightText); } public int getRightTextColor() { return mRightTextColor; } public void setRightTextColor(int rightTextColor) { mRightTextColor = rightTextColor; mTvRight.setTextColor(mRightTextColor); } public int getRightTextSize() { return mRightTextSize; } public void setRightTextSize(int rightTextSize) { mRightTextSize = rightTextSize; mTvRight.setTextSize(TypedValue.COMPLEX_UNIT_PX, mRightTextSize); } //==============================================================================================以上为get方法 //**********************************************************************************************以下为set方法 public boolean isRightTextVisibility() { return mRightTextVisibility; } public void setRightTextVisibility(boolean rightTextVisibility) { mRightTextVisibility = rightTextVisibility; if (mRightTextVisibility) { mTvRight.setVisibility(VISIBLE); if (isRightIconVisibility()) { mTvRight.setPadding(0, 0, 0, 0); } } else { mTvRight.setVisibility(GONE); } } public String getTitle() { return mTitle; } //**********************************************************************************************以下为Title相关方法 public void setTitle(String title) { mTitle = title; mTvTitle.setText(mTitle); } public int getTitleColor() { return mTitleColor; } public void setTitleColor(int titleColor) { mTitleColor = titleColor; mTvTitle.setTextColor(mTitleColor); } public int getTitleSize() { return mTitleSize; } public void setTitleSize(int titleSize) { mTitleSize = titleSize; mTvTitle.setTextSize(TypedValue.COMPLEX_UNIT_PX, mTitleSize); } public int getLeftIcon() { return mLeftIcon; } public void setLeftIcon(int leftIcon) { mLeftIcon = leftIcon; mIvLeft.setImageResource(mLeftIcon); } public int getRightIcon() { return mRightIcon; } //==============================================================================================以上为 Title 相关方法 public void setRightIcon(int rightIcon) { mRightIcon = rightIcon; mIvRight.setImageResource(mRightIcon); } public boolean isLeftIconVisibility() { return mLeftIconVisibility; } public void setLeftIconVisibility(boolean leftIconVisibility) { mLeftIconVisibility = leftIconVisibility; if (mLeftIconVisibility) { mIvLeft.setVisibility(VISIBLE); } else { mIvLeft.setVisibility(GONE); } } public boolean isRightIconVisibility() { return mRightIconVisibility; } //==============================================================================================以上为 左边文字 相关方法 public void setRightIconVisibility(boolean rightIconVisibility) { mRightIconVisibility = rightIconVisibility; if (mRightIconVisibility) { mIvRight.setVisibility(VISIBLE); } else { mIvRight.setVisibility(GONE); } } public void setLeftFinish(final Activity activity) { mLlLeft.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { activity.finish(); } }); } public void setLeftOnClickListener(OnClickListener onClickListener) { mLlLeft.setOnClickListener(onClickListener); } public void setRightOnClickListener(OnClickListener onClickListener) { mLlRight.setOnClickListener(onClickListener); } //==============================================================================================以上为 右边文字 相关方法 public void setLeftTextOnClickListener(OnClickListener onClickListener) { mTvLeft.setOnClickListener(onClickListener); } public void setRightTextOnClickListener(OnClickListener onClickListener) { mTvRight.setOnClickListener(onClickListener); } public void setLeftIconOnClickListener(OnClickListener onClickListener) { mIvLeft.setOnClickListener(onClickListener); } public void setRightIconOnClickListener(OnClickListener onClickListener) { mIvRight.setOnClickListener(onClickListener); } //==============================================================================================以上为set方法 }
14,571
0.592951
0.590945
446
30.298206
30.189215
125
false
false
0
0
0
0
96
0.040977
0.446188
false
false
2
5e6743307f442b7dc1cb5b121d0ed962af526db7
1,614,907,736,055
2f4bf48aa677a94a3979255d9019f48d045c979c
/Chapter4/src/com/polymorphism/Manager.java
59f14813f3b56b4fb92ccc7530195b2c2c343204
[]
no_license
filiumbelli/Tim-Buchalcka-Course-Notes
https://github.com/filiumbelli/Tim-Buchalcka-Course-Notes
2f602e42ccb83f0b670d4b5d9428cf6d7bd81e08
ee4c8086080390a8472c72c2a7bef2c997787439
refs/heads/master
2023-04-06T07:39:06.860000
2021-04-07T19:21:20
2021-04-07T19:21:20
355,657,786
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.polymorphism; public class Manager extends Employee{ private double bonus; public Manager(double salary, String name,double bonus) { super(salary, name); this.bonus = bonus; } public double getSalary(){ return (super.getSalary() + bonus); } public void setBonus(double bonus){ this.bonus = bonus; } }
UTF-8
Java
378
java
Manager.java
Java
[]
null
[]
package com.polymorphism; public class Manager extends Employee{ private double bonus; public Manager(double salary, String name,double bonus) { super(salary, name); this.bonus = bonus; } public double getSalary(){ return (super.getSalary() + bonus); } public void setBonus(double bonus){ this.bonus = bonus; } }
378
0.626984
0.626984
19
18.894737
18.093019
61
false
false
0
0
0
0
0
0
0.473684
false
false
2
eb382eccad3fa9d2f80c72d417c2df5cb0f1495e
24,524,263,264,508
abb7b70871975297153956c818eed958365101ad
/src/main/java/edu/dmacc/codedsm/finalproject/DefaultPayrollService.java
12c2a8dcc1ee6a6550a8910a3d4eb88f8c743159
[]
no_license
rlogden/FinalProject
https://github.com/rlogden/FinalProject
8230c3ccfa251d12f8bcda215c1807c98ad695bd
c22d1652fecb25599dd36f5e720104ddc2ac655c
refs/heads/master
2020-05-21T02:52:03.330000
2019-05-20T03:29:44
2019-05-20T03:29:44
185,886,495
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package edu.dmacc.codedsm.finalproject; import java.io.*; import java.text.NumberFormat; import java.util.HashMap; public class DefaultPayrollService implements PayrollService { private EmployeeRepository repository; public DefaultPayrollService(EmployeeRepository repository) { this.repository = repository; } @Override public void calculatePayroll() { HashMap<Integer, PaidEmployee> paidEmployees = new HashMap<>(); PrintStream out = null; for (Employee employee : repository.getRepEmployeeList().values()) { Double amountPaid; amountPaid = employee.getHoursWorked() * employee.getHourlyRate() / 1.2; NumberFormat formatter = NumberFormat.getCurrencyInstance(); PaidEmployee storeEmployee = new PaidEmployee(employee.getName(), formatter.format(amountPaid)); paidEmployees.put(employee.getId(), storeEmployee); } try { out = new PrintStream(new File("payroll_results.txt")); for (HashMap.Entry<Integer, PaidEmployee> entry : paidEmployees.entrySet()) { Integer key = entry.getKey(); Object value = entry.getValue(); out.print("ID: " + key.toString() + "\n" + value.toString() + "\n"); } } catch(IOException e) { System.out.println("IOException : " + e); } finally { if (out != null) { out.close(); } } } }
UTF-8
Java
1,515
java
DefaultPayrollService.java
Java
[]
null
[]
package edu.dmacc.codedsm.finalproject; import java.io.*; import java.text.NumberFormat; import java.util.HashMap; public class DefaultPayrollService implements PayrollService { private EmployeeRepository repository; public DefaultPayrollService(EmployeeRepository repository) { this.repository = repository; } @Override public void calculatePayroll() { HashMap<Integer, PaidEmployee> paidEmployees = new HashMap<>(); PrintStream out = null; for (Employee employee : repository.getRepEmployeeList().values()) { Double amountPaid; amountPaid = employee.getHoursWorked() * employee.getHourlyRate() / 1.2; NumberFormat formatter = NumberFormat.getCurrencyInstance(); PaidEmployee storeEmployee = new PaidEmployee(employee.getName(), formatter.format(amountPaid)); paidEmployees.put(employee.getId(), storeEmployee); } try { out = new PrintStream(new File("payroll_results.txt")); for (HashMap.Entry<Integer, PaidEmployee> entry : paidEmployees.entrySet()) { Integer key = entry.getKey(); Object value = entry.getValue(); out.print("ID: " + key.toString() + "\n" + value.toString() + "\n"); } } catch(IOException e) { System.out.println("IOException : " + e); } finally { if (out != null) { out.close(); } } } }
1,515
0.60462
0.6033
44
33.454544
29.469904
108
false
false
0
0
0
0
0
0
0.522727
false
false
2
6d8ae315faf09ef2015a4457c5b4ff31c88420b8
6,975,026,919,402
5039bd79b96a5b3df3bf7f198239508e923842fa
/Deliv1/app/src/main/java/com/ahhhh/deliv1/Administrator.java
4ef109d4f67f4759a69996c92a58f71e06167331
[]
no_license
s-glmxmd/SEG2105_GroupProj
https://github.com/s-glmxmd/SEG2105_GroupProj
7f89ad376a7df2a4bd3cb62f399735453e01a13a
294da2ef6ed0a89a226d9b199bbf13413a7bc43d
refs/heads/master
2020-03-29T05:59:16.371000
2018-12-06T05:07:43
2018-12-06T05:07:43
149,604,264
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.ahhhh.deliv1; public class Administrator extends UserAccount { public Administrator(String username, String password, String firstName, String lastName){ super(username,password,firstName,lastName); } }
UTF-8
Java
232
java
Administrator.java
Java
[]
null
[]
package com.ahhhh.deliv1; public class Administrator extends UserAccount { public Administrator(String username, String password, String firstName, String lastName){ super(username,password,firstName,lastName); } }
232
0.762931
0.758621
7
32.142857
32.21104
94
false
false
0
0
0
0
0
0
1.142857
false
false
2
3280bf658239174bcceaf78e358825bd591b9f84
919,123,040,173
fc2d1b5360c1ad469c5805c4dced2d1123bbf8b1
/src/Controller/UpdateUserController.java
7a5b7862643652383a4ad16b53220ff16fdb9100
[]
no_license
1872033/Tubes_PBO2_Bengkel
https://github.com/1872033/Tubes_PBO2_Bengkel
6f8a8b67c5de050e6dbabe9ee3e066c6c0f591a2
b2161c89cbd393e77b507dd2a7bc8f010ce46bb0
refs/heads/RayProgressCode
2023-02-16T19:26:22.309000
2021-01-14T02:52:14
2021-01-14T02:52:14
319,523,223
0
0
null
false
2021-01-08T17:00:21
2020-12-08T04:14:43
2021-01-08T10:12:46
2021-01-08T17:00:21
268
0
0
0
Java
false
false
package Controller; import Dao.UserDaoImpl; import Entity.User; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.Button; import javafx.scene.control.PasswordField; import javafx.scene.control.TextField; import javafx.stage.Stage; import java.net.URL; import java.util.ResourceBundle; public class UpdateUserController implements Initializable { @FXML private TextField txtNamaUser; @FXML private TextField txtUsername; @FXML private PasswordField txtPassword; @FXML private PasswordField txtConfirmPassword; @FXML private Button btnCancel; public MenuPageController controller; public User user; public void setController(MenuPageController controller){ this.controller=controller; txtNamaUser.setText(String.valueOf(controller.u.getNama())); txtUsername.setText(String.valueOf(controller.u.getUsername())); txtPassword.setText(String.valueOf(controller.u.getPassword())); txtConfirmPassword.setText(String.valueOf(controller.u.getPassword())); user=controller.u; } @FXML private void actionUpdateUser(ActionEvent actionEvent) { user.setNama(txtNamaUser.getText().trim()); user.setUsername(txtUsername.getText().trim()); user.setPassword(txtPassword.getText().trim()); controller.getUserDAO().editData(user); controller.uList.clear(); controller.uList.addAll(controller.getUserDAO().fetchAll()); } @FXML private void actionCancelUser(ActionEvent actionEvent) { Stage stage = (Stage) btnCancel.getScene().getWindow(); stage.close(); } @Override public void initialize(URL location, ResourceBundle resources) { } }
UTF-8
Java
1,800
java
UpdateUserController.java
Java
[]
null
[]
package Controller; import Dao.UserDaoImpl; import Entity.User; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.Button; import javafx.scene.control.PasswordField; import javafx.scene.control.TextField; import javafx.stage.Stage; import java.net.URL; import java.util.ResourceBundle; public class UpdateUserController implements Initializable { @FXML private TextField txtNamaUser; @FXML private TextField txtUsername; @FXML private PasswordField txtPassword; @FXML private PasswordField txtConfirmPassword; @FXML private Button btnCancel; public MenuPageController controller; public User user; public void setController(MenuPageController controller){ this.controller=controller; txtNamaUser.setText(String.valueOf(controller.u.getNama())); txtUsername.setText(String.valueOf(controller.u.getUsername())); txtPassword.setText(String.valueOf(controller.u.getPassword())); txtConfirmPassword.setText(String.valueOf(controller.u.getPassword())); user=controller.u; } @FXML private void actionUpdateUser(ActionEvent actionEvent) { user.setNama(txtNamaUser.getText().trim()); user.setUsername(txtUsername.getText().trim()); user.setPassword(txtPassword.getText().trim()); controller.getUserDAO().editData(user); controller.uList.clear(); controller.uList.addAll(controller.getUserDAO().fetchAll()); } @FXML private void actionCancelUser(ActionEvent actionEvent) { Stage stage = (Stage) btnCancel.getScene().getWindow(); stage.close(); } @Override public void initialize(URL location, ResourceBundle resources) { } }
1,800
0.719444
0.719444
63
27.571428
23.95347
79
false
false
0
0
0
0
0
0
0.539683
false
false
2
185536d6286fe896e6900c9b964f7a0a338123c8
532,575,998,293
909b6d0fe1ff026ab0cdda3f27466294d6732fa0
/src/test/java/utility/Utility.java
30513792a2734a94990e6569281e3bc779fb6388
[]
no_license
selstepin2itJuly/MavenSeleniumJuly2019
https://github.com/selstepin2itJuly/MavenSeleniumJuly2019
a2e68d79f2c64575ae83c35ccbb85b64f8e843cc
58d7242c1441072098678bb635ab059254a3ddbe
refs/heads/master
2022-12-28T02:52:00.748000
2019-07-21T19:24:34
2019-07-21T19:24:34
198,095,607
0
0
null
false
2020-10-13T14:45:30
2019-07-21T19:14:14
2019-07-21T19:25:08
2020-10-13T14:45:29
9,103
0
0
1
Java
false
false
package utility; import java.io.File; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; import org.openqa.selenium.By; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.OutputType; import org.openqa.selenium.TakesScreenshot; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.io.FileHandler; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.Select; import org.openqa.selenium.support.ui.WebDriverWait; import config.TestBase; public class Utility { public static String getDateStamp() { Date date=new Date(); System.out.println(date); SimpleDateFormat sdf=new SimpleDateFormat("YYYY_MM_dd_HH_mm_ss"); String str = sdf.format(date); return str; } public static void capturScreen(WebDriver driver) throws IOException { File f=((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE); FileHandler.copy(f, new File(TestBase.SCREENSHOTLOCATION+"/"+getDateStamp()+"_image"+".jpg")); } public static void waitForElement(WebElement ele, WebDriver driver) { WebDriverWait wait= new WebDriverWait(driver, 15); wait.until(ExpectedConditions.visibilityOf(ele)); } public static void scrollToElement(WebElement ele, WebDriver driver) { JavascriptExecutor je=(JavascriptExecutor) driver; je.executeScript("arguments[0].scrollIntoView(false);", ele); je.executeScript("window.scrollBy(0,200);", ele); } }
UTF-8
Java
1,670
java
Utility.java
Java
[]
null
[]
package utility; import java.io.File; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; import org.openqa.selenium.By; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.OutputType; import org.openqa.selenium.TakesScreenshot; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.io.FileHandler; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.Select; import org.openqa.selenium.support.ui.WebDriverWait; import config.TestBase; public class Utility { public static String getDateStamp() { Date date=new Date(); System.out.println(date); SimpleDateFormat sdf=new SimpleDateFormat("YYYY_MM_dd_HH_mm_ss"); String str = sdf.format(date); return str; } public static void capturScreen(WebDriver driver) throws IOException { File f=((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE); FileHandler.copy(f, new File(TestBase.SCREENSHOTLOCATION+"/"+getDateStamp()+"_image"+".jpg")); } public static void waitForElement(WebElement ele, WebDriver driver) { WebDriverWait wait= new WebDriverWait(driver, 15); wait.until(ExpectedConditions.visibilityOf(ele)); } public static void scrollToElement(WebElement ele, WebDriver driver) { JavascriptExecutor je=(JavascriptExecutor) driver; je.executeScript("arguments[0].scrollIntoView(false);", ele); je.executeScript("window.scrollBy(0,200);", ele); } }
1,670
0.724551
0.720359
54
28.925926
25.649239
99
false
false
0
0
0
0
0
0
1.185185
false
false
2
6bb68910e2cbfba860999d89375436afc5e7ac3a
20,761,871,924,899
ce9ed6a495b8c25bfa4ea57fc133b2a0c3aaf67d
/10_metalsoft/MetalSoft_Desktop/src/metalsoft/datos/jpa/entity/Detalletrabajotercerizado.java
4fc408bf9d3b6a9b8fee5c72d5a24fc61b59e0dc
[]
no_license
hemoreno33/metalurgica
https://github.com/hemoreno33/metalurgica
23804ae1d966b175b4409630ef08cd937de29202
db0d4406e9151fd4b91de21f7a4e18c63f4c8ce6
refs/heads/master
2015-08-21T12:41:46.716000
2011-11-22T18:37:44
2011-11-22T18:37:44
32,117,254
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package metalsoft.datos.jpa.entity; import java.io.Serializable; import java.math.BigInteger; import java.util.Date; import java.util.List; import javax.persistence.Basic; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.OneToMany; import javax.persistence.SequenceGenerator; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; /** * * @author Nino */ @Entity @Table(name = "detalletrabajotercerizado") @NamedQueries({ @NamedQuery(name = "Detalletrabajotercerizado.findAll", query = "SELECT d FROM Detalletrabajotercerizado d"), @NamedQuery(name = "Detalletrabajotercerizado.findByIddetalle", query = "SELECT d FROM Detalletrabajotercerizado d WHERE d.iddetalle = :iddetalle"), @NamedQuery(name = "Detalletrabajotercerizado.findByMontoparcial", query = "SELECT d FROM Detalletrabajotercerizado d WHERE d.montoparcial = :montoparcial"), @NamedQuery(name = "Detalletrabajotercerizado.findByCantidad", query = "SELECT d FROM Detalletrabajotercerizado d WHERE d.cantidad = :cantidad"), @NamedQuery(name = "Detalletrabajotercerizado.findByDescripcion", query = "SELECT d FROM Detalletrabajotercerizado d WHERE d.descripcion = :descripcion"), @NamedQuery(name = "Detalletrabajotercerizado.findByFechaenvioreal", query = "SELECT d FROM Detalletrabajotercerizado d WHERE d.fechaenvioreal = :fechaenvioreal"), @NamedQuery(name = "Detalletrabajotercerizado.findByFechaentregareal", query = "SELECT d FROM Detalletrabajotercerizado d WHERE d.fechaentregareal = :fechaentregareal"), @NamedQuery(name = "Detalletrabajotercerizado.findByPieza", query = "SELECT d FROM Detalletrabajotercerizado d WHERE d.pieza = :pieza")}) public class Detalletrabajotercerizado implements Serializable { private static final long serialVersionUID = 1L; @Id @Basic(optional = false) @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "detalletrabajotercerizado_seq") @SequenceGenerator(name = "detalletrabajotercerizado_seq", sequenceName = "detalletrabajotercerizado_iddetalle_seq", allocationSize = 1) @Column(name = "iddetalle") private Long iddetalle; // @Max(value=?) @Min(value=?)//if you know range of your decimal fields consider using these annotations to enforce field validation @Column(name = "montoparcial") private Double montoparcial; @Column(name = "cantidad") private Integer cantidad; @Column(name = "descripcion") private String descripcion; @Column(name = "fechaenvioreal") @Temporal(TemporalType.DATE) private Date fechaenvioreal; @Column(name = "fechaentregareal") @Temporal(TemporalType.DATE) private Date fechaentregareal; @Column(name = "pieza") private BigInteger pieza; @OneToMany(mappedBy = "iddetalletrabajo") private List<Detallereclamoempresamantenimiento> detallereclamoempresamantenimientoList; @JoinColumn(name = "idtrabajotercerizado", referencedColumnName = "idtrabajo") @ManyToOne(optional = false) private Trabajotercerizado idtrabajotercerizado; @JoinColumn(name = "proceso", referencedColumnName = "idetapaproduccion") @ManyToOne private Etapadeproduccion proceso; @JoinColumn(name = "estado", referencedColumnName = "idestado") @ManyToOne private Estadodetalletrabajotercerizado estado; public Detalletrabajotercerizado() { } public Detalletrabajotercerizado(Long iddetalle) { this.iddetalle = iddetalle; } public Long getIddetalle() { return iddetalle; } public void setIddetalle(Long iddetalle) { this.iddetalle = iddetalle; } public Double getMontoparcial() { return montoparcial; } public void setMontoparcial(Double montoparcial) { this.montoparcial = montoparcial; } public Integer getCantidad() { return cantidad; } public void setCantidad(Integer cantidad) { this.cantidad = cantidad; } public String getDescripcion() { return descripcion; } public void setDescripcion(String descripcion) { this.descripcion = descripcion; } public Date getFechaenvioreal() { return fechaenvioreal; } public void setFechaenvioreal(Date fechaenvioreal) { this.fechaenvioreal = fechaenvioreal; } public Date getFechaentregareal() { return fechaentregareal; } public void setFechaentregareal(Date fechaentregareal) { this.fechaentregareal = fechaentregareal; } public BigInteger getPieza() { return pieza; } public void setPieza(BigInteger pieza) { this.pieza = pieza; } public List<Detallereclamoempresamantenimiento> getDetallereclamoempresamantenimientoList() { return detallereclamoempresamantenimientoList; } public void setDetallereclamoempresamantenimientoList(List<Detallereclamoempresamantenimiento> detallereclamoempresamantenimientoList) { this.detallereclamoempresamantenimientoList = detallereclamoempresamantenimientoList; } public Trabajotercerizado getIdtrabajotercerizado() { return idtrabajotercerizado; } public void setIdtrabajotercerizado(Trabajotercerizado idtrabajotercerizado) { this.idtrabajotercerizado = idtrabajotercerizado; } public Etapadeproduccion getProceso() { return proceso; } public void setProceso(Etapadeproduccion proceso) { this.proceso = proceso; } public Estadodetalletrabajotercerizado getEstado() { return estado; } public void setEstado(Estadodetalletrabajotercerizado estado) { this.estado = estado; } @Override public int hashCode() { int hash = 0; hash += (iddetalle != null ? iddetalle.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof Detalletrabajotercerizado)) { return false; } Detalletrabajotercerizado other = (Detalletrabajotercerizado) object; if ((this.iddetalle == null && other.iddetalle != null) || (this.iddetalle != null && !this.iddetalle.equals(other.iddetalle))) { return false; } return true; } @Override public String toString() { return "metalsoft.datos.jpa.entity.Detalletrabajotercerizado[ iddetalle=" + iddetalle + " ]"; } }
UTF-8
Java
6,926
java
Detalletrabajotercerizado.java
Java
[ { "context": "javax.persistence.TemporalType;\n\n/**\n *\n * @author Nino\n */\n@Entity\n@Table(name = \"detalletrabajoterceriz", "end": 808, "score": 0.9803498983383179, "start": 804, "tag": "NAME", "value": "Nino" } ]
null
[]
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package metalsoft.datos.jpa.entity; import java.io.Serializable; import java.math.BigInteger; import java.util.Date; import java.util.List; import javax.persistence.Basic; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.OneToMany; import javax.persistence.SequenceGenerator; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; /** * * @author Nino */ @Entity @Table(name = "detalletrabajotercerizado") @NamedQueries({ @NamedQuery(name = "Detalletrabajotercerizado.findAll", query = "SELECT d FROM Detalletrabajotercerizado d"), @NamedQuery(name = "Detalletrabajotercerizado.findByIddetalle", query = "SELECT d FROM Detalletrabajotercerizado d WHERE d.iddetalle = :iddetalle"), @NamedQuery(name = "Detalletrabajotercerizado.findByMontoparcial", query = "SELECT d FROM Detalletrabajotercerizado d WHERE d.montoparcial = :montoparcial"), @NamedQuery(name = "Detalletrabajotercerizado.findByCantidad", query = "SELECT d FROM Detalletrabajotercerizado d WHERE d.cantidad = :cantidad"), @NamedQuery(name = "Detalletrabajotercerizado.findByDescripcion", query = "SELECT d FROM Detalletrabajotercerizado d WHERE d.descripcion = :descripcion"), @NamedQuery(name = "Detalletrabajotercerizado.findByFechaenvioreal", query = "SELECT d FROM Detalletrabajotercerizado d WHERE d.fechaenvioreal = :fechaenvioreal"), @NamedQuery(name = "Detalletrabajotercerizado.findByFechaentregareal", query = "SELECT d FROM Detalletrabajotercerizado d WHERE d.fechaentregareal = :fechaentregareal"), @NamedQuery(name = "Detalletrabajotercerizado.findByPieza", query = "SELECT d FROM Detalletrabajotercerizado d WHERE d.pieza = :pieza")}) public class Detalletrabajotercerizado implements Serializable { private static final long serialVersionUID = 1L; @Id @Basic(optional = false) @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "detalletrabajotercerizado_seq") @SequenceGenerator(name = "detalletrabajotercerizado_seq", sequenceName = "detalletrabajotercerizado_iddetalle_seq", allocationSize = 1) @Column(name = "iddetalle") private Long iddetalle; // @Max(value=?) @Min(value=?)//if you know range of your decimal fields consider using these annotations to enforce field validation @Column(name = "montoparcial") private Double montoparcial; @Column(name = "cantidad") private Integer cantidad; @Column(name = "descripcion") private String descripcion; @Column(name = "fechaenvioreal") @Temporal(TemporalType.DATE) private Date fechaenvioreal; @Column(name = "fechaentregareal") @Temporal(TemporalType.DATE) private Date fechaentregareal; @Column(name = "pieza") private BigInteger pieza; @OneToMany(mappedBy = "iddetalletrabajo") private List<Detallereclamoempresamantenimiento> detallereclamoempresamantenimientoList; @JoinColumn(name = "idtrabajotercerizado", referencedColumnName = "idtrabajo") @ManyToOne(optional = false) private Trabajotercerizado idtrabajotercerizado; @JoinColumn(name = "proceso", referencedColumnName = "idetapaproduccion") @ManyToOne private Etapadeproduccion proceso; @JoinColumn(name = "estado", referencedColumnName = "idestado") @ManyToOne private Estadodetalletrabajotercerizado estado; public Detalletrabajotercerizado() { } public Detalletrabajotercerizado(Long iddetalle) { this.iddetalle = iddetalle; } public Long getIddetalle() { return iddetalle; } public void setIddetalle(Long iddetalle) { this.iddetalle = iddetalle; } public Double getMontoparcial() { return montoparcial; } public void setMontoparcial(Double montoparcial) { this.montoparcial = montoparcial; } public Integer getCantidad() { return cantidad; } public void setCantidad(Integer cantidad) { this.cantidad = cantidad; } public String getDescripcion() { return descripcion; } public void setDescripcion(String descripcion) { this.descripcion = descripcion; } public Date getFechaenvioreal() { return fechaenvioreal; } public void setFechaenvioreal(Date fechaenvioreal) { this.fechaenvioreal = fechaenvioreal; } public Date getFechaentregareal() { return fechaentregareal; } public void setFechaentregareal(Date fechaentregareal) { this.fechaentregareal = fechaentregareal; } public BigInteger getPieza() { return pieza; } public void setPieza(BigInteger pieza) { this.pieza = pieza; } public List<Detallereclamoempresamantenimiento> getDetallereclamoempresamantenimientoList() { return detallereclamoempresamantenimientoList; } public void setDetallereclamoempresamantenimientoList(List<Detallereclamoempresamantenimiento> detallereclamoempresamantenimientoList) { this.detallereclamoempresamantenimientoList = detallereclamoempresamantenimientoList; } public Trabajotercerizado getIdtrabajotercerizado() { return idtrabajotercerizado; } public void setIdtrabajotercerizado(Trabajotercerizado idtrabajotercerizado) { this.idtrabajotercerizado = idtrabajotercerizado; } public Etapadeproduccion getProceso() { return proceso; } public void setProceso(Etapadeproduccion proceso) { this.proceso = proceso; } public Estadodetalletrabajotercerizado getEstado() { return estado; } public void setEstado(Estadodetalletrabajotercerizado estado) { this.estado = estado; } @Override public int hashCode() { int hash = 0; hash += (iddetalle != null ? iddetalle.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof Detalletrabajotercerizado)) { return false; } Detalletrabajotercerizado other = (Detalletrabajotercerizado) object; if ((this.iddetalle == null && other.iddetalle != null) || (this.iddetalle != null && !this.iddetalle.equals(other.iddetalle))) { return false; } return true; } @Override public String toString() { return "metalsoft.datos.jpa.entity.Detalletrabajotercerizado[ iddetalle=" + iddetalle + " ]"; } }
6,926
0.723072
0.722495
197
34.15736
37.09407
173
false
false
0
0
0
0
0
0
0.446701
false
false
2
413f69712481ee77301c740b741c5791888c6ac7
19,370,302,519,062
290ef436c6f44f695f5525a7c62746893f0e979c
/src/SumaDosEnteros.java
faf8c7bfa2523c28a20d89ae9740a55391698ec8
[]
no_license
maruian/SumaDosEnteros
https://github.com/maruian/SumaDosEnteros
959e2574d93976cae89efeda09f0fba5a5ee5c2b
4a610c857b59145f5b45b8f18ab3492c96b43a5f
refs/heads/master
2020-07-04T01:05:40.753000
2016-11-19T16:35:32
2016-11-19T16:35:32
74,220,421
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.util.Scanner; public class SumaDosEnteros { public static void main(String[] args) { // TODO Auto-generated method stub int x=0; x=5+2; System.out.println(x); } }
UTF-8
Java
195
java
SumaDosEnteros.java
Java
[]
null
[]
import java.util.Scanner; public class SumaDosEnteros { public static void main(String[] args) { // TODO Auto-generated method stub int x=0; x=5+2; System.out.println(x); } }
195
0.65641
0.641026
14
12.928572
14.295176
41
false
false
0
0
0
0
0
0
1.357143
false
false
2
ce150e040325df37ebc7a8722e9e22bf69bf9888
28,750,511,099,161
9d6ca6ab51e4f406ad0d56b463b0defc2cd757e8
/app/src/main/java/logistus/net/logiweather/models/City.java
e01dbdc17b89b19bb6dd0da06dc6c47891a9d29e
[]
no_license
logistus/LogiWeather
https://github.com/logistus/LogiWeather
73e671f4d9ca1d3663b6d4e22cf0c10cd8281687
20e4e07a0b3735f7f8907de134c8ee2021c2e917
refs/heads/master
2021-09-03T06:26:35.211000
2018-01-06T12:36:17
2018-01-06T12:36:17
116,481,422
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package logistus.net.logiweather.models; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; import java.util.TimeZone; import logistus.net.logiweather.MainActivity; public class City { private String mCityText; private String mLastUpdate; private String mTimezone; private String mQueryUrl; private int cityId; public City() {} public int getCityId() { return cityId; } public void setCityId(int cityId) { this.cityId = cityId; } public String getTimezone() { return mTimezone; } public void setTimezone(String timezone) { mTimezone = timezone; } public String getLastUpdate() { return mLastUpdate; } public void setLastUpdate(String lastUpdate) { mLastUpdate = lastUpdate; } public String getQueryUrl() { return mQueryUrl; } public void setQueryUrl(String queryUrl) { mQueryUrl = queryUrl; } public String getCityText() { return mCityText; } public void setCityText(String cityText) { mCityText = cityText; } public String getFormattedTime(String unix_time, String type) { int epoch = Integer.parseInt(unix_time); SimpleDateFormat formatter; if (MainActivity.TIME_TYPE == 24) formatter = new SimpleDateFormat("dd MMM yyyy, HH:mm", Locale.getDefault()); else formatter = new SimpleDateFormat("dd MMM yyyy, hh:mm aaa", Locale.getDefault()); if ("updated".equals(type)) formatter.setTimeZone(TimeZone.getTimeZone(TimeZone.getDefault().getDisplayName(false, TimeZone.SHORT))); else { if ("Europe/Istanbul".equals(getTimezone())) formatter.setTimeZone(TimeZone.getTimeZone("GMT+3")); else formatter.setTimeZone(TimeZone.getTimeZone(getTimezone())); } return formatter.format(new Date(epoch * 1000L)); } }
UTF-8
Java
1,996
java
City.java
Java
[]
null
[]
package logistus.net.logiweather.models; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; import java.util.TimeZone; import logistus.net.logiweather.MainActivity; public class City { private String mCityText; private String mLastUpdate; private String mTimezone; private String mQueryUrl; private int cityId; public City() {} public int getCityId() { return cityId; } public void setCityId(int cityId) { this.cityId = cityId; } public String getTimezone() { return mTimezone; } public void setTimezone(String timezone) { mTimezone = timezone; } public String getLastUpdate() { return mLastUpdate; } public void setLastUpdate(String lastUpdate) { mLastUpdate = lastUpdate; } public String getQueryUrl() { return mQueryUrl; } public void setQueryUrl(String queryUrl) { mQueryUrl = queryUrl; } public String getCityText() { return mCityText; } public void setCityText(String cityText) { mCityText = cityText; } public String getFormattedTime(String unix_time, String type) { int epoch = Integer.parseInt(unix_time); SimpleDateFormat formatter; if (MainActivity.TIME_TYPE == 24) formatter = new SimpleDateFormat("dd MMM yyyy, HH:mm", Locale.getDefault()); else formatter = new SimpleDateFormat("dd MMM yyyy, hh:mm aaa", Locale.getDefault()); if ("updated".equals(type)) formatter.setTimeZone(TimeZone.getTimeZone(TimeZone.getDefault().getDisplayName(false, TimeZone.SHORT))); else { if ("Europe/Istanbul".equals(getTimezone())) formatter.setTimeZone(TimeZone.getTimeZone("GMT+3")); else formatter.setTimeZone(TimeZone.getTimeZone(getTimezone())); } return formatter.format(new Date(epoch * 1000L)); } }
1,996
0.638778
0.635271
76
25.263159
24.202202
117
false
false
0
0
0
0
0
0
0.460526
false
false
2
d4a1606e7c6d169190dfe2abfdfc2f0671abc0c7
7,310,034,354,726
ec4bf238118d5c73e69e9f46cf33e94767eeeff1
/KillerPlop/src/fr/emn/killerplop/graphics/sprites/Sprite.java
9189e7586181407870eb9d930cd56c5dda701576
[]
no_license
dasylfloce/killerplop
https://github.com/dasylfloce/killerplop
eeea4f745f332bbc4fa803f9682c98eb6b44ca77
17e369b5502fc711cb64b5e185ce9e3dc7c479b3
refs/heads/master
2021-01-19T06:43:38.710000
2009-12-16T14:08:23
2009-12-16T14:08:23
32,212,184
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package fr.emn.killerplop.graphics.sprites; import fr.emn.killerplop.game.entities.shapes.Shape; import fr.emn.killerplop.graphics.context.GraphicContext; /** * A sprite to be displayed on the screen. Note that a sprite contains no state * information, i.e. its just the image and not the location. This allows us to * use a single sprite in lots of different places without having to store * multiple copies of the image. * * @author Kevin Glass */ public interface Sprite { /** * @return the shape of the sprite */ public Shape getShape(); /** * Draw the sprite onto the graphics context provided * @param graphicContext graphicContext * Graphic context to draw on. * @param x * The x location at which to draw the sprite * @param y * The y location at which to draw the sprite */ public void draw(GraphicContext graphicContext, int x, int y); /** * Update the sprite. * * @param delta * Time elapsed since last update. */ public void update(long delta); /** * Set the shape of the sprite * @param shape New shape */ public void setShape(Shape shape); }
UTF-8
Java
1,198
java
Sprite.java
Java
[ { "context": "\n * multiple copies of the image.\r\n * \r\n * @author Kevin Glass\r\n */\r\npublic interface Sprite {\r\n\r\n\t/**\r\n\t * @ret", "end": 468, "score": 0.9996469020843506, "start": 457, "tag": "NAME", "value": "Kevin Glass" } ]
null
[]
package fr.emn.killerplop.graphics.sprites; import fr.emn.killerplop.game.entities.shapes.Shape; import fr.emn.killerplop.graphics.context.GraphicContext; /** * A sprite to be displayed on the screen. Note that a sprite contains no state * information, i.e. its just the image and not the location. This allows us to * use a single sprite in lots of different places without having to store * multiple copies of the image. * * @author <NAME> */ public interface Sprite { /** * @return the shape of the sprite */ public Shape getShape(); /** * Draw the sprite onto the graphics context provided * @param graphicContext graphicContext * Graphic context to draw on. * @param x * The x location at which to draw the sprite * @param y * The y location at which to draw the sprite */ public void draw(GraphicContext graphicContext, int x, int y); /** * Update the sprite. * * @param delta * Time elapsed since last update. */ public void update(long delta); /** * Set the shape of the sprite * @param shape New shape */ public void setShape(Shape shape); }
1,193
0.656928
0.656928
47
23.531916
23.993662
79
false
false
0
0
0
0
0
0
0.829787
false
false
2
f972036dc77315309498596e487e75c2613e099f
15,994,458,243,108
393dd8a248daa1e543e6f2747894903a857a627b
/core/src/main/java/org/objectagon/core/server/ServerImpl.java
f2f83ab074d2b2807a71a60652bc3856313ab72e
[ "MIT" ]
permissive
cheijken/objectagon
https://github.com/cheijken/objectagon
13e4f6725aab4e81be9c2303c7659e8ef9de6f20
ae362900e015901c4ebe4115fc13d64bd36ebb00
refs/heads/master
2020-12-24T05:35:57.443000
2018-01-28T22:14:05
2018-01-28T22:14:05
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.objectagon.core.server; import org.objectagon.core.Server; import org.objectagon.core.exception.ErrorClass; import org.objectagon.core.exception.ErrorKind; import org.objectagon.core.exception.SevereError; import org.objectagon.core.msg.*; import org.objectagon.core.msg.field.StandardField; import org.objectagon.core.msg.message.MessageValue; import org.objectagon.core.msg.message.VolatileAddressValue; import org.objectagon.core.msg.message.VolatileNameValue; import org.objectagon.core.msg.protocol.StandardProtocol; import org.objectagon.core.task.StandardTaskBuilder; import org.objectagon.core.task.TaskBuilder; import org.objectagon.core.utils.IdCounter; import org.objectagon.core.utils.OneReceiverConfigurations; import org.objectagon.core.utils.SwitchCase; import java.util.*; import java.util.concurrent.DelayQueue; import java.util.concurrent.Delayed; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; /** * Created by christian on 2015-11-16. */ public class ServerImpl implements Server, Server.CreateReceiverByName, Receiver.ReceiverCtrl { private ServerId serverId; private SystemTime systemTime; private IdCounter idCounter = new IdCounter(0); private Map<Name, Factory> factories = new HashMap<>(); private Map<Address, Receiver> receivers = new HashMap<>(); EnvelopeProcessor envelopeProcessor; private ServerAliasCtrlImpl serverAliasCtrl = new ServerAliasCtrlImpl(); private org.objectagon.core.utils.Formatter.Format format = org.objectagon.core.utils.FormatterImpl.standard(); private Formatter textFormatter = new Formatter(); private final DelayedQueue delayedQueue; @Override public ServerId getServerId() {return serverId;} public ServerImpl(ServerId serverId) { this(serverId, System::currentTimeMillis); } public ServerImpl(ServerId serverId, SystemTime systemTime) { this.serverId = serverId; this.systemTime = systemTime; this.envelopeProcessor = new EnvelopeProcessorImpl(this::processEnvelopeTarget); this.delayedQueue = new DelayedQueue(); } private Optional<Factory> getFactoryByName(Name name) { Factory factory = factories.get(name); if (factory==null) return Optional.empty(); return Optional.of(factory); } @Override public void registerFactory(Name name, Factory factory) { factories.put(name, factory); } @Override public TaskBuilder getTaskBuilder() { return createReceiver(StandardTaskBuilder.STANDARD_TASK_BUILDER); } @Override public Receiver create(Receiver.ReceiverCtrl receiverCtrl) { throw new RuntimeException("Not implemented!"); } @Override public <A extends Address, R extends Receiver<A>> R createReceiver(Name name, Receiver.Configurations... configurations) { Factory factory = getFactoryByName(name).orElseThrow(() -> new SevereError(ErrorClass.SERVER, ErrorKind.RECEIVER_NOT_FOUND, VolatileNameValue.name(name))); R receiver = (R) factory.create(this); if (receiver.getAddress()==null) { OneReceiverConfigurations oneReceiverConfigurations = OneReceiverConfigurations.create(Receiver.ADDRESS_CONFIGURATIONS, ReceiverAddressConfigurationParameters.create(serverId, idCounter.next(), systemTime.currentTimeMillis())); if (configurations.length==0) { receiver.configure(oneReceiverConfigurations); } else if (configurations.length==1) { receiver.configure(oneReceiverConfigurations, configurations[0]); } else { List<Receiver.Configurations> receiverConfigurations = Arrays.asList(configurations); receiverConfigurations.add(oneReceiverConfigurations); receiver.configure(receiverConfigurations.stream().toArray(Receiver.Configurations[]::new)); } if (receiver.getAddress() == null) throw new SevereError(ErrorClass.SERVER, ErrorKind.RECEIVER_HAS_NO_ADDRESS, VolatileNameValue.name(name)); registerReceiver(receiver.getAddress(), receiver); //System.out.println("ServerImpl.createReceiver "+receiver.getAddress()); } return receiver; } public void registerReceiver(Address address, Receiver receiver) { Receiver alreadyExists = receivers.put(address, receiver); if (alreadyExists!=null) throw new SevereError(ErrorClass.SERVER, ErrorKind.RECEIVER_ALLREADY_EXISTS, VolatileAddressValue.address(address)); } Optional<Transporter> processEnvelopeTarget(Address target) { if (target==null) throw new SevereError(ErrorClass.SERVER, ErrorKind.ADDRESS_IS_NULL); Receiver receiver = receivers.get(target); if (receiver==null) { if (target instanceof Name) /* System.out.println("ServerImpl.processEnvelopeTarget >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"); receivers.keySet().forEach(v -> System.out.println("ServerImpl.processEnvelopeTarget "+v)); System.out.println("ServerImpl.processEnvelopeTarget <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<"); */ receivers.keySet().forEach(address -> { try { address.getClass().getSimpleName(); target.getClass().getSimpleName(); address.equals(target); /* if (address != null) System.out.println("ServerImpl.processEnvelopeTarget " + address.getClass().getSimpleName() + "=" + target.getClass().getSimpleName() + " => " + Objects.equals(address,target)); else System.out.println("Address is null!"); */ } catch (Exception e) { e.printStackTrace(); } }); /* System.out.println("ServerImpl.processEnvelopeTarget ****************************************************"); */ return Optional.empty(); } return Optional.of(receiver::receive); } @Override public void transport(Envelope envelope) { //System.out.println(""+envelope); envelopeProcessor.transport(envelope); } public void stop() { //TODO Should really start stopping this thing here... } @Override public void envelopeDelayed(Receiver.DelayDetails delayDetails) { delayedQueue.put(delayDetails); } private static class EnvelopeProcessorImpl implements EnvelopeProcessor { private Queue<Envelope> queue = new LinkedList<>(); private Envelope.Targets targets; public EnvelopeProcessorImpl(Envelope.Targets targets) { this.targets = targets; new Thread(this::run).start(); } @Override public void transport(Envelope envelope) { synchronized (this) { queue.add(envelope); notify(); } } public void run() { synchronized (this) { while (true) { Envelope envelope = null; try { while (!queue.isEmpty()) { envelope = queue.poll(); envelope.targets(targets); } try { wait(1000); } catch (InterruptedException e) { e.printStackTrace(); } } catch (SevereError severeError) { final Envelope errorEnvelope = envelope; SwitchCase.create(severeError.getErrorKind()) .caseDo(ErrorKind.UNKNOWN_TARGET, errorKind -> { if (errorEnvelope != null) { transport(errorEnvelope.createReplyComposer().create(new StandardProtocol.ErrorMessage(severeError))); } else { System.out.println("EnvelopeProcessorImpl.run -------------------- SevereError ---------------------"); System.out.println("Cannot find "+severeError.getValue(StandardField.ADDRESS).asAddress()); } }) .elseDo(errorKind1 -> severeError.printStackTrace()); } catch (Throwable unknownError) { unknownError.printStackTrace(); transport(envelope.createReplyComposer().create(new StandardProtocol.ErrorMessage( StandardProtocol.ErrorSeverity.Severe, ErrorClass.UNKNOWN, ErrorKind.UNEXPECTED, MessageValue.text(unknownError.getMessage()), MessageValue.text(unknownError.getClass().getSimpleName()), MessageValue.text(Arrays.stream(unknownError.getStackTrace()) .map(StackTraceElement::toString) .collect(Collectors.joining("\n")))))); } } } } } private class DelayedQueue implements Runnable { DelayQueue<DelayedEnvelope> queue = new DelayQueue<>(); public DelayedQueue() { new Thread(this).start(); } public void put(Receiver.DelayDetails delayDetails) { final DelayedEnvelope delayedEnvelope = new DelayedEnvelope(this, delayDetails); queue.add(delayedEnvelope); transport(delayedEnvelope.createDelayReplyEnvelope()); } @Override public void run() { while (true) { try { final DelayedEnvelope delayedEnvelope = queue.poll(1, TimeUnit.SECONDS); if (delayedEnvelope != null) transport(delayedEnvelope.getEnvelope()); } catch (InterruptedException e) { e.printStackTrace(); } } } public void release(DelayedEnvelope delayedEnvelope) { queue.remove(delayedEnvelope); transport(delayedEnvelope.getEnvelope()); } } private class DelayedEnvelope implements Delayed { private DelayedQueue delayedQueue; Receiver.DelayDetails delayDetails; public DelayedEnvelope(DelayedQueue delayedQueue, Receiver.DelayDetails delayDetails) { this.delayedQueue = delayedQueue; this.delayDetails = delayDetails; this.delayDetails.release(this::release); } private void release() { this.delayedQueue.release(this); } @Override public long getDelay(TimeUnit unit) { return delayDetails.getEstimatedDelayTime() .map(unit::toMillis) .orElse(unit.toMillis(20L)); } @Override public int compareTo(Delayed delayed) { return Long.compare(getDelay(TimeUnit.MILLISECONDS), delayed.getDelay(TimeUnit.MILLISECONDS)); } public Envelope getEnvelope() { return delayDetails.getEnvelope(); } public Envelope createDelayReplyEnvelope() { return delayDetails.createDelayReplyEnvelope(getDelay(TimeUnit.MILLISECONDS)); } } // Delegation of interface Server.AliasCtrl in ReceiverCtrl @Override public void registerAliasForAddress(Name name, Address address) { serverAliasCtrl.registerAliasForAddress(name, address); } @Override public void removeAlias(Name name) { serverAliasCtrl.removeAlias(name); } @Override public Optional<Address> lookupAddressByAlias(Name name) { return serverAliasCtrl.lookupAddressByAlias(name); } private static class ReceiverAddressConfigurationParameters implements Receiver.AddressConfigurationParameters { private final ServerId serverId; private final Long id; private final Long timeStamp; private ReceiverAddressConfigurationParameters(ServerId serverId, Long id, Long timeStamp) { this.serverId = serverId; this.id = id; this.timeStamp = timeStamp; } public static ReceiverAddressConfigurationParameters create(ServerId serverId, Long id, Long timeStamp) { return new ReceiverAddressConfigurationParameters(serverId, id, timeStamp); } @Override public ServerId getServerId() { return serverId; } @Override public Long getId() { return id; } @Override public Long getTimeStamp() { return timeStamp; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof ReceiverAddressConfigurationParameters)) return false; ReceiverAddressConfigurationParameters that = (ReceiverAddressConfigurationParameters) o; return Objects.equals(getServerId(), that.getServerId()) && Objects.equals(getId(), that.getId()) && Objects.equals(getTimeStamp(), that.getTimeStamp()); } @Override public int hashCode() { return Objects.hash(getServerId(), getId(), getTimeStamp()); } @Override public String toString() { return "ReceiverAddressConfigurationParameters{" + "serverId=" + serverId + ", id=" + id + ", timeStamp=" + timeStamp + '}'; } } }
UTF-8
Java
14,018
java
ServerImpl.java
Java
[ { "context": "rt java.util.stream.Collectors;\n\n/**\n * Created by christian on 2015-11-16.\n */\npublic class ServerImpl implem", "end": 982, "score": 0.9990842938423157, "start": 973, "tag": "NAME", "value": "christian" } ]
null
[]
package org.objectagon.core.server; import org.objectagon.core.Server; import org.objectagon.core.exception.ErrorClass; import org.objectagon.core.exception.ErrorKind; import org.objectagon.core.exception.SevereError; import org.objectagon.core.msg.*; import org.objectagon.core.msg.field.StandardField; import org.objectagon.core.msg.message.MessageValue; import org.objectagon.core.msg.message.VolatileAddressValue; import org.objectagon.core.msg.message.VolatileNameValue; import org.objectagon.core.msg.protocol.StandardProtocol; import org.objectagon.core.task.StandardTaskBuilder; import org.objectagon.core.task.TaskBuilder; import org.objectagon.core.utils.IdCounter; import org.objectagon.core.utils.OneReceiverConfigurations; import org.objectagon.core.utils.SwitchCase; import java.util.*; import java.util.concurrent.DelayQueue; import java.util.concurrent.Delayed; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; /** * Created by christian on 2015-11-16. */ public class ServerImpl implements Server, Server.CreateReceiverByName, Receiver.ReceiverCtrl { private ServerId serverId; private SystemTime systemTime; private IdCounter idCounter = new IdCounter(0); private Map<Name, Factory> factories = new HashMap<>(); private Map<Address, Receiver> receivers = new HashMap<>(); EnvelopeProcessor envelopeProcessor; private ServerAliasCtrlImpl serverAliasCtrl = new ServerAliasCtrlImpl(); private org.objectagon.core.utils.Formatter.Format format = org.objectagon.core.utils.FormatterImpl.standard(); private Formatter textFormatter = new Formatter(); private final DelayedQueue delayedQueue; @Override public ServerId getServerId() {return serverId;} public ServerImpl(ServerId serverId) { this(serverId, System::currentTimeMillis); } public ServerImpl(ServerId serverId, SystemTime systemTime) { this.serverId = serverId; this.systemTime = systemTime; this.envelopeProcessor = new EnvelopeProcessorImpl(this::processEnvelopeTarget); this.delayedQueue = new DelayedQueue(); } private Optional<Factory> getFactoryByName(Name name) { Factory factory = factories.get(name); if (factory==null) return Optional.empty(); return Optional.of(factory); } @Override public void registerFactory(Name name, Factory factory) { factories.put(name, factory); } @Override public TaskBuilder getTaskBuilder() { return createReceiver(StandardTaskBuilder.STANDARD_TASK_BUILDER); } @Override public Receiver create(Receiver.ReceiverCtrl receiverCtrl) { throw new RuntimeException("Not implemented!"); } @Override public <A extends Address, R extends Receiver<A>> R createReceiver(Name name, Receiver.Configurations... configurations) { Factory factory = getFactoryByName(name).orElseThrow(() -> new SevereError(ErrorClass.SERVER, ErrorKind.RECEIVER_NOT_FOUND, VolatileNameValue.name(name))); R receiver = (R) factory.create(this); if (receiver.getAddress()==null) { OneReceiverConfigurations oneReceiverConfigurations = OneReceiverConfigurations.create(Receiver.ADDRESS_CONFIGURATIONS, ReceiverAddressConfigurationParameters.create(serverId, idCounter.next(), systemTime.currentTimeMillis())); if (configurations.length==0) { receiver.configure(oneReceiverConfigurations); } else if (configurations.length==1) { receiver.configure(oneReceiverConfigurations, configurations[0]); } else { List<Receiver.Configurations> receiverConfigurations = Arrays.asList(configurations); receiverConfigurations.add(oneReceiverConfigurations); receiver.configure(receiverConfigurations.stream().toArray(Receiver.Configurations[]::new)); } if (receiver.getAddress() == null) throw new SevereError(ErrorClass.SERVER, ErrorKind.RECEIVER_HAS_NO_ADDRESS, VolatileNameValue.name(name)); registerReceiver(receiver.getAddress(), receiver); //System.out.println("ServerImpl.createReceiver "+receiver.getAddress()); } return receiver; } public void registerReceiver(Address address, Receiver receiver) { Receiver alreadyExists = receivers.put(address, receiver); if (alreadyExists!=null) throw new SevereError(ErrorClass.SERVER, ErrorKind.RECEIVER_ALLREADY_EXISTS, VolatileAddressValue.address(address)); } Optional<Transporter> processEnvelopeTarget(Address target) { if (target==null) throw new SevereError(ErrorClass.SERVER, ErrorKind.ADDRESS_IS_NULL); Receiver receiver = receivers.get(target); if (receiver==null) { if (target instanceof Name) /* System.out.println("ServerImpl.processEnvelopeTarget >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"); receivers.keySet().forEach(v -> System.out.println("ServerImpl.processEnvelopeTarget "+v)); System.out.println("ServerImpl.processEnvelopeTarget <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<"); */ receivers.keySet().forEach(address -> { try { address.getClass().getSimpleName(); target.getClass().getSimpleName(); address.equals(target); /* if (address != null) System.out.println("ServerImpl.processEnvelopeTarget " + address.getClass().getSimpleName() + "=" + target.getClass().getSimpleName() + " => " + Objects.equals(address,target)); else System.out.println("Address is null!"); */ } catch (Exception e) { e.printStackTrace(); } }); /* System.out.println("ServerImpl.processEnvelopeTarget ****************************************************"); */ return Optional.empty(); } return Optional.of(receiver::receive); } @Override public void transport(Envelope envelope) { //System.out.println(""+envelope); envelopeProcessor.transport(envelope); } public void stop() { //TODO Should really start stopping this thing here... } @Override public void envelopeDelayed(Receiver.DelayDetails delayDetails) { delayedQueue.put(delayDetails); } private static class EnvelopeProcessorImpl implements EnvelopeProcessor { private Queue<Envelope> queue = new LinkedList<>(); private Envelope.Targets targets; public EnvelopeProcessorImpl(Envelope.Targets targets) { this.targets = targets; new Thread(this::run).start(); } @Override public void transport(Envelope envelope) { synchronized (this) { queue.add(envelope); notify(); } } public void run() { synchronized (this) { while (true) { Envelope envelope = null; try { while (!queue.isEmpty()) { envelope = queue.poll(); envelope.targets(targets); } try { wait(1000); } catch (InterruptedException e) { e.printStackTrace(); } } catch (SevereError severeError) { final Envelope errorEnvelope = envelope; SwitchCase.create(severeError.getErrorKind()) .caseDo(ErrorKind.UNKNOWN_TARGET, errorKind -> { if (errorEnvelope != null) { transport(errorEnvelope.createReplyComposer().create(new StandardProtocol.ErrorMessage(severeError))); } else { System.out.println("EnvelopeProcessorImpl.run -------------------- SevereError ---------------------"); System.out.println("Cannot find "+severeError.getValue(StandardField.ADDRESS).asAddress()); } }) .elseDo(errorKind1 -> severeError.printStackTrace()); } catch (Throwable unknownError) { unknownError.printStackTrace(); transport(envelope.createReplyComposer().create(new StandardProtocol.ErrorMessage( StandardProtocol.ErrorSeverity.Severe, ErrorClass.UNKNOWN, ErrorKind.UNEXPECTED, MessageValue.text(unknownError.getMessage()), MessageValue.text(unknownError.getClass().getSimpleName()), MessageValue.text(Arrays.stream(unknownError.getStackTrace()) .map(StackTraceElement::toString) .collect(Collectors.joining("\n")))))); } } } } } private class DelayedQueue implements Runnable { DelayQueue<DelayedEnvelope> queue = new DelayQueue<>(); public DelayedQueue() { new Thread(this).start(); } public void put(Receiver.DelayDetails delayDetails) { final DelayedEnvelope delayedEnvelope = new DelayedEnvelope(this, delayDetails); queue.add(delayedEnvelope); transport(delayedEnvelope.createDelayReplyEnvelope()); } @Override public void run() { while (true) { try { final DelayedEnvelope delayedEnvelope = queue.poll(1, TimeUnit.SECONDS); if (delayedEnvelope != null) transport(delayedEnvelope.getEnvelope()); } catch (InterruptedException e) { e.printStackTrace(); } } } public void release(DelayedEnvelope delayedEnvelope) { queue.remove(delayedEnvelope); transport(delayedEnvelope.getEnvelope()); } } private class DelayedEnvelope implements Delayed { private DelayedQueue delayedQueue; Receiver.DelayDetails delayDetails; public DelayedEnvelope(DelayedQueue delayedQueue, Receiver.DelayDetails delayDetails) { this.delayedQueue = delayedQueue; this.delayDetails = delayDetails; this.delayDetails.release(this::release); } private void release() { this.delayedQueue.release(this); } @Override public long getDelay(TimeUnit unit) { return delayDetails.getEstimatedDelayTime() .map(unit::toMillis) .orElse(unit.toMillis(20L)); } @Override public int compareTo(Delayed delayed) { return Long.compare(getDelay(TimeUnit.MILLISECONDS), delayed.getDelay(TimeUnit.MILLISECONDS)); } public Envelope getEnvelope() { return delayDetails.getEnvelope(); } public Envelope createDelayReplyEnvelope() { return delayDetails.createDelayReplyEnvelope(getDelay(TimeUnit.MILLISECONDS)); } } // Delegation of interface Server.AliasCtrl in ReceiverCtrl @Override public void registerAliasForAddress(Name name, Address address) { serverAliasCtrl.registerAliasForAddress(name, address); } @Override public void removeAlias(Name name) { serverAliasCtrl.removeAlias(name); } @Override public Optional<Address> lookupAddressByAlias(Name name) { return serverAliasCtrl.lookupAddressByAlias(name); } private static class ReceiverAddressConfigurationParameters implements Receiver.AddressConfigurationParameters { private final ServerId serverId; private final Long id; private final Long timeStamp; private ReceiverAddressConfigurationParameters(ServerId serverId, Long id, Long timeStamp) { this.serverId = serverId; this.id = id; this.timeStamp = timeStamp; } public static ReceiverAddressConfigurationParameters create(ServerId serverId, Long id, Long timeStamp) { return new ReceiverAddressConfigurationParameters(serverId, id, timeStamp); } @Override public ServerId getServerId() { return serverId; } @Override public Long getId() { return id; } @Override public Long getTimeStamp() { return timeStamp; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof ReceiverAddressConfigurationParameters)) return false; ReceiverAddressConfigurationParameters that = (ReceiverAddressConfigurationParameters) o; return Objects.equals(getServerId(), that.getServerId()) && Objects.equals(getId(), that.getId()) && Objects.equals(getTimeStamp(), that.getTimeStamp()); } @Override public int hashCode() { return Objects.hash(getServerId(), getId(), getTimeStamp()); } @Override public String toString() { return "ReceiverAddressConfigurationParameters{" + "serverId=" + serverId + ", id=" + id + ", timeStamp=" + timeStamp + '}'; } } }
14,018
0.597232
0.595805
343
39.868805
35.058598
239
false
false
0
0
0
0
0
0
0.530612
false
false
12
115cba1c753b1bd9ff55b289a01c67099ba1dc85
24,197,845,755,333
3c04afcdb126c46401e835f006b59748ccecc0bb
/src/main/java/com/stripcode/web/sf/SF30_052Controller.java
fd93ba5c64231ef4b7153e7279ea806ff2855a7f
[ "Apache-2.0" ]
permissive
zhiyin369love/JeeMQ
https://github.com/zhiyin369love/JeeMQ
ec19a84219e9a49fd7b43eb0976db638a33b2321
1706db5a4e8b1e79be665b5e216eca16018deaa3
refs/heads/master
2017-12-18T09:28:24.103000
2016-12-22T14:59:59
2016-12-22T14:59:59
77,153,083
0
2
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.stripcode.web.sf; import com.stripcode.core.dto.cs.CreateOrModifyCsTaskCompletionDto; import com.stripcode.core.util.tree.GenerateTreeDataUtil; import com.stripcode.core.util.tree.TreeNode; import com.stripcode.mybatis.sf.model.SFSiteInfo; import com.stripcode.mybatis.sf.model.SFStyleAreaPerInfo; import com.stripcode.mybatis.user.model.TCodeMacroDefine; import com.stripcode.service.sf.SF30_052Service; import com.stripcode.service.user.TCodeMacroDefineService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import java.util.HashMap; import java.util.List; import java.util.Map; /** * @author Metro */ @Controller @RequestMapping("SF30_052") public class SF30_052Controller { @Autowired private SF30_052Service sf30_052Service; @Autowired private TCodeMacroDefineService tCodeMacroDefineService; /** * 保存 * @param sfSiteInfo * @return Map */ @ResponseBody @RequestMapping(value = "update",method = RequestMethod.POST) public Map update(SFSiteInfo sfSiteInfo, CreateOrModifyCsTaskCompletionDto csTaskCompletionDto){ return sf30_052Service.update(sfSiteInfo,csTaskCompletionDto.toModel()); } /** * 查询场地信息 * @param ppId * @return map */ @ResponseBody @RequestMapping(value = "querySiteInfo",method = RequestMethod.POST) public Map<String,Object> querySiteInfo(String ppId){ Map<String,Object> map = new HashMap<String,Object>(); map.put("main",sf30_052Service.querySiteInfo(ppId)); map.put("codeList",tCodeMacroDefineService.queryForSiteArea()); return map; } @ResponseBody @RequestMapping(value = "loadTableHead",method = RequestMethod.POST) public List<TCodeMacroDefine> loadTableHead(String storeImage){ return sf30_052Service.loadTableHead(storeImage); } @ResponseBody @RequestMapping(value = "queryStyleAreaPerInfo",method = RequestMethod.POST) public List<TreeNode> queryStyleAreaPerInfo(String ppId){ return GenerateTreeDataUtil.recursionChildren("root",sf30_052Service.queryStyleAreaPerInfo(ppId)); } @ResponseBody @RequestMapping(value = "queryStyleInfo",method = RequestMethod.POST) public List<SFStyleAreaPerInfo> queryStyleInfo(String ppId,String seriesSex){ return sf30_052Service.queryStyleInfo(ppId,seriesSex); } }
UTF-8
Java
2,494
java
SF30_052Controller.java
Java
[ { "context": "a.util.List;\nimport java.util.Map;\n\n/**\n * @author Metro\n */\n@Controller\n@RequestMapping(\"SF30_052\")\npubli", "end": 734, "score": 0.5837260484695435, "start": 729, "tag": "USERNAME", "value": "Metro" } ]
null
[]
package com.stripcode.web.sf; import com.stripcode.core.dto.cs.CreateOrModifyCsTaskCompletionDto; import com.stripcode.core.util.tree.GenerateTreeDataUtil; import com.stripcode.core.util.tree.TreeNode; import com.stripcode.mybatis.sf.model.SFSiteInfo; import com.stripcode.mybatis.sf.model.SFStyleAreaPerInfo; import com.stripcode.mybatis.user.model.TCodeMacroDefine; import com.stripcode.service.sf.SF30_052Service; import com.stripcode.service.user.TCodeMacroDefineService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import java.util.HashMap; import java.util.List; import java.util.Map; /** * @author Metro */ @Controller @RequestMapping("SF30_052") public class SF30_052Controller { @Autowired private SF30_052Service sf30_052Service; @Autowired private TCodeMacroDefineService tCodeMacroDefineService; /** * 保存 * @param sfSiteInfo * @return Map */ @ResponseBody @RequestMapping(value = "update",method = RequestMethod.POST) public Map update(SFSiteInfo sfSiteInfo, CreateOrModifyCsTaskCompletionDto csTaskCompletionDto){ return sf30_052Service.update(sfSiteInfo,csTaskCompletionDto.toModel()); } /** * 查询场地信息 * @param ppId * @return map */ @ResponseBody @RequestMapping(value = "querySiteInfo",method = RequestMethod.POST) public Map<String,Object> querySiteInfo(String ppId){ Map<String,Object> map = new HashMap<String,Object>(); map.put("main",sf30_052Service.querySiteInfo(ppId)); map.put("codeList",tCodeMacroDefineService.queryForSiteArea()); return map; } @ResponseBody @RequestMapping(value = "loadTableHead",method = RequestMethod.POST) public List<TCodeMacroDefine> loadTableHead(String storeImage){ return sf30_052Service.loadTableHead(storeImage); } @ResponseBody @RequestMapping(value = "queryStyleAreaPerInfo",method = RequestMethod.POST) public List<TreeNode> queryStyleAreaPerInfo(String ppId){ return GenerateTreeDataUtil.recursionChildren("root",sf30_052Service.queryStyleAreaPerInfo(ppId)); } @ResponseBody @RequestMapping(value = "queryStyleInfo",method = RequestMethod.POST) public List<SFStyleAreaPerInfo> queryStyleInfo(String ppId,String seriesSex){ return sf30_052Service.queryStyleInfo(ppId,seriesSex); } }
2,494
0.746166
0.725989
74
32.486488
28.685736
106
false
false
0
0
0
0
0
0
0.540541
false
false
12
872082443978061cc785f71ca8c832156f720e33
23,175,643,560,205
32b72e1dc8b6ee1be2e80bb70a03a021c83db550
/ast_results/kromonos_Mustard-Mod/src/org/mumod/android/provider/StatusNet.java
08a67235a700c55c3dfa3786e1e914659771fc52
[]
no_license
cmFodWx5YWRhdjEyMTA5/smell-and-machine-learning
https://github.com/cmFodWx5YWRhdjEyMTA5/smell-and-machine-learning
d90c41a17e88fcd99d543124eeb6e93f9133cb4a
0564143d92f8024ff5fa6b659c2baebf827582b1
refs/heads/master
2020-07-13T13:53:40.297000
2019-01-11T11:51:18
2019-01-11T11:51:18
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
// isComment package org.mumod.android.provider; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import java.net.URLEncoder; import java.util.ArrayList; import oauth.signpost.commonshttp.CommonsHttpOAuthConsumer; import org.apache.http.NameValuePair; import org.apache.http.message.BasicNameValuePair; import org.apache.http.protocol.HTTP; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.mumod.android.Account; import org.mumod.android.MustardApplication; import org.mumod.android.MustardDbAdapter; import org.mumod.android.Preferences; import org.mumod.rsd.Service; import org.mumod.statusnet.DirectMessage; import org.mumod.statusnet.Group; import org.mumod.statusnet.Relationship; import org.mumod.statusnet.Status; import org.mumod.statusnet.StatusNetService; import org.mumod.statusnet.User; import org.mumod.util.AuthException; import org.mumod.util.HttpManager; import org.mumod.util.MustardException; import org.w3c.dom.Attr; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import android.content.Context; import android.util.Log; public class isClassOrIsInterface { protected static final String isVariable = "isStringConstant"; // isComment private final String isVariable = "isStringConstant"; // isComment private final String isVariable = "isStringConstant"; private final String isVariable = "isStringConstant"; private final String isVariable = "isStringConstant"; private final String isVariable = "isStringConstant"; // isComment private final String isVariable = "isStringConstant"; // isComment private final String isVariable = "isStringConstant"; private final String isVariable = "isStringConstant"; // isComment private final String isVariable = "isStringConstant"; private final String isVariable = "isStringConstant"; private final String isVariable = "isStringConstant"; private final String isVariable = "isStringConstant"; private final String isVariable = "isStringConstant"; private final String isVariable = "isStringConstant"; private final String isVariable = "isStringConstant"; private final String isVariable = "isStringConstant"; private final String isVariable = "isStringConstant"; private final String isVariable = "isStringConstant"; private final String isVariable = "isStringConstant"; private final String isVariable = "isStringConstant"; private final String isVariable = "isStringConstant"; private final String isVariable = "isStringConstant"; // isComment private final String isVariable = "isStringConstant"; private final String isVariable = "isStringConstant"; private final String isVariable = "isStringConstant"; // isComment private final String isVariable = "isStringConstant"; private final String isVariable = "isStringConstant"; private final String isVariable = "isStringConstant"; private final String isVariable = "isStringConstant"; private final String isVariable = "isStringConstant"; private final String isVariable = "isStringConstant"; private final String isVariable = "isStringConstant"; // isComment private final String isVariable = "isStringConstant"; private final String isVariable = "isStringConstant"; private final String isVariable = "isStringConstant"; private final String isVariable = "isStringConstant"; private final String isVariable = "isStringConstant"; // isComment private final String isVariable = "isStringConstant"; // isComment private final String isVariable = "isStringConstant"; private HttpManager isVariable; private URL isVariable; private String isVariable; private long isVariable; private long isVariable; private int isVariable = isNameExpr.isFieldAccessExpr; private Context isVariable; private Account isVariable; public void isMethod() { if (isNameExpr.isMethod().isMethod("isStringConstant")) { isNameExpr = true; } else { isNameExpr = true; } } public Account isMethod() { return isNameExpr; } public void isMethod(Account isParameter) { this.isFieldAccessExpr = isNameExpr; } private boolean isVariable = true; public isConstructor(Context isParameter) { isNameExpr = isNameExpr; } public void isMethod(int isParameter) { isNameExpr = isNameExpr; } public void isMethod(URL isParameter) { isNameExpr = isNameExpr; String isVariable = isNameExpr.isMethod(); if (isNameExpr.isMethod("isStringConstant")) { isNameExpr = "isStringConstant"; try { isNameExpr = new URL("isStringConstant" + isNameExpr + "isStringConstant"); } catch (MalformedURLException isParameter) { // isComment isNameExpr.isMethod(); } isNameExpr = true; } isNameExpr = new HttpManager(isNameExpr, isNameExpr); } public URL isMethod() { return isNameExpr; } public void isMethod(String isParameter, String isParameter) throws MustardException { if (isNameExpr == null) { throw new MustardException("isStringConstant"); } isNameExpr.isMethod(isNameExpr, isNameExpr); this.isFieldAccessExpr = isNameExpr; return; } public void isMethod(CommonsHttpOAuthConsumer isParameter, String isParameter) throws MustardException { if (isNameExpr == null) { throw new MustardException("isStringConstant"); } isNameExpr.isMethod(isNameExpr); this.isFieldAccessExpr = isNameExpr; } public void isMethod(long isParameter) { this.isFieldAccessExpr = isNameExpr; } public long isMethod() { return isNameExpr; } public void isMethod(long isParameter) { this.isFieldAccessExpr = isNameExpr; } public long isMethod() { return isNameExpr; } public String isMethod() { return isNameExpr; } public User isMethod(String isParameter) throws MustardException { if (isNameExpr == null || "isStringConstant".isMethod(isNameExpr)) throw new MustardException("isStringConstant"); isMethod(); User isVariable = null; JSONObject isVariable = null; try { String isVariable = isNameExpr.isMethod() + (!isNameExpr ? isNameExpr : isNameExpr) + isNameExpr.isMethod("isStringConstant", isNameExpr.isMethod()); isNameExpr = isNameExpr.isMethod(isNameExpr, isNameExpr.isFieldAccessExpr); } catch (MustardException isParameter) { throw isNameExpr; } catch (Exception isParameter) { if (isNameExpr.isFieldAccessExpr) isNameExpr.isMethod(); throw new MustardException(isNameExpr.isMethod() == null ? isNameExpr.isMethod() : isNameExpr.isMethod()); } if (isNameExpr != null) { try { isNameExpr = isNameExpr.isMethod(isNameExpr); } catch (JSONException isParameter) { if (isNameExpr.isFieldAccessExpr) isNameExpr.isMethod(); throw new MustardException(isNameExpr.isMethod() == null ? isNameExpr.isMethod() : isNameExpr.isMethod()); } } return isNameExpr; } private String isMethod(Element isParameter) { String isVariable = "isStringConstant"; Node isVariable; int isVariable = isNameExpr.isMethod("isStringConstant").isMethod(); for (int isVariable = isIntegerConstant; isNameExpr < isNameExpr; isNameExpr++) { isNameExpr = isNameExpr.isMethod("isStringConstant").isMethod(isNameExpr); NamedNodeMap isVariable = isNameExpr.isMethod(); for (int isVariable = isIntegerConstant; isNameExpr < isNameExpr.isMethod(); isNameExpr++) { Attr isVariable = (Attr) isNameExpr.isMethod(isNameExpr); if (isNameExpr.isMethod().isMethod("isStringConstant") && isNameExpr.isMethod().isMethod("isStringConstant")) { try { if (isNameExpr.isMethod().isMethod("isStringConstant").isMethod().isMethod("isStringConstant")) isNameExpr = isNameExpr.isMethod().isMethod("isStringConstant").isMethod(); } catch (Exception isParameter) { if (isNameExpr.isFieldAccessExpr) isNameExpr.isMethod(); } } } } return isNameExpr; } public User isMethod(String isParameter) throws MustardException { if (isNameExpr == null || "isStringConstant".isMethod(isNameExpr)) throw new MustardException("isStringConstant"); User isVariable = null; JSONObject isVariable = null; String isVariable = "isStringConstant"; try { // isComment URL isVariable = new URL(isNameExpr); String isVariable = isNameExpr.isMethod(); HttpManager isVariable = new HttpManager(isNameExpr, isNameExpr); Document isVariable = isNameExpr.isMethod(isNameExpr, isNameExpr.isFieldAccessExpr, null); isNameExpr = isMethod(isNameExpr.isMethod()); isNameExpr.isMethod("isStringConstant", "isStringConstant" + isNameExpr); if (!isNameExpr.isMethod("isStringConstant")) { String isVariable = isNameExpr.isMethod(isIntegerConstant, isNameExpr.isMethod("isStringConstant")); isNameExpr += "isStringConstant"; String isVariable = isNameExpr.isMethod(isNameExpr.isMethod("isStringConstant") + isIntegerConstant, isNameExpr.isMethod("isStringConstant")); isNameExpr += isNameExpr; isNameExpr.isMethod("isStringConstant", "isStringConstant" + isNameExpr); isNameExpr = isNameExpr.isMethod(isNameExpr, isNameExpr.isFieldAccessExpr); } } catch (MustardException isParameter) { throw isNameExpr; } catch (Exception isParameter) { // isComment isNameExpr.isMethod(); throw new MustardException(isNameExpr.isMethod() == null ? isNameExpr.isMethod() : isNameExpr.isMethod()); } if (isNameExpr != null) { try { isNameExpr = isNameExpr.isMethod(isNameExpr); isNameExpr.isMethod(isNameExpr); } catch (JSONException isParameter) { if (isNameExpr.isFieldAccessExpr) isNameExpr.isMethod(); throw new MustardException(isNameExpr.isMethod() == null ? isNameExpr.isMethod() : isNameExpr.isMethod()); } } return isNameExpr; } public Group isMethod(String isParameter) throws MustardException { Group isVariable = null; JSONObject isVariable = null; isMethod(); try { String isVariable = isNameExpr.isMethod() + (!isNameExpr ? isNameExpr : isNameExpr) + isNameExpr.isMethod("isStringConstant", isNameExpr.isMethod()); isNameExpr = isNameExpr.isMethod(isNameExpr, isNameExpr.isFieldAccessExpr); } catch (MustardException isParameter) { throw isNameExpr; } catch (Exception isParameter) { if (isNameExpr.isFieldAccessExpr) isNameExpr.isMethod(); throw new MustardException(isNameExpr.isMethod() == null ? isNameExpr.isMethod() : isNameExpr.isMethod()); } if (isNameExpr != null) { try { isNameExpr = isNameExpr.isMethod(isNameExpr); } catch (JSONException isParameter) { throw new MustardException(isNameExpr.isMethod()); } } return isNameExpr; } public ArrayList<Status> isMethod(String isParameter) throws MustardException { String isVariable = "isStringConstant"; try { isNameExpr = isNameExpr.isMethod(isNameExpr, isNameExpr.isFieldAccessExpr); } catch (Exception isParameter) { throw new MustardException(isNameExpr.isMethod()); } String isVariable = "isStringConstant"; if (isNameExpr) isNameExpr = "isStringConstant" + isNameExpr + "isStringConstant" + isNameExpr + "isStringConstant" + isNameExpr + "isStringConstant"; else { isNameExpr = isNameExpr.isMethod() + "isStringConstant" + isNameExpr + "isStringConstant" + isNameExpr + "isStringConstant" + isNameExpr; } ArrayList<Status> isVariable = new ArrayList<Status>(); try { JSONObject isVariable = isNameExpr.isMethod(isNameExpr); // isComment JSONArray isVariable = isNameExpr.isMethod("isStringConstant"); for (int isVariable = isIntegerConstant; isNameExpr < isNameExpr.isMethod(); isNameExpr++) { try { JSONObject isVariable = isNameExpr.isMethod(isNameExpr); isNameExpr.isMethod(isNameExpr.isMethod(isNameExpr)); } catch (JSONException isParameter) { isNameExpr.isMethod(); } } if (isNameExpr.isFieldAccessExpr) isNameExpr.isMethod(isNameExpr, "isStringConstant" + isNameExpr.isMethod() + "isStringConstant"); } catch (IOException isParameter) { isNameExpr.isMethod(); throw new MustardException(isNameExpr.isMethod()); } catch (MustardException isParameter) { isNameExpr.isMethod(); throw new MustardException(isNameExpr.isMethod()); } catch (AuthException isParameter) { isNameExpr.isMethod(); throw new MustardException(isNameExpr.isMethod()); } catch (Exception isParameter) { isNameExpr.isMethod(); throw new MustardException(isNameExpr.isMethod()); } return isNameExpr; } public ArrayList<Status> isMethod(int isParameter, String isParameter, long isParameter, boolean isParameter) throws MustardException { switch(isNameExpr) { case isNameExpr.isFieldAccessExpr: return isMethod(isNameExpr, isNameExpr, isNameExpr); } return null; } public ArrayList<Status> isMethod(int isParameter, String isParameter, long isParameter, boolean isParameter) throws MustardException { switch(isNameExpr) { case isNameExpr.isFieldAccessExpr: return isMethod(isNameExpr, isNameExpr, isNameExpr); case isNameExpr.isFieldAccessExpr: return isMethod(isNameExpr, isNameExpr); case isNameExpr.isFieldAccessExpr: return isMethod(isNameExpr, isNameExpr, isNameExpr); case isNameExpr.isFieldAccessExpr: return isMethod(isNameExpr, isNameExpr, isNameExpr); case isNameExpr.isFieldAccessExpr: return isMethod(isNameExpr, isNameExpr, isNameExpr); case isNameExpr.isFieldAccessExpr: return isMethod(isNameExpr, isNameExpr, isNameExpr); case isNameExpr.isFieldAccessExpr: return isMethod(isNameExpr); case isNameExpr.isFieldAccessExpr: return isMethod(isNameExpr); case isNameExpr.isFieldAccessExpr: return isMethod(isNameExpr, isNameExpr, isNameExpr); case isNameExpr.isFieldAccessExpr: return isMethod(isNameExpr); } return null; } private String isMethod(long isParameter, boolean isParameter) { isMethod(); if (isNameExpr <= isIntegerConstant) return isNameExpr ? "isStringConstant" : "isStringConstant"; String isVariable = "isStringConstant"; if (isNameExpr) isNameExpr = "isStringConstant"; else isNameExpr = "isStringConstant"; return "isStringConstant" + isNameExpr + "isStringConstant" + isNameExpr + (isNameExpr ? "isStringConstant" : "isStringConstant"); } public ArrayList<Status> isMethod(long isParameter, boolean isParameter) throws MustardException { isMethod(); String isVariable = isMethod(isNameExpr, isNameExpr); String isVariable = isNameExpr.isMethod() + (!isNameExpr ? isNameExpr : isNameExpr) + isNameExpr + "isStringConstant" + isNameExpr + isNameExpr; return isMethod(isNameExpr); } public ArrayList<Status> isMethod(long isParameter, boolean isParameter) throws MustardException { return isMethod(isNameExpr, isNameExpr, isNameExpr); } public ArrayList<Status> isMethod(String isParameter, long isParameter, boolean isParameter) throws MustardException { String isVariable = isMethod(isNameExpr, isNameExpr); String isVariable = isNameExpr.isMethod("isStringConstant", "isStringConstant") + "isStringConstant" + isNameExpr + isNameExpr; return isMethod(isNameExpr); } public ArrayList<Status> isMethod(String isParameter, long isParameter, boolean isParameter) throws MustardException { isMethod(); String isVariable = isMethod(isNameExpr, isNameExpr); String isVariable = isNameExpr.isMethod() + (!isNameExpr ? isNameExpr : isNameExpr) + isNameExpr.isMethod("isStringConstant", isNameExpr.isMethod()) + "isStringConstant" + isNameExpr + isNameExpr; return isMethod(isNameExpr); } public ArrayList<Status> isMethod(String isParameter, long isParameter, boolean isParameter) throws MustardException { isMethod(); String isVariable = isMethod(isNameExpr, isNameExpr); String isVariable = isNameExpr.isMethod() + (!isNameExpr ? isNameExpr : isNameExpr) + isNameExpr.isMethod("isStringConstant", isNameExpr.isMethod()) + "isStringConstant" + isNameExpr + isNameExpr; return isMethod(isNameExpr); } public ArrayList<Status> isMethod(long isParameter, boolean isParameter) throws MustardException { return isMethod(isNameExpr, isNameExpr, isNameExpr); } public ArrayList<Status> isMethod(String isParameter, long isParameter, boolean isParameter) throws MustardException { isMethod(); String isVariable = isMethod(isNameExpr, isNameExpr); String isVariable = "isStringConstant"; if (isNameExpr) { isNameExpr = isNameExpr.isMethod() + isNameExpr + isNameExpr + "isStringConstant" + isNameExpr + isNameExpr; } else { isNameExpr = isNameExpr.isMethod() + isNameExpr + isNameExpr.isMethod("isStringConstant", isNameExpr.isMethod()) + "isStringConstant" + isNameExpr + isNameExpr; } return isMethod(isNameExpr); } public ArrayList<Status> isMethod(String isParameter, long isParameter, boolean isParameter) throws MustardException { String isVariable = isMethod(isNameExpr, isNameExpr); isMethod(); if (isNameExpr.isMethod("isStringConstant")) isNameExpr = isMethod(); String isVariable = isNameExpr.isMethod() + (!isNameExpr ? isNameExpr : isNameExpr) + isNameExpr.isMethod("isStringConstant", isNameExpr.isMethod()) + "isStringConstant" + isNameExpr + isNameExpr; return isMethod(isNameExpr); } public ArrayList<DirectMessage> isMethod(long isParameter, boolean isParameter) throws MustardException { String isVariable = isMethod(isNameExpr, isNameExpr); isMethod(); String isVariable = isNameExpr.isMethod() + (!isNameExpr ? isNameExpr : isNameExpr) + isNameExpr + "isStringConstant" + isNameExpr + isNameExpr; return isMethod(isNameExpr.isFieldAccessExpr, isNameExpr); } public ArrayList<DirectMessage> isMethod(long isParameter, boolean isParameter) throws MustardException { String isVariable = isMethod(isNameExpr, isNameExpr); isMethod(); String isVariable = isNameExpr.isMethod() + (!isNameExpr ? isNameExpr : isNameExpr) + isNameExpr + "isStringConstant" + isNameExpr + isNameExpr; return isMethod(isNameExpr.isFieldAccessExpr, isNameExpr); } public ArrayList<Status> isMethod(String isParameter, long isParameter, boolean isParameter) throws MustardException { String isVariable = isMethod(isNameExpr, isNameExpr); isMethod(); String isVariable = isNameExpr.isMethod() + (!isNameExpr ? isNameExpr : isNameExpr) + isNameExpr.isMethod("isStringConstant", isNameExpr.isMethod()) + "isStringConstant" + isNameExpr + isNameExpr; return isMethod(isNameExpr); } public ArrayList<Status> isMethod(String isParameter, long isParameter, boolean isParameter) throws MustardException { String isVariable = isMethod(isNameExpr, isNameExpr); isMethod(); String isVariable = isNameExpr.isMethod() + (!isNameExpr ? isNameExpr : isNameExpr) + isNameExpr.isMethod("isStringConstant", isNameExpr.isMethod()) + "isStringConstant" + isNameExpr + isNameExpr; return isMethod(isNameExpr); } public Status isMethod(String isParameter, boolean isParameter) throws MustardException { Status isVariable = null; isMethod(); String isVariable = isNameExpr.isMethod() + (!isNameExpr ? isNameExpr : isNameExpr) + isNameExpr.isMethod("isStringConstant", isNameExpr); try { JSONObject isVariable = isNameExpr.isMethod(isNameExpr); isNameExpr = isNameExpr.isMethod(isNameExpr); } catch (Exception isParameter) { if (isNameExpr.isFieldAccessExpr) isNameExpr.isMethod(); } return isNameExpr; } public ArrayList<Status> isMethod(String isParameter) throws MustardException { ArrayList<Status> isVariable = new ArrayList<Status>(); Status isVariable = isMethod(isNameExpr, true); isNameExpr.isMethod(isNameExpr); while (true) { try { long isVariable = isNameExpr.isMethod().isMethod(); if (isNameExpr > isIntegerConstant) { isNameExpr = isMethod(isNameExpr.isMethod(isNameExpr), true); isNameExpr.isMethod(isNameExpr); } else { break; } } catch (Exception isParameter) { if (isNameExpr.isFieldAccessExpr) isNameExpr.isMethod(); break; } } return isNameExpr; } public ArrayList<Status> isMethod(String isParameter) throws MustardException { ArrayList<Status> isVariable = new ArrayList<Status>(isIntegerConstant); isNameExpr.isMethod(isMethod(isNameExpr, true)); return isNameExpr; } private ArrayList<Status> isMethod(String isParameter) throws MustardException { if (isNameExpr.isFieldAccessExpr) isNameExpr.isMethod("isStringConstant", isNameExpr); ArrayList<Status> isVariable = new ArrayList<Status>(); try { URL isVariable = new URL(isNameExpr); HttpManager isVariable = new HttpManager(isNameExpr, isNameExpr.isMethod()); JSONArray isVariable = isNameExpr.isMethod(isNameExpr); for (int isVariable = isIntegerConstant; isNameExpr < isNameExpr.isMethod(); isNameExpr++) { try { JSONObject isVariable = isNameExpr.isMethod(isNameExpr); isNameExpr.isMethod(isNameExpr.isMethod(isNameExpr)); } catch (JSONException isParameter) { isNameExpr.isMethod(); } } } catch (IOException isParameter) { isNameExpr.isMethod(); throw new MustardException(isNameExpr.isMethod()); } catch (MustardException isParameter) { isNameExpr.isMethod(); throw new MustardException(isNameExpr.isMethod()); } catch (AuthException isParameter) { isNameExpr.isMethod(); throw new MustardException(isNameExpr.isMethod()); } catch (Exception isParameter) { isNameExpr.isMethod(); throw new MustardException(isNameExpr.isMethod()); } return isNameExpr; } private ArrayList<Status> isMethod(String isParameter) throws MustardException { if (isNameExpr.isFieldAccessExpr) isNameExpr.isMethod("isStringConstant", isNameExpr); ArrayList<Status> isVariable = new ArrayList<Status>(); try { JSONArray isVariable = isNameExpr.isMethod(isNameExpr); for (int isVariable = isIntegerConstant; isNameExpr < isNameExpr.isMethod(); isNameExpr++) { try { JSONObject isVariable = isNameExpr.isMethod(isNameExpr); isNameExpr.isMethod(isNameExpr.isMethod(isNameExpr)); } catch (JSONException isParameter) { isNameExpr.isMethod(); } } } catch (IOException isParameter) { isNameExpr.isMethod(); throw new MustardException(isNameExpr.isMethod()); } catch (MustardException isParameter) { isNameExpr.isMethod(); throw new MustardException(isNameExpr.isMethod()); } catch (AuthException isParameter) { isNameExpr.isMethod(); throw new MustardException(isNameExpr.isMethod()); } catch (Exception isParameter) { isNameExpr.isMethod(); throw new MustardException(isNameExpr.isMethod()); } return isNameExpr; } private ArrayList<DirectMessage> isMethod(int isParameter, String isParameter) throws MustardException { // isComment isNameExpr.isMethod("isStringConstant", isNameExpr); ArrayList<DirectMessage> isVariable = new ArrayList<DirectMessage>(); try { JSONArray isVariable = isNameExpr.isMethod(isNameExpr, isNameExpr.isFieldAccessExpr, null, true); for (int isVariable = isIntegerConstant; isNameExpr < isNameExpr.isMethod(); isNameExpr++) { try { JSONObject isVariable = isNameExpr.isMethod(isNameExpr); isNameExpr.isMethod(isNameExpr.isMethod(isNameExpr, isNameExpr)); } catch (JSONException isParameter) { isNameExpr.isMethod(); } } } catch (IOException isParameter) { isNameExpr.isMethod(); throw new MustardException(isNameExpr.isMethod()); } catch (MustardException isParameter) { isNameExpr.isMethod(); throw new MustardException(isNameExpr.isMethod()); } catch (AuthException isParameter) { isNameExpr.isMethod(); throw new MustardException(isNameExpr.isMethod()); } catch (Exception isParameter) { isNameExpr.isMethod(); throw new MustardException(isNameExpr.isMethod()); } return isNameExpr; } public User isMethod() throws MustardException { isMethod(); isNameExpr.isMethod("isStringConstant", "isStringConstant" + isNameExpr + "isStringConstant" + isNameExpr.isMethod() + (!isNameExpr ? "isStringConstant" : "isStringConstant") + isNameExpr); User isVariable = null; JSONObject isVariable = null; try { String isVariable = isNameExpr.isMethod() + (!isNameExpr ? isNameExpr : isNameExpr) + isNameExpr; isNameExpr = isNameExpr.isMethod(isNameExpr, isNameExpr.isFieldAccessExpr); } catch (MustardException isParameter) { throw isNameExpr; } catch (Exception isParameter) { if (isNameExpr.isFieldAccessExpr) isNameExpr.isMethod(); throw new MustardException(isNameExpr.isMethod() == null ? isNameExpr.isMethod() : isNameExpr.isMethod()); } if (isNameExpr != null) { try { isNameExpr = isNameExpr.isMethod(isNameExpr); } catch (JSONException isParameter) { if (isNameExpr.isFieldAccessExpr) isNameExpr.isMethod(); throw new MustardException(isNameExpr.isMethod() == null ? isNameExpr.isMethod() : isNameExpr.isMethod()); } } return isNameExpr; } public boolean isMethod(String isParameter) { isMethod(); String isVariable = isNameExpr.isMethod() + (!isNameExpr ? isNameExpr : isNameExpr) + isNameExpr.isMethod("isStringConstant", isNameExpr); try { isNameExpr.isMethod(isNameExpr, isNameExpr.isFieldAccessExpr); } catch (Exception isParameter) { if (isNameExpr.isFieldAccessExpr) isNameExpr.isMethod(isNameExpr, isNameExpr.isMethod()); return true; } return true; } public boolean isMethod(String isParameter) { isMethod(); if (!isNameExpr) { String isVariable = isNameExpr.isMethod() + isNameExpr + isNameExpr.isMethod("isStringConstant", isNameExpr); try { isNameExpr.isMethod(isNameExpr, isNameExpr.isFieldAccessExpr); } catch (Exception isParameter) { if (isNameExpr.isFieldAccessExpr) isNameExpr.isMethod(isNameExpr, isNameExpr.isMethod()); return true; } } else { String isVariable = isNameExpr.isMethod() + isNameExpr + isNameExpr; try { ArrayList<NameValuePair> isVariable = new ArrayList<NameValuePair>(); isNameExpr.isMethod(new BasicNameValuePair("isStringConstant", isNameExpr)); isNameExpr.isMethod(isNameExpr, isNameExpr.isFieldAccessExpr, isNameExpr); } catch (Exception isParameter) { if (isNameExpr.isFieldAccessExpr) isNameExpr.isMethod(isNameExpr, isNameExpr.isMethod()); return true; } } return true; } public boolean isMethod(String isParameter) { isMethod(); if (!isNameExpr) { String isVariable = isNameExpr.isMethod() + isNameExpr + isNameExpr.isMethod("isStringConstant", isNameExpr); try { isNameExpr.isMethod(isNameExpr, isNameExpr.isFieldAccessExpr); } catch (Exception isParameter) { if (isNameExpr.isFieldAccessExpr) isNameExpr.isMethod(isNameExpr, isNameExpr.isMethod()); return true; } } else { String isVariable = isNameExpr.isMethod() + isNameExpr + isNameExpr; try { ArrayList<NameValuePair> isVariable = new ArrayList<NameValuePair>(); isNameExpr.isMethod(new BasicNameValuePair("isStringConstant", isNameExpr)); isNameExpr.isMethod(isNameExpr, isNameExpr.isFieldAccessExpr, isNameExpr); } catch (Exception isParameter) { if (isNameExpr.isFieldAccessExpr) isNameExpr.isMethod(isNameExpr, isNameExpr.isMethod()); return true; } } return true; } public boolean isMethod(String isParameter) { isMethod(); String isVariable = isNameExpr.isMethod() + (!isNameExpr ? isNameExpr : isNameExpr) + isNameExpr.isMethod("isStringConstant", isNameExpr); try { isNameExpr.isMethod(isNameExpr, isNameExpr.isFieldAccessExpr); } catch (Exception isParameter) { if (isNameExpr.isFieldAccessExpr) isNameExpr.isMethod(isNameExpr, isNameExpr.isMethod()); return true; } return true; } public boolean isMethod(String isParameter) throws MustardException { isMethod(); String isVariable = isNameExpr.isMethod() + (!isNameExpr ? isNameExpr : isNameExpr) + isNameExpr.isMethod("isStringConstant", isNameExpr); try { if (isNameExpr.isFieldAccessExpr) isNameExpr.isMethod(isNameExpr, isNameExpr); isNameExpr.isMethod(isNameExpr, isNameExpr.isFieldAccessExpr); } catch (MustardException isParameter) { throw isNameExpr; } catch (Exception isParameter) { if (isNameExpr.isFieldAccessExpr) isNameExpr.isMethod(isNameExpr, isNameExpr.isMethod()); throw new MustardException(isNameExpr.isMethod() == null ? isNameExpr.isMethod() : isNameExpr.isMethod()); } return true; } public boolean isMethod(String isParameter) throws MustardException { isMethod(); String isVariable = isNameExpr.isMethod() + (!isNameExpr ? isNameExpr : isNameExpr) + isNameExpr.isMethod("isStringConstant", isNameExpr); try { if (isNameExpr.isFieldAccessExpr) isNameExpr.isMethod(isNameExpr, isNameExpr); isNameExpr.isMethod(isNameExpr, isNameExpr.isFieldAccessExpr); } catch (MustardException isParameter) { throw isNameExpr; } catch (Exception isParameter) { // isComment if (isNameExpr.isFieldAccessExpr) isNameExpr.isMethod(isNameExpr, isNameExpr.isMethod()); throw new MustardException(isNameExpr.isMethod() == null ? isNameExpr.isMethod() : isNameExpr.isMethod()); } return true; } public boolean isMethod(String isParameter) { isMethod(); String isVariable = isNameExpr.isMethod() + (!isNameExpr ? isNameExpr : isNameExpr) + isNameExpr.isMethod("isStringConstant", isNameExpr); try { isNameExpr.isMethod(isNameExpr, isNameExpr.isFieldAccessExpr); // isComment } catch (Exception isParameter) { // isComment isNameExpr.isMethod(isNameExpr, isNameExpr.isMethod()); return true; } return true; } public boolean isMethod(String isParameter) { isMethod(); String isVariable = isNameExpr.isMethod() + (!isNameExpr ? isNameExpr : isNameExpr) + isNameExpr.isMethod("isStringConstant", isNameExpr); try { isNameExpr.isMethod(isNameExpr, isNameExpr.isFieldAccessExpr); // isComment } catch (Exception isParameter) { // isComment isNameExpr.isMethod(isNameExpr, isNameExpr.isMethod()); return true; } return true; } public boolean isMethod(String isParameter) { isMethod(); String isVariable = isNameExpr.isMethod() + (!isNameExpr ? isNameExpr : isNameExpr) + isNameExpr.isMethod("isStringConstant", isNameExpr); try { isNameExpr.isMethod(isNameExpr, isNameExpr.isFieldAccessExpr); } catch (Exception isParameter) { if (isNameExpr.isFieldAccessExpr) isNameExpr.isMethod(isNameExpr, isNameExpr.isMethod()); return true; } return true; } public boolean isMethod(String isParameter) { isMethod(); String isVariable = isNameExpr.isMethod() + (!isNameExpr ? isNameExpr : isNameExpr) + isNameExpr.isMethod("isStringConstant", isNameExpr); try { isNameExpr.isMethod(isNameExpr, isNameExpr.isFieldAccessExpr); } catch (Exception isParameter) { if (isNameExpr.isFieldAccessExpr) isNameExpr.isMethod(isNameExpr, isNameExpr.isMethod()); return true; } return true; } public Relationship isMethod(String isParameter) { isMethod(); Relationship isVariable = null; String isVariable = isNameExpr.isMethod() + isNameExpr.isMethod("isStringConstant", isNameExpr); if (isNameExpr) isNameExpr = isNameExpr.isMethod() + isNameExpr.isMethod("isStringConstant", isNameExpr).isMethod("isStringConstant", isNameExpr); try { JSONObject isVariable = isNameExpr.isMethod(isNameExpr, isNameExpr.isFieldAccessExpr); isNameExpr = isNameExpr.isMethod(isNameExpr); } catch (Exception isParameter) { if (isNameExpr.isFieldAccessExpr) isNameExpr.isMethod(isNameExpr, isNameExpr.isMethod()); isNameExpr.isMethod(); } return isNameExpr; } public boolean isMethod(String isParameter) { isMethod(); String isVariable = isNameExpr.isMethod() + (!isNameExpr ? isNameExpr : isNameExpr) + isNameExpr.isMethod("isStringConstant", isNameExpr); try { JSONObject isVariable = isNameExpr.isMethod(isNameExpr, isNameExpr.isFieldAccessExpr); return isNameExpr.isMethod("isStringConstant"); } catch (Exception isParameter) { isNameExpr.isMethod(); if (isNameExpr.isFieldAccessExpr) isNameExpr.isMethod(isNameExpr, isNameExpr.isMethod()); return true; } } public String isMethod() { isMethod(); String isVariable = null; try { String isVariable = isNameExpr.isMethod() + (!isNameExpr ? isNameExpr : isNameExpr) + isNameExpr; isNameExpr = isNameExpr.isMethod(isNameExpr, isNameExpr.isFieldAccessExpr); if (isNameExpr != null) { isNameExpr = isNameExpr.isMethod(); if (isNameExpr.isMethod("isStringConstant")) isNameExpr = isNameExpr.isMethod("isStringConstant", "isStringConstant"); } } catch (MustardException isParameter) { isNameExpr.isMethod(); } catch (AuthException isParameter) { isNameExpr.isMethod(); } catch (IOException isParameter) { isNameExpr.isMethod(); } catch (Exception isParameter) { isNameExpr.isMethod(); } return isNameExpr; } public Service isMethod() { Service isVariable = null; InputStream isVariable = null; try { String isVariable = isNameExpr.isMethod() + isNameExpr; isNameExpr = isNameExpr.isMethod(isNameExpr, isNameExpr.isFieldAccessExpr, null); isNameExpr = isNameExpr.isMethod(isNameExpr); } catch (MustardException isParameter) { isNameExpr.isMethod(); } catch (AuthException isParameter) { isNameExpr.isMethod(); } catch (IOException isParameter) { isNameExpr.isMethod(); } catch (Exception isParameter) { isNameExpr.isMethod(); } finally { if (isNameExpr != null) { try { isNameExpr.isMethod(); } catch (IOException isParameter) { } } } return isNameExpr; } public boolean isMethod() { isMethod(); boolean isVariable = true; try { String isVariable = isNameExpr.isMethod() + (!isNameExpr ? isNameExpr : isNameExpr) + isNameExpr; String isVariable = isNameExpr.isMethod(isNameExpr, isNameExpr.isFieldAccessExpr); if (isNameExpr != null) { isNameExpr = isNameExpr.isMethod(); if (isNameExpr.isMethod("isStringConstant")) isNameExpr = isNameExpr.isMethod("isStringConstant", "isStringConstant"); if (isNameExpr.isMethod("isStringConstant")) isNameExpr = true; } } catch (MustardException isParameter) { isNameExpr.isMethod(); } catch (AuthException isParameter) { isNameExpr.isMethod(); } catch (IOException isParameter) { isNameExpr.isMethod(); } catch (Exception isParameter) { isNameExpr.isMethod(); } return isNameExpr; } public long isMethod(String isParameter, String isParameter) throws MustardException, AuthException { isMethod(); ArrayList<NameValuePair> isVariable = new ArrayList<NameValuePair>(); isNameExpr.isMethod(new BasicNameValuePair("isStringConstant", isNameExpr)); isNameExpr.isMethod(new BasicNameValuePair("isStringConstant", isNameExpr)); isNameExpr.isMethod(new BasicNameValuePair("isStringConstant", isNameExpr.isFieldAccessExpr)); String isVariable = isNameExpr.isMethod() + (!isNameExpr ? isNameExpr : isNameExpr) + isNameExpr; JSONObject isVariable = null; long isVariable = -isIntegerConstant; try { String isVariable = isNameExpr.isMethod(isNameExpr, isNameExpr.isFieldAccessExpr, isNameExpr); isNameExpr = new JSONObject(isNameExpr); isNameExpr = isNameExpr.isMethod("isStringConstant"); } catch (AuthException isParameter) { throw isNameExpr; } catch (MustardException isParameter) { if (isNameExpr.isFieldAccessExpr) isNameExpr.isMethod(); throw isNameExpr; } catch (Exception isParameter) { if (isNameExpr.isFieldAccessExpr) isNameExpr.isMethod(); throw new MustardException(isNameExpr.isMethod()); } return isNameExpr; } public StatusNetService isMethod() throws MustardException { isMethod(); StatusNetService isVariable = new StatusNetService(); JSONObject isVariable = null; try { String isVariable = isNameExpr.isMethod() + (!isNameExpr ? isNameExpr : isNameExpr) + isNameExpr; isNameExpr = isNameExpr.isMethod(isNameExpr); // isComment isNameExpr = isNameExpr.isMethod(isNameExpr); } catch (MustardException isParameter) { throw isNameExpr; } catch (AuthException isParameter) { // isComment throw new MustardException(isNameExpr.isMethod()); } catch (IOException isParameter) { throw new MustardException(isNameExpr.isMethod()); } catch (JSONException isParameter) { throw new MustardException(isNameExpr.isMethod()); } return isNameExpr; } public long isMethod(String isParameter, String isParameter) throws MustardException, AuthException { return isMethod(isNameExpr, isNameExpr, null, null, null); } public long isMethod(String isParameter, String isParameter, String isParameter, String isParameter) throws MustardException, AuthException { return isMethod(isNameExpr, isNameExpr, isNameExpr, isNameExpr, null); } public long isMethod(String isParameter, String isParameter, String isParameter, String isParameter, File isParameter) throws MustardException, AuthException { isMethod(); ArrayList<NameValuePair> isVariable = new ArrayList<NameValuePair>(); isNameExpr.isMethod(new BasicNameValuePair("isStringConstant", isNameExpr)); isNameExpr.isMethod(new BasicNameValuePair("isStringConstant", isNameExpr.isFieldAccessExpr)); if (!isNameExpr.isMethod("isStringConstant") && !isNameExpr.isMethod("isStringConstant")) isNameExpr.isMethod(new BasicNameValuePair("isStringConstant", isNameExpr)); if (isNameExpr != null && !"isStringConstant".isMethod(isNameExpr)) isNameExpr.isMethod(new BasicNameValuePair("isStringConstant", isNameExpr)); if (isNameExpr != null && !"isStringConstant".isMethod(isNameExpr)) isNameExpr.isMethod(new BasicNameValuePair("isStringConstant", isNameExpr)); String isVariable = isNameExpr.isMethod() + (!isNameExpr ? isNameExpr : isNameExpr) + isNameExpr; JSONObject isVariable = null; long isVariable = -isIntegerConstant; try { if (isNameExpr == null) { // isComment // isComment // isComment // isComment // isComment isNameExpr = isNameExpr.isMethod(isNameExpr, isNameExpr.isFieldAccessExpr, isNameExpr); } else { if (!isNameExpr) isNameExpr = isNameExpr.isMethod(isNameExpr, isNameExpr, "isStringConstant", isNameExpr); } // isComment Status isVariable = isNameExpr.isMethod(isNameExpr); isNameExpr = isNameExpr.isMethod().isMethod(); } catch (AuthException isParameter) { throw isNameExpr; } catch (MustardException isParameter) { if (isNameExpr.isFieldAccessExpr) isNameExpr.isMethod(); throw isNameExpr; } catch (Exception isParameter) { if (isNameExpr.isFieldAccessExpr) isNameExpr.isMethod(); throw new MustardException(isNameExpr.isMethod()); } return isNameExpr; } public boolean isMethod(File isParameter) throws MustardException { isMethod(); String isVariable = isNameExpr.isMethod() + (!isNameExpr ? isNameExpr : isNameExpr) + isNameExpr; try { isNameExpr.isMethod(isNameExpr, null, "isStringConstant", isNameExpr); return true; } catch (Exception isParameter) { if (isNameExpr.isFieldAccessExpr) isNameExpr.isMethod(); throw new MustardException(isNameExpr.isMethod()); } } public boolean isMethod() { return isNameExpr; } }
UTF-8
Java
45,794
java
StatusNet.java
Java
[]
null
[]
// isComment package org.mumod.android.provider; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import java.net.URLEncoder; import java.util.ArrayList; import oauth.signpost.commonshttp.CommonsHttpOAuthConsumer; import org.apache.http.NameValuePair; import org.apache.http.message.BasicNameValuePair; import org.apache.http.protocol.HTTP; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.mumod.android.Account; import org.mumod.android.MustardApplication; import org.mumod.android.MustardDbAdapter; import org.mumod.android.Preferences; import org.mumod.rsd.Service; import org.mumod.statusnet.DirectMessage; import org.mumod.statusnet.Group; import org.mumod.statusnet.Relationship; import org.mumod.statusnet.Status; import org.mumod.statusnet.StatusNetService; import org.mumod.statusnet.User; import org.mumod.util.AuthException; import org.mumod.util.HttpManager; import org.mumod.util.MustardException; import org.w3c.dom.Attr; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import android.content.Context; import android.util.Log; public class isClassOrIsInterface { protected static final String isVariable = "isStringConstant"; // isComment private final String isVariable = "isStringConstant"; // isComment private final String isVariable = "isStringConstant"; private final String isVariable = "isStringConstant"; private final String isVariable = "isStringConstant"; private final String isVariable = "isStringConstant"; // isComment private final String isVariable = "isStringConstant"; // isComment private final String isVariable = "isStringConstant"; private final String isVariable = "isStringConstant"; // isComment private final String isVariable = "isStringConstant"; private final String isVariable = "isStringConstant"; private final String isVariable = "isStringConstant"; private final String isVariable = "isStringConstant"; private final String isVariable = "isStringConstant"; private final String isVariable = "isStringConstant"; private final String isVariable = "isStringConstant"; private final String isVariable = "isStringConstant"; private final String isVariable = "isStringConstant"; private final String isVariable = "isStringConstant"; private final String isVariable = "isStringConstant"; private final String isVariable = "isStringConstant"; private final String isVariable = "isStringConstant"; private final String isVariable = "isStringConstant"; // isComment private final String isVariable = "isStringConstant"; private final String isVariable = "isStringConstant"; private final String isVariable = "isStringConstant"; // isComment private final String isVariable = "isStringConstant"; private final String isVariable = "isStringConstant"; private final String isVariable = "isStringConstant"; private final String isVariable = "isStringConstant"; private final String isVariable = "isStringConstant"; private final String isVariable = "isStringConstant"; private final String isVariable = "isStringConstant"; // isComment private final String isVariable = "isStringConstant"; private final String isVariable = "isStringConstant"; private final String isVariable = "isStringConstant"; private final String isVariable = "isStringConstant"; private final String isVariable = "isStringConstant"; // isComment private final String isVariable = "isStringConstant"; // isComment private final String isVariable = "isStringConstant"; private HttpManager isVariable; private URL isVariable; private String isVariable; private long isVariable; private long isVariable; private int isVariable = isNameExpr.isFieldAccessExpr; private Context isVariable; private Account isVariable; public void isMethod() { if (isNameExpr.isMethod().isMethod("isStringConstant")) { isNameExpr = true; } else { isNameExpr = true; } } public Account isMethod() { return isNameExpr; } public void isMethod(Account isParameter) { this.isFieldAccessExpr = isNameExpr; } private boolean isVariable = true; public isConstructor(Context isParameter) { isNameExpr = isNameExpr; } public void isMethod(int isParameter) { isNameExpr = isNameExpr; } public void isMethod(URL isParameter) { isNameExpr = isNameExpr; String isVariable = isNameExpr.isMethod(); if (isNameExpr.isMethod("isStringConstant")) { isNameExpr = "isStringConstant"; try { isNameExpr = new URL("isStringConstant" + isNameExpr + "isStringConstant"); } catch (MalformedURLException isParameter) { // isComment isNameExpr.isMethod(); } isNameExpr = true; } isNameExpr = new HttpManager(isNameExpr, isNameExpr); } public URL isMethod() { return isNameExpr; } public void isMethod(String isParameter, String isParameter) throws MustardException { if (isNameExpr == null) { throw new MustardException("isStringConstant"); } isNameExpr.isMethod(isNameExpr, isNameExpr); this.isFieldAccessExpr = isNameExpr; return; } public void isMethod(CommonsHttpOAuthConsumer isParameter, String isParameter) throws MustardException { if (isNameExpr == null) { throw new MustardException("isStringConstant"); } isNameExpr.isMethod(isNameExpr); this.isFieldAccessExpr = isNameExpr; } public void isMethod(long isParameter) { this.isFieldAccessExpr = isNameExpr; } public long isMethod() { return isNameExpr; } public void isMethod(long isParameter) { this.isFieldAccessExpr = isNameExpr; } public long isMethod() { return isNameExpr; } public String isMethod() { return isNameExpr; } public User isMethod(String isParameter) throws MustardException { if (isNameExpr == null || "isStringConstant".isMethod(isNameExpr)) throw new MustardException("isStringConstant"); isMethod(); User isVariable = null; JSONObject isVariable = null; try { String isVariable = isNameExpr.isMethod() + (!isNameExpr ? isNameExpr : isNameExpr) + isNameExpr.isMethod("isStringConstant", isNameExpr.isMethod()); isNameExpr = isNameExpr.isMethod(isNameExpr, isNameExpr.isFieldAccessExpr); } catch (MustardException isParameter) { throw isNameExpr; } catch (Exception isParameter) { if (isNameExpr.isFieldAccessExpr) isNameExpr.isMethod(); throw new MustardException(isNameExpr.isMethod() == null ? isNameExpr.isMethod() : isNameExpr.isMethod()); } if (isNameExpr != null) { try { isNameExpr = isNameExpr.isMethod(isNameExpr); } catch (JSONException isParameter) { if (isNameExpr.isFieldAccessExpr) isNameExpr.isMethod(); throw new MustardException(isNameExpr.isMethod() == null ? isNameExpr.isMethod() : isNameExpr.isMethod()); } } return isNameExpr; } private String isMethod(Element isParameter) { String isVariable = "isStringConstant"; Node isVariable; int isVariable = isNameExpr.isMethod("isStringConstant").isMethod(); for (int isVariable = isIntegerConstant; isNameExpr < isNameExpr; isNameExpr++) { isNameExpr = isNameExpr.isMethod("isStringConstant").isMethod(isNameExpr); NamedNodeMap isVariable = isNameExpr.isMethod(); for (int isVariable = isIntegerConstant; isNameExpr < isNameExpr.isMethod(); isNameExpr++) { Attr isVariable = (Attr) isNameExpr.isMethod(isNameExpr); if (isNameExpr.isMethod().isMethod("isStringConstant") && isNameExpr.isMethod().isMethod("isStringConstant")) { try { if (isNameExpr.isMethod().isMethod("isStringConstant").isMethod().isMethod("isStringConstant")) isNameExpr = isNameExpr.isMethod().isMethod("isStringConstant").isMethod(); } catch (Exception isParameter) { if (isNameExpr.isFieldAccessExpr) isNameExpr.isMethod(); } } } } return isNameExpr; } public User isMethod(String isParameter) throws MustardException { if (isNameExpr == null || "isStringConstant".isMethod(isNameExpr)) throw new MustardException("isStringConstant"); User isVariable = null; JSONObject isVariable = null; String isVariable = "isStringConstant"; try { // isComment URL isVariable = new URL(isNameExpr); String isVariable = isNameExpr.isMethod(); HttpManager isVariable = new HttpManager(isNameExpr, isNameExpr); Document isVariable = isNameExpr.isMethod(isNameExpr, isNameExpr.isFieldAccessExpr, null); isNameExpr = isMethod(isNameExpr.isMethod()); isNameExpr.isMethod("isStringConstant", "isStringConstant" + isNameExpr); if (!isNameExpr.isMethod("isStringConstant")) { String isVariable = isNameExpr.isMethod(isIntegerConstant, isNameExpr.isMethod("isStringConstant")); isNameExpr += "isStringConstant"; String isVariable = isNameExpr.isMethod(isNameExpr.isMethod("isStringConstant") + isIntegerConstant, isNameExpr.isMethod("isStringConstant")); isNameExpr += isNameExpr; isNameExpr.isMethod("isStringConstant", "isStringConstant" + isNameExpr); isNameExpr = isNameExpr.isMethod(isNameExpr, isNameExpr.isFieldAccessExpr); } } catch (MustardException isParameter) { throw isNameExpr; } catch (Exception isParameter) { // isComment isNameExpr.isMethod(); throw new MustardException(isNameExpr.isMethod() == null ? isNameExpr.isMethod() : isNameExpr.isMethod()); } if (isNameExpr != null) { try { isNameExpr = isNameExpr.isMethod(isNameExpr); isNameExpr.isMethod(isNameExpr); } catch (JSONException isParameter) { if (isNameExpr.isFieldAccessExpr) isNameExpr.isMethod(); throw new MustardException(isNameExpr.isMethod() == null ? isNameExpr.isMethod() : isNameExpr.isMethod()); } } return isNameExpr; } public Group isMethod(String isParameter) throws MustardException { Group isVariable = null; JSONObject isVariable = null; isMethod(); try { String isVariable = isNameExpr.isMethod() + (!isNameExpr ? isNameExpr : isNameExpr) + isNameExpr.isMethod("isStringConstant", isNameExpr.isMethod()); isNameExpr = isNameExpr.isMethod(isNameExpr, isNameExpr.isFieldAccessExpr); } catch (MustardException isParameter) { throw isNameExpr; } catch (Exception isParameter) { if (isNameExpr.isFieldAccessExpr) isNameExpr.isMethod(); throw new MustardException(isNameExpr.isMethod() == null ? isNameExpr.isMethod() : isNameExpr.isMethod()); } if (isNameExpr != null) { try { isNameExpr = isNameExpr.isMethod(isNameExpr); } catch (JSONException isParameter) { throw new MustardException(isNameExpr.isMethod()); } } return isNameExpr; } public ArrayList<Status> isMethod(String isParameter) throws MustardException { String isVariable = "isStringConstant"; try { isNameExpr = isNameExpr.isMethod(isNameExpr, isNameExpr.isFieldAccessExpr); } catch (Exception isParameter) { throw new MustardException(isNameExpr.isMethod()); } String isVariable = "isStringConstant"; if (isNameExpr) isNameExpr = "isStringConstant" + isNameExpr + "isStringConstant" + isNameExpr + "isStringConstant" + isNameExpr + "isStringConstant"; else { isNameExpr = isNameExpr.isMethod() + "isStringConstant" + isNameExpr + "isStringConstant" + isNameExpr + "isStringConstant" + isNameExpr; } ArrayList<Status> isVariable = new ArrayList<Status>(); try { JSONObject isVariable = isNameExpr.isMethod(isNameExpr); // isComment JSONArray isVariable = isNameExpr.isMethod("isStringConstant"); for (int isVariable = isIntegerConstant; isNameExpr < isNameExpr.isMethod(); isNameExpr++) { try { JSONObject isVariable = isNameExpr.isMethod(isNameExpr); isNameExpr.isMethod(isNameExpr.isMethod(isNameExpr)); } catch (JSONException isParameter) { isNameExpr.isMethod(); } } if (isNameExpr.isFieldAccessExpr) isNameExpr.isMethod(isNameExpr, "isStringConstant" + isNameExpr.isMethod() + "isStringConstant"); } catch (IOException isParameter) { isNameExpr.isMethod(); throw new MustardException(isNameExpr.isMethod()); } catch (MustardException isParameter) { isNameExpr.isMethod(); throw new MustardException(isNameExpr.isMethod()); } catch (AuthException isParameter) { isNameExpr.isMethod(); throw new MustardException(isNameExpr.isMethod()); } catch (Exception isParameter) { isNameExpr.isMethod(); throw new MustardException(isNameExpr.isMethod()); } return isNameExpr; } public ArrayList<Status> isMethod(int isParameter, String isParameter, long isParameter, boolean isParameter) throws MustardException { switch(isNameExpr) { case isNameExpr.isFieldAccessExpr: return isMethod(isNameExpr, isNameExpr, isNameExpr); } return null; } public ArrayList<Status> isMethod(int isParameter, String isParameter, long isParameter, boolean isParameter) throws MustardException { switch(isNameExpr) { case isNameExpr.isFieldAccessExpr: return isMethod(isNameExpr, isNameExpr, isNameExpr); case isNameExpr.isFieldAccessExpr: return isMethod(isNameExpr, isNameExpr); case isNameExpr.isFieldAccessExpr: return isMethod(isNameExpr, isNameExpr, isNameExpr); case isNameExpr.isFieldAccessExpr: return isMethod(isNameExpr, isNameExpr, isNameExpr); case isNameExpr.isFieldAccessExpr: return isMethod(isNameExpr, isNameExpr, isNameExpr); case isNameExpr.isFieldAccessExpr: return isMethod(isNameExpr, isNameExpr, isNameExpr); case isNameExpr.isFieldAccessExpr: return isMethod(isNameExpr); case isNameExpr.isFieldAccessExpr: return isMethod(isNameExpr); case isNameExpr.isFieldAccessExpr: return isMethod(isNameExpr, isNameExpr, isNameExpr); case isNameExpr.isFieldAccessExpr: return isMethod(isNameExpr); } return null; } private String isMethod(long isParameter, boolean isParameter) { isMethod(); if (isNameExpr <= isIntegerConstant) return isNameExpr ? "isStringConstant" : "isStringConstant"; String isVariable = "isStringConstant"; if (isNameExpr) isNameExpr = "isStringConstant"; else isNameExpr = "isStringConstant"; return "isStringConstant" + isNameExpr + "isStringConstant" + isNameExpr + (isNameExpr ? "isStringConstant" : "isStringConstant"); } public ArrayList<Status> isMethod(long isParameter, boolean isParameter) throws MustardException { isMethod(); String isVariable = isMethod(isNameExpr, isNameExpr); String isVariable = isNameExpr.isMethod() + (!isNameExpr ? isNameExpr : isNameExpr) + isNameExpr + "isStringConstant" + isNameExpr + isNameExpr; return isMethod(isNameExpr); } public ArrayList<Status> isMethod(long isParameter, boolean isParameter) throws MustardException { return isMethod(isNameExpr, isNameExpr, isNameExpr); } public ArrayList<Status> isMethod(String isParameter, long isParameter, boolean isParameter) throws MustardException { String isVariable = isMethod(isNameExpr, isNameExpr); String isVariable = isNameExpr.isMethod("isStringConstant", "isStringConstant") + "isStringConstant" + isNameExpr + isNameExpr; return isMethod(isNameExpr); } public ArrayList<Status> isMethod(String isParameter, long isParameter, boolean isParameter) throws MustardException { isMethod(); String isVariable = isMethod(isNameExpr, isNameExpr); String isVariable = isNameExpr.isMethod() + (!isNameExpr ? isNameExpr : isNameExpr) + isNameExpr.isMethod("isStringConstant", isNameExpr.isMethod()) + "isStringConstant" + isNameExpr + isNameExpr; return isMethod(isNameExpr); } public ArrayList<Status> isMethod(String isParameter, long isParameter, boolean isParameter) throws MustardException { isMethod(); String isVariable = isMethod(isNameExpr, isNameExpr); String isVariable = isNameExpr.isMethod() + (!isNameExpr ? isNameExpr : isNameExpr) + isNameExpr.isMethod("isStringConstant", isNameExpr.isMethod()) + "isStringConstant" + isNameExpr + isNameExpr; return isMethod(isNameExpr); } public ArrayList<Status> isMethod(long isParameter, boolean isParameter) throws MustardException { return isMethod(isNameExpr, isNameExpr, isNameExpr); } public ArrayList<Status> isMethod(String isParameter, long isParameter, boolean isParameter) throws MustardException { isMethod(); String isVariable = isMethod(isNameExpr, isNameExpr); String isVariable = "isStringConstant"; if (isNameExpr) { isNameExpr = isNameExpr.isMethod() + isNameExpr + isNameExpr + "isStringConstant" + isNameExpr + isNameExpr; } else { isNameExpr = isNameExpr.isMethod() + isNameExpr + isNameExpr.isMethod("isStringConstant", isNameExpr.isMethod()) + "isStringConstant" + isNameExpr + isNameExpr; } return isMethod(isNameExpr); } public ArrayList<Status> isMethod(String isParameter, long isParameter, boolean isParameter) throws MustardException { String isVariable = isMethod(isNameExpr, isNameExpr); isMethod(); if (isNameExpr.isMethod("isStringConstant")) isNameExpr = isMethod(); String isVariable = isNameExpr.isMethod() + (!isNameExpr ? isNameExpr : isNameExpr) + isNameExpr.isMethod("isStringConstant", isNameExpr.isMethod()) + "isStringConstant" + isNameExpr + isNameExpr; return isMethod(isNameExpr); } public ArrayList<DirectMessage> isMethod(long isParameter, boolean isParameter) throws MustardException { String isVariable = isMethod(isNameExpr, isNameExpr); isMethod(); String isVariable = isNameExpr.isMethod() + (!isNameExpr ? isNameExpr : isNameExpr) + isNameExpr + "isStringConstant" + isNameExpr + isNameExpr; return isMethod(isNameExpr.isFieldAccessExpr, isNameExpr); } public ArrayList<DirectMessage> isMethod(long isParameter, boolean isParameter) throws MustardException { String isVariable = isMethod(isNameExpr, isNameExpr); isMethod(); String isVariable = isNameExpr.isMethod() + (!isNameExpr ? isNameExpr : isNameExpr) + isNameExpr + "isStringConstant" + isNameExpr + isNameExpr; return isMethod(isNameExpr.isFieldAccessExpr, isNameExpr); } public ArrayList<Status> isMethod(String isParameter, long isParameter, boolean isParameter) throws MustardException { String isVariable = isMethod(isNameExpr, isNameExpr); isMethod(); String isVariable = isNameExpr.isMethod() + (!isNameExpr ? isNameExpr : isNameExpr) + isNameExpr.isMethod("isStringConstant", isNameExpr.isMethod()) + "isStringConstant" + isNameExpr + isNameExpr; return isMethod(isNameExpr); } public ArrayList<Status> isMethod(String isParameter, long isParameter, boolean isParameter) throws MustardException { String isVariable = isMethod(isNameExpr, isNameExpr); isMethod(); String isVariable = isNameExpr.isMethod() + (!isNameExpr ? isNameExpr : isNameExpr) + isNameExpr.isMethod("isStringConstant", isNameExpr.isMethod()) + "isStringConstant" + isNameExpr + isNameExpr; return isMethod(isNameExpr); } public Status isMethod(String isParameter, boolean isParameter) throws MustardException { Status isVariable = null; isMethod(); String isVariable = isNameExpr.isMethod() + (!isNameExpr ? isNameExpr : isNameExpr) + isNameExpr.isMethod("isStringConstant", isNameExpr); try { JSONObject isVariable = isNameExpr.isMethod(isNameExpr); isNameExpr = isNameExpr.isMethod(isNameExpr); } catch (Exception isParameter) { if (isNameExpr.isFieldAccessExpr) isNameExpr.isMethod(); } return isNameExpr; } public ArrayList<Status> isMethod(String isParameter) throws MustardException { ArrayList<Status> isVariable = new ArrayList<Status>(); Status isVariable = isMethod(isNameExpr, true); isNameExpr.isMethod(isNameExpr); while (true) { try { long isVariable = isNameExpr.isMethod().isMethod(); if (isNameExpr > isIntegerConstant) { isNameExpr = isMethod(isNameExpr.isMethod(isNameExpr), true); isNameExpr.isMethod(isNameExpr); } else { break; } } catch (Exception isParameter) { if (isNameExpr.isFieldAccessExpr) isNameExpr.isMethod(); break; } } return isNameExpr; } public ArrayList<Status> isMethod(String isParameter) throws MustardException { ArrayList<Status> isVariable = new ArrayList<Status>(isIntegerConstant); isNameExpr.isMethod(isMethod(isNameExpr, true)); return isNameExpr; } private ArrayList<Status> isMethod(String isParameter) throws MustardException { if (isNameExpr.isFieldAccessExpr) isNameExpr.isMethod("isStringConstant", isNameExpr); ArrayList<Status> isVariable = new ArrayList<Status>(); try { URL isVariable = new URL(isNameExpr); HttpManager isVariable = new HttpManager(isNameExpr, isNameExpr.isMethod()); JSONArray isVariable = isNameExpr.isMethod(isNameExpr); for (int isVariable = isIntegerConstant; isNameExpr < isNameExpr.isMethod(); isNameExpr++) { try { JSONObject isVariable = isNameExpr.isMethod(isNameExpr); isNameExpr.isMethod(isNameExpr.isMethod(isNameExpr)); } catch (JSONException isParameter) { isNameExpr.isMethod(); } } } catch (IOException isParameter) { isNameExpr.isMethod(); throw new MustardException(isNameExpr.isMethod()); } catch (MustardException isParameter) { isNameExpr.isMethod(); throw new MustardException(isNameExpr.isMethod()); } catch (AuthException isParameter) { isNameExpr.isMethod(); throw new MustardException(isNameExpr.isMethod()); } catch (Exception isParameter) { isNameExpr.isMethod(); throw new MustardException(isNameExpr.isMethod()); } return isNameExpr; } private ArrayList<Status> isMethod(String isParameter) throws MustardException { if (isNameExpr.isFieldAccessExpr) isNameExpr.isMethod("isStringConstant", isNameExpr); ArrayList<Status> isVariable = new ArrayList<Status>(); try { JSONArray isVariable = isNameExpr.isMethod(isNameExpr); for (int isVariable = isIntegerConstant; isNameExpr < isNameExpr.isMethod(); isNameExpr++) { try { JSONObject isVariable = isNameExpr.isMethod(isNameExpr); isNameExpr.isMethod(isNameExpr.isMethod(isNameExpr)); } catch (JSONException isParameter) { isNameExpr.isMethod(); } } } catch (IOException isParameter) { isNameExpr.isMethod(); throw new MustardException(isNameExpr.isMethod()); } catch (MustardException isParameter) { isNameExpr.isMethod(); throw new MustardException(isNameExpr.isMethod()); } catch (AuthException isParameter) { isNameExpr.isMethod(); throw new MustardException(isNameExpr.isMethod()); } catch (Exception isParameter) { isNameExpr.isMethod(); throw new MustardException(isNameExpr.isMethod()); } return isNameExpr; } private ArrayList<DirectMessage> isMethod(int isParameter, String isParameter) throws MustardException { // isComment isNameExpr.isMethod("isStringConstant", isNameExpr); ArrayList<DirectMessage> isVariable = new ArrayList<DirectMessage>(); try { JSONArray isVariable = isNameExpr.isMethod(isNameExpr, isNameExpr.isFieldAccessExpr, null, true); for (int isVariable = isIntegerConstant; isNameExpr < isNameExpr.isMethod(); isNameExpr++) { try { JSONObject isVariable = isNameExpr.isMethod(isNameExpr); isNameExpr.isMethod(isNameExpr.isMethod(isNameExpr, isNameExpr)); } catch (JSONException isParameter) { isNameExpr.isMethod(); } } } catch (IOException isParameter) { isNameExpr.isMethod(); throw new MustardException(isNameExpr.isMethod()); } catch (MustardException isParameter) { isNameExpr.isMethod(); throw new MustardException(isNameExpr.isMethod()); } catch (AuthException isParameter) { isNameExpr.isMethod(); throw new MustardException(isNameExpr.isMethod()); } catch (Exception isParameter) { isNameExpr.isMethod(); throw new MustardException(isNameExpr.isMethod()); } return isNameExpr; } public User isMethod() throws MustardException { isMethod(); isNameExpr.isMethod("isStringConstant", "isStringConstant" + isNameExpr + "isStringConstant" + isNameExpr.isMethod() + (!isNameExpr ? "isStringConstant" : "isStringConstant") + isNameExpr); User isVariable = null; JSONObject isVariable = null; try { String isVariable = isNameExpr.isMethod() + (!isNameExpr ? isNameExpr : isNameExpr) + isNameExpr; isNameExpr = isNameExpr.isMethod(isNameExpr, isNameExpr.isFieldAccessExpr); } catch (MustardException isParameter) { throw isNameExpr; } catch (Exception isParameter) { if (isNameExpr.isFieldAccessExpr) isNameExpr.isMethod(); throw new MustardException(isNameExpr.isMethod() == null ? isNameExpr.isMethod() : isNameExpr.isMethod()); } if (isNameExpr != null) { try { isNameExpr = isNameExpr.isMethod(isNameExpr); } catch (JSONException isParameter) { if (isNameExpr.isFieldAccessExpr) isNameExpr.isMethod(); throw new MustardException(isNameExpr.isMethod() == null ? isNameExpr.isMethod() : isNameExpr.isMethod()); } } return isNameExpr; } public boolean isMethod(String isParameter) { isMethod(); String isVariable = isNameExpr.isMethod() + (!isNameExpr ? isNameExpr : isNameExpr) + isNameExpr.isMethod("isStringConstant", isNameExpr); try { isNameExpr.isMethod(isNameExpr, isNameExpr.isFieldAccessExpr); } catch (Exception isParameter) { if (isNameExpr.isFieldAccessExpr) isNameExpr.isMethod(isNameExpr, isNameExpr.isMethod()); return true; } return true; } public boolean isMethod(String isParameter) { isMethod(); if (!isNameExpr) { String isVariable = isNameExpr.isMethod() + isNameExpr + isNameExpr.isMethod("isStringConstant", isNameExpr); try { isNameExpr.isMethod(isNameExpr, isNameExpr.isFieldAccessExpr); } catch (Exception isParameter) { if (isNameExpr.isFieldAccessExpr) isNameExpr.isMethod(isNameExpr, isNameExpr.isMethod()); return true; } } else { String isVariable = isNameExpr.isMethod() + isNameExpr + isNameExpr; try { ArrayList<NameValuePair> isVariable = new ArrayList<NameValuePair>(); isNameExpr.isMethod(new BasicNameValuePair("isStringConstant", isNameExpr)); isNameExpr.isMethod(isNameExpr, isNameExpr.isFieldAccessExpr, isNameExpr); } catch (Exception isParameter) { if (isNameExpr.isFieldAccessExpr) isNameExpr.isMethod(isNameExpr, isNameExpr.isMethod()); return true; } } return true; } public boolean isMethod(String isParameter) { isMethod(); if (!isNameExpr) { String isVariable = isNameExpr.isMethod() + isNameExpr + isNameExpr.isMethod("isStringConstant", isNameExpr); try { isNameExpr.isMethod(isNameExpr, isNameExpr.isFieldAccessExpr); } catch (Exception isParameter) { if (isNameExpr.isFieldAccessExpr) isNameExpr.isMethod(isNameExpr, isNameExpr.isMethod()); return true; } } else { String isVariable = isNameExpr.isMethod() + isNameExpr + isNameExpr; try { ArrayList<NameValuePair> isVariable = new ArrayList<NameValuePair>(); isNameExpr.isMethod(new BasicNameValuePair("isStringConstant", isNameExpr)); isNameExpr.isMethod(isNameExpr, isNameExpr.isFieldAccessExpr, isNameExpr); } catch (Exception isParameter) { if (isNameExpr.isFieldAccessExpr) isNameExpr.isMethod(isNameExpr, isNameExpr.isMethod()); return true; } } return true; } public boolean isMethod(String isParameter) { isMethod(); String isVariable = isNameExpr.isMethod() + (!isNameExpr ? isNameExpr : isNameExpr) + isNameExpr.isMethod("isStringConstant", isNameExpr); try { isNameExpr.isMethod(isNameExpr, isNameExpr.isFieldAccessExpr); } catch (Exception isParameter) { if (isNameExpr.isFieldAccessExpr) isNameExpr.isMethod(isNameExpr, isNameExpr.isMethod()); return true; } return true; } public boolean isMethod(String isParameter) throws MustardException { isMethod(); String isVariable = isNameExpr.isMethod() + (!isNameExpr ? isNameExpr : isNameExpr) + isNameExpr.isMethod("isStringConstant", isNameExpr); try { if (isNameExpr.isFieldAccessExpr) isNameExpr.isMethod(isNameExpr, isNameExpr); isNameExpr.isMethod(isNameExpr, isNameExpr.isFieldAccessExpr); } catch (MustardException isParameter) { throw isNameExpr; } catch (Exception isParameter) { if (isNameExpr.isFieldAccessExpr) isNameExpr.isMethod(isNameExpr, isNameExpr.isMethod()); throw new MustardException(isNameExpr.isMethod() == null ? isNameExpr.isMethod() : isNameExpr.isMethod()); } return true; } public boolean isMethod(String isParameter) throws MustardException { isMethod(); String isVariable = isNameExpr.isMethod() + (!isNameExpr ? isNameExpr : isNameExpr) + isNameExpr.isMethod("isStringConstant", isNameExpr); try { if (isNameExpr.isFieldAccessExpr) isNameExpr.isMethod(isNameExpr, isNameExpr); isNameExpr.isMethod(isNameExpr, isNameExpr.isFieldAccessExpr); } catch (MustardException isParameter) { throw isNameExpr; } catch (Exception isParameter) { // isComment if (isNameExpr.isFieldAccessExpr) isNameExpr.isMethod(isNameExpr, isNameExpr.isMethod()); throw new MustardException(isNameExpr.isMethod() == null ? isNameExpr.isMethod() : isNameExpr.isMethod()); } return true; } public boolean isMethod(String isParameter) { isMethod(); String isVariable = isNameExpr.isMethod() + (!isNameExpr ? isNameExpr : isNameExpr) + isNameExpr.isMethod("isStringConstant", isNameExpr); try { isNameExpr.isMethod(isNameExpr, isNameExpr.isFieldAccessExpr); // isComment } catch (Exception isParameter) { // isComment isNameExpr.isMethod(isNameExpr, isNameExpr.isMethod()); return true; } return true; } public boolean isMethod(String isParameter) { isMethod(); String isVariable = isNameExpr.isMethod() + (!isNameExpr ? isNameExpr : isNameExpr) + isNameExpr.isMethod("isStringConstant", isNameExpr); try { isNameExpr.isMethod(isNameExpr, isNameExpr.isFieldAccessExpr); // isComment } catch (Exception isParameter) { // isComment isNameExpr.isMethod(isNameExpr, isNameExpr.isMethod()); return true; } return true; } public boolean isMethod(String isParameter) { isMethod(); String isVariable = isNameExpr.isMethod() + (!isNameExpr ? isNameExpr : isNameExpr) + isNameExpr.isMethod("isStringConstant", isNameExpr); try { isNameExpr.isMethod(isNameExpr, isNameExpr.isFieldAccessExpr); } catch (Exception isParameter) { if (isNameExpr.isFieldAccessExpr) isNameExpr.isMethod(isNameExpr, isNameExpr.isMethod()); return true; } return true; } public boolean isMethod(String isParameter) { isMethod(); String isVariable = isNameExpr.isMethod() + (!isNameExpr ? isNameExpr : isNameExpr) + isNameExpr.isMethod("isStringConstant", isNameExpr); try { isNameExpr.isMethod(isNameExpr, isNameExpr.isFieldAccessExpr); } catch (Exception isParameter) { if (isNameExpr.isFieldAccessExpr) isNameExpr.isMethod(isNameExpr, isNameExpr.isMethod()); return true; } return true; } public Relationship isMethod(String isParameter) { isMethod(); Relationship isVariable = null; String isVariable = isNameExpr.isMethod() + isNameExpr.isMethod("isStringConstant", isNameExpr); if (isNameExpr) isNameExpr = isNameExpr.isMethod() + isNameExpr.isMethod("isStringConstant", isNameExpr).isMethod("isStringConstant", isNameExpr); try { JSONObject isVariable = isNameExpr.isMethod(isNameExpr, isNameExpr.isFieldAccessExpr); isNameExpr = isNameExpr.isMethod(isNameExpr); } catch (Exception isParameter) { if (isNameExpr.isFieldAccessExpr) isNameExpr.isMethod(isNameExpr, isNameExpr.isMethod()); isNameExpr.isMethod(); } return isNameExpr; } public boolean isMethod(String isParameter) { isMethod(); String isVariable = isNameExpr.isMethod() + (!isNameExpr ? isNameExpr : isNameExpr) + isNameExpr.isMethod("isStringConstant", isNameExpr); try { JSONObject isVariable = isNameExpr.isMethod(isNameExpr, isNameExpr.isFieldAccessExpr); return isNameExpr.isMethod("isStringConstant"); } catch (Exception isParameter) { isNameExpr.isMethod(); if (isNameExpr.isFieldAccessExpr) isNameExpr.isMethod(isNameExpr, isNameExpr.isMethod()); return true; } } public String isMethod() { isMethod(); String isVariable = null; try { String isVariable = isNameExpr.isMethod() + (!isNameExpr ? isNameExpr : isNameExpr) + isNameExpr; isNameExpr = isNameExpr.isMethod(isNameExpr, isNameExpr.isFieldAccessExpr); if (isNameExpr != null) { isNameExpr = isNameExpr.isMethod(); if (isNameExpr.isMethod("isStringConstant")) isNameExpr = isNameExpr.isMethod("isStringConstant", "isStringConstant"); } } catch (MustardException isParameter) { isNameExpr.isMethod(); } catch (AuthException isParameter) { isNameExpr.isMethod(); } catch (IOException isParameter) { isNameExpr.isMethod(); } catch (Exception isParameter) { isNameExpr.isMethod(); } return isNameExpr; } public Service isMethod() { Service isVariable = null; InputStream isVariable = null; try { String isVariable = isNameExpr.isMethod() + isNameExpr; isNameExpr = isNameExpr.isMethod(isNameExpr, isNameExpr.isFieldAccessExpr, null); isNameExpr = isNameExpr.isMethod(isNameExpr); } catch (MustardException isParameter) { isNameExpr.isMethod(); } catch (AuthException isParameter) { isNameExpr.isMethod(); } catch (IOException isParameter) { isNameExpr.isMethod(); } catch (Exception isParameter) { isNameExpr.isMethod(); } finally { if (isNameExpr != null) { try { isNameExpr.isMethod(); } catch (IOException isParameter) { } } } return isNameExpr; } public boolean isMethod() { isMethod(); boolean isVariable = true; try { String isVariable = isNameExpr.isMethod() + (!isNameExpr ? isNameExpr : isNameExpr) + isNameExpr; String isVariable = isNameExpr.isMethod(isNameExpr, isNameExpr.isFieldAccessExpr); if (isNameExpr != null) { isNameExpr = isNameExpr.isMethod(); if (isNameExpr.isMethod("isStringConstant")) isNameExpr = isNameExpr.isMethod("isStringConstant", "isStringConstant"); if (isNameExpr.isMethod("isStringConstant")) isNameExpr = true; } } catch (MustardException isParameter) { isNameExpr.isMethod(); } catch (AuthException isParameter) { isNameExpr.isMethod(); } catch (IOException isParameter) { isNameExpr.isMethod(); } catch (Exception isParameter) { isNameExpr.isMethod(); } return isNameExpr; } public long isMethod(String isParameter, String isParameter) throws MustardException, AuthException { isMethod(); ArrayList<NameValuePair> isVariable = new ArrayList<NameValuePair>(); isNameExpr.isMethod(new BasicNameValuePair("isStringConstant", isNameExpr)); isNameExpr.isMethod(new BasicNameValuePair("isStringConstant", isNameExpr)); isNameExpr.isMethod(new BasicNameValuePair("isStringConstant", isNameExpr.isFieldAccessExpr)); String isVariable = isNameExpr.isMethod() + (!isNameExpr ? isNameExpr : isNameExpr) + isNameExpr; JSONObject isVariable = null; long isVariable = -isIntegerConstant; try { String isVariable = isNameExpr.isMethod(isNameExpr, isNameExpr.isFieldAccessExpr, isNameExpr); isNameExpr = new JSONObject(isNameExpr); isNameExpr = isNameExpr.isMethod("isStringConstant"); } catch (AuthException isParameter) { throw isNameExpr; } catch (MustardException isParameter) { if (isNameExpr.isFieldAccessExpr) isNameExpr.isMethod(); throw isNameExpr; } catch (Exception isParameter) { if (isNameExpr.isFieldAccessExpr) isNameExpr.isMethod(); throw new MustardException(isNameExpr.isMethod()); } return isNameExpr; } public StatusNetService isMethod() throws MustardException { isMethod(); StatusNetService isVariable = new StatusNetService(); JSONObject isVariable = null; try { String isVariable = isNameExpr.isMethod() + (!isNameExpr ? isNameExpr : isNameExpr) + isNameExpr; isNameExpr = isNameExpr.isMethod(isNameExpr); // isComment isNameExpr = isNameExpr.isMethod(isNameExpr); } catch (MustardException isParameter) { throw isNameExpr; } catch (AuthException isParameter) { // isComment throw new MustardException(isNameExpr.isMethod()); } catch (IOException isParameter) { throw new MustardException(isNameExpr.isMethod()); } catch (JSONException isParameter) { throw new MustardException(isNameExpr.isMethod()); } return isNameExpr; } public long isMethod(String isParameter, String isParameter) throws MustardException, AuthException { return isMethod(isNameExpr, isNameExpr, null, null, null); } public long isMethod(String isParameter, String isParameter, String isParameter, String isParameter) throws MustardException, AuthException { return isMethod(isNameExpr, isNameExpr, isNameExpr, isNameExpr, null); } public long isMethod(String isParameter, String isParameter, String isParameter, String isParameter, File isParameter) throws MustardException, AuthException { isMethod(); ArrayList<NameValuePair> isVariable = new ArrayList<NameValuePair>(); isNameExpr.isMethod(new BasicNameValuePair("isStringConstant", isNameExpr)); isNameExpr.isMethod(new BasicNameValuePair("isStringConstant", isNameExpr.isFieldAccessExpr)); if (!isNameExpr.isMethod("isStringConstant") && !isNameExpr.isMethod("isStringConstant")) isNameExpr.isMethod(new BasicNameValuePair("isStringConstant", isNameExpr)); if (isNameExpr != null && !"isStringConstant".isMethod(isNameExpr)) isNameExpr.isMethod(new BasicNameValuePair("isStringConstant", isNameExpr)); if (isNameExpr != null && !"isStringConstant".isMethod(isNameExpr)) isNameExpr.isMethod(new BasicNameValuePair("isStringConstant", isNameExpr)); String isVariable = isNameExpr.isMethod() + (!isNameExpr ? isNameExpr : isNameExpr) + isNameExpr; JSONObject isVariable = null; long isVariable = -isIntegerConstant; try { if (isNameExpr == null) { // isComment // isComment // isComment // isComment // isComment isNameExpr = isNameExpr.isMethod(isNameExpr, isNameExpr.isFieldAccessExpr, isNameExpr); } else { if (!isNameExpr) isNameExpr = isNameExpr.isMethod(isNameExpr, isNameExpr, "isStringConstant", isNameExpr); } // isComment Status isVariable = isNameExpr.isMethod(isNameExpr); isNameExpr = isNameExpr.isMethod().isMethod(); } catch (AuthException isParameter) { throw isNameExpr; } catch (MustardException isParameter) { if (isNameExpr.isFieldAccessExpr) isNameExpr.isMethod(); throw isNameExpr; } catch (Exception isParameter) { if (isNameExpr.isFieldAccessExpr) isNameExpr.isMethod(); throw new MustardException(isNameExpr.isMethod()); } return isNameExpr; } public boolean isMethod(File isParameter) throws MustardException { isMethod(); String isVariable = isNameExpr.isMethod() + (!isNameExpr ? isNameExpr : isNameExpr) + isNameExpr; try { isNameExpr.isMethod(isNameExpr, null, "isStringConstant", isNameExpr); return true; } catch (Exception isParameter) { if (isNameExpr.isFieldAccessExpr) isNameExpr.isMethod(); throw new MustardException(isNameExpr.isMethod()); } } public boolean isMethod() { return isNameExpr; } }
45,794
0.639341
0.639232
1,071
41.758171
35.758453
204
false
false
0
0
0
0
0
0
0.67507
false
false
12
925328ad56c1aba482372182e971fbc6fb8c9c2c
17,806,934,434,833
3ecc62df0db43d310881768530b386348583d777
/Satelite/src/main/java/DAO/ImplRecintoDAO.java
4a504fb5c9442dbc32dfa4a7ec634846b962938f
[]
no_license
AgustinGonzalezMurua/SateliteJavaPFT002V
https://github.com/AgustinGonzalezMurua/SateliteJavaPFT002V
a8e62cf918361f24cbc4c053cdcfb2cc68579053
51d7b747aa95e0794e0f80aa533eeb8b624820b6
refs/heads/master
2021-06-09T13:06:57.343000
2016-12-15T17:16:51
2016-12-15T17:16:51
66,988,698
0
0
null
false
2016-11-23T01:54:03
2016-08-31T00:47:03
2016-11-19T22:39:27
2016-11-23T01:54:03
703
0
0
0
Java
null
null
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package DAO; import static DAO.IBaseDAO.JSONPARSER; import static DAO.IBaseDAO.SERVICIO; import DTO.Comuna; import DTO.Recinto; import DTO.Ubicacion; import Exceptions.ServiceError; import java.util.ArrayList; import java.util.Iterator; import org.json.simple.JSONArray; import org.json.simple.JSONObject; public class ImplRecintoDAO implements IRecintoDAO { @Override public ArrayList<Recinto> RecuperarRecinto_Todos() { try { ArrayList<Recinto> _recintos = new ArrayList<>(); String result = SERVICIO.recuperarRecintoTodos(); Object _resultado = JSONPARSER.parse(result); if (!ContieneErrores(_resultado)){ } else{ JSONArray _jeventos = (JSONArray)_resultado; Iterator iterator = _jeventos.iterator(); while(iterator.hasNext()){ JSONObject jsonObject = (JSONObject) iterator.next(); DTO.Recinto _recinto = new DTO.Recinto(jsonObject); _recintos.add(_recinto); } } return _recintos; } catch (Exception e) { throw new IllegalArgumentException(e.getMessage()); } } public void CrearRecinto(Recinto recinto) { try { JSONObject _resultado = (JSONObject)JSONPARSER.parse(SERVICIO.registrarRecinto(recinto.toJSONString())); if(_resultado.containsKey("Error")){ throw new ServiceError("Ha ocurrido un error: " + _resultado.get("Error").toString()); } } catch (Exception e) { throw new IllegalArgumentException(e.getMessage()); } } public Recinto ObtenerRecinto(int codigo) { Recinto _recinto = new Recinto(); Comuna _comuna = new Comuna(); try { String result = SERVICIO.recuperarRecintoCodigo(codigo); JSONObject _resultado = (JSONObject)JSONPARSER.parse(result); if (_resultado.containsKey("Error")) { throw new ServiceError("Ha ocurrido un error: " + _resultado.get("Error").toString()); }else{ _recinto.setCodigo(Integer.parseInt(_resultado.get("Codigo").toString())); _recinto.setNombre(_resultado.get("Nombre").toString()); _recinto.setDireccion(_resultado.get("Direccion").toString()); //_recinto.setComuna(_resultado.get("Comuna").toString()); _recinto.setFono(Integer.parseInt(_resultado.get("Fono").toString())); _recinto.setCapacidadMaxima(Integer.parseInt(_resultado.get("CapacidadMaxima").toString())); } return _recinto; } catch (Exception e) { throw new IllegalArgumentException(e.getMessage()); } } public void ModificarRecinto(Recinto recinto){ try{ JSONObject _resultado = (JSONObject)JSONPARSER.parse(SERVICIO.modificarRecinto(recinto.toJSONString())); if (ContieneErrores(_resultado)) { throw new ServiceError("Ha ocurrido un error al modificar el recinto:" + _resultado.get("Error").toString()); } } catch (Exception e){ throw new IllegalArgumentException(e.getMessage()); } } public void EliminarRecinto(Recinto recinto) { try{ JSONObject _resultado = (JSONObject)JSONPARSER.parse(SERVICIO.eliminarRecinto(recinto.getCodigo())); if (ContieneErrores(_resultado)) { throw new ServiceError("Ha ocurrido un error al eliminar el recinto:" + _resultado.get("Error").toString()); } } catch (Exception e){ throw new IllegalArgumentException(e.getMessage()); } } public void CrearUbicacion(Ubicacion ubicacion) { try { JSONObject _resultado = (JSONObject)JSONPARSER.parse(SERVICIO.registrarUbicacion(ubicacion.toJSONString())); if(_resultado.containsKey("Error")){ throw new ServiceError("Ha ocurrido un error: " + _resultado.get("Error").toString()); } } catch (Exception e) { throw new IllegalArgumentException(e.getMessage()); } } public Ubicacion ObtenerUbicacion(int codigo) { Ubicacion _ubicacion = new Ubicacion(); try { String result = SERVICIO.recuperarUbicacion(codigo); JSONObject _resultado = (JSONObject)JSONPARSER.parse(result); if (_resultado.containsKey("Error")) { throw new ServiceError("Ha ocurrido un error: " + _resultado.get("Error").toString()); }else{ _ubicacion.setCodigo(Integer.parseInt(_resultado.get("Codigo").toString())); _ubicacion.setFila(_resultado.get("Fila").toString().charAt(0)); _ubicacion.setRecinto(Integer.parseInt(_resultado.get("Recinto").toString())); } return _ubicacion; } catch (Exception e) { throw new IllegalArgumentException(e.getMessage()); } } public void ModificarUbicacion(Ubicacion ubicacion){ try{ JSONObject _resultado = (JSONObject)JSONPARSER.parse(SERVICIO.modificarUbicacion(ubicacion.toJSONString())); if (ContieneErrores(_resultado)) { throw new ServiceError("Ha ocurrido un error al modificar la ubicación:" + _resultado.get("Error").toString()); } } catch (Exception e){ throw new IllegalArgumentException(e.getMessage()); } } public void EliminarUbicacion(Ubicacion ubicacion) { try{ JSONObject _resultado = (JSONObject)JSONPARSER.parse(SERVICIO.eliminarUbicacion(ubicacion.toJSONString())); if (ContieneErrores(_resultado)) { throw new ServiceError("Ha ocurrido un error al eliminar la ubicación: " + _resultado.get("Error").toString()); } } catch (Exception e){ throw new IllegalArgumentException(e.getMessage()); } } public ArrayList<DTO.Comuna> ListarComunas(){ ArrayList<DTO.Comuna> _comunas = new ArrayList<>(); try { // RECUPERAR LAS COMUNAS String result = SERVICIO.listarComunas(); Object _resultado = JSONPARSER.parse(result); if (!ContieneErrores(_resultado)){ } else{ JSONArray _jeventos = (JSONArray)_resultado; Iterator iterator = _jeventos.iterator(); while(iterator.hasNext()){ JSONObject jsonObject = (JSONObject) iterator.next(); DTO.Comuna _comuna = new DTO.Comuna(jsonObject); _comunas.add(_comuna); } } return _comunas; } catch (Exception e) { throw new IllegalArgumentException(e.getMessage()); } } public ArrayList<Ubicacion> RecuperarUbicacionesPorRecinto(int codigo) { try { ArrayList<Ubicacion> _ubicaciones = new ArrayList<>(); String result = SERVICIO.listarUbicacionesPorRecinto(codigo); Object _resultado = JSONPARSER.parse(result); JSONArray _jubicaciones = (JSONArray)_resultado; Iterator iterator = _jubicaciones.iterator(); while(iterator.hasNext()){ JSONObject jsonObject = (JSONObject) iterator.next(); DTO.Ubicacion _ubicacion = new DTO.Ubicacion(jsonObject); _ubicaciones.add(_ubicacion); } return _ubicaciones; } catch (Exception e) { throw new IllegalArgumentException(e.getMessage()); } } private boolean ContieneErrores(Object obj) throws ServiceError{ if (obj instanceof JSONObject) { if (((JSONObject)obj).containsKey("Error")) { throw new ServiceError("Ha ocurrido un error: " + ((JSONObject)obj).get("Error").toString()); }else{ return false; } }else{ return true; } } }
UTF-8
Java
8,882
java
ImplRecintoDAO.java
Java
[]
null
[]
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package DAO; import static DAO.IBaseDAO.JSONPARSER; import static DAO.IBaseDAO.SERVICIO; import DTO.Comuna; import DTO.Recinto; import DTO.Ubicacion; import Exceptions.ServiceError; import java.util.ArrayList; import java.util.Iterator; import org.json.simple.JSONArray; import org.json.simple.JSONObject; public class ImplRecintoDAO implements IRecintoDAO { @Override public ArrayList<Recinto> RecuperarRecinto_Todos() { try { ArrayList<Recinto> _recintos = new ArrayList<>(); String result = SERVICIO.recuperarRecintoTodos(); Object _resultado = JSONPARSER.parse(result); if (!ContieneErrores(_resultado)){ } else{ JSONArray _jeventos = (JSONArray)_resultado; Iterator iterator = _jeventos.iterator(); while(iterator.hasNext()){ JSONObject jsonObject = (JSONObject) iterator.next(); DTO.Recinto _recinto = new DTO.Recinto(jsonObject); _recintos.add(_recinto); } } return _recintos; } catch (Exception e) { throw new IllegalArgumentException(e.getMessage()); } } public void CrearRecinto(Recinto recinto) { try { JSONObject _resultado = (JSONObject)JSONPARSER.parse(SERVICIO.registrarRecinto(recinto.toJSONString())); if(_resultado.containsKey("Error")){ throw new ServiceError("Ha ocurrido un error: " + _resultado.get("Error").toString()); } } catch (Exception e) { throw new IllegalArgumentException(e.getMessage()); } } public Recinto ObtenerRecinto(int codigo) { Recinto _recinto = new Recinto(); Comuna _comuna = new Comuna(); try { String result = SERVICIO.recuperarRecintoCodigo(codigo); JSONObject _resultado = (JSONObject)JSONPARSER.parse(result); if (_resultado.containsKey("Error")) { throw new ServiceError("Ha ocurrido un error: " + _resultado.get("Error").toString()); }else{ _recinto.setCodigo(Integer.parseInt(_resultado.get("Codigo").toString())); _recinto.setNombre(_resultado.get("Nombre").toString()); _recinto.setDireccion(_resultado.get("Direccion").toString()); //_recinto.setComuna(_resultado.get("Comuna").toString()); _recinto.setFono(Integer.parseInt(_resultado.get("Fono").toString())); _recinto.setCapacidadMaxima(Integer.parseInt(_resultado.get("CapacidadMaxima").toString())); } return _recinto; } catch (Exception e) { throw new IllegalArgumentException(e.getMessage()); } } public void ModificarRecinto(Recinto recinto){ try{ JSONObject _resultado = (JSONObject)JSONPARSER.parse(SERVICIO.modificarRecinto(recinto.toJSONString())); if (ContieneErrores(_resultado)) { throw new ServiceError("Ha ocurrido un error al modificar el recinto:" + _resultado.get("Error").toString()); } } catch (Exception e){ throw new IllegalArgumentException(e.getMessage()); } } public void EliminarRecinto(Recinto recinto) { try{ JSONObject _resultado = (JSONObject)JSONPARSER.parse(SERVICIO.eliminarRecinto(recinto.getCodigo())); if (ContieneErrores(_resultado)) { throw new ServiceError("Ha ocurrido un error al eliminar el recinto:" + _resultado.get("Error").toString()); } } catch (Exception e){ throw new IllegalArgumentException(e.getMessage()); } } public void CrearUbicacion(Ubicacion ubicacion) { try { JSONObject _resultado = (JSONObject)JSONPARSER.parse(SERVICIO.registrarUbicacion(ubicacion.toJSONString())); if(_resultado.containsKey("Error")){ throw new ServiceError("Ha ocurrido un error: " + _resultado.get("Error").toString()); } } catch (Exception e) { throw new IllegalArgumentException(e.getMessage()); } } public Ubicacion ObtenerUbicacion(int codigo) { Ubicacion _ubicacion = new Ubicacion(); try { String result = SERVICIO.recuperarUbicacion(codigo); JSONObject _resultado = (JSONObject)JSONPARSER.parse(result); if (_resultado.containsKey("Error")) { throw new ServiceError("Ha ocurrido un error: " + _resultado.get("Error").toString()); }else{ _ubicacion.setCodigo(Integer.parseInt(_resultado.get("Codigo").toString())); _ubicacion.setFila(_resultado.get("Fila").toString().charAt(0)); _ubicacion.setRecinto(Integer.parseInt(_resultado.get("Recinto").toString())); } return _ubicacion; } catch (Exception e) { throw new IllegalArgumentException(e.getMessage()); } } public void ModificarUbicacion(Ubicacion ubicacion){ try{ JSONObject _resultado = (JSONObject)JSONPARSER.parse(SERVICIO.modificarUbicacion(ubicacion.toJSONString())); if (ContieneErrores(_resultado)) { throw new ServiceError("Ha ocurrido un error al modificar la ubicación:" + _resultado.get("Error").toString()); } } catch (Exception e){ throw new IllegalArgumentException(e.getMessage()); } } public void EliminarUbicacion(Ubicacion ubicacion) { try{ JSONObject _resultado = (JSONObject)JSONPARSER.parse(SERVICIO.eliminarUbicacion(ubicacion.toJSONString())); if (ContieneErrores(_resultado)) { throw new ServiceError("Ha ocurrido un error al eliminar la ubicación: " + _resultado.get("Error").toString()); } } catch (Exception e){ throw new IllegalArgumentException(e.getMessage()); } } public ArrayList<DTO.Comuna> ListarComunas(){ ArrayList<DTO.Comuna> _comunas = new ArrayList<>(); try { // RECUPERAR LAS COMUNAS String result = SERVICIO.listarComunas(); Object _resultado = JSONPARSER.parse(result); if (!ContieneErrores(_resultado)){ } else{ JSONArray _jeventos = (JSONArray)_resultado; Iterator iterator = _jeventos.iterator(); while(iterator.hasNext()){ JSONObject jsonObject = (JSONObject) iterator.next(); DTO.Comuna _comuna = new DTO.Comuna(jsonObject); _comunas.add(_comuna); } } return _comunas; } catch (Exception e) { throw new IllegalArgumentException(e.getMessage()); } } public ArrayList<Ubicacion> RecuperarUbicacionesPorRecinto(int codigo) { try { ArrayList<Ubicacion> _ubicaciones = new ArrayList<>(); String result = SERVICIO.listarUbicacionesPorRecinto(codigo); Object _resultado = JSONPARSER.parse(result); JSONArray _jubicaciones = (JSONArray)_resultado; Iterator iterator = _jubicaciones.iterator(); while(iterator.hasNext()){ JSONObject jsonObject = (JSONObject) iterator.next(); DTO.Ubicacion _ubicacion = new DTO.Ubicacion(jsonObject); _ubicaciones.add(_ubicacion); } return _ubicaciones; } catch (Exception e) { throw new IllegalArgumentException(e.getMessage()); } } private boolean ContieneErrores(Object obj) throws ServiceError{ if (obj instanceof JSONObject) { if (((JSONObject)obj).containsKey("Error")) { throw new ServiceError("Ha ocurrido un error: " + ((JSONObject)obj).get("Error").toString()); }else{ return false; } }else{ return true; } } }
8,882
0.556532
0.556419
225
38.462223
31.786226
127
false
false
0
0
0
0
0
0
0.386667
false
false
12
58c220436e39ae84a892f2c18083538d3448d031
11,330,123,761,972
0adb85c516b6dfd722872f4c261f480d76959a7d
/revapi-maven-plugin/src/main/java/org/revapi/maven/Analyzer.java
887aee753e5569496642694f5c2b99bc798406d5
[ "Apache-2.0" ]
permissive
sbernard31/revapi
https://github.com/sbernard31/revapi
e6cee954d93e6d1c0caddc08715609a693e11228
b41333025aa7f9f121a3da21a6127ec869509417
refs/heads/master
2022-11-16T09:37:40.986000
2020-07-06T16:09:37
2020-07-06T16:09:37
278,401,700
0
0
Apache-2.0
true
2020-07-09T15:26:34
2020-07-09T15:26:33
2020-07-06T16:16:25
2020-07-06T16:16:20
4,601
0
0
0
null
false
false
/* * Copyright 2014-2020 Lukas Krejci * and other contributors as indicated by the @author tags. * * 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.revapi.maven; import static java.util.stream.Collectors.toList; import static org.revapi.maven.utils.ArtifactResolver.getRevapiDependencySelector; import static org.revapi.maven.utils.ArtifactResolver.getRevapiDependencyTraverser; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.Spliterator; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Supplier; import java.util.regex.Pattern; import java.util.stream.Stream; import java.util.stream.StreamSupport; import org.apache.maven.RepositoryUtils; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.logging.Log; import org.apache.maven.project.MavenProject; import org.codehaus.plexus.configuration.PlexusConfiguration; import org.codehaus.plexus.configuration.xml.XmlPlexusConfiguration; import org.codehaus.plexus.util.xml.Xpp3DomBuilder; import org.codehaus.plexus.util.xml.pull.XmlPullParserException; import org.eclipse.aether.DefaultRepositorySystemSession; import org.eclipse.aether.RepositoryException; import org.eclipse.aether.RepositorySystem; import org.eclipse.aether.RepositorySystemSession; import org.eclipse.aether.artifact.Artifact; import org.eclipse.aether.artifact.DefaultArtifact; import org.eclipse.aether.repository.RepositoryPolicy; import org.eclipse.aether.resolution.ArtifactResolutionException; import org.eclipse.aether.resolution.VersionRangeResolutionException; import org.jboss.dmr.ModelNode; import org.revapi.API; import org.revapi.AnalysisContext; import org.revapi.AnalysisResult; import org.revapi.PipelineConfiguration; import org.revapi.Reporter; import org.revapi.Revapi; import org.revapi.configuration.JSONUtil; import org.revapi.configuration.ValidationResult; import org.revapi.configuration.XmlToJson; import org.revapi.maven.utils.ArtifactResolver; /** * @author Lukas Krejci * @since 0.1 */ public final class Analyzer { private static final Pattern ANY_NON_SNAPSHOT = Pattern.compile("^.*(?<!-SNAPSHOT)$"); private static final Pattern ANY = Pattern.compile(".*"); private final PlexusConfiguration pipelineConfiguration; private final PlexusConfiguration analysisConfiguration; private final Object[] analysisConfigurationFiles; private final String[] oldGavs; private final String[] newGavs; private final Artifact[] oldArtifacts; private final Artifact[] newArtifacts; private final MavenProject project; private final RepositorySystem repositorySystem; private final RepositorySystemSession repositorySystemSession; private final Class<? extends Reporter> reporterType; private final Map<String, Object> contextData; private final Locale locale; private final Log log; private final boolean failOnMissingConfigurationFiles; private final boolean failOnMissingArchives; private final boolean failOnMissingSupportArchives; private final Consumer<PipelineConfiguration.Builder> pipelineModifier; private final boolean resolveDependencies; private final Pattern versionRegex; private API resolvedOldApi; private API resolvedNewApi; private Revapi revapi; Analyzer(PlexusConfiguration pipelineConfiguration, PlexusConfiguration analysisConfiguration, Object[] analysisConfigurationFiles, Artifact[] oldArtifacts, Artifact[] newArtifacts, String[] oldGavs, String[] newGavs, MavenProject project, RepositorySystem repositorySystem, RepositorySystemSession repositorySystemSession, Class<? extends Reporter> reporterType, Map<String, Object> contextData, Locale locale, Log log, boolean failOnMissingConfigurationFiles, boolean failOnMissingArchives, boolean failOnMissingSupportArchives, boolean alwaysUpdate, boolean resolveDependencies, boolean resolveProvidedDependencies, boolean resolveTransitiveProvidedDependencies, String versionRegex, Consumer<PipelineConfiguration.Builder> pipelineModifier, Revapi sharedRevapi) { this.pipelineConfiguration = pipelineConfiguration; this.analysisConfiguration = analysisConfiguration; this.analysisConfigurationFiles = analysisConfigurationFiles; this.oldGavs = oldGavs; this.newGavs = newGavs; this.oldArtifacts = oldArtifacts; this.newArtifacts = newArtifacts; this.project = project; this.repositorySystem = repositorySystem; this.resolveDependencies = resolveDependencies; this.versionRegex = versionRegex == null ? null : Pattern.compile(versionRegex); DefaultRepositorySystemSession session = new DefaultRepositorySystemSession(repositorySystemSession); session.setDependencySelector(getRevapiDependencySelector(resolveProvidedDependencies, resolveTransitiveProvidedDependencies)); session.setDependencyTraverser(getRevapiDependencyTraverser(resolveProvidedDependencies, resolveTransitiveProvidedDependencies)); if (alwaysUpdate) { session.setUpdatePolicy(RepositoryPolicy.UPDATE_POLICY_ALWAYS); } this.repositorySystemSession = session; this.reporterType = reporterType; this.contextData = contextData; this.locale = locale; this.log = log; this.failOnMissingConfigurationFiles = failOnMissingConfigurationFiles; this.failOnMissingArchives = failOnMissingArchives; this.failOnMissingSupportArchives = failOnMissingSupportArchives; this.revapi = sharedRevapi; this.pipelineModifier = pipelineModifier; } public static String getProjectArtifactCoordinates(MavenProject project, String versionOverride) { org.apache.maven.artifact.Artifact artifact = project.getArtifact(); String extension = artifact.getArtifactHandler().getExtension(); String version = versionOverride == null ? project.getVersion() : versionOverride; if (artifact.hasClassifier()) { return project.getGroupId() + ":" + project.getArtifactId() + ":" + extension + ":" + artifact.getClassifier() + ":" + version; } else { return project.getGroupId() + ":" + project.getArtifactId() + ":" + extension + ":" + version; } } ValidationResult validateConfiguration() throws Exception { buildRevapi(); AnalysisContext.Builder ctxBuilder = AnalysisContext.builder(revapi).withLocale(locale); gatherConfig(ctxBuilder); ctxBuilder.withData(contextData); return revapi.validateConfiguration(ctxBuilder.build()); } /** * Resolves the gav using the resolver. If the gav corresponds to the project artifact and is an unresolved version * for a RELEASE or LATEST, the gav is resolved such it a release not newer than the project version is found that * optionally corresponds to the provided version regex, if provided. * * <p>If the gav exactly matches the current project, the file of the artifact is found on the filesystem in * target directory and the resolver is ignored. * * @param project the project to restrict by, if applicable * @param gav the gav to resolve * @param versionRegex the optional regex the version must match to be considered. * @param resolver the version resolver to use * @return the resolved artifact matching the criteria. * @throws VersionRangeResolutionException on error * @throws ArtifactResolutionException on error */ static Artifact resolveConstrained(MavenProject project, String gav, Pattern versionRegex, ArtifactResolver resolver) throws VersionRangeResolutionException, ArtifactResolutionException { boolean latest = gav.endsWith(":LATEST"); if (latest || gav.endsWith(":RELEASE")) { Artifact a = new DefaultArtifact(gav); if (latest) { versionRegex = versionRegex == null ? ANY : versionRegex; } else { versionRegex = versionRegex == null ? ANY_NON_SNAPSHOT : versionRegex; } String upTo = project.getGroupId().equals(a.getGroupId()) && project.getArtifactId().equals(a.getArtifactId()) ? project.getVersion() : null; return resolver.resolveNewestMatching(gav, upTo, versionRegex, latest, latest); } else { String projectGav = getProjectArtifactCoordinates(project, null); Artifact ret = null; if (projectGav.equals(gav)) { ret = findProjectArtifact(project); } return ret == null ? resolver.resolveArtifact(gav) : ret; } } private static Artifact findProjectArtifact(MavenProject project) { String extension = project.getArtifact().getArtifactHandler().getExtension(); String fileName = project.getModel().getBuild().getFinalName() + "." + extension; File f = new File(new File(project.getBasedir(), "target"), fileName); if (f.exists()) { Artifact ret = RepositoryUtils.toArtifact(project.getArtifact()); return ret.setFile(f); } else { return null; } } @SuppressWarnings("unchecked") void resolveArtifacts() { if (resolvedOldApi == null) { final ArtifactResolver resolver = new ArtifactResolver(repositorySystem, repositorySystemSession, project.getRemoteProjectRepositories()); Function<String, MavenArchive> toFileArchive = gav -> { try { Artifact a = resolveConstrained(project, gav, versionRegex, resolver); return MavenArchive.of(a); } catch (ArtifactResolutionException | VersionRangeResolutionException | IllegalArgumentException e) { throw new MarkerException(e.getMessage(), e); } }; List<MavenArchive> oldArchives = new ArrayList<>(1); try { if (oldGavs != null) { oldArchives = Stream.of(oldGavs).map(toFileArchive).collect(toList()); } if (oldArtifacts != null) { oldArchives.addAll(Stream.of(oldArtifacts).map(MavenArchive::of).collect(toList())); } } catch (MarkerException | IllegalArgumentException e) { String message = "Failed to resolve old artifacts: " + e.getMessage() + "."; if (failOnMissingArchives) { throw new IllegalStateException(message, e); } else { log.warn(message + " The API analysis will proceed comparing the new archives against an empty" + " archive."); } } List<MavenArchive> newArchives = new ArrayList<>(1); try { if (newGavs != null) { newArchives = Stream.of(newGavs).map(toFileArchive).collect(toList()); } if (newArtifacts != null) { newArchives.addAll(Stream.of(newArtifacts).map(MavenArchive::of).collect(toList())); } } catch (MarkerException | IllegalArgumentException e) { String message = "Failed to resolve new artifacts: " + e.getMessage() + "."; if (failOnMissingArchives) { throw new IllegalStateException(message, e); } else { log.warn(message + " The API analysis will not proceed."); return; } } //now we need to be a little bit clever. When using RELEASE or LATEST as the version of the old artifact //it might happen that it gets resolved to the same version as the new artifacts - this notoriously happens //when releasing using the release plugin - you first build your artifacts, put them into the local repo //and then do the site updates for the released version. When you do the site, maven will find the released //version in the repo and resolve RELEASE to it. You compare it against what you just built, i.e. the same //code, et voila, the site report doesn't ever contain any found differences... Set<MavenArchive> oldTransitiveDeps = new HashSet<>(); Set<MavenArchive> newTransitiveDeps = new HashSet<>(); if (resolveDependencies) { String[] resolvedOld = oldArchives.stream().map(MavenArchive::getName).toArray(String[]::new); String[] resolvedNew = newArchives.stream().map(MavenArchive::getName).toArray(String[]::new); oldTransitiveDeps.addAll(collectDeps("old", resolver, resolvedOld)); newTransitiveDeps.addAll(collectDeps("new", resolver, resolvedNew)); } resolvedOldApi = API.of(oldArchives).supportedBy(oldTransitiveDeps).build(); resolvedNewApi = API.of(newArchives).supportedBy(newTransitiveDeps).build(); } } private Set<MavenArchive> collectDeps(String depDescription, ArtifactResolver resolver, String... gavs) { try { if (gavs == null) { return Collections.emptySet(); } ArtifactResolver.CollectionResult res = resolver.collectTransitiveDeps(gavs); return collectDeps(depDescription, res); } catch (RepositoryException e) { return handleResolutionError(e, depDescription, null); } } @SuppressWarnings("unchecked") private Set<MavenArchive> collectDeps(String depDescription, ArtifactResolver.CollectionResult res) { Set<MavenArchive> ret = null; try { ret = new HashSet<>(); for (Artifact a : res.getResolvedArtifacts()) { try { ret.add(MavenArchive.of(a)); } catch (IllegalArgumentException e) { res.getFailures().add(e); } } if (!res.getFailures().isEmpty()) { StringBuilder bld = new StringBuilder(); for (Exception e : res.getFailures()) { bld.append(e.getMessage()).append(", "); } bld.replace(bld.length() - 2, bld.length(), ""); throw new MarkerException("Resolution of some artifacts failed: " + bld.toString()); } else { return ret; } } catch (MarkerException e) { return handleResolutionError(e, depDescription, ret); } } private Set<MavenArchive> handleResolutionError(Exception e, String depDescription, Set<MavenArchive> toReturn) { String message = "Failed to resolve dependencies of " + depDescription + " artifacts: " + e.getMessage() + "."; if (failOnMissingSupportArchives) { throw new IllegalArgumentException(message, e); } else { if (log.isDebugEnabled()) { log.warn(message + ". The API analysis might produce unexpected results.", e); } else { log.warn(message + ". The API analysis might produce unexpected results."); } return toReturn == null ? Collections.<MavenArchive>emptySet() : toReturn; } } @SuppressWarnings("unchecked") AnalysisResult analyze() throws MojoExecutionException { resolveArtifacts(); if (resolvedOldApi == null || resolvedNewApi == null) { return AnalysisResult.fakeSuccess(); } List<?> oldArchives = StreamSupport.stream( (Spliterator<MavenArchive>) resolvedOldApi.getArchives().spliterator(), false) .map(MavenArchive::getName).collect(toList()); List<?> newArchives = StreamSupport.stream( (Spliterator<MavenArchive>) resolvedNewApi.getArchives().spliterator(), false) .map(MavenArchive::getName).collect(toList()); log.info("Comparing " + oldArchives + " against " + newArchives + (resolveDependencies ? " (including their transitive dependencies)." : ".")); try { buildRevapi(); AnalysisContext.Builder ctxBuilder = AnalysisContext.builder(revapi).withOldAPI(resolvedOldApi) .withNewAPI(resolvedNewApi).withLocale(locale); gatherConfig(ctxBuilder); ctxBuilder.withData(contextData); return revapi.analyze(ctxBuilder.build()); } catch (Exception e) { throw new MojoExecutionException("Failed to analyze archives", e); } } public API getResolvedNewApi() { return resolvedNewApi; } public API getResolvedOldApi() { return resolvedOldApi; } public Revapi getRevapi() { buildRevapi(); return revapi; } private PipelineConfiguration.Builder gatherPipelineConfiguration() { String jsonConfig = pipelineConfiguration == null ? null : pipelineConfiguration.getValue(); PipelineConfiguration.Builder ret; if (jsonConfig == null) { // we're seeing XML. PipelineConfiguration is a set "format", not something dynamic as the extension // configurations. We can therefore try to parse it straight away. ret = parsePipelineConfigurationXML(); } else { ModelNode json = ModelNode.fromJSONString(jsonConfig); ret = PipelineConfiguration.parse(json); } // important to NOT add any extensions here yet. That's the job of the pipelineModifier that is responsible // to construct return ret; } private PipelineConfiguration.Builder parsePipelineConfigurationXML() { PipelineConfiguration.Builder bld = PipelineConfiguration.builder(); if (pipelineConfiguration == null) { return bld; } for (PlexusConfiguration c : pipelineConfiguration.getChildren()) { switch (c.getName()) { case "analyzers": parseIncludeExclude(c, bld::addAnalyzerExtensionIdInclude, bld::addAnalyzerExtensionIdExclude); break; case "reporters": parseIncludeExclude(c, bld::addReporterExtensionIdInclude, bld::addReporterExtensionIdExclude); break; case "filters": parseIncludeExclude(c, bld::addFilterExtensionIdInclude, bld::addFilterExtensionIdExclude); break; case "transforms": parseIncludeExclude(c, bld::addTransformExtensionIdInclude, bld::addTransformExtensionIdExclude); break; case "transformBlocks": for (PlexusConfiguration b : c.getChildren()) { List<String> blockIds = Stream.of(b.getChildren()) .map(PlexusConfiguration::getValue).collect(toList()); bld.addTransformationBlock(blockIds); } break; } } return bld; } private void parseIncludeExclude(PlexusConfiguration parent, Consumer<String> handleInclude, Consumer<String> handleExclude) { PlexusConfiguration include = parent.getChild("include"); PlexusConfiguration exclude = parent.getChild("exclude"); if (include != null) { Stream.of(include.getChildren()).forEach(c -> handleInclude.accept(c.getValue())); } if (exclude != null) { Stream.of(exclude.getChildren()).forEach(c -> handleExclude.accept(c.getValue())); } } @SuppressWarnings("unchecked") private void gatherConfig(AnalysisContext.Builder ctxBld) throws MojoExecutionException { if (analysisConfigurationFiles != null && analysisConfigurationFiles.length > 0) { for (Object pathOrConfigFile : analysisConfigurationFiles) { ConfigurationFile configFile; if (pathOrConfigFile instanceof String) { configFile = new ConfigurationFile(); configFile.setPath((String) pathOrConfigFile); } else { configFile = (ConfigurationFile) pathOrConfigFile; } String path = configFile.getPath(); String resource = configFile.getResource(); if (path == null && resource == null) { throw new MojoExecutionException( "Either 'path' or 'resource' has to be specified in a configurationFile definition."); } else if (path != null && resource != null) { throw new MojoExecutionException( "Either 'path' or 'resource' has to be specified in a configurationFile definition but" + " not both."); } String readErrorMessage = "Error while processing the configuration file on " + (path == null ? "classpath " + resource : "path " + path); Supplier<Iterator<InputStream>> configFileContents; if (path != null) { File f = new File(path); if (!f.isAbsolute()) { f = new File(project.getBasedir(), path); } if (!f.isFile() || !f.canRead()) { String message = "Could not locate analysis configuration file '" + f.getAbsolutePath() + "'."; if (failOnMissingConfigurationFiles) { throw new MojoExecutionException(message); } else { log.debug(message); continue; } } final File ff = f; configFileContents = () -> { try { return Collections.<InputStream>singletonList(new FileInputStream(ff)).iterator(); } catch (FileNotFoundException e) { throw new MarkerException("Failed to read the configuration file '" + ff.getAbsolutePath() + "'.", e); } }; } else { configFileContents = () -> { try { return Collections.list(getClass().getClassLoader().getResources(resource)) .stream() .map(url -> { try { return url.openStream(); } catch (IOException e) { throw new MarkerException( "Failed to read the classpath resource '" + url + "'."); } }).iterator(); } catch (IOException e) { throw new IllegalArgumentException( "Failed to locate classpath resources on path '" + resource + "'."); } }; } Iterator<InputStream> it = configFileContents.get(); List<Integer> nonJsonIndexes = new ArrayList<>(4); int idx = 0; while (it.hasNext()) { ModelNode config; try (InputStream in = it.next()) { config = readJson(in); } catch (MarkerException | IOException e) { throw new MojoExecutionException(readErrorMessage, e.getCause()); } if (config == null) { nonJsonIndexes.add(idx); continue; } mergeJsonConfigFile(ctxBld, configFile, config); idx++; } if (!nonJsonIndexes.isEmpty()) { idx = 0; it = configFileContents.get(); while (it.hasNext()) { try (Reader rdr = new InputStreamReader(it.next())) { if (nonJsonIndexes.contains(idx)) { mergeXmlConfigFile(ctxBld, configFile, rdr); } } catch (MarkerException | IOException | XmlPullParserException e) { throw new MojoExecutionException(readErrorMessage, e.getCause()); } idx++; } } } } if (analysisConfiguration != null) { String text = analysisConfiguration.getValue(); if (text == null || text.isEmpty()) { convertNewStyleConfigFromXml(ctxBld, getRevapi()); } else { ctxBld.mergeConfigurationFromJSON(text); } } } private void mergeXmlConfigFile(AnalysisContext.Builder ctxBld, ConfigurationFile configFile, Reader rdr) throws IOException, XmlPullParserException { XmlToJson<PlexusConfiguration> conv = new XmlToJson<>(revapi, PlexusConfiguration::getName, PlexusConfiguration::getValue, PlexusConfiguration::getAttribute, x -> Arrays.asList(x.getChildren())); PlexusConfiguration xml = new XmlPlexusConfiguration(Xpp3DomBuilder.build(rdr)); String[] roots = configFile.getRoots(); if (roots == null) { ctxBld.mergeConfiguration(conv.convert(xml)); } else { roots: for (String r : roots) { PlexusConfiguration root = xml; boolean first = true; String[] rootPath = r.split("/"); for (String name : rootPath) { if (first) { first = false; if (!name.equals(root.getName())) { continue roots; } } else { root = root.getChild(name); if (root == null) { continue roots; } } } ctxBld.mergeConfiguration(conv.convert(root)); } } } private void mergeJsonConfigFile(AnalysisContext.Builder ctxBld, ConfigurationFile configFile, ModelNode config) { String[] roots = configFile.getRoots(); if (roots == null) { ctxBld.mergeConfiguration(config); } else { for (String r : roots) { String[] rootPath = r.split("/"); ModelNode root = config.get(rootPath); if (!root.isDefined()) { continue; } ctxBld.mergeConfiguration(root); } } } private void buildRevapi() { if (revapi == null) { PipelineConfiguration.Builder builder = gatherPipelineConfiguration(); pipelineModifier.accept(builder); if (reporterType != null) { builder.withReporters(reporterType); } revapi = new Revapi(builder.build()); } } private void convertNewStyleConfigFromXml(AnalysisContext.Builder bld, Revapi revapi) { XmlToJson<PlexusConfiguration> conv = new XmlToJson<>(revapi, PlexusConfiguration::getName, PlexusConfiguration::getValue, PlexusConfiguration::getAttribute, x -> Arrays.asList(x.getChildren())); bld.mergeConfiguration(conv.convert(analysisConfiguration)); } private ModelNode readJson(InputStream in) { try { return ModelNode.fromJSONStream(JSONUtil.stripComments(in, Charset.forName("UTF-8"))); } catch (IOException e) { return null; } } private static final class MarkerException extends RuntimeException { public MarkerException(String message) { super(message); } public MarkerException(String message, Throwable cause) { super(message, cause); } } @FunctionalInterface private interface ThrowingSupplier<T> { T get() throws Exception; } }
UTF-8
Java
30,104
java
Analyzer.java
Java
[ { "context": "/*\n * Copyright 2014-2020 Lukas Krejci\n * and other contributors as indicated by the @au", "end": 38, "score": 0.9998416304588318, "start": 26, "tag": "NAME", "value": "Lukas Krejci" }, { "context": "vapi.maven.utils.ArtifactResolver;\n\n/**\n * @author Lukas Krejci\n * @since 0.1\n */\npublic final class Analyzer {\n ", "end": 2966, "score": 0.9998701214790344, "start": 2954, "tag": "NAME", "value": "Lukas Krejci" } ]
null
[]
/* * Copyright 2014-2020 <NAME> * and other contributors as indicated by the @author tags. * * 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.revapi.maven; import static java.util.stream.Collectors.toList; import static org.revapi.maven.utils.ArtifactResolver.getRevapiDependencySelector; import static org.revapi.maven.utils.ArtifactResolver.getRevapiDependencyTraverser; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.Spliterator; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Supplier; import java.util.regex.Pattern; import java.util.stream.Stream; import java.util.stream.StreamSupport; import org.apache.maven.RepositoryUtils; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.logging.Log; import org.apache.maven.project.MavenProject; import org.codehaus.plexus.configuration.PlexusConfiguration; import org.codehaus.plexus.configuration.xml.XmlPlexusConfiguration; import org.codehaus.plexus.util.xml.Xpp3DomBuilder; import org.codehaus.plexus.util.xml.pull.XmlPullParserException; import org.eclipse.aether.DefaultRepositorySystemSession; import org.eclipse.aether.RepositoryException; import org.eclipse.aether.RepositorySystem; import org.eclipse.aether.RepositorySystemSession; import org.eclipse.aether.artifact.Artifact; import org.eclipse.aether.artifact.DefaultArtifact; import org.eclipse.aether.repository.RepositoryPolicy; import org.eclipse.aether.resolution.ArtifactResolutionException; import org.eclipse.aether.resolution.VersionRangeResolutionException; import org.jboss.dmr.ModelNode; import org.revapi.API; import org.revapi.AnalysisContext; import org.revapi.AnalysisResult; import org.revapi.PipelineConfiguration; import org.revapi.Reporter; import org.revapi.Revapi; import org.revapi.configuration.JSONUtil; import org.revapi.configuration.ValidationResult; import org.revapi.configuration.XmlToJson; import org.revapi.maven.utils.ArtifactResolver; /** * @author <NAME> * @since 0.1 */ public final class Analyzer { private static final Pattern ANY_NON_SNAPSHOT = Pattern.compile("^.*(?<!-SNAPSHOT)$"); private static final Pattern ANY = Pattern.compile(".*"); private final PlexusConfiguration pipelineConfiguration; private final PlexusConfiguration analysisConfiguration; private final Object[] analysisConfigurationFiles; private final String[] oldGavs; private final String[] newGavs; private final Artifact[] oldArtifacts; private final Artifact[] newArtifacts; private final MavenProject project; private final RepositorySystem repositorySystem; private final RepositorySystemSession repositorySystemSession; private final Class<? extends Reporter> reporterType; private final Map<String, Object> contextData; private final Locale locale; private final Log log; private final boolean failOnMissingConfigurationFiles; private final boolean failOnMissingArchives; private final boolean failOnMissingSupportArchives; private final Consumer<PipelineConfiguration.Builder> pipelineModifier; private final boolean resolveDependencies; private final Pattern versionRegex; private API resolvedOldApi; private API resolvedNewApi; private Revapi revapi; Analyzer(PlexusConfiguration pipelineConfiguration, PlexusConfiguration analysisConfiguration, Object[] analysisConfigurationFiles, Artifact[] oldArtifacts, Artifact[] newArtifacts, String[] oldGavs, String[] newGavs, MavenProject project, RepositorySystem repositorySystem, RepositorySystemSession repositorySystemSession, Class<? extends Reporter> reporterType, Map<String, Object> contextData, Locale locale, Log log, boolean failOnMissingConfigurationFiles, boolean failOnMissingArchives, boolean failOnMissingSupportArchives, boolean alwaysUpdate, boolean resolveDependencies, boolean resolveProvidedDependencies, boolean resolveTransitiveProvidedDependencies, String versionRegex, Consumer<PipelineConfiguration.Builder> pipelineModifier, Revapi sharedRevapi) { this.pipelineConfiguration = pipelineConfiguration; this.analysisConfiguration = analysisConfiguration; this.analysisConfigurationFiles = analysisConfigurationFiles; this.oldGavs = oldGavs; this.newGavs = newGavs; this.oldArtifacts = oldArtifacts; this.newArtifacts = newArtifacts; this.project = project; this.repositorySystem = repositorySystem; this.resolveDependencies = resolveDependencies; this.versionRegex = versionRegex == null ? null : Pattern.compile(versionRegex); DefaultRepositorySystemSession session = new DefaultRepositorySystemSession(repositorySystemSession); session.setDependencySelector(getRevapiDependencySelector(resolveProvidedDependencies, resolveTransitiveProvidedDependencies)); session.setDependencyTraverser(getRevapiDependencyTraverser(resolveProvidedDependencies, resolveTransitiveProvidedDependencies)); if (alwaysUpdate) { session.setUpdatePolicy(RepositoryPolicy.UPDATE_POLICY_ALWAYS); } this.repositorySystemSession = session; this.reporterType = reporterType; this.contextData = contextData; this.locale = locale; this.log = log; this.failOnMissingConfigurationFiles = failOnMissingConfigurationFiles; this.failOnMissingArchives = failOnMissingArchives; this.failOnMissingSupportArchives = failOnMissingSupportArchives; this.revapi = sharedRevapi; this.pipelineModifier = pipelineModifier; } public static String getProjectArtifactCoordinates(MavenProject project, String versionOverride) { org.apache.maven.artifact.Artifact artifact = project.getArtifact(); String extension = artifact.getArtifactHandler().getExtension(); String version = versionOverride == null ? project.getVersion() : versionOverride; if (artifact.hasClassifier()) { return project.getGroupId() + ":" + project.getArtifactId() + ":" + extension + ":" + artifact.getClassifier() + ":" + version; } else { return project.getGroupId() + ":" + project.getArtifactId() + ":" + extension + ":" + version; } } ValidationResult validateConfiguration() throws Exception { buildRevapi(); AnalysisContext.Builder ctxBuilder = AnalysisContext.builder(revapi).withLocale(locale); gatherConfig(ctxBuilder); ctxBuilder.withData(contextData); return revapi.validateConfiguration(ctxBuilder.build()); } /** * Resolves the gav using the resolver. If the gav corresponds to the project artifact and is an unresolved version * for a RELEASE or LATEST, the gav is resolved such it a release not newer than the project version is found that * optionally corresponds to the provided version regex, if provided. * * <p>If the gav exactly matches the current project, the file of the artifact is found on the filesystem in * target directory and the resolver is ignored. * * @param project the project to restrict by, if applicable * @param gav the gav to resolve * @param versionRegex the optional regex the version must match to be considered. * @param resolver the version resolver to use * @return the resolved artifact matching the criteria. * @throws VersionRangeResolutionException on error * @throws ArtifactResolutionException on error */ static Artifact resolveConstrained(MavenProject project, String gav, Pattern versionRegex, ArtifactResolver resolver) throws VersionRangeResolutionException, ArtifactResolutionException { boolean latest = gav.endsWith(":LATEST"); if (latest || gav.endsWith(":RELEASE")) { Artifact a = new DefaultArtifact(gav); if (latest) { versionRegex = versionRegex == null ? ANY : versionRegex; } else { versionRegex = versionRegex == null ? ANY_NON_SNAPSHOT : versionRegex; } String upTo = project.getGroupId().equals(a.getGroupId()) && project.getArtifactId().equals(a.getArtifactId()) ? project.getVersion() : null; return resolver.resolveNewestMatching(gav, upTo, versionRegex, latest, latest); } else { String projectGav = getProjectArtifactCoordinates(project, null); Artifact ret = null; if (projectGav.equals(gav)) { ret = findProjectArtifact(project); } return ret == null ? resolver.resolveArtifact(gav) : ret; } } private static Artifact findProjectArtifact(MavenProject project) { String extension = project.getArtifact().getArtifactHandler().getExtension(); String fileName = project.getModel().getBuild().getFinalName() + "." + extension; File f = new File(new File(project.getBasedir(), "target"), fileName); if (f.exists()) { Artifact ret = RepositoryUtils.toArtifact(project.getArtifact()); return ret.setFile(f); } else { return null; } } @SuppressWarnings("unchecked") void resolveArtifacts() { if (resolvedOldApi == null) { final ArtifactResolver resolver = new ArtifactResolver(repositorySystem, repositorySystemSession, project.getRemoteProjectRepositories()); Function<String, MavenArchive> toFileArchive = gav -> { try { Artifact a = resolveConstrained(project, gav, versionRegex, resolver); return MavenArchive.of(a); } catch (ArtifactResolutionException | VersionRangeResolutionException | IllegalArgumentException e) { throw new MarkerException(e.getMessage(), e); } }; List<MavenArchive> oldArchives = new ArrayList<>(1); try { if (oldGavs != null) { oldArchives = Stream.of(oldGavs).map(toFileArchive).collect(toList()); } if (oldArtifacts != null) { oldArchives.addAll(Stream.of(oldArtifacts).map(MavenArchive::of).collect(toList())); } } catch (MarkerException | IllegalArgumentException e) { String message = "Failed to resolve old artifacts: " + e.getMessage() + "."; if (failOnMissingArchives) { throw new IllegalStateException(message, e); } else { log.warn(message + " The API analysis will proceed comparing the new archives against an empty" + " archive."); } } List<MavenArchive> newArchives = new ArrayList<>(1); try { if (newGavs != null) { newArchives = Stream.of(newGavs).map(toFileArchive).collect(toList()); } if (newArtifacts != null) { newArchives.addAll(Stream.of(newArtifacts).map(MavenArchive::of).collect(toList())); } } catch (MarkerException | IllegalArgumentException e) { String message = "Failed to resolve new artifacts: " + e.getMessage() + "."; if (failOnMissingArchives) { throw new IllegalStateException(message, e); } else { log.warn(message + " The API analysis will not proceed."); return; } } //now we need to be a little bit clever. When using RELEASE or LATEST as the version of the old artifact //it might happen that it gets resolved to the same version as the new artifacts - this notoriously happens //when releasing using the release plugin - you first build your artifacts, put them into the local repo //and then do the site updates for the released version. When you do the site, maven will find the released //version in the repo and resolve RELEASE to it. You compare it against what you just built, i.e. the same //code, et voila, the site report doesn't ever contain any found differences... Set<MavenArchive> oldTransitiveDeps = new HashSet<>(); Set<MavenArchive> newTransitiveDeps = new HashSet<>(); if (resolveDependencies) { String[] resolvedOld = oldArchives.stream().map(MavenArchive::getName).toArray(String[]::new); String[] resolvedNew = newArchives.stream().map(MavenArchive::getName).toArray(String[]::new); oldTransitiveDeps.addAll(collectDeps("old", resolver, resolvedOld)); newTransitiveDeps.addAll(collectDeps("new", resolver, resolvedNew)); } resolvedOldApi = API.of(oldArchives).supportedBy(oldTransitiveDeps).build(); resolvedNewApi = API.of(newArchives).supportedBy(newTransitiveDeps).build(); } } private Set<MavenArchive> collectDeps(String depDescription, ArtifactResolver resolver, String... gavs) { try { if (gavs == null) { return Collections.emptySet(); } ArtifactResolver.CollectionResult res = resolver.collectTransitiveDeps(gavs); return collectDeps(depDescription, res); } catch (RepositoryException e) { return handleResolutionError(e, depDescription, null); } } @SuppressWarnings("unchecked") private Set<MavenArchive> collectDeps(String depDescription, ArtifactResolver.CollectionResult res) { Set<MavenArchive> ret = null; try { ret = new HashSet<>(); for (Artifact a : res.getResolvedArtifacts()) { try { ret.add(MavenArchive.of(a)); } catch (IllegalArgumentException e) { res.getFailures().add(e); } } if (!res.getFailures().isEmpty()) { StringBuilder bld = new StringBuilder(); for (Exception e : res.getFailures()) { bld.append(e.getMessage()).append(", "); } bld.replace(bld.length() - 2, bld.length(), ""); throw new MarkerException("Resolution of some artifacts failed: " + bld.toString()); } else { return ret; } } catch (MarkerException e) { return handleResolutionError(e, depDescription, ret); } } private Set<MavenArchive> handleResolutionError(Exception e, String depDescription, Set<MavenArchive> toReturn) { String message = "Failed to resolve dependencies of " + depDescription + " artifacts: " + e.getMessage() + "."; if (failOnMissingSupportArchives) { throw new IllegalArgumentException(message, e); } else { if (log.isDebugEnabled()) { log.warn(message + ". The API analysis might produce unexpected results.", e); } else { log.warn(message + ". The API analysis might produce unexpected results."); } return toReturn == null ? Collections.<MavenArchive>emptySet() : toReturn; } } @SuppressWarnings("unchecked") AnalysisResult analyze() throws MojoExecutionException { resolveArtifacts(); if (resolvedOldApi == null || resolvedNewApi == null) { return AnalysisResult.fakeSuccess(); } List<?> oldArchives = StreamSupport.stream( (Spliterator<MavenArchive>) resolvedOldApi.getArchives().spliterator(), false) .map(MavenArchive::getName).collect(toList()); List<?> newArchives = StreamSupport.stream( (Spliterator<MavenArchive>) resolvedNewApi.getArchives().spliterator(), false) .map(MavenArchive::getName).collect(toList()); log.info("Comparing " + oldArchives + " against " + newArchives + (resolveDependencies ? " (including their transitive dependencies)." : ".")); try { buildRevapi(); AnalysisContext.Builder ctxBuilder = AnalysisContext.builder(revapi).withOldAPI(resolvedOldApi) .withNewAPI(resolvedNewApi).withLocale(locale); gatherConfig(ctxBuilder); ctxBuilder.withData(contextData); return revapi.analyze(ctxBuilder.build()); } catch (Exception e) { throw new MojoExecutionException("Failed to analyze archives", e); } } public API getResolvedNewApi() { return resolvedNewApi; } public API getResolvedOldApi() { return resolvedOldApi; } public Revapi getRevapi() { buildRevapi(); return revapi; } private PipelineConfiguration.Builder gatherPipelineConfiguration() { String jsonConfig = pipelineConfiguration == null ? null : pipelineConfiguration.getValue(); PipelineConfiguration.Builder ret; if (jsonConfig == null) { // we're seeing XML. PipelineConfiguration is a set "format", not something dynamic as the extension // configurations. We can therefore try to parse it straight away. ret = parsePipelineConfigurationXML(); } else { ModelNode json = ModelNode.fromJSONString(jsonConfig); ret = PipelineConfiguration.parse(json); } // important to NOT add any extensions here yet. That's the job of the pipelineModifier that is responsible // to construct return ret; } private PipelineConfiguration.Builder parsePipelineConfigurationXML() { PipelineConfiguration.Builder bld = PipelineConfiguration.builder(); if (pipelineConfiguration == null) { return bld; } for (PlexusConfiguration c : pipelineConfiguration.getChildren()) { switch (c.getName()) { case "analyzers": parseIncludeExclude(c, bld::addAnalyzerExtensionIdInclude, bld::addAnalyzerExtensionIdExclude); break; case "reporters": parseIncludeExclude(c, bld::addReporterExtensionIdInclude, bld::addReporterExtensionIdExclude); break; case "filters": parseIncludeExclude(c, bld::addFilterExtensionIdInclude, bld::addFilterExtensionIdExclude); break; case "transforms": parseIncludeExclude(c, bld::addTransformExtensionIdInclude, bld::addTransformExtensionIdExclude); break; case "transformBlocks": for (PlexusConfiguration b : c.getChildren()) { List<String> blockIds = Stream.of(b.getChildren()) .map(PlexusConfiguration::getValue).collect(toList()); bld.addTransformationBlock(blockIds); } break; } } return bld; } private void parseIncludeExclude(PlexusConfiguration parent, Consumer<String> handleInclude, Consumer<String> handleExclude) { PlexusConfiguration include = parent.getChild("include"); PlexusConfiguration exclude = parent.getChild("exclude"); if (include != null) { Stream.of(include.getChildren()).forEach(c -> handleInclude.accept(c.getValue())); } if (exclude != null) { Stream.of(exclude.getChildren()).forEach(c -> handleExclude.accept(c.getValue())); } } @SuppressWarnings("unchecked") private void gatherConfig(AnalysisContext.Builder ctxBld) throws MojoExecutionException { if (analysisConfigurationFiles != null && analysisConfigurationFiles.length > 0) { for (Object pathOrConfigFile : analysisConfigurationFiles) { ConfigurationFile configFile; if (pathOrConfigFile instanceof String) { configFile = new ConfigurationFile(); configFile.setPath((String) pathOrConfigFile); } else { configFile = (ConfigurationFile) pathOrConfigFile; } String path = configFile.getPath(); String resource = configFile.getResource(); if (path == null && resource == null) { throw new MojoExecutionException( "Either 'path' or 'resource' has to be specified in a configurationFile definition."); } else if (path != null && resource != null) { throw new MojoExecutionException( "Either 'path' or 'resource' has to be specified in a configurationFile definition but" + " not both."); } String readErrorMessage = "Error while processing the configuration file on " + (path == null ? "classpath " + resource : "path " + path); Supplier<Iterator<InputStream>> configFileContents; if (path != null) { File f = new File(path); if (!f.isAbsolute()) { f = new File(project.getBasedir(), path); } if (!f.isFile() || !f.canRead()) { String message = "Could not locate analysis configuration file '" + f.getAbsolutePath() + "'."; if (failOnMissingConfigurationFiles) { throw new MojoExecutionException(message); } else { log.debug(message); continue; } } final File ff = f; configFileContents = () -> { try { return Collections.<InputStream>singletonList(new FileInputStream(ff)).iterator(); } catch (FileNotFoundException e) { throw new MarkerException("Failed to read the configuration file '" + ff.getAbsolutePath() + "'.", e); } }; } else { configFileContents = () -> { try { return Collections.list(getClass().getClassLoader().getResources(resource)) .stream() .map(url -> { try { return url.openStream(); } catch (IOException e) { throw new MarkerException( "Failed to read the classpath resource '" + url + "'."); } }).iterator(); } catch (IOException e) { throw new IllegalArgumentException( "Failed to locate classpath resources on path '" + resource + "'."); } }; } Iterator<InputStream> it = configFileContents.get(); List<Integer> nonJsonIndexes = new ArrayList<>(4); int idx = 0; while (it.hasNext()) { ModelNode config; try (InputStream in = it.next()) { config = readJson(in); } catch (MarkerException | IOException e) { throw new MojoExecutionException(readErrorMessage, e.getCause()); } if (config == null) { nonJsonIndexes.add(idx); continue; } mergeJsonConfigFile(ctxBld, configFile, config); idx++; } if (!nonJsonIndexes.isEmpty()) { idx = 0; it = configFileContents.get(); while (it.hasNext()) { try (Reader rdr = new InputStreamReader(it.next())) { if (nonJsonIndexes.contains(idx)) { mergeXmlConfigFile(ctxBld, configFile, rdr); } } catch (MarkerException | IOException | XmlPullParserException e) { throw new MojoExecutionException(readErrorMessage, e.getCause()); } idx++; } } } } if (analysisConfiguration != null) { String text = analysisConfiguration.getValue(); if (text == null || text.isEmpty()) { convertNewStyleConfigFromXml(ctxBld, getRevapi()); } else { ctxBld.mergeConfigurationFromJSON(text); } } } private void mergeXmlConfigFile(AnalysisContext.Builder ctxBld, ConfigurationFile configFile, Reader rdr) throws IOException, XmlPullParserException { XmlToJson<PlexusConfiguration> conv = new XmlToJson<>(revapi, PlexusConfiguration::getName, PlexusConfiguration::getValue, PlexusConfiguration::getAttribute, x -> Arrays.asList(x.getChildren())); PlexusConfiguration xml = new XmlPlexusConfiguration(Xpp3DomBuilder.build(rdr)); String[] roots = configFile.getRoots(); if (roots == null) { ctxBld.mergeConfiguration(conv.convert(xml)); } else { roots: for (String r : roots) { PlexusConfiguration root = xml; boolean first = true; String[] rootPath = r.split("/"); for (String name : rootPath) { if (first) { first = false; if (!name.equals(root.getName())) { continue roots; } } else { root = root.getChild(name); if (root == null) { continue roots; } } } ctxBld.mergeConfiguration(conv.convert(root)); } } } private void mergeJsonConfigFile(AnalysisContext.Builder ctxBld, ConfigurationFile configFile, ModelNode config) { String[] roots = configFile.getRoots(); if (roots == null) { ctxBld.mergeConfiguration(config); } else { for (String r : roots) { String[] rootPath = r.split("/"); ModelNode root = config.get(rootPath); if (!root.isDefined()) { continue; } ctxBld.mergeConfiguration(root); } } } private void buildRevapi() { if (revapi == null) { PipelineConfiguration.Builder builder = gatherPipelineConfiguration(); pipelineModifier.accept(builder); if (reporterType != null) { builder.withReporters(reporterType); } revapi = new Revapi(builder.build()); } } private void convertNewStyleConfigFromXml(AnalysisContext.Builder bld, Revapi revapi) { XmlToJson<PlexusConfiguration> conv = new XmlToJson<>(revapi, PlexusConfiguration::getName, PlexusConfiguration::getValue, PlexusConfiguration::getAttribute, x -> Arrays.asList(x.getChildren())); bld.mergeConfiguration(conv.convert(analysisConfiguration)); } private ModelNode readJson(InputStream in) { try { return ModelNode.fromJSONStream(JSONUtil.stripComments(in, Charset.forName("UTF-8"))); } catch (IOException e) { return null; } } private static final class MarkerException extends RuntimeException { public MarkerException(String message) { super(message); } public MarkerException(String message, Throwable cause) { super(message, cause); } } @FunctionalInterface private interface ThrowingSupplier<T> { T get() throws Exception; } }
30,092
0.597495
0.596698
729
40.294926
33.298985
137
false
false
0
0
0
0
0
0
0.581619
false
false
12
c2a0c7f957eec28b19afc19be358959355f80765
14,259,291,482,818
a93dfcefa3bbf779a038c5a8f9f68fed43e8905c
/newsletters/src/crud/ModificaValori.java
7d241814457572be17cd2db3d549c9e0e1f22029
[]
no_license
fulviomariola/newsletter_java
https://github.com/fulviomariola/newsletter_java
38bae43c10a7c4e95d81d0fdf00d56da4a1f38fc
ef1d06fad811129bdab52336712ab4eaeb2d1977
refs/heads/master
2023-08-08T11:42:38.296000
2020-09-15T16:05:18
2020-09-15T16:05:18
210,310,131
0
0
null
false
2023-07-22T16:55:19
2019-09-23T09:02:46
2020-09-15T16:05:22
2023-07-22T16:55:18
33
0
0
4
Java
false
false
package crud; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import connessione.ConnessioneDB; import connessione.UtenteBean; public class ModificaValori { public UtenteBean getValoreUtene(int id) { ConnessioneDB connessione = new ConnessioneDB(); Connection conn = connessione.getConn(); PreparedStatement ps = null; ResultSet rs = null; UtenteBean utente = new UtenteBean(); try { String query = "select * from gruppo where id=?"; ps = conn.prepareStatement(query); ps.setInt(1, id); rs = ps.executeQuery(); while (rs.next()) { utente.setId(rs.getInt("id")); utente.setNome(rs.getString("nome")); utente.setCognome(rs.getString("cognome")); utente.setGruppo(rs.getString("gruppo")); utente.setEmail(rs.getString("email")); utente.setInvio(rs.getInt("invio")); } } catch (Exception e) { System.out.println(e); } return utente; } public void modificaUtente(UtenteBean utente) { ConnessioneDB connessione = new ConnessioneDB(); Connection conn = connessione.getConn(); PreparedStatement ps = null; try { String query = "update gruppo set nome=?,cognome=?,gruppo=?,email=?,invio=? where id=?"; ps = conn.prepareStatement(query); ps.setString(1, utente.getNome()); ps.setString(2, utente.getCognome()); ps.setString(3, utente.getGruppo()); ps.setString(4, utente.getEmail()); ps.setInt(5, utente.getInvio()); ps.setInt(6, utente.getId()); ps.executeUpdate(); } catch (Exception e) { System.out.println(e); } } }
UTF-8
Java
1,582
java
ModificaValori.java
Java
[]
null
[]
package crud; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import connessione.ConnessioneDB; import connessione.UtenteBean; public class ModificaValori { public UtenteBean getValoreUtene(int id) { ConnessioneDB connessione = new ConnessioneDB(); Connection conn = connessione.getConn(); PreparedStatement ps = null; ResultSet rs = null; UtenteBean utente = new UtenteBean(); try { String query = "select * from gruppo where id=?"; ps = conn.prepareStatement(query); ps.setInt(1, id); rs = ps.executeQuery(); while (rs.next()) { utente.setId(rs.getInt("id")); utente.setNome(rs.getString("nome")); utente.setCognome(rs.getString("cognome")); utente.setGruppo(rs.getString("gruppo")); utente.setEmail(rs.getString("email")); utente.setInvio(rs.getInt("invio")); } } catch (Exception e) { System.out.println(e); } return utente; } public void modificaUtente(UtenteBean utente) { ConnessioneDB connessione = new ConnessioneDB(); Connection conn = connessione.getConn(); PreparedStatement ps = null; try { String query = "update gruppo set nome=?,cognome=?,gruppo=?,email=?,invio=? where id=?"; ps = conn.prepareStatement(query); ps.setString(1, utente.getNome()); ps.setString(2, utente.getCognome()); ps.setString(3, utente.getGruppo()); ps.setString(4, utente.getEmail()); ps.setInt(5, utente.getInvio()); ps.setInt(6, utente.getId()); ps.executeUpdate(); } catch (Exception e) { System.out.println(e); } } }
1,582
0.683312
0.678887
61
24.934425
18.807802
91
false
false
0
0
0
0
0
0
2.704918
false
false
12
f9537adbe1417fcf56355f979487b3c4f276538a
32,547,262,179,748
1e356d592a220c94da01631aa6c00ceb5db96143
/src/main/java/com/sv/udb/controlador/PersCtrl.java
875eb31ae4c2f115890fad40900408d835cec4f2
[]
no_license
LuisAraujo123/GUIA02_POO2
https://github.com/LuisAraujo123/GUIA02_POO2
0c41c42c5afb4bfef9174aeb91b8b0232b706bdd
fca810df8ebc28762d3917e9b1e6f924abc54fbc
refs/heads/master
2021-01-01T20:01:57.252000
2017-07-29T18:17:14
2017-07-29T18:17:14
98,744,363
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.sv.udb.controlador; import com.sv.udb.modelo.Pers; import com.sv.udb.recursos.Conexion; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; import java.util.List; /** * * @author bernardo */ public class PersCtrl { public boolean guar(Pers obje){ boolean resp = false; Connection cn = new Conexion().getConn(); try { PreparedStatement cmd = cn.prepareStatement("INSERT INTO PERS VALUES(null, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);"); cmd.setString(1, obje.getNombPers()); cmd.setString(2, obje.getApelPers()); cmd.setBytes(3, obje.getFotoPers()); cmd.setInt(4, obje.getCodiTipoPers()); cmd.setString(5, obje.getGenePers()); cmd.setDate(6, obje.getFechNaciPers()); cmd.setString(7, obje.getDuiPers()); cmd.setString(8, obje.getNitPers()); cmd.setString(9, obje.getTipoSangPers()); cmd.setInt(10, obje.getCodiUbicGeog()); cmd.setDate(11, obje.getFechAlta()); cmd.setDate(12, obje.getFechBaja()); cmd.setInt(13, obje.getEsta()); cmd.executeUpdate(); resp = true; } catch (Exception ex) { System.err.println("Error: " + ex.getMessage()); } finally { try { if (cn!=null) { if (!cn.isClosed()) { cn.close(); } } } catch (Exception e) { System.err.println("Error: " + e.getMessage()); } } return resp; } public boolean upda(Pers obje){ boolean resp = false; Connection cn = new Conexion().getConn(); try { PreparedStatement cmd = cn.prepareStatement("update Pers set nomb_pers = ?, apel_pers = ?, foto_pers = ?, codi_tipo_pers = ?, gene_pers = ?, fech_naci_pers = ?, dui_pers = ?, nit_pers = ?, tipo_sang_pers = ?, codi_ubic_geog = ?, fech_alta = ?, fech_baja = ?, esta = ? where codi_pers = ?"); cmd.setString(1, obje.getNombPers()); cmd.setString(2, obje.getApelPers()); cmd.setBytes(3, obje.getFotoPers()); cmd.setInt(4, obje.getCodiTipoPers()); cmd.setString(5, obje.getGenePers()); cmd.setDate(6, obje.getFechNaciPers()); cmd.setString(7, obje.getDuiPers()); cmd.setString(8, obje.getNitPers()); cmd.setString(9, obje.getTipoSangPers()); cmd.setInt(10, obje.getCodiUbicGeog()); cmd.setDate(11, obje.getFechAlta()); cmd.setDate(12, obje.getFechBaja()); cmd.setInt(13, obje.getEsta()); cmd.setInt(14, obje.getCodiPers()); cmd.executeUpdate(); resp = true; } catch (Exception ex) { System.err.println("Error: " + ex.getMessage()); } finally { try { if (cn!=null) { if (!cn.isClosed()) { cn.close(); } } } catch (Exception e) { System.err.println("Error: " + e.getMessage()); } } return resp; } public boolean dele(Pers obje){ boolean resp = false; Connection cn = new Conexion().getConn(); try { PreparedStatement cmd = cn.prepareStatement("delete from Pers where codi_pers = ?"); cmd.setInt(1, obje.getCodiPers()); cmd.executeUpdate(); resp = true; } catch (Exception ex) { System.err.println("Error: " + ex.getMessage()); } finally { try { if (cn!=null) { if (!cn.isClosed()) { cn.close(); } } } catch (Exception e) { System.err.println("Error: " + e.getMessage()); } } return resp; } public List<Pers> consTodo(){ List<Pers> resp = new ArrayList<>(); Connection cn = new Conexion().getConn(); try { PreparedStatement cmd = cn.prepareStatement("Select * from Pers"); ResultSet rs = cmd.executeQuery(); while (rs.next()) { resp.add(new Pers(rs.getInt(1), rs.getString(2), rs.getString(3), rs.getBytes(4), rs.getInt(5), rs.getString(6), rs.getDate(7), rs.getString(8), rs.getString(9), rs.getString(10), rs.getInt(11), rs.getDate(12), rs.getDate(13), rs.getInt(14))); } } catch (Exception ex) { System.err.println("Error: " + ex.getMessage()); } finally { try { if (cn!=null) { if (!cn.isClosed()) { cn.close(); } } } catch (Exception e) { System.err.println("Error: " + e.getMessage()); } } return resp; } public Pers consUno(int id){ Pers resp = null; Connection cn = new Conexion().getConn(); try { PreparedStatement cmd = cn.prepareStatement("Select * from Pers where codi_pers = ?"); cmd.setInt(1, id); ResultSet rs = cmd.executeQuery(); if (rs.next()) { resp = (new Pers(rs.getInt(1), rs.getString(2), rs.getString(3), rs.getBytes(4), rs.getInt(5), rs.getString(6), rs.getDate(7), rs.getString(8), rs.getString(9), rs.getString(10), rs.getInt(11), rs.getDate(12), rs.getDate(13), rs.getInt(14))); } } catch (Exception ex) { System.err.println("Error: " + ex.getMessage()); } finally { try { if (cn!=null) { if (!cn.isClosed()) { cn.close(); } } } catch (Exception e) { System.err.println("Error: " + e.getMessage()); } } return resp; } }
UTF-8
Java
7,063
java
PersCtrl.java
Java
[ { "context": "st;\r\nimport java.util.List;\r\n\r\n/**\r\n *\r\n * @author bernardo\r\n */\r\npublic class PersCtrl {\r\n public boolean", "end": 471, "score": 0.8470064997673035, "start": 463, "tag": "USERNAME", "value": "bernardo" } ]
null
[]
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.sv.udb.controlador; import com.sv.udb.modelo.Pers; import com.sv.udb.recursos.Conexion; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; import java.util.List; /** * * @author bernardo */ public class PersCtrl { public boolean guar(Pers obje){ boolean resp = false; Connection cn = new Conexion().getConn(); try { PreparedStatement cmd = cn.prepareStatement("INSERT INTO PERS VALUES(null, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);"); cmd.setString(1, obje.getNombPers()); cmd.setString(2, obje.getApelPers()); cmd.setBytes(3, obje.getFotoPers()); cmd.setInt(4, obje.getCodiTipoPers()); cmd.setString(5, obje.getGenePers()); cmd.setDate(6, obje.getFechNaciPers()); cmd.setString(7, obje.getDuiPers()); cmd.setString(8, obje.getNitPers()); cmd.setString(9, obje.getTipoSangPers()); cmd.setInt(10, obje.getCodiUbicGeog()); cmd.setDate(11, obje.getFechAlta()); cmd.setDate(12, obje.getFechBaja()); cmd.setInt(13, obje.getEsta()); cmd.executeUpdate(); resp = true; } catch (Exception ex) { System.err.println("Error: " + ex.getMessage()); } finally { try { if (cn!=null) { if (!cn.isClosed()) { cn.close(); } } } catch (Exception e) { System.err.println("Error: " + e.getMessage()); } } return resp; } public boolean upda(Pers obje){ boolean resp = false; Connection cn = new Conexion().getConn(); try { PreparedStatement cmd = cn.prepareStatement("update Pers set nomb_pers = ?, apel_pers = ?, foto_pers = ?, codi_tipo_pers = ?, gene_pers = ?, fech_naci_pers = ?, dui_pers = ?, nit_pers = ?, tipo_sang_pers = ?, codi_ubic_geog = ?, fech_alta = ?, fech_baja = ?, esta = ? where codi_pers = ?"); cmd.setString(1, obje.getNombPers()); cmd.setString(2, obje.getApelPers()); cmd.setBytes(3, obje.getFotoPers()); cmd.setInt(4, obje.getCodiTipoPers()); cmd.setString(5, obje.getGenePers()); cmd.setDate(6, obje.getFechNaciPers()); cmd.setString(7, obje.getDuiPers()); cmd.setString(8, obje.getNitPers()); cmd.setString(9, obje.getTipoSangPers()); cmd.setInt(10, obje.getCodiUbicGeog()); cmd.setDate(11, obje.getFechAlta()); cmd.setDate(12, obje.getFechBaja()); cmd.setInt(13, obje.getEsta()); cmd.setInt(14, obje.getCodiPers()); cmd.executeUpdate(); resp = true; } catch (Exception ex) { System.err.println("Error: " + ex.getMessage()); } finally { try { if (cn!=null) { if (!cn.isClosed()) { cn.close(); } } } catch (Exception e) { System.err.println("Error: " + e.getMessage()); } } return resp; } public boolean dele(Pers obje){ boolean resp = false; Connection cn = new Conexion().getConn(); try { PreparedStatement cmd = cn.prepareStatement("delete from Pers where codi_pers = ?"); cmd.setInt(1, obje.getCodiPers()); cmd.executeUpdate(); resp = true; } catch (Exception ex) { System.err.println("Error: " + ex.getMessage()); } finally { try { if (cn!=null) { if (!cn.isClosed()) { cn.close(); } } } catch (Exception e) { System.err.println("Error: " + e.getMessage()); } } return resp; } public List<Pers> consTodo(){ List<Pers> resp = new ArrayList<>(); Connection cn = new Conexion().getConn(); try { PreparedStatement cmd = cn.prepareStatement("Select * from Pers"); ResultSet rs = cmd.executeQuery(); while (rs.next()) { resp.add(new Pers(rs.getInt(1), rs.getString(2), rs.getString(3), rs.getBytes(4), rs.getInt(5), rs.getString(6), rs.getDate(7), rs.getString(8), rs.getString(9), rs.getString(10), rs.getInt(11), rs.getDate(12), rs.getDate(13), rs.getInt(14))); } } catch (Exception ex) { System.err.println("Error: " + ex.getMessage()); } finally { try { if (cn!=null) { if (!cn.isClosed()) { cn.close(); } } } catch (Exception e) { System.err.println("Error: " + e.getMessage()); } } return resp; } public Pers consUno(int id){ Pers resp = null; Connection cn = new Conexion().getConn(); try { PreparedStatement cmd = cn.prepareStatement("Select * from Pers where codi_pers = ?"); cmd.setInt(1, id); ResultSet rs = cmd.executeQuery(); if (rs.next()) { resp = (new Pers(rs.getInt(1), rs.getString(2), rs.getString(3), rs.getBytes(4), rs.getInt(5), rs.getString(6), rs.getDate(7), rs.getString(8), rs.getString(9), rs.getString(10), rs.getInt(11), rs.getDate(12), rs.getDate(13), rs.getInt(14))); } } catch (Exception ex) { System.err.println("Error: " + ex.getMessage()); } finally { try { if (cn!=null) { if (!cn.isClosed()) { cn.close(); } } } catch (Exception e) { System.err.println("Error: " + e.getMessage()); } } return resp; } }
7,063
0.443721
0.432961
208
31.95673
35.247383
302
false
false
0
0
0
0
0
0
0.798077
false
false
12
5d25bd790319e0c1c645d5c6bc95b7ca89d66003
22,514,218,628,202
8061be34fd0b88de3dddbfc9f618584fef226c3f
/TesteNetGames/src/JChat/Participante.java
1dbdd2c879bd5ed99f3631a1c4ad9f553a52dc46
[]
no_license
davifelipe13/TesteNetGames
https://github.com/davifelipe13/TesteNetGames
1a8e3eb67bb919262d4e5a1d59d94446349ec4f7
44acf9129a7b9ca901f4ccdc313976a476d236aa
refs/heads/master
2021-01-25T07:54:43.123000
2017-06-08T21:01:38
2017-06-08T21:01:38
93,681,702
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package JChat; /** * * @author Davi */ public class Participante { private String nome; private boolean vez; public Participante(String nome) { super(); this.nome = nome; vez = false; } public String getNome() { return nome; } public void tomarVez() { vez = true; } public void passarVez() { vez =false; } public boolean ehVez() { return this.vez; } }
UTF-8
Java
717
java
Participante.java
Java
[ { "context": "tor.\r\n */\r\npackage JChat;\r\n\r\n\r\n/**\r\n *\r\n * @author Davi\r\n */\r\npublic class Participante {\r\n \r\n priv", "end": 234, "score": 0.9989463090896606, "start": 230, "tag": "NAME", "value": "Davi" } ]
null
[]
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package JChat; /** * * @author Davi */ public class Participante { private String nome; private boolean vez; public Participante(String nome) { super(); this.nome = nome; vez = false; } public String getNome() { return nome; } public void tomarVez() { vez = true; } public void passarVez() { vez =false; } public boolean ehVez() { return this.vez; } }
717
0.531381
0.531381
40
15.925
16.657412
79
false
false
0
0
0
0
0
0
0.325
false
false
12
7a69195573029f5a0691a35ddafa6c0f40b41e58
24,773,371,373,000
953a6218c6a52c5530ba1e127a6f9a445dc41317
/EjemploHerencia/src/mundo/Principal.java
32a410a57a63b4ecb6361b1ba7b0b357e3b1bc94
[]
no_license
fjvivanco/Repositorio_lab
https://github.com/fjvivanco/Repositorio_lab
c92f1e60fa6eb10347b7328179e89c8f362342e3
59c6c3d398a4813926c6a24a17d929dabd30fd6f
refs/heads/master
2023-03-10T17:40:30.114000
2021-02-27T17:34:10
2021-02-27T17:34:10
342,906,619
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package mundo; public class Principal { public static void main(String[] args) { // TODO Auto-generated method stub //crear un objeto Estudiante estudiante=new Estudiante("Fernando ","Vivanco ", 20 , 3121 ,17.8f); estudiante.mostrarNotas(); System.out.println(estudiante.getApellido()); } }
UTF-8
Java
306
java
Principal.java
Java
[ { "context": "un objeto\n\t\tEstudiante estudiante=new Estudiante(\"Fernando \",\"Vivanco \", 20 , 3121 ,17.8f);\n\t\testudiante.mos", "end": 189, "score": 0.9998238682746887, "start": 181, "tag": "NAME", "value": "Fernando" }, { "context": "Estudiante estudiante=new Estudiante(\"Fernando \",\"Vivanco \", 20 , 3121 ,17.8f);\n\t\testudiante.mostrarNot", "end": 196, "score": 0.7173279523849487, "start": 193, "tag": "NAME", "value": "Viv" } ]
null
[]
package mundo; public class Principal { public static void main(String[] args) { // TODO Auto-generated method stub //crear un objeto Estudiante estudiante=new Estudiante("Fernando ","Vivanco ", 20 , 3121 ,17.8f); estudiante.mostrarNotas(); System.out.println(estudiante.getApellido()); } }
306
0.715686
0.686275
13
22.538462
23.312643
81
false
false
0
0
0
0
0
0
1.538462
false
false
12
c02375cd300b3c93ddd5e4ea11e9b420898712ad
24,773,371,374,267
8ec80e588ea158e183a99f68838f76559c916ff0
/src/gui/shell/database/SkillEffectShell.java
6dbe44dd61b087e3761a8399a19b1e9d9fb35512
[]
no_license
GloamingCat/LTH-Editor
https://github.com/GloamingCat/LTH-Editor
12c23438a72f7a46a709cbf7fb84bc09a55b7b98
cfe81dea80b941e10055709ce13e6bfbb96a7741
refs/heads/master
2023-02-20T07:46:49.564000
2023-02-11T17:37:00
2023-02-11T17:37:00
152,141,219
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package gui.shell.database; import gui.Vocab; import gui.shell.ObjectShell; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Shell; import data.Skill.Effect; import lwt.widget.LCheckBox; import lwt.widget.LLabel; import lwt.widget.LNodeSelector; import lwt.widget.LText; import project.Project; import org.eclipse.swt.SWT; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.FillLayout; public class SkillEffectShell extends ObjectShell<Effect> { public SkillEffectShell(Shell parent) { super(parent); setMinimumSize(300, 100); contentEditor.setLayout(new GridLayout(2, false)); new LLabel(contentEditor, Vocab.instance.KEY); LText txtKey = new LText(contentEditor); txtKey.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); addControl(txtKey, "key"); new LLabel(contentEditor, Vocab.instance.BASICRESULT); LText txtBasicResult = new LText(contentEditor); txtBasicResult.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); addControl(txtBasicResult, "basicResult"); new LLabel(contentEditor, Vocab.instance.SUCCESSRATE); LText txtSuccessRate = new LText(contentEditor); txtSuccessRate.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); addControl(txtSuccessRate, "successRate"); LCheckBox btnHeal = new LCheckBox(contentEditor); btnHeal.setText(Vocab.instance.HEAL); addControl(btnHeal, "heal"); LCheckBox btnAbsorb = new LCheckBox(contentEditor); btnAbsorb.setText(Vocab.instance.ABSORB); addControl(btnAbsorb, "absorb"); Group grpStatus = new Group(contentEditor, SWT.NONE); grpStatus.setLayout(new FillLayout(SWT.HORIZONTAL)); grpStatus.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 2, 1)); grpStatus.setText(Vocab.instance.STATUS); LNodeSelector<Object> tree = new LNodeSelector<Object>(grpStatus, 1); tree.setCollection(Project.current.status.getTree()); addControl(tree, "statusID"); pack(); } }
UTF-8
Java
2,050
java
SkillEffectShell.java
Java
[]
null
[]
package gui.shell.database; import gui.Vocab; import gui.shell.ObjectShell; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Shell; import data.Skill.Effect; import lwt.widget.LCheckBox; import lwt.widget.LLabel; import lwt.widget.LNodeSelector; import lwt.widget.LText; import project.Project; import org.eclipse.swt.SWT; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.FillLayout; public class SkillEffectShell extends ObjectShell<Effect> { public SkillEffectShell(Shell parent) { super(parent); setMinimumSize(300, 100); contentEditor.setLayout(new GridLayout(2, false)); new LLabel(contentEditor, Vocab.instance.KEY); LText txtKey = new LText(contentEditor); txtKey.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); addControl(txtKey, "key"); new LLabel(contentEditor, Vocab.instance.BASICRESULT); LText txtBasicResult = new LText(contentEditor); txtBasicResult.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); addControl(txtBasicResult, "basicResult"); new LLabel(contentEditor, Vocab.instance.SUCCESSRATE); LText txtSuccessRate = new LText(contentEditor); txtSuccessRate.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); addControl(txtSuccessRate, "successRate"); LCheckBox btnHeal = new LCheckBox(contentEditor); btnHeal.setText(Vocab.instance.HEAL); addControl(btnHeal, "heal"); LCheckBox btnAbsorb = new LCheckBox(contentEditor); btnAbsorb.setText(Vocab.instance.ABSORB); addControl(btnAbsorb, "absorb"); Group grpStatus = new Group(contentEditor, SWT.NONE); grpStatus.setLayout(new FillLayout(SWT.HORIZONTAL)); grpStatus.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 2, 1)); grpStatus.setText(Vocab.instance.STATUS); LNodeSelector<Object> tree = new LNodeSelector<Object>(grpStatus, 1); tree.setCollection(Project.current.status.getTree()); addControl(tree, "statusID"); pack(); } }
2,050
0.759024
0.75122
66
30.060606
24.069897
86
false
false
0
0
0
0
0
0
2.393939
false
false
12
f16d5e7c0489128274495a9e4ab045aa0f308269
3,599,182,603,198
b5436b52146df4589e8708b8f2a3db380f5a1506
/app/src/main/java/rx/internal/p105a/bk.java
3ea01abedb74d47d6aabe8e125e97b184a5d9d67
[]
no_license
KobeGong/AzarDev2
https://github.com/KobeGong/AzarDev2
3af539544a69ea62de64b0ffd3d42c7a2c96fc0e
93549dce7a675c6ba4992590f8313b5ca679e6c7
refs/heads/master
2018-02-09T15:11:24.821000
2017-07-10T13:18:21
2017-07-10T13:18:21
96,779,211
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package rx.internal.p105a; import rx.C4856d; import rx.b; import rx.b$g; import rx.h; import rx.p099a.C4775b; import rx.p102e.C4862d; public final class bk<T> implements b$g<T, T> { final b<? extends T> f12421a; public bk(b<? extends T> bVar) { this.f12421a = bVar; } public h<? super T> call(final h<? super T> hVar) { Object c50301 = new h<T>(this) { final /* synthetic */ bk f12419b; private boolean f12420c = false; public void onNext(T t) { if (!this.f12420c) { hVar.onNext(t); } } public void onError(Throwable th) { if (this.f12420c) { C4775b.throwIfFatal(th); return; } this.f12420c = true; C4862d.getInstance().getErrorHandler().handleError(th); unsubscribe(); this.f12419b.f12421a.unsafeSubscribe(hVar); } public void onCompleted() { if (!this.f12420c) { this.f12420c = true; hVar.onCompleted(); } } public void setProducer(final C4856d c4856d) { hVar.setProducer(new C4856d(this) { final /* synthetic */ C50301 f12417b; public void request(long j) { c4856d.request(j); } }); } }; hVar.add(c50301); return c50301; } }
UTF-8
Java
1,593
java
bk.java
Java
[]
null
[]
package rx.internal.p105a; import rx.C4856d; import rx.b; import rx.b$g; import rx.h; import rx.p099a.C4775b; import rx.p102e.C4862d; public final class bk<T> implements b$g<T, T> { final b<? extends T> f12421a; public bk(b<? extends T> bVar) { this.f12421a = bVar; } public h<? super T> call(final h<? super T> hVar) { Object c50301 = new h<T>(this) { final /* synthetic */ bk f12419b; private boolean f12420c = false; public void onNext(T t) { if (!this.f12420c) { hVar.onNext(t); } } public void onError(Throwable th) { if (this.f12420c) { C4775b.throwIfFatal(th); return; } this.f12420c = true; C4862d.getInstance().getErrorHandler().handleError(th); unsubscribe(); this.f12419b.f12421a.unsafeSubscribe(hVar); } public void onCompleted() { if (!this.f12420c) { this.f12420c = true; hVar.onCompleted(); } } public void setProducer(final C4856d c4856d) { hVar.setProducer(new C4856d(this) { final /* synthetic */ C50301 f12417b; public void request(long j) { c4856d.request(j); } }); } }; hVar.add(c50301); return c50301; } }
1,593
0.458255
0.379787
59
26
18.510647
71
false
false
0
0
0
0
0
0
0.457627
false
false
12
7c1dad4b165a961055e4f4540c4c5562d8a69fb6
18,940,805,786,123
1d928c3f90d4a0a9a3919a804597aa0a4aab19a3
/java/neo4j/2019/12/KernelTransactionTestBase.java
ed091245b2a42c5af2fae378dc5e8c03c6884186
[]
no_license
rosoareslv/SED99
https://github.com/rosoareslv/SED99
d8b2ff5811e7f0ffc59be066a5a0349a92cbb845
a062c118f12b93172e31e8ca115ce3f871b64461
refs/heads/main
2023-02-22T21:59:02.703000
2021-01-28T19:40:51
2021-01-28T19:40:51
306,497,459
1
1
null
false
2020-11-24T20:56:18
2020-10-23T01:18:07
2020-11-24T20:46:14
2020-11-24T20:56:17
744,608
0
0
0
null
false
false
/* * Copyright (c) 2002-2019 "Neo4j," * Neo4j Sweden AB [http://neo4j.com] * * This file is part of Neo4j. * * Neo4j is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.neo4j.kernel.impl.api; import org.eclipse.collections.api.map.primitive.MutableLongObjectMap; import org.eclipse.collections.api.set.primitive.MutableLongSet; import org.eclipse.collections.impl.map.mutable.primitive.LongObjectHashMap; import org.junit.jupiter.api.BeforeEach; import org.mockito.Mockito; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.concurrent.atomic.AtomicReference; import org.neo4j.collection.Dependencies; import org.neo4j.collection.pool.Pool; import org.neo4j.configuration.Config; import org.neo4j.configuration.GraphDatabaseSettings; import org.neo4j.internal.index.label.LabelScanStore; import org.neo4j.internal.kernel.api.security.LoginContext; import org.neo4j.internal.kernel.api.security.SecurityContext; import org.neo4j.internal.schema.SchemaState; import org.neo4j.io.pagecache.tracing.cursor.context.EmptyVersionContextSupplier; import org.neo4j.kernel.api.KernelTransaction; import org.neo4j.kernel.availability.AvailabilityGuard; import org.neo4j.kernel.database.DatabaseTracers; import org.neo4j.kernel.database.TestDatabaseIdRepository; import org.neo4j.kernel.impl.api.index.IndexingService; import org.neo4j.kernel.impl.api.index.stats.IndexStatisticsStore; import org.neo4j.kernel.impl.constraints.StandardConstraintSemantics; import org.neo4j.kernel.impl.factory.CanWrite; import org.neo4j.kernel.impl.factory.GraphDatabaseFacade; import org.neo4j.kernel.impl.locking.Locks; import org.neo4j.kernel.impl.locking.NoOpClient; import org.neo4j.kernel.impl.locking.SimpleStatementLocks; import org.neo4j.kernel.impl.locking.StatementLocks; import org.neo4j.kernel.impl.transaction.TransactionMonitor; import org.neo4j.kernel.impl.transaction.TransactionRepresentation; import org.neo4j.kernel.impl.transaction.tracing.CommitEvent; import org.neo4j.kernel.impl.util.collection.CollectionsFactory; import org.neo4j.kernel.impl.util.collection.OnHeapCollectionsFactory; import org.neo4j.kernel.impl.util.diffsets.MutableLongDiffSetsImpl; import org.neo4j.kernel.internal.event.DatabaseTransactionEventListeners; import org.neo4j.lock.ResourceLocker; import org.neo4j.memory.MemoryTracker; import org.neo4j.resources.CpuClock; import org.neo4j.resources.HeapAllocation; import org.neo4j.storageengine.api.CommandCreationContext; import org.neo4j.storageengine.api.StorageCommand; import org.neo4j.storageengine.api.StorageEngine; import org.neo4j.storageengine.api.StorageReader; import org.neo4j.storageengine.api.TransactionApplicationMode; import org.neo4j.storageengine.api.TransactionIdStore; import org.neo4j.storageengine.api.txstate.ReadableTransactionState; import org.neo4j.storageengine.api.txstate.TxStateVisitor; import org.neo4j.time.Clocks; import org.neo4j.time.FakeClock; import org.neo4j.values.storable.Value; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyCollection; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.Mockito.RETURNS_MOCKS; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.neo4j.configuration.GraphDatabaseSettings.DEFAULT_DATABASE_NAME; import static org.neo4j.internal.kernel.api.connectioninfo.ClientConnectionInfo.EMBEDDED_CONNECTION; import static org.neo4j.internal.kernel.api.security.LoginContext.AUTH_DISABLED; import static org.neo4j.storageengine.api.TransactionIdStore.BASE_TX_COMMIT_TIMESTAMP; import static org.neo4j.test.rule.DatabaseRule.mockedTokenHolders; class KernelTransactionTestBase { protected final StorageEngine storageEngine = mock( StorageEngine.class ); protected final StorageReader storageReader = mock( StorageReader.class ); protected final TransactionIdStore transactionIdStore = mock( TransactionIdStore.class ); protected final CommandCreationContext commandCreationContext = mock( CommandCreationContext.class ); protected final TransactionMonitor transactionMonitor = mock( TransactionMonitor.class ); protected final CapturingCommitProcess commitProcess = new CapturingCommitProcess(); protected final TransactionHeaderInformation headerInformation = mock( TransactionHeaderInformation.class ); protected final AvailabilityGuard availabilityGuard = mock( AvailabilityGuard.class ); protected final FakeClock clock = Clocks.fakeClock(); protected final Pool<KernelTransactionImplementation> txPool = mock( Pool.class ); protected CollectionsFactory collectionsFactory; protected final Config config = Config.defaults(); private final long defaultTransactionTimeoutMillis = config.get( GraphDatabaseSettings.transaction_timeout ).toMillis(); @BeforeEach public void before() throws Exception { collectionsFactory = Mockito.spy( new TestCollectionsFactory() ); when( headerInformation.getAdditionalHeader() ).thenReturn( new byte[0] ); when( storageEngine.newReader() ).thenReturn( storageReader ); when( storageEngine.newCommandCreationContext() ).thenReturn( commandCreationContext ); when( storageEngine.transactionIdStore() ).thenReturn( transactionIdStore ); doAnswer( invocation -> ((Collection<StorageCommand>) invocation.getArgument(0) ).add( new TestCommand() ) ) .when( storageEngine ).createCommands( anyCollection(), any( ReadableTransactionState.class ), any( StorageReader.class ), any( CommandCreationContext.class ), any( ResourceLocker.class ), anyLong(), any( TxStateVisitor.Decorator.class ) ); } public KernelTransactionImplementation newTransaction( long transactionTimeoutMillis ) { return newTransaction( 0, AUTH_DISABLED, transactionTimeoutMillis ); } public KernelTransactionImplementation newTransaction( LoginContext loginContext ) { return newTransaction( 0, loginContext ); } public KernelTransactionImplementation newTransaction( LoginContext loginContext, Locks.Client locks ) { return newTransaction( 0, loginContext, locks, defaultTransactionTimeoutMillis ); } public KernelTransactionImplementation newTransaction( long lastTransactionIdWhenStarted, LoginContext loginContext ) { return newTransaction( lastTransactionIdWhenStarted, loginContext, defaultTransactionTimeoutMillis ); } public KernelTransactionImplementation newTransaction( long lastTransactionIdWhenStarted, LoginContext loginContext, long transactionTimeoutMillis ) { return newTransaction( lastTransactionIdWhenStarted, loginContext, new NoOpClient(), transactionTimeoutMillis ); } public KernelTransactionImplementation newTransaction( long lastTransactionIdWhenStarted, LoginContext loginContext, Locks.Client locks, long transactionTimeout ) { KernelTransactionImplementation tx = newNotInitializedTransaction(); StatementLocks statementLocks = new SimpleStatementLocks( locks ); SecurityContext securityContext = loginContext.authorize( LoginContext.IdLookup.EMPTY, DEFAULT_DATABASE_NAME ); tx.initialize( lastTransactionIdWhenStarted, BASE_TX_COMMIT_TIMESTAMP, statementLocks, KernelTransaction.Type.EXPLICIT, securityContext, transactionTimeout, 1L, EMBEDDED_CONNECTION ); return tx; } KernelTransactionImplementation newNotInitializedTransaction() { return newNotInitializedTransaction( LeaseService.NO_LEASES ); } KernelTransactionImplementation newNotInitializedTransaction( LeaseService leaseService ) { Dependencies dependencies = new Dependencies(); dependencies.satisfyDependency( mock( GraphDatabaseFacade.class ) ); return new KernelTransactionImplementation( config, mock( DatabaseTransactionEventListeners.class ), null, null, commitProcess, transactionMonitor, txPool, clock, new AtomicReference<>( CpuClock.NOT_AVAILABLE ), new AtomicReference<>( HeapAllocation.NOT_AVAILABLE ), mock( DatabaseTracers.class, RETURNS_MOCKS ), storageEngine, new CanWrite(), EmptyVersionContextSupplier.EMPTY, () -> collectionsFactory, new StandardConstraintSemantics(), mock( SchemaState.class ), mockedTokenHolders(), mock( IndexingService.class ), mock( LabelScanStore.class ), mock( IndexStatisticsStore.class ), dependencies, new TestDatabaseIdRepository().defaultDatabase(), leaseService ); } public static class CapturingCommitProcess implements TransactionCommitProcess { private long txId = TransactionIdStore.BASE_TX_ID; public List<TransactionRepresentation> transactions = new ArrayList<>(); @Override public long commit( TransactionToApply batch, CommitEvent commitEvent, TransactionApplicationMode mode ) { transactions.add( batch.transactionRepresentation() ); return ++txId; } } private static class TestCollectionsFactory implements CollectionsFactory { @Override public MutableLongSet newLongSet() { return OnHeapCollectionsFactory.INSTANCE.newLongSet(); } @Override public MutableLongDiffSetsImpl newLongDiffSets() { return OnHeapCollectionsFactory.INSTANCE.newLongDiffSets(); } @Override public MutableLongObjectMap<Value> newValuesMap() { return new LongObjectHashMap<>(); } @Override public MemoryTracker getMemoryTracker() { return OnHeapCollectionsFactory.INSTANCE.getMemoryTracker(); } @Override public void release() { // nop } } }
UTF-8
Java
10,752
java
KernelTransactionTestBase.java
Java
[ { "context": "/*\n * Copyright (c) 2002-2019 \"Neo4j,\"\n * Neo4j Sweden AB [http://neo4j.com]\n *\n * Thi", "end": 36, "score": 0.5903338193893433, "start": 31, "tag": "USERNAME", "value": "Neo4j" } ]
null
[]
/* * Copyright (c) 2002-2019 "Neo4j," * Neo4j Sweden AB [http://neo4j.com] * * This file is part of Neo4j. * * Neo4j is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.neo4j.kernel.impl.api; import org.eclipse.collections.api.map.primitive.MutableLongObjectMap; import org.eclipse.collections.api.set.primitive.MutableLongSet; import org.eclipse.collections.impl.map.mutable.primitive.LongObjectHashMap; import org.junit.jupiter.api.BeforeEach; import org.mockito.Mockito; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.concurrent.atomic.AtomicReference; import org.neo4j.collection.Dependencies; import org.neo4j.collection.pool.Pool; import org.neo4j.configuration.Config; import org.neo4j.configuration.GraphDatabaseSettings; import org.neo4j.internal.index.label.LabelScanStore; import org.neo4j.internal.kernel.api.security.LoginContext; import org.neo4j.internal.kernel.api.security.SecurityContext; import org.neo4j.internal.schema.SchemaState; import org.neo4j.io.pagecache.tracing.cursor.context.EmptyVersionContextSupplier; import org.neo4j.kernel.api.KernelTransaction; import org.neo4j.kernel.availability.AvailabilityGuard; import org.neo4j.kernel.database.DatabaseTracers; import org.neo4j.kernel.database.TestDatabaseIdRepository; import org.neo4j.kernel.impl.api.index.IndexingService; import org.neo4j.kernel.impl.api.index.stats.IndexStatisticsStore; import org.neo4j.kernel.impl.constraints.StandardConstraintSemantics; import org.neo4j.kernel.impl.factory.CanWrite; import org.neo4j.kernel.impl.factory.GraphDatabaseFacade; import org.neo4j.kernel.impl.locking.Locks; import org.neo4j.kernel.impl.locking.NoOpClient; import org.neo4j.kernel.impl.locking.SimpleStatementLocks; import org.neo4j.kernel.impl.locking.StatementLocks; import org.neo4j.kernel.impl.transaction.TransactionMonitor; import org.neo4j.kernel.impl.transaction.TransactionRepresentation; import org.neo4j.kernel.impl.transaction.tracing.CommitEvent; import org.neo4j.kernel.impl.util.collection.CollectionsFactory; import org.neo4j.kernel.impl.util.collection.OnHeapCollectionsFactory; import org.neo4j.kernel.impl.util.diffsets.MutableLongDiffSetsImpl; import org.neo4j.kernel.internal.event.DatabaseTransactionEventListeners; import org.neo4j.lock.ResourceLocker; import org.neo4j.memory.MemoryTracker; import org.neo4j.resources.CpuClock; import org.neo4j.resources.HeapAllocation; import org.neo4j.storageengine.api.CommandCreationContext; import org.neo4j.storageengine.api.StorageCommand; import org.neo4j.storageengine.api.StorageEngine; import org.neo4j.storageengine.api.StorageReader; import org.neo4j.storageengine.api.TransactionApplicationMode; import org.neo4j.storageengine.api.TransactionIdStore; import org.neo4j.storageengine.api.txstate.ReadableTransactionState; import org.neo4j.storageengine.api.txstate.TxStateVisitor; import org.neo4j.time.Clocks; import org.neo4j.time.FakeClock; import org.neo4j.values.storable.Value; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyCollection; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.Mockito.RETURNS_MOCKS; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.neo4j.configuration.GraphDatabaseSettings.DEFAULT_DATABASE_NAME; import static org.neo4j.internal.kernel.api.connectioninfo.ClientConnectionInfo.EMBEDDED_CONNECTION; import static org.neo4j.internal.kernel.api.security.LoginContext.AUTH_DISABLED; import static org.neo4j.storageengine.api.TransactionIdStore.BASE_TX_COMMIT_TIMESTAMP; import static org.neo4j.test.rule.DatabaseRule.mockedTokenHolders; class KernelTransactionTestBase { protected final StorageEngine storageEngine = mock( StorageEngine.class ); protected final StorageReader storageReader = mock( StorageReader.class ); protected final TransactionIdStore transactionIdStore = mock( TransactionIdStore.class ); protected final CommandCreationContext commandCreationContext = mock( CommandCreationContext.class ); protected final TransactionMonitor transactionMonitor = mock( TransactionMonitor.class ); protected final CapturingCommitProcess commitProcess = new CapturingCommitProcess(); protected final TransactionHeaderInformation headerInformation = mock( TransactionHeaderInformation.class ); protected final AvailabilityGuard availabilityGuard = mock( AvailabilityGuard.class ); protected final FakeClock clock = Clocks.fakeClock(); protected final Pool<KernelTransactionImplementation> txPool = mock( Pool.class ); protected CollectionsFactory collectionsFactory; protected final Config config = Config.defaults(); private final long defaultTransactionTimeoutMillis = config.get( GraphDatabaseSettings.transaction_timeout ).toMillis(); @BeforeEach public void before() throws Exception { collectionsFactory = Mockito.spy( new TestCollectionsFactory() ); when( headerInformation.getAdditionalHeader() ).thenReturn( new byte[0] ); when( storageEngine.newReader() ).thenReturn( storageReader ); when( storageEngine.newCommandCreationContext() ).thenReturn( commandCreationContext ); when( storageEngine.transactionIdStore() ).thenReturn( transactionIdStore ); doAnswer( invocation -> ((Collection<StorageCommand>) invocation.getArgument(0) ).add( new TestCommand() ) ) .when( storageEngine ).createCommands( anyCollection(), any( ReadableTransactionState.class ), any( StorageReader.class ), any( CommandCreationContext.class ), any( ResourceLocker.class ), anyLong(), any( TxStateVisitor.Decorator.class ) ); } public KernelTransactionImplementation newTransaction( long transactionTimeoutMillis ) { return newTransaction( 0, AUTH_DISABLED, transactionTimeoutMillis ); } public KernelTransactionImplementation newTransaction( LoginContext loginContext ) { return newTransaction( 0, loginContext ); } public KernelTransactionImplementation newTransaction( LoginContext loginContext, Locks.Client locks ) { return newTransaction( 0, loginContext, locks, defaultTransactionTimeoutMillis ); } public KernelTransactionImplementation newTransaction( long lastTransactionIdWhenStarted, LoginContext loginContext ) { return newTransaction( lastTransactionIdWhenStarted, loginContext, defaultTransactionTimeoutMillis ); } public KernelTransactionImplementation newTransaction( long lastTransactionIdWhenStarted, LoginContext loginContext, long transactionTimeoutMillis ) { return newTransaction( lastTransactionIdWhenStarted, loginContext, new NoOpClient(), transactionTimeoutMillis ); } public KernelTransactionImplementation newTransaction( long lastTransactionIdWhenStarted, LoginContext loginContext, Locks.Client locks, long transactionTimeout ) { KernelTransactionImplementation tx = newNotInitializedTransaction(); StatementLocks statementLocks = new SimpleStatementLocks( locks ); SecurityContext securityContext = loginContext.authorize( LoginContext.IdLookup.EMPTY, DEFAULT_DATABASE_NAME ); tx.initialize( lastTransactionIdWhenStarted, BASE_TX_COMMIT_TIMESTAMP, statementLocks, KernelTransaction.Type.EXPLICIT, securityContext, transactionTimeout, 1L, EMBEDDED_CONNECTION ); return tx; } KernelTransactionImplementation newNotInitializedTransaction() { return newNotInitializedTransaction( LeaseService.NO_LEASES ); } KernelTransactionImplementation newNotInitializedTransaction( LeaseService leaseService ) { Dependencies dependencies = new Dependencies(); dependencies.satisfyDependency( mock( GraphDatabaseFacade.class ) ); return new KernelTransactionImplementation( config, mock( DatabaseTransactionEventListeners.class ), null, null, commitProcess, transactionMonitor, txPool, clock, new AtomicReference<>( CpuClock.NOT_AVAILABLE ), new AtomicReference<>( HeapAllocation.NOT_AVAILABLE ), mock( DatabaseTracers.class, RETURNS_MOCKS ), storageEngine, new CanWrite(), EmptyVersionContextSupplier.EMPTY, () -> collectionsFactory, new StandardConstraintSemantics(), mock( SchemaState.class ), mockedTokenHolders(), mock( IndexingService.class ), mock( LabelScanStore.class ), mock( IndexStatisticsStore.class ), dependencies, new TestDatabaseIdRepository().defaultDatabase(), leaseService ); } public static class CapturingCommitProcess implements TransactionCommitProcess { private long txId = TransactionIdStore.BASE_TX_ID; public List<TransactionRepresentation> transactions = new ArrayList<>(); @Override public long commit( TransactionToApply batch, CommitEvent commitEvent, TransactionApplicationMode mode ) { transactions.add( batch.transactionRepresentation() ); return ++txId; } } private static class TestCollectionsFactory implements CollectionsFactory { @Override public MutableLongSet newLongSet() { return OnHeapCollectionsFactory.INSTANCE.newLongSet(); } @Override public MutableLongDiffSetsImpl newLongDiffSets() { return OnHeapCollectionsFactory.INSTANCE.newLongDiffSets(); } @Override public MutableLongObjectMap<Value> newValuesMap() { return new LongObjectHashMap<>(); } @Override public MemoryTracker getMemoryTracker() { return OnHeapCollectionsFactory.INSTANCE.getMemoryTracker(); } @Override public void release() { // nop } } }
10,752
0.757347
0.750837
230
45.747826
34.805008
131
false
false
0
0
0
0
0
0
0.743478
false
false
12
df39e4194b9163ef8a6a922cda9681f37b43f246
28,192,165,346,195
4e8a7beb6fc5a09b9e3b2b8de8b84cdfd5db8244
/OS/Lab3/src/main/java/lab3/Task2.java
62729f4610796648160ea02f2579f28c31256bee
[]
no_license
Kirill128/4Sem
https://github.com/Kirill128/4Sem
0bb34a2a8601ef150e3d676d29da31f8adbe4295
5f79d6b40f36f7cec9f77e46e0d19e14ec19e05b
refs/heads/master
2023-05-11T20:12:54.417000
2021-06-01T05:08:23
2021-06-01T05:08:23
340,308,201
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package lab3; public class Task2 implements ITask{ private MyNodeBox myNodeBox; public Task2(MyNodeBox myNodeBox) { this.myNodeBox = myNodeBox; } @Override public void makeTask() { String input=this.myNodeBox.getTextInputString(); char c=input.toCharArray()[0]; this.myNodeBox.setResultString("Result: "+(int)c); } //--------------------------------------------------------------- @Override public MyNodeBox getMyNodeBox() { return myNodeBox; } @Override public void setMyNodeBox(MyNodeBox myNodeBox) { this.myNodeBox = myNodeBox; } }
UTF-8
Java
636
java
Task2.java
Java
[]
null
[]
package lab3; public class Task2 implements ITask{ private MyNodeBox myNodeBox; public Task2(MyNodeBox myNodeBox) { this.myNodeBox = myNodeBox; } @Override public void makeTask() { String input=this.myNodeBox.getTextInputString(); char c=input.toCharArray()[0]; this.myNodeBox.setResultString("Result: "+(int)c); } //--------------------------------------------------------------- @Override public MyNodeBox getMyNodeBox() { return myNodeBox; } @Override public void setMyNodeBox(MyNodeBox myNodeBox) { this.myNodeBox = myNodeBox; } }
636
0.575472
0.569182
27
22.555555
20.177607
65
false
false
0
0
0
0
0
0
0.296296
false
false
12
0c8631cab6097c55b1f03d3e7a5c6cc69aa1bc92
816,043,833,733
5f9c16526521b87797cfe1b11132fd99f8377071
/src/main/java/com/gd/HelloSonarQubeBad.java
1c3f869d2347d713089e7507fbf6d57e23c75b50
[]
no_license
gangadharparde/sonar-demos
https://github.com/gangadharparde/sonar-demos
3244f1a9c798d5a89ee03e21af4bb8285272e7da
9d282666e55497d8b36a053cbf2f880441c52d8a
refs/heads/master
2021-06-06T21:59:58.192000
2021-05-26T14:42:32
2021-05-26T14:42:32
143,194,532
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.gd; public class HelloSonarQubeBad { public static void main(String[] args) { System.out.println("Hello Sonar Qube World......."); } }
UTF-8
Java
154
java
HelloSonarQubeBad.java
Java
[]
null
[]
package com.gd; public class HelloSonarQubeBad { public static void main(String[] args) { System.out.println("Hello Sonar Qube World......."); } }
154
0.681818
0.681818
9
16.111111
19.762167
54
false
false
0
0
0
0
0
0
0.666667
false
false
12
07c1762b79ed4747dc240de6cff82e930be25892
21,010,980,059,546
014f566ab22cc6dabe1ec7237077fa2c44b71d57
/java/spring/spring-all-in-one/19-spring-message/src/main/java/com/wjiec/sprngaio/message/RabbitMqApplication.java
6b18452f21f64959a5eb07ef0e736d0c5b3d8fa7
[ "MIT" ]
permissive
JShadowMan/packages
https://github.com/JShadowMan/packages
ab2b6c56854601923c0334e051ff47b0e4540b95
755ee1918e2fca5f414131eb028f222da095ba45
refs/heads/master
2021-05-22T10:49:33.556000
2021-05-20T15:23:04
2021-05-20T15:23:04
48,322,192
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.wjiec.sprngaio.message; import org.springframework.amqp.core.AmqpAdmin; import org.springframework.amqp.core.Message; import org.springframework.amqp.core.Queue; import org.springframework.amqp.rabbit.connection.ConnectionFactory; import org.springframework.amqp.rabbit.core.RabbitAdmin; import org.springframework.amqp.rabbit.core.RabbitOperations; import org.springframework.amqp.rabbit.core.RabbitTemplate; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.ImportResource; import org.springframework.stereotype.Component; @Configuration @ImportResource("/amqp.xml") public class RabbitMqApplication { public static void main(String[] args) throws InterruptedException { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); context.register(RabbitMqApplication.class); context.refresh(); RabbitOperations rabbitOperations = context.getBean(RabbitOperations.class); System.out.println(rabbitOperations); new Thread(() -> { while (true) { // Message message = rabbitOperations.receive("spring.queue"); // System.out.println(message); String s = (String) rabbitOperations.receiveAndConvert("spring.queue"); System.out.println(s); try { Thread.sleep(1000); } catch (InterruptedException ignored) {} } }).start(); Thread.sleep(1000); rabbitOperations.convertAndSend("spring.queue", "content"); rabbitOperations.convertAndSend("spring.queue", "content"); rabbitOperations.convertAndSend("spring.queue", "content"); rabbitOperations.convertAndSend("spring.queue", "content"); rabbitOperations.convertAndSend("spring.queue", "content"); rabbitOperations.convertAndSend("spring.queue", "content"); rabbitOperations.convertAndSend("spring.queue", "content"); } @Bean public AmqpAdmin amqpAdmin(RabbitTemplate rabbitTemplate) { RabbitAdmin admin = new RabbitAdmin(rabbitTemplate); admin.declareQueue(new Queue("spring.queue")); return admin; } @Bean public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory) { return new RabbitTemplate(connectionFactory); } @Component("stringHandler") public static class StringHandler { public void handle(String message) { System.out.println("StringHandler.handle : " + message); } } }
UTF-8
Java
2,811
java
RabbitMqApplication.java
Java
[]
null
[]
package com.wjiec.sprngaio.message; import org.springframework.amqp.core.AmqpAdmin; import org.springframework.amqp.core.Message; import org.springframework.amqp.core.Queue; import org.springframework.amqp.rabbit.connection.ConnectionFactory; import org.springframework.amqp.rabbit.core.RabbitAdmin; import org.springframework.amqp.rabbit.core.RabbitOperations; import org.springframework.amqp.rabbit.core.RabbitTemplate; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.ImportResource; import org.springframework.stereotype.Component; @Configuration @ImportResource("/amqp.xml") public class RabbitMqApplication { public static void main(String[] args) throws InterruptedException { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); context.register(RabbitMqApplication.class); context.refresh(); RabbitOperations rabbitOperations = context.getBean(RabbitOperations.class); System.out.println(rabbitOperations); new Thread(() -> { while (true) { // Message message = rabbitOperations.receive("spring.queue"); // System.out.println(message); String s = (String) rabbitOperations.receiveAndConvert("spring.queue"); System.out.println(s); try { Thread.sleep(1000); } catch (InterruptedException ignored) {} } }).start(); Thread.sleep(1000); rabbitOperations.convertAndSend("spring.queue", "content"); rabbitOperations.convertAndSend("spring.queue", "content"); rabbitOperations.convertAndSend("spring.queue", "content"); rabbitOperations.convertAndSend("spring.queue", "content"); rabbitOperations.convertAndSend("spring.queue", "content"); rabbitOperations.convertAndSend("spring.queue", "content"); rabbitOperations.convertAndSend("spring.queue", "content"); } @Bean public AmqpAdmin amqpAdmin(RabbitTemplate rabbitTemplate) { RabbitAdmin admin = new RabbitAdmin(rabbitTemplate); admin.declareQueue(new Queue("spring.queue")); return admin; } @Bean public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory) { return new RabbitTemplate(connectionFactory); } @Component("stringHandler") public static class StringHandler { public void handle(String message) { System.out.println("StringHandler.handle : " + message); } } }
2,811
0.688723
0.685877
71
37.591549
27.834307
94
false
false
0
0
0
0
0
0
0.619718
false
false
12
21f50acc3f53c52ca2ea8b73991c6e21a7d632e4
9,964,324,127,369
623a9f5cf51cf77150128f5b042f377a14110c39
/app/src/main/java/com/fenrir_inc/databindingfragment/apis/ConfigClient.java
8b462acd3a596cc61a2068e58f4a99865c2344fe
[]
no_license
Kohei0309/MaterialDesign
https://github.com/Kohei0309/MaterialDesign
aab9918f294a6b56918d74036a943f0102a87ce0
03180d74cc7df205e42f5750403f955086767c90
refs/heads/master
2016-09-21T19:30:42.028000
2016-09-07T00:26:17
2016-09-07T00:26:17
67,557,022
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.fenrir_inc.databindingfragment.apis; import android.support.annotation.NonNull; import okhttp3.OkHttpClient; import retrofit2.Retrofit; import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory; import retrofit2.converter.gson.GsonConverterFactory; /** * サーバー通信 の 設定 */ public class ConfigClient implements IConfigClient { private OkHttpClient mClient; private IItemApi mItemApi; private IMailApi mMailApi; public ConfigClient() { getOkHttpClient(); } @NonNull @Override public OkHttpClient getOkHttpClient() { mClient = new OkHttpClient(); return mClient; } @NonNull @Override public IItemApi getItemApi() { if (mItemApi == null) { Retrofit retrofit = new Retrofit.Builder() .baseUrl(ConfigUrl.API_BASE_URL) .client(mClient) .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .build(); mItemApi = retrofit.create(IItemApi.class); } return mItemApi; } @NonNull @Override public IMailApi getMailApi() { if (mMailApi == null) { Retrofit retrofit = new Retrofit.Builder() .baseUrl(ConfigUrl.API_BASE_URL) .client(mClient) .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .build(); mMailApi = retrofit.create(IMailApi.class); } return mMailApi; } }
UTF-8
Java
1,619
java
ConfigClient.java
Java
[]
null
[]
package com.fenrir_inc.databindingfragment.apis; import android.support.annotation.NonNull; import okhttp3.OkHttpClient; import retrofit2.Retrofit; import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory; import retrofit2.converter.gson.GsonConverterFactory; /** * サーバー通信 の 設定 */ public class ConfigClient implements IConfigClient { private OkHttpClient mClient; private IItemApi mItemApi; private IMailApi mMailApi; public ConfigClient() { getOkHttpClient(); } @NonNull @Override public OkHttpClient getOkHttpClient() { mClient = new OkHttpClient(); return mClient; } @NonNull @Override public IItemApi getItemApi() { if (mItemApi == null) { Retrofit retrofit = new Retrofit.Builder() .baseUrl(ConfigUrl.API_BASE_URL) .client(mClient) .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .build(); mItemApi = retrofit.create(IItemApi.class); } return mItemApi; } @NonNull @Override public IMailApi getMailApi() { if (mMailApi == null) { Retrofit retrofit = new Retrofit.Builder() .baseUrl(ConfigUrl.API_BASE_URL) .client(mClient) .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .build(); mMailApi = retrofit.create(IMailApi.class); } return mMailApi; } }
1,619
0.610244
0.607745
58
26.620689
21.37258
77
false
false
0
0
0
0
0
0
0.310345
false
false
12
d85264fb9305939f0c7a184345294efe2c88055d
15,685,220,607,819
60fa3b381e11eaf2ed866742e87a7d407f20ba45
/src/com/isnotok/sleep/model/TileResource.java
9eec48472e8cd7aa4dce5e346f33e4b7faae6f52
[]
no_license
islocated/Sleepy
https://github.com/islocated/Sleepy
ffe458279e706082ff661dbbb371d68941710690
038a53c43f1a51b00f4cd87ee6bde71c143a78ed
refs/heads/master
2021-01-01T17:57:23.146000
2010-05-18T22:38:35
2010-05-18T22:38:35
667,528
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.isnotok.sleep.model; import java.io.File; import org.eclipse.swt.graphics.ImageData; import org.eclipse.swt.graphics.PaletteData; public class TileResource extends Resource{ public static final int SIZE = 16; public static final int BYTES_PER_PIXEL = 4; public static final int BYTES_TOTAL = SIZE * SIZE * BYTES_PER_PIXEL; public TileResource(File file){ super(file); load(); nameOffset = BYTES_TOTAL; } @Override public String getType() { return "tile"; }; @Override protected ImageData calculateImageData(){ if(data == null || data.length < BYTES_TOTAL) return null; PaletteData palette = new PaletteData(0xFF000000, 0xFF0000, 0xFF00); return new ImageData(SIZE, SIZE, 8 * BYTES_PER_PIXEL, palette, 1, data); } public static void main(String [] args){ File file = new File(".", "input/0A3A96732EF2"); TileResource resourceFile = new TileResource(file); //resourceFile.load(); } }
UTF-8
Java
949
java
TileResource.java
Java
[]
null
[]
package com.isnotok.sleep.model; import java.io.File; import org.eclipse.swt.graphics.ImageData; import org.eclipse.swt.graphics.PaletteData; public class TileResource extends Resource{ public static final int SIZE = 16; public static final int BYTES_PER_PIXEL = 4; public static final int BYTES_TOTAL = SIZE * SIZE * BYTES_PER_PIXEL; public TileResource(File file){ super(file); load(); nameOffset = BYTES_TOTAL; } @Override public String getType() { return "tile"; }; @Override protected ImageData calculateImageData(){ if(data == null || data.length < BYTES_TOTAL) return null; PaletteData palette = new PaletteData(0xFF000000, 0xFF0000, 0xFF00); return new ImageData(SIZE, SIZE, 8 * BYTES_PER_PIXEL, palette, 1, data); } public static void main(String [] args){ File file = new File(".", "input/0A3A96732EF2"); TileResource resourceFile = new TileResource(file); //resourceFile.load(); } }
949
0.711275
0.68177
39
23.333334
22.382839
77
false
false
0
0
0
0
0
0
1.794872
false
false
12
27af8acd911dba4fa628b4ad078bba52cfe0b62e
29,609,504,569,165
359de94e45318c309683f16573764a99bc471b7f
/app/src/main/java/fy/mu/exams/easy/easyexamsnew/Second_java.java
ed8c9a8cfe4db1477de7ff969205274a5f684c25
[]
no_license
AyushKumarPrasad/EasyExamsNew
https://github.com/AyushKumarPrasad/EasyExamsNew
4619001a1ccad03cfd8fcaf274e5dd00de5edb4b
623f816d5413fd405e30edc49a8853772f96c38f
refs/heads/master
2020-05-14T04:41:36.097000
2019-04-16T13:47:00
2019-04-16T13:47:00
181,698,081
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package fy.mu.exams.easy.easyexamsnew; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; public class Second_java extends AppCompatActivity { ImageView m1, m2, m3, m4; Button b3, b4, b5, b6; ImageView back ; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.second_screen); b3 = (Button) findViewById(R.id.button3); b3.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent ayush = new Intent(Second_java.this, Fourth_java.class); startActivity(ayush); } }); b4 = (Button) findViewById(R.id.button4); b4.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent ayush = new Intent(Second_java.this, Fifth_java.class); startActivity(ayush); } }); b5 = (Button) findViewById(R.id.button5); b5.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent ayush = new Intent(Second_java.this, Sixth_java.class); startActivity(ayush); } }); b6 = (Button) findViewById(R.id.button6); b6.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent ayush = new Intent(Second_java.this, Seventh_java.class); startActivity(ayush); } }); back = (ImageView) findViewById(R.id.back_sem1); back.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(Second_java.this,Home.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent); } }); } public void onBackPressed() { Intent intent = new Intent(Second_java.this,Home.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent); } }
UTF-8
Java
2,768
java
Second_java.java
Java
[]
null
[]
package fy.mu.exams.easy.easyexamsnew; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; public class Second_java extends AppCompatActivity { ImageView m1, m2, m3, m4; Button b3, b4, b5, b6; ImageView back ; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.second_screen); b3 = (Button) findViewById(R.id.button3); b3.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent ayush = new Intent(Second_java.this, Fourth_java.class); startActivity(ayush); } }); b4 = (Button) findViewById(R.id.button4); b4.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent ayush = new Intent(Second_java.this, Fifth_java.class); startActivity(ayush); } }); b5 = (Button) findViewById(R.id.button5); b5.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent ayush = new Intent(Second_java.this, Sixth_java.class); startActivity(ayush); } }); b6 = (Button) findViewById(R.id.button6); b6.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent ayush = new Intent(Second_java.this, Seventh_java.class); startActivity(ayush); } }); back = (ImageView) findViewById(R.id.back_sem1); back.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(Second_java.this,Home.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent); } }); } public void onBackPressed() { Intent intent = new Intent(Second_java.this,Home.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent); } }
2,768
0.569003
0.560694
90
28.777779
23.793453
96
false
false
0
0
0
0
0
0
0.6
false
false
12
f06fd6caad3a4ab92cd1f035b67f2dbb623d6d30
8,169,027,839,905
d0db2c2940742027ca1a9b378c8b08abba2e68cc
/ProgEx/src/DemoSubsciptions.java
98aa798edae44410604ea84e0e512e0047540dd5
[]
no_license
lukeveltjensswan/cp2406_farrell8_ch11
https://github.com/lukeveltjensswan/cp2406_farrell8_ch11
f92af1973f183f517197cd34337b7b08e83b4f81
7abd5e7a8a5c61bce54adeaa4bb753b79d629203
refs/heads/master
2019-01-15T03:03:31.991000
2016-09-20T02:40:00
2016-09-20T02:40:00
68,566,163
0
0
null
true
2016-09-19T03:31:42
2016-09-19T03:31:41
2015-11-13T03:56:33
2015-11-13T03:56:33
0
0
0
0
null
null
null
/** * Created by Luke on 15/09/2016. */ public class DemoSubsciptions { public static void main(String args[]) { PhysicalNewspaperSubscription pnsGood = new PhysicalNewspaperSubscription(); OnlineNewspaperSubscription onsGood = new OnlineNewspaperSubscription(); PhysicalNewspaperSubscription pnsBad = new PhysicalNewspaperSubscription(); OnlineNewspaperSubscription onsBad = new OnlineNewspaperSubscription(); pnsGood.setName("Smith"); pnsGood.setAddress("2 house street"); display(pnsGood); pnsBad.setName("Murray"); pnsBad.setAddress("Whereat Road"); display(pnsBad); onsGood.setName("Smithers"); onsGood.setAddress("smith@outlook.com"); display(onsGood); onsBad.setName("Don"); onsBad.setAddress("Lol Street"); display(onsBad); } public static void display(NewspaperSubscription n) { System.out.println("Name: " + n.getName() + " Address: " + n.getAddress() + " Rate: " + n.getRate() + "\n"); } }
UTF-8
Java
1,084
java
DemoSubsciptions.java
Java
[ { "context": "/**\n * Created by Luke on 15/09/2016.\n */\npublic class DemoSubsciptions\n", "end": 22, "score": 0.9997400045394897, "start": 18, "tag": "NAME", "value": "Luke" }, { "context": "NewspaperSubscription();\n pnsGood.setName(\"Smith\");\n pnsGood.setAddress(\"2 house street\");\n", "end": 483, "score": 0.999631404876709, "start": 478, "tag": "NAME", "value": "Smith" }, { "context": " display(pnsGood);\n pnsBad.setName(\"Murray\");\n pnsBad.setAddress(\"Whereat Road\");\n ", "end": 589, "score": 0.9997243881225586, "start": 583, "tag": "NAME", "value": "Murray" }, { "context": " display(pnsBad);\n onsGood.setName(\"Smithers\");\n onsGood.setAddress(\"smith@outlook.com\"", "end": 694, "score": 0.9996168613433838, "start": 686, "tag": "NAME", "value": "Smithers" }, { "context": ".setName(\"Smithers\");\n onsGood.setAddress(\"smith@outlook.com\");\n display(onsGood);\n onsBad.setNa", "end": 743, "score": 0.9999229311943054, "start": 726, "tag": "EMAIL", "value": "smith@outlook.com" }, { "context": " display(onsGood);\n onsBad.setName(\"Don\");\n onsBad.setAddress(\"Lol Street\");\n ", "end": 800, "score": 0.9998051524162292, "start": 797, "tag": "NAME", "value": "Don" } ]
null
[]
/** * Created by Luke on 15/09/2016. */ public class DemoSubsciptions { public static void main(String args[]) { PhysicalNewspaperSubscription pnsGood = new PhysicalNewspaperSubscription(); OnlineNewspaperSubscription onsGood = new OnlineNewspaperSubscription(); PhysicalNewspaperSubscription pnsBad = new PhysicalNewspaperSubscription(); OnlineNewspaperSubscription onsBad = new OnlineNewspaperSubscription(); pnsGood.setName("Smith"); pnsGood.setAddress("2 house street"); display(pnsGood); pnsBad.setName("Murray"); pnsBad.setAddress("Whereat Road"); display(pnsBad); onsGood.setName("Smithers"); onsGood.setAddress("<EMAIL>"); display(onsGood); onsBad.setName("Don"); onsBad.setAddress("Lol Street"); display(onsBad); } public static void display(NewspaperSubscription n) { System.out.println("Name: " + n.getName() + " Address: " + n.getAddress() + " Rate: " + n.getRate() + "\n"); } }
1,074
0.635609
0.627306
30
35.099998
25.850016
84
false
false
0
0
0
0
0
0
0.566667
false
false
12
2e6526c6c1b6baec4f096b4ab5193f5fb7486441
4,587,025,106,449
a40df585e6ba3e4bcb026828419cb70da36944af
/zl-micro/zl-micro-security/src/main/java/com/xdzl/security/ZlBootSecurityApplication.java
071d27282810e3246a944acdea9b8af52a9018f8
[]
no_license
csf00298/xdzl
https://github.com/csf00298/xdzl
1c1c8d4a3c28500609cd73427a5a3cb901dbab35
2212f2fd1cc0df14ff32fc775b8767ca807f8d6b
refs/heads/master
2021-01-22T13:23:05.850000
2017-09-09T07:39:40
2017-09-09T07:39:40
100,666,165
3
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.xdzl.security; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; /** 参考:http://blog.csdn.net/u012702547/article/details/54319508*/ @SpringBootApplication public class ZlBootSecurityApplication { public static void main(String[] args) { SpringApplication.run(ZlBootSecurityApplication.class, args); } }
UTF-8
Java
397
java
ZlBootSecurityApplication.java
Java
[ { "context": "ringBootApplication;\n\n/** 参考:http://blog.csdn.net/u012702547/article/details/54319508*/\n@SpringBootApplication", "end": 187, "score": 0.9995523691177368, "start": 177, "tag": "USERNAME", "value": "u012702547" } ]
null
[]
package com.xdzl.security; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; /** 参考:http://blog.csdn.net/u012702547/article/details/54319508*/ @SpringBootApplication public class ZlBootSecurityApplication { public static void main(String[] args) { SpringApplication.run(ZlBootSecurityApplication.class, args); } }
397
0.815857
0.772379
13
29.076923
25.977688
68
false
false
0
0
0
0
0
0
0.692308
false
false
12
70273c0bf288aef237ea51fa0cac9f343583594f
15,814,069,620,088
51738545b74747da23bef08eba915cc56894fe25
/UserDetailsInterface.java
c684c97b009923e3446df364b6bda7235fcb93e3
[]
no_license
aishwariya-cloud/mysample
https://github.com/aishwariya-cloud/mysample
83668efca92d23f8306718f3f89874f73bebc417
e7d81e4da06b957866412109d9f1902790c726c4
refs/heads/master
2020-12-04T02:36:59.667000
2020-01-03T11:33:31
2020-01-03T11:33:31
231,574,502
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.readygo.services; import java.util.ArrayList; import com.readygo.model.Users; public interface UserDetailsInterface { public void addUser(String userFName,String userLName,int contact,String email,String address,String city,String password,String role ); public ArrayList<Users> display(); public void login(String email,String password); }
UTF-8
Java
375
java
UserDetailsInterface.java
Java
[]
null
[]
package com.readygo.services; import java.util.ArrayList; import com.readygo.model.Users; public interface UserDetailsInterface { public void addUser(String userFName,String userLName,int contact,String email,String address,String city,String password,String role ); public ArrayList<Users> display(); public void login(String email,String password); }
375
0.776
0.776
13
26.846153
36.246689
137
false
false
0
0
0
0
0
0
1.384615
false
false
12
873f43655a3aec7dda406af5afad4a17ace4112c
16,982,300,733,989
f3aec68bc48dc52e76f276fd3b47c3260c01b2a4
/core/database/src/main/java/ru/korus/tmis/schedule/TypeOfQuota.java
1a1da5e941ce81065ee36704ac0fc7a6f05a8c9f
[]
no_license
MarsStirner/core
https://github.com/MarsStirner/core
c9a383799a92e485e2395d81a0bc95d51ada5fa5
6fbf37af989aa48fabb9c4c2566195aafd2b16ab
refs/heads/master
2020-12-03T00:39:51.407000
2016-04-29T12:28:32
2016-04-29T12:28:32
96,041,573
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package ru.korus.tmis.schedule; /** * Author: Sergey A. Zagrebelny <br> * Date: 23.12.13, 20:33 <br> * Company: Korus Consulting IT<br> * Description: <br> */ public enum TypeOfQuota { FROM_REGISTRY(1), SECOND_VISIT(2), BETWEEN_CABINET(3), FROM_OTHER_LPU(4), FROM_PORTAL(5); private final int value; private TypeOfQuota(int value) { this.value = value; } public int getValue() { return value; } }
UTF-8
Java
478
java
TypeOfQuota.java
Java
[ { "context": "ckage ru.korus.tmis.schedule;\n\n/**\n * Author: Sergey A. Zagrebelny <br>\n * Date: 23.12.13, 20:33 <br>\n * Comp", "end": 73, "score": 0.9998782277107239, "start": 53, "tag": "NAME", "value": "Sergey A. Zagrebelny" } ]
null
[]
package ru.korus.tmis.schedule; /** * Author: <NAME> <br> * Date: 23.12.13, 20:33 <br> * Company: Korus Consulting IT<br> * Description: <br> */ public enum TypeOfQuota { FROM_REGISTRY(1), SECOND_VISIT(2), BETWEEN_CABINET(3), FROM_OTHER_LPU(4), FROM_PORTAL(5); private final int value; private TypeOfQuota(int value) { this.value = value; } public int getValue() { return value; } }
464
0.583682
0.552301
25
18.16
13.48089
41
false
false
0
0
0
0
0
0
0.4
false
false
12
dee74bd207eb2e8fbf158e4d78c4a8e8fb3a1da7
30,571,577,264,940
bd12771abb5284c654ada5f8ae4114f15164e34c
/app/src/main/java/com/evnica/theatermap/Locator.java
b7f09edb9aed2ac7ce9a813f910fe1e78121e223
[]
no_license
ricots/TheaterMap
https://github.com/ricots/TheaterMap
96f413837cc4806cdd9c894055f00d642fb28ed4
cbd1899937769c9e3dc82b12a3366a6c62e9eb37
refs/heads/master
2021-01-18T01:37:21.152000
2016-07-07T18:48:58
2016-07-07T18:48:58
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.evnica.theatermap; import android.location.Location; import android.location.LocationListener; import android.os.Bundle; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.MarkerOptions; public class Locator implements LocationListener { private static GoogleMap googleMap; public static int accessFineLocationPermission; public static int accessCoarseLocationPermission; public static void setGoogleMap(GoogleMap googleMap) { Locator.googleMap = googleMap; } @Override public void onLocationChanged(Location location) { MarkerOptions marker = new MarkerOptions() .position(new LatLng(location.getLatitude(), location.getLongitude())) .title("Ich bin da"); googleMap.addMarker(marker); } @Override public void onStatusChanged(String provider, int status, Bundle extras) { } @Override public void onProviderEnabled(String provider) { } @Override public void onProviderDisabled(String provider) { } }
UTF-8
Java
1,133
java
Locator.java
Java
[]
null
[]
package com.evnica.theatermap; import android.location.Location; import android.location.LocationListener; import android.os.Bundle; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.MarkerOptions; public class Locator implements LocationListener { private static GoogleMap googleMap; public static int accessFineLocationPermission; public static int accessCoarseLocationPermission; public static void setGoogleMap(GoogleMap googleMap) { Locator.googleMap = googleMap; } @Override public void onLocationChanged(Location location) { MarkerOptions marker = new MarkerOptions() .position(new LatLng(location.getLatitude(), location.getLongitude())) .title("Ich bin da"); googleMap.addMarker(marker); } @Override public void onStatusChanged(String provider, int status, Bundle extras) { } @Override public void onProviderEnabled(String provider) { } @Override public void onProviderDisabled(String provider) { } }
1,133
0.721977
0.721977
44
24.75
24.613489
86
false
false
0
0
0
0
0
0
0.363636
false
false
12
df1c48aa3f7e1ca51709f07ab47037ed77ab3680
19,825,569,042,669
4dbfcf1b975db3deecfc2300eabe4dab23923b99
/easyBuyWorkSpace/easybuy-manager-web/src/test/java/org/java/text/fastdfs/FastDFSText.java
2d8c834474ca3e1849d10e3693d6386409e344ca
[]
no_license
BluenessSky/easyBuy
https://github.com/BluenessSky/easyBuy
52d54bdf627aa442ca15c7ab419643229b6074b4
e8015a4c6dbb76e9cc89708c2b284097a1e4579c
refs/heads/master
2020-04-13T01:03:48.725000
2018-12-23T04:53:20
2018-12-23T04:53:20
162,862,909
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.java.text.fastdfs; import org.csource.fastdfs.ClientGlobal; import org.csource.fastdfs.StorageClient; import org.csource.fastdfs.StorageServer; import org.csource.fastdfs.TrackerClient; import org.csource.fastdfs.TrackerServer; import org.java.common.utils.FastDFSClient; import org.junit.Test; public class FastDFSText { @Test public void textFastText() throws Exception{ //1.导入fastdfs的jar包 //2.加载配置文件,配置文件 ClientGlobal.init("F:\\easyBuyWorkSpace\\easybuy-manager-web\\src\\main\\resources\\resource\\fdfs_client.conf"); //3.创建trackerClient对象 TrackerClient trackerClient=new TrackerClient(); TrackerServer trackerServer=trackerClient.getConnection(); //4.创建storageServer对象 StorageServer storageServer=null; StorageClient storageClient=new StorageClient(trackerServer, storageServer); //6.使用storageServer实现上传图片 String[] upload_file = storageClient.upload_file("D:/新建文件夹 (2)/lvguang.png","png",null); //7.返回一个数组 for (String string : upload_file) { System.out.println(string); } } @Test public void textFastText1() throws Exception{ FastDFSClient fastDFSClient=new FastDFSClient("F:\\easyBuyWorkSpace\\easybuy-manager-web\\src\\main\\resources\\resource\\fdfs_client.conf"); String str=fastDFSClient.uploadFile("D:/新建文件夹 (2)/lvguang.png"); System.out.println(str); } }
UTF-8
Java
1,418
java
FastDFSText.java
Java
[]
null
[]
package org.java.text.fastdfs; import org.csource.fastdfs.ClientGlobal; import org.csource.fastdfs.StorageClient; import org.csource.fastdfs.StorageServer; import org.csource.fastdfs.TrackerClient; import org.csource.fastdfs.TrackerServer; import org.java.common.utils.FastDFSClient; import org.junit.Test; public class FastDFSText { @Test public void textFastText() throws Exception{ //1.导入fastdfs的jar包 //2.加载配置文件,配置文件 ClientGlobal.init("F:\\easyBuyWorkSpace\\easybuy-manager-web\\src\\main\\resources\\resource\\fdfs_client.conf"); //3.创建trackerClient对象 TrackerClient trackerClient=new TrackerClient(); TrackerServer trackerServer=trackerClient.getConnection(); //4.创建storageServer对象 StorageServer storageServer=null; StorageClient storageClient=new StorageClient(trackerServer, storageServer); //6.使用storageServer实现上传图片 String[] upload_file = storageClient.upload_file("D:/新建文件夹 (2)/lvguang.png","png",null); //7.返回一个数组 for (String string : upload_file) { System.out.println(string); } } @Test public void textFastText1() throws Exception{ FastDFSClient fastDFSClient=new FastDFSClient("F:\\easyBuyWorkSpace\\easybuy-manager-web\\src\\main\\resources\\resource\\fdfs_client.conf"); String str=fastDFSClient.uploadFile("D:/新建文件夹 (2)/lvguang.png"); System.out.println(str); } }
1,418
0.77568
0.768882
36
35.777779
31.396313
143
false
false
0
0
0
0
0
0
1.777778
false
false
12
37ee208966e88749931e2834d2682d0f1c17d0ef
9,380,208,593,164
70115684d5432a741c3d246136bb55e841fd5ae3
/javahandson6/src/Animal.java
d4e0e1fa382b8acc3d0b9aa70891c3d77fbc30a5
[]
no_license
narasimhamuvva/JAVAHANDSON
https://github.com/narasimhamuvva/JAVAHANDSON
47c8de73025d4adeaccbe8eae8c4da13fc4bf718
f9402cdc8e289352935fa831e38f45071e318745
refs/heads/master
2021-01-10T06:59:47.517000
2015-10-20T14:22:07
2015-10-20T14:22:07
44,044,488
0
0
null
false
2015-10-12T12:02:28
2015-10-11T08:22:48
2015-10-11T08:31:55
2015-10-12T12:02:28
0
0
0
0
Java
null
null
public class Animal { String family="Animal"; } class Fish extends Animal{ String habitat="Water"; String type="Aquatic"; } class Shark extends Fish{ String kind="Shark"; public void display() { System.out.println(kind+"is an"+family+"which lives in"+habitat+",hence it is"+"\t"+type); } }
UTF-8
Java
304
java
Animal.java
Java
[]
null
[]
public class Animal { String family="Animal"; } class Fish extends Animal{ String habitat="Water"; String type="Aquatic"; } class Shark extends Fish{ String kind="Shark"; public void display() { System.out.println(kind+"is an"+family+"which lives in"+habitat+",hence it is"+"\t"+type); } }
304
0.684211
0.684211
20
14.2
20.689611
91
false
false
0
0
0
0
0
0
0.7
false
false
12
f9278a0611b8413f4f839c4c767cddff3aed9b7b
9,380,208,596,750
1007f7464ea3e2d516fae5333eee858e74fc1c89
/TEST2/src/view/NewJFrame.java
697bc8c89021f003d7953dd48b643a3d8605ac8a
[]
no_license
dangdinhvu221/Java3
https://github.com/dangdinhvu221/Java3
eeda58093f0745430c5fbf280583698dfc8acaa6
ae7a974d5613c887119b838661bb16499465aebd
refs/heads/master
2023-07-14T03:06:52.875000
2021-08-23T04:37:51
2021-08-23T04:37:51
391,115,348
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package view; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import javax.swing.JOptionPane; import javax.swing.table.DefaultTableModel; import modal.Sach; import modal.danhMuc; import service.SachDao; import service.danhMucDao; /** * * @author dangd */ public class NewJFrame extends javax.swing.JFrame { List<danhMuc> listDM; List<Sach> listS; SachDao sachDao; danhMucDao mucDao; DefaultTableModel tblModal; int index = 0; /** * Creates new form NewJFrame */ public NewJFrame() { initComponents(); setLocationRelativeTo(null); listS = new ArrayList<>(); listDM = new ArrayList<>(); sachDao = new SachDao(); mucDao = new danhMucDao(); tblModal = (DefaultTableModel) tblShow.getModel(); loadCBO(); } public void loadCBO() { try { listDM = mucDao.getAll(); cboDanhMuc.removeAllItems(); for (danhMuc muc : listDM) { cboDanhMuc.addItem(muc.getTenDanhMuc()); } } catch (Exception e) { e.printStackTrace(); } } public void fillTable(int id) { try { tblModal.setRowCount(0); listS = sachDao.getAll(id); for (Sach s : listS) { tblModal.addRow(new Object[]{s.getMaS(), s.getTenS(), s.getNgayNh(), s.getSoL()}); } tblModal.fireTableDataChanged(); } catch (Exception e) { e.printStackTrace(); } } public boolean checkTRung(String maS) { for (int i = 0; i < listS.size(); i++) { if (listS.get(i).getMaS().equalsIgnoreCase(maS)) { return true; } } return false; } public void mouseClick() { index = tblShow.getSelectedRow(); String row1 = tblShow.getValueAt(index, 0).toString(); String row2 = tblShow.getValueAt(index, 1).toString(); String row3 = tblShow.getValueAt(index, 2).toString(); String row4 = tblShow.getValueAt(index, 3).toString(); txtMaS.setText(row1); txtTenS.setText(row2); txtNgayNh.setText(row3); txtSoL.setText(row4); } public void them() { if (checkTRung(txtMaS.getText()) == true) { JOptionPane.showMessageDialog(this, "trùng mà!!!"); return; } if (txtMaS.getText().isEmpty() || txtTenS.getText().isEmpty() || txtNgayNh.getText().isEmpty() || txtSoL.getText().isEmpty()) { JOptionPane.showMessageDialog(this, "không được để trống"); return; } try { Date ngayNh = null; Sach s = new Sach(); s.setMaS(txtMaS.getText()); s.setTenS(txtMaS.getText()); try { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); ngayNh = sdf.parse(txtNgayNh.getText()); } catch (Exception e) { e.printStackTrace(); JOptionPane.showMessageDialog(this, "ngày nhập ko đúng định dạng!!!"); } s.setNgayNh(ngayNh); s.setSoL(Integer.parseInt(txtSoL.getText())); s.setDanhMucID(cboDanhMuc.getSelectedIndex() + 1); sachDao.insert(s); JOptionPane.showMessageDialog(this, "them thanh cong!!!"); lamMoi(); } catch (Exception e) { e.printStackTrace(); JOptionPane.showMessageDialog(this, "them ko thanh cong!!!"); } } public void sua() { if (txtMaS.getText().isEmpty() || txtTenS.getText().isEmpty() || txtNgayNh.getText().isEmpty() || txtSoL.getText().isEmpty()) { JOptionPane.showMessageDialog(this, "không được để trống"); return; } try { Date ngayNh = null; index = tblShow.getSelectedRow(); Sach s = listS.get(index); s.setMaS(txtMaS.getText()); s.setTenS(txtMaS.getText()); try { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); ngayNh = sdf.parse(txtNgayNh.getText()); } catch (Exception e) { e.printStackTrace(); JOptionPane.showMessageDialog(this, "ngày nhập ko đúng định dạng!!!"); } s.setNgayNh(ngayNh); s.setSoL(Integer.parseInt(txtSoL.getText())); if (sachDao.update(s) == 0) { JOptionPane.showMessageDialog(this, "sua thanh cong!!!"); lamMoi(); } } catch (Exception e) { e.printStackTrace(); JOptionPane.showMessageDialog(this, "sua ko thanh cong!!!"); } } public void xoa() { if (txtMaS.getText().isEmpty()) { JOptionPane.showMessageDialog(this, "không được để trống"); return; } try { index = tblShow.getSelectedRow(); Sach s = listS.get(index); int id = s.getId(); if (sachDao.delete(id) == 0) { JOptionPane.showMessageDialog(this, "xoa thanh cong!!!"); lamMoi(); } } catch (Exception e) { e.printStackTrace(); JOptionPane.showMessageDialog(this, "xoa ko thanh cong!!!"); } } public void lamMoi() { txtMaS.setText(""); txtTenS.setText(""); txtNgayNh.setText(""); txtSoL.setText(""); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { cboDanhMuc = new javax.swing.JComboBox<>(); lblDanhMuc = new javax.swing.JLabel(); jPanel1 = new javax.swing.JPanel(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); txtTenS = new javax.swing.JTextField(); txtMaS = new javax.swing.JTextField(); txtNgayNh = new javax.swing.JTextField(); txtSoL = new javax.swing.JTextField(); jButton1 = new javax.swing.JButton(); jButton2 = new javax.swing.JButton(); jButton3 = new javax.swing.JButton(); jButton4 = new javax.swing.JButton(); jScrollPane1 = new javax.swing.JScrollPane(); tblShow = new javax.swing.JTable(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); cboDanhMuc.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" })); cboDanhMuc.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cboDanhMucActionPerformed(evt); } }); lblDanhMuc.setText("jLabel1"); jLabel2.setText("Tên sách:"); jLabel3.setText("mã Sách:"); jLabel4.setText("ngày Nhập"); jLabel5.setText("số Lượng:"); jButton1.setText("thêm"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); jButton2.setText("sửa"); jButton2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton2ActionPerformed(evt); } }); jButton3.setText("xoá"); jButton3.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton3ActionPerformed(evt); } }); jButton4.setText("clear"); jButton4.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton4ActionPerformed(evt); } }); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(45, 45, 45) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabel3) .addGap(18, 18, 18) .addComponent(txtMaS, javax.swing.GroupLayout.DEFAULT_SIZE, 181, Short.MAX_VALUE) .addGap(25, 25, 25) .addComponent(jLabel5)) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabel2) .addGap(18, 18, 18) .addComponent(txtTenS) .addGap(18, 18, 18) .addComponent(jLabel4))) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(22, 22, 22) .addComponent(txtNgayNh, javax.swing.GroupLayout.DEFAULT_SIZE, 181, Short.MAX_VALUE)) .addGroup(jPanel1Layout.createSequentialGroup() .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jButton4) .addGap(0, 0, Short.MAX_VALUE)) .addComponent(txtSoL, javax.swing.GroupLayout.DEFAULT_SIZE, 199, Short.MAX_VALUE)))) .addContainerGap()) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(28, 28, 28) .addComponent(jButton1) .addGap(34, 34, 34) .addComponent(jButton2) .addGap(60, 60, 60) .addComponent(jButton3) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(27, 27, 27) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel2) .addComponent(jLabel4) .addComponent(txtTenS, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(txtNgayNh, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(36, 36, 36) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel3) .addComponent(jLabel5) .addComponent(txtMaS, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(txtSoL, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 49, Short.MAX_VALUE) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jButton1) .addComponent(jButton2) .addComponent(jButton3) .addComponent(jButton4)) .addGap(31, 31, 31)) ); tblShow.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { }, new String [] { "Title 1", "Title 2", "Title 3", "Title 4" } ) { boolean[] canEdit = new boolean [] { false, false, false, false }; public boolean isCellEditable(int rowIndex, int columnIndex) { return canEdit [columnIndex]; } }); tblShow.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { tblShowMouseClicked(evt); } }); jScrollPane1.setViewportView(tblShow); 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(53, 53, 53) .addComponent(cboDanhMuc, javax.swing.GroupLayout.PREFERRED_SIZE, 161, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(126, 126, 126) .addComponent(lblDanhMuc)) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addGap(26, 26, 26) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 542, 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(29, 29, 29) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(cboDanhMuc, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(lblDanhMuc)) .addGap(18, 18, 18) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 54, Short.MAX_VALUE) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 168, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(27, 27, 27)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void cboDanhMucActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cboDanhMucActionPerformed // TODO add your handling code here: index = cboDanhMuc.getSelectedIndex(); fillTable(index + 1); }//GEN-LAST:event_cboDanhMucActionPerformed private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed // TODO add your handling code here: them(); }//GEN-LAST:event_jButton1ActionPerformed private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed sua(); // TODO add your handling code here: }//GEN-LAST:event_jButton2ActionPerformed private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed xoa(); // TODO add your handling code here: }//GEN-LAST:event_jButton3ActionPerformed private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed lamMoi(); // TODO add your handling code here: }//GEN-LAST:event_jButton4ActionPerformed private void tblShowMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tblShowMouseClicked // TODO add your handling code here: mouseClick(); }//GEN-LAST:event_tblShowMouseClicked /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new NewJFrame().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JComboBox<String> cboDanhMuc; private javax.swing.JButton jButton1; private javax.swing.JButton jButton2; private javax.swing.JButton jButton3; private javax.swing.JButton jButton4; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JPanel jPanel1; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JLabel lblDanhMuc; private javax.swing.JTable tblShow; private javax.swing.JTextField txtMaS; private javax.swing.JTextField txtNgayNh; private javax.swing.JTextField txtSoL; private javax.swing.JTextField txtTenS; // End of variables declaration//GEN-END:variables }
UTF-8
Java
20,195
java
NewJFrame.java
Java
[ { "context": "Dao;\nimport service.danhMucDao;\n\n/**\n *\n * @author dangd\n */\npublic class NewJFrame extends javax.swing.JF", "end": 501, "score": 0.9996048808097839, "start": 496, "tag": "USERNAME", "value": "dangd" } ]
null
[]
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package view; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import javax.swing.JOptionPane; import javax.swing.table.DefaultTableModel; import modal.Sach; import modal.danhMuc; import service.SachDao; import service.danhMucDao; /** * * @author dangd */ public class NewJFrame extends javax.swing.JFrame { List<danhMuc> listDM; List<Sach> listS; SachDao sachDao; danhMucDao mucDao; DefaultTableModel tblModal; int index = 0; /** * Creates new form NewJFrame */ public NewJFrame() { initComponents(); setLocationRelativeTo(null); listS = new ArrayList<>(); listDM = new ArrayList<>(); sachDao = new SachDao(); mucDao = new danhMucDao(); tblModal = (DefaultTableModel) tblShow.getModel(); loadCBO(); } public void loadCBO() { try { listDM = mucDao.getAll(); cboDanhMuc.removeAllItems(); for (danhMuc muc : listDM) { cboDanhMuc.addItem(muc.getTenDanhMuc()); } } catch (Exception e) { e.printStackTrace(); } } public void fillTable(int id) { try { tblModal.setRowCount(0); listS = sachDao.getAll(id); for (Sach s : listS) { tblModal.addRow(new Object[]{s.getMaS(), s.getTenS(), s.getNgayNh(), s.getSoL()}); } tblModal.fireTableDataChanged(); } catch (Exception e) { e.printStackTrace(); } } public boolean checkTRung(String maS) { for (int i = 0; i < listS.size(); i++) { if (listS.get(i).getMaS().equalsIgnoreCase(maS)) { return true; } } return false; } public void mouseClick() { index = tblShow.getSelectedRow(); String row1 = tblShow.getValueAt(index, 0).toString(); String row2 = tblShow.getValueAt(index, 1).toString(); String row3 = tblShow.getValueAt(index, 2).toString(); String row4 = tblShow.getValueAt(index, 3).toString(); txtMaS.setText(row1); txtTenS.setText(row2); txtNgayNh.setText(row3); txtSoL.setText(row4); } public void them() { if (checkTRung(txtMaS.getText()) == true) { JOptionPane.showMessageDialog(this, "trùng mà!!!"); return; } if (txtMaS.getText().isEmpty() || txtTenS.getText().isEmpty() || txtNgayNh.getText().isEmpty() || txtSoL.getText().isEmpty()) { JOptionPane.showMessageDialog(this, "không được để trống"); return; } try { Date ngayNh = null; Sach s = new Sach(); s.setMaS(txtMaS.getText()); s.setTenS(txtMaS.getText()); try { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); ngayNh = sdf.parse(txtNgayNh.getText()); } catch (Exception e) { e.printStackTrace(); JOptionPane.showMessageDialog(this, "ngày nhập ko đúng định dạng!!!"); } s.setNgayNh(ngayNh); s.setSoL(Integer.parseInt(txtSoL.getText())); s.setDanhMucID(cboDanhMuc.getSelectedIndex() + 1); sachDao.insert(s); JOptionPane.showMessageDialog(this, "them thanh cong!!!"); lamMoi(); } catch (Exception e) { e.printStackTrace(); JOptionPane.showMessageDialog(this, "them ko thanh cong!!!"); } } public void sua() { if (txtMaS.getText().isEmpty() || txtTenS.getText().isEmpty() || txtNgayNh.getText().isEmpty() || txtSoL.getText().isEmpty()) { JOptionPane.showMessageDialog(this, "không được để trống"); return; } try { Date ngayNh = null; index = tblShow.getSelectedRow(); Sach s = listS.get(index); s.setMaS(txtMaS.getText()); s.setTenS(txtMaS.getText()); try { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); ngayNh = sdf.parse(txtNgayNh.getText()); } catch (Exception e) { e.printStackTrace(); JOptionPane.showMessageDialog(this, "ngày nhập ko đúng định dạng!!!"); } s.setNgayNh(ngayNh); s.setSoL(Integer.parseInt(txtSoL.getText())); if (sachDao.update(s) == 0) { JOptionPane.showMessageDialog(this, "sua thanh cong!!!"); lamMoi(); } } catch (Exception e) { e.printStackTrace(); JOptionPane.showMessageDialog(this, "sua ko thanh cong!!!"); } } public void xoa() { if (txtMaS.getText().isEmpty()) { JOptionPane.showMessageDialog(this, "không được để trống"); return; } try { index = tblShow.getSelectedRow(); Sach s = listS.get(index); int id = s.getId(); if (sachDao.delete(id) == 0) { JOptionPane.showMessageDialog(this, "xoa thanh cong!!!"); lamMoi(); } } catch (Exception e) { e.printStackTrace(); JOptionPane.showMessageDialog(this, "xoa ko thanh cong!!!"); } } public void lamMoi() { txtMaS.setText(""); txtTenS.setText(""); txtNgayNh.setText(""); txtSoL.setText(""); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { cboDanhMuc = new javax.swing.JComboBox<>(); lblDanhMuc = new javax.swing.JLabel(); jPanel1 = new javax.swing.JPanel(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); txtTenS = new javax.swing.JTextField(); txtMaS = new javax.swing.JTextField(); txtNgayNh = new javax.swing.JTextField(); txtSoL = new javax.swing.JTextField(); jButton1 = new javax.swing.JButton(); jButton2 = new javax.swing.JButton(); jButton3 = new javax.swing.JButton(); jButton4 = new javax.swing.JButton(); jScrollPane1 = new javax.swing.JScrollPane(); tblShow = new javax.swing.JTable(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); cboDanhMuc.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" })); cboDanhMuc.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cboDanhMucActionPerformed(evt); } }); lblDanhMuc.setText("jLabel1"); jLabel2.setText("Tên sách:"); jLabel3.setText("mã Sách:"); jLabel4.setText("ngày Nhập"); jLabel5.setText("số Lượng:"); jButton1.setText("thêm"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); jButton2.setText("sửa"); jButton2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton2ActionPerformed(evt); } }); jButton3.setText("xoá"); jButton3.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton3ActionPerformed(evt); } }); jButton4.setText("clear"); jButton4.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton4ActionPerformed(evt); } }); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(45, 45, 45) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabel3) .addGap(18, 18, 18) .addComponent(txtMaS, javax.swing.GroupLayout.DEFAULT_SIZE, 181, Short.MAX_VALUE) .addGap(25, 25, 25) .addComponent(jLabel5)) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabel2) .addGap(18, 18, 18) .addComponent(txtTenS) .addGap(18, 18, 18) .addComponent(jLabel4))) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(22, 22, 22) .addComponent(txtNgayNh, javax.swing.GroupLayout.DEFAULT_SIZE, 181, Short.MAX_VALUE)) .addGroup(jPanel1Layout.createSequentialGroup() .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jButton4) .addGap(0, 0, Short.MAX_VALUE)) .addComponent(txtSoL, javax.swing.GroupLayout.DEFAULT_SIZE, 199, Short.MAX_VALUE)))) .addContainerGap()) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(28, 28, 28) .addComponent(jButton1) .addGap(34, 34, 34) .addComponent(jButton2) .addGap(60, 60, 60) .addComponent(jButton3) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(27, 27, 27) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel2) .addComponent(jLabel4) .addComponent(txtTenS, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(txtNgayNh, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(36, 36, 36) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel3) .addComponent(jLabel5) .addComponent(txtMaS, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(txtSoL, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 49, Short.MAX_VALUE) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jButton1) .addComponent(jButton2) .addComponent(jButton3) .addComponent(jButton4)) .addGap(31, 31, 31)) ); tblShow.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { }, new String [] { "Title 1", "Title 2", "Title 3", "Title 4" } ) { boolean[] canEdit = new boolean [] { false, false, false, false }; public boolean isCellEditable(int rowIndex, int columnIndex) { return canEdit [columnIndex]; } }); tblShow.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { tblShowMouseClicked(evt); } }); jScrollPane1.setViewportView(tblShow); 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(53, 53, 53) .addComponent(cboDanhMuc, javax.swing.GroupLayout.PREFERRED_SIZE, 161, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(126, 126, 126) .addComponent(lblDanhMuc)) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addGap(26, 26, 26) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 542, 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(29, 29, 29) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(cboDanhMuc, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(lblDanhMuc)) .addGap(18, 18, 18) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 54, Short.MAX_VALUE) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 168, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(27, 27, 27)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void cboDanhMucActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cboDanhMucActionPerformed // TODO add your handling code here: index = cboDanhMuc.getSelectedIndex(); fillTable(index + 1); }//GEN-LAST:event_cboDanhMucActionPerformed private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed // TODO add your handling code here: them(); }//GEN-LAST:event_jButton1ActionPerformed private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed sua(); // TODO add your handling code here: }//GEN-LAST:event_jButton2ActionPerformed private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed xoa(); // TODO add your handling code here: }//GEN-LAST:event_jButton3ActionPerformed private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed lamMoi(); // TODO add your handling code here: }//GEN-LAST:event_jButton4ActionPerformed private void tblShowMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tblShowMouseClicked // TODO add your handling code here: mouseClick(); }//GEN-LAST:event_tblShowMouseClicked /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new NewJFrame().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JComboBox<String> cboDanhMuc; private javax.swing.JButton jButton1; private javax.swing.JButton jButton2; private javax.swing.JButton jButton3; private javax.swing.JButton jButton4; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JPanel jPanel1; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JLabel lblDanhMuc; private javax.swing.JTable tblShow; private javax.swing.JTextField txtMaS; private javax.swing.JTextField txtNgayNh; private javax.swing.JTextField txtSoL; private javax.swing.JTextField txtTenS; // End of variables declaration//GEN-END:variables }
20,195
0.591395
0.578129
465
42.283871
32.750427
165
false
false
0
0
0
0
0
0
0.686022
false
false
12
4d1ae1235bd4b6b0f0087a3f0ff2dcc321b10ed4
15,324,443,329,534
965f2d09c6e5bc6f8886e6c446d15ee22253083a
/app/src/main/java/es/dprimenko/redsocial/Repository.java
4740bf1e4970d38ac364af030baf2ccea56e4518
[]
no_license
dprimenko/ExamenRedSocial
https://github.com/dprimenko/ExamenRedSocial
73aa3921c91760ce2da9107e9a4cd6fd5ef6521c
263e3e635732f97558473f21bb51f56d113a79b5
refs/heads/master
2021-01-09T05:46:39.222000
2017-02-03T13:25:54
2017-02-03T13:25:54
80,831,192
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package es.dprimenko.redsocial; import java.util.ArrayList; import java.util.List; import es.dprimenko.redsocial.models.User; /** * Created by dprimenko on 3/02/17. */ public class Repository { public static final String FACEBOOK = "facebook"; public static final String GMAIL = "gmail"; public static final String TWITTER = "twitter"; private List<User> users; private List<User> tempFriendsGmail; private List<User> tempFriendsFacebook; private List<User> tempFriendsTwitter; private User userSelected; private static Repository ourInstance = new Repository(); public static Repository getInstance() { return ourInstance; } private Repository() { users = new ArrayList<>(); tempFriendsGmail = new ArrayList<>(); tempFriendsFacebook = new ArrayList<>(); tempFriendsTwitter = new ArrayList<>(); tempFriendsGmail.add(new User("gbartolocano", "test", "bartolobano@gmail.com", new ArrayList<User>(), GMAIL)); tempFriendsGmail.add(new User("gdavidprimenko", "test", "davidprimenko@gmail.com", new ArrayList<User>(), GMAIL)); tempFriendsGmail.add(new User("dprimenko", "test", "dprimenkoo@gmail.com", new ArrayList<User>(), GMAIL)); tempFriendsGmail.add(new User("auser", "test", "user@gmail.com", new ArrayList<User>(), GMAIL)); tempFriendsFacebook.add(new User("fcarloscano", "test", "fcarloscano@gmail.com", new ArrayList<User>(), FACEBOOK)); tempFriendsFacebook.add(new User("barroso", "test", "barroso@gmail.com", new ArrayList<User>(), FACEBOOK)); tempFriendsFacebook.add(new User("amaria", "test", "maria@gmail.com", new ArrayList<User>(), FACEBOOK)); tempFriendsFacebook.add(new User("fjavieraranda", "test", "javi@gmail.com", new ArrayList<User>(), FACEBOOK)); tempFriendsTwitter.add(new User("tdaviddado", "test", "tdaviddado@gmail.com", new ArrayList<User>(), TWITTER)); tempFriendsTwitter.add(new User("tjesus", "test", "jesus@gmail.com", new ArrayList<User>(), TWITTER)); tempFriendsTwitter.add(new User("agp", "test", "agp@gmail.com", new ArrayList<User>(), TWITTER)); addUser(new User("usuariog", "gmail", "usuariog@gmail.com", tempFriendsGmail, GMAIL)); addUser(new User("usuariof", "face", "usuariof@gmail.com", tempFriendsFacebook, FACEBOOK)); addUser(new User("usuariot", "twit", "usuariot@gmail.com", tempFriendsTwitter, TWITTER)); } public void addUser(User user) { users.add(user); } public void addFriendToUser(User newFriend) { users.get(users.indexOf(userSelected)).getmFriends().add(newFriend); } public boolean friendExists(String email) { boolean result = false; for (User user:userSelected.getmFriends()) { if (email.equals(user.getmEmail())) { result = true; } } return result; } public User getUserSelected() { return userSelected; } public boolean login(String cuenta, String username, String password) { boolean result = false; for (User user:users) { if (user.getmUsername().equals(username) && user.getmPassword().equals(password) && user.getmAccount().equals(cuenta)) { userSelected = user; result = true; } } return result; } public List<User> getUsers() { return users; } }
UTF-8
Java
3,476
java
Repository.java
Java
[ { "context": "primenko.redsocial.models.User;\n\n/**\n * Created by dprimenko on 3/02/17.\n */\npublic class Repository {\n\n pu", "end": 156, "score": 0.9997147917747498, "start": 147, "tag": "USERNAME", "value": "dprimenko" }, { "context": "List<>();\n\n tempFriendsGmail.add(new User(\"gbartolocano\", \"test\", \"bartolobano@gmail.com\", new ArrayList<", "end": 945, "score": 0.9997093081474304, "start": 933, "tag": "USERNAME", "value": "gbartolocano" }, { "context": "riendsGmail.add(new User(\"gbartolocano\", \"test\", \"bartolobano@gmail.com\", new ArrayList<User>(), GMAIL));\n tempFri", "end": 978, "score": 0.9999270439147949, "start": 957, "tag": "EMAIL", "value": "bartolobano@gmail.com" }, { "context": ", GMAIL));\n tempFriendsGmail.add(new User(\"gdavidprimenko\", \"test\", \"davidprimenko@gmail.com\", new ArrayLis", "end": 1066, "score": 0.9997139573097229, "start": 1052, "tag": "USERNAME", "value": "gdavidprimenko" }, { "context": "endsGmail.add(new User(\"gdavidprimenko\", \"test\", \"davidprimenko@gmail.com\", new ArrayList<User>(), GMAIL));\n tempFri", "end": 1101, "score": 0.9999227523803711, "start": 1078, "tag": "EMAIL", "value": "davidprimenko@gmail.com" }, { "context": ", GMAIL));\n tempFriendsGmail.add(new User(\"dprimenko\", \"test\", \"dprimenkoo@gmail.com\", new ArrayList<U", "end": 1184, "score": 0.9997091293334961, "start": 1175, "tag": "USERNAME", "value": "dprimenko" }, { "context": "mpFriendsGmail.add(new User(\"dprimenko\", \"test\", \"dprimenkoo@gmail.com\", new ArrayList<User>(), GMAIL));\n tempFri", "end": 1216, "score": 0.9999236464500427, "start": 1196, "tag": "EMAIL", "value": "dprimenkoo@gmail.com" }, { "context": ", GMAIL));\n tempFriendsGmail.add(new User(\"auser\", \"test\", \"user@gmail.com\", new ArrayList<User>()", "end": 1295, "score": 0.999717116355896, "start": 1290, "tag": "USERNAME", "value": "auser" }, { "context": " tempFriendsGmail.add(new User(\"auser\", \"test\", \"user@gmail.com\", new ArrayList<User>(), GMAIL));\n\n tempFr", "end": 1321, "score": 0.9999264478683472, "start": 1307, "tag": "EMAIL", "value": "user@gmail.com" }, { "context": "AIL));\n\n tempFriendsFacebook.add(new User(\"fcarloscano\", \"test\", \"fcarloscano@gmail.com\", new ArrayList<", "end": 1410, "score": 0.9997066259384155, "start": 1399, "tag": "USERNAME", "value": "fcarloscano" }, { "context": "endsFacebook.add(new User(\"fcarloscano\", \"test\", \"fcarloscano@gmail.com\", new ArrayList<User>(), FACEBOOK));\n temp", "end": 1443, "score": 0.9999262690544128, "start": 1422, "tag": "EMAIL", "value": "fcarloscano@gmail.com" }, { "context": "BOOK));\n tempFriendsFacebook.add(new User(\"barroso\", \"test\", \"barroso@gmail.com\", new ArrayList<User", "end": 1530, "score": 0.9997096657752991, "start": 1523, "tag": "USERNAME", "value": "barroso" }, { "context": "pFriendsFacebook.add(new User(\"barroso\", \"test\", \"barroso@gmail.com\", new ArrayList<User>(), FACEBOOK));\n temp", "end": 1559, "score": 0.999927818775177, "start": 1542, "tag": "EMAIL", "value": "barroso@gmail.com" }, { "context": "BOOK));\n tempFriendsFacebook.add(new User(\"amaria\", \"test\", \"maria@gmail.com\", new ArrayList<User>(", "end": 1645, "score": 0.9997129440307617, "start": 1639, "tag": "USERNAME", "value": "amaria" }, { "context": "mpFriendsFacebook.add(new User(\"amaria\", \"test\", \"maria@gmail.com\", new ArrayList<User>(), FACEBOOK));\n temp", "end": 1672, "score": 0.9999263286590576, "start": 1657, "tag": "EMAIL", "value": "maria@gmail.com" }, { "context": "BOOK));\n tempFriendsFacebook.add(new User(\"fjavieraranda\", \"test\", \"javi@gmail.com\", new ArrayList<User>()", "end": 1765, "score": 0.9997190237045288, "start": 1752, "tag": "USERNAME", "value": "fjavieraranda" }, { "context": "dsFacebook.add(new User(\"fjavieraranda\", \"test\", \"javi@gmail.com\", new ArrayList<User>(), FACEBOOK));\n\n tem", "end": 1791, "score": 0.9999262690544128, "start": 1777, "tag": "EMAIL", "value": "javi@gmail.com" }, { "context": "BOOK));\n\n tempFriendsTwitter.add(new User(\"tdaviddado\", \"test\", \"tdaviddado@gmail.com\", new ArrayList<U", "end": 1881, "score": 0.9997233748435974, "start": 1871, "tag": "USERNAME", "value": "tdaviddado" }, { "context": "riendsTwitter.add(new User(\"tdaviddado\", \"test\", \"tdaviddado@gmail.com\", new ArrayList<User>(), TWITTER));\n", "end": 1900, "score": 0.9990230202674866, "start": 1893, "tag": "USERNAME", "value": "tdavidd" }, { "context": "witter.add(new User(\"tdaviddado\", \"test\", \"tdaviddado@gmail.com\", new ArrayList<User>(), TWITTER));\n tempF", "end": 1913, "score": 0.9999327659606934, "start": 1900, "tag": "EMAIL", "value": "ado@gmail.com" }, { "context": "ITTER));\n tempFriendsTwitter.add(new User(\"tjesus\", \"test\", \"jesus@gmail.com\", new ArrayList<User>(", "end": 1997, "score": 0.9996810555458069, "start": 1991, "tag": "USERNAME", "value": "tjesus" }, { "context": "empFriendsTwitter.add(new User(\"tjesus\", \"test\", \"jesus@gmail.com\", new ArrayList<User>(), TWITTER));\n tempF", "end": 2024, "score": 0.9999246597290039, "start": 2009, "tag": "EMAIL", "value": "jesus@gmail.com" }, { "context": "ITTER));\n tempFriendsTwitter.add(new User(\"agp\", \"test\", \"agp@gmail.com\", new ArrayList<User>(),", "end": 2105, "score": 0.9996772408485413, "start": 2102, "tag": "USERNAME", "value": "agp" }, { "context": " tempFriendsTwitter.add(new User(\"agp\", \"test\", \"agp@gmail.com\", new ArrayList<User>(), TWITTER));\n\n addU", "end": 2130, "score": 0.9999246001243591, "start": 2117, "tag": "EMAIL", "value": "agp@gmail.com" }, { "context": "st<User>(), TWITTER));\n\n addUser(new User(\"usuariog\", \"gmail\", \"usuariog@gmail.com\", tempFriendsGmail", "end": 2202, "score": 0.9995918869972229, "start": 2194, "tag": "USERNAME", "value": "usuariog" }, { "context": ";\n\n addUser(new User(\"usuariog\", \"gmail\", \"usuariog@gmail.com\", tempFriendsGmail, GMAIL));\n addUser(new ", "end": 2233, "score": 0.9999258518218994, "start": 2215, "tag": "EMAIL", "value": "usuariog@gmail.com" }, { "context": "pFriendsGmail, GMAIL));\n addUser(new User(\"usuariof\", \"face\", \"usuariof@gmail.com\", tempFriendsFacebo", "end": 2297, "score": 0.9996273517608643, "start": 2289, "tag": "USERNAME", "value": "usuariof" }, { "context": "));\n addUser(new User(\"usuariof\", \"face\", \"usuariof@gmail.com\", tempFriendsFacebook, FACEBOOK));\n addUse", "end": 2327, "score": 0.9999235272407532, "start": 2309, "tag": "EMAIL", "value": "usuariof@gmail.com" }, { "context": "dsFacebook, FACEBOOK));\n addUser(new User(\"usuariot\", \"twit\", \"usuariot@gmail.com\", tempFriendsTwitte", "end": 2397, "score": 0.9996607899665833, "start": 2389, "tag": "USERNAME", "value": "usuariot" }, { "context": "FACEBOOK));\n addUser(new User(\"usuariot\", \"twit\", \"usuariot@gmail.com\", tempFriendsTwitter, TWITT", "end": 2405, "score": 0.9209163188934326, "start": 2401, "tag": "USERNAME", "value": "twit" }, { "context": "));\n addUser(new User(\"usuariot\", \"twit\", \"usuariot@gmail.com\", tempFriendsTwitter, TWITTER));\n }\n\n publi", "end": 2427, "score": 0.9999271035194397, "start": 2409, "tag": "EMAIL", "value": "usuariot@gmail.com" }, { "context": "ers) {\n if (user.getmUsername().equals(username) && user.getmPassword().equals(password) && user.", "end": 3206, "score": 0.9572774767875671, "start": 3198, "tag": "USERNAME", "value": "username" } ]
null
[]
package es.dprimenko.redsocial; import java.util.ArrayList; import java.util.List; import es.dprimenko.redsocial.models.User; /** * Created by dprimenko on 3/02/17. */ public class Repository { public static final String FACEBOOK = "facebook"; public static final String GMAIL = "gmail"; public static final String TWITTER = "twitter"; private List<User> users; private List<User> tempFriendsGmail; private List<User> tempFriendsFacebook; private List<User> tempFriendsTwitter; private User userSelected; private static Repository ourInstance = new Repository(); public static Repository getInstance() { return ourInstance; } private Repository() { users = new ArrayList<>(); tempFriendsGmail = new ArrayList<>(); tempFriendsFacebook = new ArrayList<>(); tempFriendsTwitter = new ArrayList<>(); tempFriendsGmail.add(new User("gbartolocano", "test", "<EMAIL>", new ArrayList<User>(), GMAIL)); tempFriendsGmail.add(new User("gdavidprimenko", "test", "<EMAIL>", new ArrayList<User>(), GMAIL)); tempFriendsGmail.add(new User("dprimenko", "test", "<EMAIL>", new ArrayList<User>(), GMAIL)); tempFriendsGmail.add(new User("auser", "test", "<EMAIL>", new ArrayList<User>(), GMAIL)); tempFriendsFacebook.add(new User("fcarloscano", "test", "<EMAIL>", new ArrayList<User>(), FACEBOOK)); tempFriendsFacebook.add(new User("barroso", "test", "<EMAIL>", new ArrayList<User>(), FACEBOOK)); tempFriendsFacebook.add(new User("amaria", "test", "<EMAIL>", new ArrayList<User>(), FACEBOOK)); tempFriendsFacebook.add(new User("fjavieraranda", "test", "<EMAIL>", new ArrayList<User>(), FACEBOOK)); tempFriendsTwitter.add(new User("tdaviddado", "test", "tdavidd<EMAIL>", new ArrayList<User>(), TWITTER)); tempFriendsTwitter.add(new User("tjesus", "test", "<EMAIL>", new ArrayList<User>(), TWITTER)); tempFriendsTwitter.add(new User("agp", "test", "<EMAIL>", new ArrayList<User>(), TWITTER)); addUser(new User("usuariog", "gmail", "<EMAIL>", tempFriendsGmail, GMAIL)); addUser(new User("usuariof", "face", "<EMAIL>", tempFriendsFacebook, FACEBOOK)); addUser(new User("usuariot", "twit", "<EMAIL>", tempFriendsTwitter, TWITTER)); } public void addUser(User user) { users.add(user); } public void addFriendToUser(User newFriend) { users.get(users.indexOf(userSelected)).getmFriends().add(newFriend); } public boolean friendExists(String email) { boolean result = false; for (User user:userSelected.getmFriends()) { if (email.equals(user.getmEmail())) { result = true; } } return result; } public User getUserSelected() { return userSelected; } public boolean login(String cuenta, String username, String password) { boolean result = false; for (User user:users) { if (user.getmUsername().equals(username) && user.getmPassword().equals(password) && user.getmAccount().equals(cuenta)) { userSelected = user; result = true; } } return result; } public List<User> getUsers() { return users; } }
3,334
0.645857
0.644419
95
35.589474
38.285217
132
false
false
0
0
0
0
0
0
1.063158
false
false
12
2f2f01f6ada5cddd3c7e0b4803eff4b7197707d0
16,080,357,580,803
bf7fd23dd294b8eac9755bfa3f7f6b0d0fd6e557
/mmsc/src/uk/co/mmscomputing/application/imageviewer/ImageTab.java
74bbbc0366d61ea69db89cccc473acd2dd99e4ee
[]
no_license
erickescalona/dw4j
https://github.com/erickescalona/dw4j
6a49f40170f8c3bec8a5094fd64df77f616dfa2a
8936ec9be697b00e2a5ef7fed837f4c824e61ef9
refs/heads/master
2021-09-14T17:31:14.868000
2018-04-09T14:20:38
2018-04-09T14:20:38
103,979,595
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package uk.co.mmscomputing.application.imageviewer; import java.awt.BorderLayout; import java.awt.GridLayout; import java.awt.Image; import java.awt.event.ActionEvent; import java.awt.image.BufferedImage; import java.awt.image.ColorModel; import java.awt.print.Book; import java.awt.print.PageFormat; import java.awt.print.Paper; import java.awt.print.PrinterJob; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.io.File; import java.io.IOException; import java.util.Iterator; import java.util.Properties; import javax.imageio.IIOImage; import javax.imageio.IIOParamController; import javax.imageio.ImageIO; import javax.imageio.ImageReader; import javax.imageio.ImageTypeSpecifier; import javax.imageio.ImageWriteParam; import javax.imageio.ImageWriter; import javax.imageio.metadata.IIOMetadata; import javax.imageio.stream.ImageInputStream; import javax.imageio.stream.ImageOutputStream; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JFileChooser; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTabbedPane; import uk.co.mmscomputing.util.JarImageIcon; //import uk.co.mmscomputing.imageio.*; import uk.co.mmscomputing.image.operators.*; public class ImageTab extends JPanel implements PropertyChangeListener { static public final String fileOpenID = "uk.co.mmscomputing.file.open.dir"; static public final String fileSaveID = "uk.co.mmscomputing.file.save.dir"; private static final long serialVersionUID = -6736685001902413098L; protected Properties properties; protected JTabbedPane images; protected JFileChooser openfc; protected JFileChooser savefc; public ImageTab(Properties properties) { this.properties = properties; setLayout(new BorderLayout()); JPanel p = new JPanel(); p.setLayout(new BorderLayout()); JPanel q = new JPanel(); q.setLayout(new BoxLayout(q, BoxLayout.PAGE_AXIS)); setButtonPanel(q); p.add(q, BorderLayout.NORTH); add(p, BorderLayout.EAST); images = new JTabbedPane(); add(images, BorderLayout.CENTER); String userdir = System.getProperty("user.home"); setOpenDir(properties.getProperty(fileOpenID, userdir)); setSaveDir(properties.getProperty(fileSaveID, userdir)); } public void setOpenDir(String path) { new File(path).mkdirs(); openfc = new JFileChooser(path); } public void setSaveDir(String path) { new File(path).mkdirs(); savefc = new JFileChooser(path); } protected void setButtonPanel(JPanel gui) { JPanel buttonPanel = new JPanel(); buttonPanel.setLayout(new GridLayout(0, 1)); buttonPanel.add(new JButton(getNewAction())); buttonPanel.add(new JButton(getOpenAction())); buttonPanel.add(new JButton(getSaveAction())); buttonPanel.add(new JButton(getPrintAction())); buttonPanel.add(new JButton(getConvertAction())); buttonPanel.add(new JButton(getRotateAction())); gui.add(buttonPanel); } public Action getNewAction() { return new AbstractAction("new", new JarImageIcon(getClass(), "32x32/new.png")) { private static final long serialVersionUID = 8711948053140429014L; @Override public void actionPerformed(ActionEvent ev) { images.removeAll(); } }; } public Action getOpenAction() { return new AbstractAction("open", new JarImageIcon(getClass(), "32x32/open.png")) { private static final long serialVersionUID = 8711948053140429014L; @Override public void actionPerformed(ActionEvent ev) { int res = openfc.showOpenDialog(null); properties.setProperty(fileOpenID, openfc.getCurrentDirectory().toString()); if (res == JFileChooser.APPROVE_OPTION) { try { open(openfc.getSelectedFile().getPath()); } catch (Exception e) { JOptionPane.showMessageDialog(null, "Image Open Error : " + e.getMessage(), "Exception", JOptionPane.ERROR_MESSAGE); } } } }; } public Action getSaveAction() { return new AbstractAction("save", new JarImageIcon(getClass(), "32x32/save.png")) { private static final long serialVersionUID = 8711948053140429014L; @Override public void actionPerformed(ActionEvent ev) { int res = savefc.showSaveDialog(null); properties.setProperty(fileSaveID, savefc.getCurrentDirectory().toString()); if (res == JFileChooser.APPROVE_OPTION) { new Thread() { @Override public void run() { try { save(savefc.getSelectedFile().getPath()); } catch (Exception e) { JOptionPane.showMessageDialog(null, "Image Save Error : " + e.getMessage(), "Exception", JOptionPane.ERROR_MESSAGE); } } }.start(); } } }; } public Action getPrintAction() { return new AbstractAction("", new JarImageIcon(getClass(), "32x32/print.png")) { private static final long serialVersionUID = 8711948053140429014L; @Override public void actionPerformed(ActionEvent ev) { new Thread() { @Override public void run() { Printer p = new Printer(); for (int i = 0; i < images.getTabCount(); i++) { JScrollPane sp = (JScrollPane) images.getComponentAt(i); ImagePanel ip = (ImagePanel) sp.getViewport().getView(); p.append(ip); } p.print(); } }.start(); } }; } public Action getConvertAction() { return new AbstractAction("<html><center><b>Colour</b><br><b>Reduction</b></center></html>"/*,new JarImageIcon(getClass(),"32x32/blackWhite.png")*/) { private static final long serialVersionUID = 4377386270269629176L; @Override public void actionPerformed(ActionEvent ev) { convertImage(); } }; } public Action getRotateAction() { return new AbstractAction("", new JarImageIcon(getClass(), "32x32/rotate.png")) { private static final long serialVersionUID = 8711948053140429014L; @Override public void actionPerformed(ActionEvent ev) { JScrollPane sp = (JScrollPane) images.getSelectedComponent(); if (sp != null) { ImagePanel ip = (ImagePanel) sp.getViewport().getView(); ip.rotate(); } } }; } protected void addImage(String fn, BufferedImage img) { Object md = img.getProperty("iiometadata"); if ((md != Image.UndefinedProperty) && (md != null) && (md instanceof IIOMetadata)) { // new MetadataReader().read((IIOMetadata)md); } System.out.println("Image.Width =" + img.getWidth()); System.out.println("Image.Height =" + img.getHeight()); ImagePanel ip = new ImagePanel(); ip.addPropertyChangeListener(this); JScrollPane sp = new JScrollPane(ip); sp.getVerticalScrollBar().setUnitIncrement(100); sp.getHorizontalScrollBar().setUnitIncrement(100); ip.setImage(img); // images.addTab("image",sp); images.addTab(fn, new TabCloseIcon(), sp); images.setSelectedIndex(images.getTabCount() - 1); } public void open(String filename) throws IOException { long time = System.currentTimeMillis(); String ext = filename.substring(filename.lastIndexOf('.') + 1); Iterator readers = ImageIO.getImageReadersByFormatName(ext); if (!readers.hasNext()) { throw new IOException(getClass().getName() + ".open:\n\tNo reader for format '" + ext + "' available."); } ImageReader reader = (ImageReader) readers.next(); while (!reader.getClass().getName().startsWith("uk.co.mmscomputing") && readers.hasNext()) {// prefer our own reader reader = (ImageReader) readers.next(); } File f = new File(filename); ImageInputStream iis = ImageIO.createImageInputStream(f); try { reader.setInput(iis, true); try { for (int i = 0; true; i++) { IIOMetadata md = reader.getImageMetadata(i); // if(md!=null){new MetadataReader().read(md);} addImage(f.getName() + " " + i, reader.read(i)); } } catch (IndexOutOfBoundsException ioobe) { } } catch (Error e) { System.out.println("9\b" + getClass().getName() + ".open:\n\t" + e); e.printStackTrace(); throw e; } finally { iis.close(); } time = System.currentTimeMillis() - time; System.out.println("Opened : " + filename); System.out.println("Time used to load images : " + time); } private IIOImage getIIOImage(ImageWriter writer, ImageWriteParam iwp, BufferedImage image) { ImageTypeSpecifier it = ImageTypeSpecifier.createFromRenderedImage(image); /* try{ uk.co.mmscomputing.imageio.bmp.BMPMetadata md=(uk.co.mmscomputing.imageio.bmp.BMPMetadata)image.getProperty("iiometadata"); if(md!=null){ md.setXPixelsPerMeter(11812); // force 300 dpi for bmp images md.setYPixelsPerMeter(11812); // works only with mmsc.bmp package } }catch(Exception e){} */ IIOMetadata md; Object obj = image.getProperty("iiometadata"); // if image is a TwainBufferedImage get metadata if ((obj != null) && (obj instanceof IIOMetadata)) { md = (IIOMetadata) obj; } else { md = writer.getDefaultImageMetadata(it, iwp); } return new IIOImage(image, null, md); } public void save(String filename) throws IOException { if (images.getTabCount() <= 0) { throw new IOException(getClass().getName() + ".save:\n\tNo images available!"); } String ext = filename.substring(filename.lastIndexOf('.') + 1); Iterator writers = ImageIO.getImageWritersByFormatName(ext); if (!writers.hasNext()) { throw new IOException(getClass().getName() + ".save:\n\tNo writer for format '" + ext + "' available."); } ImageWriter writer = (ImageWriter) writers.next(); while (!writer.getClass().getName().startsWith("uk.co.mmscomputing") && writers.hasNext()) {// prefer our own writer writer = (ImageWriter) writers.next(); } ImageWriteParam iwp = writer.getDefaultWriteParam(); IIOParamController controller = iwp.getController(); if (controller != null) { controller.activate(iwp); } long time = System.currentTimeMillis(); File file = new File(filename); if (file.exists()) { file.delete(); } ImageOutputStream ios = null; try { ios = ImageIO.createImageOutputStream(file); writer.setOutput(ios); if (writer.canWriteSequence()) { //i.e tiff,sff(fax) writer.prepareWriteSequence(null); for (int i = 0; i < images.getTabCount(); i++) { JScrollPane sp = (JScrollPane) images.getComponentAt(i); ImagePanel ip = (ImagePanel) sp.getViewport().getView(); writer.writeToSequence(getIIOImage(writer, iwp, ip.getImage()), iwp); } writer.endWriteSequence(); } else { JScrollPane sp = (JScrollPane) images.getComponentAt(0); ImagePanel ip = (ImagePanel) sp.getViewport().getView(); writer.write(null, getIIOImage(writer, iwp, ip.getImage()), iwp); for (int i = 1; i < images.getTabCount(); i++) { if (writer.canInsertImage(i)) { sp = (JScrollPane) images.getComponentAt(i); ip = (ImagePanel) sp.getViewport().getView(); writer.write(null, getIIOImage(writer, iwp, ip.getImage()), iwp); } else { throw new IOException("Image Writer cannot append image [" + i + "] (" + filename + ")"); } } } time = System.currentTimeMillis() - time; System.out.println("Saved : " + filename); System.out.println("3\bTime used to save images : " + time); } finally { if (ios != null) { ios.close(); } } } public void convertImage() { new Thread() { @Override public void run() { try { ImageTypeConvertOpPanel itcop = new ImageTypeConvertOpPanel(); ImageTypeConvertOp itco = itcop.activate(); if (itco != null) { for (int i = 0; i < images.getTabCount(); i++) { JScrollPane sp = (JScrollPane) images.getComponentAt(i); ImagePanel ip = (ImagePanel) sp.getViewport().getView(); BufferedImage image = itco.filter(ip.getImage()); ip.setImage(image); ip.revalidate(); ip.repaint(); String type = "Unknown Type"; switch (image.getType()) { case BufferedImage.TYPE_BYTE_BINARY: type = "Byte Binary"; break; case BufferedImage.TYPE_BYTE_INDEXED: type = "Byte Indexed"; break; } ColorModel cm = image.getColorModel(); System.out.println("9\bConverted Images to:\n\ntype: " + type + "\nbpp: " + cm.getPixelSize()); } } } catch (Exception e) { System.out.println("9\b" + getClass().getName() + ".convertImage:\n\t" + e); e.printStackTrace(); } } }.start(); } /* public void convertToBWImage(){ for(int i=0; i<images.getTabCount(); i++){ JScrollPane sp=(JScrollPane)images.getComponentAt(i); ImagePanel ip=(ImagePanel)sp.getViewport().getView(); BufferedImage original=ip.getImage(); BufferedImage image=new BufferedImage(original.getWidth(),original.getHeight(),BufferedImage.TYPE_BYTE_BINARY); Graphics2D g=image.createGraphics(); AffineTransform t=new AffineTransform(); g.drawRenderedImage(original,t); ip.setImage(image); ip.revalidate();ip.repaint(); } } */ @Override public void propertyChange(final PropertyChangeEvent evt) { /* String prop=evt.getPropertyName(); if(prop.equals("open")){ JTabbedPane tp=(JTabbedPane)getParent(); tp.setSelectedIndex(1); new Thread(){ public void run(){ try{ open((String)evt.getNewValue()); }catch(Exception e){ JOptionPane.showMessageDialog(null, "Image Open Error : "+e.getMessage(), "Exception", JOptionPane.ERROR_MESSAGE); } } }.start(); }else if(prop.equals("save")){ new Thread(){ public void run(){ try{ open((String)evt.getNewValue()); int res=savefc.showSaveDialog(null); if(res==JFileChooser.APPROVE_OPTION){ save(savefc.getSelectedFile().getPath()); } }catch(IOException ioe){ System.out.println("9\b"+ioe.getMessage()); } } }.start(); } */ } static private class Printer extends Thread { PrinterJob pj; PageFormat pf; Book bk; public Printer() { pj = PrinterJob.getPrinterJob(); pf = pj.defaultPage(); Paper p = pf.getPaper(); p.setImageableArea(0.0, 0.0, p.getWidth(), p.getHeight()); pf.setPaper(p); pf = pj.validatePage(pf); bk = new Book(); } public void append(ImagePanel image) { bk.append(image, pf); } public void print() { pj.setPageable(bk); if (pj.printDialog()) { try { pj.print(); } catch (Exception e) { e.printStackTrace(); System.out.println("9\b" + getClass().getName() + ".print:\n\t" + e.getMessage()); } } } } }
UTF-8
Java
17,734
java
ImageTab.java
Java
[]
null
[]
package uk.co.mmscomputing.application.imageviewer; import java.awt.BorderLayout; import java.awt.GridLayout; import java.awt.Image; import java.awt.event.ActionEvent; import java.awt.image.BufferedImage; import java.awt.image.ColorModel; import java.awt.print.Book; import java.awt.print.PageFormat; import java.awt.print.Paper; import java.awt.print.PrinterJob; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.io.File; import java.io.IOException; import java.util.Iterator; import java.util.Properties; import javax.imageio.IIOImage; import javax.imageio.IIOParamController; import javax.imageio.ImageIO; import javax.imageio.ImageReader; import javax.imageio.ImageTypeSpecifier; import javax.imageio.ImageWriteParam; import javax.imageio.ImageWriter; import javax.imageio.metadata.IIOMetadata; import javax.imageio.stream.ImageInputStream; import javax.imageio.stream.ImageOutputStream; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JFileChooser; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTabbedPane; import uk.co.mmscomputing.util.JarImageIcon; //import uk.co.mmscomputing.imageio.*; import uk.co.mmscomputing.image.operators.*; public class ImageTab extends JPanel implements PropertyChangeListener { static public final String fileOpenID = "uk.co.mmscomputing.file.open.dir"; static public final String fileSaveID = "uk.co.mmscomputing.file.save.dir"; private static final long serialVersionUID = -6736685001902413098L; protected Properties properties; protected JTabbedPane images; protected JFileChooser openfc; protected JFileChooser savefc; public ImageTab(Properties properties) { this.properties = properties; setLayout(new BorderLayout()); JPanel p = new JPanel(); p.setLayout(new BorderLayout()); JPanel q = new JPanel(); q.setLayout(new BoxLayout(q, BoxLayout.PAGE_AXIS)); setButtonPanel(q); p.add(q, BorderLayout.NORTH); add(p, BorderLayout.EAST); images = new JTabbedPane(); add(images, BorderLayout.CENTER); String userdir = System.getProperty("user.home"); setOpenDir(properties.getProperty(fileOpenID, userdir)); setSaveDir(properties.getProperty(fileSaveID, userdir)); } public void setOpenDir(String path) { new File(path).mkdirs(); openfc = new JFileChooser(path); } public void setSaveDir(String path) { new File(path).mkdirs(); savefc = new JFileChooser(path); } protected void setButtonPanel(JPanel gui) { JPanel buttonPanel = new JPanel(); buttonPanel.setLayout(new GridLayout(0, 1)); buttonPanel.add(new JButton(getNewAction())); buttonPanel.add(new JButton(getOpenAction())); buttonPanel.add(new JButton(getSaveAction())); buttonPanel.add(new JButton(getPrintAction())); buttonPanel.add(new JButton(getConvertAction())); buttonPanel.add(new JButton(getRotateAction())); gui.add(buttonPanel); } public Action getNewAction() { return new AbstractAction("new", new JarImageIcon(getClass(), "32x32/new.png")) { private static final long serialVersionUID = 8711948053140429014L; @Override public void actionPerformed(ActionEvent ev) { images.removeAll(); } }; } public Action getOpenAction() { return new AbstractAction("open", new JarImageIcon(getClass(), "32x32/open.png")) { private static final long serialVersionUID = 8711948053140429014L; @Override public void actionPerformed(ActionEvent ev) { int res = openfc.showOpenDialog(null); properties.setProperty(fileOpenID, openfc.getCurrentDirectory().toString()); if (res == JFileChooser.APPROVE_OPTION) { try { open(openfc.getSelectedFile().getPath()); } catch (Exception e) { JOptionPane.showMessageDialog(null, "Image Open Error : " + e.getMessage(), "Exception", JOptionPane.ERROR_MESSAGE); } } } }; } public Action getSaveAction() { return new AbstractAction("save", new JarImageIcon(getClass(), "32x32/save.png")) { private static final long serialVersionUID = 8711948053140429014L; @Override public void actionPerformed(ActionEvent ev) { int res = savefc.showSaveDialog(null); properties.setProperty(fileSaveID, savefc.getCurrentDirectory().toString()); if (res == JFileChooser.APPROVE_OPTION) { new Thread() { @Override public void run() { try { save(savefc.getSelectedFile().getPath()); } catch (Exception e) { JOptionPane.showMessageDialog(null, "Image Save Error : " + e.getMessage(), "Exception", JOptionPane.ERROR_MESSAGE); } } }.start(); } } }; } public Action getPrintAction() { return new AbstractAction("", new JarImageIcon(getClass(), "32x32/print.png")) { private static final long serialVersionUID = 8711948053140429014L; @Override public void actionPerformed(ActionEvent ev) { new Thread() { @Override public void run() { Printer p = new Printer(); for (int i = 0; i < images.getTabCount(); i++) { JScrollPane sp = (JScrollPane) images.getComponentAt(i); ImagePanel ip = (ImagePanel) sp.getViewport().getView(); p.append(ip); } p.print(); } }.start(); } }; } public Action getConvertAction() { return new AbstractAction("<html><center><b>Colour</b><br><b>Reduction</b></center></html>"/*,new JarImageIcon(getClass(),"32x32/blackWhite.png")*/) { private static final long serialVersionUID = 4377386270269629176L; @Override public void actionPerformed(ActionEvent ev) { convertImage(); } }; } public Action getRotateAction() { return new AbstractAction("", new JarImageIcon(getClass(), "32x32/rotate.png")) { private static final long serialVersionUID = 8711948053140429014L; @Override public void actionPerformed(ActionEvent ev) { JScrollPane sp = (JScrollPane) images.getSelectedComponent(); if (sp != null) { ImagePanel ip = (ImagePanel) sp.getViewport().getView(); ip.rotate(); } } }; } protected void addImage(String fn, BufferedImage img) { Object md = img.getProperty("iiometadata"); if ((md != Image.UndefinedProperty) && (md != null) && (md instanceof IIOMetadata)) { // new MetadataReader().read((IIOMetadata)md); } System.out.println("Image.Width =" + img.getWidth()); System.out.println("Image.Height =" + img.getHeight()); ImagePanel ip = new ImagePanel(); ip.addPropertyChangeListener(this); JScrollPane sp = new JScrollPane(ip); sp.getVerticalScrollBar().setUnitIncrement(100); sp.getHorizontalScrollBar().setUnitIncrement(100); ip.setImage(img); // images.addTab("image",sp); images.addTab(fn, new TabCloseIcon(), sp); images.setSelectedIndex(images.getTabCount() - 1); } public void open(String filename) throws IOException { long time = System.currentTimeMillis(); String ext = filename.substring(filename.lastIndexOf('.') + 1); Iterator readers = ImageIO.getImageReadersByFormatName(ext); if (!readers.hasNext()) { throw new IOException(getClass().getName() + ".open:\n\tNo reader for format '" + ext + "' available."); } ImageReader reader = (ImageReader) readers.next(); while (!reader.getClass().getName().startsWith("uk.co.mmscomputing") && readers.hasNext()) {// prefer our own reader reader = (ImageReader) readers.next(); } File f = new File(filename); ImageInputStream iis = ImageIO.createImageInputStream(f); try { reader.setInput(iis, true); try { for (int i = 0; true; i++) { IIOMetadata md = reader.getImageMetadata(i); // if(md!=null){new MetadataReader().read(md);} addImage(f.getName() + " " + i, reader.read(i)); } } catch (IndexOutOfBoundsException ioobe) { } } catch (Error e) { System.out.println("9\b" + getClass().getName() + ".open:\n\t" + e); e.printStackTrace(); throw e; } finally { iis.close(); } time = System.currentTimeMillis() - time; System.out.println("Opened : " + filename); System.out.println("Time used to load images : " + time); } private IIOImage getIIOImage(ImageWriter writer, ImageWriteParam iwp, BufferedImage image) { ImageTypeSpecifier it = ImageTypeSpecifier.createFromRenderedImage(image); /* try{ uk.co.mmscomputing.imageio.bmp.BMPMetadata md=(uk.co.mmscomputing.imageio.bmp.BMPMetadata)image.getProperty("iiometadata"); if(md!=null){ md.setXPixelsPerMeter(11812); // force 300 dpi for bmp images md.setYPixelsPerMeter(11812); // works only with mmsc.bmp package } }catch(Exception e){} */ IIOMetadata md; Object obj = image.getProperty("iiometadata"); // if image is a TwainBufferedImage get metadata if ((obj != null) && (obj instanceof IIOMetadata)) { md = (IIOMetadata) obj; } else { md = writer.getDefaultImageMetadata(it, iwp); } return new IIOImage(image, null, md); } public void save(String filename) throws IOException { if (images.getTabCount() <= 0) { throw new IOException(getClass().getName() + ".save:\n\tNo images available!"); } String ext = filename.substring(filename.lastIndexOf('.') + 1); Iterator writers = ImageIO.getImageWritersByFormatName(ext); if (!writers.hasNext()) { throw new IOException(getClass().getName() + ".save:\n\tNo writer for format '" + ext + "' available."); } ImageWriter writer = (ImageWriter) writers.next(); while (!writer.getClass().getName().startsWith("uk.co.mmscomputing") && writers.hasNext()) {// prefer our own writer writer = (ImageWriter) writers.next(); } ImageWriteParam iwp = writer.getDefaultWriteParam(); IIOParamController controller = iwp.getController(); if (controller != null) { controller.activate(iwp); } long time = System.currentTimeMillis(); File file = new File(filename); if (file.exists()) { file.delete(); } ImageOutputStream ios = null; try { ios = ImageIO.createImageOutputStream(file); writer.setOutput(ios); if (writer.canWriteSequence()) { //i.e tiff,sff(fax) writer.prepareWriteSequence(null); for (int i = 0; i < images.getTabCount(); i++) { JScrollPane sp = (JScrollPane) images.getComponentAt(i); ImagePanel ip = (ImagePanel) sp.getViewport().getView(); writer.writeToSequence(getIIOImage(writer, iwp, ip.getImage()), iwp); } writer.endWriteSequence(); } else { JScrollPane sp = (JScrollPane) images.getComponentAt(0); ImagePanel ip = (ImagePanel) sp.getViewport().getView(); writer.write(null, getIIOImage(writer, iwp, ip.getImage()), iwp); for (int i = 1; i < images.getTabCount(); i++) { if (writer.canInsertImage(i)) { sp = (JScrollPane) images.getComponentAt(i); ip = (ImagePanel) sp.getViewport().getView(); writer.write(null, getIIOImage(writer, iwp, ip.getImage()), iwp); } else { throw new IOException("Image Writer cannot append image [" + i + "] (" + filename + ")"); } } } time = System.currentTimeMillis() - time; System.out.println("Saved : " + filename); System.out.println("3\bTime used to save images : " + time); } finally { if (ios != null) { ios.close(); } } } public void convertImage() { new Thread() { @Override public void run() { try { ImageTypeConvertOpPanel itcop = new ImageTypeConvertOpPanel(); ImageTypeConvertOp itco = itcop.activate(); if (itco != null) { for (int i = 0; i < images.getTabCount(); i++) { JScrollPane sp = (JScrollPane) images.getComponentAt(i); ImagePanel ip = (ImagePanel) sp.getViewport().getView(); BufferedImage image = itco.filter(ip.getImage()); ip.setImage(image); ip.revalidate(); ip.repaint(); String type = "Unknown Type"; switch (image.getType()) { case BufferedImage.TYPE_BYTE_BINARY: type = "Byte Binary"; break; case BufferedImage.TYPE_BYTE_INDEXED: type = "Byte Indexed"; break; } ColorModel cm = image.getColorModel(); System.out.println("9\bConverted Images to:\n\ntype: " + type + "\nbpp: " + cm.getPixelSize()); } } } catch (Exception e) { System.out.println("9\b" + getClass().getName() + ".convertImage:\n\t" + e); e.printStackTrace(); } } }.start(); } /* public void convertToBWImage(){ for(int i=0; i<images.getTabCount(); i++){ JScrollPane sp=(JScrollPane)images.getComponentAt(i); ImagePanel ip=(ImagePanel)sp.getViewport().getView(); BufferedImage original=ip.getImage(); BufferedImage image=new BufferedImage(original.getWidth(),original.getHeight(),BufferedImage.TYPE_BYTE_BINARY); Graphics2D g=image.createGraphics(); AffineTransform t=new AffineTransform(); g.drawRenderedImage(original,t); ip.setImage(image); ip.revalidate();ip.repaint(); } } */ @Override public void propertyChange(final PropertyChangeEvent evt) { /* String prop=evt.getPropertyName(); if(prop.equals("open")){ JTabbedPane tp=(JTabbedPane)getParent(); tp.setSelectedIndex(1); new Thread(){ public void run(){ try{ open((String)evt.getNewValue()); }catch(Exception e){ JOptionPane.showMessageDialog(null, "Image Open Error : "+e.getMessage(), "Exception", JOptionPane.ERROR_MESSAGE); } } }.start(); }else if(prop.equals("save")){ new Thread(){ public void run(){ try{ open((String)evt.getNewValue()); int res=savefc.showSaveDialog(null); if(res==JFileChooser.APPROVE_OPTION){ save(savefc.getSelectedFile().getPath()); } }catch(IOException ioe){ System.out.println("9\b"+ioe.getMessage()); } } }.start(); } */ } static private class Printer extends Thread { PrinterJob pj; PageFormat pf; Book bk; public Printer() { pj = PrinterJob.getPrinterJob(); pf = pj.defaultPage(); Paper p = pf.getPaper(); p.setImageableArea(0.0, 0.0, p.getWidth(), p.getHeight()); pf.setPaper(p); pf = pj.validatePage(pf); bk = new Book(); } public void append(ImagePanel image) { bk.append(image, pf); } public void print() { pj.setPageable(bk); if (pj.printDialog()) { try { pj.print(); } catch (Exception e) { e.printStackTrace(); System.out.println("9\b" + getClass().getName() + ".print:\n\t" + e.getMessage()); } } } } }
17,734
0.554584
0.54325
465
37.137634
28.907907
158
false
false
0
0
0
0
0
0
0.651613
false
false
12
0a090db9ae3ebb9c8e4bf2d7fd10c679596ad449
16,612,933,513,648
421b77ac5d7deec32a38cf1acff0911130ad6325
/app/src/main/java/com/example/coffeenest/FragmentDetails/SmoothieDetails.java
0b687f40ed283cb9586f6d9ac372bbca9773c6ad
[]
no_license
nikos-koukis/Coffee-Nest-Android-Studio
https://github.com/nikos-koukis/Coffee-Nest-Android-Studio
52d39629d3781d1d587119946abd1a8174284f0a
ec1295e56605c88dbe1e341cd07416df6c482b37
refs/heads/master
2023-03-15T20:28:28.077000
2021-03-01T17:12:32
2021-03-01T17:12:32
343,495,690
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.coffeenest.FragmentDetails; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import android.content.Intent; import android.content.IntentFilter; import android.net.ConnectivityManager; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.example.coffeenest.CartActivity; import com.example.coffeenest.Database.Database; import com.example.coffeenest.Fragments.MainFragment; import com.example.coffeenest.Listener.NetworkChangeListener; import com.example.coffeenest.Model.CoffeeOrder; import com.example.coffeenest.R; import com.google.android.material.appbar.CollapsingToolbarLayout; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.squareup.picasso.Picasso; public class SmoothieDetails extends AppCompatActivity { //Init Variables TextView smoothieName, smoothiePrice, smoothieDescription; CollapsingToolbarLayout collapsingToolbarLayout; Toolbar smoothieDetailsToolbar; ImageView imageSmoothie; String smoothieNameFromFragment = "Smoothie Name Not Set"; String smoothieDescriptionFromFragment = "Smoothie Description Not Set"; String smoothiePriceFromFragment = "Smoothie Price Not Set"; String smoothieImageFromFragment = "Smoothie Image Not Set"; FirebaseDatabase database; DatabaseReference smoothieRef; Button buttonAddCart; String smoothieId = ""; int ID; //Create a new Network Listener NetworkChangeListener networkChangeListener = new NetworkChangeListener(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_smoothie_details); //Hook Elements From xml File - drink_details.xml smoothieDetailsToolbar = findViewById(R.id.smoothie_details_toolbar); smoothieName = findViewById(R.id.smoothie_name); smoothieDescription = findViewById(R.id.smoothie_description); smoothiePrice = findViewById(R.id.smoothie_price); imageSmoothie = findViewById(R.id.image_smoothie); buttonAddCart = findViewById(R.id.btn_add_cart); collapsingToolbarLayout = findViewById(R.id.smoothie_collapsing); setSupportActionBar(smoothieDetailsToolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); collapsingToolbarLayout.setExpandedTitleTextAppearance(R.style.ExpandedAppbar); collapsingToolbarLayout.setCollapsedTitleTextAppearance(R.style.CollapsedAppbar); database = FirebaseDatabase.getInstance(); smoothieRef = database.getReference("Smoothie"); //Take smoothie_name,smoothie_price,smoothie_image and smoothie_image from Smoothie Fragment Bundle extras = getIntent().getExtras(); if (extras != null) { smoothieNameFromFragment = extras.getString("smoothieNameFromFragment"); smoothieDescriptionFromFragment = extras.getString("smoothieDescriptionFromFragment"); smoothiePriceFromFragment = extras.getString("smoothiePriceFromFragment"); smoothieImageFromFragment = extras.getString("smoothieImageFromFragment"); } collapsingToolbarLayout.setTitle(smoothieNameFromFragment); smoothieDetailsToolbar.setTitle(smoothieNameFromFragment); smoothieDescription.setText(smoothieDescriptionFromFragment); smoothieName.setText(smoothieNameFromFragment); smoothiePrice.setText(smoothiePriceFromFragment + " \u20ac"); Picasso.get().load(smoothieImageFromFragment) .into(imageSmoothie); buttonAddCart.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { new Database(getBaseContext()).addToCart(new CoffeeOrder( ID, smoothieId, smoothieNameFromFragment, "1", smoothiePriceFromFragment )); Toast.makeText(getApplication(), "Το προϊόν προστέθηκε στο καλάθι σας!", Toast.LENGTH_SHORT).show(); startActivity(new Intent(SmoothieDetails.this, MainFragment.class)); } }); } // Add shopping cart icon in toolbar public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu, menu); return true; } //When cart icon pressed, then Cart Activity will started public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == R.id.cart) { Intent intent = new Intent(SmoothieDetails.this, CartActivity.class); startActivity(intent); return true; } return super.onOptionsItemSelected(item); } //Check For Internet Connection @Override protected void onStart() { IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION); registerReceiver(networkChangeListener, filter); super.onStart(); } @Override protected void onStop() { unregisterReceiver(networkChangeListener); super.onStop(); } }
UTF-8
Java
5,499
java
SmoothieDetails.java
Java
[]
null
[]
package com.example.coffeenest.FragmentDetails; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import android.content.Intent; import android.content.IntentFilter; import android.net.ConnectivityManager; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.example.coffeenest.CartActivity; import com.example.coffeenest.Database.Database; import com.example.coffeenest.Fragments.MainFragment; import com.example.coffeenest.Listener.NetworkChangeListener; import com.example.coffeenest.Model.CoffeeOrder; import com.example.coffeenest.R; import com.google.android.material.appbar.CollapsingToolbarLayout; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.squareup.picasso.Picasso; public class SmoothieDetails extends AppCompatActivity { //Init Variables TextView smoothieName, smoothiePrice, smoothieDescription; CollapsingToolbarLayout collapsingToolbarLayout; Toolbar smoothieDetailsToolbar; ImageView imageSmoothie; String smoothieNameFromFragment = "Smoothie Name Not Set"; String smoothieDescriptionFromFragment = "Smoothie Description Not Set"; String smoothiePriceFromFragment = "Smoothie Price Not Set"; String smoothieImageFromFragment = "Smoothie Image Not Set"; FirebaseDatabase database; DatabaseReference smoothieRef; Button buttonAddCart; String smoothieId = ""; int ID; //Create a new Network Listener NetworkChangeListener networkChangeListener = new NetworkChangeListener(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_smoothie_details); //Hook Elements From xml File - drink_details.xml smoothieDetailsToolbar = findViewById(R.id.smoothie_details_toolbar); smoothieName = findViewById(R.id.smoothie_name); smoothieDescription = findViewById(R.id.smoothie_description); smoothiePrice = findViewById(R.id.smoothie_price); imageSmoothie = findViewById(R.id.image_smoothie); buttonAddCart = findViewById(R.id.btn_add_cart); collapsingToolbarLayout = findViewById(R.id.smoothie_collapsing); setSupportActionBar(smoothieDetailsToolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); collapsingToolbarLayout.setExpandedTitleTextAppearance(R.style.ExpandedAppbar); collapsingToolbarLayout.setCollapsedTitleTextAppearance(R.style.CollapsedAppbar); database = FirebaseDatabase.getInstance(); smoothieRef = database.getReference("Smoothie"); //Take smoothie_name,smoothie_price,smoothie_image and smoothie_image from Smoothie Fragment Bundle extras = getIntent().getExtras(); if (extras != null) { smoothieNameFromFragment = extras.getString("smoothieNameFromFragment"); smoothieDescriptionFromFragment = extras.getString("smoothieDescriptionFromFragment"); smoothiePriceFromFragment = extras.getString("smoothiePriceFromFragment"); smoothieImageFromFragment = extras.getString("smoothieImageFromFragment"); } collapsingToolbarLayout.setTitle(smoothieNameFromFragment); smoothieDetailsToolbar.setTitle(smoothieNameFromFragment); smoothieDescription.setText(smoothieDescriptionFromFragment); smoothieName.setText(smoothieNameFromFragment); smoothiePrice.setText(smoothiePriceFromFragment + " \u20ac"); Picasso.get().load(smoothieImageFromFragment) .into(imageSmoothie); buttonAddCart.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { new Database(getBaseContext()).addToCart(new CoffeeOrder( ID, smoothieId, smoothieNameFromFragment, "1", smoothiePriceFromFragment )); Toast.makeText(getApplication(), "Το προϊόν προστέθηκε στο καλάθι σας!", Toast.LENGTH_SHORT).show(); startActivity(new Intent(SmoothieDetails.this, MainFragment.class)); } }); } // Add shopping cart icon in toolbar public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu, menu); return true; } //When cart icon pressed, then Cart Activity will started public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == R.id.cart) { Intent intent = new Intent(SmoothieDetails.this, CartActivity.class); startActivity(intent); return true; } return super.onOptionsItemSelected(item); } //Check For Internet Connection @Override protected void onStart() { IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION); registerReceiver(networkChangeListener, filter); super.onStart(); } @Override protected void onStop() { unregisterReceiver(networkChangeListener); super.onStop(); } }
5,499
0.712379
0.71183
159
33.402515
28.591049
116
false
false
0
0
0
0
0
0
0.597484
false
false
12
eb2b37e0757aededbf6213bc214be3265a4894a5
34,222,299,421,470
000ebf40b8cb14ee682fcbaeba93500dd327c3d6
/src/main/java/com/mentor/workflow/engine/WorkflowEngine.java
34779d7936151c5b059c1e7c4c76fc11b9c6343e
[]
no_license
kensipe/simple-workflow
https://github.com/kensipe/simple-workflow
3ae1503f8861fdcf30ba7dbb8b29886d461135ed
4823a20e6d3e1e577e9ac954f234a3772d2b0e48
refs/heads/master
2021-01-10T19:11:08.764000
2020-05-03T22:00:46
2020-05-03T22:00:46
8,037,882
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.mentor.workflow.engine; import com.mentor.workflow.WorkflowComponent; import com.mentor.workflow.exception.InvalidWorkflowException; import com.mentor.workflow.Action; import com.mentor.workflow.ActionHandler; import com.mentor.workflow.Workflow; import com.mentor.workflow.WorkflowState; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.Arrays; import java.util.List; //import org.springframework.stereotype.Service; /** * @author: ksipe */ public class WorkflowEngine { private final Logger logger = LoggerFactory.getLogger(getClass()); public List<Action> getAvailableActions(Workflow workflow, WorkflowComponent component) { return getAvailableActions(workflow,component.getStatus()); } public List<Action> getAvailableActions(Workflow workflow, String currentState) { WorkflowState workflowState = currentState == null? workflow.getInitialState() : workflow.getState(currentState); List<Action> actions; if (workflowState == null) { // we are in a bad state... a state that doesn't exist in the workflow String message = currentState + " state does not exist in the workflow: " + workflow.getName(); logger.error(message); throw new InvalidWorkflowException(message); } if (!workflowState.isFinalState()) { actions = new ArrayList<>(Arrays.asList(workflowState.getActions())); } else { // we ignore actions if it is the final state actions = new ArrayList<>(); } return actions; } public String invokeAction(Workflow workflow, WorkflowComponent component, Action action) { String currentState = component.getStatus(); if (!isValidAction(workflow, currentState, action)) { throw new InvalidWorkflowException("invoked action: " + action.getName() + " invalidated for state: " + currentState); } WorkflowState workflowState = getWorkflowState(workflow, action, currentState); ActionHandler handler = getActionHandler(workflow, action, workflowState); if (continueAfterBeforeAction(handler, component)) { currentState = getNextStateName(workflowState, action); component.setStatus(currentState); invokeHandlerOnAction(component, handler, action); } return currentState; } private boolean isValidAction(Workflow workflow, String currentState, Action action) { List<Action> actions = getAvailableActions(workflow, currentState); return actions.contains(action); } private WorkflowState getWorkflowState(Workflow workflow, Action action, String currentState) { WorkflowState workflowState = workflow.getState(currentState); if (workflowState.isFinalState()) { throw new InvalidWorkflowException("invoked action: " + action.getName() + " on final state not allowed"); } return workflowState; } private ActionHandler getActionHandler(Workflow workflow, Action action, WorkflowState workflowState) { ActionHandler handler = null; if (workflow.getState(workflowState.getStateForAction(action).getName()) != null) { handler = workflow.getState(workflowState.getStateForAction(action).getName()).getTransitionHandler(); } // consider a list of action handlers... that would be better return handler; } private void invokeHandlerOnAction(WorkflowComponent component, ActionHandler handler, Action action) { if (handler != null) { try { handler.onAction(action, component); } catch (Exception e) { logger.error("error on handler.onAction {}", handler.getClass(), e); } } } private boolean continueAfterBeforeAction(ActionHandler handler, WorkflowComponent component) { boolean continueWorkflow = true; if (handler != null) { try { continueWorkflow = handler.beforeAction(component); } catch (Exception e) { logger.error("handler failure: {}", handler.getClass(), e); continueWorkflow = false; } } return continueWorkflow; } private String getNextStateName(WorkflowState workflowState, Action action) { return workflowState.getStateForAction(action).getName(); } }
UTF-8
Java
4,505
java
WorkflowEngine.java
Java
[ { "context": "ringframework.stereotype.Service;\n\n/**\n * @author: ksipe\n */\npublic class WorkflowEngine {\n\n private fi", "end": 508, "score": 0.9996598362922668, "start": 503, "tag": "USERNAME", "value": "ksipe" } ]
null
[]
package com.mentor.workflow.engine; import com.mentor.workflow.WorkflowComponent; import com.mentor.workflow.exception.InvalidWorkflowException; import com.mentor.workflow.Action; import com.mentor.workflow.ActionHandler; import com.mentor.workflow.Workflow; import com.mentor.workflow.WorkflowState; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.Arrays; import java.util.List; //import org.springframework.stereotype.Service; /** * @author: ksipe */ public class WorkflowEngine { private final Logger logger = LoggerFactory.getLogger(getClass()); public List<Action> getAvailableActions(Workflow workflow, WorkflowComponent component) { return getAvailableActions(workflow,component.getStatus()); } public List<Action> getAvailableActions(Workflow workflow, String currentState) { WorkflowState workflowState = currentState == null? workflow.getInitialState() : workflow.getState(currentState); List<Action> actions; if (workflowState == null) { // we are in a bad state... a state that doesn't exist in the workflow String message = currentState + " state does not exist in the workflow: " + workflow.getName(); logger.error(message); throw new InvalidWorkflowException(message); } if (!workflowState.isFinalState()) { actions = new ArrayList<>(Arrays.asList(workflowState.getActions())); } else { // we ignore actions if it is the final state actions = new ArrayList<>(); } return actions; } public String invokeAction(Workflow workflow, WorkflowComponent component, Action action) { String currentState = component.getStatus(); if (!isValidAction(workflow, currentState, action)) { throw new InvalidWorkflowException("invoked action: " + action.getName() + " invalidated for state: " + currentState); } WorkflowState workflowState = getWorkflowState(workflow, action, currentState); ActionHandler handler = getActionHandler(workflow, action, workflowState); if (continueAfterBeforeAction(handler, component)) { currentState = getNextStateName(workflowState, action); component.setStatus(currentState); invokeHandlerOnAction(component, handler, action); } return currentState; } private boolean isValidAction(Workflow workflow, String currentState, Action action) { List<Action> actions = getAvailableActions(workflow, currentState); return actions.contains(action); } private WorkflowState getWorkflowState(Workflow workflow, Action action, String currentState) { WorkflowState workflowState = workflow.getState(currentState); if (workflowState.isFinalState()) { throw new InvalidWorkflowException("invoked action: " + action.getName() + " on final state not allowed"); } return workflowState; } private ActionHandler getActionHandler(Workflow workflow, Action action, WorkflowState workflowState) { ActionHandler handler = null; if (workflow.getState(workflowState.getStateForAction(action).getName()) != null) { handler = workflow.getState(workflowState.getStateForAction(action).getName()).getTransitionHandler(); } // consider a list of action handlers... that would be better return handler; } private void invokeHandlerOnAction(WorkflowComponent component, ActionHandler handler, Action action) { if (handler != null) { try { handler.onAction(action, component); } catch (Exception e) { logger.error("error on handler.onAction {}", handler.getClass(), e); } } } private boolean continueAfterBeforeAction(ActionHandler handler, WorkflowComponent component) { boolean continueWorkflow = true; if (handler != null) { try { continueWorkflow = handler.beforeAction(component); } catch (Exception e) { logger.error("handler failure: {}", handler.getClass(), e); continueWorkflow = false; } } return continueWorkflow; } private String getNextStateName(WorkflowState workflowState, Action action) { return workflowState.getStateForAction(action).getName(); } }
4,505
0.673918
0.673474
115
38.173912
34.983044
130
false
false
0
0
0
0
0
0
0.678261
false
false
12
c73d126d579926f11a383b944d4c3be42d945b34
3,959,959,875,647
a094f0873a0af719421d49c82a01f8368e45572d
/src/interface_ex/Ex03.java
5101325a1550634225d69dcf5f9a1a83c92d6dea
[]
no_license
Gimyejin/day16_overriding_interface
https://github.com/Gimyejin/day16_overriding_interface
e7ad3e5b8307e6edd36f68d8ebab442d245a5903
8ca347fda50d0843ace21dc271fd4bdae038dfc2
refs/heads/master
2023-07-20T14:41:58.504000
2021-08-23T11:49:13
2021-08-23T11:49:13
399,082,921
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package interface_ex; interface Test { // public int aÇÏ¸é ¿¡·¯³² public static final int a = 123;// Àº µÊ public final int a1 = 12345;// Àº µÊ public static int a2 = 12356;// Àº µÊ public static String id ="È«±æµ¿"; public static String pw ="1111"; } public class Ex03 implements Test { public static void main(String[] args) { System.out.println(Test.id); System.out.println(pw); } }
WINDOWS-1252
Java
432
java
Ex03.java
Java
[]
null
[]
package interface_ex; interface Test { // public int aÇÏ¸é ¿¡·¯³² public static final int a = 123;// Àº µÊ public final int a1 = 12345;// Àº µÊ public static int a2 = 12356;// Àº µÊ public static String id ="È«±æµ¿"; public static String pw ="1111"; } public class Ex03 implements Test { public static void main(String[] args) { System.out.println(Test.id); System.out.println(pw); } }
432
0.670792
0.613861
20
19.200001
16.277592
41
false
false
0
0
0
0
0
0
1.05
false
false
12
d73a7ca1f5aed5df2fb1c5c415b071d496fdcddf
4,638,564,712,709
d2de73f8c681a5c6215a260464b250bccc2b9281
/Winner.java
6b30ec5e5dad7b745ff3c063127c03fe8921a3e1
[]
no_license
karthic-psa/Tic-Tac-Toe-Game
https://github.com/karthic-psa/Tic-Tac-Toe-Game
3e3e21962d2e5a9cd90f1c90e27848f4a7055df5
ae07d234ab295ea0848e1ca61c9e5b389ce94af4
refs/heads/master
2020-03-28T19:46:17.744000
2017-12-11T03:56:50
2017-12-11T03:56:50
94,602,274
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package tic; public class Winner { public static boolean DecideWinner(char[][] board, int move) { char symbol = ' '; if (move%2 != 0) { symbol = 'o'; // it was computer's move } else { symbol = 'x'; // it was user's move } int r = board.length; int c = board[0].length; int i, j; boolean gameOver = false; for (i = 0; i < r && !gameOver; i++) { // checking row for (j = 0; j < c; j++) { if (board[i][j] != symbol) break; } if (j == c) gameOver = true; } for (j = 0; j < c && !gameOver; j++) { // ckecking column for (i = 0; i < r; i++) { if (board[i][j] != symbol) break; } if (i == r) gameOver = true; } if (!gameOver) { // checking the diagonal for (i = 0; i < r; i++) { if (board[i][i] != symbol) break; } if (i == r) gameOver = true; } if (!gameOver) { // Second diagonal check for (i = 0; i < r; i++) { if (board[i][r - 1 - i] != symbol) break; } if (i == r) gameOver = true; } return gameOver; } public static void restart(char[][] board) { for (int i = 0; i < board.length; i++) for (int j = 0; j < board[0].length; j++) board[i][j] = ' '; } }
UTF-8
Java
1,396
java
Winner.java
Java
[]
null
[]
package tic; public class Winner { public static boolean DecideWinner(char[][] board, int move) { char symbol = ' '; if (move%2 != 0) { symbol = 'o'; // it was computer's move } else { symbol = 'x'; // it was user's move } int r = board.length; int c = board[0].length; int i, j; boolean gameOver = false; for (i = 0; i < r && !gameOver; i++) { // checking row for (j = 0; j < c; j++) { if (board[i][j] != symbol) break; } if (j == c) gameOver = true; } for (j = 0; j < c && !gameOver; j++) { // ckecking column for (i = 0; i < r; i++) { if (board[i][j] != symbol) break; } if (i == r) gameOver = true; } if (!gameOver) { // checking the diagonal for (i = 0; i < r; i++) { if (board[i][i] != symbol) break; } if (i == r) gameOver = true; } if (!gameOver) { // Second diagonal check for (i = 0; i < r; i++) { if (board[i][r - 1 - i] != symbol) break; } if (i == r) gameOver = true; } return gameOver; } public static void restart(char[][] board) { for (int i = 0; i < board.length; i++) for (int j = 0; j < board[0].length; j++) board[i][j] = ' '; } }
1,396
0.420487
0.411175
64
20.78125
16.888855
63
false
false
0
0
0
0
0
0
1.5625
false
false
12
780e0e70295d61f6b2e7e5285554b94ae8b8195e
11,630,771,457,761
e1b4de3e02ba088f203a410b8cd1c82d3273139a
/src/main/java/com/fms/rest/Chau.java
b1058b9a1954e1fe37baf8aad6aa167b6e3a4924
[]
no_license
fsoylemez/liberty-jnosql
https://github.com/fsoylemez/liberty-jnosql
375b8cd33b06d08dab7c1846dddcbaa55e88049d
a0236f7617b568041bf59d7ad683b716cd333c16
refs/heads/master
2023-08-03T08:20:39.739000
2021-09-17T08:35:34
2021-09-17T08:35:34
407,140,799
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.fms.rest; import com.fms.jnosql.HeroService; import javax.inject.Inject; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; @Path("/chau") public class Chau { @Inject HeroService service; @GET @Produces public String sayChau() { service.create(); return "Chau mau"; } }
UTF-8
Java
354
java
Chau.java
Java
[]
null
[]
package com.fms.rest; import com.fms.jnosql.HeroService; import javax.inject.Inject; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; @Path("/chau") public class Chau { @Inject HeroService service; @GET @Produces public String sayChau() { service.create(); return "Chau mau"; } }
354
0.655367
0.655367
22
15.090909
11.401392
34
false
false
0
0
0
0
0
0
0.409091
false
false
12
43fd8d8dfa911873f905f9eaee7f503083aa94b0
25,529,285,653,434
8144f79f8b1ade65d6bec133660945ecbf35b786
/src/com/zzkj/thoa/pubinfo/entity/PubInforWfNewsRead.java
65bcde466f932617df9ead7919e2b206f6f0cdf1
[]
no_license
yanhan569046480/thoa
https://github.com/yanhan569046480/thoa
3b7963811642fda1f635929a1868d57ba11b8e72
ddcbddeb12f5e6b9921e579d92ee19026e510bb4
refs/heads/master
2016-03-06T22:42:42.756000
2015-03-09T10:53:52
2015-03-09T10:53:52
31,889,406
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.zzkj.thoa.pubinfo.entity; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; import org.hibernate.annotations.GenericGenerator; /** * PubInforWfNewsRead entity. @author MyEclipse Persistence Tools */ @Entity @Table(name = "THOA_PubInfor_WF_News_Read", schema = "dbo") public class PubInforWfNewsRead implements java.io.Serializable { private static final long serialVersionUID = 1634793315664875916L; // Fields private String id; private String newsId; private String employeeId; // Constructors /** default constructor */ public PubInforWfNewsRead() { } /** minimal constructor */ public PubInforWfNewsRead(String id) { this.id = id; } /** full constructor */ public PubInforWfNewsRead(String id, String newsId, String employeeId) { this.id = id; this.newsId = newsId; this.employeeId = employeeId; } // Property accessors @Id @GeneratedValue(generator = "uuid") @GenericGenerator(name = "uuid", strategy = "uuid") @Column(name = "id", unique = true, nullable = false, length = 32) public String getId() { return this.id; } public void setId(String id) { this.id = id; } @Column(name = "newsId") public String getNewsId() { return this.newsId; } public void setNewsId(String newsId) { this.newsId = newsId; } @Column(name = "employeeId") public String getEmployeeId() { return this.employeeId; } public void setEmployeeId(String employeeId) { this.employeeId = employeeId; } }
UTF-8
Java
1,578
java
PubInforWfNewsRead.java
Java
[]
null
[]
package com.zzkj.thoa.pubinfo.entity; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; import org.hibernate.annotations.GenericGenerator; /** * PubInforWfNewsRead entity. @author MyEclipse Persistence Tools */ @Entity @Table(name = "THOA_PubInfor_WF_News_Read", schema = "dbo") public class PubInforWfNewsRead implements java.io.Serializable { private static final long serialVersionUID = 1634793315664875916L; // Fields private String id; private String newsId; private String employeeId; // Constructors /** default constructor */ public PubInforWfNewsRead() { } /** minimal constructor */ public PubInforWfNewsRead(String id) { this.id = id; } /** full constructor */ public PubInforWfNewsRead(String id, String newsId, String employeeId) { this.id = id; this.newsId = newsId; this.employeeId = employeeId; } // Property accessors @Id @GeneratedValue(generator = "uuid") @GenericGenerator(name = "uuid", strategy = "uuid") @Column(name = "id", unique = true, nullable = false, length = 32) public String getId() { return this.id; } public void setId(String id) { this.id = id; } @Column(name = "newsId") public String getNewsId() { return this.newsId; } public void setNewsId(String newsId) { this.newsId = newsId; } @Column(name = "employeeId") public String getEmployeeId() { return this.employeeId; } public void setEmployeeId(String employeeId) { this.employeeId = employeeId; } }
1,578
0.726236
0.712928
74
20.337837
19.958252
73
false
false
0
0
0
0
0
0
1.108108
false
false
12
96a8a54b0eba3fba83279315d9c321de044d41d5
15,358,803,087,321
8d8ffbe7d835dc15a9b92bdd0c7b9a1417af2524
/app/src/main/java/com/tohier/cartercoin/activity/UpdateMemberInfoActivity.java
02a9c55e418e3a32159edebb5e91f10abe14a548
[]
no_license
OnClickListener2048/ctc_and_v9
https://github.com/OnClickListener2048/ctc_and_v9
6e53eb7baee87b1a7ed75326efbbe2db36760da7
e757f1962ba8052ae0a753fc3e16ff2578f93c9b
refs/heads/master
2021-07-11T12:27:55.022000
2017-10-11T16:25:17
2017-10-11T16:25:17
106,579,730
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.tohier.cartercoin.activity; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.drawable.ColorDrawable; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.os.Message; import android.provider.MediaStore; import android.support.v4.graphics.drawable.RoundedBitmapDrawable; import android.support.v4.graphics.drawable.RoundedBitmapDrawableFactory; import android.text.TextUtils; import android.util.Log; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import android.view.WindowManager; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.PopupWindow; import android.widget.ProgressBar; import android.widget.TextView; import com.bumptech.glide.Glide; import com.bumptech.glide.request.target.BitmapImageViewTarget; import com.squareup.okhttp.Callback; import com.squareup.okhttp.Request; import com.squareup.okhttp.Response; import com.tencent.connect.UserInfo; import com.tencent.connect.common.Constants; import com.tencent.mm.sdk.modelmsg.SendAuth; import com.tencent.mm.sdk.openapi.IWXAPI; import com.tencent.mm.sdk.openapi.WXAPIFactory; import com.tencent.tauth.IUiListener; import com.tencent.tauth.Tencent; import com.tencent.tauth.UiError; import com.tohier.android.util.BitmapUtil; import com.tohier.android.util.FileUtils; import com.tohier.cartercoin.R; import com.tohier.cartercoin.config.HttpConnect; import com.tohier.cartercoin.config.LoginUser; import com.tohier.cartercoin.config.MyApplication; import net.sf.json.JSONObject; import org.json.JSONException; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.util.HashMap; import java.util.Map; import de.hdodenhof.circleimageview.CircleImageView; import util.PopBirthHelper; /** * Created by Administrator on 2016/12/12. */ public class UpdateMemberInfoActivity extends MyBackBaseActivity { private View view1; private Button btn_tuku, btn_camera, btn_quxiao; private PopupWindow window; private Bitmap photo; private static final int ALBUM_REQUEST_CODE = 1; private static final int CAMERA_REQUEST_CODE = 2; private static final int CROP_REQUEST_CODE = 4; private static final String IMAGE_UNSPECIFIED = "image/*"; private static final String TAG = "RegisterInfoActivity"; private Uri uritempFile; private int i = 0; private PopBirthHelper popBirthHelper; private CircleImageView memberHeadImg; private TextView tvNickName,tvSex,tvName,tvNumberID,tvBirthday,tvPhoneNum,tvWXNum,tvQQNum,tvComplete; private ImageView ivBack; private LinearLayout linearlayoutIntoMemberUpgrade,linearLayoutIntoAddBackCard,linearlayout_into_update_member_img,linearlayout_into_update_member_nickname,linearlayout_into_update_member_sex, linearlayout_into_update_member_reaname,linearlayout_into_update_member_idnumber,linearlayout_into_update_member_birthday,linearlayout_into_update_member_bandphone,linearlayout_into_update_member_bandwx,linearlayout_into_update_member_bandqq; private static final String QQ_APP_ID = "1105547483"; public Tencent mTencent; private String QQopenID; private static final String WX_APP_ID = "wx7ad749f6cba84064"; public IWXAPI api; private ProgressBar progressBarInfoPerfectDegree; private TextView tvInfoPerfectDegree,tv_nickname_reward_ctc,tv_name_reward_ctc,tv_idnumber_reward_ctc,tv_birthday_reward_ctc,tv_mobile_reward_ctc,tv_wx_reward_ctc,tv_qq_reward_ctc,tv_backcard_reward_ctc,tv_bankcard; private View.OnClickListener onClickListener = new View.OnClickListener() { @Override public void onClick(View v) { switch (v.getId()) { case R.id.title_back: finish(); break; case R.id.tv_complete: updateMemberInfo(); break; case R.id.linearlayout_into_member_upgrade: startActivity(new Intent(UpdateMemberInfoActivity.this,ShouHuoAddressActivity.class)); break; case R.id.linearLayout_into_add_backcard: startActivity(new Intent(UpdateMemberInfoActivity.this,AddCardActivity.class)); break; case R.id.linearlayout_into_update_member_nickname: View view2 = View.inflate(UpdateMemberInfoActivity.this,R.layout.nickname_popuwindow,null); final PopupWindow popupWindow = new PopupWindow(view2,WindowManager.LayoutParams.MATCH_PARENT,WindowManager.LayoutParams.MATCH_PARENT); // 设置背景颜色变暗 WindowManager.LayoutParams lp = getWindow().getAttributes(); lp.alpha = 0.7f; getWindow().setAttributes(lp); popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() { @Override public void onDismiss() { WindowManager.LayoutParams lp = getWindow().getAttributes(); lp.alpha = 1f; getWindow().setAttributes(lp); } }); popupWindow.setFocusable(true); popupWindow.setOutsideTouchable(true); // 实例化一个ColorDrawable颜色为半透明 ColorDrawable dw2 = new ColorDrawable(0x00ffffff); popupWindow.setBackgroundDrawable(dw2); popupWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN); // 设置popWindow的显示和消失动画 // popupWindow.setAnimationStyle(R.style.Mypopwindow_anim_style); popupWindow.setAnimationStyle(R.style.Mypopwindow_anim_style); popupWindow.showAtLocation(linearlayout_into_update_member_nickname,Gravity.CENTER,0,0); final EditText etNick = (EditText) view2.findViewById(R.id.et_name); view2.findViewById(R.id.btn_commit).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String name = etNick.getText().toString(); if(!TextUtils.isEmpty(name)) { nickname = name; tvNickName.setText(name); popupWindow.dismiss(); }else { sToast("昵称不能为空"); } } }); view2.findViewById(R.id.btn_clear).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { popupWindow.dismiss(); } }); break; case R.id.linearlayout_into_update_member_sex: AlertDialog.Builder builder1= new AlertDialog.Builder(UpdateMemberInfoActivity.this,AlertDialog.THEME_HOLO_LIGHT); builder1.setTitle("性别"); //定义列表中的选项 final String[] items = new String[]{ "保密", "美女", "帅哥" }; //设置列表选项 builder1.setItems(items, new DialogInterface.OnClickListener() { //点击任何一个列表选项都会触发这个方法 //arg1:点击的是哪一个选项 @Override public void onClick(DialogInterface dialog, int which) { switch (which){ case 0: tvSex.setText("保密"); sex = "保密"; break; case 1: tvSex.setText("美女"); sex = "美女"; break; case 2: tvSex.setText("帅哥"); sex = "帅哥"; break; } } }); // 取消选择 builder1.setNegativeButton("取消", null); builder1.show(); break; case R.id.linearlayout_into_update_member_reaname: View view3 = View.inflate(UpdateMemberInfoActivity.this,R.layout.reanname_popuwindow,null); final PopupWindow reanamePopupWindow = new PopupWindow(view3,WindowManager.LayoutParams.MATCH_PARENT,WindowManager.LayoutParams.MATCH_PARENT); reanamePopupWindow.setFocusable(true); // 设置背景颜色变暗 WindowManager.LayoutParams lp2 = getWindow().getAttributes(); lp2.alpha = 0.7f; getWindow().setAttributes(lp2); reanamePopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() { @Override public void onDismiss() { WindowManager.LayoutParams lp3 = getWindow().getAttributes(); lp3.alpha = 1f; getWindow().setAttributes(lp3); } }); reanamePopupWindow.setOutsideTouchable(true); // 实例化一个ColorDrawable颜色为半透明 ColorDrawable dw3 = new ColorDrawable(0x00ffffff); reanamePopupWindow.setBackgroundDrawable(dw3); reanamePopupWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN); // 设置popWindow的显示和消失动画 reanamePopupWindow.setAnimationStyle(R.style.Mypopwindow_anim_style); reanamePopupWindow.showAtLocation(linearlayout_into_update_member_nickname,Gravity.CENTER,0,0); final EditText reaname = (EditText) view3.findViewById(R.id.et_name); view3.findViewById(R.id.btn_commit).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String name8 = reaname.getText().toString(); if(!TextUtils.isEmpty(name8)) { name = name8; tvName.setText(name8); reanamePopupWindow.dismiss(); }else { sToast("姓名不能为空"); } } }); view3.findViewById(R.id.btn_clear).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { reanamePopupWindow.dismiss(); } }); break; case R.id.linearlayout_into_update_member_img: window = new PopupWindow(view1, WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT); // 设置背景颜色变暗 WindowManager.LayoutParams lp5 = getWindow().getAttributes(); lp5.alpha = 0.5f; getWindow().setAttributes(lp5); window.setOnDismissListener(new PopupWindow.OnDismissListener() { @Override public void onDismiss() { WindowManager.LayoutParams lp3 = getWindow().getAttributes(); lp3.alpha = 1f; getWindow().setAttributes(lp3); } }); window.setOutsideTouchable(true); // 实例化一个ColorDrawable颜色为半透明 ColorDrawable dw = new ColorDrawable(0x00ffffff); window.setBackgroundDrawable(dw); // 设置popWindow的显示和消失动画 window.setAnimationStyle(R.style.Mypopwindow_anim_style); // 在底部显示 window.showAtLocation(findViewById(R.id.fenxiang_title), Gravity.BOTTOM, 0, 0); break; case R.id.linearlayout_into_update_member_birthday: popBirthHelper.show(tvBirthday); break; case R.id.linearlayout_into_update_member_idnumber: View view4 = View.inflate(UpdateMemberInfoActivity.this,R.layout.idnumber_popuwindow,null); final PopupWindow idNumberPopupWindow = new PopupWindow(view4,WindowManager.LayoutParams.MATCH_PARENT,WindowManager.LayoutParams.MATCH_PARENT); // 设置背景颜色变暗 WindowManager.LayoutParams lp4 = getWindow().getAttributes(); lp4.alpha = 0.7f; getWindow().setAttributes(lp4); idNumberPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() { @Override public void onDismiss() { WindowManager.LayoutParams lp3 = getWindow().getAttributes(); lp3.alpha = 1f; getWindow().setAttributes(lp3); } }); idNumberPopupWindow.setFocusable(true); idNumberPopupWindow.setOutsideTouchable(true); // 实例化一个ColorDrawable颜色为半透明 ColorDrawable dw4 = new ColorDrawable(0x00ffffff); idNumberPopupWindow.setBackgroundDrawable(dw4); idNumberPopupWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN); // 设置popWindow的显示和消失动画 idNumberPopupWindow.setAnimationStyle(R.style.Mypopwindow_anim_style); idNumberPopupWindow.showAtLocation(linearlayout_into_update_member_nickname,Gravity.CENTER,0,0); final EditText etIdNumber = (EditText) view4.findViewById(R.id.et_name); view4.findViewById(R.id.btn_commit).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String name = etIdNumber.getText().toString(); if(!TextUtils.isEmpty(name)) { idnumber = name; tvNumberID.setText(name); idNumberPopupWindow.dismiss(); }else { sToast("身份证号不能为空"); } } }); view4.findViewById(R.id.btn_clear).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { idNumberPopupWindow.dismiss(); } }); break; case R.id.linearlayout_into_update_member_bandqq: mTencent = Tencent.createInstance(QQ_APP_ID, getApplicationContext()); if (!mTencent.isSessionValid()) { mTencent.login(UpdateMemberInfoActivity.this, "get_simple_userinfo", listener); } else { mTencent.logout(getApplicationContext()); mTencent.login(UpdateMemberInfoActivity.this, "get_simple_userinfo", listener); } break; case R.id.linearlayout_into_update_member_bandwx: getSharedPreferences("weixinlogin", Context.MODE_APPEND).edit().putString("login","bandphone").commit(); api = WXAPIFactory.createWXAPI(getApplicationContext(), WX_APP_ID, true); api.registerApp(WX_APP_ID); final SendAuth.Req req = new SendAuth.Req(); req.scope = "snsapi_userinfo"; req.state = "wechat_sdk_demo_test"; if (!api.sendReq(req)) { sToast("请您安装微信"); } break; } } }; private IUiListener listener = new IUiListener() { @Override public void onCancel() { sToast("您取消了QQ登录"); } @Override public void onComplete(Object arg0) { sToast("进入授权"); org.json.JSONObject jo = (org.json.JSONObject) arg0; initLoginID(jo); } @Override public void onError(UiError arg0) { sToast("QQ登录出错"); } }; private void initLoginID(org.json.JSONObject jsonObject) { try { if (jsonObject.getString("ret").equals("0")) { String token = jsonObject.getString(Constants.PARAM_ACCESS_TOKEN); String expires = jsonObject.getString(Constants.PARAM_EXPIRES_IN); QQopenID = jsonObject.getString(Constants.PARAM_OPEN_ID); mTencent.setOpenId(QQopenID); mTencent.setAccessToken(token, expires); getuserInfo(); } } catch (JSONException e) { e.printStackTrace(); } } private void getuserInfo() { UserInfo qqInfo = new UserInfo(this, mTencent.getQQToken()); qqInfo.getUserInfo(getQQinfoListener); } private IUiListener getQQinfoListener = new IUiListener() { @Override public void onComplete(Object response) { try { org.json.JSONObject jsonObject = (org.json.JSONObject) response; int ret = jsonObject.getInt("ret"); String headImgUrl = jsonObject.getString("figureurl_qq_2"); String nickname = jsonObject.getString("nickname"); Map<String, String> par1 = new HashMap<String, String>(); par1.put("id", LoginUser.getInstantiation(getApplicationContext()) .getLoginUser().getUserId()); par1.put("openid", QQopenID); HttpConnect.post(UpdateMemberInfoActivity.this, "member_modify_qq", par1, new Callback() { @Override public void onFailure(Request arg0, IOException arg1) { Handler dataHandler = new Handler( getContext().getMainLooper()) { @Override public void handleMessage( final Message msg) { // sToast("请检查你的网络状态"); } }; dataHandler.sendEmptyMessage(0); } @Override public void onResponse(Response arg0) throws IOException { JSONObject object = JSONObject.fromObject(arg0.body().string()); if (object.get("status").equals("success")) { Handler dataHandler = new Handler( getContext().getMainLooper()) { @Override public void handleMessage( final Message msg) { sToast("QQ已绑定成功"); tvQQNum.setText("已绑定"); linearlayout_into_update_member_bandqq.setClickable(false); } }; dataHandler.sendEmptyMessage(0); }else { Handler dataHandler = new Handler( getContext().getMainLooper()) { @Override public void handleMessage( final Message msg) { sToast("该QQ已有用户绑定"); } }; dataHandler.sendEmptyMessage(0); } } }); //处理自己需要的信息 } catch (Exception e) { } } @Override public void onError(UiError uiError) { } @Override public void onCancel() { } }; private String mobile; private String idnumber; private String qqopenid; private String wechatopenid; private String agent; private String introducermobile; private String sex; private String introducerid; private String name; private String gesturepassword; private String linkcode; private String type; private String nickname; private String pic; private String birthday; private String id; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_update_memberinfo_layout); MyApplication.maps.put("UpdateMemberInfoActivity",this); initData(); setUpView(); loadMemberInfo(); loadInfoComplete(); } @Override public void initData() { memberHeadImg = (CircleImageView) this.findViewById(R.id.iv_member_head_img); tvNickName = (TextView) this.findViewById(R.id.tv_nickname); tvSex = (TextView) this.findViewById(R.id.tv_sex); tvName = (TextView) this.findViewById(R.id.tv_name); tvNumberID = (TextView) this.findViewById(R.id.tv_numberID); tvBirthday = (TextView) this.findViewById(R.id.tv_birthday); tvPhoneNum = (TextView) this.findViewById(R.id.tv_mobile); tvInfoPerfectDegree = (TextView) this.findViewById(R.id.tv_info_perfect_degree); tv_nickname_reward_ctc = (TextView) this.findViewById(R.id.tv_nickname_reward_ctc); tv_name_reward_ctc = (TextView) this.findViewById(R.id.tv_name_reward_ctc); tv_idnumber_reward_ctc = (TextView) this.findViewById(R.id.tv_idnumber_reward_ctc); tv_birthday_reward_ctc = (TextView) this.findViewById(R.id.tv_birthday_reward_ctc); tv_mobile_reward_ctc = (TextView) this.findViewById(R.id.tv_mobile_reward_ctc); tv_wx_reward_ctc = (TextView) this.findViewById(R.id.tv_wx_reward_ctc); tv_qq_reward_ctc = (TextView) this.findViewById(R.id.tv_qq_reward_ctc); tv_backcard_reward_ctc = (TextView) this.findViewById(R.id.tv_backcard_reward_ctc); tvWXNum = (TextView) this.findViewById(R.id.tv_wx_num); tvQQNum = (TextView) this.findViewById(R.id.tv_qq_num); tv_bankcard = (TextView) this.findViewById(R.id.tv_bankcard); tvComplete = (TextView) this.findViewById(R.id.tv_complete); ivBack = (ImageView) this.findViewById(R.id.title_back); progressBarInfoPerfectDegree = (ProgressBar) this.findViewById(R.id.progressBar_info_perfect_degree); view1 = View.inflate(this, R.layout.photo_popupwindow_item, null); btn_tuku = (Button) view1 .findViewById(R.id.photo_popupwindow_item_photo); btn_camera = (Button) view1 .findViewById(R.id.photo_popupwindow_item_camera); btn_quxiao = (Button) view1 .findViewById(R.id.photo_popupwindow_item_look); linearlayoutIntoMemberUpgrade = (LinearLayout) this.findViewById(R.id.linearlayout_into_member_upgrade); linearLayoutIntoAddBackCard = (LinearLayout) this.findViewById(R.id.linearLayout_into_add_backcard); linearlayout_into_update_member_img = (LinearLayout) this.findViewById(R.id.linearlayout_into_update_member_img); linearlayout_into_update_member_nickname = (LinearLayout) this.findViewById(R.id.linearlayout_into_update_member_nickname); linearlayout_into_update_member_sex = (LinearLayout) this.findViewById(R.id.linearlayout_into_update_member_sex); linearlayout_into_update_member_reaname = (LinearLayout) this.findViewById(R.id.linearlayout_into_update_member_reaname); linearlayout_into_update_member_idnumber = (LinearLayout) this.findViewById(R.id.linearlayout_into_update_member_idnumber); linearlayout_into_update_member_birthday = (LinearLayout) this.findViewById(R.id.linearlayout_into_update_member_birthday); linearlayout_into_update_member_bandphone = (LinearLayout) this.findViewById(R.id.linearlayout_into_update_member_bandphone); linearlayout_into_update_member_bandwx = (LinearLayout) this.findViewById(R.id.linearlayout_into_update_member_bandwx); linearlayout_into_update_member_bandqq = (LinearLayout) this.findViewById(R.id.linearlayout_into_update_member_bandqq); popBirthHelper = new PopBirthHelper(this); popBirthHelper.setOnClickOkListener(new PopBirthHelper.OnClickOkListener() { @Override public void onClickOk(String birthday) { tvBirthday.setText(birthday); } }); } private void setUpView() { ivBack.setOnClickListener(onClickListener); tvComplete.setOnClickListener(onClickListener); linearlayoutIntoMemberUpgrade.setOnClickListener(onClickListener); linearLayoutIntoAddBackCard.setOnClickListener(onClickListener); linearlayout_into_update_member_nickname.setOnClickListener(onClickListener); linearlayout_into_update_member_sex.setOnClickListener(onClickListener); linearlayout_into_update_member_img.setOnClickListener(onClickListener); linearlayout_into_update_member_reaname.setOnClickListener(onClickListener); linearlayout_into_update_member_birthday.setOnClickListener(onClickListener); linearlayout_into_update_member_idnumber.setOnClickListener(onClickListener); linearlayout_into_update_member_bandqq.setOnClickListener(onClickListener); linearlayout_into_update_member_bandwx.setOnClickListener(onClickListener); /** * 头像处理 */ btn_tuku.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (FileUtils.checkSDCard()){ window.dismiss(); Intent intent = new Intent(Intent.ACTION_PICK, null); intent.setDataAndType( MediaStore.Images.Media.EXTERNAL_CONTENT_URI, IMAGE_UNSPECIFIED); startActivityForResult(intent, ALBUM_REQUEST_CODE); }else{ UpdateMemberInfoActivity.this.sToast("请先插入SD卡"); } } }); btn_camera.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (FileUtils.checkSDCard()){ window.dismiss(); Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File( Environment.getExternalStorageDirectory(), "temp.jpg"))); startActivityForResult(intent, CAMERA_REQUEST_CODE); }else{ UpdateMemberInfoActivity.this.sToast("请先插入SD卡"); } } }); btn_quxiao.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (FileUtils.checkSDCard()){ window.dismiss(); } } }); } /** * 获取会员的信息 */ public void loadMemberInfo() { mZProgressHUD.show(); HttpConnect.post(UpdateMemberInfoActivity.this, "member_info", null, new Callback() { @Override public void onResponse(Response arg0) throws IOException { JSONObject data = JSONObject.fromObject(arg0.body().string()); if (data.get("status").equals("success")) { id = data.getJSONArray("data").getJSONObject(0).getString("ID"); birthday = data.getJSONArray("data").getJSONObject(0).getString("birthday"); pic = data.getJSONArray("data").getJSONObject(0).getString("pic"); nickname = data.getJSONArray("data").getJSONObject(0).getString("nickname"); type = data.getJSONArray("data").getJSONObject(0).getString("type"); linkcode = data.getJSONArray("data").getJSONObject(0).getString("linkcode"); gesturepassword = data.getJSONArray("data").getJSONObject(0).getString("gesturespassword"); name = data.getJSONArray("data").getJSONObject(0).getString("name"); introducerid = data.getJSONArray("data").getJSONObject(0).getString("introducerid"); sex = data.getJSONArray("data").getJSONObject(0).getString("sex"); introducermobile = data.getJSONArray("data").getJSONObject(0).getString("introducermobile"); agent = data.getJSONArray("data").getJSONObject(0).getString("agent"); wechatopenid = data.getJSONArray("data").getJSONObject(0).getString("wechatopenid"); qqopenid = data.getJSONArray("data").getJSONObject(0).getString("qqopenid"); idnumber = data.getJSONArray("data").getJSONObject(0).getString("idnumber"); mobile = data.getJSONArray("data").getJSONObject(0).getString("mobile"); Handler dataHandler = new Handler(getContext() .getMainLooper()) { @Override public void handleMessage(final Message msg) { loadInfoComplete(); /** * 设置头像 以及昵称 */ if (pic!=null){ Glide.with(UpdateMemberInfoActivity.this).load(pic).asBitmap().centerCrop().into(new BitmapImageViewTarget(memberHeadImg) { @Override protected void setResource(Bitmap resource) { RoundedBitmapDrawable circularBitmapDrawable = RoundedBitmapDrawableFactory.create(getResources(), resource); circularBitmapDrawable.setCircular(true); memberHeadImg.setImageDrawable(circularBitmapDrawable); } }); } if(!TextUtils.isEmpty(nickname)) { tvNickName.setText(nickname); } if(!TextUtils.isEmpty(sex)) { if(sex.equals("保密")) { tvSex.setText("保密"); }else if(sex.equals("美女")) { tvSex.setText("美女"); }else if(sex.equals("帅哥")) { tvSex.setText("帅哥"); } } if(!TextUtils.isEmpty(name)) { tvName.setText(name); } if(!TextUtils.isEmpty(birthday)) { tvBirthday.setText(birthday); } if(!TextUtils.isEmpty(idnumber)) { tvNumberID.setText(idnumber); } if(!TextUtils.isEmpty(mobile)) { tvPhoneNum.setText(mobile.substring(0,3)+"****"+mobile.substring(7,11)); linearlayout_into_update_member_bandwx.setClickable(false); }else { tvPhoneNum.setText("未绑定"); linearlayout_into_update_member_bandphone.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { View view3 = View.inflate(UpdateMemberInfoActivity.this,R.layout.bandphone_popuwindow,null); final PopupWindow reanamePopupWindow = new PopupWindow(view3,WindowManager.LayoutParams.MATCH_PARENT,WindowManager.LayoutParams.MATCH_PARENT); reanamePopupWindow.setFocusable(true); // 设置背景颜色变暗 WindowManager.LayoutParams lp2 = getWindow().getAttributes(); lp2.alpha = 0.7f; getWindow().setAttributes(lp2); reanamePopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() { @Override public void onDismiss() { WindowManager.LayoutParams lp3 = getWindow().getAttributes(); lp3.alpha = 1f; getWindow().setAttributes(lp3); } }); reanamePopupWindow.setOutsideTouchable(true); // 实例化一个ColorDrawable颜色为半透明 ColorDrawable dw3 = new ColorDrawable(0x00ffffff); reanamePopupWindow.setBackgroundDrawable(dw3); reanamePopupWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN); // 设置popWindow的显示和消失动画 reanamePopupWindow.setAnimationStyle(R.style.Mypopwindow_anim_style); reanamePopupWindow.showAtLocation(linearlayout_into_update_member_nickname,Gravity.CENTER,0,0); final EditText reaname = (EditText) view3.findViewById(R.id.et_name); view3.findViewById(R.id.btn_commit).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String name8 = reaname.getText().toString(); if(TextUtils.isEmpty(name8)) { sToast("手机号不能为空"); }else if(name8.length()!=11) { sToast("请提供正确的手机号"); }else { reanamePopupWindow.dismiss(); bandphone(name8); } } }); view3.findViewById(R.id.btn_clear).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { reanamePopupWindow.dismiss(); } }); } }); } if(!TextUtils.isEmpty(wechatopenid)) { tvWXNum.setText("已绑定"); linearlayout_into_update_member_bandwx.setClickable(false); }else { tvWXNum.setText("未绑定"); } if(!TextUtils.isEmpty(qqopenid)) { tvQQNum.setText("已绑定"); linearlayout_into_update_member_bandqq.setClickable(false); }else { tvQQNum.setText("未绑定"); } } }; dataHandler.sendEmptyMessage(0); }else { final String msg8 = data.getString("msg"); Handler dataHandler = new Handler(getContext() .getMainLooper()) { @Override public void handleMessage(final Message msg) { mZProgressHUD.hide(); sToast(msg8); } }; dataHandler.sendEmptyMessage(0); } } @Override public void onFailure(Request arg0, IOException arg1) { Handler dataHandler = new Handler(getContext() .getMainLooper()) { @Override public void handleMessage(final Message msg) { mZProgressHUD.hide(); sToast("链接超时"); } }; dataHandler.sendEmptyMessage(0); } }); } @Override protected void onResume() { // TODO Auto-generated method stub super.onResume(); if (i != 1 ){ loadMemberInfo(); }else{ i = 0; } } public void updateMemberInfo() { mZProgressHUD.show(); Map<String, String> par1 = new HashMap<String, String>(); if (photo == null) { par1.put("pic", pic); } else { par1.put("upfile:pic", BitmapUtil.bitmapToBase64(photo)); } par1.put("nickname", nickname); par1.put("name", name); String birthday = tvBirthday.getText().toString().trim(); par1.put("birthday", birthday); String s = sex; if (s.equals("保密")){ par1.put("sex", "-1"); }else if (s.equals("帅哥")){ par1.put("sex", "1"); }else if (s.equals("美女")){ par1.put("sex", "0"); } par1.put("qqopenid", qqopenid); par1.put("wechatopenid", wechatopenid); par1.put("idnumber", idnumber); par1.put("phonenunber",mobile ); HttpConnect.post(this, "member_update_information", par1, new Callback() { @Override public void onFailure(Request arg0, IOException arg1) { Handler dataHandler = new Handler(getContext() .getMainLooper()) { @Override public void handleMessage(final Message msg) { mZProgressHUD.hide(); sToast("链接超时"); } }; dataHandler.sendEmptyMessage(0); } @Override public void onResponse(Response arg0) throws IOException { JSONObject object = JSONObject.fromObject(arg0.body().string()); if (object.get("status").equals("success")) { Handler dataHandler = new Handler(getContext() .getMainLooper()) { @Override public void handleMessage(final Message msg) { mZProgressHUD.hide(); // sToast("修改成功"); } }; dataHandler.sendEmptyMessage(0); }else{ Handler dataHandler = new Handler(getContext() .getMainLooper()) { @Override public void handleMessage(final Message msg) { mZProgressHUD.hide(); sToast("修改失败"); } }; dataHandler.sendEmptyMessage(0); } } }); } /** * 裁剪图片 */ private void startPhotoZoom(Uri uri, int size) { Intent intent = new Intent("com.android.camera.action.CROP"); intent.setDataAndType(uri, "image/*"); // crop为true是设置在开启的intent中设置显示的view可以剪裁 intent.putExtra("crop", "true"); // aspectX aspectY 是宽高的比例 intent.putExtra("aspectX", 1); intent.putExtra("aspectY", 1); // outputX,outputY 是剪裁图片的宽高 intent.putExtra("outputX", size); intent.putExtra("outputY", size); /** * 此方法返回的图片只能是小图片(sumsang测试为高宽160px的图片) * 故将图片保存在Uri中,调用时将Uri转换为Bitmap,此方法还可解决miui系统不能return data的问题 */ // intent.putExtra("return-data", true); // uritempFile为Uri类变量,实例化uritempFile uritempFile = Uri.parse("file://" + "/" + Environment.getExternalStorageDirectory().getPath() + "/" + "small.jpg"); intent.putExtra(MediaStore.EXTRA_OUTPUT, uritempFile); intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString()); startActivityForResult(intent, CROP_REQUEST_CODE); } /** * 照相必备1 * */ @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == Constants.REQUEST_LOGIN || requestCode == Constants.REQUEST_APPBAR) { Tencent.onActivityResultData(requestCode, resultCode, data, listener); return; } if (resultCode != Activity.RESULT_OK) return; switch (requestCode) { case ALBUM_REQUEST_CODE: Log.i(TAG, "相册,开始裁剪"); Log.i(TAG, "相册 [ " + data + " ]"); if (data == null) { return; } startPhotoZoom(data.getData(), 300); break; case CAMERA_REQUEST_CODE: Log.i(TAG, "相机, 开始裁剪"); File picture = new File(Environment.getExternalStorageDirectory() + "/temp.jpg"); startPhotoZoom(Uri.fromFile(picture), 300); break; case CROP_REQUEST_CODE: Log.i(TAG, "相册裁剪成功"); Log.i(TAG, "裁剪以后 [ " + data + " ]"); // 将Uri图片转换为Bitmap try { photo = BitmapFactory.decodeStream(getContentResolver() .openInputStream(uritempFile)); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } // ((ImageView)findViewById(R.id.iv)) i = 1; memberHeadImg.setImageBitmap(photo); // 把图片显示在ImageView控件上 break; } } private void loadInfoComplete() { HttpConnect.post(this, "member_information_complete", null, new Callback() { @Override public void onFailure(Request arg0, IOException arg1) { Handler dataHandler = new Handler(getContext() .getMainLooper()) { @Override public void handleMessage(final Message msg) { mZProgressHUD.dismiss(); sToast("链接超时"); } }; dataHandler.sendEmptyMessage(0); } @Override public void onResponse(Response arg0) throws IOException { final JSONObject object = JSONObject.fromObject(arg0.body().string()); final String message = object.getString("msg"); if (object.get("status").equals("success")) { Handler dataHandler = new Handler(getContext() .getMainLooper()) { @Override public void handleMessage(final Message msg) { mZProgressHUD.dismiss(); String sex = object.getJSONArray("data").getJSONObject(0).getString("sex"); String name = object.getJSONArray("data").getJSONObject(0).getString("name"); String brithday = object.getJSONArray("data").getJSONObject(0).getString("brithday"); String idnumber = object.getJSONArray("data").getJSONObject(0).getString("idnumber"); String mobile = object.getJSONArray("data").getJSONObject(0).getString("mobile"); String wechatid = object.getJSONArray("data").getJSONObject(0).getString("wechatid"); String qqid = object.getJSONArray("data").getJSONObject(0).getString("qqid"); String bankcount = object.getJSONArray("data").getJSONObject(0).getString("bankcount"); String perfect = object.getJSONArray("data").getJSONObject(0).getString("perfect"); if(!TextUtils.isEmpty(perfect)) { progressBarInfoPerfectDegree.setProgress((int) (Float.parseFloat(perfect)*100)); tvInfoPerfectDegree.setText(removeDecimalPoint(String.valueOf(Float.parseFloat(perfect)*100))+"%"); } if(!TextUtils.isEmpty(sex)&&sex.equals("0")) { tv_nickname_reward_ctc.setVisibility(View.VISIBLE); setTextViewWidth(tvNickName); } if(!TextUtils.isEmpty(name)&&name.equals("0")) { tv_name_reward_ctc.setVisibility(View.VISIBLE); setTextViewWidth(tvName); } if(!TextUtils.isEmpty(brithday)&&brithday.equals("0")) { tv_birthday_reward_ctc.setVisibility(View.VISIBLE); setTextViewWidth(tvBirthday); } if(!TextUtils.isEmpty(idnumber)&&idnumber.equals("0")) { tv_idnumber_reward_ctc.setVisibility(View.VISIBLE); setTextViewWidth(tvNumberID); } if(!TextUtils.isEmpty(mobile)&&mobile.equals("0")) { tv_mobile_reward_ctc.setVisibility(View.VISIBLE); setTextViewWidth(tvPhoneNum); } if(!TextUtils.isEmpty(wechatid)&&wechatid.equals("0")) { tv_wx_reward_ctc.setVisibility(View.VISIBLE); setTextViewWidth(tvWXNum); } if(!TextUtils.isEmpty(qqid)&&qqid.equals("0")) { tv_qq_reward_ctc.setVisibility(View.VISIBLE); setTextViewWidth(tvQQNum); } if(!TextUtils.isEmpty(bankcount)&&bankcount.equals("0")) { tv_backcard_reward_ctc.setVisibility(View.VISIBLE); setTextViewWidth(tv_bankcard); } } }; dataHandler.sendEmptyMessage(0); }else{ Handler dataHandler = new Handler(getContext() .getMainLooper()) { @Override public void handleMessage(final Message msg) { mZProgressHUD.hide(); sToast(message); } }; dataHandler.sendEmptyMessage(0); } } }); } private void setTextViewWidth(TextView textView) { ViewGroup.LayoutParams layoutParams = textView.getLayoutParams(); layoutParams.width = WindowManager.LayoutParams.WRAP_CONTENT; textView.setLayoutParams(layoutParams); } /** * 百分比可能会有小数 此方法去除小数 * @param str * @return */ public String removeDecimalPoint(String str) { if(str.contains(".")) { int count = str.indexOf("."); return str.substring(0,count); } return str; } /** * 绑定手机号 */ public void bandphone(final String mobile) { mZProgressHUD.show(); Map<String, String> par = new HashMap<String, String>(); par.put("mobile", mobile); HttpConnect.post(UpdateMemberInfoActivity.this, "member_modify_mobile", par, new Callback() { @Override public void onResponse(Response arg0) throws IOException { final JSONObject data = JSONObject.fromObject(arg0.body().string()); if (data.get("status").equals("success")) { UpdateMemberInfoActivity.this.runOnUiThread(new Runnable() { @Override public void run() { sToast("绑定成功"); tvPhoneNum.setText(mobile.substring(0,3)+"****"+mobile.substring(7,11)); linearlayout_into_update_member_bandphone.setClickable(false); } }); } else { UpdateMemberInfoActivity.this.runOnUiThread(new Runnable() { @Override public void run() { sToast(data.getString("msg")); } }); } UpdateMemberInfoActivity.this.runOnUiThread(new Runnable() { @Override public void run() { mZProgressHUD.cancel(); } }); } @Override public void onFailure(Request arg0, IOException arg1) { UpdateMemberInfoActivity.this.runOnUiThread(new Runnable() { @Override public void run() { mZProgressHUD.cancel(); sToast("链接超时!"); } }); } }); } }
UTF-8
Java
56,119
java
UpdateMemberInfoActivity.java
Java
[ { "context": "\nimport util.PopBirthHelper;\r\n\r\n/**\r\n * Created by Administrator on 2016/12/12.\r\n */\r\n\r\npublic class UpdateMemberI", "end": 2221, "score": 0.4906952381134033, "start": 2208, "tag": "NAME", "value": "Administrator" }, { "context": "\r\n private static final String QQ_APP_ID = \"1105547483\";\r\n public Tencent mTencent;\r\n private Stri", "end": 3553, "score": 0.5704761743545532, "start": 3546, "tag": "KEY", "value": "5547483" }, { "context": " {\r\n nickname = name;\r\n tvNickName.setT", "end": 6966, "score": 0.5002482533454895, "start": 6962, "tag": "USERNAME", "value": "name" }, { "context": "帅哥\");\r\n sex = \"帅哥\";\r\n break;\r\n ", "end": 8970, "score": 0.9473329186439514, "start": 8968, "tag": "NAME", "value": "帅哥" } ]
null
[]
package com.tohier.cartercoin.activity; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.drawable.ColorDrawable; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.os.Message; import android.provider.MediaStore; import android.support.v4.graphics.drawable.RoundedBitmapDrawable; import android.support.v4.graphics.drawable.RoundedBitmapDrawableFactory; import android.text.TextUtils; import android.util.Log; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import android.view.WindowManager; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.PopupWindow; import android.widget.ProgressBar; import android.widget.TextView; import com.bumptech.glide.Glide; import com.bumptech.glide.request.target.BitmapImageViewTarget; import com.squareup.okhttp.Callback; import com.squareup.okhttp.Request; import com.squareup.okhttp.Response; import com.tencent.connect.UserInfo; import com.tencent.connect.common.Constants; import com.tencent.mm.sdk.modelmsg.SendAuth; import com.tencent.mm.sdk.openapi.IWXAPI; import com.tencent.mm.sdk.openapi.WXAPIFactory; import com.tencent.tauth.IUiListener; import com.tencent.tauth.Tencent; import com.tencent.tauth.UiError; import com.tohier.android.util.BitmapUtil; import com.tohier.android.util.FileUtils; import com.tohier.cartercoin.R; import com.tohier.cartercoin.config.HttpConnect; import com.tohier.cartercoin.config.LoginUser; import com.tohier.cartercoin.config.MyApplication; import net.sf.json.JSONObject; import org.json.JSONException; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.util.HashMap; import java.util.Map; import de.hdodenhof.circleimageview.CircleImageView; import util.PopBirthHelper; /** * Created by Administrator on 2016/12/12. */ public class UpdateMemberInfoActivity extends MyBackBaseActivity { private View view1; private Button btn_tuku, btn_camera, btn_quxiao; private PopupWindow window; private Bitmap photo; private static final int ALBUM_REQUEST_CODE = 1; private static final int CAMERA_REQUEST_CODE = 2; private static final int CROP_REQUEST_CODE = 4; private static final String IMAGE_UNSPECIFIED = "image/*"; private static final String TAG = "RegisterInfoActivity"; private Uri uritempFile; private int i = 0; private PopBirthHelper popBirthHelper; private CircleImageView memberHeadImg; private TextView tvNickName,tvSex,tvName,tvNumberID,tvBirthday,tvPhoneNum,tvWXNum,tvQQNum,tvComplete; private ImageView ivBack; private LinearLayout linearlayoutIntoMemberUpgrade,linearLayoutIntoAddBackCard,linearlayout_into_update_member_img,linearlayout_into_update_member_nickname,linearlayout_into_update_member_sex, linearlayout_into_update_member_reaname,linearlayout_into_update_member_idnumber,linearlayout_into_update_member_birthday,linearlayout_into_update_member_bandphone,linearlayout_into_update_member_bandwx,linearlayout_into_update_member_bandqq; private static final String QQ_APP_ID = "1105547483"; public Tencent mTencent; private String QQopenID; private static final String WX_APP_ID = "wx7ad749f6cba84064"; public IWXAPI api; private ProgressBar progressBarInfoPerfectDegree; private TextView tvInfoPerfectDegree,tv_nickname_reward_ctc,tv_name_reward_ctc,tv_idnumber_reward_ctc,tv_birthday_reward_ctc,tv_mobile_reward_ctc,tv_wx_reward_ctc,tv_qq_reward_ctc,tv_backcard_reward_ctc,tv_bankcard; private View.OnClickListener onClickListener = new View.OnClickListener() { @Override public void onClick(View v) { switch (v.getId()) { case R.id.title_back: finish(); break; case R.id.tv_complete: updateMemberInfo(); break; case R.id.linearlayout_into_member_upgrade: startActivity(new Intent(UpdateMemberInfoActivity.this,ShouHuoAddressActivity.class)); break; case R.id.linearLayout_into_add_backcard: startActivity(new Intent(UpdateMemberInfoActivity.this,AddCardActivity.class)); break; case R.id.linearlayout_into_update_member_nickname: View view2 = View.inflate(UpdateMemberInfoActivity.this,R.layout.nickname_popuwindow,null); final PopupWindow popupWindow = new PopupWindow(view2,WindowManager.LayoutParams.MATCH_PARENT,WindowManager.LayoutParams.MATCH_PARENT); // 设置背景颜色变暗 WindowManager.LayoutParams lp = getWindow().getAttributes(); lp.alpha = 0.7f; getWindow().setAttributes(lp); popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() { @Override public void onDismiss() { WindowManager.LayoutParams lp = getWindow().getAttributes(); lp.alpha = 1f; getWindow().setAttributes(lp); } }); popupWindow.setFocusable(true); popupWindow.setOutsideTouchable(true); // 实例化一个ColorDrawable颜色为半透明 ColorDrawable dw2 = new ColorDrawable(0x00ffffff); popupWindow.setBackgroundDrawable(dw2); popupWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN); // 设置popWindow的显示和消失动画 // popupWindow.setAnimationStyle(R.style.Mypopwindow_anim_style); popupWindow.setAnimationStyle(R.style.Mypopwindow_anim_style); popupWindow.showAtLocation(linearlayout_into_update_member_nickname,Gravity.CENTER,0,0); final EditText etNick = (EditText) view2.findViewById(R.id.et_name); view2.findViewById(R.id.btn_commit).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String name = etNick.getText().toString(); if(!TextUtils.isEmpty(name)) { nickname = name; tvNickName.setText(name); popupWindow.dismiss(); }else { sToast("昵称不能为空"); } } }); view2.findViewById(R.id.btn_clear).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { popupWindow.dismiss(); } }); break; case R.id.linearlayout_into_update_member_sex: AlertDialog.Builder builder1= new AlertDialog.Builder(UpdateMemberInfoActivity.this,AlertDialog.THEME_HOLO_LIGHT); builder1.setTitle("性别"); //定义列表中的选项 final String[] items = new String[]{ "保密", "美女", "帅哥" }; //设置列表选项 builder1.setItems(items, new DialogInterface.OnClickListener() { //点击任何一个列表选项都会触发这个方法 //arg1:点击的是哪一个选项 @Override public void onClick(DialogInterface dialog, int which) { switch (which){ case 0: tvSex.setText("保密"); sex = "保密"; break; case 1: tvSex.setText("美女"); sex = "美女"; break; case 2: tvSex.setText("帅哥"); sex = "帅哥"; break; } } }); // 取消选择 builder1.setNegativeButton("取消", null); builder1.show(); break; case R.id.linearlayout_into_update_member_reaname: View view3 = View.inflate(UpdateMemberInfoActivity.this,R.layout.reanname_popuwindow,null); final PopupWindow reanamePopupWindow = new PopupWindow(view3,WindowManager.LayoutParams.MATCH_PARENT,WindowManager.LayoutParams.MATCH_PARENT); reanamePopupWindow.setFocusable(true); // 设置背景颜色变暗 WindowManager.LayoutParams lp2 = getWindow().getAttributes(); lp2.alpha = 0.7f; getWindow().setAttributes(lp2); reanamePopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() { @Override public void onDismiss() { WindowManager.LayoutParams lp3 = getWindow().getAttributes(); lp3.alpha = 1f; getWindow().setAttributes(lp3); } }); reanamePopupWindow.setOutsideTouchable(true); // 实例化一个ColorDrawable颜色为半透明 ColorDrawable dw3 = new ColorDrawable(0x00ffffff); reanamePopupWindow.setBackgroundDrawable(dw3); reanamePopupWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN); // 设置popWindow的显示和消失动画 reanamePopupWindow.setAnimationStyle(R.style.Mypopwindow_anim_style); reanamePopupWindow.showAtLocation(linearlayout_into_update_member_nickname,Gravity.CENTER,0,0); final EditText reaname = (EditText) view3.findViewById(R.id.et_name); view3.findViewById(R.id.btn_commit).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String name8 = reaname.getText().toString(); if(!TextUtils.isEmpty(name8)) { name = name8; tvName.setText(name8); reanamePopupWindow.dismiss(); }else { sToast("姓名不能为空"); } } }); view3.findViewById(R.id.btn_clear).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { reanamePopupWindow.dismiss(); } }); break; case R.id.linearlayout_into_update_member_img: window = new PopupWindow(view1, WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT); // 设置背景颜色变暗 WindowManager.LayoutParams lp5 = getWindow().getAttributes(); lp5.alpha = 0.5f; getWindow().setAttributes(lp5); window.setOnDismissListener(new PopupWindow.OnDismissListener() { @Override public void onDismiss() { WindowManager.LayoutParams lp3 = getWindow().getAttributes(); lp3.alpha = 1f; getWindow().setAttributes(lp3); } }); window.setOutsideTouchable(true); // 实例化一个ColorDrawable颜色为半透明 ColorDrawable dw = new ColorDrawable(0x00ffffff); window.setBackgroundDrawable(dw); // 设置popWindow的显示和消失动画 window.setAnimationStyle(R.style.Mypopwindow_anim_style); // 在底部显示 window.showAtLocation(findViewById(R.id.fenxiang_title), Gravity.BOTTOM, 0, 0); break; case R.id.linearlayout_into_update_member_birthday: popBirthHelper.show(tvBirthday); break; case R.id.linearlayout_into_update_member_idnumber: View view4 = View.inflate(UpdateMemberInfoActivity.this,R.layout.idnumber_popuwindow,null); final PopupWindow idNumberPopupWindow = new PopupWindow(view4,WindowManager.LayoutParams.MATCH_PARENT,WindowManager.LayoutParams.MATCH_PARENT); // 设置背景颜色变暗 WindowManager.LayoutParams lp4 = getWindow().getAttributes(); lp4.alpha = 0.7f; getWindow().setAttributes(lp4); idNumberPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() { @Override public void onDismiss() { WindowManager.LayoutParams lp3 = getWindow().getAttributes(); lp3.alpha = 1f; getWindow().setAttributes(lp3); } }); idNumberPopupWindow.setFocusable(true); idNumberPopupWindow.setOutsideTouchable(true); // 实例化一个ColorDrawable颜色为半透明 ColorDrawable dw4 = new ColorDrawable(0x00ffffff); idNumberPopupWindow.setBackgroundDrawable(dw4); idNumberPopupWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN); // 设置popWindow的显示和消失动画 idNumberPopupWindow.setAnimationStyle(R.style.Mypopwindow_anim_style); idNumberPopupWindow.showAtLocation(linearlayout_into_update_member_nickname,Gravity.CENTER,0,0); final EditText etIdNumber = (EditText) view4.findViewById(R.id.et_name); view4.findViewById(R.id.btn_commit).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String name = etIdNumber.getText().toString(); if(!TextUtils.isEmpty(name)) { idnumber = name; tvNumberID.setText(name); idNumberPopupWindow.dismiss(); }else { sToast("身份证号不能为空"); } } }); view4.findViewById(R.id.btn_clear).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { idNumberPopupWindow.dismiss(); } }); break; case R.id.linearlayout_into_update_member_bandqq: mTencent = Tencent.createInstance(QQ_APP_ID, getApplicationContext()); if (!mTencent.isSessionValid()) { mTencent.login(UpdateMemberInfoActivity.this, "get_simple_userinfo", listener); } else { mTencent.logout(getApplicationContext()); mTencent.login(UpdateMemberInfoActivity.this, "get_simple_userinfo", listener); } break; case R.id.linearlayout_into_update_member_bandwx: getSharedPreferences("weixinlogin", Context.MODE_APPEND).edit().putString("login","bandphone").commit(); api = WXAPIFactory.createWXAPI(getApplicationContext(), WX_APP_ID, true); api.registerApp(WX_APP_ID); final SendAuth.Req req = new SendAuth.Req(); req.scope = "snsapi_userinfo"; req.state = "wechat_sdk_demo_test"; if (!api.sendReq(req)) { sToast("请您安装微信"); } break; } } }; private IUiListener listener = new IUiListener() { @Override public void onCancel() { sToast("您取消了QQ登录"); } @Override public void onComplete(Object arg0) { sToast("进入授权"); org.json.JSONObject jo = (org.json.JSONObject) arg0; initLoginID(jo); } @Override public void onError(UiError arg0) { sToast("QQ登录出错"); } }; private void initLoginID(org.json.JSONObject jsonObject) { try { if (jsonObject.getString("ret").equals("0")) { String token = jsonObject.getString(Constants.PARAM_ACCESS_TOKEN); String expires = jsonObject.getString(Constants.PARAM_EXPIRES_IN); QQopenID = jsonObject.getString(Constants.PARAM_OPEN_ID); mTencent.setOpenId(QQopenID); mTencent.setAccessToken(token, expires); getuserInfo(); } } catch (JSONException e) { e.printStackTrace(); } } private void getuserInfo() { UserInfo qqInfo = new UserInfo(this, mTencent.getQQToken()); qqInfo.getUserInfo(getQQinfoListener); } private IUiListener getQQinfoListener = new IUiListener() { @Override public void onComplete(Object response) { try { org.json.JSONObject jsonObject = (org.json.JSONObject) response; int ret = jsonObject.getInt("ret"); String headImgUrl = jsonObject.getString("figureurl_qq_2"); String nickname = jsonObject.getString("nickname"); Map<String, String> par1 = new HashMap<String, String>(); par1.put("id", LoginUser.getInstantiation(getApplicationContext()) .getLoginUser().getUserId()); par1.put("openid", QQopenID); HttpConnect.post(UpdateMemberInfoActivity.this, "member_modify_qq", par1, new Callback() { @Override public void onFailure(Request arg0, IOException arg1) { Handler dataHandler = new Handler( getContext().getMainLooper()) { @Override public void handleMessage( final Message msg) { // sToast("请检查你的网络状态"); } }; dataHandler.sendEmptyMessage(0); } @Override public void onResponse(Response arg0) throws IOException { JSONObject object = JSONObject.fromObject(arg0.body().string()); if (object.get("status").equals("success")) { Handler dataHandler = new Handler( getContext().getMainLooper()) { @Override public void handleMessage( final Message msg) { sToast("QQ已绑定成功"); tvQQNum.setText("已绑定"); linearlayout_into_update_member_bandqq.setClickable(false); } }; dataHandler.sendEmptyMessage(0); }else { Handler dataHandler = new Handler( getContext().getMainLooper()) { @Override public void handleMessage( final Message msg) { sToast("该QQ已有用户绑定"); } }; dataHandler.sendEmptyMessage(0); } } }); //处理自己需要的信息 } catch (Exception e) { } } @Override public void onError(UiError uiError) { } @Override public void onCancel() { } }; private String mobile; private String idnumber; private String qqopenid; private String wechatopenid; private String agent; private String introducermobile; private String sex; private String introducerid; private String name; private String gesturepassword; private String linkcode; private String type; private String nickname; private String pic; private String birthday; private String id; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_update_memberinfo_layout); MyApplication.maps.put("UpdateMemberInfoActivity",this); initData(); setUpView(); loadMemberInfo(); loadInfoComplete(); } @Override public void initData() { memberHeadImg = (CircleImageView) this.findViewById(R.id.iv_member_head_img); tvNickName = (TextView) this.findViewById(R.id.tv_nickname); tvSex = (TextView) this.findViewById(R.id.tv_sex); tvName = (TextView) this.findViewById(R.id.tv_name); tvNumberID = (TextView) this.findViewById(R.id.tv_numberID); tvBirthday = (TextView) this.findViewById(R.id.tv_birthday); tvPhoneNum = (TextView) this.findViewById(R.id.tv_mobile); tvInfoPerfectDegree = (TextView) this.findViewById(R.id.tv_info_perfect_degree); tv_nickname_reward_ctc = (TextView) this.findViewById(R.id.tv_nickname_reward_ctc); tv_name_reward_ctc = (TextView) this.findViewById(R.id.tv_name_reward_ctc); tv_idnumber_reward_ctc = (TextView) this.findViewById(R.id.tv_idnumber_reward_ctc); tv_birthday_reward_ctc = (TextView) this.findViewById(R.id.tv_birthday_reward_ctc); tv_mobile_reward_ctc = (TextView) this.findViewById(R.id.tv_mobile_reward_ctc); tv_wx_reward_ctc = (TextView) this.findViewById(R.id.tv_wx_reward_ctc); tv_qq_reward_ctc = (TextView) this.findViewById(R.id.tv_qq_reward_ctc); tv_backcard_reward_ctc = (TextView) this.findViewById(R.id.tv_backcard_reward_ctc); tvWXNum = (TextView) this.findViewById(R.id.tv_wx_num); tvQQNum = (TextView) this.findViewById(R.id.tv_qq_num); tv_bankcard = (TextView) this.findViewById(R.id.tv_bankcard); tvComplete = (TextView) this.findViewById(R.id.tv_complete); ivBack = (ImageView) this.findViewById(R.id.title_back); progressBarInfoPerfectDegree = (ProgressBar) this.findViewById(R.id.progressBar_info_perfect_degree); view1 = View.inflate(this, R.layout.photo_popupwindow_item, null); btn_tuku = (Button) view1 .findViewById(R.id.photo_popupwindow_item_photo); btn_camera = (Button) view1 .findViewById(R.id.photo_popupwindow_item_camera); btn_quxiao = (Button) view1 .findViewById(R.id.photo_popupwindow_item_look); linearlayoutIntoMemberUpgrade = (LinearLayout) this.findViewById(R.id.linearlayout_into_member_upgrade); linearLayoutIntoAddBackCard = (LinearLayout) this.findViewById(R.id.linearLayout_into_add_backcard); linearlayout_into_update_member_img = (LinearLayout) this.findViewById(R.id.linearlayout_into_update_member_img); linearlayout_into_update_member_nickname = (LinearLayout) this.findViewById(R.id.linearlayout_into_update_member_nickname); linearlayout_into_update_member_sex = (LinearLayout) this.findViewById(R.id.linearlayout_into_update_member_sex); linearlayout_into_update_member_reaname = (LinearLayout) this.findViewById(R.id.linearlayout_into_update_member_reaname); linearlayout_into_update_member_idnumber = (LinearLayout) this.findViewById(R.id.linearlayout_into_update_member_idnumber); linearlayout_into_update_member_birthday = (LinearLayout) this.findViewById(R.id.linearlayout_into_update_member_birthday); linearlayout_into_update_member_bandphone = (LinearLayout) this.findViewById(R.id.linearlayout_into_update_member_bandphone); linearlayout_into_update_member_bandwx = (LinearLayout) this.findViewById(R.id.linearlayout_into_update_member_bandwx); linearlayout_into_update_member_bandqq = (LinearLayout) this.findViewById(R.id.linearlayout_into_update_member_bandqq); popBirthHelper = new PopBirthHelper(this); popBirthHelper.setOnClickOkListener(new PopBirthHelper.OnClickOkListener() { @Override public void onClickOk(String birthday) { tvBirthday.setText(birthday); } }); } private void setUpView() { ivBack.setOnClickListener(onClickListener); tvComplete.setOnClickListener(onClickListener); linearlayoutIntoMemberUpgrade.setOnClickListener(onClickListener); linearLayoutIntoAddBackCard.setOnClickListener(onClickListener); linearlayout_into_update_member_nickname.setOnClickListener(onClickListener); linearlayout_into_update_member_sex.setOnClickListener(onClickListener); linearlayout_into_update_member_img.setOnClickListener(onClickListener); linearlayout_into_update_member_reaname.setOnClickListener(onClickListener); linearlayout_into_update_member_birthday.setOnClickListener(onClickListener); linearlayout_into_update_member_idnumber.setOnClickListener(onClickListener); linearlayout_into_update_member_bandqq.setOnClickListener(onClickListener); linearlayout_into_update_member_bandwx.setOnClickListener(onClickListener); /** * 头像处理 */ btn_tuku.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (FileUtils.checkSDCard()){ window.dismiss(); Intent intent = new Intent(Intent.ACTION_PICK, null); intent.setDataAndType( MediaStore.Images.Media.EXTERNAL_CONTENT_URI, IMAGE_UNSPECIFIED); startActivityForResult(intent, ALBUM_REQUEST_CODE); }else{ UpdateMemberInfoActivity.this.sToast("请先插入SD卡"); } } }); btn_camera.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (FileUtils.checkSDCard()){ window.dismiss(); Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File( Environment.getExternalStorageDirectory(), "temp.jpg"))); startActivityForResult(intent, CAMERA_REQUEST_CODE); }else{ UpdateMemberInfoActivity.this.sToast("请先插入SD卡"); } } }); btn_quxiao.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (FileUtils.checkSDCard()){ window.dismiss(); } } }); } /** * 获取会员的信息 */ public void loadMemberInfo() { mZProgressHUD.show(); HttpConnect.post(UpdateMemberInfoActivity.this, "member_info", null, new Callback() { @Override public void onResponse(Response arg0) throws IOException { JSONObject data = JSONObject.fromObject(arg0.body().string()); if (data.get("status").equals("success")) { id = data.getJSONArray("data").getJSONObject(0).getString("ID"); birthday = data.getJSONArray("data").getJSONObject(0).getString("birthday"); pic = data.getJSONArray("data").getJSONObject(0).getString("pic"); nickname = data.getJSONArray("data").getJSONObject(0).getString("nickname"); type = data.getJSONArray("data").getJSONObject(0).getString("type"); linkcode = data.getJSONArray("data").getJSONObject(0).getString("linkcode"); gesturepassword = data.getJSONArray("data").getJSONObject(0).getString("gesturespassword"); name = data.getJSONArray("data").getJSONObject(0).getString("name"); introducerid = data.getJSONArray("data").getJSONObject(0).getString("introducerid"); sex = data.getJSONArray("data").getJSONObject(0).getString("sex"); introducermobile = data.getJSONArray("data").getJSONObject(0).getString("introducermobile"); agent = data.getJSONArray("data").getJSONObject(0).getString("agent"); wechatopenid = data.getJSONArray("data").getJSONObject(0).getString("wechatopenid"); qqopenid = data.getJSONArray("data").getJSONObject(0).getString("qqopenid"); idnumber = data.getJSONArray("data").getJSONObject(0).getString("idnumber"); mobile = data.getJSONArray("data").getJSONObject(0).getString("mobile"); Handler dataHandler = new Handler(getContext() .getMainLooper()) { @Override public void handleMessage(final Message msg) { loadInfoComplete(); /** * 设置头像 以及昵称 */ if (pic!=null){ Glide.with(UpdateMemberInfoActivity.this).load(pic).asBitmap().centerCrop().into(new BitmapImageViewTarget(memberHeadImg) { @Override protected void setResource(Bitmap resource) { RoundedBitmapDrawable circularBitmapDrawable = RoundedBitmapDrawableFactory.create(getResources(), resource); circularBitmapDrawable.setCircular(true); memberHeadImg.setImageDrawable(circularBitmapDrawable); } }); } if(!TextUtils.isEmpty(nickname)) { tvNickName.setText(nickname); } if(!TextUtils.isEmpty(sex)) { if(sex.equals("保密")) { tvSex.setText("保密"); }else if(sex.equals("美女")) { tvSex.setText("美女"); }else if(sex.equals("帅哥")) { tvSex.setText("帅哥"); } } if(!TextUtils.isEmpty(name)) { tvName.setText(name); } if(!TextUtils.isEmpty(birthday)) { tvBirthday.setText(birthday); } if(!TextUtils.isEmpty(idnumber)) { tvNumberID.setText(idnumber); } if(!TextUtils.isEmpty(mobile)) { tvPhoneNum.setText(mobile.substring(0,3)+"****"+mobile.substring(7,11)); linearlayout_into_update_member_bandwx.setClickable(false); }else { tvPhoneNum.setText("未绑定"); linearlayout_into_update_member_bandphone.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { View view3 = View.inflate(UpdateMemberInfoActivity.this,R.layout.bandphone_popuwindow,null); final PopupWindow reanamePopupWindow = new PopupWindow(view3,WindowManager.LayoutParams.MATCH_PARENT,WindowManager.LayoutParams.MATCH_PARENT); reanamePopupWindow.setFocusable(true); // 设置背景颜色变暗 WindowManager.LayoutParams lp2 = getWindow().getAttributes(); lp2.alpha = 0.7f; getWindow().setAttributes(lp2); reanamePopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() { @Override public void onDismiss() { WindowManager.LayoutParams lp3 = getWindow().getAttributes(); lp3.alpha = 1f; getWindow().setAttributes(lp3); } }); reanamePopupWindow.setOutsideTouchable(true); // 实例化一个ColorDrawable颜色为半透明 ColorDrawable dw3 = new ColorDrawable(0x00ffffff); reanamePopupWindow.setBackgroundDrawable(dw3); reanamePopupWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN); // 设置popWindow的显示和消失动画 reanamePopupWindow.setAnimationStyle(R.style.Mypopwindow_anim_style); reanamePopupWindow.showAtLocation(linearlayout_into_update_member_nickname,Gravity.CENTER,0,0); final EditText reaname = (EditText) view3.findViewById(R.id.et_name); view3.findViewById(R.id.btn_commit).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String name8 = reaname.getText().toString(); if(TextUtils.isEmpty(name8)) { sToast("手机号不能为空"); }else if(name8.length()!=11) { sToast("请提供正确的手机号"); }else { reanamePopupWindow.dismiss(); bandphone(name8); } } }); view3.findViewById(R.id.btn_clear).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { reanamePopupWindow.dismiss(); } }); } }); } if(!TextUtils.isEmpty(wechatopenid)) { tvWXNum.setText("已绑定"); linearlayout_into_update_member_bandwx.setClickable(false); }else { tvWXNum.setText("未绑定"); } if(!TextUtils.isEmpty(qqopenid)) { tvQQNum.setText("已绑定"); linearlayout_into_update_member_bandqq.setClickable(false); }else { tvQQNum.setText("未绑定"); } } }; dataHandler.sendEmptyMessage(0); }else { final String msg8 = data.getString("msg"); Handler dataHandler = new Handler(getContext() .getMainLooper()) { @Override public void handleMessage(final Message msg) { mZProgressHUD.hide(); sToast(msg8); } }; dataHandler.sendEmptyMessage(0); } } @Override public void onFailure(Request arg0, IOException arg1) { Handler dataHandler = new Handler(getContext() .getMainLooper()) { @Override public void handleMessage(final Message msg) { mZProgressHUD.hide(); sToast("链接超时"); } }; dataHandler.sendEmptyMessage(0); } }); } @Override protected void onResume() { // TODO Auto-generated method stub super.onResume(); if (i != 1 ){ loadMemberInfo(); }else{ i = 0; } } public void updateMemberInfo() { mZProgressHUD.show(); Map<String, String> par1 = new HashMap<String, String>(); if (photo == null) { par1.put("pic", pic); } else { par1.put("upfile:pic", BitmapUtil.bitmapToBase64(photo)); } par1.put("nickname", nickname); par1.put("name", name); String birthday = tvBirthday.getText().toString().trim(); par1.put("birthday", birthday); String s = sex; if (s.equals("保密")){ par1.put("sex", "-1"); }else if (s.equals("帅哥")){ par1.put("sex", "1"); }else if (s.equals("美女")){ par1.put("sex", "0"); } par1.put("qqopenid", qqopenid); par1.put("wechatopenid", wechatopenid); par1.put("idnumber", idnumber); par1.put("phonenunber",mobile ); HttpConnect.post(this, "member_update_information", par1, new Callback() { @Override public void onFailure(Request arg0, IOException arg1) { Handler dataHandler = new Handler(getContext() .getMainLooper()) { @Override public void handleMessage(final Message msg) { mZProgressHUD.hide(); sToast("链接超时"); } }; dataHandler.sendEmptyMessage(0); } @Override public void onResponse(Response arg0) throws IOException { JSONObject object = JSONObject.fromObject(arg0.body().string()); if (object.get("status").equals("success")) { Handler dataHandler = new Handler(getContext() .getMainLooper()) { @Override public void handleMessage(final Message msg) { mZProgressHUD.hide(); // sToast("修改成功"); } }; dataHandler.sendEmptyMessage(0); }else{ Handler dataHandler = new Handler(getContext() .getMainLooper()) { @Override public void handleMessage(final Message msg) { mZProgressHUD.hide(); sToast("修改失败"); } }; dataHandler.sendEmptyMessage(0); } } }); } /** * 裁剪图片 */ private void startPhotoZoom(Uri uri, int size) { Intent intent = new Intent("com.android.camera.action.CROP"); intent.setDataAndType(uri, "image/*"); // crop为true是设置在开启的intent中设置显示的view可以剪裁 intent.putExtra("crop", "true"); // aspectX aspectY 是宽高的比例 intent.putExtra("aspectX", 1); intent.putExtra("aspectY", 1); // outputX,outputY 是剪裁图片的宽高 intent.putExtra("outputX", size); intent.putExtra("outputY", size); /** * 此方法返回的图片只能是小图片(sumsang测试为高宽160px的图片) * 故将图片保存在Uri中,调用时将Uri转换为Bitmap,此方法还可解决miui系统不能return data的问题 */ // intent.putExtra("return-data", true); // uritempFile为Uri类变量,实例化uritempFile uritempFile = Uri.parse("file://" + "/" + Environment.getExternalStorageDirectory().getPath() + "/" + "small.jpg"); intent.putExtra(MediaStore.EXTRA_OUTPUT, uritempFile); intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString()); startActivityForResult(intent, CROP_REQUEST_CODE); } /** * 照相必备1 * */ @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == Constants.REQUEST_LOGIN || requestCode == Constants.REQUEST_APPBAR) { Tencent.onActivityResultData(requestCode, resultCode, data, listener); return; } if (resultCode != Activity.RESULT_OK) return; switch (requestCode) { case ALBUM_REQUEST_CODE: Log.i(TAG, "相册,开始裁剪"); Log.i(TAG, "相册 [ " + data + " ]"); if (data == null) { return; } startPhotoZoom(data.getData(), 300); break; case CAMERA_REQUEST_CODE: Log.i(TAG, "相机, 开始裁剪"); File picture = new File(Environment.getExternalStorageDirectory() + "/temp.jpg"); startPhotoZoom(Uri.fromFile(picture), 300); break; case CROP_REQUEST_CODE: Log.i(TAG, "相册裁剪成功"); Log.i(TAG, "裁剪以后 [ " + data + " ]"); // 将Uri图片转换为Bitmap try { photo = BitmapFactory.decodeStream(getContentResolver() .openInputStream(uritempFile)); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } // ((ImageView)findViewById(R.id.iv)) i = 1; memberHeadImg.setImageBitmap(photo); // 把图片显示在ImageView控件上 break; } } private void loadInfoComplete() { HttpConnect.post(this, "member_information_complete", null, new Callback() { @Override public void onFailure(Request arg0, IOException arg1) { Handler dataHandler = new Handler(getContext() .getMainLooper()) { @Override public void handleMessage(final Message msg) { mZProgressHUD.dismiss(); sToast("链接超时"); } }; dataHandler.sendEmptyMessage(0); } @Override public void onResponse(Response arg0) throws IOException { final JSONObject object = JSONObject.fromObject(arg0.body().string()); final String message = object.getString("msg"); if (object.get("status").equals("success")) { Handler dataHandler = new Handler(getContext() .getMainLooper()) { @Override public void handleMessage(final Message msg) { mZProgressHUD.dismiss(); String sex = object.getJSONArray("data").getJSONObject(0).getString("sex"); String name = object.getJSONArray("data").getJSONObject(0).getString("name"); String brithday = object.getJSONArray("data").getJSONObject(0).getString("brithday"); String idnumber = object.getJSONArray("data").getJSONObject(0).getString("idnumber"); String mobile = object.getJSONArray("data").getJSONObject(0).getString("mobile"); String wechatid = object.getJSONArray("data").getJSONObject(0).getString("wechatid"); String qqid = object.getJSONArray("data").getJSONObject(0).getString("qqid"); String bankcount = object.getJSONArray("data").getJSONObject(0).getString("bankcount"); String perfect = object.getJSONArray("data").getJSONObject(0).getString("perfect"); if(!TextUtils.isEmpty(perfect)) { progressBarInfoPerfectDegree.setProgress((int) (Float.parseFloat(perfect)*100)); tvInfoPerfectDegree.setText(removeDecimalPoint(String.valueOf(Float.parseFloat(perfect)*100))+"%"); } if(!TextUtils.isEmpty(sex)&&sex.equals("0")) { tv_nickname_reward_ctc.setVisibility(View.VISIBLE); setTextViewWidth(tvNickName); } if(!TextUtils.isEmpty(name)&&name.equals("0")) { tv_name_reward_ctc.setVisibility(View.VISIBLE); setTextViewWidth(tvName); } if(!TextUtils.isEmpty(brithday)&&brithday.equals("0")) { tv_birthday_reward_ctc.setVisibility(View.VISIBLE); setTextViewWidth(tvBirthday); } if(!TextUtils.isEmpty(idnumber)&&idnumber.equals("0")) { tv_idnumber_reward_ctc.setVisibility(View.VISIBLE); setTextViewWidth(tvNumberID); } if(!TextUtils.isEmpty(mobile)&&mobile.equals("0")) { tv_mobile_reward_ctc.setVisibility(View.VISIBLE); setTextViewWidth(tvPhoneNum); } if(!TextUtils.isEmpty(wechatid)&&wechatid.equals("0")) { tv_wx_reward_ctc.setVisibility(View.VISIBLE); setTextViewWidth(tvWXNum); } if(!TextUtils.isEmpty(qqid)&&qqid.equals("0")) { tv_qq_reward_ctc.setVisibility(View.VISIBLE); setTextViewWidth(tvQQNum); } if(!TextUtils.isEmpty(bankcount)&&bankcount.equals("0")) { tv_backcard_reward_ctc.setVisibility(View.VISIBLE); setTextViewWidth(tv_bankcard); } } }; dataHandler.sendEmptyMessage(0); }else{ Handler dataHandler = new Handler(getContext() .getMainLooper()) { @Override public void handleMessage(final Message msg) { mZProgressHUD.hide(); sToast(message); } }; dataHandler.sendEmptyMessage(0); } } }); } private void setTextViewWidth(TextView textView) { ViewGroup.LayoutParams layoutParams = textView.getLayoutParams(); layoutParams.width = WindowManager.LayoutParams.WRAP_CONTENT; textView.setLayoutParams(layoutParams); } /** * 百分比可能会有小数 此方法去除小数 * @param str * @return */ public String removeDecimalPoint(String str) { if(str.contains(".")) { int count = str.indexOf("."); return str.substring(0,count); } return str; } /** * 绑定手机号 */ public void bandphone(final String mobile) { mZProgressHUD.show(); Map<String, String> par = new HashMap<String, String>(); par.put("mobile", mobile); HttpConnect.post(UpdateMemberInfoActivity.this, "member_modify_mobile", par, new Callback() { @Override public void onResponse(Response arg0) throws IOException { final JSONObject data = JSONObject.fromObject(arg0.body().string()); if (data.get("status").equals("success")) { UpdateMemberInfoActivity.this.runOnUiThread(new Runnable() { @Override public void run() { sToast("绑定成功"); tvPhoneNum.setText(mobile.substring(0,3)+"****"+mobile.substring(7,11)); linearlayout_into_update_member_bandphone.setClickable(false); } }); } else { UpdateMemberInfoActivity.this.runOnUiThread(new Runnable() { @Override public void run() { sToast(data.getString("msg")); } }); } UpdateMemberInfoActivity.this.runOnUiThread(new Runnable() { @Override public void run() { mZProgressHUD.cancel(); } }); } @Override public void onFailure(Request arg0, IOException arg1) { UpdateMemberInfoActivity.this.runOnUiThread(new Runnable() { @Override public void run() { mZProgressHUD.cancel(); sToast("链接超时!"); } }); } }); } }
56,119
0.483753
0.478698
1,222
43.004093
32.901417
269
false
false
0
0
0
0
0
0
0.581015
false
false
12
fcd4c5c346179ab09db60dc6ff0f4ff883b53389
6,897,717,501,419
6a700daef0569dd367f9d82f998da42ddebfb2d4
/TPO/TPO-6/src/hello.java
1c7d7cee682c16caa9a4781211a683526c721023
[]
no_license
McMelloy/UTP-PJATK
https://github.com/McMelloy/UTP-PJATK
1702cc6c8d1f5cc675733523ab99c1dbda4a72ff
a4050b8f03f20d40795f8e1fe17b51e8ad05853b
refs/heads/master
2022-10-27T08:44:53.120000
2020-04-22T09:09:51
2020-04-22T09:09:51
175,717,042
1
0
null
false
2022-10-04T23:56:24
2019-03-14T23:48:34
2020-04-22T09:14:11
2022-10-04T23:56:22
105,492
0
0
1
Java
false
false
import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; @WebServlet("/add") public class hello extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { response.setContentType("text/plain"); System.out.println("Controller"); PrintWriter out = response.getWriter(); String a = request.getParameter("a"); String b = request.getParameter("b"); System.out.println(a + " " +b); try { int answer = Integer.parseInt(a) + Integer.parseInt(b); out.println(answer); System.out.println(answer); }catch (NumberFormatException e){ out.println("Invalid input"); }catch (NullPointerException e){ out.println("Invalid input"); } } public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException { doGet(request,response); } }
UTF-8
Java
1,195
java
hello.java
Java
[]
null
[]
import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; @WebServlet("/add") public class hello extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { response.setContentType("text/plain"); System.out.println("Controller"); PrintWriter out = response.getWriter(); String a = request.getParameter("a"); String b = request.getParameter("b"); System.out.println(a + " " +b); try { int answer = Integer.parseInt(a) + Integer.parseInt(b); out.println(answer); System.out.println(answer); }catch (NumberFormatException e){ out.println("Invalid input"); }catch (NullPointerException e){ out.println("Invalid input"); } } public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException { doGet(request,response); } }
1,195
0.646862
0.646862
37
31.297297
21.183706
73
false
false
0
0
0
0
0
0
0.567568
false
false
12
7bb96e0c7fabb2ee822d4ee5672855628f8cf058
35,261,681,501,717
76307eda4e60efd39760010888957609aa2529f7
/src/test/java/com/test/file/InputValidatorTest.java
f56db5adb788346537a85d0d053717c21ac8dd91
[]
no_license
chiragdesai2005/readfile-demo
https://github.com/chiragdesai2005/readfile-demo
ed3b4fb9301fffecc27811913dce25876890fe0a
4ca3610cb3b507a40400732e406bd3b6f6dbdaf5
refs/heads/master
2021-07-21T01:35:41.687000
2019-11-25T10:33:12
2019-11-25T10:33:12
223,660,034
0
0
null
false
2020-10-13T17:41:52
2019-11-23T22:14:11
2019-11-25T10:33:21
2020-10-13T17:41:50
9
0
0
1
Java
false
false
package com.test.file; import org.junit.Test; import static org.junit.Assert.assertEquals; public class InputValidatorTest { @Test(expected = RuntimeException.class) public void shouldThrowExceptionWhenArgsDoNotMatch() throws Exception { String[] args = new String[1]; assertEquals("", InputValidator.validate(args)); } @Test(expected = RuntimeException.class) public void shouldThrowExceptionWhenInvalidArgs() throws Exception { String[] args = new String[2]; args[0] = ""; assertEquals("", InputValidator.validate(args)); } @Test(expected = RuntimeException.class) public void shouldThrowExceptionWhenInvalidThreadCount() throws Exception { String[] args = {"./tt.txt", "0"}; assertEquals("", InputValidator.validate(args)); } @Test(expected = RuntimeException.class) public void shouldThrowExceptionWhenStringThreadCount() throws Exception { String[] args = {"./tt.txt", "abc"}; assertEquals("", InputValidator.validate(args)); } @Test(expected = RuntimeException.class) public void shouldThrowExceptionWhenFileNotFound() throws Exception { String[] args = {"./tt.txt", "2"}; assertEquals("", InputValidator.validate(args)); } }
UTF-8
Java
1,288
java
InputValidatorTest.java
Java
[]
null
[]
package com.test.file; import org.junit.Test; import static org.junit.Assert.assertEquals; public class InputValidatorTest { @Test(expected = RuntimeException.class) public void shouldThrowExceptionWhenArgsDoNotMatch() throws Exception { String[] args = new String[1]; assertEquals("", InputValidator.validate(args)); } @Test(expected = RuntimeException.class) public void shouldThrowExceptionWhenInvalidArgs() throws Exception { String[] args = new String[2]; args[0] = ""; assertEquals("", InputValidator.validate(args)); } @Test(expected = RuntimeException.class) public void shouldThrowExceptionWhenInvalidThreadCount() throws Exception { String[] args = {"./tt.txt", "0"}; assertEquals("", InputValidator.validate(args)); } @Test(expected = RuntimeException.class) public void shouldThrowExceptionWhenStringThreadCount() throws Exception { String[] args = {"./tt.txt", "abc"}; assertEquals("", InputValidator.validate(args)); } @Test(expected = RuntimeException.class) public void shouldThrowExceptionWhenFileNotFound() throws Exception { String[] args = {"./tt.txt", "2"}; assertEquals("", InputValidator.validate(args)); } }
1,288
0.675466
0.671584
39
32.025642
26.182287
79
false
false
0
0
0
0
0
0
0.564103
false
false
12
a2e14feb394564b64bb881226a87be03c6ab2c5d
3,513,283,275,433
596a53d820c09ddaadb3658c846df933a125162d
/trunk/fastcodingtools/src/com/fastcodingtools/util/io/ZipUtils.java
8936cc93cce88e4bcaad1547aeb8141284cd9c73
[ "Apache-2.0" ]
permissive
mutyalart/fastcodingtools
https://github.com/mutyalart/fastcodingtools
bf3b2bd9cec188e72cdedf419931366748b04501
61eb671b63b75c223c1c1b96551400c160132853
refs/heads/master
2021-01-10T06:50:51.141000
2008-03-27T18:24:09
2008-03-27T18:24:09
51,544,946
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package com.fastcodingtools.util.io; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.Enumeration; import java.util.List; import java.util.zip.ZipEntry; import java.util.zip.ZipException; import java.util.zip.ZipFile; import java.util.zip.ZipOutputStream; import org.apache.log4j.Logger; import com.fastcodingtools.util.log.log4j.LogFastLevel; /** * @author macg * */ public class ZipUtils { private static final Logger logger = Logger.getLogger(ZipUtils.class.getName()); private static final int TAMANHO_BUFFER = 1024 * 10; public static String ziparArquivo(String pathArquivoOriginal, String pathDiretorioDestino, String extensaoArquivoComprimido) { File arquivoOriginal = new File(pathArquivoOriginal); String pathArquivoZipado = pathDiretorioDestino + FileUtils.getFileNameWithoutExtension(pathArquivoOriginal); pathArquivoZipado = pathArquivoZipado + extensaoArquivoComprimido; try { criarZip(new File(pathArquivoZipado), new File[] {arquivoOriginal }); return pathArquivoZipado; } catch (IOException e) { logger.log(LogFastLevel.LOGFAST,e.getMessage(),e); return null; } } public static String[] extrairZip(String pathArquivoOriginal){ String[] pathsArquivosExtraidos = new String[] {}; try { pathsArquivosExtraidos = extrairZip(new File(pathArquivoOriginal), new File(pathArquivoOriginal).getParentFile()); } catch (IOException e) { logger.log(LogFastLevel.LOGFAST,e.getMessage(),e); } return pathsArquivosExtraidos; } public static void extrairZip(String pathArquivoOriginal,String pathDiretorioDestino){ try { extrairZip(new File(pathArquivoOriginal), new File(pathDiretorioDestino)); } catch (IOException e) { logger.log(LogFastLevel.LOGFAST,e.getMessage(),e); } } /** * Abre o arquivo zip e extrai a lista de entradas do zip. * * @param arquivo * File que representa o arquivo zip em disco. * @return List com objetos ZipEntry. * @throws ZipException * @throws IOException */ public static List listarEntradasZip(File arquivo) throws IOException { List<ZipEntry> entradasDoZip = new ArrayList<ZipEntry>(); ZipFile zip = null; try { zip = new ZipFile(arquivo); Enumeration e = zip.entries(); ZipEntry entrada; while (e.hasMoreElements()) { entrada = (ZipEntry) e.nextElement(); entradasDoZip.add(entrada); } } finally { if (zip != null) { zip.close(); } } return entradasDoZip; } /** * Cria um arquivo zip em disco. * * @param arquivoZip * Arquivo zip a ser criado. * @param arquivos * Arquivos e diretório a serem compactados dentro do zip. * @return Retorna um List com as entradas (ZipEntry) salvas. * @throws ZipException * @throws IOException */ public static List criarZip(File arquivoZip, File[] arquivos) throws IOException { FileOutputStream fos = null; BufferedOutputStream bos = null; FileUtils.createDirs(arquivoZip.getParent()); try { fos = new FileOutputStream(arquivoZip); bos = new BufferedOutputStream(fos, TAMANHO_BUFFER); List listaEntradasZip = criarZip(bos, arquivos); return listaEntradasZip; } finally { if (bos != null) { try { bos.close(); } catch (Exception e) { } } if (fos != null) { try { fos.close(); } catch (Exception e) { } } } } /** * Cria um zip gravando os dados no OutputStream passado como argumento, * adicionando os arquivos informados. * * @param os * OutputStream onde será gravado o zip. * @param arquivos * Arquivos e diretório a serem compactados dentro do zip. * @return Retorna um List com as entradas (ZipEntry) salvas. * @throws ZipException * @throws IOException */ public static List criarZip(OutputStream os, File[] arquivos) throws IOException { if ((arquivos == null) || (arquivos.length < 1)) { throw new ZipException("Adicione ao menos um arquivo ou diretório"); } List<ZipEntry> listaEntradasZip = new ArrayList<ZipEntry>(); ZipOutputStream zos = null; try { zos = new ZipOutputStream(os); for (File arquivo : arquivos) { String caminhoInicial = arquivo.getParent(); List<ZipEntry> novasEntradas = adicionarArquivoNoZip(zos, arquivo, caminhoInicial); if (novasEntradas != null) { listaEntradasZip.addAll(novasEntradas); } } } finally { if (zos != null) { try { zos.close(); } catch (Exception e) { } } } return listaEntradasZip; } /** * Adiciona o arquivo ou arquivos dentro do diretório no output do zip. * * @param zos * @param arquivo * @param caminhoInicial * @return Retorna um List de entradas (ZipEntry) salvas no zip. * @throws IOException */ private static List<ZipEntry> adicionarArquivoNoZip(ZipOutputStream zos, File arquivo, String caminhoInicial) throws IOException { List<ZipEntry> listaEntradasZip = new ArrayList<ZipEntry>(); FileInputStream fis = null; BufferedInputStream bis = null; byte buffer[] = new byte[TAMANHO_BUFFER]; try { // diretórios não são adicionados if (arquivo.isDirectory()) { // recursivamente adiciona os arquivos dos diretórios abaixo File[] arquivos = arquivo.listFiles(); for (File arquivo1 : arquivos) { List<ZipEntry> novasEntradas = adicionarArquivoNoZip(zos, arquivo1, caminhoInicial); if (novasEntradas != null) { listaEntradasZip.addAll(novasEntradas); } } return listaEntradasZip; } String caminhoEntradaZip = null; int idx = arquivo.getAbsolutePath().indexOf(caminhoInicial); if (idx >= 0) { // calcula os diretórios a partir do diretório inicial // isso serve para não colocar uma entrada com o caminho // completo caminhoEntradaZip = arquivo.getAbsolutePath().substring(idx + caminhoInicial.length() + 1); } ZipEntry entrada = new ZipEntry(caminhoEntradaZip); zos.putNextEntry(entrada); zos.setMethod(ZipOutputStream.DEFLATED); fis = new FileInputStream(arquivo); bis = new BufferedInputStream(fis, TAMANHO_BUFFER); int bytesLidos; while ((bytesLidos = bis.read(buffer, 0, TAMANHO_BUFFER)) != -1) { zos.write(buffer, 0, bytesLidos); } listaEntradasZip.add(entrada); } finally { if (bis != null) { try { bis.close(); } catch (Exception e) { } } if (fis != null) { try { fis.close(); } catch (Exception e) { } } } return listaEntradasZip; } /** * Extrai o zip informado para o diretório informado. * * @param arquivoZip * Arquivo zip a ser extraído. * @param diretorio * Diretório onde o zip será extraido. * @throws ZipException * @throws IOException */ public static String[] extrairZip(File arquivoZip, File diretorio) throws IOException { ZipFile zip = null; File arquivo; InputStream is = null; OutputStream os = null; byte[] buffer = new byte[TAMANHO_BUFFER]; ArrayList<String> pathsArquivosExtraidos = new ArrayList<String>(); try { // cria diretório informado, caso não exista if (!diretorio.exists()) { diretorio.mkdirs(); } if (!diretorio.exists() || !diretorio.isDirectory()) { throw new IOException("Informe um diretório válido"); } zip = new ZipFile(arquivoZip); Enumeration e = zip.entries(); while (e.hasMoreElements()) { ZipEntry entrada = (ZipEntry) e.nextElement(); arquivo = new File(diretorio, entrada.getName()); pathsArquivosExtraidos.add(arquivo.getPath()); // se for diretório inexistente, cria a estrutura // e pula pra próxima entrada if (entrada.isDirectory() && !arquivo.exists()) { arquivo.mkdirs(); } // se a estrutura de diretórios não existe, cria if (!arquivo.getParentFile().exists()) { arquivo.getParentFile().mkdirs(); } try { // lê o arquivo do zip e grava em disco is = zip.getInputStream(entrada); os = new FileOutputStream(arquivo); int bytesLidos; if (is == null) { throw new ZipException("Erro ao ler a entrada do zip: " + entrada.getName()); } while ((bytesLidos = is.read(buffer)) > 0) { os.write(buffer, 0, bytesLidos); } } finally { if (is != null) { try { is.close(); } catch (Exception ex) { } } if (os != null) { try { os.close(); } catch (Exception ex) { } } } } } finally { if (zip != null) { try { zip.close(); } catch (Exception e) { } } } return pathsArquivosExtraidos.toArray(new String[pathsArquivosExtraidos.size()]); } }
ISO-8859-1
Java
10,203
java
ZipUtils.java
Java
[ { "context": "til.log.log4j.LogFastLevel;\r\n\r\n\r\n\r\n/**\r\n * @author macg\r\n *\r\n */\r\npublic class ZipUtils {\r\n\r\n\tprivate sta", "end": 1458, "score": 0.999451756477356, "start": 1454, "tag": "USERNAME", "value": "macg" } ]
null
[]
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package com.fastcodingtools.util.io; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.Enumeration; import java.util.List; import java.util.zip.ZipEntry; import java.util.zip.ZipException; import java.util.zip.ZipFile; import java.util.zip.ZipOutputStream; import org.apache.log4j.Logger; import com.fastcodingtools.util.log.log4j.LogFastLevel; /** * @author macg * */ public class ZipUtils { private static final Logger logger = Logger.getLogger(ZipUtils.class.getName()); private static final int TAMANHO_BUFFER = 1024 * 10; public static String ziparArquivo(String pathArquivoOriginal, String pathDiretorioDestino, String extensaoArquivoComprimido) { File arquivoOriginal = new File(pathArquivoOriginal); String pathArquivoZipado = pathDiretorioDestino + FileUtils.getFileNameWithoutExtension(pathArquivoOriginal); pathArquivoZipado = pathArquivoZipado + extensaoArquivoComprimido; try { criarZip(new File(pathArquivoZipado), new File[] {arquivoOriginal }); return pathArquivoZipado; } catch (IOException e) { logger.log(LogFastLevel.LOGFAST,e.getMessage(),e); return null; } } public static String[] extrairZip(String pathArquivoOriginal){ String[] pathsArquivosExtraidos = new String[] {}; try { pathsArquivosExtraidos = extrairZip(new File(pathArquivoOriginal), new File(pathArquivoOriginal).getParentFile()); } catch (IOException e) { logger.log(LogFastLevel.LOGFAST,e.getMessage(),e); } return pathsArquivosExtraidos; } public static void extrairZip(String pathArquivoOriginal,String pathDiretorioDestino){ try { extrairZip(new File(pathArquivoOriginal), new File(pathDiretorioDestino)); } catch (IOException e) { logger.log(LogFastLevel.LOGFAST,e.getMessage(),e); } } /** * Abre o arquivo zip e extrai a lista de entradas do zip. * * @param arquivo * File que representa o arquivo zip em disco. * @return List com objetos ZipEntry. * @throws ZipException * @throws IOException */ public static List listarEntradasZip(File arquivo) throws IOException { List<ZipEntry> entradasDoZip = new ArrayList<ZipEntry>(); ZipFile zip = null; try { zip = new ZipFile(arquivo); Enumeration e = zip.entries(); ZipEntry entrada; while (e.hasMoreElements()) { entrada = (ZipEntry) e.nextElement(); entradasDoZip.add(entrada); } } finally { if (zip != null) { zip.close(); } } return entradasDoZip; } /** * Cria um arquivo zip em disco. * * @param arquivoZip * Arquivo zip a ser criado. * @param arquivos * Arquivos e diretório a serem compactados dentro do zip. * @return Retorna um List com as entradas (ZipEntry) salvas. * @throws ZipException * @throws IOException */ public static List criarZip(File arquivoZip, File[] arquivos) throws IOException { FileOutputStream fos = null; BufferedOutputStream bos = null; FileUtils.createDirs(arquivoZip.getParent()); try { fos = new FileOutputStream(arquivoZip); bos = new BufferedOutputStream(fos, TAMANHO_BUFFER); List listaEntradasZip = criarZip(bos, arquivos); return listaEntradasZip; } finally { if (bos != null) { try { bos.close(); } catch (Exception e) { } } if (fos != null) { try { fos.close(); } catch (Exception e) { } } } } /** * Cria um zip gravando os dados no OutputStream passado como argumento, * adicionando os arquivos informados. * * @param os * OutputStream onde será gravado o zip. * @param arquivos * Arquivos e diretório a serem compactados dentro do zip. * @return Retorna um List com as entradas (ZipEntry) salvas. * @throws ZipException * @throws IOException */ public static List criarZip(OutputStream os, File[] arquivos) throws IOException { if ((arquivos == null) || (arquivos.length < 1)) { throw new ZipException("Adicione ao menos um arquivo ou diretório"); } List<ZipEntry> listaEntradasZip = new ArrayList<ZipEntry>(); ZipOutputStream zos = null; try { zos = new ZipOutputStream(os); for (File arquivo : arquivos) { String caminhoInicial = arquivo.getParent(); List<ZipEntry> novasEntradas = adicionarArquivoNoZip(zos, arquivo, caminhoInicial); if (novasEntradas != null) { listaEntradasZip.addAll(novasEntradas); } } } finally { if (zos != null) { try { zos.close(); } catch (Exception e) { } } } return listaEntradasZip; } /** * Adiciona o arquivo ou arquivos dentro do diretório no output do zip. * * @param zos * @param arquivo * @param caminhoInicial * @return Retorna um List de entradas (ZipEntry) salvas no zip. * @throws IOException */ private static List<ZipEntry> adicionarArquivoNoZip(ZipOutputStream zos, File arquivo, String caminhoInicial) throws IOException { List<ZipEntry> listaEntradasZip = new ArrayList<ZipEntry>(); FileInputStream fis = null; BufferedInputStream bis = null; byte buffer[] = new byte[TAMANHO_BUFFER]; try { // diretórios não são adicionados if (arquivo.isDirectory()) { // recursivamente adiciona os arquivos dos diretórios abaixo File[] arquivos = arquivo.listFiles(); for (File arquivo1 : arquivos) { List<ZipEntry> novasEntradas = adicionarArquivoNoZip(zos, arquivo1, caminhoInicial); if (novasEntradas != null) { listaEntradasZip.addAll(novasEntradas); } } return listaEntradasZip; } String caminhoEntradaZip = null; int idx = arquivo.getAbsolutePath().indexOf(caminhoInicial); if (idx >= 0) { // calcula os diretórios a partir do diretório inicial // isso serve para não colocar uma entrada com o caminho // completo caminhoEntradaZip = arquivo.getAbsolutePath().substring(idx + caminhoInicial.length() + 1); } ZipEntry entrada = new ZipEntry(caminhoEntradaZip); zos.putNextEntry(entrada); zos.setMethod(ZipOutputStream.DEFLATED); fis = new FileInputStream(arquivo); bis = new BufferedInputStream(fis, TAMANHO_BUFFER); int bytesLidos; while ((bytesLidos = bis.read(buffer, 0, TAMANHO_BUFFER)) != -1) { zos.write(buffer, 0, bytesLidos); } listaEntradasZip.add(entrada); } finally { if (bis != null) { try { bis.close(); } catch (Exception e) { } } if (fis != null) { try { fis.close(); } catch (Exception e) { } } } return listaEntradasZip; } /** * Extrai o zip informado para o diretório informado. * * @param arquivoZip * Arquivo zip a ser extraído. * @param diretorio * Diretório onde o zip será extraido. * @throws ZipException * @throws IOException */ public static String[] extrairZip(File arquivoZip, File diretorio) throws IOException { ZipFile zip = null; File arquivo; InputStream is = null; OutputStream os = null; byte[] buffer = new byte[TAMANHO_BUFFER]; ArrayList<String> pathsArquivosExtraidos = new ArrayList<String>(); try { // cria diretório informado, caso não exista if (!diretorio.exists()) { diretorio.mkdirs(); } if (!diretorio.exists() || !diretorio.isDirectory()) { throw new IOException("Informe um diretório válido"); } zip = new ZipFile(arquivoZip); Enumeration e = zip.entries(); while (e.hasMoreElements()) { ZipEntry entrada = (ZipEntry) e.nextElement(); arquivo = new File(diretorio, entrada.getName()); pathsArquivosExtraidos.add(arquivo.getPath()); // se for diretório inexistente, cria a estrutura // e pula pra próxima entrada if (entrada.isDirectory() && !arquivo.exists()) { arquivo.mkdirs(); } // se a estrutura de diretórios não existe, cria if (!arquivo.getParentFile().exists()) { arquivo.getParentFile().mkdirs(); } try { // lê o arquivo do zip e grava em disco is = zip.getInputStream(entrada); os = new FileOutputStream(arquivo); int bytesLidos; if (is == null) { throw new ZipException("Erro ao ler a entrada do zip: " + entrada.getName()); } while ((bytesLidos = is.read(buffer)) > 0) { os.write(buffer, 0, bytesLidos); } } finally { if (is != null) { try { is.close(); } catch (Exception ex) { } } if (os != null) { try { os.close(); } catch (Exception ex) { } } } } } finally { if (zip != null) { try { zip.close(); } catch (Exception e) { } } } return pathsArquivosExtraidos.toArray(new String[pathsArquivosExtraidos.size()]); } }
10,203
0.644429
0.642268
337
28.20178
24.959093
131
false
false
0
0
0
0
0
0
2.52819
false
false
12
3ccc531d8c1e6bccbefc9d03d6ae0b7d185d7282
6,751,688,609,722
88fa8dad46b98b779249a9b08824dc68b725fa3e
/src/main/test/java/designModel/FacadeModel/hasFacadeModel/Test.java
e8766b727153848d42fa5601a3a6a090d40c90e9
[]
no_license
jwlong/topbnt_spring
https://github.com/jwlong/topbnt_spring
15dac18a7d301dffbf8d8e16cd83f1796ba0ddea
2ebc7e89fb13bad8eaea84c3afee00ac0914cfa4
refs/heads/master
2021-01-22T07:42:49.203000
2018-07-07T15:49:34
2018-07-07T15:49:34
102,312,052
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package designModel.FacadeModel.hasFacadeModel; /** * Created by longjinwen on 27/10/2017. */ public class Test { public static void main(String[] args) { Customer customer = new Customer(); customer.haveDinner(); } }
UTF-8
Java
245
java
Test.java
Java
[ { "context": "del.FacadeModel.hasFacadeModel;\n\n/**\n * Created by longjinwen on 27/10/2017.\n */\npublic class Test {\n public", "end": 77, "score": 0.9994407296180725, "start": 67, "tag": "USERNAME", "value": "longjinwen" } ]
null
[]
package designModel.FacadeModel.hasFacadeModel; /** * Created by longjinwen on 27/10/2017. */ public class Test { public static void main(String[] args) { Customer customer = new Customer(); customer.haveDinner(); } }
245
0.661224
0.628571
11
21.272728
18.689281
47
false
false
0
0
0
0
0
0
0.272727
false
false
12
8023bd1a0336091ea37802512fda53dd5f17fd34
19,318,762,961,518
859aa35e7af5c5a3b1437a6727760b76340b5d03
/src/delphos/AnalisisTendencia.java
33002f4684c1e018ad31c969e28ba14115c12fa2
[]
no_license
mjtenmat/ATHENA
https://github.com/mjtenmat/ATHENA
275d94a73d1fc0a20361746fa7b180a5bea35b2b
73f1a8071cad928b35b05e0555b787b9ec272b5f
refs/heads/master
2021-01-13T13:46:02.941000
2018-09-26T10:10:21
2018-09-26T10:10:21
76,355,089
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package delphos; import java.util.ArrayList; import delphos.AnalisisTendencia.CategoriasLicitaciones; import delphos.AnalisisTendencia.Tipo; public class AnalisisTendencia { public static enum Tipo {PATENTES, LICITACIONES}; public static enum CategoriasPatentes {SECTOR, PAIS, INVENTOR, SOLICITANTE, CONTENIDO}; public static enum CategoriasLicitaciones {SECTOR, PAIS, TIPO, SOLICITANTE, CONTENIDO}; public static enum TipoGeneral {LICITACION_SECTOR, LICITACION_PAIS, LICITACION_TIPO, LICITACION_SOLICITANTE, LICITACION_CONTENIDO, PATENTE_SECTOR, PATENTE_PAIS, PATENTE_INVENTOR, PATENTE_SOLICITANTE, PATENTE_CONTENIDO}; private Tendencia tendencia; private ArrayList<EntradaAnalisisTendencia> listaPatenteSector = new ArrayList<EntradaAnalisisTendencia>(); private ArrayList<EntradaAnalisisTendencia> listaPatentePais = new ArrayList<EntradaAnalisisTendencia>(); private ArrayList<EntradaAnalisisTendencia> listaPatenteInventor = new ArrayList<EntradaAnalisisTendencia>(); private ArrayList<EntradaAnalisisTendencia> listaPatenteSolicitante = new ArrayList<EntradaAnalisisTendencia>(); private ArrayList<EntradaAnalisisTendencia> listaPatenteContenido = new ArrayList<EntradaAnalisisTendencia>(); private ArrayList<EntradaAnalisisTendencia> listaLicitacionSector = new ArrayList<EntradaAnalisisTendencia>(); private ArrayList<EntradaAnalisisTendencia> listaLicitacionPais = new ArrayList<EntradaAnalisisTendencia>(); private ArrayList<EntradaAnalisisTendencia> listaLicitacionTipo = new ArrayList<EntradaAnalisisTendencia>(); private ArrayList<EntradaAnalisisTendencia> listaLicitacionSolicitante = new ArrayList<EntradaAnalisisTendencia>(); private ArrayList<EntradaAnalisisTendencia> listaLicitacionContenido = new ArrayList<EntradaAnalisisTendencia>(); public Tendencia getTendencia() { return tendencia; } public ArrayList<EntradaAnalisisTendencia> getListaPatenteSector() { return listaPatenteSector; } public ArrayList<EntradaAnalisisTendencia> getListaPatentePais() { return listaPatentePais; } public ArrayList<EntradaAnalisisTendencia> getListaPatenteInventor() { return listaPatenteInventor; } public ArrayList<EntradaAnalisisTendencia> getListaPatenteSolicitante() { return listaPatenteSolicitante; } public ArrayList<EntradaAnalisisTendencia> getListaPatenteContenido() { return listaPatenteContenido; } public ArrayList<EntradaAnalisisTendencia> getListaLicitacionSector() { return listaLicitacionSector; } public ArrayList<EntradaAnalisisTendencia> getListaLicitacionPais() { return listaLicitacionPais; } public ArrayList<EntradaAnalisisTendencia> getListaLicitacionTipo() { return listaLicitacionTipo; } public ArrayList<EntradaAnalisisTendencia> getListaLicitacionSolicitante() { return listaLicitacionSolicitante; } public ArrayList<EntradaAnalisisTendencia> getListaLicitacionContenido() { return listaLicitacionContenido; } private ArrayList<EntradaAnalisisTendencia> getListaPorTipoGeneral(TipoGeneral tipo){ ArrayList<EntradaAnalisisTendencia> lista = null; switch(tipo){ case LICITACION_SECTOR: lista = this.getListaLicitacionSector(); break; case LICITACION_PAIS: lista = this.getListaLicitacionPais(); break; case LICITACION_TIPO: lista = this.getListaLicitacionTipo(); break; case LICITACION_SOLICITANTE: lista = this.getListaLicitacionSolicitante(); break; case LICITACION_CONTENIDO: lista = this.getListaLicitacionContenido(); break; case PATENTE_SECTOR: lista = this.getListaPatenteSector(); break; case PATENTE_PAIS: lista = this.getListaPatentePais(); break; case PATENTE_INVENTOR: lista = this.getListaPatenteInventor(); break; case PATENTE_SOLICITANTE: lista = this.getListaPatenteSolicitante(); break; case PATENTE_CONTENIDO: lista = this.getListaPatenteContenido(); break; } return lista; } public void aniadirListaALista(TipoGeneral tipo, ArrayList<String> listaTerminos) { for(String termino : listaTerminos){ termino = termino.trim(); if (termino != null) if (termino.length() > 1) aniadirALista(tipo, termino); } } public void aniadirALista(TipoGeneral tipo, String termino) { ArrayList<EntradaAnalisisTendencia> lista = getListaPorTipoGeneral(tipo); boolean encontrado = false; for(EntradaAnalisisTendencia entrada : lista){ if (termino.equals(entrada.getTermino())){ encontrado = true; entrada.incrementar(); break; } } if (!encontrado) lista.add(new EntradaAnalisisTendencia(termino, 1)); } }
UTF-8
Java
4,546
java
AnalisisTendencia.java
Java
[]
null
[]
package delphos; import java.util.ArrayList; import delphos.AnalisisTendencia.CategoriasLicitaciones; import delphos.AnalisisTendencia.Tipo; public class AnalisisTendencia { public static enum Tipo {PATENTES, LICITACIONES}; public static enum CategoriasPatentes {SECTOR, PAIS, INVENTOR, SOLICITANTE, CONTENIDO}; public static enum CategoriasLicitaciones {SECTOR, PAIS, TIPO, SOLICITANTE, CONTENIDO}; public static enum TipoGeneral {LICITACION_SECTOR, LICITACION_PAIS, LICITACION_TIPO, LICITACION_SOLICITANTE, LICITACION_CONTENIDO, PATENTE_SECTOR, PATENTE_PAIS, PATENTE_INVENTOR, PATENTE_SOLICITANTE, PATENTE_CONTENIDO}; private Tendencia tendencia; private ArrayList<EntradaAnalisisTendencia> listaPatenteSector = new ArrayList<EntradaAnalisisTendencia>(); private ArrayList<EntradaAnalisisTendencia> listaPatentePais = new ArrayList<EntradaAnalisisTendencia>(); private ArrayList<EntradaAnalisisTendencia> listaPatenteInventor = new ArrayList<EntradaAnalisisTendencia>(); private ArrayList<EntradaAnalisisTendencia> listaPatenteSolicitante = new ArrayList<EntradaAnalisisTendencia>(); private ArrayList<EntradaAnalisisTendencia> listaPatenteContenido = new ArrayList<EntradaAnalisisTendencia>(); private ArrayList<EntradaAnalisisTendencia> listaLicitacionSector = new ArrayList<EntradaAnalisisTendencia>(); private ArrayList<EntradaAnalisisTendencia> listaLicitacionPais = new ArrayList<EntradaAnalisisTendencia>(); private ArrayList<EntradaAnalisisTendencia> listaLicitacionTipo = new ArrayList<EntradaAnalisisTendencia>(); private ArrayList<EntradaAnalisisTendencia> listaLicitacionSolicitante = new ArrayList<EntradaAnalisisTendencia>(); private ArrayList<EntradaAnalisisTendencia> listaLicitacionContenido = new ArrayList<EntradaAnalisisTendencia>(); public Tendencia getTendencia() { return tendencia; } public ArrayList<EntradaAnalisisTendencia> getListaPatenteSector() { return listaPatenteSector; } public ArrayList<EntradaAnalisisTendencia> getListaPatentePais() { return listaPatentePais; } public ArrayList<EntradaAnalisisTendencia> getListaPatenteInventor() { return listaPatenteInventor; } public ArrayList<EntradaAnalisisTendencia> getListaPatenteSolicitante() { return listaPatenteSolicitante; } public ArrayList<EntradaAnalisisTendencia> getListaPatenteContenido() { return listaPatenteContenido; } public ArrayList<EntradaAnalisisTendencia> getListaLicitacionSector() { return listaLicitacionSector; } public ArrayList<EntradaAnalisisTendencia> getListaLicitacionPais() { return listaLicitacionPais; } public ArrayList<EntradaAnalisisTendencia> getListaLicitacionTipo() { return listaLicitacionTipo; } public ArrayList<EntradaAnalisisTendencia> getListaLicitacionSolicitante() { return listaLicitacionSolicitante; } public ArrayList<EntradaAnalisisTendencia> getListaLicitacionContenido() { return listaLicitacionContenido; } private ArrayList<EntradaAnalisisTendencia> getListaPorTipoGeneral(TipoGeneral tipo){ ArrayList<EntradaAnalisisTendencia> lista = null; switch(tipo){ case LICITACION_SECTOR: lista = this.getListaLicitacionSector(); break; case LICITACION_PAIS: lista = this.getListaLicitacionPais(); break; case LICITACION_TIPO: lista = this.getListaLicitacionTipo(); break; case LICITACION_SOLICITANTE: lista = this.getListaLicitacionSolicitante(); break; case LICITACION_CONTENIDO: lista = this.getListaLicitacionContenido(); break; case PATENTE_SECTOR: lista = this.getListaPatenteSector(); break; case PATENTE_PAIS: lista = this.getListaPatentePais(); break; case PATENTE_INVENTOR: lista = this.getListaPatenteInventor(); break; case PATENTE_SOLICITANTE: lista = this.getListaPatenteSolicitante(); break; case PATENTE_CONTENIDO: lista = this.getListaPatenteContenido(); break; } return lista; } public void aniadirListaALista(TipoGeneral tipo, ArrayList<String> listaTerminos) { for(String termino : listaTerminos){ termino = termino.trim(); if (termino != null) if (termino.length() > 1) aniadirALista(tipo, termino); } } public void aniadirALista(TipoGeneral tipo, String termino) { ArrayList<EntradaAnalisisTendencia> lista = getListaPorTipoGeneral(tipo); boolean encontrado = false; for(EntradaAnalisisTendencia entrada : lista){ if (termino.equals(entrada.getTermino())){ encontrado = true; entrada.incrementar(); break; } } if (!encontrado) lista.add(new EntradaAnalisisTendencia(termino, 1)); } }
4,546
0.798944
0.798504
117
37.854702
36.772171
220
false
false
0
0
0
0
0
0
2.452991
false
false
12
4a59b1f75b27910ce1fcecbafebbe2a2ac1c34be
25,623,774,927,306
457fefa37f03685bf6d0ad2337742d4a8c5571eb
/src/org/totemcraftmc/tcplugin/TCGUI/Commands/ResguiadminCommand.java
d89f4292561dc69368e3f1e317676182447a03e7
[ "MIT" ]
permissive
theTd/TCGUI
https://github.com/theTd/TCGUI
6589b6e12c033edbb740417d8fec89c1a8b04f0a
d0f5b3e773eec5ac7c3e2ccfaa66102f5c932f4e
refs/heads/master
2015-09-24T19:56:26.785000
2015-09-02T01:16:43
2015-09-02T01:16:43
38,505,408
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.totemcraftmc.tcplugin.TCGUI.Commands; import org.bukkit.ChatColor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.totemcraftmc.tcplugin.TCGUI.ResidenceManageGUI.ResidenceManageGUI; import org.totemcraftmc.tcplugin.TCLib.CommandLib.RootCommand; import com.bekvon.bukkit.residence.Residence; import com.bekvon.bukkit.residence.protection.ClaimedResidence; public class ResguiadminCommand extends RootCommand{ public ResguiadminCommand() { super("resguiadmin", false, true); } @Override protected boolean onCall(boolean playerRun, CommandSender sender, Player player, String[] args) { Player p = player; if(!Residence.getPermissionManager().isResidenceAdmin(p)){ return true; } if(args.length>1){ return false; } ClaimedResidence res; if(args.length==1){ res = Residence.getResidenceManager().getByName(args[0]); }else{ res = Residence.getResidenceManager().getByLoc(p.getLocation()); } if(res==null){ if(args.length==1){ p.sendMessage(ChatColor.RED+"没有叫做 "+args[0]+" 的领地"); }else{ p.sendMessage(ChatColor.RED+"这个位置没有领地"); } return true; } new ResidenceManageGUI(p, res).open();; return true; } }
GB18030
Java
1,311
java
ResguiadminCommand.java
Java
[]
null
[]
package org.totemcraftmc.tcplugin.TCGUI.Commands; import org.bukkit.ChatColor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.totemcraftmc.tcplugin.TCGUI.ResidenceManageGUI.ResidenceManageGUI; import org.totemcraftmc.tcplugin.TCLib.CommandLib.RootCommand; import com.bekvon.bukkit.residence.Residence; import com.bekvon.bukkit.residence.protection.ClaimedResidence; public class ResguiadminCommand extends RootCommand{ public ResguiadminCommand() { super("resguiadmin", false, true); } @Override protected boolean onCall(boolean playerRun, CommandSender sender, Player player, String[] args) { Player p = player; if(!Residence.getPermissionManager().isResidenceAdmin(p)){ return true; } if(args.length>1){ return false; } ClaimedResidence res; if(args.length==1){ res = Residence.getResidenceManager().getByName(args[0]); }else{ res = Residence.getResidenceManager().getByLoc(p.getLocation()); } if(res==null){ if(args.length==1){ p.sendMessage(ChatColor.RED+"没有叫做 "+args[0]+" 的领地"); }else{ p.sendMessage(ChatColor.RED+"这个位置没有领地"); } return true; } new ResidenceManageGUI(p, res).open();; return true; } }
1,311
0.704137
0.700234
50
23.620001
24.643774
98
false
false
0
0
0
0
0
0
2.06
false
false
12
c840e58d8336808e197e9859d6fa06abcddc35a7
4,681,514,378,231
529e5e633a18784284fcd561213461dc37a0f25b
/app/src/main/java/com/upenn/chriswang1990/sunshine/sync/retrofit/WeatherAPI.java
4f5a3b538e0a1be976264593e9d9f4153797354c
[]
no_license
chriswang1990/Sunshine
https://github.com/chriswang1990/Sunshine
e3cf5756c097074c43dea5e7d5cd3f4510ee28e4
6ca3987502a36c6bf16c9fc5b604b3afd668b4cc
refs/heads/master
2020-12-23T22:28:35.844000
2017-01-08T21:13:16
2017-01-08T21:13:16
56,131,220
1
0
null
false
2016-07-31T18:31:24
2016-04-13T07:38:53
2016-05-26T18:24:17
2016-07-31T18:31:24
2,576
1
0
0
Java
null
null
package com.upenn.chriswang1990.sunshine.sync.retrofit; import retrofit2.Response; import retrofit2.http.GET; import retrofit2.http.Query; import rx.Observable; public interface WeatherAPI { String ENDPOINT = "http://api.openweathermap.org"; @GET("data/2.5/forecast/daily") Observable<Response<WeatherResponse>> getResponse(@Query("q") String locationQuery, @Query("lat") String locationLatitude, @Query("lon") String locationLongitude, @Query("mode") String format, @Query("units") String units, @Query("cnt") int numDays, @Query("APPID") String appID); }
UTF-8
Java
889
java
WeatherAPI.java
Java
[]
null
[]
package com.upenn.chriswang1990.sunshine.sync.retrofit; import retrofit2.Response; import retrofit2.http.GET; import retrofit2.http.Query; import rx.Observable; public interface WeatherAPI { String ENDPOINT = "http://api.openweathermap.org"; @GET("data/2.5/forecast/daily") Observable<Response<WeatherResponse>> getResponse(@Query("q") String locationQuery, @Query("lat") String locationLatitude, @Query("lon") String locationLongitude, @Query("mode") String format, @Query("units") String units, @Query("cnt") int numDays, @Query("APPID") String appID); }
889
0.484814
0.474691
18
48.388889
32.770481
92
false
false
0
0
0
0
0
0
0.722222
false
false
12
8ca55ec2c827362a4094c38bc8c447667651011c
32,942,399,201,968
4cc56097211d4e936336192893ce7729d50896a3
/lore-molecules/src/test/java/ca/on/mshri/lore/molecules/operations/FetchUniprotSeqsTest.java
1ccd222dabcf6f6d19c1f5c40d9ab74a64ffb717
[]
no_license
jweile/lore
https://github.com/jweile/lore
1df8e4269b7d277f0360e5fca7823527e6689dd4
1b30295edf469f1d826b576d63ebd869ae254d4f
refs/heads/master
2021-09-24T09:01:34.943000
2014-03-03T18:58:51
2014-03-03T18:58:51
225,717,054
0
0
null
false
2021-09-20T20:33:04
2019-12-03T21:13:53
2019-12-03T21:14:28
2021-09-20T20:33:04
4,342
0
0
11
Java
false
false
/* * Copyright (C) 2013 Department of Molecular Genetics, University of Toronto * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package ca.on.mshri.lore.molecules.operations; import ca.on.mshri.lore.molecules.MoleculesModel; import ca.on.mshri.lore.molecules.Protein; import com.hp.hpl.jena.ontology.OntModelSpec; import com.hp.hpl.jena.rdf.model.ModelFactory; import junit.framework.TestCase; /** * * @author Jochen Weile <jochenweile@gmail.com> */ public class FetchUniprotSeqsTest extends TestCase { public FetchUniprotSeqsTest(String testName) { super(testName); } @Override protected void setUp() throws Exception { super.setUp(); } @Override protected void tearDown() throws Exception { super.tearDown(); } public void test() throws Exception { // // MoleculesModel model = new MoleculesModel(OntModelSpec.OWL_MEM, ModelFactory.createDefaultModel()); // // Protein protein = Protein.createOrGet(model, model.UNIPROT, "O00151"); // // FetchUniprotSeqs op = new FetchUniprotSeqs(); // op.setModel(model); // op.setParameter(op.selectionP, op.selectionP.validate(protein.getURI())); // op.run(); // // String sequence = protein.getSequence(); // assertNotNull(sequence); // assertTrue(sequence.length() > 0); // // System.out.println(sequence); // } }
UTF-8
Java
2,089
java
FetchUniprotSeqsTest.java
Java
[ { "context": "mport junit.framework.TestCase;\n\n/**\n *\n * @author Jochen Weile <jochenweile@gmail.com>\n */\npublic class FetchUni", "end": 1053, "score": 0.9991825222969055, "start": 1041, "tag": "NAME", "value": "Jochen Weile" }, { "context": "mework.TestCase;\n\n/**\n *\n * @author Jochen Weile <jochenweile@gmail.com>\n */\npublic class FetchUniprotSeqsTest extends Te", "end": 1076, "score": 0.9999338388442993, "start": 1055, "tag": "EMAIL", "value": "jochenweile@gmail.com" } ]
null
[]
/* * Copyright (C) 2013 Department of Molecular Genetics, University of Toronto * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package ca.on.mshri.lore.molecules.operations; import ca.on.mshri.lore.molecules.MoleculesModel; import ca.on.mshri.lore.molecules.Protein; import com.hp.hpl.jena.ontology.OntModelSpec; import com.hp.hpl.jena.rdf.model.ModelFactory; import junit.framework.TestCase; /** * * @author <NAME> <<EMAIL>> */ public class FetchUniprotSeqsTest extends TestCase { public FetchUniprotSeqsTest(String testName) { super(testName); } @Override protected void setUp() throws Exception { super.setUp(); } @Override protected void tearDown() throws Exception { super.tearDown(); } public void test() throws Exception { // // MoleculesModel model = new MoleculesModel(OntModelSpec.OWL_MEM, ModelFactory.createDefaultModel()); // // Protein protein = Protein.createOrGet(model, model.UNIPROT, "O00151"); // // FetchUniprotSeqs op = new FetchUniprotSeqs(); // op.setModel(model); // op.setParameter(op.selectionP, op.selectionP.validate(protein.getURI())); // op.run(); // // String sequence = protein.getSequence(); // assertNotNull(sequence); // assertTrue(sequence.length() > 0); // // System.out.println(sequence); // } }
2,069
0.677358
0.672092
63
32.15873
27.770149
109
false
false
0
0
0
0
0
0
0.460317
false
false
12
102384e4db2fd1d99838b985f2297b74ce15f464
33,174,327,426,919
0422c449c424827b2397eaa62b27a693578d376b
/src/main/java/com/qi/weibo/dao/FocusDAO.java
b22d954b085c67c6e76697e6e28f8a1a89140e98
[]
no_license
Hbase-qi/hbaseapi20
https://github.com/Hbase-qi/hbaseapi20
991e750fd2dedad3abb4c311531bac1d80398a81
5fb10dcd962744614a84234f70e6c8631d30e3d1
refs/heads/master
2021-01-02T18:47:13.107000
2020-02-11T12:11:43
2020-02-11T12:11:43
239,749,958
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.qi.weibo.dao; import java.util.Arrays; import org.apache.hadoop.hbase.client.Get; import org.apache.hadoop.hbase.client.Put; import org.apache.hadoop.hbase.client.Result; import org.apache.hadoop.hbase.client.ResultScanner; import org.apache.hadoop.hbase.client.Scan; import org.apache.hadoop.hbase.client.Table; import org.apache.hadoop.hbase.filter.BinaryComparator; import org.apache.hadoop.hbase.filter.BinaryPrefixComparator; import org.apache.hadoop.hbase.filter.CompareFilter.CompareOp; import org.apache.hadoop.hbase.filter.FamilyFilter; import org.apache.hadoop.hbase.filter.Filter; import org.apache.hadoop.hbase.filter.FilterList; import org.apache.hadoop.hbase.filter.FilterList.Operator; import org.apache.hadoop.hbase.filter.QualifierFilter; import org.apache.hadoop.hbase.filter.RowFilter; import org.apache.hadoop.hbase.util.Bytes; import com.qi.HBaseUtil; import com.qi.weibo.WeiBoUtils; public class FocusDAO { private Table table; public void setTable() { this.table = HBaseUtil.getTable("bd20:w_user"); } public void focusOperate(String currentUerId, String otherUserId) throws Exception { byte[] currentUerRowkey = WeiBoUtils.getRowKeyByUserId(currentUerId,table); Get get=new Get(currentUerRowkey); Result result=table.get(get); HBaseUtil.printResult(result); Put currentPut=new Put(currentUerRowkey); currentPut.addColumn(Bytes.toBytes("c"), Bytes.toBytes("f"+otherUserId), Bytes.toBytes("0")); table.put(currentPut); byte[] otherUerRowkey = WeiBoUtils.getRowKeyByUserId(otherUserId,table); Put otherPut=new Put(otherUerRowkey); otherPut.addColumn(Bytes.toBytes("c"), Bytes.toBytes("u"+currentUerId), Bytes.toBytes("0")); table.put(otherPut); } public void searchFocusUser(String userId) throws Exception { Filter rowFilter=new RowFilter(CompareOp.EQUAL, new BinaryPrefixComparator(Bytes.toBytes(userId))); Filter familyFilter = new FamilyFilter(CompareOp.EQUAL, new BinaryComparator(Bytes.toBytes("c"))); Filter qualifierFilter = new QualifierFilter(CompareOp.EQUAL, new BinaryPrefixComparator(Bytes.toBytes("f"))); FilterList filterList = new FilterList(Operator.MUST_PASS_ALL); filterList.addFilter(rowFilter); filterList.addFilter(familyFilter); filterList.addFilter(qualifierFilter); Scan scan = new Scan(); scan.setFilter(filterList); ResultScanner resultScanner = table.getScanner(scan); HBaseUtil.printResultScanner(resultScanner); } public void searchOtherUser(String userId) throws Exception { Filter rowFilter=new RowFilter(CompareOp.EQUAL, new BinaryPrefixComparator(Bytes.toBytes(userId))); Filter familyFilter = new FamilyFilter(CompareOp.EQUAL, new BinaryComparator(Bytes.toBytes("c"))); Filter qualifierFilter = new QualifierFilter(CompareOp.EQUAL, new BinaryPrefixComparator(Bytes.toBytes("u"))); FilterList filterList = new FilterList(Operator.MUST_PASS_ALL); filterList.addFilter(rowFilter); filterList.addFilter(familyFilter); filterList.addFilter(qualifierFilter); Scan scan = new Scan(); scan.setFilter(filterList); ResultScanner resultScanner = table.getScanner(scan); HBaseUtil.printResultScanner(resultScanner); } }
UTF-8
Java
3,194
java
FocusDAO.java
Java
[]
null
[]
package com.qi.weibo.dao; import java.util.Arrays; import org.apache.hadoop.hbase.client.Get; import org.apache.hadoop.hbase.client.Put; import org.apache.hadoop.hbase.client.Result; import org.apache.hadoop.hbase.client.ResultScanner; import org.apache.hadoop.hbase.client.Scan; import org.apache.hadoop.hbase.client.Table; import org.apache.hadoop.hbase.filter.BinaryComparator; import org.apache.hadoop.hbase.filter.BinaryPrefixComparator; import org.apache.hadoop.hbase.filter.CompareFilter.CompareOp; import org.apache.hadoop.hbase.filter.FamilyFilter; import org.apache.hadoop.hbase.filter.Filter; import org.apache.hadoop.hbase.filter.FilterList; import org.apache.hadoop.hbase.filter.FilterList.Operator; import org.apache.hadoop.hbase.filter.QualifierFilter; import org.apache.hadoop.hbase.filter.RowFilter; import org.apache.hadoop.hbase.util.Bytes; import com.qi.HBaseUtil; import com.qi.weibo.WeiBoUtils; public class FocusDAO { private Table table; public void setTable() { this.table = HBaseUtil.getTable("bd20:w_user"); } public void focusOperate(String currentUerId, String otherUserId) throws Exception { byte[] currentUerRowkey = WeiBoUtils.getRowKeyByUserId(currentUerId,table); Get get=new Get(currentUerRowkey); Result result=table.get(get); HBaseUtil.printResult(result); Put currentPut=new Put(currentUerRowkey); currentPut.addColumn(Bytes.toBytes("c"), Bytes.toBytes("f"+otherUserId), Bytes.toBytes("0")); table.put(currentPut); byte[] otherUerRowkey = WeiBoUtils.getRowKeyByUserId(otherUserId,table); Put otherPut=new Put(otherUerRowkey); otherPut.addColumn(Bytes.toBytes("c"), Bytes.toBytes("u"+currentUerId), Bytes.toBytes("0")); table.put(otherPut); } public void searchFocusUser(String userId) throws Exception { Filter rowFilter=new RowFilter(CompareOp.EQUAL, new BinaryPrefixComparator(Bytes.toBytes(userId))); Filter familyFilter = new FamilyFilter(CompareOp.EQUAL, new BinaryComparator(Bytes.toBytes("c"))); Filter qualifierFilter = new QualifierFilter(CompareOp.EQUAL, new BinaryPrefixComparator(Bytes.toBytes("f"))); FilterList filterList = new FilterList(Operator.MUST_PASS_ALL); filterList.addFilter(rowFilter); filterList.addFilter(familyFilter); filterList.addFilter(qualifierFilter); Scan scan = new Scan(); scan.setFilter(filterList); ResultScanner resultScanner = table.getScanner(scan); HBaseUtil.printResultScanner(resultScanner); } public void searchOtherUser(String userId) throws Exception { Filter rowFilter=new RowFilter(CompareOp.EQUAL, new BinaryPrefixComparator(Bytes.toBytes(userId))); Filter familyFilter = new FamilyFilter(CompareOp.EQUAL, new BinaryComparator(Bytes.toBytes("c"))); Filter qualifierFilter = new QualifierFilter(CompareOp.EQUAL, new BinaryPrefixComparator(Bytes.toBytes("u"))); FilterList filterList = new FilterList(Operator.MUST_PASS_ALL); filterList.addFilter(rowFilter); filterList.addFilter(familyFilter); filterList.addFilter(qualifierFilter); Scan scan = new Scan(); scan.setFilter(filterList); ResultScanner resultScanner = table.getScanner(scan); HBaseUtil.printResultScanner(resultScanner); } }
3,194
0.786788
0.785535
89
34.887642
31.019182
112
false
false
0
0
0
0
0
0
1.820225
false
false
12
5c8ae157df4d2fbc2f56b36c1562f2c167b4e9c7
33,174,327,428,336
60557de04fb0393e9dc6c14fed5b40e6649d3d51
/src/main/java/org/wooddog/woodstub/junit/StubEvent.java
02c7ca5ea156c0c9121d90b2cda2bbaaab9b90ac
[]
no_license
woodstub/woodstub
https://github.com/woodstub/woodstub
64aab26ae058c6172b8f4c3e1a7c087927d332e4
7385a96ba0debac0252c98ac6c167391719d34a6
refs/heads/master
2021-06-28T09:26:15.301000
2016-09-21T20:28:18
2016-09-21T20:28:18
2,349,946
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/****************************************************************************** * Woodstub * * Copyright (c) 2011 * * Developed by Claus Brøndby Reimer & Asbjørn Andersen * * All rights reserved * ******************************************************************************/ package org.wooddog.woodstub.junit; public interface StubEvent { /** * * @return The name of the invoked class */ String getClassName(); /** * @return The name of the invoked method. */ String getMethodName(); /** * Returns a parameter as an object. * @param parameterIndex The index of the argument starting at 1. * @return The parameter value */ Object getObject(int parameterIndex); /** * Gets the numbered occurrence of the type. * * @param parameterIndex The index of the argument starting at 1. * @return The the long value represented at the given parameter index. */ boolean getBoolean(int parameterIndex); /** * Gets the numbered occurrence of the type. * * @param parameterIndex The index of the argument starting at 1. * @return The the long value represented at the given parameter index. */ char getChar(int parameterIndex); /** * Gets the numbered occurrence of the type. * * @param parameterIndex The index of the argument starting at 1. * @return The the long value represented at the given parameter index. */ byte getByte(int parameterIndex); /** * Gets the numbered occurrence of the type. * * @param parameterIndex The index of the argument starting at 1. * @return The the long value represented at the given parameter index. */ short getShort(int parameterIndex); /** * Gets the numbered occurrence of the type. * * @param parameterIndex The index of the argument starting at 1. * @return The the long value represented at the given parameter index. */ int getInt(int parameterIndex); /** * Gets the numbered occurrence of the type. * * @param parameterIndex The index of the argument starting at 1. * @return The the long value represented at the given parameter index. */ long getLong(int parameterIndex); /** * Gets the numbered occurrence of the type. * * @param parameterIndex The index of the argument starting at 1. * @return The the long value represented at the given parameter index. */ float getFloat(int parameterIndex); /** * Gets the numbered occurrence of the type. * * @param parameterIndex The index of the argument starting at 1. * @return The the long value represented at the given parameter index. */ double getDouble(int parameterIndex); /** * Tells Woodstub to call the real (unstubbed class) if true. * @param redirect Whether to call real class or not. */ void setRedirectToRealClass(boolean redirect); boolean getRedirectToRealClass(); /** * Gets all the method parameter values. * Only intended for internal use. * @return All parameter values. */ Object[] getValues(); /** * Set the result to return. * It must match the type returned by the method. * If the method is void, the result will be ignored. * @param result The result to return */ void setResult(Object result); Object getResult(); /** * @return The class for the result type, if any. */ Class getReturnType(); /** * Sets an exception to raise. * Will only be raised when the callback returns. * @param x The exception to raise */ void raiseException(Throwable x); }
UTF-8
Java
3,952
java
StubEvent.java
Java
[ { "context": " *\n * Developed by Claus Brøndby Reimer & Asbjørn Andersen *\n * All", "end": 276, "score": 0.9998733997344971, "start": 256, "tag": "NAME", "value": "Claus Brøndby Reimer" }, { "context": " *\n * Developed by Claus Brøndby Reimer & Asbjørn Andersen *\n * All rights reserved ", "end": 295, "score": 0.9998795390129089, "start": 279, "tag": "NAME", "value": "Asbjørn Andersen" } ]
null
[]
/****************************************************************************** * Woodstub * * Copyright (c) 2011 * * Developed by <NAME> & <NAME> * * All rights reserved * ******************************************************************************/ package org.wooddog.woodstub.junit; public interface StubEvent { /** * * @return The name of the invoked class */ String getClassName(); /** * @return The name of the invoked method. */ String getMethodName(); /** * Returns a parameter as an object. * @param parameterIndex The index of the argument starting at 1. * @return The parameter value */ Object getObject(int parameterIndex); /** * Gets the numbered occurrence of the type. * * @param parameterIndex The index of the argument starting at 1. * @return The the long value represented at the given parameter index. */ boolean getBoolean(int parameterIndex); /** * Gets the numbered occurrence of the type. * * @param parameterIndex The index of the argument starting at 1. * @return The the long value represented at the given parameter index. */ char getChar(int parameterIndex); /** * Gets the numbered occurrence of the type. * * @param parameterIndex The index of the argument starting at 1. * @return The the long value represented at the given parameter index. */ byte getByte(int parameterIndex); /** * Gets the numbered occurrence of the type. * * @param parameterIndex The index of the argument starting at 1. * @return The the long value represented at the given parameter index. */ short getShort(int parameterIndex); /** * Gets the numbered occurrence of the type. * * @param parameterIndex The index of the argument starting at 1. * @return The the long value represented at the given parameter index. */ int getInt(int parameterIndex); /** * Gets the numbered occurrence of the type. * * @param parameterIndex The index of the argument starting at 1. * @return The the long value represented at the given parameter index. */ long getLong(int parameterIndex); /** * Gets the numbered occurrence of the type. * * @param parameterIndex The index of the argument starting at 1. * @return The the long value represented at the given parameter index. */ float getFloat(int parameterIndex); /** * Gets the numbered occurrence of the type. * * @param parameterIndex The index of the argument starting at 1. * @return The the long value represented at the given parameter index. */ double getDouble(int parameterIndex); /** * Tells Woodstub to call the real (unstubbed class) if true. * @param redirect Whether to call real class or not. */ void setRedirectToRealClass(boolean redirect); boolean getRedirectToRealClass(); /** * Gets all the method parameter values. * Only intended for internal use. * @return All parameter values. */ Object[] getValues(); /** * Set the result to return. * It must match the type returned by the method. * If the method is void, the result will be ignored. * @param result The result to return */ void setResult(Object result); Object getResult(); /** * @return The class for the result type, if any. */ Class getReturnType(); /** * Sets an exception to raise. * Will only be raised when the callback returns. * @param x The exception to raise */ void raiseException(Throwable x); }
3,926
0.585823
0.582532
129
29.620155
26.959974
80
false
false
0
0
0
0
0
0
0.162791
false
false
12
d1b2f17b2ee48c3fd6450041af5adddf7e8d6545
16,492,674,458,934
883e4af04a316345faec18331c41d0449ce8f4a2
/arpc-netty/src/main/java/com/amos/arpc/netty/client/NettyClientHandler.java
74a6418b8a9d37906ddd1447dd4119b0b287b0f9
[]
no_license
AmosWang0626/rpc
https://github.com/AmosWang0626/rpc
e7f59db24fd22061902bdda1ae4b358ce2fa5583
7fffedb8393ed6d7b2a75e57f8e86ffc436b7f85
refs/heads/main
2023-06-14T02:17:40.598000
2021-07-04T14:59:49
2021-07-04T14:59:49
383,676,977
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.amos.arpc.netty.client; import com.amos.arpc.netty.common.exception.RpcException; import com.amos.arpc.netty.common.model.RpcRequest; import com.amos.arpc.netty.common.model.RpcResponse; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.SimpleChannelInboundHandler; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.concurrent.Callable; /** * NettyClientHandler * * @author wangdaoyuan.wdy * @date 2021/6/20 */ public class NettyClientHandler extends SimpleChannelInboundHandler<RpcResponse> implements Callable<Object> { private static final Logger LOGGER = LoggerFactory.getLogger(NettyClientHandler.class); private ChannelHandlerContext context; private RpcRequest rpcRequest; private RpcResponse rpcResponse; @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { this.context = ctx; } @Override protected synchronized void channelRead0(ChannelHandlerContext channelHandlerContext, RpcResponse rpcResponse) throws Exception { this.rpcResponse = rpcResponse; if (rpcResponse.successful()) { LOGGER.debug("call method successful, response body: [{}]", rpcResponse.getBody()); } else { LOGGER.debug("call method fail, error code: [{}], message: [{}]", rpcResponse.getRpcError().getCode(), rpcResponse.getRpcError().getMessage()); } // 唤醒 call 中的等待方法 notify(); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { cause.printStackTrace(); ctx.close(); } @Override public synchronized Object call() throws Exception { context.writeAndFlush(rpcRequest); // 等待返回结果 wait(); if (rpcResponse.successful()) { return rpcResponse.getBody(); } throw new RpcException(rpcResponse.getRpcError().getMessage()); } public void setRpcRequest(RpcRequest rpcRequest) { this.rpcRequest = rpcRequest; } }
UTF-8
Java
2,124
java
NettyClientHandler.java
Java
[ { "context": "Callable;\n\n/**\n * NettyClientHandler\n *\n * @author wangdaoyuan.wdy\n * @date 2021/6/20\n */\npublic class", "end": 438, "score": 0.5335050821304321, "start": 437, "tag": "NAME", "value": "w" }, { "context": "llable;\n\n/**\n * NettyClientHandler\n *\n * @author wangdaoyuan.wdy\n * @date 2021/6/20\n */\npublic class NettyClientHa", "end": 452, "score": 0.8802065849304199, "start": 438, "tag": "USERNAME", "value": "angdaoyuan.wdy" } ]
null
[]
package com.amos.arpc.netty.client; import com.amos.arpc.netty.common.exception.RpcException; import com.amos.arpc.netty.common.model.RpcRequest; import com.amos.arpc.netty.common.model.RpcResponse; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.SimpleChannelInboundHandler; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.concurrent.Callable; /** * NettyClientHandler * * @author wangdaoyuan.wdy * @date 2021/6/20 */ public class NettyClientHandler extends SimpleChannelInboundHandler<RpcResponse> implements Callable<Object> { private static final Logger LOGGER = LoggerFactory.getLogger(NettyClientHandler.class); private ChannelHandlerContext context; private RpcRequest rpcRequest; private RpcResponse rpcResponse; @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { this.context = ctx; } @Override protected synchronized void channelRead0(ChannelHandlerContext channelHandlerContext, RpcResponse rpcResponse) throws Exception { this.rpcResponse = rpcResponse; if (rpcResponse.successful()) { LOGGER.debug("call method successful, response body: [{}]", rpcResponse.getBody()); } else { LOGGER.debug("call method fail, error code: [{}], message: [{}]", rpcResponse.getRpcError().getCode(), rpcResponse.getRpcError().getMessage()); } // 唤醒 call 中的等待方法 notify(); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { cause.printStackTrace(); ctx.close(); } @Override public synchronized Object call() throws Exception { context.writeAndFlush(rpcRequest); // 等待返回结果 wait(); if (rpcResponse.successful()) { return rpcResponse.getBody(); } throw new RpcException(rpcResponse.getRpcError().getMessage()); } public void setRpcRequest(RpcRequest rpcRequest) { this.rpcRequest = rpcRequest; } }
2,124
0.695611
0.69084
71
28.521128
30.854889
133
false
false
0
0
0
0
0
0
0.464789
false
false
12
9197a2db945bf6b575aa0b023d887ce00d82f82b
26,929,444,986,207
45957a92fa1b52097cc8b1d0d5d9e7c41cbc8c8b
/src/test/java/stepdefinations/Registration.java
a1d8ca3eab5f962ec6b5246c38a889c2f6012766
[]
no_license
sachin3339/Cucumber-BDD-testing
https://github.com/sachin3339/Cucumber-BDD-testing
691515a10a0d1d5784975835a74df663010633b6
193b7992a1b40fd9b3ba2988175a65eecd198d5b
refs/heads/master
2020-12-23T06:08:56.195000
2020-01-29T19:13:48
2020-01-29T19:13:48
237,061,502
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package stepdefinations; import org.junit.runner.RunWith; import cucumber.api.CucumberOptions; import cucumber.api.java.en.Given; import cucumber.api.java.en.Then; import cucumber.api.java.en.When; import cucumber.api.junit.Cucumber; @RunWith(Cucumber.class) @CucumberOptions(features="classpath:Test.feature" ,glue = "stepdefinations", plugin= {"html:target/test-report", "junit:target/junit-xml-report.xml", "json:target/json-report.json"}) public class Registration { }
UTF-8
Java
478
java
Registration.java
Java
[]
null
[]
package stepdefinations; import org.junit.runner.RunWith; import cucumber.api.CucumberOptions; import cucumber.api.java.en.Given; import cucumber.api.java.en.Then; import cucumber.api.java.en.When; import cucumber.api.junit.Cucumber; @RunWith(Cucumber.class) @CucumberOptions(features="classpath:Test.feature" ,glue = "stepdefinations", plugin= {"html:target/test-report", "junit:target/junit-xml-report.xml", "json:target/json-report.json"}) public class Registration { }
478
0.786611
0.786611
18
25.611111
14.395751
50
false
false
0
0
0
0
0
0
0.722222
false
false
12
d5881b14cb4b95b9c1010a9fc1d1099d4a871590
10,015,863,739,663
f9f93709c4a92c2722f823128849c1dbfa7261f6
/src/com/servlets/RegisterServlet.java
379bb912fce6a303240ada7c6d9b185262d2cfb8
[]
no_license
hritikhanda4/Meeting-Setter-Web-App
https://github.com/hritikhanda4/Meeting-Setter-Web-App
0dceae11b6f5babfb44ff9bb8728bd2aadb3d33d
7cd44712aed38a2e531c393619dde781257545a9
refs/heads/main
2023-03-27T21:52:00.846000
2021-02-19T14:10:59
2021-02-19T14:10:59
340,380,502
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.servlets; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.annotation.MultipartConfig; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.Part; import com.database.Database; import com.database.UserBean; @MultipartConfig public class RegisterServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { { resp.setContentType("text/html"); PrintWriter out=resp.getWriter(); String oldOtp=(String) req.getSession().getAttribute("otp"); String otp= req.getParameter("otp").trim(); if(oldOtp==null) { out.println("SendOtpFirst"); } else if(!oldOtp.equals(otp)) { System.out.println(oldOtp+"--"+otp); out.println("wrongOtp"); } else { boolean flag=true; UserBean ub=new UserBean(); String fname="",lname=""; if(flag) if(req.getParameter("fname")!=null&&req.getParameter("fname").trim().length()>0) { fname=req.getParameter("fname").trim(); fname=fname.substring(0,1).toUpperCase()+fname.substring(1,fname.length()).toLowerCase(); ub.setFname(fname); } else { flag=false; out.println("500error"); } if(flag) if(req.getParameter("lname")!=null&&req.getParameter("lname").trim().length()>0) { lname=req.getParameter("lname").trim(); lname=lname.substring(0,1).toUpperCase()+lname.substring(1,lname.length()).toLowerCase(); ub.setLname(lname); } else { flag=false; out.println("500error"); } if(flag) if(req.getParameter("email")!=null&&req.getParameter("email").trim().length()>0&&( req.getParameter("email").trim().matches("[A-Za-z0-9.!#$%&'*+/=?^_`{|}~-]+@[A-Z0-9a-z]+([.][A-Za-z0-9]+)+"))) { System.out.println("hello "); String email=req.getParameter("email").trim().toLowerCase(); ub.setEmail(email); } else { flag=false; out.println("500error"); } if(flag) if(req.getParameter("password")!=null&&req.getParameter("password").trim().length()>=6&&req.getParameter("confirmPassword")!=null&&req.getParameter("confirmPassword").trim().length()>=6&&req.getParameter("password").equals(req.getParameter("confirmPassword"))) { String password=req.getParameter("password").trim(); ub.setPassword(password); } else { flag=false; out.println("500error"); } if(flag) if(req.getParameter("DOB")!=null&&req.getParameter("DOB").trim().length()==10) { String dob=req.getParameter("DOB").trim(); ub.setDateOfBith(dob); } else { flag=false; out.println("500error"); } if(flag) if(req.getParameter("genderRadio")!=null&&(req.getParameter("genderRadio").trim().equals("Male")||req.getParameter("genderRadio").trim().equals("Female"))) { String gender=req.getParameter("genderRadio").trim(); ub.setGender(gender); } else { flag=false; out.println("500error"); } if(flag) if(req.getParameter("company")!=null&&req.getParameter("company").trim().length()>0) { String company=req.getParameter("company").trim(); ub.setCompany(company); } else { flag=false; out.println("500error"); } if(flag) if(req.getParameter("contact")!=null||req.getParameter("contact").trim().length()==10) { String contact=req.getParameter("contact").trim(); ub.setContact(contact); } else { flag=false; out.println("500error"); } if(flag) if(req.getPart("profilePicture")!=null) { Part profilePicture=req.getPart("profilePicture"); ub.setProfilePicture(profilePicture.getInputStream()); } else { flag=false; out.println("500error"); } if(req.getPart("coverPicture")!=null) { Part coverPicture=req.getPart("coverPicture"); ub.setCoverPicture(coverPicture.getInputStream()); } // Validations ends here // At this point if flag is true it means data is correct if(flag) { ub.setUsername(fname+" "+lname); int result=Database.registerData(ub); System.out.println(result); if(result==1) out.println("RegisteredSuccess"); else if(result==0) out.println("AlreadyRegistered"); else out.println("500error"); } else { System.out.println("Error"); out.println("500error"); } } } } }
UTF-8
Java
4,536
java
RegisterServlet.java
Java
[]
null
[]
package com.servlets; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.annotation.MultipartConfig; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.Part; import com.database.Database; import com.database.UserBean; @MultipartConfig public class RegisterServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { { resp.setContentType("text/html"); PrintWriter out=resp.getWriter(); String oldOtp=(String) req.getSession().getAttribute("otp"); String otp= req.getParameter("otp").trim(); if(oldOtp==null) { out.println("SendOtpFirst"); } else if(!oldOtp.equals(otp)) { System.out.println(oldOtp+"--"+otp); out.println("wrongOtp"); } else { boolean flag=true; UserBean ub=new UserBean(); String fname="",lname=""; if(flag) if(req.getParameter("fname")!=null&&req.getParameter("fname").trim().length()>0) { fname=req.getParameter("fname").trim(); fname=fname.substring(0,1).toUpperCase()+fname.substring(1,fname.length()).toLowerCase(); ub.setFname(fname); } else { flag=false; out.println("500error"); } if(flag) if(req.getParameter("lname")!=null&&req.getParameter("lname").trim().length()>0) { lname=req.getParameter("lname").trim(); lname=lname.substring(0,1).toUpperCase()+lname.substring(1,lname.length()).toLowerCase(); ub.setLname(lname); } else { flag=false; out.println("500error"); } if(flag) if(req.getParameter("email")!=null&&req.getParameter("email").trim().length()>0&&( req.getParameter("email").trim().matches("[A-Za-z0-9.!#$%&'*+/=?^_`{|}~-]+@[A-Z0-9a-z]+([.][A-Za-z0-9]+)+"))) { System.out.println("hello "); String email=req.getParameter("email").trim().toLowerCase(); ub.setEmail(email); } else { flag=false; out.println("500error"); } if(flag) if(req.getParameter("password")!=null&&req.getParameter("password").trim().length()>=6&&req.getParameter("confirmPassword")!=null&&req.getParameter("confirmPassword").trim().length()>=6&&req.getParameter("password").equals(req.getParameter("confirmPassword"))) { String password=req.getParameter("password").trim(); ub.setPassword(password); } else { flag=false; out.println("500error"); } if(flag) if(req.getParameter("DOB")!=null&&req.getParameter("DOB").trim().length()==10) { String dob=req.getParameter("DOB").trim(); ub.setDateOfBith(dob); } else { flag=false; out.println("500error"); } if(flag) if(req.getParameter("genderRadio")!=null&&(req.getParameter("genderRadio").trim().equals("Male")||req.getParameter("genderRadio").trim().equals("Female"))) { String gender=req.getParameter("genderRadio").trim(); ub.setGender(gender); } else { flag=false; out.println("500error"); } if(flag) if(req.getParameter("company")!=null&&req.getParameter("company").trim().length()>0) { String company=req.getParameter("company").trim(); ub.setCompany(company); } else { flag=false; out.println("500error"); } if(flag) if(req.getParameter("contact")!=null||req.getParameter("contact").trim().length()==10) { String contact=req.getParameter("contact").trim(); ub.setContact(contact); } else { flag=false; out.println("500error"); } if(flag) if(req.getPart("profilePicture")!=null) { Part profilePicture=req.getPart("profilePicture"); ub.setProfilePicture(profilePicture.getInputStream()); } else { flag=false; out.println("500error"); } if(req.getPart("coverPicture")!=null) { Part coverPicture=req.getPart("coverPicture"); ub.setCoverPicture(coverPicture.getInputStream()); } // Validations ends here // At this point if flag is true it means data is correct if(flag) { ub.setUsername(fname+" "+lname); int result=Database.registerData(ub); System.out.println(result); if(result==1) out.println("RegisteredSuccess"); else if(result==0) out.println("AlreadyRegistered"); else out.println("500error"); } else { System.out.println("Error"); out.println("500error"); } } } } }
4,536
0.652116
0.63933
180
24.200001
32.933502
262
false
false
0
0
0
0
0
0
2.522222
false
false
12
53e67f23f1cf89a30ff77a8f4cf6cc997ad5fd8e
6,287,832,136,339
5da86b832a6367fbbcdc221177971e80bfe18269
/src/Day18_Debugging_Methods_MethodParameters_MethodWithReturnTypes/_02_Task.java
dc863d068aca042e93b2655e9090beda8a478f71
[]
no_license
JulieBolat/JavaCourse
https://github.com/JulieBolat/JavaCourse
dc08280b5391d7f9aa495e700b6812a4728e27b6
2aa72cde00e22237c5628ea27156ebde52317cab
refs/heads/master
2023-06-11T22:09:55.434000
2021-07-01T23:43:51
2021-07-01T23:43:51
382,181,834
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package Day18_Debugging_Methods_MethodParameters_MethodWithReturnTypes; public class _02_Task { public static void main(String[] args) { //create a simple method to print "Hello World!" 5 times printHelloWorld(); } public static void printHelloWorld() { System.out.println("Hello World!"); System.out.println("Hello World!"); System.out.println("Hello World!"); System.out.println("Hello World!"); System.out.println("Hello World!"); } }
UTF-8
Java
515
java
_02_Task.java
Java
[]
null
[]
package Day18_Debugging_Methods_MethodParameters_MethodWithReturnTypes; public class _02_Task { public static void main(String[] args) { //create a simple method to print "Hello World!" 5 times printHelloWorld(); } public static void printHelloWorld() { System.out.println("Hello World!"); System.out.println("Hello World!"); System.out.println("Hello World!"); System.out.println("Hello World!"); System.out.println("Hello World!"); } }
515
0.640777
0.631068
21
23.523809
23.520243
71
false
false
0
0
0
0
0
0
0.333333
false
false
12
9da7ac4111ab07004ed7f2c1af283d376d514e0e
14,585,708,979,847
0517ae9ad164038cc6e6be0509ac9bf23d7ec44c
/hazelcast/src/main/java/com/hazelcast/map/impl/operation/PutAllPartitionAwareOperationFactory.java
55449a608b5e1f6fc872b1dd5a237501cab1647a
[ "Apache-2.0" ]
permissive
atlassian/hazelcast
https://github.com/atlassian/hazelcast
1c8e5ec58f626102d4de0dc97b6f2f4dfd946b9d
174b3db30e001c2a1b60d870cfcc3138f10edecc
refs/heads/master
2023-07-08T07:23:49.811000
2016-11-28T15:01:28
2016-11-28T19:16:15
24,581,214
4
4
null
true
2023-03-23T23:55:52
2014-09-29T05:33:05
2019-07-22T16:36:59
2023-03-23T23:55:52
100,300
5
4
8
Java
false
false
/* * Copyright (c) 2008-2016, Hazelcast, Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hazelcast.map.impl.operation; import com.hazelcast.map.impl.MapDataSerializerHook; import com.hazelcast.map.impl.MapEntries; import com.hazelcast.nio.ObjectDataInput; import com.hazelcast.nio.ObjectDataOutput; import com.hazelcast.spi.Operation; import com.hazelcast.spi.impl.operationservice.impl.operations.PartitionAwareOperationFactory; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.io.IOException; import java.util.Arrays; import java.util.Map; /** * Inserts the {@link MapEntries} for all partitions of a member via locally invoked {@link PutAllOperation}. * <p/> * Used to reduce the number of remote invocations of an {@link com.hazelcast.core.IMap#putAll(Map)} call. */ public class PutAllPartitionAwareOperationFactory extends PartitionAwareOperationFactory { protected String name; protected MapEntries[] mapEntries; public PutAllPartitionAwareOperationFactory() { } @SuppressFBWarnings("EI_EXPOSE_REP2") public PutAllPartitionAwareOperationFactory(String name, int[] partitions, MapEntries[] mapEntries) { this.name = name; this.partitions = partitions; this.mapEntries = mapEntries; } @Override public Operation createPartitionOperation(int partitionId) { for (int i = 0; i < partitions.length; i++) { if (partitions[i] == partitionId) { return new PutAllOperation(name, mapEntries[i]); } } throw new IllegalArgumentException("Unknown partitionId " + partitionId + " (" + Arrays.toString(partitions) + ")"); } @Override public void writeData(ObjectDataOutput out) throws IOException { out.writeUTF(name); out.writeIntArray(partitions); for (MapEntries entry : mapEntries) { entry.writeData(out); } } @Override public void readData(ObjectDataInput in) throws IOException { name = in.readUTF(); partitions = in.readIntArray(); mapEntries = new MapEntries[partitions.length]; for (int i = 0; i < partitions.length; i++) { MapEntries entry = new MapEntries(); entry.readData(in); mapEntries[i] = entry; } } @Override public int getFactoryId() { return MapDataSerializerHook.F_ID; } @Override public int getId() { return MapDataSerializerHook.PUT_ALL_PARTITION_AWARE_FACTORY; } }
UTF-8
Java
3,080
java
PutAllPartitionAwareOperationFactory.java
Java
[]
null
[]
/* * Copyright (c) 2008-2016, Hazelcast, Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hazelcast.map.impl.operation; import com.hazelcast.map.impl.MapDataSerializerHook; import com.hazelcast.map.impl.MapEntries; import com.hazelcast.nio.ObjectDataInput; import com.hazelcast.nio.ObjectDataOutput; import com.hazelcast.spi.Operation; import com.hazelcast.spi.impl.operationservice.impl.operations.PartitionAwareOperationFactory; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.io.IOException; import java.util.Arrays; import java.util.Map; /** * Inserts the {@link MapEntries} for all partitions of a member via locally invoked {@link PutAllOperation}. * <p/> * Used to reduce the number of remote invocations of an {@link com.hazelcast.core.IMap#putAll(Map)} call. */ public class PutAllPartitionAwareOperationFactory extends PartitionAwareOperationFactory { protected String name; protected MapEntries[] mapEntries; public PutAllPartitionAwareOperationFactory() { } @SuppressFBWarnings("EI_EXPOSE_REP2") public PutAllPartitionAwareOperationFactory(String name, int[] partitions, MapEntries[] mapEntries) { this.name = name; this.partitions = partitions; this.mapEntries = mapEntries; } @Override public Operation createPartitionOperation(int partitionId) { for (int i = 0; i < partitions.length; i++) { if (partitions[i] == partitionId) { return new PutAllOperation(name, mapEntries[i]); } } throw new IllegalArgumentException("Unknown partitionId " + partitionId + " (" + Arrays.toString(partitions) + ")"); } @Override public void writeData(ObjectDataOutput out) throws IOException { out.writeUTF(name); out.writeIntArray(partitions); for (MapEntries entry : mapEntries) { entry.writeData(out); } } @Override public void readData(ObjectDataInput in) throws IOException { name = in.readUTF(); partitions = in.readIntArray(); mapEntries = new MapEntries[partitions.length]; for (int i = 0; i < partitions.length; i++) { MapEntries entry = new MapEntries(); entry.readData(in); mapEntries[i] = entry; } } @Override public int getFactoryId() { return MapDataSerializerHook.F_ID; } @Override public int getId() { return MapDataSerializerHook.PUT_ALL_PARTITION_AWARE_FACTORY; } }
3,080
0.692857
0.687987
92
32.47826
29.92399
124
false
false
0
0
0
0
0
0
0.467391
false
false
12
292098b2cf781a71bf4f3772f8ef8d84bba1fccc
32,804,960,246,613
43c20fa2d559bc946db328d956e713ac393288d1
/src/main/java/com/promineotech/pokemonApi/repository/TrainerRepository.java
73b3aa16ac5f72d4212b61bcd402fffc490b3b2e
[]
no_license
Robert-Metz/BESD_Final
https://github.com/Robert-Metz/BESD_Final
5f87a583d5504b44ec8c1ed572b62a27eddddae2
ddfc05724193d6904af01bd16e7f2e73417c2cf8
refs/heads/master
2023-02-27T14:52:46.534000
2021-02-04T01:38:06
2021-02-04T01:38:06
333,227,315
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.promineotech.pokemonApi.repository; import org.springframework.data.repository.CrudRepository; import com.promineotech.pokemonApi.entity.Trainer; public interface TrainerRepository extends CrudRepository<Trainer, Long> { }
UTF-8
Java
238
java
TrainerRepository.java
Java
[]
null
[]
package com.promineotech.pokemonApi.repository; import org.springframework.data.repository.CrudRepository; import com.promineotech.pokemonApi.entity.Trainer; public interface TrainerRepository extends CrudRepository<Trainer, Long> { }
238
0.84874
0.84874
8
28.75
29.448048
74
false
false
0
0
0
0
0
0
0.5
false
false
12
a5d44d5fbeee6580b7287adb14c7001ec381350b
15,410,342,661,070
d38c8bc54ba568d7d3c74eb38d8f2d2576c4f372
/sumOf2Num.java
590510894b78704eaeeeb64eeb6b094b8ed38e3d
[]
no_license
Sujithakumaravelg/java-programming
https://github.com/Sujithakumaravelg/java-programming
d2d2a13727aad3f989227be7706c70c7910add3c
71bc7f0c5fc0f5d93e4e08396646ba2392d62f1f
refs/heads/master
2021-09-28T22:33:19.049000
2021-09-24T16:50:26
2021-09-24T16:50:26
122,157,817
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.util.Scanner; public class sumOf2Num{ public static void main(String arg[])throws Exception { try{ Scanner s = new Scanner(System.in); int n1=s.nextInt(); int n2=s.nextInt(); System.out.println(n1+n2); } catch(Exception e){ System.out.println("enter valid value"); } } }
UTF-8
Java
366
java
sumOf2Num.java
Java
[]
null
[]
import java.util.Scanner; public class sumOf2Num{ public static void main(String arg[])throws Exception { try{ Scanner s = new Scanner(System.in); int n1=s.nextInt(); int n2=s.nextInt(); System.out.println(n1+n2); } catch(Exception e){ System.out.println("enter valid value"); } } }
366
0.562842
0.54918
14
25.142857
17.369337
58
false
false
0
0
0
0
0
0
0.428571
false
false
12
4ccf71c22f5102d06f8500cecabfa0bb365972b7
2,216,203,188,047
3946fb4dba7c07dba2edecfac6bcc61c43d1b80f
/app/src/main/java/by/zubchenok/gitfadvicer/data/GiftDbHelper.java
d7337439c58c792b15629431af5c80b410b34f98
[]
no_license
AntonZubchenok/GiftAdviser
https://github.com/AntonZubchenok/GiftAdviser
2f95ed444a65a08633743a914f448cf541291808
0ae0cf63cced182b8f5e7decc8ed1ca518d1c3ab
refs/heads/master
2021-06-11T15:02:54.049000
2017-01-23T11:11:01
2017-01-23T11:11:01
75,469,041
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package by.zubchenok.gitfadvicer.data; import android.content.Context; import com.readystatesoftware.sqliteasset.SQLiteAssetHelper; public class GiftDbHelper extends SQLiteAssetHelper { public static final String DATABASE_NAME = "gifts.db"; public static final int DATABASE_VERSION = 1; public GiftDbHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } }
UTF-8
Java
415
java
GiftDbHelper.java
Java
[]
null
[]
package by.zubchenok.gitfadvicer.data; import android.content.Context; import com.readystatesoftware.sqliteasset.SQLiteAssetHelper; public class GiftDbHelper extends SQLiteAssetHelper { public static final String DATABASE_NAME = "gifts.db"; public static final int DATABASE_VERSION = 1; public GiftDbHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } }
415
0.759036
0.756626
16
24.9375
25.32654
62
false
false
0
0
0
0
0
0
0.5625
false
false
12
0fde0db4d564de1f2eba6cf7a6e627e8436c17a2
7,705,171,340,536
02601f7e73858dc1dfcac5157386814313715766
/rocketmq-impl/src/main/java/org/streamnative/pulsar/handlers/rocketmq/inner/RopClientChannelCnx.java
dbfadd53af2b84ffa687f0df72eff219813eea40
[ "Apache-2.0" ]
permissive
Demogorgon314/rop
https://github.com/Demogorgon314/rop
3e799c5de19eb42af017038b3f984a34607cc86a
65e9d0520b7c2df07e358f143828dc7bb318ac5f
refs/heads/master
2023-08-23T15:02:56.395000
2021-09-27T10:32:18
2021-09-27T10:32:18
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * 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.streamnative.pulsar.handlers.rocketmq.inner; import io.netty.channel.ChannelHandlerContext; import java.util.Objects; import lombok.Getter; import lombok.extern.slf4j.Slf4j; import org.apache.rocketmq.broker.client.ClientChannelInfo; import org.apache.rocketmq.remoting.protocol.LanguageCode; /** * Rop client channel cnx. */ @Slf4j public class RopClientChannelCnx extends ClientChannelInfo { @Getter private final RocketMQBrokerController brokerController; @Getter private final RopServerCnx serverCnx; public RopClientChannelCnx(RocketMQBrokerController brokerController, ChannelHandlerContext ctx) { this(brokerController, ctx, (String) null, (LanguageCode) null, 0); } public RopClientChannelCnx(RocketMQBrokerController brokerController, ChannelHandlerContext ctx, String clientId, LanguageCode language, int version) { super(ctx.channel(), clientId, language, version); this.brokerController = brokerController; this.serverCnx = new RopServerCnx(brokerController, ctx); } public String toString() { return super.toString(); } public boolean equals(Object obj) { return super.equals(obj); } @Override public int hashCode() { return Objects.hash(super.hashCode(), brokerController, serverCnx); } }
UTF-8
Java
1,913
java
RopClientChannelCnx.java
Java
[]
null
[]
/** * 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.streamnative.pulsar.handlers.rocketmq.inner; import io.netty.channel.ChannelHandlerContext; import java.util.Objects; import lombok.Getter; import lombok.extern.slf4j.Slf4j; import org.apache.rocketmq.broker.client.ClientChannelInfo; import org.apache.rocketmq.remoting.protocol.LanguageCode; /** * Rop client channel cnx. */ @Slf4j public class RopClientChannelCnx extends ClientChannelInfo { @Getter private final RocketMQBrokerController brokerController; @Getter private final RopServerCnx serverCnx; public RopClientChannelCnx(RocketMQBrokerController brokerController, ChannelHandlerContext ctx) { this(brokerController, ctx, (String) null, (LanguageCode) null, 0); } public RopClientChannelCnx(RocketMQBrokerController brokerController, ChannelHandlerContext ctx, String clientId, LanguageCode language, int version) { super(ctx.channel(), clientId, language, version); this.brokerController = brokerController; this.serverCnx = new RopServerCnx(brokerController, ctx); } public String toString() { return super.toString(); } public boolean equals(Object obj) { return super.equals(obj); } @Override public int hashCode() { return Objects.hash(super.hashCode(), brokerController, serverCnx); } }
1,913
0.737585
0.733403
58
31.982759
29.904152
117
false
false
0
0
0
0
0
0
0.62069
false
false
12
2c242973e5072e68aa0598ef8b5aec6a5e3b9d43
21,560,735,884,184
8268d4dc2291d4a913964406fa0762e00f2e453e
/src/main/java/com/navtech/models/Course.java
59c0bd83342490af0e0f42a228a9ae7fee563b46
[]
no_license
JainNaveen94/Spring-Hiberbnate-Practise-Project
https://github.com/JainNaveen94/Spring-Hiberbnate-Practise-Project
a37b159ba929b8602076ed26b0b1bd5bf8b06736
f09bc50481d71f0a1c0e96afb9275d7a474ebe5f
refs/heads/master
2021-01-03T01:22:10.978000
2020-02-14T20:35:18
2020-02-14T20:35:18
239,853,990
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.navtech.models; import java.util.List; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.ManyToMany; import javax.persistence.Table; @Entity @Table(name="Course") public class Course { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name="courseId") private long courseId; @Column(name="courseName") private String courseName; @Column(name="courseDuration") private String courseDuration; @Column(name="courseDescription") private String courseDescription; @Column(name="courseFees") private float courseFees; @ManyToMany(cascade = { CascadeType.DETACH, CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH }) @JoinTable( name="Student_Course", joinColumns = @JoinColumn(name="courseId"), inverseJoinColumns = @JoinColumn(name="studentId") ) private List<Student> students; /* Default Constructor */ public Course() { // TODO Auto-generated constructor stub } /* Getter / Setter */ public long getCourseId() { return courseId; } public void setCourseId(long courseId) { this.courseId = courseId; } public String getCourseName() { return courseName; } public void setCourseName(String courseName) { this.courseName = courseName; } public String getCourseDuration() { return courseDuration; } public void setCourseDuration(String courseDuration) { this.courseDuration = courseDuration; } public String getCourseDescription() { return courseDescription; } public void setCourseDescription(String courseDescription) { this.courseDescription = courseDescription; } public float getCourseFees() { return courseFees; } public void setCourseFees(float courseFees) { this.courseFees = courseFees; } public List<Student> getStudents() { return students; } public void setStudents(List<Student> students) { this.students = students; } }
UTF-8
Java
2,151
java
Course.java
Java
[]
null
[]
package com.navtech.models; import java.util.List; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.ManyToMany; import javax.persistence.Table; @Entity @Table(name="Course") public class Course { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name="courseId") private long courseId; @Column(name="courseName") private String courseName; @Column(name="courseDuration") private String courseDuration; @Column(name="courseDescription") private String courseDescription; @Column(name="courseFees") private float courseFees; @ManyToMany(cascade = { CascadeType.DETACH, CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH }) @JoinTable( name="Student_Course", joinColumns = @JoinColumn(name="courseId"), inverseJoinColumns = @JoinColumn(name="studentId") ) private List<Student> students; /* Default Constructor */ public Course() { // TODO Auto-generated constructor stub } /* Getter / Setter */ public long getCourseId() { return courseId; } public void setCourseId(long courseId) { this.courseId = courseId; } public String getCourseName() { return courseName; } public void setCourseName(String courseName) { this.courseName = courseName; } public String getCourseDuration() { return courseDuration; } public void setCourseDuration(String courseDuration) { this.courseDuration = courseDuration; } public String getCourseDescription() { return courseDescription; } public void setCourseDescription(String courseDescription) { this.courseDescription = courseDescription; } public float getCourseFees() { return courseFees; } public void setCourseFees(float courseFees) { this.courseFees = courseFees; } public List<Student> getStudents() { return students; } public void setStudents(List<Student> students) { this.students = students; } }
2,151
0.752208
0.752208
108
18.916666
16.877075
61
false
false
0
0
0
0
0
0
1.25
false
false
12
48da760e3bbd8d6844a950c46e414a6ecc7ea1cb
21,560,735,884,682
6b00ee38ddd47635b98cc0c643bd95a6c0763d95
/curso/src/main/java/edu/cibertec/curso/common/ErrorDTO.java
c60c52bb53f9c1c7c38c6a6ab7a6462389ad106c
[]
no_license
UserPabloJuarez/ServiciosREST
https://github.com/UserPabloJuarez/ServiciosREST
d4ff8df5053c6237e61c33661b068ee5ed61ec50
a2a1ea939c4497f36fbde052d8c943c6ec3bb486
refs/heads/master
2023-02-08T23:43:12.600000
2021-01-02T16:11:10
2021-01-02T16:11:10
326,219,486
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package edu.cibertec.curso.common; import lombok.Data; import lombok.AllArgsConstructor; @Data @AllArgsConstructor public class ErrorDTO { private String status; private String error; private String message; }
UTF-8
Java
225
java
ErrorDTO.java
Java
[]
null
[]
package edu.cibertec.curso.common; import lombok.Data; import lombok.AllArgsConstructor; @Data @AllArgsConstructor public class ErrorDTO { private String status; private String error; private String message; }
225
0.768889
0.768889
13
16.307692
12.693939
34
false
false
0
0
0
0
0
0
0.461538
false
false
12
7b1d3d48240f453e06eb7536d50fe1d7701e4f93
28,132,035,854,804
3f12f4620aa129097b3f1b70914de8e54fad595b
/p2p-core/src/main/java/cn/wolfcode/p2p/base/domain/UserFile.java
aedbd99e7bee4309889c82bbae15b738b78050dd
[]
no_license
luan66/p2p
https://github.com/luan66/p2p
4e632bc19caab2c666b23674ffa11fb90d0f3c13
b961e22fdd716002d52cd0862c333a4e09b75f17
refs/heads/master
2021-04-03T07:59:06.686000
2018-12-08T07:37:37
2018-12-08T07:37:37
124,626,218
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package cn.wolfcode.p2p.base.domain; import com.alibaba.fastjson.JSON; import lombok.Getter; import lombok.Setter; import java.util.HashMap; import java.util.Map; /** * 资料文件上传对象 */ @Setter @Getter public class UserFile extends BaseAuditorDomain { private String image; //文件路径; private SystemDictionaryItem fileTypeId; //文件类型; private int score; //文件单个获取分数; //回显数据的json: public String getJsonString(){ Map<String,Object> map = new HashMap<String, Object>(); map.put("id",id); map.put("username",applierId.getUsername()); map.put("fileTypeId",fileTypeId.getTitle()); map.put("image",image); return JSON.toJSONString(map); } }
UTF-8
Java
805
java
UserFile.java
Java
[]
null
[]
package cn.wolfcode.p2p.base.domain; import com.alibaba.fastjson.JSON; import lombok.Getter; import lombok.Setter; import java.util.HashMap; import java.util.Map; /** * 资料文件上传对象 */ @Setter @Getter public class UserFile extends BaseAuditorDomain { private String image; //文件路径; private SystemDictionaryItem fileTypeId; //文件类型; private int score; //文件单个获取分数; //回显数据的json: public String getJsonString(){ Map<String,Object> map = new HashMap<String, Object>(); map.put("id",id); map.put("username",applierId.getUsername()); map.put("fileTypeId",fileTypeId.getTitle()); map.put("image",image); return JSON.toJSONString(map); } }
805
0.634538
0.633199
29
24.758621
20.356571
63
false
false
0
0
0
0
0
0
0.827586
false
false
12
4f1efcda8222992af1b337f3b66f54bed39ce489
3,676,492,011,396
e44623cc76727f2d38d2afdf08a46997ad5cfc7e
/Java/Frolova_Elizaveta_Daniilovna_BSE185_HW4/BattleShip_desktop/tests/battleship/ships/OceanTest.java
80e67e3810ebed18762219aea843e4e317d64cd2
[]
no_license
kiwikk/hse_study
https://github.com/kiwikk/hse_study
430d9bc3bb76fbbbb514f826d75367ec36eb1e16
8d6f1cda1d0814dd6296a166078fbc9cf3ba3de8
refs/heads/master
2023-01-22T08:45:13.805000
2020-07-02T14:22:50
2020-07-02T14:22:50
276,656,703
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package battleship.ships; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; class OceanTest { @Test void createCruiserShip() { // Ocean ocean=new Ocean(10, null, null, null, null); // CruiserButton ship= new CruiserButton(ocean, null); // // ship.generateDeck(ship.getLenght()); // // for (int i = 0; i < ship.decks.size(); i++) { // assertFalse(ocean.getShipAt(ship.decks.get(i).coordinates.getX()-1,ship.decks.get(i).coordinates.getY()-1)); // } } @Test void createBattleShips() { } @Test void createDestroyer() { } @Test void createSubmarine() { } @Test void setShip() { } }
UTF-8
Java
726
java
OceanTest.java
Java
[]
null
[]
package battleship.ships; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; class OceanTest { @Test void createCruiserShip() { // Ocean ocean=new Ocean(10, null, null, null, null); // CruiserButton ship= new CruiserButton(ocean, null); // // ship.generateDeck(ship.getLenght()); // // for (int i = 0; i < ship.decks.size(); i++) { // assertFalse(ocean.getShipAt(ship.decks.get(i).coordinates.getX()-1,ship.decks.get(i).coordinates.getY()-1)); // } } @Test void createBattleShips() { } @Test void createDestroyer() { } @Test void createSubmarine() { } @Test void setShip() { } }
726
0.589532
0.582645
36
19.194445
25.266161
122
false
false
0
0
0
0
0
0
0.416667
false
false
12
1034fc8468116ab519728d72313746919b578100
30,537,217,535,949
e45436c54930d44e421b521977040f588333c0b5
/src/main/java/cn/ejie/dao/EquipmentNameMapper.java
772784e904b3c029e92a15ec7944112a99216ffd
[]
no_license
Fire-Star/FinancialManager
https://github.com/Fire-Star/FinancialManager
d18e41e1e8054d3582bdeaa400832b5501f2b3cd
7268835364946b948ddd90f7c3c5bef1c5f48cc1
refs/heads/master
2021-01-19T15:05:05.294000
2017-10-23T09:36:08
2017-10-23T09:36:08
100,942,602
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package cn.ejie.dao; import cn.ejie.pocustom.EquipmentNameCustom; import java.util.List; /** * Created by Administrator on 2017/8/22. */ public interface EquipmentNameMapper { /** * 插入单个设备名称 * @param equipmentNameCustom * @throws Exception */ public void insertSingleEquipmentName(EquipmentNameCustom equipmentNameCustom) throws Exception; /** * 查询出所有的设备名称 * @return * @throws Exception */ public List<EquipmentNameCustom> showAllEquipmentName() throws Exception; /** * 查找相同设备名称和设备类型的UUID的数量 * @param equipmentNameCustom * @return * @throws Exception */ public Integer findEquipmentNameCountByEquipmentNameAndType(EquipmentNameCustom equipmentNameCustom) throws Exception; public List<EquipmentNameCustom> findAllEquipmentNameByEqTypeID(String eqTypeId) throws Exception; public void delEquipmentName(EquipmentNameCustom equipmentNameCustom) throws Exception; public void delEquipmentNameByEqType(String eqType) throws Exception; public String findEquipmentNameIDByEquipmentName(String eqName) throws Exception; }
UTF-8
Java
1,200
java
EquipmentNameMapper.java
Java
[ { "context": "Custom;\n\nimport java.util.List;\n\n/**\n * Created by Administrator on 2017/8/22.\n */\npublic interface EquipmentNameM", "end": 123, "score": 0.7041212916374207, "start": 110, "tag": "NAME", "value": "Administrator" } ]
null
[]
package cn.ejie.dao; import cn.ejie.pocustom.EquipmentNameCustom; import java.util.List; /** * Created by Administrator on 2017/8/22. */ public interface EquipmentNameMapper { /** * 插入单个设备名称 * @param equipmentNameCustom * @throws Exception */ public void insertSingleEquipmentName(EquipmentNameCustom equipmentNameCustom) throws Exception; /** * 查询出所有的设备名称 * @return * @throws Exception */ public List<EquipmentNameCustom> showAllEquipmentName() throws Exception; /** * 查找相同设备名称和设备类型的UUID的数量 * @param equipmentNameCustom * @return * @throws Exception */ public Integer findEquipmentNameCountByEquipmentNameAndType(EquipmentNameCustom equipmentNameCustom) throws Exception; public List<EquipmentNameCustom> findAllEquipmentNameByEqTypeID(String eqTypeId) throws Exception; public void delEquipmentName(EquipmentNameCustom equipmentNameCustom) throws Exception; public void delEquipmentNameByEqType(String eqType) throws Exception; public String findEquipmentNameIDByEquipmentName(String eqName) throws Exception; }
1,200
0.747788
0.741593
40
27.25
33.242855
122
false
false
0
0
0
0
0
0
0.25
false
false
12
3ef1b5f408d2bb5d66d3979e78ff9f42f5f34b15
26,645,977,131,033
27fce8811bb4256582b5e2e5b520ab31c60a10c4
/thirdeye/thirdeye-pinot/src/main/java/com/linkedin/thirdeye/dashboard/resources/CacheResource.java
c1954e974fa1e7df467696d7e2e0e2d972f078cb
[ "BSD-3-Clause", "Apache-2.0" ]
permissive
sajavadi/pinot
https://github.com/sajavadi/pinot
87926571c4254c133bd6dd5a9d38e83edc891687
81f76c2e71e3b75bb1294187941c644e70799405
refs/heads/master
2021-01-19T00:59:30.346000
2017-09-15T16:34:55
2017-09-15T16:34:55
95,609,456
2
1
null
true
2017-06-27T23:32:09
2017-06-27T23:32:09
2017-06-27T15:21:40
2017-06-27T23:02:06
140,345
0
0
0
null
null
null
package com.linkedin.thirdeye.dashboard.resources; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import com.google.common.cache.LoadingCache; import com.linkedin.thirdeye.datalayer.dto.DashboardConfigDTO; import com.linkedin.thirdeye.datalayer.dto.DatasetConfigDTO; import com.linkedin.thirdeye.datalayer.dto.MetricConfigDTO; import com.linkedin.thirdeye.datasource.DAORegistry; import com.linkedin.thirdeye.datasource.ThirdEyeCacheRegistry; import com.linkedin.thirdeye.datasource.cache.MetricDataset; @Path("/cache") @Produces(MediaType.APPLICATION_JSON) public class CacheResource { private static final ExecutorService EXECUTOR_SERVICE = Executors.newFixedThreadPool(20); private ThirdEyeCacheRegistry CACHE_INSTANCE = ThirdEyeCacheRegistry.getInstance(); private DAORegistry DAO_REGISTRY = DAORegistry.getInstance(); @GET @Path(value = "/") @Produces(MediaType.TEXT_HTML) public String getCaches() { return "usage"; } @POST @Path("/refresh") public Response refreshAllCaches() { refreshDatasets(); refreshDatasetConfigCache(); refreshMetricConfigCache(); refreshDashoardConfigsCache(); refreshMaxDataTimeCache(); refreshDimensionFiltersCache(); return Response.ok().build(); } @POST @Path("/refresh/maxDataTime") public Response refreshMaxDataTimeCache() { List<String> datasets = CACHE_INSTANCE.getDatasetsCache().getDatasets(); final LoadingCache<String,Long> cache = CACHE_INSTANCE.getDatasetMaxDataTimeCache(); for (final String dataset : datasets) { EXECUTOR_SERVICE.submit(new Runnable() { @Override public void run() { cache.refresh(dataset); } }); } return Response.ok().build(); } @POST @Path("/refresh/datasetConfig") public Response refreshDatasetConfigCache() { List<String> datasets = CACHE_INSTANCE.getDatasetsCache().getDatasets(); final LoadingCache<String,DatasetConfigDTO> cache = CACHE_INSTANCE.getDatasetConfigCache(); for (final String dataset : datasets) { EXECUTOR_SERVICE.submit(new Runnable() { @Override public void run() { cache.refresh(dataset); } }); } return Response.ok().build(); } @POST @Path("/refresh/metricConfig") public Response refreshMetricConfigCache() { final LoadingCache<MetricDataset, MetricConfigDTO> cache = CACHE_INSTANCE.getMetricConfigCache(); List<String> datasets = CACHE_INSTANCE.getDatasetsCache().getDatasets(); for (final String dataset : datasets) { EXECUTOR_SERVICE.submit(new Runnable() { @Override public void run() { List<MetricConfigDTO> metricConfigs = DAO_REGISTRY.getMetricConfigDAO().findByDataset(dataset); for (MetricConfigDTO metricConfig : metricConfigs) { cache.refresh(new MetricDataset(metricConfig.getName(), metricConfig.getDataset())); } } }); } return Response.ok().build(); } @POST @Path("/refresh/dashboardConfigs") public Response refreshDashoardConfigsCache() { List<String> datasets = CACHE_INSTANCE.getDatasetsCache().getDatasets(); final LoadingCache<String,List<DashboardConfigDTO>> cache = CACHE_INSTANCE.getDashboardConfigsCache(); for (final String dataset : datasets) { EXECUTOR_SERVICE.submit(new Runnable() { @Override public void run() { cache.refresh(dataset); } }); } return Response.ok().build(); } @POST @Path("/refresh/filters") public Response refreshDimensionFiltersCache() { List<String> datasets = CACHE_INSTANCE.getDatasetsCache().getDatasets(); final LoadingCache<String,String> cache = CACHE_INSTANCE.getDimensionFiltersCache(); for (final String dataset : datasets) { EXECUTOR_SERVICE.submit(new Runnable() { @Override public void run() { cache.refresh(dataset); } }); } return Response.ok().build(); } @POST @Path("/refresh/collections") public Response refreshDatasets() { Response response = Response.ok().build(); CACHE_INSTANCE.getDatasetsCache().loadDatasets(); return response; } }
UTF-8
Java
4,437
java
CacheResource.java
Java
[]
null
[]
package com.linkedin.thirdeye.dashboard.resources; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import com.google.common.cache.LoadingCache; import com.linkedin.thirdeye.datalayer.dto.DashboardConfigDTO; import com.linkedin.thirdeye.datalayer.dto.DatasetConfigDTO; import com.linkedin.thirdeye.datalayer.dto.MetricConfigDTO; import com.linkedin.thirdeye.datasource.DAORegistry; import com.linkedin.thirdeye.datasource.ThirdEyeCacheRegistry; import com.linkedin.thirdeye.datasource.cache.MetricDataset; @Path("/cache") @Produces(MediaType.APPLICATION_JSON) public class CacheResource { private static final ExecutorService EXECUTOR_SERVICE = Executors.newFixedThreadPool(20); private ThirdEyeCacheRegistry CACHE_INSTANCE = ThirdEyeCacheRegistry.getInstance(); private DAORegistry DAO_REGISTRY = DAORegistry.getInstance(); @GET @Path(value = "/") @Produces(MediaType.TEXT_HTML) public String getCaches() { return "usage"; } @POST @Path("/refresh") public Response refreshAllCaches() { refreshDatasets(); refreshDatasetConfigCache(); refreshMetricConfigCache(); refreshDashoardConfigsCache(); refreshMaxDataTimeCache(); refreshDimensionFiltersCache(); return Response.ok().build(); } @POST @Path("/refresh/maxDataTime") public Response refreshMaxDataTimeCache() { List<String> datasets = CACHE_INSTANCE.getDatasetsCache().getDatasets(); final LoadingCache<String,Long> cache = CACHE_INSTANCE.getDatasetMaxDataTimeCache(); for (final String dataset : datasets) { EXECUTOR_SERVICE.submit(new Runnable() { @Override public void run() { cache.refresh(dataset); } }); } return Response.ok().build(); } @POST @Path("/refresh/datasetConfig") public Response refreshDatasetConfigCache() { List<String> datasets = CACHE_INSTANCE.getDatasetsCache().getDatasets(); final LoadingCache<String,DatasetConfigDTO> cache = CACHE_INSTANCE.getDatasetConfigCache(); for (final String dataset : datasets) { EXECUTOR_SERVICE.submit(new Runnable() { @Override public void run() { cache.refresh(dataset); } }); } return Response.ok().build(); } @POST @Path("/refresh/metricConfig") public Response refreshMetricConfigCache() { final LoadingCache<MetricDataset, MetricConfigDTO> cache = CACHE_INSTANCE.getMetricConfigCache(); List<String> datasets = CACHE_INSTANCE.getDatasetsCache().getDatasets(); for (final String dataset : datasets) { EXECUTOR_SERVICE.submit(new Runnable() { @Override public void run() { List<MetricConfigDTO> metricConfigs = DAO_REGISTRY.getMetricConfigDAO().findByDataset(dataset); for (MetricConfigDTO metricConfig : metricConfigs) { cache.refresh(new MetricDataset(metricConfig.getName(), metricConfig.getDataset())); } } }); } return Response.ok().build(); } @POST @Path("/refresh/dashboardConfigs") public Response refreshDashoardConfigsCache() { List<String> datasets = CACHE_INSTANCE.getDatasetsCache().getDatasets(); final LoadingCache<String,List<DashboardConfigDTO>> cache = CACHE_INSTANCE.getDashboardConfigsCache(); for (final String dataset : datasets) { EXECUTOR_SERVICE.submit(new Runnable() { @Override public void run() { cache.refresh(dataset); } }); } return Response.ok().build(); } @POST @Path("/refresh/filters") public Response refreshDimensionFiltersCache() { List<String> datasets = CACHE_INSTANCE.getDatasetsCache().getDatasets(); final LoadingCache<String,String> cache = CACHE_INSTANCE.getDimensionFiltersCache(); for (final String dataset : datasets) { EXECUTOR_SERVICE.submit(new Runnable() { @Override public void run() { cache.refresh(dataset); } }); } return Response.ok().build(); } @POST @Path("/refresh/collections") public Response refreshDatasets() { Response response = Response.ok().build(); CACHE_INSTANCE.getDatasetsCache().loadDatasets(); return response; } }
4,437
0.69867
0.69822
153
28
26.370661
106
false
false
0
0
0
0
0
0
0.411765
false
false
12
11e726de209075b8e3b2b3706d886a62a9742bb9
24,876,450,581,841
3d033e82916942a1b9718c2e768979fd6fed0b47
/005-LoD/src/main/java/com/zhh/v1/Goods.java
eb4b1045a0f61d2d6d0dcdc4974c60292bc78e1f
[]
no_license
dsczs-org/java-design-patterns
https://github.com/dsczs-org/java-design-patterns
fe7eccdbf41d9bdcc50bb1435d1af67eb5d97284
4440e5fb84a8c8631f3576594bcf970b655b8992
refs/heads/master
2023-02-14T01:20:00.308000
2021-01-11T08:08:46
2021-01-11T08:08:46
318,802,015
0
0
null
true
2020-12-05T13:58:50
2020-12-05T13:58:49
2020-12-05T02:27:03
2020-04-27T23:31:35
180
0
0
0
null
false
false
package com.zhh.v1; /** * @author zhh * @description 商品类 * @date 2020-02-07 11:00 */ public class Goods { }
UTF-8
Java
119
java
Goods.java
Java
[ { "context": "package com.zhh.v1;\n\n/**\n * @author zhh\n * @description 商品类\n * @date 2020-02-07 11:00\n */", "end": 39, "score": 0.9996447563171387, "start": 36, "tag": "USERNAME", "value": "zhh" } ]
null
[]
package com.zhh.v1; /** * @author zhh * @description 商品类 * @date 2020-02-07 11:00 */ public class Goods { }
119
0.619469
0.504425
9
11.555555
9.190709
25
false
false
0
0
0
0
0
0
0.111111
false
false
12
f364fa74618afa82d2bb850dbb4b7f449e9e1ef2
33,079,838,124,792
c9fc9d7964a084115b3a5ca930bcf11cc9bba1b4
/programmieren-1/ÜbungsblätterWS18:19/Übungsblatt1/AufgabeE/src/Main.java
bb34bb1deb616706bc87bfa726d6a4fb6393714b
[]
no_license
oigGe/kit
https://github.com/oigGe/kit
3ebed1a5a5a9bc61bf191e22988d1ca23fec067f
494c363effadd8ec827c8c84d6da90c396f0659e
refs/heads/master
2020-04-09T08:22:22.098000
2019-08-26T09:22:19
2019-08-26T09:22:19
160,191,851
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
public class Main { public static void main(String[] args) { Agency kaAgency = new Agency(); Actor john = new Actor(); kaAgency.agencyName = "KaAgency"; john.forename = "John"; john.surname = "Wayne"; john.catchphrase = "All battles are fought by scared men who’d rather be some place else."; System.out.println(kaAgency.agencyName); System.out.println(john.surname); System.out.println(john.catchphrase); } }
UTF-8
Java
498
java
Main.java
Java
[ { "context": "gencyName = \"KaAgency\";\n\n john.forename = \"John\";\n john.surname = \"Wayne\";\n john.ca", "end": 213, "score": 0.9995735287666321, "start": 209, "tag": "NAME", "value": "John" }, { "context": " john.forename = \"John\";\n john.surname = \"Wayne\";\n john.catchphrase = \"All battles are fou", "end": 245, "score": 0.9976133704185486, "start": 240, "tag": "NAME", "value": "Wayne" } ]
null
[]
public class Main { public static void main(String[] args) { Agency kaAgency = new Agency(); Actor john = new Actor(); kaAgency.agencyName = "KaAgency"; john.forename = "John"; john.surname = "Wayne"; john.catchphrase = "All battles are fought by scared men who’d rather be some place else."; System.out.println(kaAgency.agencyName); System.out.println(john.surname); System.out.println(john.catchphrase); } }
498
0.614919
0.614919
19
25.105263
25.517578
99
false
false
0
0
0
0
0
0
0.473684
false
false
12
f89f08eb45fcbfe35146e587aa13e878b9a4cb24
33,079,838,124,895
cedb140c275c3ea8815fd5c57b9aaf24395d74b6
/Pemprograman #3/Fix/Unit Produksi - SMK YADIKA 11/Layout.java
565eb6828e456f76e001ba2b5dad3f6066a0cff3
[]
no_license
ronny-sugianto/Kuliah---Teknik-Informatika
https://github.com/ronny-sugianto/Kuliah---Teknik-Informatika
d26a4ab0c317a76ba5696c1e4096913a87d9ade6
9308b517a998daa8c8899af665bda7d7404b0d19
refs/heads/master
2020-09-20T04:30:42.782000
2020-01-20T04:35:04
2020-01-20T04:35:04
224,376,838
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
public class Layout { public void Header() { clrscr(); //System.out.println("********************************************************************************************"); System.out.println(" UNIT PRODUKSI - SMK YADIKA 11 "); System.out.println(" v.0.8 - BETA "); System.out.println("================================================================================================"); } public void Footer() { System.out.println("================================================================================================"); System.out.println("| TERIMA KASIH |"); System.out.println("================================================================================================"); System.out.println("|^| Credit By : \n- Ronny S (201843502340)\n- M.Hindardhi (201843502003)\n- Dicky A (201843502394)\n- Angga M (201843502394)"); System.out.println("|*| Will be uploaded on my blog on December 25 2019"); } public void Inventory_View() { System.out.println("================================================================================================"); System.out.println("|| ID || NAMA BARANG || VENDOR || PRICE || QTY ||"); System.out.println("================================================================================================"); } public void Users_View() { System.out.println("================================================================================================"); System.out.println("|| ID || KEY || NAME || LEVEL ||"); System.out.println("================================================================================================"); } public void StrukPay_View() { System.out.println("================================================================================"); System.out.println("|| NO || NAMA BARANG || QTY || TOTAL ||"); System.out.println("================================================================================"); } public void clrscr(){ //Clears Screen in java try { if (System.getProperty("os.name").contains("Windows")) new ProcessBuilder("cmd", "/c", "cls").inheritIO().start().waitFor(); else Runtime.getRuntime().exec("clear"); } catch (Exception ex) { System.exit(0); } } }
UTF-8
Java
2,890
java
Layout.java
Java
[ { "context": ";\n System.out.println(\"|^| Credit By : \\n- Ronny S (201843502340)\\n- M.Hindardhi (201843502003)\\n- D", "end": 1071, "score": 0.9998654723167419, "start": 1064, "tag": "NAME", "value": "Ronny S" }, { "context": "tln(\"|^| Credit By : \\n- Ronny S (201843502340)\\n- M.Hindardhi (201843502003)\\n- Dicky A (201843502394)\\n- Angga", "end": 1101, "score": 0.9995296597480774, "start": 1090, "tag": "NAME", "value": "M.Hindardhi" }, { "context": " S (201843502340)\\n- M.Hindardhi (201843502003)\\n- Dicky A (201843502394)\\n- Angga M (201843502394)\");\n ", "end": 1127, "score": 0.9998833537101746, "start": 1120, "tag": "NAME", "value": "Dicky A" }, { "context": "dardhi (201843502003)\\n- Dicky A (201843502394)\\n- Angga M (201843502394)\");\n System.out.println(\"|*", "end": 1153, "score": 0.9645926356315613, "start": 1146, "tag": "NAME", "value": "Angga M" } ]
null
[]
public class Layout { public void Header() { clrscr(); //System.out.println("********************************************************************************************"); System.out.println(" UNIT PRODUKSI - SMK YADIKA 11 "); System.out.println(" v.0.8 - BETA "); System.out.println("================================================================================================"); } public void Footer() { System.out.println("================================================================================================"); System.out.println("| TERIMA KASIH |"); System.out.println("================================================================================================"); System.out.println("|^| Credit By : \n- <NAME> (201843502340)\n- M.Hindardhi (201843502003)\n- <NAME> (201843502394)\n- <NAME> (201843502394)"); System.out.println("|*| Will be uploaded on my blog on December 25 2019"); } public void Inventory_View() { System.out.println("================================================================================================"); System.out.println("|| ID || NAMA BARANG || VENDOR || PRICE || QTY ||"); System.out.println("================================================================================================"); } public void Users_View() { System.out.println("================================================================================================"); System.out.println("|| ID || KEY || NAME || LEVEL ||"); System.out.println("================================================================================================"); } public void StrukPay_View() { System.out.println("================================================================================"); System.out.println("|| NO || NAMA BARANG || QTY || TOTAL ||"); System.out.println("================================================================================"); } public void clrscr(){ //Clears Screen in java try { if (System.getProperty("os.name").contains("Windows")) new ProcessBuilder("cmd", "/c", "cls").inheritIO().start().waitFor(); else Runtime.getRuntime().exec("clear"); } catch (Exception ex) { System.exit(0); } } }
2,887
0.281315
0.2609
50
56.740002
53.914307
156
false
false
0
0
0
0
96
0.287889
1.24
false
false
12
89302c0188b91b6b221538ebcbde9d3a65d1bab7
5,102,421,182,261
0084103b12283447c2610ba31309b2d2b8692bea
/src/day3/extents_demo/Demo.java
8d80f28b7d005c34a2f189fca51e0aae157bb63f
[]
no_license
wings-source/java-study
https://github.com/wings-source/java-study
04d5a6adf4f3137b680a4ffe7da5d97864f82b47
4b234328d865e3e0d05efe856c2e30e16a6b294d
refs/heads/master
2022-07-31T23:28:50.213000
2020-05-21T10:15:33
2020-05-21T10:15:33
265,814,607
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package day3.extents_demo; public class Demo { public static void main(String[] args) { Dog dog1 = new Dog(); Huskie dog2 = new Huskie(); System.out.println(dog1); System.out.println(dog2); System.out.println("---------"); //子类覆盖父类非静态方法 dog1.eat(); dog2.eat(); System.out.println("---------"); //非静态成员变量 System.out.println("age:" + dog1.age); System.out.println("age:" + dog2.age); System.out.println("---------"); //子类覆盖父类静态方法 dog1.bark(); dog2.bark(); } }
UTF-8
Java
659
java
Demo.java
Java
[]
null
[]
package day3.extents_demo; public class Demo { public static void main(String[] args) { Dog dog1 = new Dog(); Huskie dog2 = new Huskie(); System.out.println(dog1); System.out.println(dog2); System.out.println("---------"); //子类覆盖父类非静态方法 dog1.eat(); dog2.eat(); System.out.println("---------"); //非静态成员变量 System.out.println("age:" + dog1.age); System.out.println("age:" + dog2.age); System.out.println("---------"); //子类覆盖父类静态方法 dog1.bark(); dog2.bark(); } }
659
0.492537
0.474295
30
19.1
16.312265
46
false
false
0
0
0
0
0
0
0.466667
false
false
12
2244c47a767630024cfde52201a88ef1ca263ec0
19,774,029,494,422
051d32d1c0b5996ef7c61d5e7e04c07c4ab0128d
/app/src/main/java/com/subscription/android/client/view/InstructorBaseActivity.java
f61d444fdc13205f1f1c6f8d0c2cd31afc123c3e
[]
no_license
Kirill-code/SubscriptionAndroidClient
https://github.com/Kirill-code/SubscriptionAndroidClient
a2b8e88e615dba4f59bdf2336bdb6ad5ef59e858
f0d93da24b3b635ff572f1e620c697239705d088
refs/heads/master
2021-07-10T05:08:44.796000
2020-07-31T14:27:20
2020-07-31T14:27:20
178,858,917
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.subscription.android.client.view; import android.content.Intent; import android.os.Build; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.ArrayAdapter; import android.widget.TextView; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.annotation.RequiresApi; import androidx.appcompat.widget.Toolbar; import androidx.core.widget.NestedScrollView; import androidx.recyclerview.widget.GridLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.android.material.bottomappbar.BottomAppBar; import com.google.android.material.bottomsheet.BottomSheetDialogFragment; import com.google.android.material.floatingactionbutton.FloatingActionButton; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.auth.GetTokenResult; import com.google.zxing.integration.android.IntentIntegrator; import com.google.zxing.integration.android.IntentResult; import com.subscription.android.client.Api; import com.subscription.android.client.BaseActivity; import com.subscription.android.client.VisitCardRecyclerViewAdapter; import com.subscription.android.client.VisitGridItemDecoration; import com.subscription.android.client.R; import com.subscription.android.client.fragments.BottomSheetNavigationFragment; import com.subscription.android.client.fragments.DateRangePickerFragment; import com.subscription.android.client.model.DTO.VisitsDTO; import com.subscription.android.client.model.Instructor; import com.subscription.android.client.model.Subscription; import com.subscription.android.client.print.PrinterActivity; import java.io.EOFException; import java.net.ConnectException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.time.LocalDate; import java.time.temporal.TemporalAdjusters; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; import java.util.Locale; import java.util.concurrent.TimeoutException; import io.reactivex.Observable; import io.reactivex.Observer; import io.reactivex.disposables.Disposable; import io.reactivex.functions.Consumer; import io.reactivex.schedulers.Schedulers; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; import retrofit2.Retrofit; import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory; import retrofit2.converter.gson.GsonConverterFactory; public class InstructorBaseActivity extends BaseActivity implements DateRangePickerFragment.OnDateRangeSelectedListener { private static final String TAG = InstructorBaseActivity.class.getName(); RecyclerView recyclerView; BottomAppBar bottomAppBar; TextView adminBtn; Instructor intentInstructor=new Instructor(); public Retrofit retrofitRx = new Retrofit.Builder() .baseUrl(Api.BASE_URL) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .addConverterFactory(GsonConverterFactory.create()) .build(); public Api apiRx = retrofitRx.create(Api.class); public FirebaseUser mUserInstr = FirebaseAuth.getInstance().getCurrentUser(); @RequiresApi(api = Build.VERSION_CODES.O) protected void onCreate(Bundle savedInstanceState) { Log.i(TAG, "Activity started"); super.onCreate(savedInstanceState); setContentView(R.layout.activity_instructor_base); BaseActivity base=new BaseActivity(); base.getToken(); showProgressDialog(); //Разобраться с состоянием ответов getTokenLocaly(mUserInstr.getUid()); FloatingActionButton fab=findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { IntentIntegrator integrator = new IntentIntegrator(InstructorBaseActivity.this); integrator.setDesiredBarcodeFormats(IntentIntegrator.QR_CODE_TYPES); integrator.setCameraId(0); integrator.setBeepEnabled(false); integrator.initiateScan(); } }); //add position of current date or nearest //int scrollTo = ((View) childView.getParent().getParent()).getTop() + childView.getTop(); //adminBtn=findViewById(R.id.app_bar_person); View.OnClickListener oclBtnOk = new View.OnClickListener() { @Override public void onClick(View v) { go2AdminPage(); } }; // Bars Toolbar myToolbar = findViewById(R.id.app_bar); setSupportActionBar(myToolbar); bottomAppBar=findViewById(R.id.bottom_app_bar); bottomAppBar.replaceMenu(R.menu.bottomappbar_menu); bottomAppBar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { //open bottom sheet BottomSheetDialogFragment bottomSheetDialogFragment = BottomSheetNavigationFragment.newInstance(); bottomSheetDialogFragment.show(getSupportFragmentManager(), "Bottom Sheet Dialog Fragment"); } }); bottomAppBar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem item) { switch (item.getItemId()) { case R.id.app_bar_add: go2Print(); break; } return false; } }); } private void getCurrentMonth(long instructorId) { Calendar calendar = Calendar.getInstance(); calendar.set(Calendar.DATE, calendar.getActualMinimum(Calendar.DAY_OF_MONTH)); Date MonthFirstDay = calendar.getTime(); calendar.set(Calendar.DATE, calendar.getActualMaximum(Calendar.DAY_OF_MONTH)); Date MonthLastDay = calendar.getTime(); getVisitsInPeriod(instructorId,sdf.format(MonthFirstDay),sdf.format(MonthLastDay)); // getVisitsInPeriodRx(1,sdf.format(MonthFirstDay),sdf.format(MonthLastDay)); } public void getTokenLocaly(String uid){ mUser.getIdToken(true) .addOnCompleteListener(new OnCompleteListener<GetTokenResult>() { public void onComplete(@NonNull Task<GetTokenResult> task) { if (task.isSuccessful()) { String idToken = task.getResult().getToken(); ////////////////////////////delete this token assigmnet! getInstructor(idToken,uid); } else { Log.e("CallbackException", task.getException().toString()); } } }); } public void getInstructor(String idtokenlocal, String uid ) { Call<Instructor> call = api.getInstructorByUid(idtokenlocal, uid); call.enqueue(new Callback<Instructor>() { @Override public void onResponse(Call<Instructor> call, Response<Instructor> response) { if(response!=null) { Instructor tempInstructor=new Instructor(); tempInstructor.setId(response.body().getId()); tempInstructor.setName(response.body().getName()); tempInstructor.setSurname(response.body().getSurname()); //change to callbacks getCurrentMonth(response.body().getId()); } } @Override public void onFailure(Call<Instructor> call, Throwable t) { try { throw t; } catch (ConnectException ex) { Log.e(TAG, ex.getMessage()); hideProgressDialog(); Toast.makeText(getApplicationContext(), getResources().getString(R.string.errorconnection), Toast.LENGTH_SHORT).show(); } catch (EOFException ex) { Log.e(TAG, ex.getMessage()); hideProgressDialog(); Toast.makeText(getApplicationContext(), getResources().getString(R.string.helpdesk), Toast.LENGTH_SHORT).show(); } catch (Throwable et) { Log.e(TAG, et.getMessage()); hideProgressDialog(); Toast.makeText(getApplicationContext(), getResources().getString(R.string.helpdesk), Toast.LENGTH_SHORT).show(); } } }); } //old version will be changed by RxJava implementation private void getVisitsInPeriod(long instid,String dateStart, String dateEnd) { recyclerView=null; Call<List<List>> call = api.getMonthVisits(instid,dateStart,dateEnd); call.enqueue(new Callback<List<List>>() { @Override public void onResponse(Call<List<List>> call, Response<List<List>> response) { hideProgressDialog(); //CAST PROBLEMS List<List> responseVisits = response.body(); List<VisitsDTO> tempList=new ArrayList<>(); for (int i=0;i<response.body().size();i++) { VisitsDTO temp=new VisitsDTO(); temp.setDate(response.body().get(i).get(0).toString()); temp.setVisits_count((double) response.body().get(i).get(1)); temp.setInstr_id((double) response.body().get(i).get(2)); tempList.add(temp); } VisitCardRecyclerViewAdapter adapter = new VisitCardRecyclerViewAdapter(tempList); recyclerView = findViewById(R.id.recycler_view); NestedScrollView nestedScrollView=findViewById(R.id.nsv); recyclerView.setHasFixedSize(true); recyclerView.setLayoutManager(new GridLayoutManager(getApplicationContext(), 1, GridLayoutManager.VERTICAL, false)); int largePadding = getResources().getDimensionPixelSize(R.dimen.shr_product_grid_spacing); int smallPadding = getResources().getDimensionPixelSize(R.dimen.shr_product_grid_spacing_small); recyclerView.addItemDecoration(new VisitGridItemDecoration(largePadding, smallPadding)); recyclerView.setAdapter(adapter); //add scroll to position here /*recyclerView.post(() -> { float y = recyclerView.getY() + recyclerView.getChildAt(2).getY(); nestedScrollView.smoothScrollTo(0, (int) y); });*/ } @Override public void onFailure(Call<List<List>> call, Throwable t) { try { throw t; } catch (ConnectException ex) { Log.e(TAG, ex.getMessage()); hideProgressDialog(); Toast.makeText(getApplicationContext(),getResources().getString(R.string.errorconnection) , Toast.LENGTH_SHORT).show(); } catch (TimeoutException ex) { Log.e(TAG, ex.getMessage()); hideProgressDialog(); Toast.makeText(getApplicationContext(),getResources().getString(R.string.timeout) , Toast.LENGTH_SHORT).show(); } catch (Throwable et) { Log.e(TAG, et.getMessage()); hideProgressDialog(); Toast.makeText(getApplicationContext(),getResources().getString(R.string.helpdesk) , Toast.LENGTH_SHORT).show(); } } }); } private void getVisitsInPeriodRx(long instid,String dateStart, String dateEnd) { apiRx.getMonthVisitsRx(instid,dateStart,dateEnd) .toObservable() .subscribeOn(Schedulers.io()) .subscribe(new Observer<List<List>>() { @Override public void onSubscribe(Disposable d) { } @Override public void onNext(List<List> list) { Log.d(TAG,"onNext:"); System.out.println(); } @Override public void onError(Throwable e) { Log.e(TAG,"onError",e); } @Override public void onComplete() { } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.uptoolbar_menu,menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()){ case R.id.search: Toast.makeText(this, "Clicked Person", Toast.LENGTH_SHORT).show(); break; case R.id.filter: DateRangePickerFragment dateRangePickerFragment= DateRangePickerFragment.newInstance(InstructorBaseActivity.this,false); dateRangePickerFragment.show(getSupportFragmentManager(),"datePicker"); break; } return true; } private void go2Print() { Intent intent = new Intent(this, PrinterActivity.class); intent.putExtra("Instructor2Sub", intentInstructor); startActivity(intent); } private void go2AdminPage() { Intent intent = new Intent(this, AdminActivity.class); startActivity(intent); } private void updateSubscription(String uid) { FirebaseUser mUser = FirebaseAuth.getInstance().getCurrentUser(); mUser.getIdToken(true) .addOnCompleteListener(new OnCompleteListener<GetTokenResult>() { public void onComplete(@NonNull Task<GetTokenResult> task) { if (task.isSuccessful()) { String idToken = task.getResult().getToken(); showProgressDialog(); Call<Subscription> call = api.getSubscriptionByUid(idToken,uid); call.enqueue(new Callback<Subscription>() { @Override public void onResponse(Call<Subscription> call, Response<Subscription> response) { Call<Void> call2save = api.savevisit(response.body().getAssociatedUserId()); call2save.enqueue(new Callback<Void>() { @Override public void onResponse(Call<Void> call2save, Response<Void> response) { hideProgressDialog(); Toast.makeText(getApplicationContext(), getResources().getText(R.string.scanSucsessful), Toast.LENGTH_SHORT).show(); } @Override public void onFailure(Call<Void> call2save, Throwable t) { Log.e(TAG, t.getMessage()); hideProgressDialog(); Toast.makeText(getApplicationContext(), getResources().getText(R.string.repeatlater), Toast.LENGTH_SHORT).show(); } }); } @Override public void onFailure(Call<Subscription> call, Throwable t) { try { throw t; } catch (ConnectException ex) { hideProgressDialog(); Log.e(TAG, ex.getMessage()); String[] visitedDates = {getResources().getString(R.string.errorconnection)}; // gvMain.setAdapter(new ArrayAdapter<String>(getApplicationContext(), R.layout.list_black_text, R.id.list_content, visitedDates)); } catch (EOFException ex) { Log.e(TAG, ex.getMessage()); hideProgressDialog(); String[] visitedDates = {getResources().getString(R.string.emptylessons)}; // gvMain.setAdapter(new ArrayAdapter<String>(getApplicationContext(), R.layout.list_black_text, R.id.list_content, visitedDates)); } catch (Throwable et) { Log.e(TAG, et.getMessage()); hideProgressDialog(); String[] visitedDates = {getResources().getString(R.string.helpdesk)}; // gvMain.setAdapter(new ArrayAdapter<String>(getApplicationContext(), R.layout.list_black_text, R.id.list_content, visitedDates)); } } }); } else { Log.e(TAG, task.getException().toString()); } } }); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data); if (result != null) { if (result.getContents() == null) { Log.i(TAG, "Cancelled scan"); } else { System.out.println(result.getContents().substring(0, 7)); if (result.getContents().substring(0, 8).equals("syryauid")) { Log.i(TAG, "Scanned:" + result.getContents()); Toast.makeText(this, "Scan", Toast.LENGTH_SHORT).show(); updateSubscription(result.getContents().substring(8)); } else { Toast.makeText(this, "Scan", Toast.LENGTH_SHORT).show(); Log.e(TAG, result.getContents()); Toast.makeText(getApplicationContext(), getResources().getText(R.string.qrscanerror), Toast.LENGTH_SHORT).show(); } } } else { // This is important, otherwise the result will not be passed to the fragment super.onActivityResult(requestCode, resultCode, data); } } @Override public void onDateRangeSelected(int startDay, int startMonth, int startYear, int endDay, int endMonth, int endYear) { if(startDay==endDay){ Toast.makeText(getApplicationContext(),getResources().getString(R.string.samedate) , Toast.LENGTH_SHORT).show(); } Calendar calendar = Calendar.getInstance(); calendar.set(startYear,startMonth,startDay ); Date startDate = calendar.getTime(); calendar.set(endYear,endMonth,endDay ); Date endDate = calendar.getTime(); getVisitsInPeriod(1,sdf.format(startDate),sdf.format(endDate)); } @Override public void onPointerCaptureChanged(boolean hasCapture) { } }
UTF-8
Java
19,911
java
InstructorBaseActivity.java
Java
[]
null
[]
package com.subscription.android.client.view; import android.content.Intent; import android.os.Build; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.ArrayAdapter; import android.widget.TextView; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.annotation.RequiresApi; import androidx.appcompat.widget.Toolbar; import androidx.core.widget.NestedScrollView; import androidx.recyclerview.widget.GridLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.android.material.bottomappbar.BottomAppBar; import com.google.android.material.bottomsheet.BottomSheetDialogFragment; import com.google.android.material.floatingactionbutton.FloatingActionButton; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.auth.GetTokenResult; import com.google.zxing.integration.android.IntentIntegrator; import com.google.zxing.integration.android.IntentResult; import com.subscription.android.client.Api; import com.subscription.android.client.BaseActivity; import com.subscription.android.client.VisitCardRecyclerViewAdapter; import com.subscription.android.client.VisitGridItemDecoration; import com.subscription.android.client.R; import com.subscription.android.client.fragments.BottomSheetNavigationFragment; import com.subscription.android.client.fragments.DateRangePickerFragment; import com.subscription.android.client.model.DTO.VisitsDTO; import com.subscription.android.client.model.Instructor; import com.subscription.android.client.model.Subscription; import com.subscription.android.client.print.PrinterActivity; import java.io.EOFException; import java.net.ConnectException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.time.LocalDate; import java.time.temporal.TemporalAdjusters; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; import java.util.Locale; import java.util.concurrent.TimeoutException; import io.reactivex.Observable; import io.reactivex.Observer; import io.reactivex.disposables.Disposable; import io.reactivex.functions.Consumer; import io.reactivex.schedulers.Schedulers; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; import retrofit2.Retrofit; import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory; import retrofit2.converter.gson.GsonConverterFactory; public class InstructorBaseActivity extends BaseActivity implements DateRangePickerFragment.OnDateRangeSelectedListener { private static final String TAG = InstructorBaseActivity.class.getName(); RecyclerView recyclerView; BottomAppBar bottomAppBar; TextView adminBtn; Instructor intentInstructor=new Instructor(); public Retrofit retrofitRx = new Retrofit.Builder() .baseUrl(Api.BASE_URL) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .addConverterFactory(GsonConverterFactory.create()) .build(); public Api apiRx = retrofitRx.create(Api.class); public FirebaseUser mUserInstr = FirebaseAuth.getInstance().getCurrentUser(); @RequiresApi(api = Build.VERSION_CODES.O) protected void onCreate(Bundle savedInstanceState) { Log.i(TAG, "Activity started"); super.onCreate(savedInstanceState); setContentView(R.layout.activity_instructor_base); BaseActivity base=new BaseActivity(); base.getToken(); showProgressDialog(); //Разобраться с состоянием ответов getTokenLocaly(mUserInstr.getUid()); FloatingActionButton fab=findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { IntentIntegrator integrator = new IntentIntegrator(InstructorBaseActivity.this); integrator.setDesiredBarcodeFormats(IntentIntegrator.QR_CODE_TYPES); integrator.setCameraId(0); integrator.setBeepEnabled(false); integrator.initiateScan(); } }); //add position of current date or nearest //int scrollTo = ((View) childView.getParent().getParent()).getTop() + childView.getTop(); //adminBtn=findViewById(R.id.app_bar_person); View.OnClickListener oclBtnOk = new View.OnClickListener() { @Override public void onClick(View v) { go2AdminPage(); } }; // Bars Toolbar myToolbar = findViewById(R.id.app_bar); setSupportActionBar(myToolbar); bottomAppBar=findViewById(R.id.bottom_app_bar); bottomAppBar.replaceMenu(R.menu.bottomappbar_menu); bottomAppBar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { //open bottom sheet BottomSheetDialogFragment bottomSheetDialogFragment = BottomSheetNavigationFragment.newInstance(); bottomSheetDialogFragment.show(getSupportFragmentManager(), "Bottom Sheet Dialog Fragment"); } }); bottomAppBar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem item) { switch (item.getItemId()) { case R.id.app_bar_add: go2Print(); break; } return false; } }); } private void getCurrentMonth(long instructorId) { Calendar calendar = Calendar.getInstance(); calendar.set(Calendar.DATE, calendar.getActualMinimum(Calendar.DAY_OF_MONTH)); Date MonthFirstDay = calendar.getTime(); calendar.set(Calendar.DATE, calendar.getActualMaximum(Calendar.DAY_OF_MONTH)); Date MonthLastDay = calendar.getTime(); getVisitsInPeriod(instructorId,sdf.format(MonthFirstDay),sdf.format(MonthLastDay)); // getVisitsInPeriodRx(1,sdf.format(MonthFirstDay),sdf.format(MonthLastDay)); } public void getTokenLocaly(String uid){ mUser.getIdToken(true) .addOnCompleteListener(new OnCompleteListener<GetTokenResult>() { public void onComplete(@NonNull Task<GetTokenResult> task) { if (task.isSuccessful()) { String idToken = task.getResult().getToken(); ////////////////////////////delete this token assigmnet! getInstructor(idToken,uid); } else { Log.e("CallbackException", task.getException().toString()); } } }); } public void getInstructor(String idtokenlocal, String uid ) { Call<Instructor> call = api.getInstructorByUid(idtokenlocal, uid); call.enqueue(new Callback<Instructor>() { @Override public void onResponse(Call<Instructor> call, Response<Instructor> response) { if(response!=null) { Instructor tempInstructor=new Instructor(); tempInstructor.setId(response.body().getId()); tempInstructor.setName(response.body().getName()); tempInstructor.setSurname(response.body().getSurname()); //change to callbacks getCurrentMonth(response.body().getId()); } } @Override public void onFailure(Call<Instructor> call, Throwable t) { try { throw t; } catch (ConnectException ex) { Log.e(TAG, ex.getMessage()); hideProgressDialog(); Toast.makeText(getApplicationContext(), getResources().getString(R.string.errorconnection), Toast.LENGTH_SHORT).show(); } catch (EOFException ex) { Log.e(TAG, ex.getMessage()); hideProgressDialog(); Toast.makeText(getApplicationContext(), getResources().getString(R.string.helpdesk), Toast.LENGTH_SHORT).show(); } catch (Throwable et) { Log.e(TAG, et.getMessage()); hideProgressDialog(); Toast.makeText(getApplicationContext(), getResources().getString(R.string.helpdesk), Toast.LENGTH_SHORT).show(); } } }); } //old version will be changed by RxJava implementation private void getVisitsInPeriod(long instid,String dateStart, String dateEnd) { recyclerView=null; Call<List<List>> call = api.getMonthVisits(instid,dateStart,dateEnd); call.enqueue(new Callback<List<List>>() { @Override public void onResponse(Call<List<List>> call, Response<List<List>> response) { hideProgressDialog(); //CAST PROBLEMS List<List> responseVisits = response.body(); List<VisitsDTO> tempList=new ArrayList<>(); for (int i=0;i<response.body().size();i++) { VisitsDTO temp=new VisitsDTO(); temp.setDate(response.body().get(i).get(0).toString()); temp.setVisits_count((double) response.body().get(i).get(1)); temp.setInstr_id((double) response.body().get(i).get(2)); tempList.add(temp); } VisitCardRecyclerViewAdapter adapter = new VisitCardRecyclerViewAdapter(tempList); recyclerView = findViewById(R.id.recycler_view); NestedScrollView nestedScrollView=findViewById(R.id.nsv); recyclerView.setHasFixedSize(true); recyclerView.setLayoutManager(new GridLayoutManager(getApplicationContext(), 1, GridLayoutManager.VERTICAL, false)); int largePadding = getResources().getDimensionPixelSize(R.dimen.shr_product_grid_spacing); int smallPadding = getResources().getDimensionPixelSize(R.dimen.shr_product_grid_spacing_small); recyclerView.addItemDecoration(new VisitGridItemDecoration(largePadding, smallPadding)); recyclerView.setAdapter(adapter); //add scroll to position here /*recyclerView.post(() -> { float y = recyclerView.getY() + recyclerView.getChildAt(2).getY(); nestedScrollView.smoothScrollTo(0, (int) y); });*/ } @Override public void onFailure(Call<List<List>> call, Throwable t) { try { throw t; } catch (ConnectException ex) { Log.e(TAG, ex.getMessage()); hideProgressDialog(); Toast.makeText(getApplicationContext(),getResources().getString(R.string.errorconnection) , Toast.LENGTH_SHORT).show(); } catch (TimeoutException ex) { Log.e(TAG, ex.getMessage()); hideProgressDialog(); Toast.makeText(getApplicationContext(),getResources().getString(R.string.timeout) , Toast.LENGTH_SHORT).show(); } catch (Throwable et) { Log.e(TAG, et.getMessage()); hideProgressDialog(); Toast.makeText(getApplicationContext(),getResources().getString(R.string.helpdesk) , Toast.LENGTH_SHORT).show(); } } }); } private void getVisitsInPeriodRx(long instid,String dateStart, String dateEnd) { apiRx.getMonthVisitsRx(instid,dateStart,dateEnd) .toObservable() .subscribeOn(Schedulers.io()) .subscribe(new Observer<List<List>>() { @Override public void onSubscribe(Disposable d) { } @Override public void onNext(List<List> list) { Log.d(TAG,"onNext:"); System.out.println(); } @Override public void onError(Throwable e) { Log.e(TAG,"onError",e); } @Override public void onComplete() { } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.uptoolbar_menu,menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()){ case R.id.search: Toast.makeText(this, "Clicked Person", Toast.LENGTH_SHORT).show(); break; case R.id.filter: DateRangePickerFragment dateRangePickerFragment= DateRangePickerFragment.newInstance(InstructorBaseActivity.this,false); dateRangePickerFragment.show(getSupportFragmentManager(),"datePicker"); break; } return true; } private void go2Print() { Intent intent = new Intent(this, PrinterActivity.class); intent.putExtra("Instructor2Sub", intentInstructor); startActivity(intent); } private void go2AdminPage() { Intent intent = new Intent(this, AdminActivity.class); startActivity(intent); } private void updateSubscription(String uid) { FirebaseUser mUser = FirebaseAuth.getInstance().getCurrentUser(); mUser.getIdToken(true) .addOnCompleteListener(new OnCompleteListener<GetTokenResult>() { public void onComplete(@NonNull Task<GetTokenResult> task) { if (task.isSuccessful()) { String idToken = task.getResult().getToken(); showProgressDialog(); Call<Subscription> call = api.getSubscriptionByUid(idToken,uid); call.enqueue(new Callback<Subscription>() { @Override public void onResponse(Call<Subscription> call, Response<Subscription> response) { Call<Void> call2save = api.savevisit(response.body().getAssociatedUserId()); call2save.enqueue(new Callback<Void>() { @Override public void onResponse(Call<Void> call2save, Response<Void> response) { hideProgressDialog(); Toast.makeText(getApplicationContext(), getResources().getText(R.string.scanSucsessful), Toast.LENGTH_SHORT).show(); } @Override public void onFailure(Call<Void> call2save, Throwable t) { Log.e(TAG, t.getMessage()); hideProgressDialog(); Toast.makeText(getApplicationContext(), getResources().getText(R.string.repeatlater), Toast.LENGTH_SHORT).show(); } }); } @Override public void onFailure(Call<Subscription> call, Throwable t) { try { throw t; } catch (ConnectException ex) { hideProgressDialog(); Log.e(TAG, ex.getMessage()); String[] visitedDates = {getResources().getString(R.string.errorconnection)}; // gvMain.setAdapter(new ArrayAdapter<String>(getApplicationContext(), R.layout.list_black_text, R.id.list_content, visitedDates)); } catch (EOFException ex) { Log.e(TAG, ex.getMessage()); hideProgressDialog(); String[] visitedDates = {getResources().getString(R.string.emptylessons)}; // gvMain.setAdapter(new ArrayAdapter<String>(getApplicationContext(), R.layout.list_black_text, R.id.list_content, visitedDates)); } catch (Throwable et) { Log.e(TAG, et.getMessage()); hideProgressDialog(); String[] visitedDates = {getResources().getString(R.string.helpdesk)}; // gvMain.setAdapter(new ArrayAdapter<String>(getApplicationContext(), R.layout.list_black_text, R.id.list_content, visitedDates)); } } }); } else { Log.e(TAG, task.getException().toString()); } } }); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data); if (result != null) { if (result.getContents() == null) { Log.i(TAG, "Cancelled scan"); } else { System.out.println(result.getContents().substring(0, 7)); if (result.getContents().substring(0, 8).equals("syryauid")) { Log.i(TAG, "Scanned:" + result.getContents()); Toast.makeText(this, "Scan", Toast.LENGTH_SHORT).show(); updateSubscription(result.getContents().substring(8)); } else { Toast.makeText(this, "Scan", Toast.LENGTH_SHORT).show(); Log.e(TAG, result.getContents()); Toast.makeText(getApplicationContext(), getResources().getText(R.string.qrscanerror), Toast.LENGTH_SHORT).show(); } } } else { // This is important, otherwise the result will not be passed to the fragment super.onActivityResult(requestCode, resultCode, data); } } @Override public void onDateRangeSelected(int startDay, int startMonth, int startYear, int endDay, int endMonth, int endYear) { if(startDay==endDay){ Toast.makeText(getApplicationContext(),getResources().getString(R.string.samedate) , Toast.LENGTH_SHORT).show(); } Calendar calendar = Calendar.getInstance(); calendar.set(startYear,startMonth,startDay ); Date startDate = calendar.getTime(); calendar.set(endYear,endMonth,endDay ); Date endDate = calendar.getTime(); getVisitsInPeriod(1,sdf.format(startDate),sdf.format(endDate)); } @Override public void onPointerCaptureChanged(boolean hasCapture) { } }
19,911
0.576552
0.574892
473
41.033825
33.311062
170
false
false
0
0
0
0
0
0
0.706131
false
false
12
3c5570287ce4e188214c7567ef37277633d9f1a2
10,797,547,808,027
fe3302ffd3c3f111b0f593b823aeaf4bf517231c
/src/main/java/com/etps/etps/repositories/Providers.java
eeaf062213e2ec7dba53d1b61fe015bcfb29f3e0
[]
no_license
Deimos-ETPS/ETPS
https://github.com/Deimos-ETPS/ETPS
8d96d5099a0bc8f1900d7276e30a4c7983ae6e8d
762f00e04d5ceb1771448ead57b83d27b2361365
refs/heads/master
2022-05-03T03:12:48.527000
2020-03-03T01:32:45
2020-03-03T01:32:45
239,542,195
0
1
null
false
2022-03-08T21:25:04
2020-02-10T15:16:19
2020-03-03T01:32:58
2022-03-08T21:25:03
27,904
0
1
2
HTML
false
false
package com.etps.etps.repositories; import com.etps.etps.models.Campus; import com.etps.etps.models.Provider; import org.springframework.data.jpa.repository.JpaRepository; public interface Providers extends JpaRepository<Provider, Long> { Provider findById(long id); Provider findAllById(long id); Provider findAllByProvId(long id); Provider existsById(long id); }
UTF-8
Java
383
java
Providers.java
Java
[]
null
[]
package com.etps.etps.repositories; import com.etps.etps.models.Campus; import com.etps.etps.models.Provider; import org.springframework.data.jpa.repository.JpaRepository; public interface Providers extends JpaRepository<Provider, Long> { Provider findById(long id); Provider findAllById(long id); Provider findAllByProvId(long id); Provider existsById(long id); }
383
0.78329
0.78329
12
30.916666
20.568821
66
false
false
0
0
0
0
0
0
0.75
false
false
12
0c6e6f7de28558a7be03708eddd36236b9b9609e
10,797,547,807,108
6b31a49203cb1a2240b2e0014f759eda94443d59
/src/test/java/managers/ConfigFileManager.java
fa54af34c366739261121169b0ed3e2bcdbf0826
[]
no_license
packman38/bookmyshow1-Website-Automation
https://github.com/packman38/bookmyshow1-Website-Automation
2114b388403f77778c28177df91379c57e9fb7dd
3bd5af406fc01288db37322afde3c73d221ef285
refs/heads/main
2023-06-05T16:25:21.199000
2021-06-30T18:55:29
2021-06-30T18:55:29
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package test.java.managers; import java.io.BufferedReader; import java.io.FileReader; import java.util.Properties; public class ConfigFileManager { private static ConfigFileManager configFileManager= null; private Properties properties; private final String proportiesFilePath="\\src\\main\\resources\\config.properties"; private String propertyValue; private ConfigFileManager(){ BufferedReader reader; System.out.println("In config reader"); try{ System.out.print(System.getProperty("user.dir")); System.out.println(proportiesFilePath); reader=new BufferedReader(new FileReader(System.getProperty("user.dir")+proportiesFilePath)); properties= new Properties(); properties.load(reader); reader.close(); }catch(Exception E){ System.out.println(E.getStackTrace()); } } public static ConfigFileManager getInstance(){ return (configFileManager==null)?configFileManager=new ConfigFileManager():configFileManager; } public String getBrowserName(){ propertyValue= properties.getProperty("browser"); if(propertyValue!=null){ return propertyValue; }else{ throw new RuntimeException("browser not mentioned in Config"); } } public boolean getMaximizedStatus(){ propertyValue=properties.getProperty("windowMaximize"); if(propertyValue!=null){ return Boolean.valueOf(propertyValue); }else{ System.out.println("Maximize Status not specified running on Maximized mode"); return true; } } public long getImplicitWait() { propertyValue=properties.getProperty("implicitWait"); if(propertyValue!=null){ return Long.parseLong(propertyValue); }else{ System.out.println("Implicit wait not specified running with 1 sec"); return 1;// in second } } public String getMode() { propertyValue=properties.getProperty("mode"); if(propertyValue!=null){ return propertyValue; }else{ System.out.println("mode not specified so running on local"); return "local"; } } }
UTF-8
Java
2,303
java
ConfigFileManager.java
Java
[]
null
[]
package test.java.managers; import java.io.BufferedReader; import java.io.FileReader; import java.util.Properties; public class ConfigFileManager { private static ConfigFileManager configFileManager= null; private Properties properties; private final String proportiesFilePath="\\src\\main\\resources\\config.properties"; private String propertyValue; private ConfigFileManager(){ BufferedReader reader; System.out.println("In config reader"); try{ System.out.print(System.getProperty("user.dir")); System.out.println(proportiesFilePath); reader=new BufferedReader(new FileReader(System.getProperty("user.dir")+proportiesFilePath)); properties= new Properties(); properties.load(reader); reader.close(); }catch(Exception E){ System.out.println(E.getStackTrace()); } } public static ConfigFileManager getInstance(){ return (configFileManager==null)?configFileManager=new ConfigFileManager():configFileManager; } public String getBrowserName(){ propertyValue= properties.getProperty("browser"); if(propertyValue!=null){ return propertyValue; }else{ throw new RuntimeException("browser not mentioned in Config"); } } public boolean getMaximizedStatus(){ propertyValue=properties.getProperty("windowMaximize"); if(propertyValue!=null){ return Boolean.valueOf(propertyValue); }else{ System.out.println("Maximize Status not specified running on Maximized mode"); return true; } } public long getImplicitWait() { propertyValue=properties.getProperty("implicitWait"); if(propertyValue!=null){ return Long.parseLong(propertyValue); }else{ System.out.println("Implicit wait not specified running with 1 sec"); return 1;// in second } } public String getMode() { propertyValue=properties.getProperty("mode"); if(propertyValue!=null){ return propertyValue; }else{ System.out.println("mode not specified so running on local"); return "local"; } } }
2,303
0.636127
0.635258
73
30.547945
26.179068
105
false
false
0
0
0
0
0
0
0.452055
false
false
12
b6ce2ae4484904c8ae01c1e43624b52579471ded
31,679,678,778,988
c2445630a94625eeedc7bb4a3c9ad0f90f5bd0e3
/src/projectPlanner/BarChartGenerator.java
ae5a53c6805463a3d22bdd394e659d12bd7ada97
[]
no_license
AndroCrunch/ProjectPlanner
https://github.com/AndroCrunch/ProjectPlanner
8322da44c5dd9d1457fe8965351b4f765647f624
d873b46072e743de912d8b32c18bfff0f0c4f45c
refs/heads/master
2022-02-25T05:35:45.325000
2015-05-11T14:47:04
2015-05-11T14:47:11
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package projectPlanner; import java.awt.image.BufferedImage; import java.io.*; import java.sql.SQLException; import org.jfree.chart.ChartFactory; import org.jfree.chart.JFreeChart; import org.jfree.chart.plot.PlotOrientation; import org.jfree.data.category.DefaultCategoryDataset; public class BarChartGenerator{ JFreeChart barChart; public BarChartGenerator(Project project) throws SQLException{ final DefaultCategoryDataset dataset = new DefaultCategoryDataset( ); for(Activity current : project.getActivities()){ dataset.addValue(current.getTimeAccumulated(), current.getTitle()," "); } barChart = ChartFactory.createBarChart( "DISTRIBUTION OF MAN-HOURS", "Activities", "Man-hours", dataset,PlotOrientation.VERTICAL, true, true, false); } public BufferedImage getgraph() throws IOException{ int width = 1700; int height = 960; BufferedImage bufferedImage = barChart.createBufferedImage(width, height); return bufferedImage; } }
UTF-8
Java
996
java
BarChartGenerator.java
Java
[]
null
[]
package projectPlanner; import java.awt.image.BufferedImage; import java.io.*; import java.sql.SQLException; import org.jfree.chart.ChartFactory; import org.jfree.chart.JFreeChart; import org.jfree.chart.plot.PlotOrientation; import org.jfree.data.category.DefaultCategoryDataset; public class BarChartGenerator{ JFreeChart barChart; public BarChartGenerator(Project project) throws SQLException{ final DefaultCategoryDataset dataset = new DefaultCategoryDataset( ); for(Activity current : project.getActivities()){ dataset.addValue(current.getTimeAccumulated(), current.getTitle()," "); } barChart = ChartFactory.createBarChart( "DISTRIBUTION OF MAN-HOURS", "Activities", "Man-hours", dataset,PlotOrientation.VERTICAL, true, true, false); } public BufferedImage getgraph() throws IOException{ int width = 1700; int height = 960; BufferedImage bufferedImage = barChart.createBufferedImage(width, height); return bufferedImage; } }
996
0.759036
0.752008
35
27.485714
23.27644
82
false
false
0
0
0
0
0
0
1.857143
false
false
12
fb10149163e662b2c1b6cbdf6cab7b87b8cbff10
12,455,405,223,474
87715e7266fa46e61d69f7804c6c6275b0f8b631
/src/edu/LeetCode/BinarySearch/No875_KokoEatingBananas.java
2b2e3f85d739884b86460fd39e409b6a96d92982
[ "MIT" ]
permissive
Wallace4ever/Algorithms
https://github.com/Wallace4ever/Algorithms
a4454292d022b5345770849777e514704aa85003
49f718d6b232207a1df9a00ce918fa610a46d84c
refs/heads/master
2021-03-23T18:28:56.928000
2020-10-14T14:34:17
2020-10-14T14:34:17
247,475,275
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package edu.LeetCode.BinarySearch; import org.junit.Test; public class No875_KokoEatingBananas { public int minEatingSpeed(int[] piles, int H) { int min = 1, max = Integer.MIN_VALUE; for (int pile : piles) max = Math.max(max, pile); while (min <= max) { int mid = min + ((max - min) >> 1); if (canFinish(piles, H, mid)) { max = mid - 1; } else { min = mid + 1; } } return min; } private boolean canFinish(int[] piles, int H, int speed) { int hour = 0; for (int pile : piles) hour += Math.ceil((double) pile / speed); return hour <= H; } @Test public void test() { System.out.println(minEatingSpeed(new int[]{30,11,23,4,20},6)); } }
UTF-8
Java
840
java
No875_KokoEatingBananas.java
Java
[]
null
[]
package edu.LeetCode.BinarySearch; import org.junit.Test; public class No875_KokoEatingBananas { public int minEatingSpeed(int[] piles, int H) { int min = 1, max = Integer.MIN_VALUE; for (int pile : piles) max = Math.max(max, pile); while (min <= max) { int mid = min + ((max - min) >> 1); if (canFinish(piles, H, mid)) { max = mid - 1; } else { min = mid + 1; } } return min; } private boolean canFinish(int[] piles, int H, int speed) { int hour = 0; for (int pile : piles) hour += Math.ceil((double) pile / speed); return hour <= H; } @Test public void test() { System.out.println(minEatingSpeed(new int[]{30,11,23,4,20},6)); } }
840
0.494048
0.472619
32
25.25
19.119688
71
false
false
0
0
0
0
0
0
0.75
false
false
12
2bd03d950e0f38fc3562321ab1a7f5d97be514fe
31,817,117,733,517
9e31d2d0ac31546e013efd2ac46efc7e348b3efd
/e2e-tests/src/test/java/com/wixpress/common/petri/e2e/BaseTest.java
874a7705803fdde37e9ed034408c802f6bd9d988
[ "BSD-3-Clause" ]
permissive
ryanlfoster/petri
https://github.com/ryanlfoster/petri
240fa1a47aeeeda91409624333ae7e840d428525
95a6336e3f40601609248a056c57157435d4b451
refs/heads/master
2021-01-18T08:10:47.770000
2015-04-06T12:16:38
2015-04-06T12:16:38
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.wixpress.common.petri.e2e; import com.wixpress.petri.Main; import com.wixpress.petri.PetriRPCClient; import com.wixpress.petri.experiments.domain.ExperimentSnapshot; import com.wixpress.petri.experiments.domain.TestGroup; import com.wixpress.petri.laboratory.http.LaboratoryFilter; import com.wixpress.petri.petri.FullPetriClient; import com.wixpress.petri.petri.PetriClient; import com.wixpress.petri.test.SampleAppRunner; import org.joda.time.DateTime; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import util.DBDriver; import java.net.MalformedURLException; import static com.wixpress.petri.PetriConfigFile.aPetriConfigFile; import static com.wixpress.petri.experiments.domain.ExperimentSnapshotBuilder.anExperimentSnapshot; import static com.wixpress.petri.experiments.domain.ScopeDefinition.aScopeDefinitionForAllUserTypes; import static com.wixpress.petri.petri.SpecDefinition.ExperimentSpecBuilder.aNewlyGeneratedExperimentSpec; import static java.util.Arrays.asList; /** * User: Dalias * Date: 2/8/15 * Time: 8:57 AM */ public abstract class BaseTest { protected static final int PETRI_PORT = 9010; protected static final int SAMPLE_APP_PORT = 9011; protected static final String SAMPLE_WEBAPP_PATH = PetriReportsTest.class.getResource("/").getPath() + "../../../sample-petri-app/src/main/webapp"; protected static SampleAppRunner sampleAppRunner ; protected static DBDriver dbDriver; protected FullPetriClient fullPetriClient; protected PetriClient petriClient; protected void addSpec(String key) { petriClient.addSpecs(asList( aNewlyGeneratedExperimentSpec(key). withTestGroups(asList("a", "b")). withScopes(aScopeDefinitionForAllUserTypes("the scope")). build())); } protected ExperimentSnapshot experimentWithFirstWinning(String key) { DateTime now = new DateTime(); return anExperimentSnapshot(). withStartDate(now.minusMinutes(1)). withEndDate(now.plusYears(1)). withKey(key). withGroups(asList(new TestGroup(0, 100, "a"), new TestGroup(1, 0, "b"))). withOnlyForLoggedInUsers(false). build(); } @BeforeClass public static void startServers() throws Exception { sampleAppRunner = new SampleAppRunner(SAMPLE_APP_PORT, SAMPLE_WEBAPP_PATH, 1); // TODO: Remove duplication with RPCPetriServerTest dbDriver = DBDriver.dbDriver("jdbc:h2:mem:test;IGNORECASE=TRUE"); dbDriver.createSchema(); dbDriver.createMetricsTableSchema(); aPetriConfigFile().delete(); aPetriConfigFile(). withUsername("auser"). withPassword("sa"). withUrl("jdbc:h2:mem:test"). withPort(PETRI_PORT). save(); Main.main(); sampleAppRunner.start(); } @Before public void start() throws MalformedURLException { petriClient = petriClient(); fullPetriClient = fullPetriClient(); } @AfterClass public static void stopServers() throws Exception { sampleAppRunner.stop(); aPetriConfigFile().delete(); dbDriver.closeConnection(); } protected FullPetriClient fullPetriClient() throws MalformedURLException { return PetriRPCClient.makeFullClientFor("http://localhost:" + PETRI_PORT + "/petri/full_api"); } protected PetriClient petriClient() throws MalformedURLException { return PetriRPCClient.makeFor("http://localhost:" + PETRI_PORT + "/petri/api"); } }
UTF-8
Java
3,773
java
BaseTest.java
Java
[ { "context": "port static java.util.Arrays.asList;\n\n/**\n * User: Dalias\n * Date: 2/8/15\n * Time: 8:57 AM\n */\npublic abstr", "end": 1049, "score": 0.9973986744880676, "start": 1043, "tag": "USERNAME", "value": "Dalias" }, { "context": "aPetriConfigFile().\n withUsername(\"auser\").\n withPassword(\"sa\").\n ", "end": 2801, "score": 0.9996490478515625, "start": 2796, "tag": "USERNAME", "value": "auser" }, { "context": "hUsername(\"auser\").\n withPassword(\"sa\").\n withUrl(\"jdbc:h2:mem:test\").\n ", "end": 2837, "score": 0.9995155334472656, "start": 2835, "tag": "PASSWORD", "value": "sa" } ]
null
[]
package com.wixpress.common.petri.e2e; import com.wixpress.petri.Main; import com.wixpress.petri.PetriRPCClient; import com.wixpress.petri.experiments.domain.ExperimentSnapshot; import com.wixpress.petri.experiments.domain.TestGroup; import com.wixpress.petri.laboratory.http.LaboratoryFilter; import com.wixpress.petri.petri.FullPetriClient; import com.wixpress.petri.petri.PetriClient; import com.wixpress.petri.test.SampleAppRunner; import org.joda.time.DateTime; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import util.DBDriver; import java.net.MalformedURLException; import static com.wixpress.petri.PetriConfigFile.aPetriConfigFile; import static com.wixpress.petri.experiments.domain.ExperimentSnapshotBuilder.anExperimentSnapshot; import static com.wixpress.petri.experiments.domain.ScopeDefinition.aScopeDefinitionForAllUserTypes; import static com.wixpress.petri.petri.SpecDefinition.ExperimentSpecBuilder.aNewlyGeneratedExperimentSpec; import static java.util.Arrays.asList; /** * User: Dalias * Date: 2/8/15 * Time: 8:57 AM */ public abstract class BaseTest { protected static final int PETRI_PORT = 9010; protected static final int SAMPLE_APP_PORT = 9011; protected static final String SAMPLE_WEBAPP_PATH = PetriReportsTest.class.getResource("/").getPath() + "../../../sample-petri-app/src/main/webapp"; protected static SampleAppRunner sampleAppRunner ; protected static DBDriver dbDriver; protected FullPetriClient fullPetriClient; protected PetriClient petriClient; protected void addSpec(String key) { petriClient.addSpecs(asList( aNewlyGeneratedExperimentSpec(key). withTestGroups(asList("a", "b")). withScopes(aScopeDefinitionForAllUserTypes("the scope")). build())); } protected ExperimentSnapshot experimentWithFirstWinning(String key) { DateTime now = new DateTime(); return anExperimentSnapshot(). withStartDate(now.minusMinutes(1)). withEndDate(now.plusYears(1)). withKey(key). withGroups(asList(new TestGroup(0, 100, "a"), new TestGroup(1, 0, "b"))). withOnlyForLoggedInUsers(false). build(); } @BeforeClass public static void startServers() throws Exception { sampleAppRunner = new SampleAppRunner(SAMPLE_APP_PORT, SAMPLE_WEBAPP_PATH, 1); // TODO: Remove duplication with RPCPetriServerTest dbDriver = DBDriver.dbDriver("jdbc:h2:mem:test;IGNORECASE=TRUE"); dbDriver.createSchema(); dbDriver.createMetricsTableSchema(); aPetriConfigFile().delete(); aPetriConfigFile(). withUsername("auser"). withPassword("sa"). withUrl("jdbc:h2:mem:test"). withPort(PETRI_PORT). save(); Main.main(); sampleAppRunner.start(); } @Before public void start() throws MalformedURLException { petriClient = petriClient(); fullPetriClient = fullPetriClient(); } @AfterClass public static void stopServers() throws Exception { sampleAppRunner.stop(); aPetriConfigFile().delete(); dbDriver.closeConnection(); } protected FullPetriClient fullPetriClient() throws MalformedURLException { return PetriRPCClient.makeFullClientFor("http://localhost:" + PETRI_PORT + "/petri/full_api"); } protected PetriClient petriClient() throws MalformedURLException { return PetriRPCClient.makeFor("http://localhost:" + PETRI_PORT + "/petri/api"); } }
3,773
0.67771
0.670554
109
33.614677
28.301104
151
false
false
0
0
0
0
0
0
0.495413
false
false
12
31c9d9ded4ec02b3ada7e9434035788ef0ace8fb
16,071,767,626,027
fce6b097856f1eea92e64df9eb94acd212c8ef60
/app/src/main/java/com/app/hotgo/activities/ActivityMapGetLocation.java
0e90883bbe3fec764b8515959ddc4b4f0bfcfb18
[]
no_license
MinhToanIT/hotcar
https://github.com/MinhToanIT/hotcar
552864fa5139507b3007bc760107f5056dc20f4b
3d5380c7efbaf04ba654cdcb29c3b4ba672b3bda
refs/heads/master
2020-09-01T13:22:05.689000
2019-11-01T10:45:14
2019-11-01T10:45:14
218,965,457
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.app.hotgo.activities; import android.app.Activity; import android.content.Intent; import android.location.Location; import android.os.Bundle; import android.os.Handler; import android.view.View; import android.view.View.OnClickListener; import android.widget.ImageView; import android.widget.TextView; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.GoogleMap.OnMapClickListener; import com.google.android.gms.maps.GoogleMap.OnMarkerClickListener; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.Marker; import com.google.android.gms.maps.model.MarkerOptions; import com.app.hotgo.BaseActivity; import com.app.hotgo.R; import com.app.hotgo.config.Constant; import com.app.hotgo.service.GPSTracker; public class ActivityMapGetLocation extends BaseActivity { private View view; private GoogleMap mMap; private Activity self; private ImageView btnBack; private GPSTracker gps; Handler handler; private double lat; private double lnt; private LatLng latLongMap; private TextView btnSaveLatlong; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_map); self = this; gps = new GPSTracker(self); handler = new Handler(); btnBack = findViewById(R.id.btnBack); btnSaveLatlong = findViewById(R.id.btnSaveLatlong); btnSaveLatlong.setVisibility(View.GONE); btnBack.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub finish(); } }); btnSaveLatlong.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(); intent.putExtra(Constant.LOCATION, latLongMap); setResult(Activity.RESULT_OK, intent); finish(); } }); Maps(); } private void Maps() { setUpMap(); } private void setUpMap() { // TODO Auto-generated method stub if (mMap == null) { SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager() .findFragmentById(R.id.fragMaps); fm.getMapAsync(new OnMapReadyCallback() { @Override public void onMapReady(GoogleMap googleMap) { mMap = googleMap; mMap.setMyLocationEnabled(true); mMap.setOnMarkerClickListener(new OnMarkerClickListener() { @Override public boolean onMarkerClick(Marker marker) { // TODO Auto-generated method stub marker.showInfoWindow(); return true; } }); mMap.setOnMapClickListener(new OnMapClickListener() { @Override public void onMapClick(LatLng latLng) { // TODO Auto-generated method stub MarkerOptions markerOptions = new MarkerOptions(); // Setting the position for the marker markerOptions.position(latLng); // Setting the title for the marker. // This will be displayed on taping the marker markerOptions.title(latLng.latitude + " : " + latLng.longitude); // Clears the previously touched position mMap.clear(); // Animating to the touched position mMap.animateCamera(CameraUpdateFactory.newLatLng(latLng)); // Placing a marker on the touched position mMap.addMarker(markerOptions); //plotMarkers(mCustomMarkerArray); latLongMap = latLng; if (btnSaveLatlong.getVisibility() == View.GONE) { btnSaveLatlong.setVisibility(View.VISIBLE); } } }); } }); // if (lat >= 0 && lnt >= 0) { // mMap.addMarker(new MarkerOptions() // .position(new LatLng(lat, lnt)) // .title("Perth")); // } } if (gps.canGetLocation()) { handler.post(runGoogleUpdateLocation); } else { gps.showSettingsAlert(); } } private void setLocationLatLong(double longitude, double latitude) { // set filter lat = latitude; lnt = longitude; LatLng latLng = new LatLng(latitude, longitude); mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng)); mMap.animateCamera(CameraUpdateFactory.zoomTo(12), 2000, null);// zoom : // 2-21 } private void refreshMyLocation() { try { Location location = null; if (mMap != null) { location = mMap.getMyLocation(); } if (location == null) { if (gps.canGetLocation()) { location = gps.getLocation(); } handler.postDelayed(runGoogleUpdateLocation, 2 * 1000); } else { setLocationLatLong(location.getLongitude(), location.getLatitude()); } } catch (IllegalStateException ex) { ex.printStackTrace(); } catch (Exception ex) { ex.printStackTrace(); } } Runnable runGoogleUpdateLocation = new Runnable() { @Override public void run() { // TODO Auto-generated method stub refreshMyLocation(); } }; }
UTF-8
Java
6,316
java
ActivityMapGetLocation.java
Java
[]
null
[]
package com.app.hotgo.activities; import android.app.Activity; import android.content.Intent; import android.location.Location; import android.os.Bundle; import android.os.Handler; import android.view.View; import android.view.View.OnClickListener; import android.widget.ImageView; import android.widget.TextView; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.GoogleMap.OnMapClickListener; import com.google.android.gms.maps.GoogleMap.OnMarkerClickListener; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.Marker; import com.google.android.gms.maps.model.MarkerOptions; import com.app.hotgo.BaseActivity; import com.app.hotgo.R; import com.app.hotgo.config.Constant; import com.app.hotgo.service.GPSTracker; public class ActivityMapGetLocation extends BaseActivity { private View view; private GoogleMap mMap; private Activity self; private ImageView btnBack; private GPSTracker gps; Handler handler; private double lat; private double lnt; private LatLng latLongMap; private TextView btnSaveLatlong; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_map); self = this; gps = new GPSTracker(self); handler = new Handler(); btnBack = findViewById(R.id.btnBack); btnSaveLatlong = findViewById(R.id.btnSaveLatlong); btnSaveLatlong.setVisibility(View.GONE); btnBack.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub finish(); } }); btnSaveLatlong.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(); intent.putExtra(Constant.LOCATION, latLongMap); setResult(Activity.RESULT_OK, intent); finish(); } }); Maps(); } private void Maps() { setUpMap(); } private void setUpMap() { // TODO Auto-generated method stub if (mMap == null) { SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager() .findFragmentById(R.id.fragMaps); fm.getMapAsync(new OnMapReadyCallback() { @Override public void onMapReady(GoogleMap googleMap) { mMap = googleMap; mMap.setMyLocationEnabled(true); mMap.setOnMarkerClickListener(new OnMarkerClickListener() { @Override public boolean onMarkerClick(Marker marker) { // TODO Auto-generated method stub marker.showInfoWindow(); return true; } }); mMap.setOnMapClickListener(new OnMapClickListener() { @Override public void onMapClick(LatLng latLng) { // TODO Auto-generated method stub MarkerOptions markerOptions = new MarkerOptions(); // Setting the position for the marker markerOptions.position(latLng); // Setting the title for the marker. // This will be displayed on taping the marker markerOptions.title(latLng.latitude + " : " + latLng.longitude); // Clears the previously touched position mMap.clear(); // Animating to the touched position mMap.animateCamera(CameraUpdateFactory.newLatLng(latLng)); // Placing a marker on the touched position mMap.addMarker(markerOptions); //plotMarkers(mCustomMarkerArray); latLongMap = latLng; if (btnSaveLatlong.getVisibility() == View.GONE) { btnSaveLatlong.setVisibility(View.VISIBLE); } } }); } }); // if (lat >= 0 && lnt >= 0) { // mMap.addMarker(new MarkerOptions() // .position(new LatLng(lat, lnt)) // .title("Perth")); // } } if (gps.canGetLocation()) { handler.post(runGoogleUpdateLocation); } else { gps.showSettingsAlert(); } } private void setLocationLatLong(double longitude, double latitude) { // set filter lat = latitude; lnt = longitude; LatLng latLng = new LatLng(latitude, longitude); mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng)); mMap.animateCamera(CameraUpdateFactory.zoomTo(12), 2000, null);// zoom : // 2-21 } private void refreshMyLocation() { try { Location location = null; if (mMap != null) { location = mMap.getMyLocation(); } if (location == null) { if (gps.canGetLocation()) { location = gps.getLocation(); } handler.postDelayed(runGoogleUpdateLocation, 2 * 1000); } else { setLocationLatLong(location.getLongitude(), location.getLatitude()); } } catch (IllegalStateException ex) { ex.printStackTrace(); } catch (Exception ex) { ex.printStackTrace(); } } Runnable runGoogleUpdateLocation = new Runnable() { @Override public void run() { // TODO Auto-generated method stub refreshMyLocation(); } }; }
6,316
0.551932
0.549398
183
33.51366
23.614355
92
false
false
0
0
0
0
0
0
0.508197
false
false
12
feab2e5b9b378185d18533227374e1bcce042f1a
25,400,436,593,220
3070121f2e47e39f9fc1b3eea73830655c12d9b8
/src/main/java/sid/pharmacy/Model/Mode_paiement.java
2378509fa3e3b4762e99c65c512d53070c962a78
[]
no_license
midozer/pharmacy
https://github.com/midozer/pharmacy
d0d5a1247a29f2fc5d561e6b9b0fa3382b0f2ac7
5015fce61a986a6e09ae4528f3acb3b9eaba059d
refs/heads/master
2023-06-27T17:55:16.798000
2021-07-12T19:45:07
2021-07-12T19:45:07
364,408,463
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * package sid.pharmacy.Model; * * import javax.persistence.Entity; import javax.persistence.GeneratedValue; * import javax.persistence.GenerationType; import javax.persistence.Id; import * javax.persistence.Table; * * * @Entity * * @Table(name="mode_paiement") public class Mode_paiement { * * @Id * * @GeneratedValue(strategy=GenerationType.AUTO) private int id_mode; private * String type_paiement; * * * @JsonIgnore * * @OneToMany(mappedBy = "mode_paiement",fetch = FetchType.LAZY,cascade = * CascadeType.ALL) private List<Commande_client> commande_clients; * * * public Mode_paiement() { super(); // TODO Auto-generated constructor stub } * public Mode_paiement(String type_paiement) { super(); this.type_paiement = * type_paiement; } public int getId_mode() { return id_mode; } public void * setId_mode(int id_mode) { this.id_mode = id_mode; } public String * getType_paiement() { return type_paiement; } public void * setType_paiement(String type_paiement) { this.type_paiement = type_paiement; * } } */
UTF-8
Java
1,085
java
Mode_paiement.java
Java
[]
null
[]
/* * package sid.pharmacy.Model; * * import javax.persistence.Entity; import javax.persistence.GeneratedValue; * import javax.persistence.GenerationType; import javax.persistence.Id; import * javax.persistence.Table; * * * @Entity * * @Table(name="mode_paiement") public class Mode_paiement { * * @Id * * @GeneratedValue(strategy=GenerationType.AUTO) private int id_mode; private * String type_paiement; * * * @JsonIgnore * * @OneToMany(mappedBy = "mode_paiement",fetch = FetchType.LAZY,cascade = * CascadeType.ALL) private List<Commande_client> commande_clients; * * * public Mode_paiement() { super(); // TODO Auto-generated constructor stub } * public Mode_paiement(String type_paiement) { super(); this.type_paiement = * type_paiement; } public int getId_mode() { return id_mode; } public void * setId_mode(int id_mode) { this.id_mode = id_mode; } public String * getType_paiement() { return type_paiement; } public void * setType_paiement(String type_paiement) { this.type_paiement = type_paiement; * } } */
1,085
0.681106
0.681106
32
31.96875
32.272747
79
false
false
0
0
0
0
0
0
0.5625
false
false
12
9aad101bbe1f28d41bfd9b6f08f7469167c34179
25,512,105,793,041
6b84f73da12624fb2feb48e664dfc6b2a5e1b6f3
/chapter1/1_1/UniqueCharJudgement.java
cb0ed3ba5a0590929e2da7ec488c3a786ee5ae11
[]
no_license
akihiro117/AlgorithmExcersise
https://github.com/akihiro117/AlgorithmExcersise
9c1748f9e64a284f8d04e91cfe7320b1ff53269a
3c88b22b84ca5b7e8c39cc9070a320020438bf01
refs/heads/master
2020-04-17T11:35:17.026000
2019-01-20T02:16:18
2019-01-20T02:16:18
166,546,419
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.util.HashMap; import java.util.Scanner; /** * ある文字列が全て固有であるか否かを判定するプログラム。 * 文字列は標準入力から受け取る。 * 入力できる文字列は1つ。 */ class UniqueCharJudgement { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String str = scanner.nextLine(); try { //入力した文字列内に重複した文字があるか否かで分岐。 if (judgeDuplicateCharExistance(str)) { //重複した文字がある場合。 System.out.println("重複した文字が存在します。"); } else { System.out.println("全て固有の文字です。"); } } finally { if (scanner != null) { scanner.close(); } } } /** * 文字列に重複した文字が存在するか否かを判定。 * @param str 判定対象の文字列。 * @return 重複した文字が存在する->true。 * 重複した文字が存在しない->false。 */ private static boolean judgeDuplicateCharExistance(String str) { //HashMapを使うことで計算量を削減する。 HashMap<String, Boolean> map = new HashMap<String, Boolean>(); //一文字ずつ重複した文字がないか順番に調べる。 for (int i = 0; i < str.length(); i++) { //重複があるか調べる文字。 String targetChar = String.valueOf(str.charAt(i)); if (map.get(targetChar) != null) { //同じ文字が既にmapに入っている場合。 return true; } else { map.put(targetChar, true); } } //最後まで重複する文字が無かったらfalseを返す。 return false; } }
UTF-8
Java
1,975
java
UniqueCharJudgement.java
Java
[]
null
[]
import java.util.HashMap; import java.util.Scanner; /** * ある文字列が全て固有であるか否かを判定するプログラム。 * 文字列は標準入力から受け取る。 * 入力できる文字列は1つ。 */ class UniqueCharJudgement { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String str = scanner.nextLine(); try { //入力した文字列内に重複した文字があるか否かで分岐。 if (judgeDuplicateCharExistance(str)) { //重複した文字がある場合。 System.out.println("重複した文字が存在します。"); } else { System.out.println("全て固有の文字です。"); } } finally { if (scanner != null) { scanner.close(); } } } /** * 文字列に重複した文字が存在するか否かを判定。 * @param str 判定対象の文字列。 * @return 重複した文字が存在する->true。 * 重複した文字が存在しない->false。 */ private static boolean judgeDuplicateCharExistance(String str) { //HashMapを使うことで計算量を削減する。 HashMap<String, Boolean> map = new HashMap<String, Boolean>(); //一文字ずつ重複した文字がないか順番に調べる。 for (int i = 0; i < str.length(); i++) { //重複があるか調べる文字。 String targetChar = String.valueOf(str.charAt(i)); if (map.get(targetChar) != null) { //同じ文字が既にmapに入っている場合。 return true; } else { map.put(targetChar, true); } } //最後まで重複する文字が無かったらfalseを返す。 return false; } }
1,975
0.517382
0.516019
61
23.065575
18.912107
70
false
false
0
0
0
0
0
0
0.278689
false
false
12
504a42b8366fd6b43bf1536c47d85ca3da524e22
26,645,977,121,983
32b72e1dc8b6ee1be2e80bb70a03a021c83db550
/ast_results/mozilla_MozStumbler/libraries/stumbler/src/main/java/org/mozilla/mozstumbler/service/stumblerthread/datahandling/base/SerializedJSONRows.java
e8dbb541626ca45d34d66022df6fc5659af8871e
[]
no_license
cmFodWx5YWRhdjEyMTA5/smell-and-machine-learning
https://github.com/cmFodWx5YWRhdjEyMTA5/smell-and-machine-learning
d90c41a17e88fcd99d543124eeb6e93f9133cb4a
0564143d92f8024ff5fa6b659c2baebf827582b1
refs/heads/master
2020-07-13T13:53:40.297000
2019-01-11T11:51:18
2019-01-11T11:51:18
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
// isComment package org.mozilla.mozstumbler.service.stumblerthread.datahandling.base; import java.util.HashMap; public class isClassOrIsInterface { public String isVariable = "isStringConstant"; public final byte[] isVariable; public enum StorageState { ON_DISK, IN_MEMORY } public StorageState isVariable; public isConstructor(byte[] isParameter, StorageState isParameter) { this.isFieldAccessExpr = isNameExpr; this.isFieldAccessExpr = isNameExpr; } public void isMethod(HashMap<String, Integer> isParameter) { } }
UTF-8
Java
587
java
SerializedJSONRows.java
Java
[]
null
[]
// isComment package org.mozilla.mozstumbler.service.stumblerthread.datahandling.base; import java.util.HashMap; public class isClassOrIsInterface { public String isVariable = "isStringConstant"; public final byte[] isVariable; public enum StorageState { ON_DISK, IN_MEMORY } public StorageState isVariable; public isConstructor(byte[] isParameter, StorageState isParameter) { this.isFieldAccessExpr = isNameExpr; this.isFieldAccessExpr = isNameExpr; } public void isMethod(HashMap<String, Integer> isParameter) { } }
587
0.717206
0.717206
26
21.576923
23.997072
73
false
false
0
0
0
0
0
0
0.384615
false
false
12
1f6003a781ded870e86aa85c733d9dbbf8a09d5f
26,706,106,675,558
465e7229628d1f628c3c0217bc12c24b38f0c448
/src/main/java/com/carlosceron/services/usuario/Usuario.java
2beaee657777851d3d7d44671cc4bf5c17b1966f
[]
no_license
carlosCeron/wsdl-spring-boot
https://github.com/carlosCeron/wsdl-spring-boot
9f6511eae27d50cf17ce1db14b138c773bcbb874
3819919954e73bdccd466363b1abd31aa735a46f
refs/heads/master
2020-03-24T02:12:57.540000
2018-07-26T00:29:43
2018-07-26T00:29:43
142,366,876
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.carlosceron.services.usuario; public class Usuario { private Long id; private String nombre; private String correo; public Usuario(Long id, String nombre, String correo) { super(); this.id = id; this.nombre = nombre; this.correo = correo; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public String getCorreo() { return correo; } public void setCorreo(String correo) { this.correo = correo; } }
UTF-8
Java
615
java
Usuario.java
Java
[]
null
[]
package com.carlosceron.services.usuario; public class Usuario { private Long id; private String nombre; private String correo; public Usuario(Long id, String nombre, String correo) { super(); this.id = id; this.nombre = nombre; this.correo = correo; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public String getCorreo() { return correo; } public void setCorreo(String correo) { this.correo = correo; } }
615
0.658537
0.658537
53
10.603773
13.721405
56
false
false
0
0
0
0
0
0
1.075472
false
false
12
eb948bdc112234e825f8e22d4ee80683dfea465e
5,102,421,174,722
22cc79ca513b0056ac54b8c9a73eb64585f6a298
/ClientTest/src/main/java/client/test/ClientSessionHandler.java
9a05ac6d029a4a8d19dd72acb25bc9ad0bf7e0d8
[]
no_license
Amooti/SensorStream
https://github.com/Amooti/SensorStream
bf50675e087329478c4847d3482a2debdedbad22
873d8cfbf84fb23ea5fb5b17661cc0fa238c46fd
refs/heads/master
2016-08-04T01:07:32.181000
2015-01-25T18:30:10
2015-01-25T18:30:10
10,215,431
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package client.test; import org.apache.mina.core.service.IoHandlerAdapter; import org.apache.mina.core.session.IdleStatus; import org.apache.mina.core.session.IoSession; import java.util.concurrent.BlockingQueue; public class ClientSessionHandler extends IoHandlerAdapter { private final BlockingQueue<String> queue; public ClientSessionHandler(BlockingQueue<String> queue) { this.queue = queue; } @Override public void messageReceived(IoSession session, Object message) throws Exception { queue.put((String)message); } @Override public void exceptionCaught(IoSession session, Throwable cause) { System.err.println("Something went horribly wrong!"); cause.printStackTrace(); session.close(false); } @Override public void sessionIdle(IoSession session, IdleStatus status) throws Exception { System.out.println("Client session idle, closing"); session.close(false); } }
UTF-8
Java
980
java
ClientSessionHandler.java
Java
[]
null
[]
package client.test; import org.apache.mina.core.service.IoHandlerAdapter; import org.apache.mina.core.session.IdleStatus; import org.apache.mina.core.session.IoSession; import java.util.concurrent.BlockingQueue; public class ClientSessionHandler extends IoHandlerAdapter { private final BlockingQueue<String> queue; public ClientSessionHandler(BlockingQueue<String> queue) { this.queue = queue; } @Override public void messageReceived(IoSession session, Object message) throws Exception { queue.put((String)message); } @Override public void exceptionCaught(IoSession session, Throwable cause) { System.err.println("Something went horribly wrong!"); cause.printStackTrace(); session.close(false); } @Override public void sessionIdle(IoSession session, IdleStatus status) throws Exception { System.out.println("Client session idle, closing"); session.close(false); } }
980
0.720408
0.720408
34
27.82353
26.595522
85
false
false
0
0
0
0
0
0
0.5
false
false
12
270be11ece33d99e6800fe8af65761e4005c7386
20,478,404,076,548
0192b9a0df01231682dce94ef950cd1150ea070f
/src/main/java/com/ddd/content/repository/ContentRepository.java
7705e95ecc4b5621da4aca116fb9e4ebb117d0f1
[]
no_license
along603/CMS
https://github.com/along603/CMS
85b01685116cd655ff01811f98858bddab793b99
1005839465a2f14522d40144c72b88276f9cf0e1
refs/heads/master
2020-03-24T06:16:44.082000
2018-07-27T03:42:12
2018-07-27T03:42:12
142,522,700
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.ddd.content.repository; import org.springframework.data.jpa.repository.JpaRepository; import com.ddd.content.domain.bean.ContentAgg; public interface ContentRepository extends JpaRepository<ContentAgg, Long> { ContentAgg findByAssetID(String assetId); }
UTF-8
Java
275
java
ContentRepository.java
Java
[]
null
[]
package com.ddd.content.repository; import org.springframework.data.jpa.repository.JpaRepository; import com.ddd.content.domain.bean.ContentAgg; public interface ContentRepository extends JpaRepository<ContentAgg, Long> { ContentAgg findByAssetID(String assetId); }
275
0.818182
0.818182
11
24
27.843719
76
false
false
0
0
0
0
0
0
0.454545
false
false
12
2abe823b0946c979ec95aa8763c206539175ffa0
6,416,681,144,505
fd648ad8281b48bd619a94b105aced5b4d84b476
/server-spring/src/main/java/boyi/battleship/core/chat/ChatMessage.java
b4565765f5691efb9897c130d979a4d70cfefa59
[]
no_license
laowai121/battleship
https://github.com/laowai121/battleship
271a027ee212ca2cc42f56810b94efa895c25a79
5bafb9e4759fd11e34af38896c15e69bcdfaa028
refs/heads/master
2021-05-09T08:42:20.204000
2018-05-24T22:38:57
2018-05-24T22:38:57
119,401,897
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package boyi.battleship.core.chat; import boyi.battleship.core.battleshipobject.BattleshipObject; import boyi.battleship.core.player.Player; import org.jetbrains.annotations.NotNull; public class ChatMessage extends BattleshipObject { public static final int MAX_LENGTH = 10000; @NotNull private Player sender; private long messageTimestamp; @NotNull private String message; public ChatMessage(@NotNull Player sender, @NotNull String message) { this.sender = sender; this.messageTimestamp = System.currentTimeMillis(); this.message = message; } @NotNull public Player getSender() { return sender; } public long getMessageTimestamp() { return messageTimestamp; } @NotNull public String getMessage() { return message; } }
UTF-8
Java
841
java
ChatMessage.java
Java
[]
null
[]
package boyi.battleship.core.chat; import boyi.battleship.core.battleshipobject.BattleshipObject; import boyi.battleship.core.player.Player; import org.jetbrains.annotations.NotNull; public class ChatMessage extends BattleshipObject { public static final int MAX_LENGTH = 10000; @NotNull private Player sender; private long messageTimestamp; @NotNull private String message; public ChatMessage(@NotNull Player sender, @NotNull String message) { this.sender = sender; this.messageTimestamp = System.currentTimeMillis(); this.message = message; } @NotNull public Player getSender() { return sender; } public long getMessageTimestamp() { return messageTimestamp; } @NotNull public String getMessage() { return message; } }
841
0.692033
0.686088
37
21.729731
20.253326
73
false
false
0
0
0
0
0
0
0.405405
false
false
12
970e65d774b4755738cfcf58b4df686fca3c95b9
27,805,618,302,999
7212ccc1d3cf8212d9f30a87c0887cb7b91cf693
/App/src/test/java/pages/Favorites.java
08dab27abba50d1f9ff0d3a5977e8b59309d6489
[]
no_license
msdelen/Keytorc
https://github.com/msdelen/Keytorc
5649de2e141f4b5ea8a8cca296153161c6ffe5d1
a38d01928cde34454b8b0b3ea19dd1e44e6f99a2
refs/heads/master
2020-03-19T05:13:32.482000
2018-06-03T14:44:04
2018-06-03T14:44:04
135,911,200
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package pages; import org.junit.Test; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.ui.WebDriverWait; import java.util.List; public class Favorites extends firstTest { public Favorites(WebDriver driver, WebDriverWait wait) { super(driver, wait); } private static final String deleteButtonClass = "deleteProFromFavorites"; public String getActualProductName(String selectedProductId) { String selectedProductId1 = selectedProductId; driver.get(baseURL + "/hesabim/favorilerim"); String productSelector = "#p-" + selectedProductId; return driver.findElement(By.cssSelector(productSelector + " > div > a > h3")).getText(); } @Test public void deleteFromFavorites() { driver.findElement(By.className(deleteButtonClass)).click(); } public boolean isFavoriteDeleted(String selectedProductName) { List<String> favoriteBasket = new ArrayList<>(); List<WebElement> favoriteProducts = driver.findElements(By.xpath("//*[@class='productTitle']/p/a")); for (WebElement productTitle : favoriteProducts) { String productName = productTitle.getText(); favoriteBasket.add(productName); } return favoriteBasket.contains(selectedProductName); } }
UTF-8
Java
1,379
java
Favorites.java
Java
[]
null
[]
package pages; import org.junit.Test; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.ui.WebDriverWait; import java.util.List; public class Favorites extends firstTest { public Favorites(WebDriver driver, WebDriverWait wait) { super(driver, wait); } private static final String deleteButtonClass = "deleteProFromFavorites"; public String getActualProductName(String selectedProductId) { String selectedProductId1 = selectedProductId; driver.get(baseURL + "/hesabim/favorilerim"); String productSelector = "#p-" + selectedProductId; return driver.findElement(By.cssSelector(productSelector + " > div > a > h3")).getText(); } @Test public void deleteFromFavorites() { driver.findElement(By.className(deleteButtonClass)).click(); } public boolean isFavoriteDeleted(String selectedProductName) { List<String> favoriteBasket = new ArrayList<>(); List<WebElement> favoriteProducts = driver.findElements(By.xpath("//*[@class='productTitle']/p/a")); for (WebElement productTitle : favoriteProducts) { String productName = productTitle.getText(); favoriteBasket.add(productName); } return favoriteBasket.contains(selectedProductName); } }
1,379
0.708484
0.707034
39
34.384617
29.553616
108
false
false
0
0
0
0
0
0
0.538462
false
false
12
001b1c3946ee05e417c8d4a4af16dfff5ef97987
824,633,753,813
99d78e7cb0d605fa1cae06435677d4578c619bef
/apl-report-service/src/main/java/com/apl/jmreport/dao/ReportDao.java
12a7c469e919e1f8fa3219253a603b5bb668bf5c
[ "Apache-2.0" ]
permissive
hujiren/report-java
https://github.com/hujiren/report-java
00e20a57c98cc57f575247993797eaf845cc79dd
54fa02e8788419393963629ff45a9a58540ee830
refs/heads/master
2023-03-09T16:00:52.232000
2021-02-18T03:58:18
2021-02-18T03:58:18
339,930,132
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.apl.jmreport.dao; import com.apl.db.adb.AdbHelper; import com.apl.db.adb.AdbPageVo; import com.apl.jmreport.mapper.ReportMapper; import com.apl.lib.pojo.dto.PageDto; import com.apl.lmreport.po.JimuReportPo; import com.apl.lmreport.vo.JimuReportVo; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; /** * @author hjr start * @Classname JimuReportDao * @Date 2021/1/25 11:51 */ @Repository public class ReportDao extends ServiceImpl<ReportMapper, JimuReportPo> { @Autowired AdbHelper adbHelper; //获取列表 public AdbPageVo<JimuReportVo> getList(PageDto pageDto, Integer isTemplate) { StringBuffer sql = new StringBuffer(); sql.append("select id, code, name, type, create_by, create_time, report_brand from jimu_report.jimu_report where del_flag = 0"); if(isTemplate.equals(1)) sql.append(" and template = 0"); else sql.append(" and template = 1"); adbHelper.setDbType(1); AdbPageVo<JimuReportVo> jimuReportVoAdbPageVo = adbHelper.queryPage(sql.toString(), new Object(), JimuReportVo.class, pageDto.getPageIndex(), pageDto.getPageSize()); return jimuReportVoAdbPageVo; } //修改状态 public Integer updateReportStatusById(Long id) { String sql = "update jimu_report.jimu_report set del_flag = 1 where id = " + id; Integer resultInteger = adbHelper.update(sql); return resultInteger; } //更新 public Integer upd(JimuReportPo jimuReportPo) throws Exception { Integer resultInteger = adbHelper.updateById(jimuReportPo, "jimu_report"); return resultInteger; } //新增 public Integer add(JimuReportPo jimuReportPo) throws Exception { Integer resultInteger = adbHelper.insert(jimuReportPo, "jimu_report"); return resultInteger; } //获取详细 public JimuReportVo get(Long id) { String sql = "select id, code, name, type, json_str, create_by, create_time, update_by, report_brand, " + "update_time, del_flag, template from jimu_report.jimu_report where id = " + id + " and del_flag = 0"; JimuReportVo jimuReportVo = adbHelper.queryObj(sql, null, JimuReportVo.class); return jimuReportVo; } }
UTF-8
Java
2,394
java
ReportDao.java
Java
[ { "context": "gframework.stereotype.Repository;\n\n\n/**\n * @author hjr start\n * @Classname JimuReportDao\n * @Date 2021/1", "end": 462, "score": 0.9996168613433838, "start": 459, "tag": "USERNAME", "value": "hjr" } ]
null
[]
package com.apl.jmreport.dao; import com.apl.db.adb.AdbHelper; import com.apl.db.adb.AdbPageVo; import com.apl.jmreport.mapper.ReportMapper; import com.apl.lib.pojo.dto.PageDto; import com.apl.lmreport.po.JimuReportPo; import com.apl.lmreport.vo.JimuReportVo; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; /** * @author hjr start * @Classname JimuReportDao * @Date 2021/1/25 11:51 */ @Repository public class ReportDao extends ServiceImpl<ReportMapper, JimuReportPo> { @Autowired AdbHelper adbHelper; //获取列表 public AdbPageVo<JimuReportVo> getList(PageDto pageDto, Integer isTemplate) { StringBuffer sql = new StringBuffer(); sql.append("select id, code, name, type, create_by, create_time, report_brand from jimu_report.jimu_report where del_flag = 0"); if(isTemplate.equals(1)) sql.append(" and template = 0"); else sql.append(" and template = 1"); adbHelper.setDbType(1); AdbPageVo<JimuReportVo> jimuReportVoAdbPageVo = adbHelper.queryPage(sql.toString(), new Object(), JimuReportVo.class, pageDto.getPageIndex(), pageDto.getPageSize()); return jimuReportVoAdbPageVo; } //修改状态 public Integer updateReportStatusById(Long id) { String sql = "update jimu_report.jimu_report set del_flag = 1 where id = " + id; Integer resultInteger = adbHelper.update(sql); return resultInteger; } //更新 public Integer upd(JimuReportPo jimuReportPo) throws Exception { Integer resultInteger = adbHelper.updateById(jimuReportPo, "jimu_report"); return resultInteger; } //新增 public Integer add(JimuReportPo jimuReportPo) throws Exception { Integer resultInteger = adbHelper.insert(jimuReportPo, "jimu_report"); return resultInteger; } //获取详细 public JimuReportVo get(Long id) { String sql = "select id, code, name, type, json_str, create_by, create_time, update_by, report_brand, " + "update_time, del_flag, template from jimu_report.jimu_report where id = " + id + " and del_flag = 0"; JimuReportVo jimuReportVo = adbHelper.queryObj(sql, null, JimuReportVo.class); return jimuReportVo; } }
2,394
0.69475
0.68713
65
35.338463
36.367474
173
false
false
0
0
0
0
0
0
0.846154
false
false
12
3282dab9b06d348a2c7f56b8857423853827fa94
8,040,178,841,761
01767b3590765781b1ef6205fec4d80f4a4d24f9
/src/main/java/student_lilija_g/homework/lesson_5/level_2/Task_12.java
e76e93e548ab118ceff49de00141a90e194ef646
[]
no_license
ApTyPuk/java_1_monday_2020_online
https://github.com/ApTyPuk/java_1_monday_2020_online
127284d6f58a28862dd2682b62fb5c0237d3e8c0
c16bb3786d00a16ff7a70276b967caebbbc0d476
refs/heads/master
2023-02-04T06:22:19.475000
2020-12-22T00:13:46
2020-12-22T00:13:46
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package student_lilija_g.homework.lesson_5.level_2; import teacher.annotations.CodeReview; @CodeReview(approved = true) class Task_12 { public static void main(String[] args) { int[] myNumbers = new int[3]; for (int i = 0; i < myNumbers.length; i++) { myNumbers[i] = (int) (Math.random() * 100); } System.out.println("Array of integers with dimension 3 is {" + myNumbers[0] + ", " + myNumbers[1] + ", " + myNumbers[2] + "} "); } }
UTF-8
Java
537
java
Task_12.java
Java
[]
null
[]
package student_lilija_g.homework.lesson_5.level_2; import teacher.annotations.CodeReview; @CodeReview(approved = true) class Task_12 { public static void main(String[] args) { int[] myNumbers = new int[3]; for (int i = 0; i < myNumbers.length; i++) { myNumbers[i] = (int) (Math.random() * 100); } System.out.println("Array of integers with dimension 3 is {" + myNumbers[0] + ", " + myNumbers[1] + ", " + myNumbers[2] + "} "); } }
537
0.532588
0.50838
21
24.571428
22.385309
70
false
false
0
0
0
0
0
0
0.428571
false
false
12
2ab0ea85be7e111cb3d841b1d40c9664c49626fb
23,888,608,148,477
afb21d9a8003a5e7b6b85cb70af5b767c99eaab0
/src/main/java/net/nomagic/edna/config/liquibase/package-info.java
e87ed42f764b15628f30344aa5a7fe46e4bb6412
[]
no_license
BulkSecurityGeneratorProject/edna-monolith
https://github.com/BulkSecurityGeneratorProject/edna-monolith
300bc9f8bdc99867eecd416ed2adb88a24acd9cf
274b889f5254de417ccf4278960c8ed7891509bf
refs/heads/master
2022-12-08T22:30:34.444000
2016-07-04T18:50:08
2016-07-04T18:50:08
296,590,352
0
0
null
true
2020-09-18T10:34:09
2020-09-18T10:34:09
2016-07-04T18:53:32
2016-07-04T18:53:30
4,501
0
0
0
null
false
false
/** * Liquibase specific code. */ package net.nomagic.edna.config.liquibase;
UTF-8
Java
79
java
package-info.java
Java
[]
null
[]
/** * Liquibase specific code. */ package net.nomagic.edna.config.liquibase;
79
0.721519
0.721519
4
18.75
16.618891
42
false
false
0
0
0
0
0
0
0.25
false
false
12
33694061588d3ba1ae0fb439c8d49b5d3bab99ad
26,121,991,095,451
ecfd2c9c9cd8fc65710cc0a710d4ef9c087891ce
/studentTeachingInformationManagementSystem_leixindi/src/com/leixindi/service/ResultCourseService.java
1797e3839542bb4c607715c33a681c37c124c5dd
[]
no_license
leixindi/mygitremote
https://github.com/leixindi/mygitremote
a88f7955e8cfd6a45cee3e245148955def010a32
3fd307bd901d60e77bdf63a95a8b29b45869b53b
refs/heads/master
2020-06-27T07:20:56.474000
2019-08-01T06:14:50
2019-08-01T06:14:50
199,882,713
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.leixindi.service; import com.leixindi.bean.ResultCourseInfo; import java.util.List; /** * 学生、课程、教师、成绩多表查询的服务类的接口-- 多表查询的服务模块 */ public interface ResultCourseService { /** * 教师查询学生成绩 * * @param tea_id 教师编号 * @return 学生成绩的列表集合 */ public List<ResultCourseInfo> queryStuResultInfoList(int tea_id); /** * 学生查询个人成绩 * * @param stu_id 教师编号 * @return 个人成绩的列表集合 */ public List<ResultCourseInfo> queryStudentResultInfoList(int stu_id); }
GB18030
Java
657
java
ResultCourseService.java
Java
[]
null
[]
package com.leixindi.service; import com.leixindi.bean.ResultCourseInfo; import java.util.List; /** * 学生、课程、教师、成绩多表查询的服务类的接口-- 多表查询的服务模块 */ public interface ResultCourseService { /** * 教师查询学生成绩 * * @param tea_id 教师编号 * @return 学生成绩的列表集合 */ public List<ResultCourseInfo> queryStuResultInfoList(int tea_id); /** * 学生查询个人成绩 * * @param stu_id 教师编号 * @return 个人成绩的列表集合 */ public List<ResultCourseInfo> queryStudentResultInfoList(int stu_id); }
657
0.649706
0.649706
26
18.653847
19.693697
73
false
false
0
0
0
0
0
0
0.192308
false
false
12
9bdef6668962379c2318188a58f72d3fa649bb9b
12,360,915,947,300
41e8917f2a3353ce452b57975050945b779fd4f5
/java/978LongestTurbulentSubarray.java
b5418c36632d5bf9530495bf91afaa105d5b848e
[]
no_license
vigorousyd168/leetcode
https://github.com/vigorousyd168/leetcode
2f5fd8e8caafb6ad5fa6292ad91c6e2fecf73c2c
8749f8fc4a858f782ab8f2d0c812c2f630352884
refs/heads/master
2020-04-09T10:32:48.666000
2019-06-07T05:41:45
2019-06-07T05:41:45
68,264,843
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
class Solution { public int maxTurbulenceSize(int[] A) { int n = A.length; // # of turbulent array ending at i and last sign is + int lastUp = 1; // # of turbulent array ending at i and last sign is - int lastDown = 1; int ans = 1, temp; for (int i = 1; i < n; i++) { temp = lastUp; lastUp = A[i] > A[i-1] ? lastDown + 1 : 1; lastDown = A[i] < A[i-1] ? temp + 1 : 1; if (lastUp > ans) ans = lastUp; if (lastDown > ans) ans = lastDown; } return ans; } }
UTF-8
Java
592
java
978LongestTurbulentSubarray.java
Java
[]
null
[]
class Solution { public int maxTurbulenceSize(int[] A) { int n = A.length; // # of turbulent array ending at i and last sign is + int lastUp = 1; // # of turbulent array ending at i and last sign is - int lastDown = 1; int ans = 1, temp; for (int i = 1; i < n; i++) { temp = lastUp; lastUp = A[i] > A[i-1] ? lastDown + 1 : 1; lastDown = A[i] < A[i-1] ? temp + 1 : 1; if (lastUp > ans) ans = lastUp; if (lastDown > ans) ans = lastDown; } return ans; } }
592
0.467905
0.451014
18
31.944445
18.36504
62
false
false
0
0
0
0
0
0
0.722222
false
false
12