blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 4
410
| content_id
stringlengths 40
40
| detected_licenses
listlengths 0
51
| license_type
stringclasses 2
values | repo_name
stringlengths 5
132
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringlengths 4
80
| visit_date
timestamp[us] | revision_date
timestamp[us] | committer_date
timestamp[us] | github_id
int64 5.85k
689M
⌀ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 22
values | gha_event_created_at
timestamp[us] | gha_created_at
timestamp[us] | gha_language
stringclasses 131
values | src_encoding
stringclasses 34
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 2
classes | length_bytes
int64 3
9.45M
| extension
stringclasses 32
values | content
stringlengths 3
9.45M
| authors
listlengths 1
1
| author_id
stringlengths 0
313
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
39ef3f60836d48c8714dda40b653ce6d4a11b62a
|
4d1c891c46bad9627653de80717df36753381730
|
/java/springmvc_bootstrap/PatronEmail/src/main/java/hu/dfighter1985/patronemail/model/SearchPatron.java
|
0b502fc28ae572d78d5e366f0d611601b9e51c50
|
[
"MIT"
] |
permissive
|
dfighter1985/cookbook
|
14dc18b809bd253cef630cf288fde06648206c07
|
c73a174f3f4060434a1d15eb6e7a971c3c0a5aea
|
refs/heads/master
| 2022-12-21T15:21:07.860648 | 2020-06-07T23:19:30 | 2020-06-07T23:19:30 | 207,134,554 | 0 | 0 |
MIT
| 2022-12-16T01:50:40 | 2019-09-08T15:41:50 |
Java
|
UTF-8
|
Java
| false | false | 1,737 |
java
|
/*
MIT License
Copyright (c) 2019 dfighter1985
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package hu.dfighter1985.patronemail.model;
public class SearchPatron
{
private String id;
private String firstName;
private String lastName;
public String getId()
{
return id;
}
public void setId( final String id )
{
this.id = id;
}
public String getFirstName()
{
return firstName;
}
public void setFirstName( final String firstName )
{
this.firstName = firstName;
}
public String getLastName()
{
return lastName;
}
public void setLastName( final String lastName )
{
this.lastName = lastName;
}
}
|
[
"[email protected]"
] | |
14adb87eb2925205ce4e6dd1a922c4cfd731b2cc
|
0bd679d147e3b3fa86fdc50043bb76290d008f31
|
/CloudProject.java
|
506b26b6b3d7c3bcd66c447c94107610baf942dd
|
[] |
no_license
|
owen97sloughy/cs1660_project
|
37a19f5c509b3a3076b68c4528cd218855e39a3a
|
3c539924ad467fbbb1a10a31482e8305b6e2811b
|
refs/heads/main
| 2023-04-15T10:11:56.377849 | 2021-04-15T14:27:55 | 2021-04-15T14:27:55 | 358,108,580 | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 14,142 |
java
|
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.io.File;
import javax.swing.filechooser.*;
import com.google.api.gax.core.FixedCredentialsProvider;
import com.google.api.gax.longrunning.OperationFuture;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.cloud.dataproc.v1.HadoopJob;
import com.google.cloud.dataproc.v1.Job;
import com.google.cloud.dataproc.v1.JobControllerClient;
import com.google.cloud.dataproc.v1.JobControllerSettings;
import com.google.cloud.dataproc.v1.JobMetadata;
import com.google.cloud.dataproc.v1.JobPlacement;
import com.google.cloud.storage.Blob;
import com.google.cloud.storage.BlobId;
import com.google.cloud.storage.BlobInfo;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;
import com.google.common.collect.Lists;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.concurrent.ExecutionException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class CloudProject implements ActionListener{
//hadoop job variables
//project id
public static final String projectId = "cloud-computing-1660";
//project region
public static final String region = "us-central1";
//cluster name
public static final String clusterName = "owens-cluster";
//hadoop command, the input directory must be 'your bucket name/input' because this program uploads files to your bucket in a input/ folder
//output directory must be bucket output directory
public static final String hadoopFsQuery = "InvertedIndexes gs://1660-hw-bucket/input gs://1660-hw-bucket/output";
//jar file located on cluster (I believe it can be located on the bucket as well, but I only tested on the cluster)
public static final String jarFile = "gs://1660-hw-bucket/inverted.jar";
//bucket name
public static final String bucketName = "1660-hw-bucket";
//path to your google credentials!
public static final String jsonPath = "/src/cloudKeys.json";
//GUI variables!
public static boolean first_construct = false;
public static ArrayList<String> selected_files;
public static JLabel files;
public static JFrame frame;
public static JTextField bar;
public static void main(String[] args){
//initialize GUI
initializeGUI();
}
//action listener
public void actionPerformed(ActionEvent e){
if(e.getActionCommand().equals("1")){
fileChooser();
} else if(e.getActionCommand().equals("2") || e.getActionCommand().equals("7")){
try {
constructII();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
} else if(e.getActionCommand().equals("3")){
searchScreen();
} else if(e.getActionCommand().equals("4")){
topnScreen();
} else if(e.getActionCommand().equals("5")){
topnFinal();
} else if(e.getActionCommand().equals("6")){
searchFinal();
}
}
//search final
private static void searchFinal(){
Container pane = frame.getContentPane();
//get topn-value
String text = bar.getText();
//search for term
searchForTerm(text);
//clear screen
pane.removeAll();
//new screen
JButton go_back = new JButton("Go Back to Main Screen: ");
go_back.setAlignmentX(Component.CENTER_ALIGNMENT);
//add action listeners
go_back.addActionListener(new CloudProject());
go_back.setActionCommand("7");
pane.add(Box.createVerticalGlue());
pane.add(go_back);
pane.add(Box.createVerticalGlue());
pane.revalidate();
pane.repaint();
}
//search screen
private static void searchScreen(){
Container pane = frame.getContentPane();
pane.removeAll();
//new screen
JLabel enter = new JLabel("Enter Your Search Term");
enter.setAlignmentX(Component.CENTER_ALIGNMENT);
JPanel contains_bar = new JPanel();
contains_bar.setAlignmentX(Component.CENTER_ALIGNMENT);
bar = new JTextField(15);
bar.setAlignmentX(Component.CENTER_ALIGNMENT);
JButton search_topn = new JButton("Search");
search_topn.setAlignmentX(Component.CENTER_ALIGNMENT);
//add action listeners
search_topn.addActionListener(new CloudProject());
search_topn.setActionCommand("6");
contains_bar.add(bar);
pane.add(Box.createVerticalGlue());
pane.add(enter);
pane.add(Box.createVerticalGlue());
pane.add(contains_bar);
pane.add(Box.createVerticalGlue());
pane.add(search_topn);
pane.add(Box.createVerticalGlue());
pane.revalidate();
pane.repaint();
}
//topn results
private static void topnFinal(){
Container pane = frame.getContentPane();
//get topn-value
String text = bar.getText();
//topn results
getTopN(text);
//clear screen
pane.removeAll();
//new screen
JButton go_back = new JButton("Go Back to Main Screen");
go_back.setAlignmentX(Component.CENTER_ALIGNMENT);
//add action listeners
go_back.addActionListener(new CloudProject());
go_back.setActionCommand("7");
pane.add(Box.createVerticalGlue());
pane.add(go_back);
pane.add(Box.createVerticalGlue());
pane.revalidate();
pane.repaint();
}
//topn screen
private static void topnScreen(){
Container pane = frame.getContentPane();
pane.removeAll();
//new screen
JLabel enter = new JLabel("Enter Your N Value");
enter.setAlignmentX(Component.CENTER_ALIGNMENT);
JPanel contains_bar = new JPanel();
contains_bar.setAlignmentX(Component.CENTER_ALIGNMENT);
bar = new JTextField(15);
bar.setAlignmentX(Component.CENTER_ALIGNMENT);
JButton search_topn = new JButton("Search");
search_topn.setAlignmentX(Component.CENTER_ALIGNMENT);
//add action listeners
search_topn.addActionListener(new CloudProject());
search_topn.setActionCommand("5");
contains_bar.add(bar);
pane.add(Box.createVerticalGlue());
pane.add(enter);
pane.add(Box.createVerticalGlue());
pane.add(contains_bar);
pane.add(Box.createVerticalGlue());
pane.add(search_topn);
pane.add(Box.createVerticalGlue());
pane.revalidate();
pane.repaint();
}
//construct inverted indices
private static void constructII() throws IOException, InterruptedException{
Container pane = frame.getContentPane();
pane.removeAll();
//construct indices
if(!first_construct) {
for(int i=0; i<selected_files.size(); i++) {
uploadFiles(selected_files.get(i));
}
submitHadoopFsJob(projectId, region, clusterName, hadoopFsQuery);
first_construct = true;
}
//new screen
JLabel success = new JLabel("Engine was loaded and Inverted indices " +
"were constructed successfully!");
success.setAlignmentX(Component.CENTER_ALIGNMENT);
JLabel selection = new JLabel("Please Select Action");
selection.setAlignmentX(Component.CENTER_ALIGNMENT);
JButton search_term = new JButton("Search for Term");
search_term.setAlignmentX(Component.CENTER_ALIGNMENT);
JButton topn = new JButton("Top-N");
topn.setAlignmentX(Component.CENTER_ALIGNMENT);
//add action listeners
search_term.addActionListener(new CloudProject());
search_term.setActionCommand("3");
topn.addActionListener(new CloudProject());
topn.setActionCommand("4");
//add all to frame
pane.add(Box.createVerticalGlue());
pane.add(success);
pane.add(Box.createVerticalGlue());
pane.add(selection);
pane.add(Box.createVerticalGlue());
pane.add(search_term);
pane.add(topn);
pane.add(Box.createVerticalGlue());
pane.revalidate();
pane.repaint();
}
//choose files gui
private static void fileChooser(){
//store selected_files
selected_files = new ArrayList<String>();
StringBuilder sb = new StringBuilder();
//working directory for jfilechooser
File workingDir = new File(System.getProperty("user.dir"));
//set up jfilechooser
JFileChooser chooser = new JFileChooser(FileSystemView.getFileSystemView());
chooser.setMultiSelectionEnabled(true);
chooser.setCurrentDirectory(workingDir);
//open jfilechooser
int selected = chooser.showOpenDialog(null);
//selected file
if (selected == JFileChooser.APPROVE_OPTION){
File[] f = chooser.getSelectedFiles();
for(int i = 0; i < f.length; i++){
selected_files.add(f[i].getAbsolutePath());
sb.append(f[i].getAbsolutePath() + "<br>");
}
files.setText("<html>" + sb.toString() + "</html>");
}
}
//set up gui
private static void initializeGUI(){
//create JFrame
frame = new JFrame("Owen's Search Engine");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BoxLayout(frame.getContentPane(), BoxLayout.Y_AXIS));
//create home page content
JLabel load_engine = new JLabel("Load Engine");
load_engine.setAlignmentX(Component.CENTER_ALIGNMENT);
JButton choose_files = new JButton("Choose Files");
choose_files.setAlignmentX(Component.CENTER_ALIGNMENT);
JButton construct_indices = new JButton("Construct Inverted Indices");
construct_indices.setAlignmentX(Component.CENTER_ALIGNMENT);
files = new JLabel();
files.setAlignmentX(Component.CENTER_ALIGNMENT);
//add action listeners
choose_files.addActionListener(new CloudProject());
choose_files.setActionCommand("1");
construct_indices.addActionListener(new CloudProject());
construct_indices.setActionCommand("2");
//add all to frame
frame.add(Box.createVerticalGlue());
frame.add(load_engine);
frame.add(Box.createVerticalGlue());
frame.add(choose_files);
frame.add(files);
frame.add(Box.createVerticalGlue());
frame.add(construct_indices);
frame.add(Box.createVerticalGlue());
//show window
frame.setSize(800,800);
frame.setVisible(true);
}
//topn algorithm
private static void getTopN(String text) {
//get topn
}
//search for term
private static void searchForTerm(String to_find) {
/*String destFilePath = "MRoutput.txt";
Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();
Blob blob = storage.get(BlobId.of(bucketName, "output"));
blob.downloadTo(Paths.get(destFilePath));*/
}
//helper method for submitting hadoop job
public static ArrayList<String> stringToList(String s) {
return new ArrayList<>(Arrays.asList(s.split(" ")));
}
//upload files selected to construct indices
public static void uploadFiles(String filePath) throws IOException {
String objectName = "";
//get file name
for(int i=filePath.length()-1; i>=0; i--) {
if(filePath.charAt(i) == '\\') {
objectName = filePath.substring(i+1, filePath.length());
break;
}
}
// You can specify a credential file by providing a path to GoogleCredentials.
// Otherwise credentials are read from the GOOGLE_APPLICATION_CREDENTIALS environment variable.
GoogleCredentials credentials = GoogleCredentials.fromStream(new FileInputStream(jsonPath))
.createScoped(Lists.newArrayList("https://www.googleapis.com/auth/cloud-platform"));
Storage storage = StorageOptions.newBuilder().setCredentials(credentials).setProjectId(projectId).build().getService();
BlobId blobId = BlobId.of(bucketName, "input/" + objectName);
BlobInfo blobInfo = BlobInfo.newBuilder(blobId).setContentType("application/x-tar").build();
storage.create(blobInfo, Files.readAllBytes(Paths.get(filePath)));
System.out.println("File " + filePath + " uploaded to bucket " + bucketName + " as " + objectName);
}
//submit a hadoop job
public static void submitHadoopFsJob(String projectId, String region, String clusterName, String hadoopFsQuery) throws IOException, InterruptedException {
String myEndpoint = String.format("%s-dataproc.googleapis.com:443", region);
String jsonPath = "cloudKeys.json";
// You can specify a credential file by providing a path to GoogleCredentials.
// Otherwise credentials are read from the GOOGLE_APPLICATION_CREDENTIALS environment variable.
GoogleCredentials credentials = GoogleCredentials.fromStream(new FileInputStream(jsonPath))
.createScoped(Lists.newArrayList("https://www.googleapis.com/auth/cloud-platform"));
// Configure the settings for the job controller client.
JobControllerSettings jobControllerSettings =
JobControllerSettings.newBuilder().setCredentialsProvider(FixedCredentialsProvider.create(credentials)).setEndpoint(myEndpoint).build();
// Create a job controller client with the configured settings. Using a try-with-resources
// closes the client,
// but this can also be done manually with the .close() method.
try (JobControllerClient jobControllerClient =
JobControllerClient.create(jobControllerSettings)) {
// Configure cluster placement for the job.
JobPlacement jobPlacement = JobPlacement.newBuilder().setClusterName(clusterName).build();
// Configure Hadoop job settings. The HadoopFS query is set here.
HadoopJob hadoopJob =
HadoopJob.newBuilder()
.setMainJarFileUri(jarFile)
.addAllArgs(stringToList(hadoopFsQuery))
.build();
Job job = Job.newBuilder().setPlacement(jobPlacement).setHadoopJob(hadoopJob).build();
// Submit an asynchronous request to execute the job.
OperationFuture<Job, JobMetadata> submitJobAsOperationAsyncRequest =
jobControllerClient.submitJobAsOperationAsync(projectId, region, job);
Job response = submitJobAsOperationAsyncRequest.get();
// Print output from Google Cloud Storage.
Matcher matches =
Pattern.compile("gs://(.*?)/(.*)").matcher(response.getDriverOutputResourceUri());
matches.matches();
Storage storage = StorageOptions.newBuilder().setCredentials(credentials).build().getService();
Blob blob = storage.get(matches.group(1), String.format("%s.000000000", matches.group(2)));
System.out.println(String.format("Job finished successfully: %s", new String(blob.getContent())));
} catch (ExecutionException e) {
// If the job does not complete successfully, print the error message.
System.err.println(String.format("submitHadoopFSJob: %s ", e.getMessage()));
}
}
}
|
[
"[email protected]"
] | |
6fc3c74d7f804770daca406e8d942c255a5955a6
|
9d6e1af5ea9319df6ad2be703b06b45c6b7fb19d
|
/android/app/src/main/java/com/testtmdbmovie/MainActivity.java
|
3e0c68b738e5df618bbbc2d0a1249347ed3d3eb0
|
[] |
no_license
|
shanada/testTmdbmovie
|
009b467506d588b4dedac16acdfca0376b5b9bff
|
d34845417ec474ccc5faa734fb9b78c9061ce835
|
refs/heads/master
| 2022-12-20T04:05:14.322514 | 2020-09-29T16:46:42 | 2020-09-29T16:46:42 | 299,667,187 | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 353 |
java
|
package com.testtmdbmovie;
import com.facebook.react.ReactActivity;
public class MainActivity extends ReactActivity {
/**
* Returns the name of the main component registered from JavaScript. This is used to schedule
* rendering of the component.
*/
@Override
protected String getMainComponentName() {
return "testTmdbmovie";
}
}
|
[
"[email protected]"
] | |
8bcbae76cb4c6a4c98bea7662fed0c246fc09670
|
11ac8e5ad262cdea56e2fd7a1ace698da15635e3
|
/datasourceOutOfAndroid/src/main/java/com/tencent/wstt/gt/datasource/util/SFUtils.java
|
38a3b17c9b5cc722efdc867afdaa29866145d38e
|
[
"MIT"
] |
permissive
|
Name66/GTTools
|
d13b0457c236038bfe3c9e66e93a37b27056057a
|
e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5
|
refs/heads/master
| 2020-03-26T17:55:44.990945 | 2017-06-15T02:31:14 | 2017-06-15T02:31:14 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 8,740 |
java
|
/*
* Tencent is pleased to support the open source community by making
* Tencent GT (Version 2.4 and subsequent versions) available.
*
* Notwithstanding anything to the contrary herein, any previous version
* of Tencent GT shall not be subject to the license hereunder.
* All right, title, and interest, including all intellectual property rights,
* in and to the previous version of Tencent GT (including any and all copies thereof)
* shall be owned and retained by Tencent and subject to the license under the
* Tencent GT End User License Agreement (http://gt.qq.com/wp-content/EULA_EN.html).
*
* Copyright (C) 2015 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the MIT License (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of the License at
*
* http://opensource.org/licenses/MIT
*
* 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.tencent.wstt.gt.datasource.util;
import com.tencent.wstt.gt.log.logcat.LogLine;
import com.tencent.wstt.gt.util.RuntimeHelper;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
public class SFUtils {
private static Set<Integer> pids = new HashSet<Integer>(2);
private static Map<Integer, BlockingQueue<Integer>> queues = new HashMap<Integer, BlockingQueue<Integer>>(2);
private static boolean killed = true;
private static Process dumpLogcatProcess;
/**
* 启动一个进程的卡顿帧数采集
* @param pid 进程号
* @return
*/
public static BlockingQueue<Integer> startSampleSF(int pid)
{
synchronized (SFUtils.class)
{
BlockingQueue<Integer> result = queues.get(pid);
if (result != null)
{
return result;
}
result = new ArrayBlockingQueue<Integer>(2);
pids.add(pid);
queues.put(pid, result);
if (dumpLogcatProcess == null && killed)
{
killed = false;
new Thread(new Runnable() {
@Override
public void run() {
try {
filterSF();
} catch (NumberFormatException e) {
e.printStackTrace();
return;
} catch (IOException e) {
e.printStackTrace();
return;
}
}
}, "GTSFRunner").start();
}
return result;
}
}
/**
* 停止一个进程的卡顿帧数采集
* @param pid 进程号
* @return
*/
public static void stopSampleSF(int pid)
{
synchronized (SFUtils.class)
{
pids.remove(pid);
queues.remove(pid);
}
if (pids.size() == 0) killProcess();
}
private static void filterSF() throws NumberFormatException, IOException {
List<String> args = new ArrayList<String>(
Arrays.asList("logcat", "-v", "time", "Choreographer:I", "*:S"));
dumpLogcatProcess = RuntimeHelper.exec(args);
BufferedReader reader = new BufferedReader(
new InputStreamReader(dumpLogcatProcess.getInputStream()), 8192);
String line;
while ((line = reader.readLine()) != null && !killed) {
// filter "The application may be doing too much work on its main thread."
if (!line.contains("uch work on its main t")) {
continue;
}
int pid = LogLine.newLogLine(line, false).getProcessId();
if (! pids.contains(Integer.valueOf(pid))) {
continue;
}
line = line.substring(50, line.length() - 71);
Integer value = Integer.parseInt(line.trim());
BlockingQueue<Integer> queue = queues.get(pid);
queue.offer(value);
}
killProcess();
}
private static void killProcess() {
if (!killed) {
synchronized (SFUtils.class) {
if (!killed) {
if (dumpLogcatProcess != null) {
RuntimeHelper.destroy(dumpLogcatProcess);
dumpLogcatProcess = null;
}
killed = true;
}
}
}
}
/**
* 检查卡帧设置是否有效
* @return
*/
public static boolean check() {
String cmd = "getprop debug.choreographer.skipwarning";
ProcessBuilder execBuilder = new ProcessBuilder("sh", "-c", cmd);
execBuilder.redirectErrorStream(true);
boolean flag = false;
try {
Process p = execBuilder.start();
InputStream is = p.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;
while ((line = br.readLine()) != null) {
if (line.compareTo("1") == 0) {
flag = true;
break;
}
}
} catch (IOException e) {
e.printStackTrace();
}
return flag;
}
/**
* 设置卡帧阈值为1
* @return
*/
public static void modify() {
String cmd = "setprop debug.choreographer.skipwarning 1";
ProcessBuilder execBuilder = new ProcessBuilder("su", "-c", cmd);
execBuilder.redirectErrorStream(true);
try {
execBuilder.start();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 恢复卡帧设置为30
*/
public static void recover() {
String cmd = "setprop debug.choreographer.skipwarning 30";
ProcessBuilder execBuilder = new ProcessBuilder("su", "-c", cmd);
execBuilder.redirectErrorStream(true);
try {
execBuilder.start();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 软启动以使卡帧设置生效
*/
public static void restart()
{
String cmd = "setprop ctl.restart surfaceflinger; setprop ctl.restart zygote";
ProcessBuilder execBuilder = new ProcessBuilder("su", "-c", cmd);
execBuilder.redirectErrorStream(true);
try {
execBuilder.start();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 基于标准流畅度为60的算分方法
* @param lst 计算数据源
* @return 计算结果列表
*/
public static int[] getSmDetail(List<Long> lst) {
int[] resultList = new int[6];
if (lst == null || lst.size() == 0)
return resultList;
double delta = 1.2;
double w = 0.4;
int s = 5;
int count5 = 0;
long minsm = 60;
int ktimes = 0;
int high = 0;
int highScore = 0;
int lowScore = 0;
int low = 0;
int total = 0;
int count = 0;
double resultn = 0;
double result = 0;
long lastdata = -1;
double sscore = 0;
double kscore = 0;
ArrayList<Long> tempDataList = new ArrayList<Long>();
long sm = 0;
for (int i = 0; i < lst.size(); i++) {
count5 += 1;
try {
sm = lst.get(i);
} catch (Exception e) {
}
minsm = (minsm > sm) ? sm : minsm;
if (sm < 40) {
ktimes += 1;
}
if (count5 == s) {
if (minsm >= 40) {
high += 1;
} else {
low += 1;
minsm *= Math.pow(delta, 1.0 / ktimes - 1);
}
total += 1;
tempDataList.add(minsm);
minsm = 60;
count5 = 0;
ktimes = 0;
}
}
if (count5 > 0) {
if (minsm >= 40)
high += 1;
else {
low += 1;
minsm *= Math.pow(delta, 1.0 / ktimes - 1);
}
total += 1;
tempDataList.add(minsm);
}
resultList[0] = low / total;
count = 0;
resultn = 0;
result = 0;
lastdata = -1;
sscore = 0;
kscore = 0;
for (int i = 0; i < tempDataList.size(); i++) {
Long data = tempDataList.get(i);
if (lastdata < 0) {
lastdata = data;
}
if (data >= 40) {
if (lastdata < 40) {
kscore += resultn;
result += resultn;
count = 0;
resultn = 0;
}
resultn += getscore(data);
count += 1;
} else {
if (lastdata >= 40) {
result += resultn * w;
sscore += resultn;
count = 0;
resultn = 0;
}
count += 1;
resultn += getscore(data);
}
lastdata = data;
}
if (count > 0 && lastdata < 40) {
result += resultn;
kscore += resultn;
}
if (count > 0 && lastdata >= 40) {
result += resultn * w;
sscore += resultn;
}
if (low > 0) {
lowScore = (int) (kscore * 100 / low);
}
if (high > 0) {
highScore = (int) (sscore * 100 / high);
}
resultList[1]= low * 5;
resultList[2] = lowScore;
resultList[3] = high * 5;
resultList[4] = highScore;
resultList[5] = (int) (result * 100 / (high * w + low));
return resultList;
}
private static double getscore(Long data) {
if (data < 20) {
return data * 1.5 / 100.0;
}
else if (data < 30 && data >= 20) {
return 0.3 + (data - 20) * 3 / 100.0;
}
else if (data < 50 && data >= 30) {
return 0.6 + (data - 30) / 100.0;
} else {
return 0.8 + (data - 50) * 2 / 100.0;
}
}
}
|
[
"[email protected]"
] | |
89711b8b8c9630e53d244dd0a4bd380018748e53
|
d648210f10b58cc581ec730f7994b9e889190257
|
/RestAPICucumber/src/runner/TestRunner.java
|
93dd2c8980a01d84cb5ab33cb728cdede77b63e4
|
[] |
no_license
|
Srisuja29/RestAPICucumber
|
b1d966c8a86cade2e4a8b2a50b8fd385c7417ee0
|
bf6a268579bc77608647201eb2a529f9355850fa
|
refs/heads/master
| 2020-03-26T06:57:38.454882 | 2018-08-02T22:43:42 | 2018-08-02T22:43:42 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 578 |
java
|
package runner;
//src/com/feature/login.feature
import org.junit.runner.RunWith;
import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;
@RunWith(Cucumber.class)
@CucumberOptions (
format={"pretty","html:target/reportApi1.html"},
glue={"steptest"},
features={"src/com/featuretest"},
dryRun=true,strict=true,
monochrome=true
)
public class TestRunner {
}
//src/com/feature/login.feature
// or ("smoke,regression") and ("smoke","regression") // ("~smoke,regression") for ignore
// tags={"@Smoke,@Regression"}
|
[
"[email protected]"
] | |
f035a0dd4b8e5996dcbefdcec89dc34a571c1e0a
|
8290c35cda9da5b93e5bb78e063c86b0a93ac89e
|
/java/android/webkit/WebViewFactory.java
|
e38a0406322994a6c36d3f21a2eb877b9ffd2d59
|
[
"Apache-2.0"
] |
permissive
|
wubolinha/webkit_for_android5.1
|
4821293972b605a250a0b14559763fe8115ba024
|
cde6e4689d61dab8b1831be8af6c771ce77048a3
|
refs/heads/master
| 2021-01-15T18:27:13.876639 | 2017-08-04T07:22:55 | 2017-08-04T07:22:55 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 21,919 |
java
|
/*
* Copyright (C) 2012 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.webkit;
import android.annotation.SystemApi;
import android.app.ActivityManagerInternal;
import android.app.AppGlobals;
import android.app.Application;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Process;
import android.os.RemoteException;
import android.os.ServiceManager;
import android.os.StrictMode;
import android.os.SystemProperties;
import android.os.Trace;
import android.text.TextUtils;
import android.util.AndroidRuntimeException;
import android.util.Log;
import com.android.server.LocalServices;
import dalvik.system.VMRuntime;
import java.io.File;
import java.util.Arrays;
/**
* Top level factory, used creating all the main WebView implementation classes.
*
* @hide
*/
@SystemApi
public final class WebViewFactory {
private static final String CHROMIUM_WEBVIEW_FACTORY =
"com.android.webview.chromium.WebViewChromiumFactoryProvider";
private static final String NULL_WEBVIEW_FACTORY =
"com.android.webview.nullwebview.NullWebViewFactoryProvider";
private static final String WEBKIT_WEBVIEW_FACTORY =
"android.webkit.WebViewClassic$Factory";
private static final String CHROMIUM_WEBVIEW_NATIVE_RELRO_32 =
"/data/misc/shared_relro/libwebviewchromium32.relro";
private static final String CHROMIUM_WEBVIEW_NATIVE_RELRO_64 =
"/data/misc/shared_relro/libwebviewchromium64.relro";
public static final String CHROMIUM_WEBVIEW_VMSIZE_SIZE_PROPERTY =
"persist.sys.webview.vmsize";
private static final long CHROMIUM_WEBVIEW_DEFAULT_VMSIZE_BYTES = 100 * 1024 * 1024;
private static final String LOGTAG = "WebViewFactory";
private static final boolean DEBUG = true;
// Cache the factory both for efficiency, and ensure any one process gets all webviews from the
// same provider.
private static WebViewFactoryProvider sProviderInstance;
private static final Object sProviderLock = new Object();
private static boolean sAddressSpaceReserved = false;
private static PackageInfo sPackageInfo;
public static String getWebViewPackageName() {
return AppGlobals.getInitialApplication().getString(
com.android.internal.R.string.config_webViewPackageName);
}
public static PackageInfo getLoadedPackageInfo() {
return sPackageInfo;
}
static WebViewFactoryProvider getProvider() {
return getWebKitWebViewProvider();
}
private static WebViewFactoryProvider getChromiumWebViewProvider() {
synchronized (sProviderLock) {
// For now the main purpose of this function (and the factory abstraction) is to keep
// us honest and minimize usage of WebView internals when binding the proxy.
if (sProviderInstance != null) return sProviderInstance;
final int uid = android.os.Process.myUid();
if (uid == android.os.Process.ROOT_UID || uid == android.os.Process.SYSTEM_UID) {
throw new UnsupportedOperationException(
"For security reasons, WebView is not allowed in privileged processes");
}
Trace.traceBegin(Trace.TRACE_TAG_WEBVIEW, "WebViewFactory.getProvider()");
try {
Trace.traceBegin(Trace.TRACE_TAG_WEBVIEW, "WebViewFactory.loadNativeLibrary()");
loadNativeLibrary();
Trace.traceEnd(Trace.TRACE_TAG_WEBVIEW);
Class<WebViewFactoryProvider> providerClass;
Trace.traceBegin(Trace.TRACE_TAG_WEBVIEW, "WebViewFactory.getFactoryClass()");
try {
providerClass = getFactoryClass();
} catch (ClassNotFoundException e) {
Log.e(LOGTAG, "error loading provider", e);
throw new AndroidRuntimeException(e);
} finally {
Trace.traceEnd(Trace.TRACE_TAG_WEBVIEW);
}
StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
Trace.traceBegin(Trace.TRACE_TAG_WEBVIEW, "providerClass.newInstance()");
try {
try {
sProviderInstance = providerClass.getConstructor(WebViewDelegate.class)
.newInstance(new WebViewDelegate());
} catch (Exception e) {
sProviderInstance = providerClass.newInstance();
}
if (DEBUG) Log.v(LOGTAG, "Loaded provider: " + sProviderInstance);
return sProviderInstance;
} catch (Exception e) {
Log.e(LOGTAG, "error instantiating provider", e);
throw new AndroidRuntimeException(e);
} finally {
Trace.traceEnd(Trace.TRACE_TAG_WEBVIEW);
StrictMode.setThreadPolicy(oldPolicy);
}
} finally {
Trace.traceEnd(Trace.TRACE_TAG_WEBVIEW);
}
}
}
private static WebViewFactoryProvider getWebKitWebViewProvider() {
synchronized (sProviderLock) {
// For now the main purpose of this function (and the factory abstraction) is to keep
// us honest and minimize usage of WebView internals when binding the proxy.
if (sProviderInstance != null) return sProviderInstance;
final int uid = android.os.Process.myUid();
if (uid == android.os.Process.ROOT_UID || uid == android.os.Process.SYSTEM_UID) {
throw new UnsupportedOperationException(
"For security reasons, WebView is not allowed in privileged processes");
}
Trace.traceBegin(Trace.TRACE_TAG_WEBVIEW, "WebViewFactory.getProvider()");
try {
Class<WebViewFactoryProvider> providerClass;
Trace.traceBegin(Trace.TRACE_TAG_WEBVIEW, "WebViewFactory.getFactoryClass()");
try {
providerClass = (Class<WebViewFactoryProvider>) Class.forName(WEBKIT_WEBVIEW_FACTORY);;
} catch (ClassNotFoundException e) {
Log.e(LOGTAG, "error loading provider", e);
throw new AndroidRuntimeException(e);
} finally {
Trace.traceEnd(Trace.TRACE_TAG_WEBVIEW);
}
StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
Trace.traceBegin(Trace.TRACE_TAG_WEBVIEW, "providerClass.newInstance()");
try {
try {
sProviderInstance = providerClass.getConstructor(WebViewDelegate.class)
.newInstance(new WebViewDelegate());
} catch (Exception e) {
sProviderInstance = providerClass.newInstance();
}
{
System.loadLibrary("webcore");
System.loadLibrary("chromium_net");
}
if (DEBUG) Log.v(LOGTAG, "Loaded provider: " + sProviderInstance);
return sProviderInstance;
} catch (Exception e) {
Log.e(LOGTAG, "error instantiating provider", e);
throw new AndroidRuntimeException(e);
} finally {
Trace.traceEnd(Trace.TRACE_TAG_WEBVIEW);
StrictMode.setThreadPolicy(oldPolicy);
}
} finally {
Trace.traceEnd(Trace.TRACE_TAG_WEBVIEW);
}
}
}
private static Class<WebViewFactoryProvider> getFactoryClass() throws ClassNotFoundException {
Application initialApplication = AppGlobals.getInitialApplication();
try {
// First fetch the package info so we can log the webview package version.
String packageName = getWebViewPackageName();
sPackageInfo = initialApplication.getPackageManager().getPackageInfo(packageName, 0);
Log.i(LOGTAG, "Loading " + packageName + " version " + sPackageInfo.versionName +
" (code " + sPackageInfo.versionCode + ")");
// Construct a package context to load the Java code into the current app.
Context webViewContext = initialApplication.createPackageContext(packageName,
Context.CONTEXT_INCLUDE_CODE | Context.CONTEXT_IGNORE_SECURITY);
initialApplication.getAssets().addAssetPath(
webViewContext.getApplicationInfo().sourceDir);
ClassLoader clazzLoader = webViewContext.getClassLoader();
Trace.traceBegin(Trace.TRACE_TAG_WEBVIEW, "Class.forName()");
try {
return (Class<WebViewFactoryProvider>) Class.forName(CHROMIUM_WEBVIEW_FACTORY, true,
clazzLoader);
} finally {
Trace.traceEnd(Trace.TRACE_TAG_WEBVIEW);
}
} catch (PackageManager.NameNotFoundException e) {
// If the package doesn't exist, then try loading the null WebView instead.
// If that succeeds, then this is a device without WebView support; if it fails then
// swallow the failure, complain that the real WebView is missing and rethrow the
// original exception.
try {
return (Class<WebViewFactoryProvider>) Class.forName(NULL_WEBVIEW_FACTORY);
} catch (ClassNotFoundException e2) {
// Ignore.
}
Log.e(LOGTAG, "Chromium WebView package does not exist", e);
throw new AndroidRuntimeException(e);
}
}
/**
* Perform any WebView loading preparations that must happen in the zygote.
* Currently, this means allocating address space to load the real JNI library later.
*/
public static void prepareWebViewInZygote() {
try {
System.loadLibrary("webviewchromium_loader");
long addressSpaceToReserve =
SystemProperties.getLong(CHROMIUM_WEBVIEW_VMSIZE_SIZE_PROPERTY,
CHROMIUM_WEBVIEW_DEFAULT_VMSIZE_BYTES);
sAddressSpaceReserved = nativeReserveAddressSpace(addressSpaceToReserve);
if (sAddressSpaceReserved) {
if (DEBUG) {
Log.v(LOGTAG, "address space reserved: " + addressSpaceToReserve + " bytes");
}
} else {
Log.e(LOGTAG, "reserving " + addressSpaceToReserve +
" bytes of address space failed");
}
} catch (Throwable t) {
// Log and discard errors at this stage as we must not crash the zygote.
Log.e(LOGTAG, "error preparing native loader", t);
}
}
/**
* Perform any WebView loading preparations that must happen at boot from the system server,
* after the package manager has started or after an update to the webview is installed.
* This must be called in the system server.
* Currently, this means spawning the child processes which will create the relro files.
*/
public static void prepareWebViewInSystemServer() {
String[] nativePaths = null;
try {
nativePaths = getWebViewNativeLibraryPaths();
} catch (Throwable t) {
// Log and discard errors at this stage as we must not crash the system server.
Log.e(LOGTAG, "error preparing webview native library", t);
}
prepareWebViewInSystemServer(nativePaths);
}
private static void prepareWebViewInSystemServer(String[] nativeLibraryPaths) {
if (DEBUG) Log.v(LOGTAG, "creating relro files");
// We must always trigger createRelRo regardless of the value of nativeLibraryPaths. Any
// unexpected values will be handled there to ensure that we trigger notifying any process
// waiting on relreo creation.
if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
if (DEBUG) Log.v(LOGTAG, "Create 32 bit relro");
createRelroFile(false /* is64Bit */, nativeLibraryPaths);
}
if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
if (DEBUG) Log.v(LOGTAG, "Create 64 bit relro");
createRelroFile(true /* is64Bit */, nativeLibraryPaths);
}
}
public static void onWebViewUpdateInstalled() {
String[] nativeLibs = null;
try {
nativeLibs = WebViewFactory.getWebViewNativeLibraryPaths();
if (nativeLibs != null) {
long newVmSize = 0L;
for (String path : nativeLibs) {
if (DEBUG) Log.d(LOGTAG, "Checking file size of " + path);
if (path == null) continue;
File f = new File(path);
if (f.exists()) {
long length = f.length();
if (length > newVmSize) {
newVmSize = length;
}
}
}
if (DEBUG) {
Log.v(LOGTAG, "Based on library size, need " + newVmSize +
" bytes of address space.");
}
// The required memory can be larger than the file on disk (due to .bss), and an
// upgraded version of the library will likely be larger, so always attempt to
// reserve twice as much as we think to allow for the library to grow during this
// boot cycle.
newVmSize = Math.max(2 * newVmSize, CHROMIUM_WEBVIEW_DEFAULT_VMSIZE_BYTES);
Log.d(LOGTAG, "Setting new address space to " + newVmSize);
SystemProperties.set(CHROMIUM_WEBVIEW_VMSIZE_SIZE_PROPERTY,
Long.toString(newVmSize));
}
} catch (Throwable t) {
// Log and discard errors at this stage as we must not crash the system server.
Log.e(LOGTAG, "error preparing webview native library", t);
}
prepareWebViewInSystemServer(nativeLibs);
}
private static String[] getWebViewNativeLibraryPaths()
throws PackageManager.NameNotFoundException {
final String NATIVE_LIB_FILE_NAME = "libwebviewchromium.so";
PackageManager pm = AppGlobals.getInitialApplication().getPackageManager();
ApplicationInfo ai = pm.getApplicationInfo(getWebViewPackageName(), 0);
String path32;
String path64;
boolean primaryArchIs64bit = VMRuntime.is64BitAbi(ai.primaryCpuAbi);
if (!TextUtils.isEmpty(ai.secondaryCpuAbi)) {
// Multi-arch case.
if (primaryArchIs64bit) {
// Primary arch: 64-bit, secondary: 32-bit.
path64 = ai.nativeLibraryDir;
path32 = ai.secondaryNativeLibraryDir;
} else {
// Primary arch: 32-bit, secondary: 64-bit.
path64 = ai.secondaryNativeLibraryDir;
path32 = ai.nativeLibraryDir;
}
} else if (primaryArchIs64bit) {
// Single-arch 64-bit.
path64 = ai.nativeLibraryDir;
path32 = "";
} else {
// Single-arch 32-bit.
path32 = ai.nativeLibraryDir;
path64 = "";
}
if (!TextUtils.isEmpty(path32)) path32 += "/" + NATIVE_LIB_FILE_NAME;
if (!TextUtils.isEmpty(path64)) path64 += "/" + NATIVE_LIB_FILE_NAME;
return new String[] { path32, path64 };
}
private static void createRelroFile(final boolean is64Bit, String[] nativeLibraryPaths) {
final String abi =
is64Bit ? Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
// crashHandler is invoked by the ActivityManagerService when the isolated process crashes.
Runnable crashHandler = new Runnable() {
@Override
public void run() {
try {
Log.e(LOGTAG, "relro file creator for " + abi + " crashed. Proceeding without");
getUpdateService().notifyRelroCreationCompleted(is64Bit, false);
} catch (RemoteException e) {
Log.e(LOGTAG, "Cannot reach WebViewUpdateService. " + e.getMessage());
}
}
};
try {
if (nativeLibraryPaths == null
|| nativeLibraryPaths[0] == null || nativeLibraryPaths[1] == null) {
throw new IllegalArgumentException(
"Native library paths to the WebView RelRo process must not be null!");
}
int pid = LocalServices.getService(ActivityManagerInternal.class).startIsolatedProcess(
RelroFileCreator.class.getName(), nativeLibraryPaths, "WebViewLoader-" + abi, abi,
Process.SHARED_RELRO_UID, crashHandler);
if (pid <= 0) throw new Exception("Failed to start the relro file creator process");
} catch (Throwable t) {
// Log and discard errors as we must not crash the system server.
Log.e(LOGTAG, "error starting relro file creator for abi " + abi, t);
crashHandler.run();
}
}
private static class RelroFileCreator {
// Called in an unprivileged child process to create the relro file.
public static void main(String[] args) {
boolean result = false;
boolean is64Bit = VMRuntime.getRuntime().is64Bit();
try{
if (args.length != 2 || args[0] == null || args[1] == null) {
Log.e(LOGTAG, "Invalid RelroFileCreator args: " + Arrays.toString(args));
return;
}
Log.v(LOGTAG, "RelroFileCreator (64bit = " + is64Bit + "), " +
" 32-bit lib: " + args[0] + ", 64-bit lib: " + args[1]);
if (!sAddressSpaceReserved) {
Log.e(LOGTAG, "can't create relro file; address space not reserved");
return;
}
result = nativeCreateRelroFile(args[0] /* path32 */,
args[1] /* path64 */,
CHROMIUM_WEBVIEW_NATIVE_RELRO_32,
CHROMIUM_WEBVIEW_NATIVE_RELRO_64);
if (result && DEBUG) Log.v(LOGTAG, "created relro file");
} finally {
// We must do our best to always notify the update service, even if something fails.
try {
getUpdateService().notifyRelroCreationCompleted(is64Bit, result);
} catch (RemoteException e) {
Log.e(LOGTAG, "error notifying update service", e);
}
if (!result) Log.e(LOGTAG, "failed to create relro file");
// Must explicitly exit or else this process will just sit around after we return.
System.exit(0);
}
}
}
private static void loadNativeLibrary() {
if (!sAddressSpaceReserved) {
Log.e(LOGTAG, "can't load with relro file; address space not reserved");
return;
}
try {
getUpdateService().waitForRelroCreationCompleted(VMRuntime.getRuntime().is64Bit());
} catch (RemoteException e) {
Log.e(LOGTAG, "error waiting for relro creation, proceeding without", e);
return;
}
try {
String[] args = getWebViewNativeLibraryPaths();
boolean result = nativeLoadWithRelroFile(args[0] /* path32 */,
args[1] /* path64 */,
CHROMIUM_WEBVIEW_NATIVE_RELRO_32,
CHROMIUM_WEBVIEW_NATIVE_RELRO_64);
if (!result) {
Log.w(LOGTAG, "failed to load with relro file, proceeding without");
} else if (DEBUG) {
Log.v(LOGTAG, "loaded with relro file");
}
} catch (PackageManager.NameNotFoundException e) {
Log.e(LOGTAG, "Failed to list WebView package libraries for loadNativeLibrary", e);
}
}
private static IWebViewUpdateService getUpdateService() {
return IWebViewUpdateService.Stub.asInterface(ServiceManager.getService("webviewupdate"));
}
private static native boolean nativeReserveAddressSpace(long addressSpaceToReserve);
private static native boolean nativeCreateRelroFile(String lib32, String lib64,
String relro32, String relro64);
private static native boolean nativeLoadWithRelroFile(String lib32, String lib64,
String relro32, String relro64);
}
|
[
"[email protected]"
] | |
973c7ce1abd5b1a19a6c7eb2c57103d7dd2d989c
|
5d22985c31de177b388cc8a274e76dd9228a2e06
|
/UdemyLearningPracticeNew/src/com/practice/NumberToWord.java
|
b95271dfa555b0cb058d484e9b422954ec6520c6
|
[] |
no_license
|
smitha5990/MyLearnings
|
8621cceba2274b7806eca47cbd19f4df31cacabd
|
0d902c0084ab8f24e857fed8b7c3d31e04b19242
|
refs/heads/master
| 2020-06-05T23:00:55.258955 | 2019-07-03T00:09:58 | 2019-07-03T00:09:58 | 192,569,224 | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 758 |
java
|
package com.practice;
import java.util.Scanner;
public class NumberToWord {
public static void main(String[]args) {
Scanner s=new Scanner(System.in);
System.out.println("enter a number");
int n=s.nextInt();
numbertoword(n);
s.close();
}
public static void numbertoword(int n) {
int m=n;
switch(m) {
case -3:
System.out.println("negative three");
break;
case -2:
System.out.println("negative two");
break;
case -1:
System.out.println("negative one");
break;
case 0:
System.out.println("zero");
break;
case 1:
System.out.println("one");
break;
case 2:
System.out.println("two");
break;
case 3:
System.out.println("three");
break;
default:
System.out.println("invalid");
}
}
}
|
[
"[email protected]"
] | |
ad96fae1b4f393fe7a419e7a274ab5a69ffdba6e
|
bcd8ed8634a0850d5153eb34e226499e84a1d0f9
|
/pwall/vector/VectorTimestamp.java
|
131be19b2850aaeb6cf80eb616edcbab9cf651b5
|
[] |
no_license
|
petewall/distributedAlgorithmsDemonstrator
|
4f69fb8a1dba5dc56cb0ced635de514db4430418
|
59b87d8cc187362487844946f9d0a37554da1ecd
|
refs/heads/master
| 2021-01-01T19:16:18.803575 | 2014-08-05T17:08:23 | 2014-08-05T17:08:23 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 2,692 |
java
|
package pwall.vector;
public class VectorTimestamp
{
public VectorTimestamp(int size)
{
vectorClock = new int[size];
for (int i = 0; i < size; ++i) {
vectorClock[i] = 0;
}
}
public VectorTimestamp(VectorTimestamp other)
{
this(other.size());
for (int i = 0; i < size(); ++i) {
vectorClock[i] = other.get(i);
}
}
public VectorTimestamp copy()
{
return new VectorTimestamp(this);
}
public String toString()
{
return toString(-1);
}
public String toString(int index)
{
String result = "{";
for (int i = 0; i < vectorClock.length; ++i) {
if (i == index)
result += "[" + vectorClock[i] + "],";
else
result += vectorClock[i] + ",";
}
result = result.substring(0, result.length() - 1);
result += "}";
return result;
}
public int get(int index)
{
return vectorClock[index];
}
public void set(int index, int value)
{
vectorClock[index] = value;
}
public void increment(int index)
{
vectorClock[index]++;
}
public int size()
{
return vectorClock.length;
}
/**
* Ta = Tb iff for all i, Ta[i] = Tb[i]
* @param other The VectorTimestamp to compare to.
* @return The equality result.
*/
public boolean equals(VectorTimestamp other)
{
for (int i = 0; i < size(); ++i) {
if (get(i) != other.get(i))
return false;
}
return true;
}
/**
* Ta ≤ Tb iff for all i, Ta[i] ≤ Tb[i]
* @param other The VectorTimestamp to compare to.
* @return The ≤ result.
*/
public boolean lessThanEquals(VectorTimestamp other)
{
for (int i = 0; i < size(); ++i) {
if (get(i) > other.get(i))
return false;
}
return true;
}
/**
* Ta < Tb iff Ta ≤ Tb and Ta ≠ Tb
* @param other The VectorTimestamp to compare to.
* @return The < result.
*/
public boolean lessThan(VectorTimestamp other)
{
if (!equals(other) && lessThanEquals(other))
return true;
return false;
}
/**
* Ta || Tb iff Ta < Tb and Tb < Ta
* @param other The VectorTimestamp to compare to.
* @return The concurrency result.
*/
public boolean concurrent(VectorTimestamp other)
{
if (this.lessThan(other) && other.lessThan(this))
return true;
return false;
}
private int[] vectorClock;
}
|
[
"[email protected]"
] | |
42f5ca8598a2170d116a8e6221d09cc30ddd8186
|
c2576ad20f2dbe2f03b4ddf6baecdf4b3af755d7
|
/Advertisements/app/src/main/java/ah1/com/advertisements_v1/AdsSingleActivity.java
|
81a36dac7405b9b0e782123a8da9acec3aeee3b6
|
[] |
no_license
|
AhmedSalehHde/AndroidAds2
|
4c6e656fa67a8c71091624a4d7c3a89b5849fb32
|
ebe8b05cfa5e69aef5fdad7c621ec74e00dc62c6
|
refs/heads/master
| 2020-04-13T15:41:41.398164 | 2018-12-27T13:46:52 | 2018-12-27T13:46:52 | 163,299,646 | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 6,828 |
java
|
package ah1.com.advertisements_v1;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.squareup.picasso.Picasso;
public class AdsSingleActivity extends AppCompatActivity {
private String aAds_key=null;
private DatabaseReference aDatabase;
private FirebaseAuth aAuth;
private TextView aAdsSingleTitle;
private TextView aAdsSingleDesc;
private TextView aAdsSingle_userphone;
private TextView aAdsSingle_userlocation;
private TextView aAdsSingleUser;
private ImageView aAdsSingleImage;
private Button aAdsSingleRemoveBu;
private Button aAdsSingleModifyBu;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ads_single);
////////////////////////////////////////////////////////////////////////////////
//-----------------------------------------------------------------------------
//الشريط العلوي
Toolbar my_toolbar=(Toolbar)findViewById(R.id.my_toolbar);
setSupportActionBar(my_toolbar);
getSupportActionBar().setTitle(" "+"الاعلان"+" ");
getSupportActionBar().setIcon(R.mipmap.ic_launcher_adway);
//-----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
aAds_key=getIntent().getExtras().getString("ads_id");
//Toast.makeText(this, ads_key, Toast.LENGTH_SHORT).show();
aAdsSingleTitle=(TextView)findViewById(R.id.adsSingleTitle);
aAdsSingleDesc=(TextView)findViewById(R.id.adsSingleDec);
aAdsSingle_userphone=(TextView)findViewById(R.id.adsSingle_userphone);
aAdsSingle_userlocation=(TextView)findViewById(R.id.adsSingle_userlocation);
aAdsSingleUser=(TextView)findViewById(R.id.adsSingleUser);
aAdsSingleImage=(ImageView) findViewById(R.id.adsSingleImage);
aAdsSingleRemoveBu=(Button)findViewById(R.id.adsSingleRemoveBu);
aAdsSingleModifyBu=(Button)findViewById(R.id.adsSingleModifyBu);
aAuth=FirebaseAuth.getInstance();
aDatabase= FirebaseDatabase.getInstance().getReference().child("Ads");
aDatabase.child(aAds_key).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
String ads_title= (String) dataSnapshot.child("title").getValue();
String ads_desc= (String) dataSnapshot.child("descrption").getValue();
String ads_userphone= (String) dataSnapshot.child("phone").getValue();
String ads_userlocation= (String) dataSnapshot.child("location").getValue();
String ads_image= (String) dataSnapshot.child("image").getValue();
String ads_uid= (String) dataSnapshot.child("uid").getValue();
String ads_userName= (String) dataSnapshot.child("username").getValue();
aAdsSingleTitle.setText(ads_title);
aAdsSingleDesc.setText(ads_desc);
aAdsSingle_userphone.setText(ads_userphone);
aAdsSingle_userlocation.setText(ads_userlocation);
aAdsSingleUser.setText(ads_userName);
Picasso.with(AdsSingleActivity.this).load(ads_image).into(aAdsSingleImage);
if(aAuth.getCurrentUser().getUid().equals(ads_uid))
{
aAdsSingleRemoveBu.setVisibility(View.VISIBLE);
aAdsSingleModifyBu.setVisibility(View.VISIBLE);
}
else
{
aAdsSingleRemoveBu.setVisibility(View.INVISIBLE);
aAdsSingleModifyBu.setVisibility(View.INVISIBLE);
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
////////////////////////////////////////////////////////////////////////////
aAdsSingleRemoveBu.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
MassgOnRemove();
/*
aDatabase.child(aAds_key).removeValue();
// Intent mainIntent=new Intent(AdsSingleActivity.this,MainActivity.class);
//startActivity(mainIntent);
finish();
*/
}
});
aAdsSingleModifyBu.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//final String ads_key=getRef(position).getKey();//يسحب رقم الاي دي حق الريسايكل فيو للمحدده ب البوزيشن الموقع المحدد عند الضغط
Intent singleAdsIntent=new Intent(AdsSingleActivity.this,ModifyAdvertisements.class);
singleAdsIntent.putExtra("ads_id",aAds_key);
startActivity(singleAdsIntent);
}
});
}
//رسالة الديالوق لتاكيد حذف الاعلان او تراجع عن الحذف
public void MassgOnRemove()
{
AlertDialog.Builder build=new AlertDialog.Builder(this);
build.setMessage("هل تريد حذف الاعلان ؟")
.setTitle("حذف الاعلان")
.setPositiveButton("نعم", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
aDatabase.child(aAds_key).removeValue();
finish();
}
})
.setNegativeButton("لا", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
}
}).show();
}
}
|
[
"[email protected]"
] | |
8a4293275db957fc15d1177db665ff866819bdb1
|
5639bad159509b15a8cc6951e22fed8cf8439b1b
|
/bin/bbmap/current/jgi/RQCFilter2.java
|
0fbb453b4618e169c3c76b559a39b034548b0bee
|
[
"BSD-3-Clause-LBNL"
] |
permissive
|
KosuriLab/ecoli_promoter_mpra
|
3f9fe47e40a81f9bafd27f672d0e7ece5924789f
|
484abdb6ba2d398501009ee6eb25ca7f190d3b4c
|
refs/heads/master
| 2021-07-09T00:38:46.186513 | 2020-08-10T17:28:54 | 2020-08-10T17:28:54 | 179,758,077 | 0 | 1 | null | null | null | null |
UTF-8
|
Java
| false | false | 139,322 |
java
|
package jgi;
import java.io.File;
import java.io.PrintStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashSet;
import java.util.Locale;
import java.util.TimeZone;
import align2.BBMap;
import align2.BBSplitter;
import align2.RefToIndex;
import clump.Clumpify;
import clump.KmerSort;
import dna.AminoAcid;
import dna.Data;
import fileIO.ByteFile1;
import fileIO.FileFormat;
import fileIO.ReadWrite;
import fileIO.TextFile;
import fileIO.TextStreamWriter;
import hiseq.AnalyzeFlowCell;
import server.ServerTools;
import shared.Parser;
import shared.PreParser;
import shared.ReadStats;
import shared.Shared;
import shared.Timer;
import shared.Tools;
import shared.TrimRead;
import sketch.SendSketch;
import sketch.SketchObject;
import stream.FASTQ;
import stream.Read;
import stream.ReadInputStream;
import tax.FilterByTaxa;
import tax.GiToNcbi;
import tax.TaxFilter;
import tax.TaxNode;
import tax.TaxTree;
/**
* Wrapper for several other programs to implement Rolling QC's filter stage.
* Calls SendSketch, Clumpify, KmerCountExact, BBNorm, BBDuk, BBMap, BBMerge, and SplitNexteraLMP.
* Trims adapters, removes contaminants, and does quality-trimming.
* @author Brian Bushnell
* @date Nov 26, 2013
*
*/
public class RQCFilter2 {
/*--------------------------------------------------------------*/
/*---------------- Initialization Methods ----------------*/
/*--------------------------------------------------------------*/
/**
* Program entrance from command line.
* @param args Command line arguments
*/
public static void main(String[] args){
//Start a timer
Timer t=new Timer();
//Create a filter instance
RQCFilter2 x=new RQCFilter2(args);
//Execute filtering.
x.process();
//Report time
t.stop();
outstream.println("\nOverall Time: \t"+t);
//Close the print stream if it was redirected
Shared.closeStream(outstream);
}
/**
* Constructor.
* @param args Command line arguments
*/
RQCFilter2(String[] args){
{//Preparse block for help, config files, and outstream
PreParser pp=new PreParser(args, getClass(), true);
args=pp.args;
outstream=pp.outstream;
}
//Parses some shared arguments
Parser parser=new Parser();
//Symbols to insert in output filename to denote operations performed; may be overriden from command line
String symbols_=null;
boolean doNextera_=false;
FASTQ.DETECT_QUALITY_OUT=false;
FASTQ.ASCII_OFFSET_OUT=33;
ReadWrite.USE_PIGZ=ReadWrite.USE_UNPIGZ=true;
ReadWrite.MAX_ZIP_THREADS=Tools.max(Shared.threads()>1 ? 2 : 1, Shared.threads()>20 ? Shared.threads()/2 : Shared.threads());
TaxFilter.REQUIRE_PRESENT=false;
SendSketch.suppressErrors=ServerTools.suppressErrors=true;
ReadStats.GC_BINS_AUTO=true;
boolean doMerge_=true;
//Parse argument list
for(int i=0; i<args.length; i++){
String arg=args[i];
String[] split=arg.split("="); //Expect key=value pairs
String a=split[0].toLowerCase(); //All keys are converted to lower case
String b=split.length>1 ? split[1] : null;
if(Parser.parseCommonStatic(arg, a, b)){
//do nothing
}else if(Parser.parseZip(arg, a, b)){
if(a.equals("pigz")){
pigz=b;
}else if(a.equals("unpigz")){
unpigz=b;
}else if(a.equals("zl") || a.equals("ziplevel")){
zl=b;
}
}else if(parser.parseInterleaved(arg, a, b)){
//do nothing
}else if(a.equals("verbose")){
verbose=Tools.parseBoolean(b);
ByteFile1.verbose=verbose;
stream.FastaReadInputStream.verbose=verbose;
primaryArgList.add(arg);
}else if(a.equals("in") || a.equals("input") || a.equals("in1") || a.equals("input1")){
in1=b;
}else if(a.equals("in2") || a.equals("input2")){
in2=b;
}else if(a.equals("out") || a.equals("output") || a.equals("out1") || a.equals("output1")){
out1=b;
}else if(a.equals("out2") || a.equals("output2")){
out2=b;
}else if(a.equals("ref")){
if(b!=null){
if(!b.contains(",") || new File(b).exists()){
bbdukFilterRefs.add(b);
}else{
String[] split2=b.split(",");
for(String s2 : split2){
bbdukFilterRefs.add(s2);
}
}
}
}else if(a.equals("spikeinref")){
if(b!=null){
if(!b.contains(",") || new File(b).exists()){
spikeinRefs.add(b);
}else{
String[] split2=b.split(",");
for(String s2 : split2){
spikeinRefs.add(s2);
}
}
}
}else if(a.equals("artifactdb")){
mainArtifactFile=b;
}else if(a.equals("ribodb")){
riboKmers=b;
}else if(a.equals("phixref")){
phixRef=b;
}else if(a.equals("fragadapter")){
fragAdapter=b;
}else if(a.equals("rnaadapter")){
rnaAdapter=b;
}else if(a.equals("lfpelinker")){
lfpeLinker=b;
}else if(a.equals("cliplinker") || a.equals("jointseq")){
clipLinker=b;
}else if(a.equals("clrslinker")){
clrsLinker=b;
}else if(a.equals("bisulfite") || a.equals("bisulfate")){ //Allow for a common mispelling... ;)
bisulfite=Tools.parseBoolean(b);
}else if(a.equals("trimfragadapter") || a.equals("trimfragadapters")){
fragAdapterFlag=Tools.parseBoolean(b);
}else if(a.equals("trimrnaadapter") || a.equals("trimrnaadapters")){
rnaAdapterFlag=Tools.parseBoolean(b);
}else if(a.equals("removehuman") || a.equals("human")){
humanFlag=Tools.parseBoolean(b);
}else if(a.equals("removedog") || a.equals("dog")){
dogFlag=Tools.parseBoolean(b);
}else if(a.equals("removecat") || a.equals("cat")){
catFlag=Tools.parseBoolean(b);
}else if(a.equals("removemouse") || a.equals("mouse")){
mouseFlag=Tools.parseBoolean(b);
}else if(a.equals("catdoghumanmouse") || a.equals("mousecatdoghuman") || a.equals("catdogmousehuman")){
mouseCatDogHumanFlag=Tools.parseBoolean(b);
}else if(a.equals("keephumanreads") || a.equals("keephuman")){
keepHumanReads=Tools.parseBoolean(b);
}else if(a.equals("aggressive")){
aggressiveHumanFlag=aggressiveMicrobeFlag=Tools.parseBoolean(b);
}else if(a.equals("aggressivehuman")){
aggressiveHumanFlag=Tools.parseBoolean(b);
}else if(a.equals("aggressivemicrobe")){
aggressiveMicrobeFlag=Tools.parseBoolean(b);
}else if(a.equals("removemicrobes") || a.equals("removecommonmicrobes") || a.equals("microbes")){
removeCommonMicrobeFlag=Tools.parseBoolean(b);
}else if(a.equals("trimuntrim")){
trimUntrim=Tools.parseBoolean(b);
}else if(a.equals("ribomap")){
riboMapFlag=Tools.parseBoolean(b);
}else if(a.equals("removechloroplast") || a.equals("chloroplast") || a.equals("chloro") || a.equals("chloromap")){
chloroMapFlag=Tools.parseBoolean(b);
}else if(a.equals("removemito") || a.equals("mito") || a.equals("mitomap")){
mitoMapFlag=Tools.parseBoolean(b);
}else if(a.equals("detectmicrobes") || a.equals("detectcommonmicrobes")){
detectMicrobeFlag=Tools.parseBoolean(b);
}else if(a.equals("detectmicrobes2") || a.equals("detectothermicrobes")){
otherMicrobeFlag=Tools.parseBoolean(b);
}else if(a.equals("removeribo") || a.equals("ribo")){
riboKmerFlag=Tools.parseBoolean(b);
}else if(a.equals("riboout") || a.equals("outribo")){
riboOutFile=b;
}else if(a.equals("fbtout") || a.equals("outfbt")){
fbtOutFile=b;
}else if(a.equals("overwrite") || a.equals("ow")){
overwrite=Tools.parseBoolean(b);
}else if(a.equals("ml") || a.equals("minlen") || a.equals("minlength")){
minLen=Integer.parseInt(b);
}else if(a.equals("mlf") || a.equals("minlenfrac") || a.equals("minlenfraction") || a.equals("minlengthfraction")){
minLenFraction=Float.parseFloat(b);
}else if(a.equals("libtype") || a.equals("library")){
libType=toLibType(b);
}else if(a.equals("path") || a.equals("outdir")){
outDir=b;
}else if(a.equals("symbols")){
symbols_=b;
}else if(a.equals("overallstats") || a.equals("stats")){
rqcStatsName=b;
}else if(a.equals(a.equals("stats2"))){
rqcStatsName2=b;
}else if(a.equals("scafstats")){
scaffoldStatsName1=b;
}else if(a.equals("scafstatskt") || a.equals("scafstatstrim")){
scaffoldStatsName_kt=b;
}else if(a.equals("refstats")){
refStatsName=b;
}else if(a.equals("kmerstats")){
kmerStatsName1=b;
}else if(a.equals("log")){
logName=b;
}else if(a.equals("ihist")){
ihistName=b;
}else if(a.equals("merge") || a.equals("domerge")){
doMerge_=Tools.parseBoolean(b);
}else if(a.equals("khist") || a.equals("dokhist")){
doKhist=Tools.parseBoolean(b);
}else if(a.equals("filelist")){
fileListName=b;
}else if(a.equals("compress")){
compress=Tools.parseBoolean(b);
}else if(a.equalsIgnoreCase("polya") || a.equalsIgnoreCase("removepolya") || a.equalsIgnoreCase("filterpolya")){
filterPolyA=Tools.parseBoolean(b);
}else if(a.equalsIgnoreCase("trimpolya")){
trimPolyA=Tools.parseBoolean(b);
}else if(a.equals("trimpolyg")){
trimPolyGLeft=trimPolyGRight=Parser.parsePoly(b);
}else if(a.equals("trimpolygleft")){
trimPolyGLeft=Parser.parsePoly(b);
}else if(a.equals("trimpolygright")){
trimPolyGRight=Parser.parsePoly(b);
}else if(a.equals("filterpolyg")){
filterPolyG=Parser.parsePoly(b);
}else if(a.equals("phix") || a.equals("removephix")){
phixFlag=Tools.parseBoolean(b);
}else if(a.equals("lambda") || a.equals("removelambda")){
lambdaFlag=Tools.parseBoolean(b);
}else if(a.equals("pjet")){
pjetFlag=Tools.parseBoolean(b);
}else if(a.equals("mtst")){
mtstFlag=Tools.parseBoolean(b);
}else if(a.equals("kapa")){
kapaFlag=Tools.parseBoolean(b);
}else if(a.equals("jointseq")){
jointSeq=b;
}else if(a.equals("nextera") || a.equals("nexteralmp")){
doNextera_=Tools.parseBoolean(b);
}else if(a.equals("copyundefined") || a.equals("cu")){
copyUndefined=Tools.parseBoolean(b);
}else if(a.equals("ktrim")){
ktrim=b;
}else if(a.equals("ftl") || a.equals("forcetrimleft")){
ftl=Integer.parseInt(b);
}else if(a.equals("ftr") || a.equals("forcetrimright")){
ftr=Integer.parseInt(b);
}else if(a.equals("ftr2") || a.equals("forcetrimright2")){
ftr2=Integer.parseInt(b);
}else if(a.equals("mink")){
mink=Integer.parseInt(b);
}else if(a.equals("k")){
assert(false) : "To specify kmer length, use filterk, trimk, mapk, or normalizek instead of just 'k'";
filter_k=Integer.parseInt(b);
}else if(a.equals("filterk")){
filter_k=Integer.parseInt(b);
}else if(a.equals("trimk")){
trim_k=Integer.parseInt(b);
}else if(a.equals("mapk")){
map_k=Integer.parseInt(b);
}else if(a.equals("normalizek") || a.equals("normk") || a.equals("ecck")){
normalize_k=Integer.parseInt(b);
}else if(a.equals("filterhdist")){
hdist_filter=Integer.parseInt(b);
}else if(a.equals("spikeink")){
spikein_k=Integer.parseInt(b);
}else if(a.equals("spikeinhdist")){
hdist_spikein=Integer.parseInt(b);
}else if(a.equals("filterqhdist")){
qhdist_filter=Integer.parseInt(b);
}else if(a.equals("trimhdist")){
hdist_trim=Integer.parseInt(b);
}else if(a.equals("trimhdist2")){
hdist2_trim=Integer.parseInt(b);
}else if(a.equals("ribohdist")){
hdist_ribo=Integer.parseInt(b);
}else if(a.equals("riboedist") || a.equals("riboedits")){
edist_ribo=Integer.parseInt(b);
}else if(a.equals("maq")){
assert(b!=null) : "Bad parameter: "+arg;
if(b.indexOf(',')>-1){
String[] x=b.split(",");
assert(x.length==2) : "maq should be length 1 or 2 (at most 1 comma).\nFormat: maq=quality,bases; e.g. maq=10 or maq=10,20";
minAvgQuality=Byte.parseByte(x[0]);
minAvgQualityBases=Integer.parseInt(x[1]);
}else{
minAvgQuality=Byte.parseByte(b);
}
}else if(a.equals("forcetrimmod") || a.equals("forcemrimmodulo") || a.equals("ftm")){
forceTrimModulo=Integer.parseInt(b);
}else if(a.equals("trimq")){
trimq=Byte.parseByte(b);
}else if(a.equals("qtrim")){
if(b==null){qtrim="r";}
else if(b.equalsIgnoreCase("left") || b.equalsIgnoreCase("l")){qtrim="l";qtrimFlag=true;}
else if(b.equalsIgnoreCase("right") || b.equalsIgnoreCase("r")){qtrim="r";qtrimFlag=true;}
else if(b.equalsIgnoreCase("both") || b.equalsIgnoreCase("rl") || b.equalsIgnoreCase("lr")){qtrim="lr";qtrimFlag=true;}
else if(Tools.isDigit(b.charAt(0))){
trimq=Byte.parseByte(b);
qtrimFlag=(trimq>=0);
qtrim=(qtrimFlag ? "lr" : "f");
}else{
qtrimFlag=Tools.parseBoolean(b);
qtrim=""+qtrimFlag;
}
}else if(a.equals("optitrim") || a.equals("otf") || a.equals("otm")){
if(b!=null && (b.charAt(0)=='.' || Tools.isDigit(b.charAt(0)))){
TrimRead.optimalMode=true;
TrimRead.optimalBias=Float.parseFloat(b);
assert(TrimRead.optimalBias>=0 && TrimRead.optimalBias<1);
}else{
TrimRead.optimalMode=Tools.parseBoolean(b);
}
}else if(a.equals("maxns")){
maxNs=Integer.parseInt(b);
}else if(a.equals("usetmpdir")){
writeTempToTmpdir=Tools.parseBoolean(b);
}else if(a.equals("tmpdir")){
tmpDir=b;
writeTempToTmpdir=(b!=null);
}else if(a.equals("delete") || a.equals("deletetemp")){
deleteTemp=Tools.parseBoolean(b);
}else if(a.equals("humanpath")){
humanPath=b;
}else if(a.equals("catpath")){
catPath=b;
}else if(a.equals("dogpath")){
dogPath=b;
}else if(a.equals("mousepath")){
dogPath=b;
}else if(a.equalsIgnoreCase("mouseCatDogHumanPath")){
mouseCatDogHumanPath=b;
}else if(a.equals("mapref") || a.equals("maprefs")){
if(b==null){mappingRefs.clear();}
else{
for(String s : b.split(",")){
mappingRefs.add(s);
}
}
}else if(a.equals("chastityfilter") || a.equals("cf") || a.equals("chastity")){
chastityfilter=b;
}else if(a.equals("failnobarcode")){
failnobarcode=b;
}else if(a.equals("badbarcodes") || a.equals("barcodefilter")){
barcodefilter=b;
}else if(a.equals("barcodes") || a.equals("barcode")){
barcodes=b;
}else if(a.equals("extend")){
extendFlag=Tools.parseBoolean(b);
extendFlagAuto=false;
}else if(a.equals("extendauto")){
extendFlagAuto=Tools.parseBoolean(b);
}else if(a.equals("taxlist") || a.equals("tax") || a.equals("taxa") || a.equals("taxid")){
taxList=b;
}else if(a.equals("taxtree") || a.equals("tree")){
taxTreeFile=b;
}else if(a.equals("loadgitable")){
loadGiTable=Tools.parseBoolean(b);
}else if(a.equals("gitable")){
giTable=b;
loadGiTable=(b!=null);
}else if(a.equals("taxlevel") || a.equals("level")){
taxLevel=b;
}else if(a.equals("microberef")){
commonMicrobesRef=b;
}else if(a.equals("microbepath")){
commonMicrobesPath=b;
}else if(a.equals("microbebuild")){
commonMicrobesBuild=Integer.parseInt(b);
}else if(a.equals("ordered")){
ordered=Tools.parseBoolean(b);
}
else if(a.equals("sketch")){
sketchFlag=Tools.parseBoolean(b);
}else if(a.equals("silvalocal") || a.equals("localsilva")){
SILVA_LOCAL=Tools.parseBoolean(b);
}else if(a.equals("sketchdb") || a.equals("sketchserver")){
sketchDB=b;
}else if(a.equals("sketchreads")){
sketchReads=Integer.parseInt(b);
}else if(a.equals("sketchsamplerate")){
sketchSamplerate=b;
assert(b!=null);
}else if(a.equals("sketchminprob")){
sketchMinProb=b;
assert(b!=null);
}
else if(a.equals("clump") || a.equals("clumpify")){
doClump=Tools.parseBoolean(b);
}else if(a.equals("fbt") || a.equals("filterbytile")){
doFilterByTile=Tools.parseBoolean(b);
}else if(a.equals("dedupe")){
removeDuplicates=Tools.parseBoolean(b);
}else if(a.equals("alldupes")){
removeAllDuplicates=Tools.parseBoolean(b);
}else if(a.equals("opticaldupes") || a.equals("optical")){
removeOpticalDuplicates=Tools.parseBoolean(b);
}else if(a.equals("edgedupes")){
removeEdgeDuplicates=Tools.parseBoolean(b);
}else if(a.equals("dpasses")){
duplicatePasses=Integer.parseInt(b);
}else if(a.equals("dsubs")){
duplicateSubs=Integer.parseInt(b);
}else if(a.equals("ddist")){
duplicateDist=Integer.parseInt(b);
}else if(a.equals("lowcomplexity")){
lowComplexity=Tools.parseBoolean(b);
}else if(a.equals("clumpifygroups") || a.equals("groups")){
clumpifyGroups=Integer.parseInt(b);
}else if(a.equals("clumpifytmpdir")){
clumpifyTmpdir=Tools.parseBoolean(b);
}
else if(a.equals("entropy") || a.equals("efilter") || a.equals("minentropy") || a.equals("entropyfilter")){
if(b==null){entropyFilter=true;}
else if(Tools.isLetter(b.charAt(0))){
entropyFilter=Tools.parseBoolean(b);
}else{
minEntropy=Double.parseDouble(b);
entropyFilter=minEntropy>0;
}
}else if(a.equals("entropyk")){
entropyk=Integer.parseInt(b);
}else if(a.equals("entropywindow")){
entropywindow=Integer.parseInt(b);
}
else if(a.equalsIgnoreCase("RQCFilterData") || a.equalsIgnoreCase("RQCFilterPath") || a.equalsIgnoreCase("data") || a.equalsIgnoreCase("datapath")){
RQCFilterData=b;
}
else if(a.equals("discoveradapters") || a.equals("findadapters") || a.equals("detectadapters")){
discoverAdaptersFlag=Tools.parseBoolean(b);
}
else if(a.equals("bloomfilter") || a.equals("bloom")){
bloomFilter=Tools.parseBoolean(b);
}else if(a.equals("bloomk") || a.equals("bloomfilterk")){
bloomFilterK=Integer.parseInt(b);
}else if(a.equals("bloomhashes") || a.equals("bloomfilterhashes")){
bloomFilterHashes=Integer.parseInt(b);
}else if(a.equals("bloomminhits") || a.equals("bloomfilterminhits")){
bloomFilterMinHits=Integer.parseInt(b);
}else if(a.equals("bloomfilterminreads") || a.equals("bloomminreads")){
minReadsToBloomFilter=Tools.parseKMG(b);
}else if(a.equals("bloomserial") || a.equals("serialbloom")){
bloomSerial=Tools.parseBoolean(b);
}
else if(a.equals("dryrun")){
dryrun=Tools.parseBoolean(b);
}
else if(a.equals("skipfilter")){
skipFilter=Tools.parseBoolean(b);
}
//These no longer do anything
else if(a.equals("dna")){
dnaArtifactFlag=Tools.parseBoolean(b);
}else if(a.equals("rna")){
rnaArtifactFlag=Tools.parseBoolean(b);
dnaArtifactFlag=!rnaArtifactFlag; //This line requested by Bryce.
}
else{
//Uncaptured arguments are passed to BBDuk
primaryArgList.add(arg);
}
}
{
if(RQCFilterData==null){RQCFilterData=".";}
File f=new File(RQCFilterData);
assert(f.exists() && f.isDirectory()) : "RQCFilterData path is not set correctly.";
fixReferencePaths();
}
if("auto".equalsIgnoreCase(taxTreeFile)){taxTreeFile=TaxTree.defaultTreeFile();}
//Maintain clumpified order in later stages
if(doClump){ordered=true;}
doNexteraLMP=doNextera_;
if(removeCommonMicrobeFlag && detectMicrobeFlag){detectMicrobeFlag=false;}
// assert(false) : rnaArtifactFlag+"\n"+primaryArgList+"\n"+libType+"\n"+outDir;
if(writeTempToTmpdir){
if(tmpDir==null){tmpDir=Shared.tmpdir();}
if(tmpDir!=null){
tmpDir=tmpDir.replace('\\', '/');
if(tmpDir.length()>0 && !tmpDir.endsWith("/")){tmpDir+="/";}
}
}else{tmpDir=null;}
if(hdist2_trim<0){hdist2_trim=hdist_trim;}
//Pass overwrite flag to BBDuk
primaryArgList.add("ow="+overwrite);
if(outDir!=null){
outDir=outDir.trim().replace('\\', '/');
if(outDir.length()>0 && !outDir.endsWith("/")){outDir=outDir+"/";}
}else{outDir="";}
//TODO: Unify Name or File
{//Prepend output directory to output files
logName=appendOutDir(logName);
reproduceName=appendOutDir(reproduceName);
fileListName=appendOutDir(fileListName);
ihistName=appendOutDir(ihistName);
khistName=appendOutDir(khistName);
peaksName=appendOutDir(peaksName);
riboOutFile=appendOutDir(riboOutFile);
fbtOutFile=appendOutDir(fbtOutFile);
chloroOutFile=appendOutDir(chloroOutFile);
humanOutFile=appendOutDir(humanOutFile);
spikeinOutFile=appendOutDir(spikeinOutFile);
synthOutFile1=appendOutDir(synthOutFile1);
synthOutFile2=appendOutDir(synthOutFile2);
microbeOutFile=appendOutDir(microbeOutFile);
microbeStatsFile=appendOutDir(microbeStatsFile);
microbesUsed=appendOutDir(microbesUsed);
chloroStatsFile=appendOutDir(chloroStatsFile);
cardinalityName=appendOutDir(cardinalityName);
adaptersOutFile=appendOutDir(adaptersOutFile);
phistName=appendOutDir(phistName);
qhistName=appendOutDir(qhistName);
bhistName=appendOutDir(bhistName);
gchistName=appendOutDir(gchistName);
}
{//Create unique output file names for first and second trimming passes
if(rqcStatsName2!=null){
rqcStatsName2=appendOutDir(rqcStatsName2);
}
if(rqcStatsName!=null){
rqcStatsName_kt=appendOutDir("ktrim_"+rqcStatsName);
rqcStatsName=appendOutDir(rqcStatsName);
}
if(kmerStatsName1!=null){
kmerStatsName_kt=appendOutDir("ktrim_"+kmerStatsName1);
kmerStatsName1=appendOutDir(kmerStatsName1);
}
if(kmerStatsName2!=null){
kmerStatsName2=appendOutDir(kmerStatsName2);
}
if(scaffoldStatsNameSpikein!=null){
scaffoldStatsNameSpikein=appendOutDir(scaffoldStatsNameSpikein);
}
if(scaffoldStatsName1!=null){
scaffoldStatsName_kt=appendOutDir("ktrim_"+scaffoldStatsName1);
scaffoldStatsName1=appendOutDir(scaffoldStatsName1);
}
if(scaffoldStatsName2!=null){
scaffoldStatsName2=appendOutDir(scaffoldStatsName2);
}
if(refStatsName!=null){
refStatsName=appendOutDir(refStatsName);
}
}
doSpikein=(mtstFlag || kapaFlag || !spikeinRefs.isEmpty());
//Determine execution path
//This may be obsolete now
if(libType==FRAG || ((libType==LFPE && lfpeLinker==null) || (libType==CLIP && clipLinker==null) || (libType==CLRS && clrsLinker==null))){
doAdapterTrim=(fragAdapterFlag || rnaAdapterFlag);
doFilter=!skipFilter;
}else if(libType==LFPE){
doAdapterTrim=true;
doFilter=!skipFilter;
}else if(libType==CLIP){
doAdapterTrim=true;
doFilter=!skipFilter;
}else if(libType==CLRS){
doAdapterTrim=true;
doFilter=!skipFilter;
}else{
throw new RuntimeException("Unknown library type.");
}
//Use combined index if all organisms are specified (common case)
if(catFlag && dogFlag && humanFlag && mouseFlag){
mouseCatDogHumanFlag=true;
}
//Turn off individual flags if a combined flag is used
if(mouseCatDogHumanFlag){
mouseFlag=false;
catFlag=false;
dogFlag=false;
humanFlag=false;
}
if(dogFlag){mappingRefs.add("path="+dogPath);}
if(catFlag){mappingRefs.add("path="+catPath);}
if(mouseFlag){mappingRefs.add("path="+mousePath);}
if(!doMerge_){ihistName=null;}
doMerge=(ihistName!=null);
//Set final field 'symbols'
//This is for those magic letters in the filename
symbols=(symbols_==null ? abbreviation() : symbols_);
assert(in1!=null) : "No input file specified.";
in1=Tools.fixExtension(in1);
in2=Tools.fixExtension(in2);
//Create output filename from input filename if no output filename is specified
if(out1==null){
File f=new File(in1);
String name=f.getName();
rawName=ReadWrite.rawName(name);
int dot=rawName.lastIndexOf('.');
if(dot>-1){
out1=rawName.substring(0, dot)+"."+symbols+rawName.substring(dot)+(compress ? ".gz" : "");
}else{
out1=rawName+"."+symbols+".fastq"+(compress ? ".gz" : "");
}
}else{
File f=new File(out1);
String name=f.getName();
rawName=ReadWrite.rawName(name);
}
//Ensure temp files have random names
tempSalt=KmerNormalize.getSalt(out1, 1);
clumpPrefix="TEMP_CLUMP_"+tempSalt+"_";
fbtPrefix="TEMP_FBT_"+tempSalt+"_";
trimPrefix="TEMP_TRIM_"+tempSalt+"_";
humanPrefix="TEMP_HUMAN_"+tempSalt+"_";
spikeinPrefix="TEMP_SPIKEIN_"+tempSalt+"_";
filterPrefix1="TEMP_FILTER1_"+tempSalt+"_";
filterPrefix2="TEMP_FILTER2_"+tempSalt+"_";
taxaPrefix="TEMP_TAXA_"+tempSalt+"_";
microbePrefix="TEMP_MICROBE_"+tempSalt+"_";
riboPrefix="TEMP_RIBO_"+tempSalt+"_";
chloroPrefix="TEMP_CHLORO_"+tempSalt+"_";
if(mappingRefs.size()>0){
mappingPrefix=new String[mappingRefs.size()];
for(int i=0; i<mappingRefs.size(); i++){
mappingPrefix[i]="TEMP_MAP_"+tempSalt+"_"+i+"_";
}
}else{
mappingPrefix=null;
}
if(reproduceName!=null){
writeReproduceHeader(reproduceName, args, overwrite);
}
}
private String appendOutDir(String s){
if(s==null){return null;}
if(s.startsWith(outDir)){return s;}
return outDir+s;
}
private String removeOutDir(String s){
if(s==null){return null;}
if(outDir==null || outDir.length()==0){return s;}
if(s.startsWith(outDir)){return s.substring(outDir.length());}
return s;
}
/*--------------------------------------------------------------*/
/*---------------- Processing Methods ----------------*/
/*--------------------------------------------------------------*/
/**
* Primary method to fully execute the program.
*/
public void process(){
//Create output directory
if(outDir!=null && outDir.length()>0){
File f=new File(outDir);
if(!f.exists()){
f.mkdirs();
}
}
//Create log file
if(logName!=null){
boolean b=Tools.canWrite(logName, overwrite);
assert(b) : "Can't write to "+logName;
log("bbtools filter start", false);
}
//Create file list file
if(fileListName!=null){
boolean b=Tools.canWrite(fileListName, overwrite);
assert(b) : "Can't write to "+fileListName;
StringBuilder sb=new StringBuilder();
if(!doNexteraLMP){
if(out1!=null){sb.append("filtered_fastq="+out1).append('\n');}
if(out2!=null){sb.append("filtered_fastq_2="+out2).append('\n');}
}
String x=(outDir==null ? "" : outDir);
int xlen=x.length();
//Determine whether to append the output directory prefix in each case
if(ihistName!=null){
sb.append("ihist="+removeOutDir(ihistName)).append('\n');
}
if(doKhist){
if(khistName!=null){
sb.append("khist="+removeOutDir(khistName)).append('\n');
}
if(peaksName!=null){
sb.append("peaks="+removeOutDir(peaksName)).append('\n');
}
}
if(scaffoldStatsNameSpikein!=null && doSpikein){
sb.append("spikeinstats="+removeOutDir(scaffoldStatsNameSpikein)).append('\n');
}
if(scaffoldStatsName1!=null){
sb.append("scafstats1="+removeOutDir(scaffoldStatsName1)).append('\n');
}
if(scaffoldStatsName2!=null){
sb.append("scafstats2="+removeOutDir(scaffoldStatsName2)).append('\n');
}
if(refStatsName!=null){
sb.append("refstats="+removeOutDir(refStatsName)).append('\n');
}
if(riboKmerFlag && riboOutFile!=null){
sb.append("ribo="+removeOutDir(riboOutFile)).append('\n');
}
if(doFilterByTile && fbtOutFile!=null){
sb.append("filteredByTile="+removeOutDir(fbtOutFile)).append('\n');
}
if((chloroMapFlag || mitoMapFlag || riboMapFlag) && chloroOutFile!=null){
sb.append("="+removeOutDir(chloroOutFile)).append('\n');
}
if((chloroMapFlag || mitoMapFlag || riboMapFlag) && chloroStatsFile!=null){
sb.append("="+removeOutDir(chloroStatsFile)).append('\n');
}
if(removeCommonMicrobeFlag && microbeOutFile!=null){
sb.append("chaffMicrobeReads="+removeOutDir(microbeOutFile)).append('\n');
sb.append("microbeStats="+removeOutDir(microbeStatsFile)).append('\n');
}else if(detectMicrobeFlag && microbeStatsFile!=null){
sb.append("microbeStats="+removeOutDir(microbeStatsFile)).append('\n');
}
if(removeCommonMicrobeFlag && microbesUsed!=null){
sb.append("microbesUsed="+removeOutDir(microbesUsed)).append('\n');
}
if(otherMicrobeFlag && microbeStats2File!=null){
sb.append("microbeStats2="+removeOutDir(microbeStats2File)).append('\n');
}
if(discoverAdaptersFlag && adaptersOutFile!=null){
sb.append("adaptersDetected="+removeOutDir(adaptersOutFile)).append('\n');
}
if(doFilter && synthOutFile1!=null){
sb.append("chaffSynthReads1="+removeOutDir(synthOutFile1)).append('\n');
}
if(doFilter && synthOutFile2!=null){
sb.append("chaffSynthReads2="+removeOutDir(synthOutFile2)).append('\n');
}
if((humanFlag || mouseCatDogHumanFlag) && humanOutFile!=null){
sb.append("chaffHumanReads="+removeOutDir(humanOutFile)).append('\n');
}
if(sketchFlag && sketchName!=null){
sb.append("sketchResult="+removeOutDir(sketchName)).append('\n');
}
if(doAdapterTrim){
if(phistName!=null){
sb.append("polymerHist="+removeOutDir(phistName)).append('\n');
}
if(qhistName!=null){
sb.append("qualityHist="+removeOutDir(qhistName)).append('\n');
}
if(bhistName!=null){
sb.append("baseFrequencyHist="+removeOutDir(bhistName)).append('\n');
}
if(gchistName!=null){
sb.append("GCHist="+removeOutDir(gchistName)).append('\n');
}
}
if(sb.length()>0){
ReadWrite.writeString(sb, fileListName, false);
}
}
long lastReadsObserved=-1;
{
//Sketching has to be done first because after Clumpify, the entire file would need to be processed,
//rather than just the first X reads
if(sketchFlag){
boolean success=runSketch(in1, sketchName, null);
}
//Calculate number of total steps, to determine when to write to the output directory versus localdisk.
int step=0;
final int numSteps=(doClump ? 1 : 0)+(doFilterByTile ? 1 : 0)+(doSpikein ? 1 : 0)+(doFilter ? 2 : 0)+(doAdapterTrim ? 1 : 0)+(doNexteraLMP ? 1 : 0)+(riboKmerFlag ? 1 : 0)+
((chloroMapFlag || mitoMapFlag || riboMapFlag) ? 1 : 0)+
(removeCommonMicrobeFlag ? 1 : 0)+((humanFlag || mouseCatDogHumanFlag) ? 1 : 0)+mappingRefs.size();
String inPrefix=null, outPrefix=null;
if(discoverAdaptersFlag){
discoverAdapters(in1, in2, adaptersOutFile);
}
//Clumpification
if(doClump){
step++;
inPrefix=outPrefix;
outPrefix=(step<numSteps ? clumpPrefix : null);
// outstream.println("Clump. step="+step+", in="+in1+", out="+out1+", inPrefix="+inPrefix+", outPrefix="+outPrefix);
final String in1z, in2z, out1z, out2z;
if(step==1){
in1z=in1; in2z=in2;
}else{
in1z=stripDirs(out1); in2z=stripDirs(out2);
}
if(step>=numSteps){
ReadWrite.ZIPLEVEL=Tools.max(ReadWrite.ZIPLEVEL, 9);
out1z=out1; out2z=out2;
}else{
ReadWrite.ZIPLEVEL=Tools.min(ReadWrite.ZIPLEVEL, 4);
out1z=stripDirs(out1); out2z=stripDirs(out2);
}
//in1z=bar.fq
//out1z=bar.fq
//inPrefix=TEMP_SKETCH_123455y546
//outPrefix=TEMP_CLUMP_123455y546
clumpify(in1z, in2z, out1z, out2z, inPrefix, outPrefix, step);
lastReadsObserved=KmerSort.lastReadsOut;
if(in2!=null && out2==null){
FASTQ.FORCE_INTERLEAVED=true;
FASTQ.TEST_INTERLEAVED=false;
}
if(inPrefix!=null){
delete(inPrefix, out1z, out2z);//Why is this out, not in?
}
FASTQ.ASCII_OFFSET=33;
FASTQ.DETECT_QUALITY=false;
}
//FilterByTile (Illumina only)
if(doFilterByTile){
step++;
if(dryrun || lastReadsObserved<0 || lastReadsObserved>=400000){
inPrefix=outPrefix;
outPrefix=(step<numSteps ? fbtPrefix : null);
final String in1z, in2z, out1z, out2z;
if(step==1){
in1z=in1; in2z=in2;
}else{
in1z=stripDirs(out1); in2z=stripDirs(out2);
}
if(step>=numSteps){
ReadWrite.ZIPLEVEL=Tools.max(ReadWrite.ZIPLEVEL, 9);
out1z=out1; out2z=out2;
}else{
ReadWrite.ZIPLEVEL=Tools.min(ReadWrite.ZIPLEVEL, 4);
out1z=stripDirs(out1); out2z=stripDirs(out2);
}
filterByTile(in1z, in2z, out1z, out2z, fbtOutFile, inPrefix, outPrefix, step);
lastReadsObserved=AnalyzeFlowCell.lastReadsOut;
if(in2!=null && out2==null){
FASTQ.FORCE_INTERLEAVED=true;
FASTQ.TEST_INTERLEAVED=false;
}
if(inPrefix!=null){
delete(inPrefix, out1z, out2z);//Why is this out, not in?
}
FASTQ.ASCII_OFFSET=33;
FASTQ.DETECT_QUALITY=false;
}
}
//Adapter trimming
if(doAdapterTrim){
step++;
inPrefix=outPrefix;
outPrefix=(step<numSteps ? trimPrefix : null);
// outstream.println("Trim. step="+step+", in="+in1+", out="+out1+", inPrefix="+inPrefix+", outPrefix="+outPrefix);
final String in1z, in2z, out1z, out2z;
if(step==1){
in1z=in1; in2z=in2;
}else{
in1z=stripDirs(out1); in2z=stripDirs(out2);
}
if(step>=numSteps){
ReadWrite.ZIPLEVEL=Tools.max(ReadWrite.ZIPLEVEL, 9);
out1z=out1; out2z=out2;
}else{
ReadWrite.ZIPLEVEL=Tools.min(ReadWrite.ZIPLEVEL, 4);
out1z=stripDirs(out1); out2z=stripDirs(out2);
}
ktrim(in1z, in2z, out1z, out2z, inPrefix, outPrefix, step);
lastReadsObserved=BBDukF.lastReadsOut;
ReadWrite.ZIPLEVEL=Tools.max(ReadWrite.ZIPLEVEL, 6);
//TODO: This junk can go in a function
if(in2!=null && out2==null){
FASTQ.FORCE_INTERLEAVED=true;
FASTQ.TEST_INTERLEAVED=false;
}
if(inPrefix!=null){
delete(inPrefix, out1z, out2z);
}
FASTQ.ASCII_OFFSET=33;
FASTQ.DETECT_QUALITY=false;
}
//Spikein filtering
if(doSpikein){
step++;
inPrefix=outPrefix;
outPrefix=(step<numSteps ? spikeinPrefix : null);
// outstream.println("Filter. step="+step+", in="+in1+", out="+out1+", inPrefix="+inPrefix+", outPrefix="+outPrefix);
final String in1z, in2z, out1z, out2z;
if(step==1){
in1z=in1; in2z=in2;
}else{
in1z=stripDirs(out1); in2z=stripDirs(out2);
}
if(step>=numSteps){
ReadWrite.ZIPLEVEL=Tools.max(ReadWrite.ZIPLEVEL, 9);
out1z=out1; out2z=out2;
}else{
out1z=stripDirs(out1); out2z=stripDirs(out2);
}
filterSpikein(in1z, in2z, out1z, out2z, spikeinOutFile, inPrefix, outPrefix, step);
lastReadsObserved=Seal.lastReadsOut;
if(in2!=null && out2==null){
FASTQ.FORCE_INTERLEAVED=true;
FASTQ.TEST_INTERLEAVED=false;
}
if(step>1){
delete(inPrefix, out1z, out2z);
}
}
//Synthetic contaminant filtering
if(doFilter){
step++;
inPrefix=outPrefix;
outPrefix=(step<numSteps ? filterPrefix1 : null);
// outstream.println("Filter. step="+step+", in="+in1+", out="+out1+", inPrefix="+inPrefix+", outPrefix="+outPrefix);
final String in1z, in2z, out1z, out2z;
if(step==1){
in1z=in1; in2z=in2;
}else{
in1z=stripDirs(out1); in2z=stripDirs(out2);
}
if(step>=numSteps){
ReadWrite.ZIPLEVEL=Tools.max(ReadWrite.ZIPLEVEL, 9);
out1z=out1; out2z=out2;
}else{
out1z=stripDirs(out1); out2z=stripDirs(out2);
}
filter1(in1z, in2z, out1z, out2z, synthOutFile1, inPrefix, outPrefix, step);
lastReadsObserved=BBDukF.lastReadsOut;
if(in2!=null && out2==null){
FASTQ.FORCE_INTERLEAVED=true;
FASTQ.TEST_INTERLEAVED=false;
}
if(step>1){
delete(inPrefix, out1z, out2z);
}
}
//Short synthetic contaminant filtering
if(doFilter){
step++;
inPrefix=outPrefix;
outPrefix=(step<numSteps ? filterPrefix2 : null);
// outstream.println("Filter. step="+step+", in="+in1+", out="+out1+", inPrefix="+inPrefix+", outPrefix="+outPrefix);
final String in1z, in2z, out1z, out2z;
if(step==1){
in1z=in1; in2z=in2;
}else{
in1z=stripDirs(out1); in2z=stripDirs(out2);
}
if(step>=numSteps){
ReadWrite.ZIPLEVEL=Tools.max(ReadWrite.ZIPLEVEL, 9);
out1z=out1; out2z=out2;
}else{
out1z=stripDirs(out1); out2z=stripDirs(out2);
}
filter2(in1z, in2z, out1z, out2z, synthOutFile2, inPrefix, outPrefix, step);
lastReadsObserved=BBDukF.lastReadsOut;
if(in2!=null && out2==null){
FASTQ.FORCE_INTERLEAVED=true;
FASTQ.TEST_INTERLEAVED=false;
}
if(step>1){
delete(inPrefix, out1z, out2z);
}
}
//Non-specific ribosomal RNA removal via kmers
if(riboKmerFlag){
step++;
inPrefix=outPrefix;
outPrefix=(step<numSteps ? riboPrefix : null);
// outstream.println("Filter. step="+step+", in="+in1+", out="+out1+", inPrefix="+inPrefix+", outPrefix="+outPrefix);
final String in1z, in2z, out1z, out2z;
if(step==1){
in1z=in1; in2z=in2;
}else{
in1z=stripDirs(out1); in2z=stripDirs(out2);
}
if(step>=numSteps){
ReadWrite.ZIPLEVEL=Tools.max(ReadWrite.ZIPLEVEL, 9);
out1z=out1; out2z=out2;
}else{
out1z=stripDirs(out1); out2z=stripDirs(out2);
}
filterRibo(in1z, in2z, out1z, out2z, riboOutFile, inPrefix, outPrefix, step);
lastReadsObserved=BBDukF.lastReadsOut;
if(in2!=null && out2==null){
FASTQ.FORCE_INTERLEAVED=true;
FASTQ.TEST_INTERLEAVED=false;
}
if(step>1){
delete(inPrefix, out1z, out2z);
}
}
if(detectMicrobeFlag){
// assert(false) : inPrefix+", "+outPrefix+", "+in1+", "+out1;
inPrefix=outPrefix;
final String in1z, in2z;
if(step==1){
in1z=in1; in2z=in2;
}else if(step<numSteps){
in1z=stripDirs(out1); in2z=stripDirs(out2);
}else{
inPrefix=null;
in1z=outDir+stripDirs(out1);
in2z=(out2==null ? null : outDir+stripDirs(out2));
}
String ref=commonMicrobesRef;//taxFilter(commonMicrobesRef, "taxa.fa.gz", false, false, true, overwrite, false);
// assert(false) : in1z+" , "+inPrefix;
detectCommonMicrobes(in1z, in2z, microbeStatsFile, inPrefix, ref, aggressiveMicrobeFlag, commonMicrobesBuild, commonMicrobesRef, commonMicrobesPath);
}
//Microbial contaminant removal
if(removeCommonMicrobeFlag){
step++;
inPrefix=outPrefix;
outPrefix=(step<numSteps ? microbePrefix : null);
// outstream.println("Filter. step="+step+", in="+in1+", out="+out1+", inPrefix="+inPrefix+", outPrefix="+outPrefix);
final String in1z, in2z, out1z, out2z;
if(step==1){
in1z=in1; in2z=in2;
}else{
in1z=stripDirs(out1); in2z=stripDirs(out2);
}
if(step>=numSteps){
ReadWrite.ZIPLEVEL=Tools.max(ReadWrite.ZIPLEVEL, 9);
out1z=out1; out2z=out2;
}else{
out1z=stripDirs(out1); out2z=stripDirs(out2);
}
String ref=taxFilter(commonMicrobesRef, "taxa.fa.gz", microbesUsed, taxLevel, false, false, true, overwrite, false);
// outstream.println("in1z="+in1z+"\nout1z="+out1z+"\ninPrefix="+inPrefix+"\noutPrefix="+outPrefix);
{//Microbial removal uses a kmer length of 13 for seeding
int oldMapK=map_k;
map_k=13;
removeCommonMicrobes(in1z, in2z, out1z, out2z, microbeOutFile, microbeStatsFile, inPrefix, outPrefix, ref, step, aggressiveMicrobeFlag);
map_k=oldMapK;
}
if(in2!=null && out2==null){
FASTQ.FORCE_INTERLEAVED=true;
FASTQ.TEST_INTERLEAVED=false;
}
if(step>1){
delete(inPrefix, out1z, out2z);
}
}
if(otherMicrobeFlag){
// assert(false) : inPrefix+", "+outPrefix+", "+in1+", "+out1;
inPrefix=outPrefix;
final String in1z, in2z;
if(step==1){
in1z=in1; in2z=in2;
}else if(step<numSteps){
in1z=stripDirs(out1); in2z=stripDirs(out2);
}else{
inPrefix=null;
in1z=outDir+stripDirs(out1);
in2z=(out2==null ? null : outDir+stripDirs(out2));
}
String ref=otherMicrobesRef;//taxFilter(commonMicrobesRef, "taxa.fa.gz", false, false, true, overwrite, false);
// assert(false) : in1z+" , "+inPrefix;
detectCommonMicrobes(in1z, in2z, microbeStats2File, inPrefix, ref, aggressiveMicrobeFlag, otherMicrobesBuild, otherMicrobesRef, otherMicrobesPath);
}
//Organism-specific chloroplast, mito, and ribo contaminant removal via mapping
//TODO: Describe ref construction
if(chloroMapFlag || mitoMapFlag || riboMapFlag){
step++;
inPrefix=outPrefix;
outPrefix=(step<numSteps ? chloroPrefix : null);
// outstream.println("Filter. step="+step+", in="+in1+", out="+out1+", inPrefix="+inPrefix+", outPrefix="+outPrefix);
final String in1z, in2z, out1z, out2z;
if(step==1){
in1z=in1; in2z=in2;
}else{
in1z=stripDirs(out1); in2z=stripDirs(out2);
}
if(step>=numSteps){
ReadWrite.ZIPLEVEL=Tools.max(ReadWrite.ZIPLEVEL, 9);
out1z=out1; out2z=out2;
}else{
out1z=stripDirs(out1); out2z=stripDirs(out2);
}
//Disable chloroMapFlag if the organism is not a plant
if(chloroMapFlag && taxList!=null){
boolean foundPlant=false;
TaxTree tree=TaxTree.loadTaxTree(taxTreeFile, outstream, true, false);
TaxNode plant=tree.getNodeByName("Viridiplantae");//Name of plant kingdom
for(String s : taxList.split(",")){
TaxNode tn=tree.parseNodeFromHeader(s, true);
if(tn!=null && (tree.commonAncestor(plant, tn)==plant || tree.commonAncestor(plant, tn)==tn)){
foundPlant=true;
break;
}
}
if(!foundPlant){
outstream.println("Disabled chloroMapFlag because organism is not a plant.");
chloroMapFlag=false;
}
}
//A file containing relevant sequences from all available organisms
final String ref0;
if(chloroMapFlag){
if(mitoMapFlag && riboMapFlag){ref0=chloroMitoRiboRef;}
else if(mitoMapFlag){ref0=chloroMitoRef;}
else if(riboMapFlag){ref0=chloroRiboRef;}
else{ref0=chloroplastRef;}
}else if(mitoMapFlag){
if(riboMapFlag){ref0=mitoRiboRef;}
else{ref0=mitoRef;}
}else{
ref0=riboRef;
}
// String ref=taxFilter(ref0, "chloroMitoRiboRef.fa.gz", true);
//Filter the file to only include specified organisms in the taxlist.
String ref;
{//TODO: Work on this
ArrayList<String> refList=new ArrayList<String>(3);
if(chloroMapFlag){refList.add(chloroplastRef);}
if(mitoMapFlag){refList.add(mitoRef);}
if(riboMapFlag){refList.add(riboRef);}
ref=taxFilterList(refList, "chloroMitoRiboRef.fa.gz", true, true, "species");
if(ref!=null){
File f=new File(ref);
if(!f.exists() || f.length()<200){
outstream.println("Can't find chloroplast/mito/ribo for taxa; using full dataset.");
ref=ref0;
}
}else{ref=ref0;}
}
{
final boolean addToOtherStats=(chloroStatsFile==null);
decontamByMapping(in1z, in2z, out1z, out2z, chloroOutFile, chloroStatsFile, inPrefix, outPrefix, ref, step, addToOtherStats);
if(!addToOtherStats){
filterstats.parseChloro(chloroStatsFile);
assert(filterstats.toString()!=null); //Must be here due to an ordering issue with checking
}
}
//Delete the reference if it was just created.
//TODO: Maybe this should be retained
if(!ref0.equals(ref)){
delete(null, ref);
}
if(in2!=null && out2==null){
FASTQ.FORCE_INTERLEAVED=true;
FASTQ.TEST_INTERLEAVED=false;
}
if(step>1){
delete(inPrefix, out1z, out2z);
}
}
//Human, cat, dog, and mouse removal
if(humanFlag || mouseCatDogHumanFlag){
step++;
inPrefix=outPrefix;
outPrefix=(step<numSteps ? humanPrefix : null);
// outstream.println("Human. step="+step+", in="+in1+", out="+out1+", inPrefix="+inPrefix+", outPrefix="+outPrefix);
final String in1z, in2z, out1z, out2z;
if(step==1){
in1z=in1; in2z=in2;
}else{
in1z=stripDirs(out1); in2z=stripDirs(out2);
}
if(step>=numSteps){
ReadWrite.ZIPLEVEL=Tools.max(ReadWrite.ZIPLEVEL, 9);
out1z=out1; out2z=out2;
}else{
out1z=stripDirs(out1); out2z=stripDirs(out2);
}
dehumanize(in1z, in2z, out1z, out2z, humanOutFile, inPrefix, outPrefix, step, mouseCatDogHumanFlag, aggressiveHumanFlag, lastReadsObserved);
if(in2!=null && out2==null){
FASTQ.FORCE_INTERLEAVED=true;
FASTQ.TEST_INTERLEAVED=false;
}
Data.unloadAll(); //TODO: See if this needs to be added to other mapping steps
if(step>1){
delete(inPrefix, out1z, out2z);
}
}
//Removal of other assorted reference sequences by mapping
//Cat, dog, and mouse individually go here
if(mappingRefs.size()>0){
for(int i=0; i<mappingRefs.size(); i++){
step++;
inPrefix=outPrefix;
outPrefix=(step<numSteps ? mappingPrefix[i] : null);
// outstream.println("Human. step="+step+", in="+in1+", out="+out1+", inPrefix="+inPrefix+", outPrefix="+outPrefix);
final String in1z, in2z, out1z, out2z;
if(step==1){
in1z=in1; in2z=in2;
}else{
in1z=stripDirs(out1); in2z=stripDirs(out2);
}
if(step>=numSteps){
ReadWrite.ZIPLEVEL=Tools.max(ReadWrite.ZIPLEVEL, 9);
out1z=out1; out2z=out2;
}else{
out1z=stripDirs(out1); out2z=stripDirs(out2);
}
decontamByMapping(in1z, in2z, out1z, out2z, null, null, inPrefix, outPrefix, mappingRefs.get(i), step, true);
if(in2!=null && out2==null){
FASTQ.FORCE_INTERLEAVED=true;
FASTQ.TEST_INTERLEAVED=false;
}
Data.unloadAll();
if(step>1){
delete(inPrefix, out1z, out2z);
}
}
}
//Nextera LMP library processing
//TODO: Rename to nexteraLMP
if(doNexteraLMP){
step++;
inPrefix=outPrefix;
outPrefix=null;
// outstream.println("Nextera. step="+step+", in="+in1+", out="+out1+", inPrefix="+inPrefix+", outPrefix="+outPrefix);
final String in1z, in2z, out1z, out2z;
if(step==1){
in1z=in1; in2z=in2;
}else{
in1z=stripDirs(out1); in2z=stripDirs(out2);
}
if(step>=numSteps){
ReadWrite.ZIPLEVEL=Tools.max(ReadWrite.ZIPLEVEL, 9);
out1z=out1; out2z=out2;
}else{
out1z=stripDirs(out1); out2z=stripDirs(out2);
}
//Insert size calculation
//In this case it has to be done before SplitNextera
if(doMerge){merge(in1z, in2z, inPrefix);}
splitNextera(in1z, in2z, inPrefix, outPrefix, step);
if(in2!=null && out2==null){
FASTQ.FORCE_INTERLEAVED=true;
FASTQ.TEST_INTERLEAVED=false;
}
Data.unloadAll();
if(step>1){
delete(inPrefix, out1z, out2z);
}
}else{
if(doMerge){//Insert size calculation
if(step==0){
merge(in1, in2, null);
}else{
merge(out1, out2, null);
}
}
if(doKhist){//TODO: This does not run in Nextera mode
if(step==0){
khist(in1, in2, null);
}else{
khist(out1, out2, null);
}
}
}
}
if(doMerge){
BBDukF.putRqc("outputReads", BBMerge.readsProcessedTotal*2, true, false);
BBDukF.putRqc("outputBases", BBMerge.basesProcessedTotal, true, false);
}
//Write combined stats file (number of reads/bases present/removed in each stage)
if(rqcStatsName!=null){
final TextStreamWriter tsw=new TextStreamWriter(rqcStatsName, overwrite, false, false);
tsw.start();
tsw.println(BBDukF.rqcString());
tsw.println("gcPolymerRatio="+String.format("%.6f", filterstats.gcPolymerRatio));
tsw.poisonAndWait();
}
//Write the new combined stats file
if(rqcStatsName2!=null){
String s=filterstats.toString();
ReadWrite.writeString(s, rqcStatsName2, false);
}
//Finish writing log file
if(logName!=null){
log("RQCFilter complete", true);
if(logName.endsWith(".tmp")){ //Remove .tmp extension
String old=logName;
logName=logName.substring(0, logName.length()-4);
new File(old).renameTo(new File(logName));
}
}
}
private boolean discoverAdapters(String in1, String in2, String outa){
log("findAdapters start", true);
ArrayList<String> argList=new ArrayList<String>();
{//Fill list with BBMerge arguments
argList.add("overwrite="+overwrite);
//Set read I/O files
if(in1!=null){argList.add("in1="+in1);}
if(in2!=null){argList.add("in2="+in2);}
if(outa!=null){argList.add("outa="+outa);}
argList.add("reads=1m");
}
String[] mergeargs=argList.toArray(new String[0]);
if(reproduceName!=null){
writeReproduceFile(reproduceName, "bbmerge.sh", mergeargs);
}
// assert(false) : ReadInputStream.toReads(outa, FileFormat.FA, -1);
boolean success=false;
if(!dryrun){//run BBMerge
final boolean OLD_FORCE_INT=FASTQ.FORCE_INTERLEAVED, OLD_TEST_INT=FASTQ.TEST_INTERLEAVED;
BBMerge merger=new BBMerge(mergeargs);
// BBMerge merger=new BBMerge(new String[] {"overwrite=true", "in1=random.fq.gz", "outa=rqc4/adaptersDetected.fa"});
// assert(false) : ReadInputStream.toReads(outa, FileFormat.FA, -1);
try {
merger.process();
FASTQ.FORCE_INTERLEAVED=OLD_FORCE_INT;//These must be reset BEFORE reading the adapters
FASTQ.TEST_INTERLEAVED=OLD_TEST_INT;
// assert(false) : ReadInputStream.toReads(outa, FileFormat.FA, -1);
long merged=merger.correctCountTotal+merger.incorrectCountTotal;
if(outa!=null && merged>=5000){
ArrayList<Read> list=ReadInputStream.toReads(outa, FileFormat.FA, -1);
if(list!=null && list.size()>=2){
success=true;
for(int rnum=0; rnum<2 && success; rnum++){
Read r=list.get(rnum);
if(r.length()<trim_k){
// assert(false) : r.length()+", "+trim_k; //123
success=false; break;
}
for(int i=0; i<trim_k && success; i++){
if(!AminoAcid.isFullyDefined(r.bases[i])){
// assert(false) : r.length()+", "+trim_k+", "+i+", "+(char)r.bases[i]; //123
success=false; break;
}
}
}
}else{
// assert(false) : (list==null ? null : list.size()+"\n"+outa+"\n"+list+"\n");//123
}
}else{
// assert(false) : merged+", "+outa; //123
}
} catch (Exception e) {
e.printStackTrace();
log("failed", true);
System.exit(1);
}
FASTQ.FORCE_INTERLEAVED=OLD_FORCE_INT;
FASTQ.TEST_INTERLEAVED=OLD_TEST_INT;
}
discoveredAdaptersValid=success;
// assert(false) : discoveredAdaptersValid;//123
log("findAdapters finish", true);
return success;
}
/**
* Runs Clumpify for compression.
*
* @param in1 Primary input reads file (required)
* @param in2 Secondary input reads file
* @param out1 Primary output reads file (required)
* @param out2 Secondary output reads file
* @param inPrefix Append this prefix to input filenames
* @param outPrefix Append this prefix to output filenames
*/
private void clumpify(String in1, String in2, String out1, String out2, String inPrefix, String outPrefix, int stepNum){
log("clumpify start", true);
ArrayList<String> argList=new ArrayList<String>();
final String inPre=(inPrefix==null ? "" : (tmpDir==null ? outDir : tmpDir)+inPrefix);
final String outPre=(outPrefix==null ? outDir : (tmpDir==null ? outDir : tmpDir)+outPrefix);
{//Fill list with Clumpify arguments
if(pigz!=null){argList.add("pigz="+pigz);}
if(unpigz!=null){argList.add("unpigz="+unpigz);}
argList.add("zl="+(zl==null ? ""+ReadWrite.ZIPLEVEL : zl));
argList.add("reorder");
//Set read I/O files
if(in1!=null){argList.add("in1="+inPre+in1);}
if(in2!=null){argList.add("in2="+inPre+in2);}
if(out1!=null){argList.add("out1="+outPre+out1);}
if(out2!=null){argList.add("out2="+outPre+out2);}
//Set dedupe params
if(removeDuplicates){argList.add("dedupe");}
if(removeAllDuplicates){argList.add("allduplicates");}
if(removeOpticalDuplicates || removeEdgeDuplicates){argList.add("optical");}
if(removeEdgeDuplicates){argList.add("spany"); argList.add("adjacent");}
if(duplicateSubs>=0){argList.add("dsubs="+duplicateSubs);}
if(duplicateDist>=0){argList.add("ddist="+duplicateDist);}
if(duplicatePasses>0){argList.add("passes="+duplicatePasses);}
if(lowComplexity){argList.add("lowcomplexity="+lowComplexity);}
if(clumpifyGroups>0){argList.add("groups="+clumpifyGroups);}
if(clumpifyTmpdir){argList.add("usetmpdir="+clumpifyTmpdir);}
}
String[] args=argList.toArray(new String[0]);
if(reproduceName!=null){
writeReproduceFile(reproduceName, "clumpify.sh", args);
}
if(!dryrun){//Run Clumpify
Clumpify c=new Clumpify(args);
try {
c.process(new Timer());
assert(KmerSort.lastReadsOut<=KmerSort.lastReadsIn) : KmerSort.lastReadsIn+", "+KmerSort.lastBasesIn+", "+KmerSort.lastReadsOut+", "+KmerSort.lastBasesOut;
assert(KmerSort.lastBasesOut<=KmerSort.lastBasesIn) : KmerSort.lastReadsIn+", "+KmerSort.lastBasesIn+", "+KmerSort.lastReadsOut+", "+KmerSort.lastBasesOut;
assert(KmerSort.lastBasesOut>=KmerSort.lastReadsOut) : KmerSort.lastReadsIn+", "+KmerSort.lastBasesIn+", "+KmerSort.lastReadsOut+", "+KmerSort.lastBasesOut;
assert(KmerSort.lastBasesIn>=KmerSort.lastReadsIn) : KmerSort.lastReadsIn+", "+KmerSort.lastBasesIn+", "+KmerSort.lastReadsOut+", "+KmerSort.lastBasesOut;
assert(KmerSort.lastReadsOut>=0);
assert(KmerSort.lastBasesOut>=0);
assert(KmerSort.lastReadsOut>0 || KmerSort.lastReadsIn==0);
assert(KmerSort.lastBasesOut>0 || KmerSort.lastBasesIn==0);
if(filterstats.readsIn<1){
filterstats.readsIn=KmerSort.lastReadsIn;
filterstats.basesIn=KmerSort.lastBasesIn;
}
filterstats.readsOut=KmerSort.lastReadsOut;
filterstats.basesOut=KmerSort.lastBasesOut;
filterstats.readsDuplicate=KmerSort.lastReadsIn-KmerSort.lastReadsOut;
filterstats.basesDuplicate=KmerSort.lastBasesIn-KmerSort.lastBasesOut;
assert(filterstats.toString()!=null); //123
// assert(false) : KmerSort.lastReadsIn+", "+KmerSort.lastBasesIn+", "+KmerSort.lastReadsOut+", "+KmerSort.lastBasesOut;
} catch (Exception e) {
e.printStackTrace();
log("failed", true);
System.exit(1);
}
}
//Optionally append files to file list here
log("clumpify finish", true);
}
/**
* Runs FilterByTile to remove reads from low-quality areas of the flowcell.
*
* @param in1 Primary input reads file (required)
* @param in2 Secondary input reads file
* @param out1 Primary output reads file (required)
* @param out2 Secondary output reads file
* @param inPrefix Append this prefix to input filenames
* @param outPrefix Append this prefix to output filenames
*/
private void filterByTile(String in1, String in2, String out1, String out2, String outbad, String inPrefix, String outPrefix, int stepNum){
log("filterByTile start", true);
ArrayList<String> argList=new ArrayList<String>();
final String inPre=(inPrefix==null ? "" : (tmpDir==null ? outDir : tmpDir)+inPrefix);
final String outPre=(outPrefix==null ? outDir : (tmpDir==null ? outDir : tmpDir)+outPrefix);
{//Fill list with FilterByTile arguments
if(pigz!=null){argList.add("pigz="+pigz);}
if(unpigz!=null){argList.add("unpigz="+unpigz);}
argList.add("zl="+(zl==null ? ""+ReadWrite.ZIPLEVEL : zl));
//Set read I/O files
if(in1!=null){argList.add("in1="+inPre+in1);}
if(in2!=null){argList.add("in2="+inPre+in2);}
if(out1!=null){argList.add("out1="+outPre+out1);}
if(out2!=null){argList.add("out2="+outPre+out2);}
if(outbad!=null){argList.add("outb="+outbad);}
}
String[] args=argList.toArray(new String[0]);
if(reproduceName!=null){
writeReproduceFile(reproduceName, "filterbytile.sh", args);
}
if(!dryrun){//Run FilterByTile
AnalyzeFlowCell afc=new AnalyzeFlowCell(args);
try {
afc.process(new Timer());
filterstats.readsLowQuality+=afc.readsDiscarded;
filterstats.basesLowQuality+=afc.basesDiscarded;
if(filterstats.readsIn<1){
filterstats.readsIn=afc.readsProcessed;
filterstats.basesIn=afc.basesProcessed;
}
filterstats.readsOut=afc.readsProcessed-afc.readsDiscarded;
filterstats.basesOut=afc.basesProcessed-afc.basesDiscarded;
assert(filterstats.toString()!=null); //123
} catch (Exception e) {
e.printStackTrace();
log("failed", true);
System.exit(1);
}
}
//Optionally append files to file list here
log("filterByTile finish", true);
}
/**
* Runs BBDuk to perform:
* Kmer trimming, short read removal.
*
* @param in1 Primary input reads file (required)
* @param in2 Secondary input reads file
* @param out1 Primary output reads file (required)
* @param out2 Secondary output reads file
* @param inPrefix Append this prefix to input filenames
* @param outPrefix Append this prefix to output filenames
*/
private void ktrim(String in1, String in2, String out1, String out2, String inPrefix, String outPrefix, int stepNum){
log("ktrim start", true);
ktrimFlag=true;
ArrayList<String> argList=new ArrayList<String>();
final String inPre=(inPrefix==null ? "" : (tmpDir==null ? outDir : tmpDir)+inPrefix);
final String outPre=(outPrefix==null ? outDir : (tmpDir==null ? outDir : tmpDir)+outPrefix);
{//Fill list with BBDuk arguments
argList.add("ktrim="+(ktrim==null ? "f" : ktrim));
if(ordered){argList.add("ordered");}
if(minLen>0){argList.add("minlen="+minLen);}
if(minLenFraction>0){argList.add("minlenfraction="+minLenFraction);}
if((libType!=CLIP)){
argList.add("mink="+mink);
if(libType==FRAG && ("r".equalsIgnoreCase(ktrim) || "right".equalsIgnoreCase(ktrim))){
if(tboFlag){argList.add("tbo");}
if(tpeFlag){argList.add("tpe");}
}
argList.add("rcomp=f");
argList.add("overwrite="+overwrite);
argList.add("k="+trim_k);
argList.add("hdist="+hdist_trim);
if(hdist2_trim>=0){
argList.add("hdist2="+hdist2_trim);
}
if(forceTrimModulo>0){
argList.add("ftm="+forceTrimModulo);
}
argList.add("pratio=G,C");
argList.add("plen=20");
if(phistName!=null){argList.add("phist="+phistName);}
if(qhistName!=null){argList.add("qhist="+qhistName);}
if(bhistName!=null){argList.add("bhist="+bhistName);}
if(gchistName!=null){argList.add("gchist="+gchistName);}
}
if(pigz!=null){argList.add("pigz="+pigz);}
if(unpigz!=null){argList.add("unpigz="+unpigz);}
argList.add("zl="+(zl==null ? ""+ReadWrite.ZIPLEVEL : zl));
//Pass along uncaptured arguments
for(String s : primaryArgList){argList.add(s);}
//Set read I/O files
if(in1!=null){argList.add("in1="+inPre+in1);}
if(in2!=null){argList.add("in2="+inPre+in2);}
if(out1!=null){argList.add("out1="+outPre+out1);}
if(out2!=null){argList.add("out2="+outPre+out2);}
// if(rqcStatsName!=null){al.add("rqc="+rqcStatsName_kt);} //Old style for 2 log files
if(rqcStatsName!=null){argList.add("rqc=hashmap");}
if(kmerStatsName_kt!=null){argList.add("outduk="+kmerStatsName_kt);}
if(scaffoldStatsName_kt!=null){argList.add("stats="+scaffoldStatsName_kt);}
if(copyUndefined){argList.add("cu");}
argList.add("loglog"); //Cardinality
argList.add("loglogout");
}
{//Add BBDuk references
ArrayList<String> refs=new ArrayList<String>();
if(libType==FRAG){
if(discoveredAdaptersValid){argList.add("adapters="+adaptersOutFile);}
else{
if(fragAdapterFlag){refs.add(fragAdapter);}
if(rnaAdapterFlag){refs.add(rnaAdapter);}
}
}else if(libType==LFPE){
refs.add(lfpeLinker);
}else if(libType==CLIP){
// refs.add(clipLinker);
if(clipLinker!=null){
argList.add("literal="+clipLinker);
{//Special processing for literal strings of approx 4bp
String[] split=clipLinker.split(",");
int min=split[0].length();
for(String s : split){min=Tools.min(min, s.length());}
argList.add("k="+min);
argList.add("mink=-1");
argList.add("mm=f");
argList.add("hdist=0");
argList.add("edist=0");
argList.add("ktrimexclusive=t");
}
}else{
throw new RuntimeException("Null clip linker.");
}
}else if(libType==CLRS){
refs.add(clrsLinker);
}else{
throw new RuntimeException("Unknown library type.");
}
StringBuilder refstring=new StringBuilder();
for(String ref : refs){
if(ref!=null){
refstring.append(refstring.length()==0 ? "ref=" : ",");
refstring.append(ref);
}
}
if(refstring!=null && refstring.length()>0){
argList.add(refstring.toString());
}
}
String[] dukargs=argList.toArray(new String[0]);
if(reproduceName!=null){
writeReproduceFile(reproduceName, "bbduk.sh", dukargs);
}
if(!dryrun){//Run BBDuk
BBDukF duk=new BBDukF(dukargs);
try {
duk.process();
outstream.println(format("Adapter Sequence Removed:", duk.readsIn, duk.readsOut, duk.basesIn, duk.basesOut));
log("#Input:\t"+duk.readsIn+" reads\t"+duk.basesIn+" bases\t"+duk.loglogIn.cardinality()+" kmers", true, false);
log("#Remaining:\t"+duk.readsOut+" reads\t"+duk.basesOut+" bases\t"+duk.loglogOut.cardinality()+" kmers", true, false);
if(duk.errorState){throw new Exception("BBDuk did not finish successfully; see above for the error message.");}
filterstats.readsFTrimmed=duk.readsFTrimmed;
filterstats.basesFTrimmed=duk.basesFTrimmed;
filterstats.readsAdapter=duk.readsIn-duk.readsOut;
filterstats.basesAdapter=duk.basesIn-duk.basesOut-duk.basesFTrimmed;
if(filterstats.readsIn<1){
filterstats.readsIn=duk.readsIn;
filterstats.basesIn=duk.basesIn;
}
filterstats.readsOut=duk.readsOut;
filterstats.basesOut=duk.basesOut;
filterstats.gcPolymerRatio=duk.getPolymerRatio();
assert(filterstats.toString()!=null); //123
} catch (Exception e) {
e.printStackTrace();
log("failed", true);
System.exit(1);
}
}
//Optionally append files to file list here
log("ktrim finish", true);
}
/**
* Runs Seal to perform:
* Spike-in removal and quantification.
*
* @param in1 Primary input reads file (required)
* @param in2 Secondary input reads file
* @param out1 Primary output reads file (required)
* @param out2 Secondary output reads file
* @param inPrefix Append this prefix to input filenames
* @param outPrefix Append this prefix to output filenames
*/
private void filterSpikein(String in1, String in2, String out1, String out2, String outbad, String inPrefix, String outPrefix,
int stepNum){
log("filterSpikein start", true);
ArrayList<String> argList=new ArrayList<String>();
final String inPre=(inPrefix==null ? "" : (tmpDir==null ? outDir : tmpDir)+inPrefix);
final String outPre=(outPrefix==null ? outDir : (tmpDir==null ? outDir : tmpDir)+outPrefix);
// outstream.println("inPre="+inPre+", outPre="+outPre+", outDir="+outDir+", tmpDir="+tmpDir); //123
{//Fill list with BBDuk arguments
if(ordered){argList.add("ordered");}
argList.add("overwrite="+overwrite);
argList.add("k="+spikein_k);
argList.add("hdist="+hdist_spikein);
if(pigz!=null){argList.add("pigz="+pigz);}
if(unpigz!=null){argList.add("unpigz="+unpigz);}
argList.add("zl="+(zl==null ? ""+ReadWrite.ZIPLEVEL : zl));
// //Pass along uncaptured arguments
// for(String s : primaryArgList){argList.add(s);}
//Set read I/O files
if(in1!=null){argList.add("in1="+inPre+in1);}
if(in2!=null){argList.add("in2="+inPre+in2);}
if(out1!=null){argList.add("outu1="+outPre+out1);}
if(out2!=null){argList.add("outu2="+outPre+out2);}
if(outbad!=null){argList.add("outm="+outbad);}
// if(rqcStatsName!=null){al.add("rqc="+rqcStatsName);} //Old style for 2 log files
// if(rqcStatsName!=null){argList.add("rqc=hashmap");}
if(scaffoldStatsNameSpikein!=null){argList.add("stats="+scaffoldStatsNameSpikein);}
// if(copyUndefined){argList.add("cu");}
//
argList.add("loglog"); //Cardinality
argList.add("loglogout");
}
{//Add references
if(mtstFlag){spikeinRefs.add(mtstRef);}
if(kapaFlag){spikeinRefs.add(kapaRef);}
if(spikeinRefs.isEmpty()){assert(false) : "spikeinFlag is true but there are no spikein references.";}
StringBuilder refstring=new StringBuilder();
for(String ref : spikeinRefs){
if(ref!=null){
refstring.append(refstring.length()==0 ? "ref=" : ",");
refstring.append(ref);
}
}
if(refstring!=null && refstring.length()>0){
argList.add(refstring.toString());
}
}
String[] sealargs=argList.toArray(new String[0]);
if(reproduceName!=null){
writeReproduceFile(reproduceName, "seal.sh", sealargs);
}
if(!dryrun){//Run Seal
Seal seal=new Seal(sealargs);
try {
seal.process();
outstream.println(format("Spikein Sequence Removed:", seal.readsIn, seal.readsIn-seal.readsMatched, seal.basesIn, seal.basesIn-seal.basesMatched));
log("#Input:\t"+seal.readsIn+" reads\t"+seal.basesIn+" bases\t"+seal.loglog.cardinality()+" kmers", true, false);
log("#Remaining:\t"+seal.readsUnmatched+" reads\t"+seal.basesUnmatched+" bases\t"+seal.loglogOut.cardinality()+" kmers", true, false);
filterstats.readsSpikin=seal.readsMatched;
filterstats.basesSpikin=seal.basesMatched;
if(filterstats.readsIn<1){
filterstats.readsIn=seal.readsIn;
filterstats.basesIn=seal.basesIn;
}
filterstats.readsOut=seal.readsIn-seal.readsMatched;
filterstats.basesOut=seal.basesIn-seal.basesMatched;
assert(filterstats.toString()!=null); //123
} catch (Exception e) {
e.printStackTrace();
log("failed", true);
System.exit(1);
}
}
//Optionally append files to file list here
log("filterSpikein finish", true);
}
/**
* Runs BBDuk to perform:
* Quality filtering, quality trimming, n removal, short read removal, artifact removal (via kmer filtering), phiX removal, lambda removal.
*
* @param in1 Primary input reads file (required)
* @param in2 Secondary input reads file
* @param out1 Primary output reads file (required)
* @param out2 Secondary output reads file
* @param inPrefix Append this prefix to input filenames
* @param outPrefix Append this prefix to output filenames
*/
private void filter1(String in1, String in2, String out1, String out2, String outbad, String inPrefix, String outPrefix,
int stepNum){
log("filter start", true);
ArrayList<String> argList=new ArrayList<String>();
final String inPre=(inPrefix==null ? "" : (tmpDir==null ? outDir : tmpDir)+inPrefix);
final String outPre=(outPrefix==null ? outDir : (tmpDir==null ? outDir : tmpDir)+outPrefix);
// outstream.println("inPre="+inPre+", outPre="+outPre+", outDir="+outDir+", tmpDir="+tmpDir); //123
{//Fill list with BBDuk arguments
if(minAvgQuality>-1){argList.add("maq="+minAvgQuality+","+minAvgQualityBases);}
if(qtrim!=null){
argList.add("trimq="+trimq);
argList.add("qtrim="+qtrim);
}
if(ftl>=0){argList.add("ftl="+ftl);}
if(ftr>=0){argList.add("ftr="+ftr);}
if(ftr2>=0){argList.add("ftr2="+ftr2);}
if(ordered){argList.add("ordered");}
argList.add("overwrite="+overwrite);
if(maxNs>=0){argList.add("maxns="+maxNs);}
if(minLen>0){argList.add("minlen="+minLen);}
if(minLenFraction>0){argList.add("minlenfraction="+minLenFraction);}
argList.add("k="+filter_k);
argList.add("hdist="+hdist_filter);
if(qhdist_filter>0){argList.add("qhdist="+qhdist_filter);}
if(pigz!=null){argList.add("pigz="+pigz);}
if(unpigz!=null){argList.add("unpigz="+unpigz);}
argList.add("zl="+(zl==null ? ""+ReadWrite.ZIPLEVEL : zl));
if(chastityfilter!=null){argList.add("cf="+chastityfilter);}
if(failnobarcode!=null){argList.add("failnobarcode="+failnobarcode);}
if(barcodefilter!=null){argList.add("barcodefilter="+barcodefilter);}
if(barcodes!=null){argList.add("barcodes="+barcodes);}
if(entropyFilter && minEntropy>0){
argList.add("minentropy="+minEntropy);
argList.add("entropyk="+entropyk);
argList.add("entropywindow="+entropywindow);
}
//Pass along uncaptured arguments
for(String s : primaryArgList){argList.add(s);}
//Set read I/O files
if(in1!=null){argList.add("in1="+inPre+in1);}
if(in2!=null){argList.add("in2="+inPre+in2);}
if(out1!=null){argList.add("out1="+outPre+out1);}
if(out2!=null){argList.add("out2="+outPre+out2);}
if(outbad!=null){argList.add("outm="+outbad);}
// if(rqcStatsName!=null){al.add("rqc="+rqcStatsName);} //Old style for 2 log files
if(rqcStatsName!=null){argList.add("rqc=hashmap");}
if(kmerStatsName1!=null){argList.add("outduk="+kmerStatsName1);}
if(scaffoldStatsName1!=null){argList.add("stats="+scaffoldStatsName1);}
if(copyUndefined){argList.add("cu");}
if(bisulfite){argList.add("ftr2=1");}
if(trimPolyA){argList.add("trimpolya");}
if(trimPolyGLeft>0){argList.add("trimpolygleft="+trimPolyGLeft);}
if(trimPolyGRight>0){argList.add("trimpolygright="+trimPolyGRight);}
if(filterPolyG>0){argList.add("filterpolyg="+filterPolyG);}
argList.add("loglog"); //Cardinality
argList.add("loglogout");
}
{//Add BBDuk references
bbdukFilterRefs.add(mainArtifactFile);
if(!doNexteraLMP){bbdukFilterRefs.add(nexteraLinkerFile);}
if(filterPolyA){bbdukFilterRefs.add(polyAFile);}
if(phixFlag){bbdukFilterRefs.add(phixRef);}
if(lambdaFlag){bbdukFilterRefs.add(lambdaRef);}
if(pjetFlag){bbdukFilterRefs.add(pjetRef);}
if(libType==FRAG){
}else if(libType==LFPE){
}else if(libType==CLIP){
}else if(libType==CLRS){
}else{
throw new RuntimeException("Unknown library type.");
}
StringBuilder refstring=new StringBuilder();
for(String ref : bbdukFilterRefs){
if(ref!=null){
refstring.append(refstring.length()==0 ? "ref=" : ",");
refstring.append(ref);
}
}
if(refstring!=null && refstring.length()>0){
argList.add(refstring.toString());
}
}
String[] dukargs=argList.toArray(new String[0]);
if(reproduceName!=null){
writeReproduceFile(reproduceName, "bbduk.sh", dukargs);
}
if(!dryrun){//Run BBDuk
BBDukF duk=new BBDukF(dukargs);
try {
duk.process();
outstream.println(format("Synthetic Contam Sequence Removed:", duk.readsIn, duk.readsOut, duk.basesIn, duk.basesOut));
log("#Input:\t"+duk.readsIn+" reads\t"+duk.basesIn+" bases\t"+duk.loglogIn.cardinality()+" kmers", true, false);
log("#Remaining:\t"+duk.readsOut+" reads\t"+duk.basesOut+" bases\t"+duk.loglogOut.cardinality()+" kmers", true, false);
if(duk.errorState){throw new Exception("BBDuk did not finish successfully; see above for the error message.");}
// System.err.println(filterstats.toString());
long rRemoved=duk.readsIn-duk.readsOut;
long bRemoved=duk.basesIn-duk.basesOut;
filterstats.readsArtifact+=duk.readsKFiltered;
filterstats.basesArtifact+=duk.basesKFiltered;
filterstats.readsPolyG+=duk.readsPolyTrimmed;
filterstats.basesPolyG+=duk.basesPolyTrimmed;
filterstats.readsLowQuality+=(rRemoved-duk.readsKFiltered);
filterstats.basesLowQuality+=(bRemoved-duk.basesKFiltered);
filterstats.readsN+=duk.readsNFiltered;
filterstats.basesN+=duk.basesNFiltered;
if(filterstats.readsIn<1){
filterstats.readsIn=duk.readsIn;
filterstats.basesIn=duk.basesIn;
}
filterstats.readsOut=duk.readsOut;
filterstats.basesOut=duk.basesOut;
// System.err.println(filterstats.toString());
assert(filterstats.toString()!=null); //123
} catch (Exception e) {
e.printStackTrace();
log("failed", true);
System.exit(1);
}
}
//Optionally append files to file list here
log("filter finish", true);
}
/**
* Runs BBDuk to perform:
* Short contaminant removal.
*
* @param in1 Primary input reads file (required)
* @param in2 Secondary input reads file
* @param out1 Primary output reads file (required)
* @param out2 Secondary output reads file
* @param inPrefix Append this prefix to input filenames
* @param outPrefix Append this prefix to output filenames
*/
private void filter2(String in1, String in2, String out1, String out2, String outbad, String inPrefix, String outPrefix,
int stepNum){
log("short filter start", true);
ArrayList<String> argList=new ArrayList<String>();
final String inPre=(inPrefix==null ? "" : (tmpDir==null ? outDir : tmpDir)+inPrefix);
final String outPre=(outPrefix==null ? outDir : (tmpDir==null ? outDir : tmpDir)+outPrefix);
// outstream.println("inPre="+inPre+", outPre="+outPre+", outDir="+outDir+", tmpDir="+tmpDir); //123
{//Fill list with BBDuk arguments
if(ordered){argList.add("ordered");}
argList.add("overwrite="+overwrite);
argList.add("k="+(doNexteraLMP ? 19 : 20));
argList.add("hdist="+hdist_filter);
if(qhdist_filter>0){argList.add("qhdist="+qhdist_filter);}
if(pigz!=null){argList.add("pigz="+pigz);}
if(unpigz!=null){argList.add("unpigz="+unpigz);}
argList.add("zl="+(zl==null ? ""+ReadWrite.ZIPLEVEL : zl));
//Pass along uncaptured arguments
for(String s : primaryArgList){argList.add(s);}
//Set read I/O files
if(in1!=null){argList.add("in1="+inPre+in1);}
if(in2!=null){argList.add("in2="+inPre+in2);}
if(out1!=null){argList.add("out1="+outPre+out1);}
if(out2!=null){argList.add("out2="+outPre+out2);}
if(outbad!=null){argList.add("outm="+outbad);}
// if(rqcStatsName!=null){argList.add("rqc=hashmap");} //TODO
if(kmerStatsName2!=null){argList.add("outduk="+kmerStatsName2);}
if(scaffoldStatsName2!=null){argList.add("stats="+scaffoldStatsName2);}
if(copyUndefined){argList.add("cu");}
argList.add("loglog"); //Cardinality
argList.add("loglogout");
}
{//Add BBDuk references
argList.add("ref="+shortArtifactFile+(doNexteraLMP ? "" : ","+shortArtifactFile));
}
String[] dukargs=argList.toArray(new String[0]);
if(reproduceName!=null){
writeReproduceFile(reproduceName, "bbduk.sh", dukargs);
}
if(!dryrun){//Run BBDuk
BBDukF duk=new BBDukF(dukargs);
try {
duk.process();
outstream.println(format("Short Synthetic Contam Sequence Removed:", duk.readsIn, duk.readsOut, duk.basesIn, duk.basesOut));
log("#Input:\t"+duk.readsIn+" reads\t"+duk.basesIn+" bases\t"+duk.loglogIn.cardinality()+" kmers", true, false);
log("#Remaining:\t"+duk.readsOut+" reads\t"+duk.basesOut+" bases\t"+duk.loglogOut.cardinality()+" kmers", true, false);
if(duk.errorState){throw new Exception("BBDuk did not finish successfully; see above for the error message.");}
long rRemoved=duk.readsIn-duk.readsOut;
long bRemoved=duk.basesIn-duk.basesOut;
filterstats.readsArtifact+=duk.readsKFiltered;
filterstats.basesArtifact+=duk.basesKFiltered;
filterstats.readsLowQuality+=(rRemoved-duk.readsKFiltered);
filterstats.basesLowQuality+=(bRemoved-duk.basesKFiltered);
filterstats.readsN+=duk.readsNFiltered;
filterstats.basesN+=duk.basesNFiltered;
if(filterstats.readsIn<1){
filterstats.readsIn=duk.readsIn;
filterstats.basesIn=duk.basesIn;
}
filterstats.readsOut=duk.readsOut;
filterstats.basesOut=duk.basesOut;
assert(filterstats.toString()!=null); //123
} catch (Exception e) {
e.printStackTrace();
log("failed", true);
System.exit(1);
}
}
//Optionally append files to file list here
log("short filter finish", true);
}
/**
* Runs BBDuk to perform:
* Ribosomal read removal.
*
* @param in1 Primary input reads file (required)
* @param in2 Secondary input reads file
* @param out1 Primary output reads file (required)
* @param out2 Secondary output reads file
* @param outRibo Output for ribosomal reads
* @param inPrefix Append this prefix to input filenames
* @param outPrefix Append this prefix to output filenames
*/
private void filterRibo(String in1, String in2, String out1, String out2, String outRibo, String inPrefix, String outPrefix,
int stepNum){
log("filter ribo start", true);
ArrayList<String> argList=new ArrayList<String>();
final String inPre=(inPrefix==null ? "" : (tmpDir==null ? outDir : tmpDir)+inPrefix);
final String outPre=(outPrefix==null ? outDir : (tmpDir==null ? outDir : tmpDir)+outPrefix);
// outstream.println("inPre="+inPre+", outPre="+outPre+", outDir="+outDir+", tmpDir="+tmpDir); //123
{//Fill list with BBDuk arguments
if(ordered){argList.add("ordered");}
argList.add("k=31");
argList.add("ref="+riboKmers);
if(hdist_ribo>0){argList.add("hdist="+hdist_ribo);}
if(edist_ribo>0){argList.add("edist="+edist_ribo);}
//Pass along uncaptured arguments
for(String s : primaryArgList){argList.add(s);}
//Set read I/O files
if(in1!=null){argList.add("in1="+inPre+in1);}
if(in2!=null){argList.add("in2="+inPre+in2);}
if(out1!=null){argList.add("out1="+outPre+out1);}
if(out2!=null){argList.add("out2="+outPre+out2);}
if(outRibo!=null){argList.add("outm="+outRibo);}
// if(rqcStatsName!=null){al.add("rqc="+rqcStatsName);} //Old style for 2 log files
// if(rqcStatsName!=null){argList.add("rqc=hashmap");}
// if(kmerStatsName!=null){argList.add("outduk="+kmerStatsName);}
// if(scaffoldStatsName!=null){argList.add("stats="+scaffoldStatsName);}
argList.add("loglog");
argList.add("loglogout");
}
String[] dukargs=argList.toArray(new String[0]);
if(reproduceName!=null){
writeReproduceFile(reproduceName, "bbduk.sh", dukargs);
}
if(!dryrun){//Run BBDuk
BBDukF duk=new BBDukF(dukargs);
try {
duk.process();
outstream.println(format("Ribosomal Sequence Removed:", duk.readsIn, duk.readsOut, duk.basesIn, duk.basesOut));
log("#Input:\t"+duk.readsIn+" reads\t"+duk.basesIn+" bases\t"+duk.loglogIn.cardinality()+" kmers", true, false);
log("#Remaining:\t"+duk.readsOut+" reads\t"+duk.basesOut+" bases\t"+duk.loglogOut.cardinality()+" kmers", true, false);
if(duk.errorState){throw new Exception("BBDuk did not finish successfully; see above for the error message.");}
filterstats.readsRiboKmer+=duk.readsKFiltered;
filterstats.basesRiboKmer+=duk.basesKFiltered;
if(filterstats.readsIn<1){
filterstats.readsIn=duk.readsIn;
filterstats.basesIn=duk.basesIn;
}
filterstats.readsOut=duk.readsOut;
filterstats.basesOut=duk.basesOut;
assert(filterstats.toString()!=null); //123
} catch (Exception e) {
e.printStackTrace();
log("failed", true);
System.exit(1);
}
}
//Optionally append files to file list here
log("filter ribo finish", true);
}
private static String toPercent(long numerator, long denominator){
if(denominator<1){return "0.00%";}
return String.format(Locale.ROOT, "%.2f%%", numerator*100.0/denominator);
}
private static String format(String prefix, long rin, long rout, long bin, long bout){
long rrmvd=rin-rout;
long brmvd=bin-bout;
return prefix+"\t"+rrmvd+" reads ("+toPercent(rrmvd, rin)+")\t"+brmvd+" bases ("+toPercent(brmvd, bin)+")";
}
/**
* Runs SplitNexteraLMP.
*
* @param in1 Primary input reads file (required)
* @param in2 Secondary input reads file
* @param inPrefix Append this prefix to input filenames
* @param outPrefix Append this prefix to output filenames
*/
private void splitNextera(String in1, String in2, String inPrefix, String outPrefix, int stepNum){
log("splitNextera start", true);
splitNexteraFlag=true;
ArrayList<String> argList=new ArrayList<String>();
final String inPre=(inPrefix==null ? "" : (tmpDir==null ? outDir : tmpDir)+inPrefix);
final String outPre=(outPrefix==null ? outDir : (tmpDir==null ? outDir : tmpDir)+outPrefix);
final String lmpName, fragName, unknownName, singletonName;
final String statsName=outPre+nexteraStats;
int dot=rawName.lastIndexOf('.');
if(dot>-1){
lmpName=outPre+rawName.substring(0, dot)+"."+symbols+".lmp"+rawName.substring(dot)+(compress ? ".gz" : "");
fragName=outPre+rawName.substring(0, dot)+"."+symbols+".frag"+rawName.substring(dot)+(compress ? ".gz" : "");
unknownName=outPre+rawName.substring(0, dot)+"."+symbols+".unknown"+rawName.substring(dot)+(compress ? ".gz" : "");
singletonName=outPre+rawName.substring(0, dot)+"."+symbols+".singleton"+rawName.substring(dot)+(compress ? ".gz" : "");
}else{
lmpName=outPre+rawName+"."+symbols+".lmp.fastq"+(compress ? ".gz" : "");
fragName=outPre+rawName+"."+symbols+".frag.fastq"+(compress ? ".gz" : "");
unknownName=outPre+rawName+"."+symbols+".unknown.fastq"+(compress ? ".gz" : "");
singletonName=outPre+rawName+"."+symbols+".singleton.fastq"+(compress ? ".gz" : "");
}
{//Fill list with Nextera arguments
argList.add("mask");
argList.add("ow="+overwrite);
if(minLen>0){argList.add("minlen="+minLen);}
if(pigz!=null){argList.add("pigz="+pigz);}
if(unpigz!=null){argList.add("unpigz="+unpigz);}
argList.add("zl="+(zl==null ? ""+ReadWrite.ZIPLEVEL : zl));
//Set read I/O files
if(in1!=null){argList.add("in1="+inPre+in1);}
if(in2!=null){argList.add("in2="+inPre+in2);}
argList.add("out="+lmpName);
argList.add("outu="+unknownName);
argList.add("outf="+fragName);
argList.add("outs="+singletonName);
argList.add("stats="+statsName);
}
String[] splitargs=argList.toArray(new String[0]);
if(reproduceName!=null){
writeReproduceFile(reproduceName, "splitnextera.sh", splitargs);
}
if(!dryrun){//run SplitNexteraLMP
SplitNexteraLMP split=new SplitNexteraLMP(splitargs);
try {
split.process();
StringBuilder sb=new StringBuilder();
sb.append("LMP:\t"+split.readsLmp()+" reads\t"+split.basesLmp()+" bases\n");
sb.append("Frag:\t"+split.readsFrag()+" reads\t"+split.basesFrag()+" bases\n");
sb.append("Unknown:\t"+split.readsUnk()+" reads\t"+split.basesUnk()+" bases\n");
sb.append("Single:\t"+split.readsSingle()+" reads\t"+split.basesSingle()+" bases\n");
} catch (Exception e) {
e.printStackTrace();
log("failed", true);
System.exit(1);
}
}
if(fileListName!=null){
StringBuilder sb=new StringBuilder();
sb.append("lmp="+lmpName).append('\n');
sb.append("frag="+fragName).append('\n');
sb.append("unknown="+unknownName).append('\n');
sb.append("singleton="+singletonName).append('\n');
sb.append("nexterastats="+statsName).append('\n');
if(sb.length()>0){
ReadWrite.writeString(sb, fileListName, true);
}
}
log("splitNextera finish", true);
}
/**
* Runs BBMap to perform:
* Human contaminant removal.
*
* @param in1 Primary input reads file (required)
* @param in2 Secondary input reads file
* @param out1 Primary output reads file (required)
* @param out2 Secondary output reads file
* @param inPrefix Append this prefix to input filenames
* @param outPrefix Append this prefix to output filenames
*/
private void dehumanize(String in1, String in2, String out1, String out2, String outbad, String inPrefix, String outPrefix,
int stepNum, boolean mouseCatDogHuman, boolean aggressive, long lastReadsObserved){
log("dehumanize start", true);
ArrayList<String> argList=new ArrayList<String>();
final String inPre=(inPrefix==null ? "" : (tmpDir==null ? outDir : tmpDir)+inPrefix);
final String outPre=(outPrefix==null ? outDir : (tmpDir==null ? outDir : tmpDir)+outPrefix);
final boolean useBBSplit=mouseCatDogHuman;
{
argList.add("ordered="+(ordered && false)); //Ordered is too slow here
argList.add("k="+map_k);
argList.add("idtag=t");
argList.add("usemodulo");
argList.add("printunmappedcount");
argList.add("ow="+overwrite);
if(trimUntrim){
argList.add("qtrim=rl");
argList.add("trimq=10");
argList.add("untrim");
}
argList.add("kfilter=25");
argList.add("maxsites=1");
argList.add("tipsearch="+0);
if(aggressive){
argList.add("minratio=.75");
argList.add("maxindel=8");
argList.add("minhits="+1);
argList.add("bw=26");
argList.add("bwr=0.22");
argList.add("build=2");
argList.add("ef=0.02");
}else{
argList.add("minratio=.9");
argList.add("maxindel=3");
argList.add("minhits="+2);
argList.add("bw=12");
argList.add("bwr=0.16");
argList.add("fast="+true);
argList.add("maxsites2=10");
argList.add("build=1");
argList.add("ef=0.03");
}
final int genomes=Tools.max(1, (mouseCatDogHuman ? 4 : 0)+(humanFlag ? 1 : 0)+(dogFlag ? 1 : 0)+(catFlag ? 1 : 0)+(mouseFlag ? 1 : 0));
if(bloomFilter && (dryrun || lastReadsObserved<0 || lastReadsObserved>=minReadsToBloomFilter) && Shared.memAvailableAdvanced()>=(genomes*5000000000L)){
argList.add("bloomfilter");
argList.add("bloomk="+bloomFilterK);
argList.add("bloomhashes="+bloomFilterHashes);
argList.add("bloomminhits="+bloomFilterMinHits);
if(bloomSerial){argList.add("bloomserial");}
}
if(outbad!=null){argList.add("outm="+outbad);}
if(mouseCatDogHuman){
argList.add("path="+mouseCatDogHumanPath);
if(refStatsName!=null && useBBSplit){argList.add("refstats="+refStatsName);}
}else{
if(humanRef==null){
argList.add("path="+humanPath);
}else{
RefToIndex.NODISK=true;
argList.add("ref="+humanRef);
}
}
if(pigz!=null){argList.add("pigz="+pigz);}
if(unpigz!=null){argList.add("unpigz="+unpigz);}
argList.add("zl="+(zl==null ? ""+ReadWrite.ZIPLEVEL : zl));
if(useBBSplit){argList.add("forcereadonly");}
// //Pass along uncaptured arguments
// for(String s : primaryArgList){argList.add(s);}
//Set read I/O files
if(in1!=null){argList.add("in1="+inPre+in1);}
if(in2!=null){argList.add("in2="+inPre+in2);}
if(keepHumanReads){
if(out1!=null){argList.add("out1="+outPre+out1);}
if(out2!=null){argList.add("out2="+outPre+out2);}
}else{
if(out1!=null){argList.add("outu1="+outPre+out1);}
if(out2!=null){argList.add("outu2="+outPre+out2);}
}
}
String[] args=argList.toArray(new String[0]);
if(!dryrun){//Run BBMap
try {
if(useBBSplit){
// RefToIndex.FORCE_READ_ONLY=true;
BBSplitter.main(args);
RefToIndex.FORCE_READ_ONLY=false;
}else{
BBMap.main(args);
}
// System.err.println(filterstats.toString());
// final long lastReadsUsed=BBMap.lastReadsUsed;
final long lastReadsIn=BBMap.lastReadsIn;
final long lastEitherMapped=BBMap.lastEitherMapped;
final long lastReadsOut=lastReadsIn-lastEitherMapped;
// final long lastBasesUsed=BBMap.lastBasesUsed;
final long lastBasesIn=BBMap.lastBasesIn;
final long lastEitherMappedBases=BBMap.lastEitherMappedBases;
final long lastBasesOut=lastBasesIn-lastEitherMappedBases;
// System.err.println(lastReadsUsed);
// System.err.println(lastBasesUsed);
// System.err.println();
//
// System.err.println(lastReadsIn);
// System.err.println(lastBasesIn);
// System.err.println();
//
// System.err.println(lastEitherMapped);
// System.err.println(lastEitherMappedBases);
// System.err.println();
//
// System.err.println(lastReadsOut);
// System.err.println(lastBasesOut);
// System.err.println();
if(filterstats.readsIn>0){
assert(lastReadsIn==filterstats.readsOut) : lastReadsIn+", "+filterstats.readsOut;
assert(lastBasesIn==filterstats.basesOut) : lastBasesIn+", "+filterstats.basesOut;
}
// System.err.println(BBMap.lastBothUnmapped);
// System.err.println(BBMap.lastBothUnmappedBases);
// System.err.println();
// System.err.println(BBMap.lastReadsPassedBloomFilter);
// System.err.println(BBMap.lastBasesPassedBloomFilter);
// System.err.println();
if(refStatsName!=null && useBBSplit){
filterstats.parseHuman(refStatsName);
}else{
filterstats.readsHuman=lastEitherMapped;
filterstats.basesHuman=lastEitherMappedBases;
}
if(filterstats.readsIn<1){
filterstats.readsIn=lastReadsIn;
filterstats.basesIn=lastBasesIn;
}
filterstats.readsOut=lastReadsOut;
filterstats.basesOut=lastBasesOut;
// System.err.println(filterstats.toString());
assert(filterstats.toString()!=null); //123
outstream.println(format("Human Sequence Removed:", lastReadsIn, lastReadsOut,
lastBasesIn, lastBasesOut));
log("#Input:\t"+lastReadsIn+" reads\t"+lastBasesIn+" bases", true, false);
log("#Remaining:\t"+lastReadsOut+" reads\t"+lastBasesOut+" bases", true, false);
} catch (Exception e) {
e.printStackTrace();
log("failed", true);
System.exit(1);
}
}
//Clear the index
Data.unloadAll();
//Unset NODISK
RefToIndex.NODISK=false;
if(reproduceName!=null){
writeReproduceFile(reproduceName, useBBSplit ? "bbsplit.sh" : "bbmap.sh", args);
}
//Optionally append files to file list here
log("dehumanize finish", true);
}
/** Fasta only */
public static boolean printFileTaxonomy(String in, String results, String taxTreeFile, boolean ow, boolean app, boolean bestEffort){
if(results==null){return false;}
TextFile tf=new TextFile(in);
TextStreamWriter tsw=new TextStreamWriter(results, ow, app, false);
tsw.start();
TaxTree tree=TaxTree.loadTaxTree(taxTreeFile, outstream, true, false);
assert(tree!=null) : taxTreeFile+", "+in+", "+results;
LinkedHashSet<TaxNode> nodes=new LinkedHashSet<TaxNode>();
for(String line=tf.nextLine(); line!=null; line=tf.nextLine()){
if(line.startsWith(">")){
TaxNode tn=tree.parseNodeFromHeader(line.substring(1), bestEffort);
nodes.add(tn);
}
}
tf.close();
for(TaxNode tn : nodes){
tsw.println(tn.id+"\t"+tn.levelStringExtended(false)+"\t"+tn.name);
}
return tsw.poisonAndWait();
}
/**
* Runs FilterByTaxa to remove sequences from a reference.
*/
private String taxFilter(String in, String out, String results, String level, boolean include, boolean bestEffort, boolean log, boolean ow, boolean app){
if(taxList==null){
printFileTaxonomy(in, results, taxTreeFile, ow, app, true);
return in;
}
if(log){log("taxFilter start", true);}
String temp=(tmpDir==null ? outDir : tmpDir)+taxaPrefix+out;
ArrayList<String> argList=new ArrayList<String>();
{
argList.add("names="+taxList);
argList.add("tree="+taxTreeFile);
argList.add("level="+level);
argList.add("in="+in);
argList.add("out="+temp);
argList.add("ow="+ow);
argList.add("append="+app);
argList.add("include="+include);
argList.add("besteffort="+bestEffort);
if(results!=null){argList.add("results="+results);}
}
if(loadGiTable){
GiToNcbi.initialize(giTable);
}
String[] args=argList.toArray(new String[0]);
final FilterByTaxa fbt;
{
final boolean OLD_FORCE_INT=FASTQ.FORCE_INTERLEAVED, OLD_TEST_INT=FASTQ.TEST_INTERLEAVED;
FASTQ.FORCE_INTERLEAVED=FASTQ.TEST_INTERLEAVED=false;
fbt=new FilterByTaxa(args);
fbt.process(new Timer());
FASTQ.FORCE_INTERLEAVED=OLD_FORCE_INT;
FASTQ.TEST_INTERLEAVED=OLD_TEST_INT;
GiToNcbi.unload();
}
if(reproduceName!=null){
writeReproduceFile(reproduceName, "filterbytaxa.sh", args);
}
if(log){log("taxFilter finish", true);}
Shared.setBuffers();
// outstream.println("*Returning "+(fbt.basesOut>0 ? temp : null));
return fbt.basesOut>0 ? temp : null;
}
/**
* Runs FilterByTaxa to remove sequences from a reference.
*/
private String taxFilterList(ArrayList<String> in, String out, boolean include, boolean bestEffort, String initialLevel){
String level=(bestEffort && include) ? initialLevel : taxLevel;
if(in.size()<2){return taxFilter(in.get(0), out, null, level, include, bestEffort, true, overwrite, false);}
log("taxFilterList start", true);
for(int i=0; i<in.size(); i++){
taxFilter(in.get(i), out, null, level, include, bestEffort, false, (i==0 && overwrite), i>0);
}
String temp=(tmpDir==null ? outDir : tmpDir)+taxaPrefix+out;
return temp;
}
private void detectCommonMicrobes(final String in1, final String in2, final String scafstats, final String inPrefix, final String ref, boolean aggressive,
int build, String cmRef, String cmPath){
log("detectCommonMicrobes start", true);
final String inPre=(inPrefix==null ? "" : (tmpDir==null ? outDir : tmpDir)+inPrefix);
if(ref==null){
String skipped="Tax filter removed all ref sequences; skipping microbe detection.";
outstream.println(skipped);
log(skipped, true);
log("detectCommonMicrobes finish", true);
return;
}
ArrayList<String> argList=new ArrayList<String>();
{
argList.add("k="+map_k);
argList.add("idtag=t");
argList.add("printunmappedcount");
argList.add("ow="+overwrite);
if(trimUntrim){
argList.add("qtrim=rl");
argList.add("trimq=10");
argList.add("untrim");
}
argList.add("ef=0.001");
if(cmPath!=null && cmRef.equals(ref) && cmRef.startsWith(cmPath)){
RefToIndex.NODISK=false;
argList.add("path="+cmPath);
}else{
RefToIndex.NODISK=true;
argList.add("ref="+ref);
}
if(pigz!=null){argList.add("pigz="+pigz);}
if(unpigz!=null){argList.add("unpigz="+unpigz);}
argList.add("zl="+(zl==null ? ""+ReadWrite.ZIPLEVEL : zl));
if(aggressive){
argList.add("minid=.85");
argList.add("maxindel=8");
argList.add("minhits="+1);
argList.add("bw=26");
argList.add("bwr=0.22");
argList.add("build=2");
argList.add("tipsearch="+2);
}else{
argList.add("minid=.95");
argList.add("idfilter=.95");
argList.add("maxindel=3");
argList.add("minhits="+2);
argList.add("bw=12");
argList.add("bwr=0.16");
argList.add("fast="+true);
argList.add("maxsites2=10");
argList.add("build="+build);
argList.add("tipsearch="+0);
}
//Set read I/O files
if(in1!=null){argList.add("in1="+inPre+in1);}
if(in2!=null){argList.add("in2="+inPre+in2);}
// if(outbad!=null){argList.add("outm="+outbad);}
if(scafstats!=null){argList.add("scafstats="+scafstats);}
}
String[] args=argList.toArray(new String[0]);
if(!dryrun){//Run BBMap
try {
BBMap.main(args);
} catch (Exception e) {
e.printStackTrace();
log("failed", true);
System.exit(1);
}
}
//Clear the index
Data.unloadAll();
//Unset NODISK
RefToIndex.NODISK=false;
if(reproduceName!=null){
writeReproduceFile(reproduceName, "bbmap.sh", args);
}
if(ref!=null && !ref.equals(cmRef)){delete(null, ref);}
log("detectCommonMicrobes finish", true);
}
/**
* Runs BBMap to perform:
* Microbial contaminant removal.
*/
private void removeCommonMicrobes(String in1, String in2, String out1, String out2, String outbad, String scafstats, String inPrefix, String outPrefix,
final String ref, int stepNum, boolean aggressive){
log("removeCommonMicrobes start", true);
final String inPre=(inPrefix==null ? "" : (tmpDir==null ? outDir : tmpDir)+inPrefix);
final String outPre=(outPrefix==null ? outDir : (tmpDir==null ? outDir : tmpDir)+outPrefix);
if(ref==null){
String skipped="Tax filter removed all ref sequences; skipping microbe removal.";
outstream.println(skipped);
log(skipped, true);
try {
if(in1!=null){
File a=new File(inPre+in1);
File b=new File(outPre+out1);
outstream.println("Renaming "+a+" to "+b);
assert(a.exists()) : a;
assert(!b.exists() || overwrite) : b;
a.renameTo(b);
writeReproduceFile(reproduceName, "mv", new String[] {a.toString(), b.toString()});
}
if(in2!=null && out2!=null){
File a=new File(inPre+in2);
File b=new File(outPre+out2);
outstream.println("Renaming "+a+" to "+b);
assert(a.exists()) : a;
assert(!b.exists() || overwrite) : b;
a.renameTo(b);
writeReproduceFile(reproduceName, "mv", new String[] {a.toString(), b.toString()});
}
} catch (Throwable e) {
outstream.println(e.getMessage());
e.printStackTrace();
log("failed", true);
System.exit(1);
}
log("removeCommonMicrobes finish", true);
return;
}
ArrayList<String> argList=new ArrayList<String>();
{
if(ordered){argList.add("ordered");}
argList.add("quickmatch");
argList.add("k="+map_k);
argList.add("idtag=t");
argList.add("printunmappedcount");
argList.add("ow="+overwrite);
if(trimUntrim){
argList.add("qtrim=rl");
argList.add("trimq=10");
argList.add("untrim");
}
argList.add("ef=0.001");
if(commonMicrobesPath!=null && commonMicrobesRef.equals(ref) && commonMicrobesRef.startsWith(commonMicrobesPath)){
RefToIndex.NODISK=false;
argList.add("path="+commonMicrobesPath);
}else{
RefToIndex.NODISK=true;
argList.add("ref="+ref);
}
if(pigz!=null){argList.add("pigz="+pigz);}
if(unpigz!=null){argList.add("unpigz="+unpigz);}
argList.add("zl="+(zl==null ? ""+ReadWrite.ZIPLEVEL : zl));
if(aggressive){
argList.add("minid=.85");
argList.add("maxindel=8");
argList.add("minhits="+1);
argList.add("bw=26");
argList.add("bwr=0.22");
argList.add("build=2");
argList.add("tipsearch="+2);
}else{
argList.add("minid=.95");
argList.add("idfilter=.95");
argList.add("maxindel=3");
argList.add("minhits="+2);
argList.add("bw=12");
argList.add("bwr=0.16");
argList.add("fast="+true);
argList.add("maxsites2=10");
argList.add("build="+commonMicrobesBuild);
argList.add("tipsearch="+0);
}
//Set read I/O files
if(in1!=null){argList.add("in1="+inPre+in1);}
if(in2!=null){argList.add("in2="+inPre+in2);}
if(out1!=null){argList.add("outu1="+outPre+out1);}
if(out2!=null){argList.add("outu2="+outPre+out2);}
if(outbad!=null){argList.add("outm="+outbad);}
if(scafstats!=null){argList.add("scafstats="+scafstats);}
// assert(false) : scafstats+", "+microbeStatsFile;
}
String[] args=argList.toArray(new String[0]);
if(!dryrun){//Run BBMap
try {
BBMap.main(args);
final long lastReadsIn=BBMap.lastReadsIn;
final long lastEitherMapped=BBMap.lastEitherMapped;
final long lastReadsOut=lastReadsIn-lastEitherMapped;
final long lastBasesIn=BBMap.lastBasesIn;
final long lastEitherMappedBases=BBMap.lastEitherMappedBases;
final long lastBasesOut=lastBasesIn-lastEitherMappedBases;
if(filterstats.readsIn>0){
assert(lastReadsIn==filterstats.readsOut) : lastReadsIn+", "+filterstats.readsOut;
assert(lastBasesIn==filterstats.basesOut) : lastBasesIn+", "+filterstats.basesOut;
}
filterstats.readsMicrobe=lastEitherMapped;
filterstats.basesMicrobe=lastEitherMappedBases;
if(filterstats.readsIn<1){
filterstats.readsIn=lastReadsIn;
filterstats.basesIn=lastBasesIn;
}
filterstats.readsOut=lastReadsOut;
filterstats.basesOut=lastBasesOut;
assert(filterstats.toString()!=null); //123
outstream.println(format("Microbial Sequence Removed:", lastReadsIn, lastReadsOut,
lastBasesIn, lastBasesOut));
log("#Input:\t"+lastReadsIn+" reads\t"+lastReadsOut+" bases", true, false);
log("#Remaining:\t"+lastBasesIn+" reads\t"+lastBasesOut+" bases", true, false);
} catch (Exception e) {
e.printStackTrace();
log("failed", true);
System.exit(1);
}
}
//Clear the index
Data.unloadAll();
//Unset NODISK
RefToIndex.NODISK=false;
if(reproduceName!=null){
writeReproduceFile(reproduceName, "bbmap.sh", args);
}
if(ref!=null && !ref.equals(commonMicrobesRef)){delete(null, ref);}
log("removeCommonMicrobes finish", true);
}
/**
* Runs BBMap to perform:
* Arbitrary contaminant removal.
*
* @param in1 Primary input reads file (required)
* @param in2 Secondary input reads file
* @param out1 Primary output reads file (required)
* @param out2 Secondary output reads file
* @param inPrefix Append this prefix to input filenames
* @param outPrefix Append this prefix to output filenames
*/
private void decontamByMapping(String in1, String in2, String out1, String out2, String outbad, String scafstats, String inPrefix, String outPrefix,
String ref, int stepNum, boolean addToOtherStats){
log("decontamByMapping_"+ref+" start", true);
assert(ref!=null) : "Reference was null.";
ArrayList<String> argList=new ArrayList<String>();
final String inPre=(inPrefix==null ? "" : (tmpDir==null ? outDir : tmpDir)+inPrefix);
final String outPre=(outPrefix==null ? outDir : (tmpDir==null ? outDir : tmpDir)+outPrefix);
{
if(ordered){argList.add("ordered");}
argList.add("minratio=.9");
argList.add("maxindel=3");
argList.add("fast="+true);
argList.add("minhits="+2);
argList.add("tipsearch="+4);
argList.add("bw=12");
argList.add("bwr=0.16");
argList.add("quickmatch");
argList.add("k="+map_k);
argList.add("idtag=t");
// argList.add("usemodulo");
argList.add("printunmappedcount");
argList.add("ow="+overwrite);
if(trimUntrim){
argList.add("qtrim=rl");
argList.add("trimq=10");
argList.add("untrim");
}
argList.add("ef=0.03");
if(ref.startsWith("path=")){
argList.add(ref);
}else{
RefToIndex.NODISK=true;
argList.add("ref="+ref);
}
if(pigz!=null){argList.add("pigz="+pigz);}
if(unpigz!=null){argList.add("unpigz="+unpigz);}
argList.add("zl="+(zl==null ? ""+ReadWrite.ZIPLEVEL : zl));
// //Pass along uncaptured arguments
// for(String s : primaryArgList){argList.add(s);}
//Set read I/O files
if(in1!=null){argList.add("in1="+inPre+in1);}
if(in2!=null){argList.add("in2="+inPre+in2);}
if(out1!=null){argList.add("outu1="+outPre+out1);}
if(out2!=null){argList.add("outu2="+outPre+out2);}
if(outbad!=null){argList.add("outm="+outbad);}
if(scafstats!=null){argList.add("scafstats="+scafstats);}
// assert(false) : scafstats+", "+microbeStatsFile;
}
String[] args=argList.toArray(new String[0]);
if(!dryrun){//Run BBMap
try {
BBMap.main(args);
long lastReadsIn=BBMap.lastReadsIn;
long lastEitherMapped=BBMap.lastEitherMapped;
long lastReadsOut=lastReadsIn-lastEitherMapped;
long lastBasesIn=BBMap.lastBasesIn;
long lastEitherMappedBases=BBMap.lastEitherMappedBases;
long lastBasesOut=lastBasesIn-lastEitherMappedBases;
outstream.println(format("Other Contam Sequence Removed:", lastReadsIn, lastReadsOut,
lastBasesIn, lastBasesOut));
log("#Input:\t"+lastReadsIn+" reads\t"+lastBasesIn+" bases", true, false);
log("#Remaining:\t"+lastReadsOut+" reads\t"+lastBasesOut+" bases", true, false);
// System.err.println(filterstats.toString()); //123
//
// System.err.println(
// lastReadsIn+", "+lastEitherMapped+", "+lastReadsOut+"\n"
// +lastBasesIn+", "+lastEitherMappedBases+", "+lastBasesOut
// );
if(addToOtherStats){
filterstats.readsOther+=lastEitherMapped;
filterstats.basesOther+=lastEitherMappedBases;
}
if(filterstats.readsIn<1){
filterstats.readsIn=lastReadsIn;
filterstats.basesIn=lastBasesIn;
}
filterstats.readsOut=lastReadsOut;
filterstats.basesOut=lastBasesOut;
assert(!addToOtherStats || filterstats.toString()!=null); //123
} catch (Exception e) {
e.printStackTrace();
log("failed", true);
System.exit(1);
}
}
//Clear the index
Data.unloadAll();
//Unset NODISK
RefToIndex.NODISK=false;
if(reproduceName!=null){
writeReproduceFile(reproduceName, "bbmap.sh", args);
}
//Optionally append files to file list here
log("decontamByMapping_"+ref+" finish", true);
}
private boolean runSketch(String in1, String outFname, String outPrefix){
final String outPre=(outPrefix==null ? outDir : outDir+outPrefix);
final String fname=outPre+outFname;
boolean success=false;
String[] split=new String[] {"nt"};
if(sketchDB!=null){split=sketchDB.split(",");}
for(int i=0; i<split.length; i++){
success=(runSketch_inner(in1, fname, split[i], i>0))|success;
}
return success;
}
private boolean runSketch_inner(String in, String fname, String db, boolean append){
SketchObject.reset();
ArrayList<String> argList=new ArrayList<String>();
String name=in;
try {
if(taxList!=null){
TaxTree tree=TaxTree.loadTaxTree(taxTreeFile, outstream, true, false);
TaxNode tn=tree.parseNodeFromHeader(taxList.split(",")[0], true);
if(tn!=null){name=tn.name;}
}
} catch (Exception e1) {}
argList.add("in="+in);
argList.add("out="+fname);
argList.add("reads="+sketchReads);
argList.add("name="+name);
argList.add("fname="+in1);
if(sketchMinProb!=null){argList.add("minprob="+sketchMinProb);}
if(sketchSamplerate!=null){argList.add("samplerate="+sketchSamplerate);}
if(sketchMerge){argList.add("merge");}
argList.add("printname0=f");
argList.add("records=20");
argList.add("color=false");
argList.add("depth");
argList.add("depth2");
argList.add("unique2");
argList.add("volume");
argList.add("sortbyvolume");
argList.add("contam2=genus");
argList.add(db);
if("silva".equalsIgnoreCase(db)){
if(SILVA_LOCAL){argList.add("local");}
argList.add("minkeycount=2");
}
if(append){argList.add("append");} //True because db name gets written first.
else{argList.add("ow");}
String[] argArray=argList.toArray(new String[0]);
if(reproduceName!=null){
writeReproduceFile(reproduceName, "sendsketch.sh", argArray);
}
try {
// ReadWrite.writeString("DB:\t"+db, fname, append); //Already printed in query header
if(!dryrun){SendSketch.main(argArray);}
return true;
} catch (Throwable e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}
}
/**
* Runs BBMerge to generate an insert size histogram.
*
* @param in1 Primary input reads file (required)
* @param in2 Secondary input reads file
* @param prefix Append this prefix to input filenames
*/
private void merge(String in1, String in2, String prefix){
log("merge start", true);
ArrayList<String> argList=new ArrayList<String>();
final String inPre=(prefix==null ? outDir : (tmpDir==null ? outDir : tmpDir)+prefix);
if(extendFlagAuto){
final long cardinality=LogLog.lastCardinality;
final long capacity=kmerCapacity(20, true);
outstream.println("cardinality="+cardinality+", capacity="+capacity);
extendFlag=(cardinality>0 && cardinality*2<capacity);
}
{//Fill list with BBMerge arguments
if(mergeStrictness!=null){argList.add(mergeStrictness);}
argList.add("overwrite="+overwrite);
//Set read I/O files
if(in1!=null){argList.add("in1="+inPre+in1);}
if(in2!=null){argList.add("in2="+inPre+in2);}
if(ihistName!=null){argList.add("ihist="+ihistName);}
if(cardinalityName!=null){argList.add("outc="+cardinalityName);}
if(pigz!=null){argList.add("pigz="+pigz);}
if(unpigz!=null){argList.add("unpigz="+unpigz);}
argList.add("zl="+(zl==null ? ""+ReadWrite.ZIPLEVEL : zl));
if(discoveredAdaptersValid){argList.add("adapters="+adaptersOutFile);}
else if(fragAdapter!=null){argList.add("adapters="+fragAdapter);}
argList.add("mininsert=25");
if(extendFlag){
argList.add("ecct");
// argList.add("extend2=20");
// argList.add("iterations=10");
argList.add("extend2=100");
argList.add("rem");
argList.add("k=62");
argList.add("prefilter");
argList.add("prealloc");
System.gc();
}
argList.add("loglog");
}
String[] mergeargs=argList.toArray(new String[0]);
if(reproduceName!=null){
writeReproduceFile(reproduceName, "bbmerge.sh", mergeargs);
}
if(!dryrun){//run BBMerge
final boolean OLD_FORCE_INT=FASTQ.FORCE_INTERLEAVED, OLD_TEST_INT=FASTQ.TEST_INTERLEAVED;
BBMerge merger=new BBMerge(mergeargs);
try {
merger.process();
log("#Input:\t"+(merger.readsProcessedTotal*2)+" reads\t"+merger.basesProcessedTotal+" bases\t"+merger.loglog.cardinality()+" kmers", true, false);
log("#Remaining:\t"+(merger.readsProcessedTotal*2)+" reads\t"+merger.basesProcessedTotal+" bases\t"+merger.loglog.cardinality()+" kmers", true, false);
} catch (Exception e) {
e.printStackTrace();
log("failed", true);
System.exit(1);
}
FASTQ.FORCE_INTERLEAVED=OLD_FORCE_INT;
FASTQ.TEST_INTERLEAVED=OLD_TEST_INT;
}
//Optionally append files to file list here
log("merge finish", true);
}
/**
* Runs BBNorm or KmerCountExact to generate a kmer frequency histogram.
*
* @param in1 Primary input reads file (required)
* @param in2 Secondary input reads file
* @param prefix Append this prefix to input filenames
*/
private void khist(String in1, String in2, String prefix){
log("khist start", true);
ArrayList<String> argList=new ArrayList<String>();
final String inPre=(prefix==null ? outDir : (tmpDir==null ? outDir : tmpDir)+prefix);
final long cardinality=LogLog.lastCardinality;
final long capacity=kmerCapacity(12, true);
outstream.println("cardinality="+cardinality+", capacity="+capacity);
if(cardinality<1 || cardinality*1.5>capacity){ //Too many kmers for exact counts; use BBNorm
{//Fill list with BBNorm arguments
argList.add("overwrite="+overwrite);
//Set read I/O files
if(in1!=null){argList.add("in1="+inPre+in1);}
if(in2!=null){argList.add("in2="+inPre+in2);}
if(khistName!=null){argList.add("khist="+khistName);}
if(peaksName!=null){argList.add("peaks="+peaksName);}
if(unpigz!=null){argList.add("unpigz="+unpigz);}
argList.add("keepall");
argList.add("prefilter");
argList.add("passes=1");
argList.add("bits=16");
argList.add("minprob=0");
argList.add("minqual=0");
argList.add("histcolumns=2");
}
String[] khistargs=argList.toArray(new String[0]);
if(reproduceName!=null){
writeReproduceFile(reproduceName, "khist.sh", khistargs);
}
if(!dryrun){//run KmerNormalize
try {
KmerNormalize.main(khistargs);
} catch (Exception e) {
e.printStackTrace();
log("failed", true);
System.exit(1);
}
}
}else{
{//Fill list with KmerCountExact arguments
argList.add("overwrite="+overwrite);
//Set read I/O files
if(in1!=null){argList.add("in1="+inPre+in1);}
if(in2!=null){argList.add("in2="+inPre+in2);}
if(khistName!=null){argList.add("khist="+khistName);}
if(peaksName!=null){argList.add("peaks="+peaksName);}
if(unpigz!=null){argList.add("unpigz="+unpigz);}
argList.add("gchist");
if(cardinality*4>capacity){
argList.add("prealloc");
}
}
String[] khistargs=argList.toArray(new String[0]);
if(reproduceName!=null){
writeReproduceFile(reproduceName, "kmercountexact.sh", khistargs);
}
if(!dryrun){//run KmerCountExact
try {
KmerCountExact.main(khistargs);
} catch (Exception e) {
e.printStackTrace();
log("failed", true);
System.exit(1);
}
}
}
//Optionally append files to file list here
log("khist finish", true);
}
private static long kmerCapacity(int bytesPerKmer, boolean prealloc){
System.gc();
long memory=Runtime.getRuntime().maxMemory();
double xmsRatio=Shared.xmsRatio();
long usableMemory=(long)Tools.max(((memory-96000000)*(xmsRatio>0.97 ? 0.82 : 0.72)), memory*0.45);
long tableMemory=(long)(usableMemory*.95);
long estimatedKmerCapacity=(long)((tableMemory*1.0/bytesPerKmer)*(prealloc ? 0.9 : 0.6));
return estimatedKmerCapacity;
}
/*--------------------------------------------------------------*/
/*---------------- Helper Methods ----------------*/
/*--------------------------------------------------------------*/
/** Note - Seung-jin needs to be notified when new calls are added. */
private void log(String message, boolean append){log(message, append, true);}
/**
* Log a message in the log file
* @param message Message to log
* @param append True to append, false to overwrite
*/
private void log(String message, boolean append, boolean printTime){
if(logName!=null){
ReadWrite.writeString(message+(printTime ? ", "+timeString() : "")+"\n", logName, append);
}
}
/**
* Delete all non-null filenames.
* @param prefix Append this prefix to filenames before attempting to delete them
* @param names Filenames to delete
*/
private void delete(String prefix, String...names){
if(!deleteTemp){return;}
log("delete temp files start", true);
if(names!=null){
final String pre=(prefix==null ? "" : (tmpDir==null ? outDir : tmpDir)+prefix);
for(String s : names){
if(s!=null){
s=pre+s;
if(verbose){outstream.println("Trying to delete "+s);}
File f=new File(s);
if(f.exists() || dryrun){
if(!dryrun){f.delete();}
writeReproduceFile(reproduceName, "rm", new String[] {s});
}
}
}
}
log("delete temp files finish", true);
}
/**
* @return String of symbols indicating which processes were applied to the input reads
*/
private String abbreviation(){
StringBuilder sb=new StringBuilder();
if(mainArtifactFile!=null){sb.append("a");}
if(maxNs>=0){sb.append("n");}
// if(qtrim!=null && !qtrim.equalsIgnoreCase("f") && !qtrim.equalsIgnoreCase("false")){sb.append("q");}
if(minAvgQuality>0){sb.append("q");}
if(rnaArtifactFlag){sb.append("r");}
if(dnaArtifactFlag){sb.append("d");}
if(libType==CLIP){sb.append("c");}
else if(libType==LFPE){sb.append("l");}
else if(libType==CLRS){sb.append("s");}
if(phixFlag){sb.append("p");}
if(humanFlag || mouseCatDogHumanFlag){sb.append("h");}
// if(ktrimFlag){sb.append("k");}
// if(doTrim){sb.append("k");}
// if(qtrimFlag){sb.append("t");}
if(doAdapterTrim || qtrimFlag){sb.append("t");}
return sb.toString();
}
/*--------------------------------------------------------------*/
/*---------------- Static Methods ----------------*/
/*--------------------------------------------------------------*/
/**
* TODO: Some machines are set to UTC rather than PST
* @return Timestamp in RQC's format
*/
public static String timeString(){
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
// sdf.setTimeZone(TimeZone.getTimeZone("PST"));
sdf.setTimeZone(TimeZone.getDefault());
return sdf.format(new Date());
}
public static String stripDirs(String fname){
return ReadWrite.stripPath(fname);
}
/**
* Set permissions on these files to 777
* @param names List of filenames
*/
private static void setPermissions(String...names){
if(names==null){return;}
for(String name : names){
if(name!=null && name.trim().length()>0 && new File(name).exists()){
ReadWrite.setPermissions(name, true, true, true, false);
}
}
}
/**
* Writes a single command to the reproduce file
* @param fname Filename to write, including path
* @param command Command to add to file
* @param args Arguments to the command
*/
private static void writeReproduceFile(String fname, String command, String[] args){
StringBuilder sb=new StringBuilder();
sb.append('\n');
sb.append(command);
if(args!=null){
for(String s : args){
sb.append(' ').append(s);
}
}
sb.append('\n');
ReadWrite.writeString(sb, fname, true);
}
/**
* Writes the header for the reproduce file
* @param fname Filename to write, including path
* @param command Command to add to file
* @param args Arguments to the command
* @param overwrite Permission to overwrite
*/
private static void writeReproduceHeader(String fname, String[] args, boolean overwrite){
StringBuilder sb=new StringBuilder();
boolean b=Tools.canWrite(fname, overwrite);
assert(b) : "Can't write to "+fname;
sb.append("#!/bin/bash\n");
sb.append("#BBTools version "+Shared.BBMAP_VERSION_STRING+"\n");
sb.append("#The steps below recapitulate the output of RQCFilter2 when run like this:\n");
sb.append("#rqcfilter2.sh");
if(args!=null){
for(String s : args){
sb.append(' ').append(s);
}
}
sb.append('\n');
sb.append("#Data dependencies are available at http://portal.nersc.gov/dna/microbial/assembly/bushnell/RQCFilterData.tar");
sb.append('\n');
sb.append('\n');
ReadWrite.writeString(sb, fname, false);
}
/**
* @param s String representation of library type
* @return Numeric code for library type
*/
private static int toLibType(String s){
if(s==null){return FRAG;}
s=s.trim().toLowerCase();
if(s.equals("lfpe")){return LFPE;}
if(s.equals("clip")){return CLIP;}
if(s.equals("clrs")){return CLRS;}
if(s.equals("frag") || s.equals("fragment")){return FRAG;}
throw new RuntimeException("Unknown library type "+s);
}
/*--------------------------------------------------------------*/
/*---------------- Fields ----------------*/
/*--------------------------------------------------------------*/
/** Screen output */
private static PrintStream outstream=System.err;
/** Synthetic contaminant filtering */
private final boolean doFilter;
/** Forcibly override synthetic contaminant filtering */
private boolean skipFilter=false;
/** Spikein filtering */
private final boolean doSpikein;
/** Clumpify */
private boolean doClump=false;
/** FilterByTile */
private boolean doFilterByTile=false;
/** Adapter-trimming */
private final boolean doAdapterTrim;
/** Run BBMerge for insert size calculation */
private final boolean doMerge;
/** Run KmerNormalize for kmer histogram generation */
private boolean doKhist=false;
/** Do NexteraLMP splitting */
private final boolean doNexteraLMP;
/** Symbols to insert in output filename to denote operations performed */
private final String symbols;
/** Name of raw input file, minus directory and file extension */
private final String rawName;
/** Type of library; controls processing methods and references to use */
private int libType=FRAG;
/** Legacy; affects output file name */
private boolean rnaArtifactFlag=false;
/** Legacy; affects output file name */
private boolean dnaArtifactFlag=true;
/** True if phix should be filtered out */
private boolean phixFlag=true;
/** True if Lambda should be filtered out by kmer-matching */
private boolean lambdaFlag=true;
/** True if pjet should be filtered out */
private boolean pjetFlag=true;
/** True if poly-A tails should be right-trimmed */
private boolean trimPolyA=false;//TODO
/** True if poly-A should be filtered out */
private boolean filterPolyA=false;
/** Positive if poly-G should be left-trimmed during filter1 */
public int trimPolyGLeft=0;
/** Positive if poly-G should be right-trimmed during filter1 */
public int trimPolyGRight=0;
/** Positive if poly-G prefixes should be filtered during filter1 */
public int filterPolyG=0;
/** True if mtst should be quantified and filtered out */
private boolean mtstFlag=false;
/** True if kapa should be quantified and filtered out */
private boolean kapaFlag=true;
/** Enables tbo during adapter trimming */
private boolean tboFlag=true;
/** Enables tpe during adapter trimming */
private boolean tpeFlag=true;
/** Unused */
private String jointSeq=null;
/** Toss reads shorter than this */
private int minLen=25;
/** Toss reads shorter than this fraction of initial length, after trimming */
private float minLenFraction=0.333f;
/** Trim bases at this quality or below */
private float trimq=10;
/** Throw away reads below this average quality after trimming. Default: 5 */
private float minAvgQuality=5;
/** If positive, calculate the average quality from the first X bases. */
private int minAvgQualityBases=0;
/** Trim reads to be equal to 0 modulo this value. Mainly for 151, 251, and 301bp runs. */
private int forceTrimModulo=5;
/** Quality-trimming mode */
private String qtrim="f";//"rl";
/** Kmer-trimming mode */
private String ktrim="r";
/** Kmer length to use for filtering */
private int filter_k=31;
/** Kmer length to use for trimming */
private int trim_k=23;
/** Kmer length to use for normalization and error-correction */
private int normalize_k=31;
/** Kmer length to use for mapping */
private int map_k=14;
/** Shortest kmer to use for trimming */
private int mink=11;
/** Throw away reads containing more than this many Ns. Default: 0 (toss reads with any Ns) */
private int maxNs=0;
/** Use this Hamming distance when kmer filtering */
private int hdist_filter=1;
/** Use this query Hamming distance when kmer filtering */
private int qhdist_filter=0;
/** Use this Hamming distance when kmer trimming */
private int hdist_trim=1;
/** Use this Hamming distance when kmer trimming with short kmers */
private int hdist2_trim=-1;
/** Use this Hamming distance when kmer trimming with short kmers */
private int hdist_ribo=0;
/** Use this Hamming distance when kmer trimming with short kmers */
private int edist_ribo=0;
/** Kmer length to use for filtering spikeins */
private int spikein_k=31;
/** Use this Hamming distance when kmer filtering spikeins */
private int hdist_spikein=0;
/** Force-trim left during filter1 stage */
private int ftl=-1;
/** Force-trim right during filter1 stage */
private int ftr=-1;
/** Force-trim right 2 during filter1 stage */
private int ftr2=-1;
/** Merge strictness: strict, normal, loose, vloose */
private String mergeStrictness="loose";
/** Trim Truseq and Nextera adapters from right side of reads */
private boolean fragAdapterFlag=true;
/** Trim Truseq-RNA adapters from right side of reads */
private boolean rnaAdapterFlag=false;
/** Trim 1bp from right side after adapter-trimming/ */
private boolean bisulfite=false;
/** Performed quality-trimming on reads */
private boolean qtrimFlag=false;
/** Performed kmer-trimming on reads */
private boolean ktrimFlag=false;
/** Performed nextera splitting on reads */
private boolean splitNexteraFlag=false;
/*--------------------------------------------------------------*/
/*---------------- Mapping Fields ----------------*/
/*--------------------------------------------------------------*/
/** Remove reads mapping to human with high identity */
private boolean humanFlag=false;
/** Remove reads mapping to dog with high identity */
private boolean dogFlag=false;
/** Remove reads mapping to cat with high identity */
private boolean catFlag=false;
/** Remove reads mapping to mouse with high identity */
private boolean mouseFlag=false;
/** Remove mouse, cat, dog, and human reads at the same time with BBSplit. */
private boolean mouseCatDogHumanFlag=false;
/** Perform cat, dog, mouse, and human removal aggressively, using unmasked genomes. */
private boolean aggressiveHumanFlag=false;
/** Report, but do not remove, cat/dog/mouse/human sequence */
private boolean keepHumanReads=false;
/** Perform microbe removal aggressively, using unmasked genomes. */
private boolean aggressiveMicrobeFlag=false;
/** Remove reads from common microbial contaminants with BBMap */
private boolean removeCommonMicrobeFlag=false;
/** Detect but do not remove reads from common microbial contaminants with BBMap */
private boolean detectMicrobeFlag=false;
/** Detect but do not remove reads from other microbial contaminants with BBMap */
private boolean otherMicrobeFlag=false;
/** Screen reads with a Bloom filter prior to mapping */
private boolean bloomFilter=true;
/** Bloom filter kmer length */
private int bloomFilterK=29;
/** Bloom filter hashes per kmer */
private int bloomFilterHashes=1;
/** Min consecutive hits to consider a read as matching */
private int bloomFilterMinHits=6;
/** Don't use Bloom filter for libraries under this size */
private long minReadsToBloomFilter=4000000;
/** Use the serialized Bloom filter */
private boolean bloomSerial=true;
private boolean trimUntrim=true;
/*--------------------------------------------------------------*/
/*---------------- BBMerge ----------------*/
/*--------------------------------------------------------------*/
/** Use BBMerge to determine the adapter sequence, and use that instead of the default adapters */
private boolean discoverAdaptersFlag=true;
/** True if it looks like the discovered adapters are usable */
private boolean discoveredAdaptersValid=false;
/** Extend reads to merge longer inserts */
private boolean extendFlag=false;
/** Set extendFlag based on the number of unique kmers */
private boolean extendFlagAuto=true;
/*--------------------------------------------------------------*/
/*---------------- Mito Ribo Chloro ----------------*/
/*--------------------------------------------------------------*/
/** Remove ribosomal reads via kmer-matching */
private boolean riboKmerFlag=false;
/** Remove reads from specific ribosomal sequence with BBMap */
private boolean riboMapFlag=false;
/** Remove reads from specific chloroplast sequence with BBMap */
private boolean chloroMapFlag=false;
/** Remove reads from specific mitochondrial sequence with BBMap */
private boolean mitoMapFlag=false;
/*--------------------------------------------------------------*/
/*---------------- Sketch ----------------*/
/*--------------------------------------------------------------*/
/** Query the sketch server */
private boolean sketchFlag=true;
/** Use local flag for Silva */
private boolean SILVA_LOCAL=true;
/** Sketch server to query */
private String sketchDB="nt,refseq,silva";
/** Estimate kmer cardinality */
private boolean doCardinality=true;
private boolean verbose=false;
private boolean overwrite=true;
private boolean compress=true;
private boolean copyUndefined=false;
/** Write temp files to $TMPDIR (localdisk) */
private boolean writeTempToTmpdir=true;
/** Captures the command line "pigz" flag */
private String pigz="t";
/** Captures the command line "unpigz" flag */
private String unpigz="t";
/** Captures the command line "zl" flag */
private String zl;
/** Mode for processing chastity flag in Illumina read names */
private String chastityfilter="t";
/** Consider the absence of a barcode to mean failure */
private String failnobarcode=null;
/** May be set to true, false, or crash to determine how to handle reads with no barcode */
private String barcodefilter="crash";
/** An optional list of literal barcodes that are allowed */
private String barcodes=null;
/** Arguments to pass to BBDuk */
private ArrayList<String> primaryArgList=new ArrayList<String>();
/** References to pass to BBDuk for artifact removal */
private ArrayList<String> bbdukFilterRefs=new ArrayList<String>();
/** References to pass to Seal for spikein removal */
private ArrayList<String> spikeinRefs=new ArrayList<String>();
/** References to pass to BBMap for contaminant removal */
private ArrayList<String> mappingRefs=new ArrayList<String>();
/** List of taxa to NOT map against */
private String taxList=null;
/** Taxonomic level for filtering */
private String taxLevel="order";
/** Only needed if there are gi numbers in the references */
private boolean loadGiTable=false;
/** Number of reads used for SendSketch */
private int sketchReads=2000000;
private String sketchMinProb="0.2";
private String sketchSamplerate="1.0";
private boolean sketchMerge=true;
private boolean entropyFilter=false;
private double minEntropy=0.42;
private int entropyk=2;
private int entropywindow=40;
/*--------------------------------------------------------------*/
/*---------- Clumpify Deduplication Parameters ----------*/
/*--------------------------------------------------------------*/
private boolean removeDuplicates=false;
private boolean removeAllDuplicates=false;
private boolean removeOpticalDuplicates=false;
private boolean removeEdgeDuplicates=false;
private int duplicatePasses=1;
private int duplicateSubs=-1;
private int duplicateDist=-1;
private boolean lowComplexity=false;
private int clumpifyGroups=-1;
private boolean clumpifyTmpdir=false;
/*--------------------------------------------------------------*/
/*---------------- Read Data Files ----------------*/
/*--------------------------------------------------------------*/
private final String tempSalt;
private final String clumpPrefix;
private final String fbtPrefix;
private final String trimPrefix;
private final String humanPrefix;
private final String spikeinPrefix;
private final String filterPrefix1;
private final String filterPrefix2;
private final String taxaPrefix;
private final String microbePrefix;
private final String riboPrefix;
private final String chloroPrefix;
private final String[] mappingPrefix;
/** Directory in which to write all files */
private String outDir="";
/** Directory in which to write all temp files */
private String tmpDir=Shared.tmpdir();
/** Primary input reads file (required) */
private String in1=null;
/** Secondary input reads file */
private String in2=null;
/** Primary output reads file (required) */
private String out1=null;
/** Secondary output reads file */
private String out2=null;
private boolean deleteTemp=true;
private boolean ordered=false;
private boolean dryrun=false;
/*--------------------------------------------------------------*/
/*---------------- Separated Reads ----------------*/
/*--------------------------------------------------------------*/
private String riboOutFile="ribo.fq.gz";
private String fbtOutFile="filteredByTile.fq.gz";
private String chloroOutFile="chloro.fq.gz";
private String humanOutFile="human.fq.gz";
private String spikeinOutFile="spikein.fq.gz";
private String synthOutFile1="synth1.fq.gz";
private String synthOutFile2="synth2.fq.gz";
private String microbeOutFile="microbes.fq.gz";
/*--------------------------------------------------------------*/
/*---------------- Log Files ----------------*/
/*--------------------------------------------------------------*/
private RQCFilterStats filterstats=new RQCFilterStats();
private String logName="status.log";
private String reproduceName="reproduce.sh";
private String fileListName="file-list.txt";
private String rqcStatsName="filterStats.txt";
private String rqcStatsName2="filterStats2.txt";
private String kmerStatsName1="kmerStats1.txt";
private String kmerStatsName2="kmerStats2.txt";
private String scaffoldStatsName1="scaffoldStats1.txt";
private String scaffoldStatsName2="scaffoldStats2.txt";
private String scaffoldStatsNameSpikein="scaffoldStatsSpikein.txt";
private String refStatsName="refStats.txt";
private String microbeStatsFile="commonMicrobes.txt";
private String microbeStats2File="otherMicrobes.txt";
private String adaptersOutFile="adaptersDetected.fa";
private String microbesUsed="microbesUsed.txt";
private String chloroStatsFile="chloroStats.txt";
private String nexteraStats="nexteraStats.txt";
private String ihistName="ihist_merge.txt";
private String khistName="khist.txt";
private String peaksName="peaks.txt";
private String phistName="phist.txt";
private String qhistName="qhist.txt";
private String bhistName="bhist.txt";
private String gchistName="gchist.txt";
private String sketchName="sketch.txt";
private String cardinalityName="cardinality.txt";
/** ktrim phase rqc stats file */
private String rqcStatsName_kt;
/** ktrim phase stats file */
private String kmerStatsName_kt;
/** ktrim phase scaffold stats file */
private String scaffoldStatsName_kt;
/*--------------------------------------------------------------*/
/*---------------- Reference Files ----------------*/
/*--------------------------------------------------------------*/
//TODO: Need to be backed up to tape
private void fixReferencePaths(){
if(RQCFilterData==null){RQCFilterData=".";}
shortArtifactFile=fixPath(shortArtifactFile);
mainArtifactFile=fixPath(mainArtifactFile);
polyAFile=fixPath(polyAFile);
nexteraLinkerFile=fixPath(nexteraLinkerFile);
phixRef=fixPath(phixRef);
lambdaRef=fixPath(lambdaRef);
lfpeLinker=fixPath(lfpeLinker);
clrsLinker=fixPath(clrsLinker);
pjetRef=fixPath(pjetRef);
riboKmers=fixPath(riboKmers);
fragAdapter=fixPath(fragAdapter);
rnaAdapter=fixPath(rnaAdapter);
mtstRef=fixPath(mtstRef);
kapaRef=fixPath(kapaRef);
humanPath=fixPath(humanPath);
catPath=fixPath(catPath);
dogPath=fixPath(dogPath);
mousePath=fixPath(mousePath);
mouseCatDogHumanPath=fixPath(mouseCatDogHumanPath);
humanRef=fixPath(humanRef);
chloroplastRef=fixPath(chloroplastRef);
mitoRef=fixPath(mitoRef);
chloroMitoRef=fixPath(chloroMitoRef);
chloroMitoRiboRef=fixPath(chloroMitoRiboRef);
mitoRiboRef=fixPath(mitoRiboRef);
chloroRiboRef=fixPath(chloroRiboRef);
riboRef=fixPath(riboRef);
commonMicrobesPath=fixPath(commonMicrobesPath);
commonMicrobesRef=fixPath(commonMicrobesRef);
otherMicrobesPath=fixPath(otherMicrobesPath);
otherMicrobesRef=fixPath(otherMicrobesRef);
taxTreeFile=fixPath(taxTreeFile);
}
private String fixPath(String s){
if(s==null){return null;}
s=s.replaceAll("RQCFILTER_PATH", RQCFilterData);
File f=new File(s);
assert(f.exists() && f.canRead()) : "Cannot read file "+s+"\nPlease be sure RQCFilterData is set correctly.";
return s;
}
private String RQCFilterData="/global/projectb/sandbox/gaag/bbtools/RQCFilterData_Local";
private String shortArtifactFile = "RQCFILTER_PATH/short.fa.gz";
private String mainArtifactFile = "RQCFILTER_PATH/Illumina.artifacts.fa.gz";
private String polyAFile = "RQCFILTER_PATH/polyA.fa.gz";
private String nexteraLinkerFile = "RQCFILTER_PATH/nextera_LMP_linker.fa.gz";
private String phixRef = "RQCFILTER_PATH/phix174_ill.ref.fa.gz";
private String lambdaRef = "RQCFILTER_PATH/lambda.fa.gz";
private String lfpeLinker = "RQCFILTER_PATH/lfpe.linker.fa.gz";
private String clrsLinker = "RQCFILTER_PATH/crelox.fa.gz";
private String clipLinker = clipLinkerDefault; //A literal string; "CATG" is supposed to be the normal linker.
private String pjetRef = "RQCFILTER_PATH/pJET1.2.fa.gz";
private String riboKmers = "RQCFILTER_PATH/riboKmers20fused.fa.gz";
private String fragAdapter = "RQCFILTER_PATH/adapters2.fa.gz";
private String rnaAdapter = "RQCFILTER_PATH/truseq_rna.fa.gz";
private String mtstRef = "RQCFILTER_PATH/mtst.fa.gz";
private String kapaRef = "RQCFILTER_PATH/kapatags.L40.fa.gz";
private String humanPath = "RQCFILTER_PATH/human_genome/";
private String catPath = "RQCFILTER_PATH/cat_genome/";
private String dogPath = "RQCFILTER_PATH/dog_genome/";
private String mousePath = "RQCFILTER_PATH/mouse_genome/";
private String mouseCatDogHumanPath = "RQCFILTER_PATH/mousecatdoghuman/";
private String humanRef = null;
private String chloroplastRef = "RQCFILTER_PATH/plastid.fa.gz";
private String mitoRef = "RQCFILTER_PATH/mitochondrion.fa.gz";
private String chloroMitoRef = "RQCFILTER_PATH/chloro_mito.fa.gz";
private String chloroMitoRiboRef = "RQCFILTER_PATH/chloro_mito_ribo.fa.gz";
private String mitoRiboRef = "RQCFILTER_PATH/mito_ribo.fa.gz";
private String chloroRiboRef = "RQCFILTER_PATH/chloro_ribo.fa.gz";
private String riboRef = "RQCFILTER_PATH/SSU_LSU_sorted.fa.gz";
private String commonMicrobesPath = "RQCFILTER_PATH/commonMicrobes/";
private String commonMicrobesRef = "RQCFILTER_PATH/commonMicrobes/fusedERPBBmasked2.fa.gz";
private int commonMicrobesBuild = 1;
private String otherMicrobesPath = "RQCFILTER_PATH/otherMicrobes/"; //TODO
private String otherMicrobesRef = "RQCFILTER_PATH/otherMicrobes/fusedEmasked.fa.gz"; //TODO
private int otherMicrobesBuild = 1;
private String taxTreeFile="RQCFILTER_PATH/tree.taxtree.gz";
private String giTable=null;
/*--------------------------------------------------------------*/
/*---------------- Constants ----------------*/
/*--------------------------------------------------------------*/
/** Library type codes */
private static final int FRAG=0, LFPE=1, CLIP=2, CLRS=3;
private static final String clipLinkerDefault = "CATG";
}
|
[
"[email protected]"
] | |
7c84c0d5ee9e7cc0a11e0b4bd25a7d1d88fb21c4
|
3be3364e60a5409ec2e43c859e7a5c49e7120e07
|
/app/src/main/java/com/cedrox/goals/contracts/GoalContract.java
|
3132cf1ffda30499d8721e94f59ae56f573cd69e
|
[] |
no_license
|
oraymundo/Greepo
|
0e2cac1ac468978b5fce326bff60c24b89f7d546
|
7787c18a4282dc7dfdf9ab1c80df826974fdbdc9
|
refs/heads/master
| 2021-01-21T13:34:17.394554 | 2016-06-02T05:39:14 | 2016-06-02T05:39:14 | 50,391,912 | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 761 |
java
|
package com.cedrox.goals.contracts;
import android.provider.BaseColumns;
/**
* Created by edelarosaraymun on 1/10/16.
*/
public final class GoalContract {
public GoalContract() {}
public static abstract class GoalEntry implements BaseColumns {
public static final String TABLE_NAME = "goal";
public static final String COLUMN_NAME_ENTRY_ID = "goalid";
public static final String COLUMN_NAME_DESCRIPTION = "description";
public static final String COLUMN_NAME_STATUS = "status";
public static final String COLUMN_NAME_CREATIONDATE = "creationdate";
public static final String COLUMN_NAME_EXPECTEDDATE = "expecteddate";
public static final String COLUMN_NAME_FINALDATE = "finaldate";
}
}
|
[
"[email protected]"
] | |
eb0247ea5196634548813e29161214046d535287
|
3ae26b3a9507215517e6caebf9a1e43b862b8973
|
/src/ProjetoDiscPOO/CriarConexao.java
|
8179b15266560b3b5842e7917087dc1ccffe61de
|
[] |
no_license
|
nayron/projetoPooteste
|
e6e6c40616b18c1faaa8842e3d93f3616a73d681
|
cac447122695ebab67f6b51eb72e1cd4723eb8b5
|
refs/heads/master
| 2021-01-20T18:02:13.623196 | 2016-06-21T00:10:37 | 2016-06-21T00:10:37 | 61,589,001 | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 648 |
java
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package ProjetoDiscPOO;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import javax.swing.JOptionPane;
/**
*
* @author Nayron
*/
public class CriarConexao {
public static Connection getConexao() throws ClassNotFoundException, SQLException {
return DriverManager.getConnection("jdbc:mysql://localhost:3306/poo", "root", "abc123");
}
}
|
[
"[email protected]"
] | |
03e8334d988a28400bcce7f8b2a677dc046a2f47
|
563c6dae5141ee42174c95ff53852045e5de9b61
|
/20180504 SP4(validVSschedVSremot)/src/validation/lesson03p495/ConvServExample.java
|
5915fc5688953c7a4476fd0eb1c56a31dfd84226
|
[] |
no_license
|
VictorLeonidovich/SpringHibernateLessons
|
79510b5a569b0e43449b78328b047397d75106ec
|
54bd8408c9b0174c2a9e311885005578b52271e7
|
refs/heads/master
| 2020-04-01T14:19:10.990814 | 2018-10-16T13:41:55 | 2018-10-16T13:41:55 | 153,289,407 | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 1,349 |
java
|
package validation.lesson03p495;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.springframework.context.support.GenericXmlApplicationContext;
import org.springframework.core.convert.ConversionService;
public class ConvServExample {
public static void main(String[] args) {
GenericXmlApplicationContext ctx = new GenericXmlApplicationContext();
ctx.load("classpath:META-INF/validation/lesson03/app-context.xml");
ctx.refresh();
Contact chris = ctx.getBean("chris", Contact.class);
System.out.println("Chris info: " + chris);
ConversionService conversionService = ctx.getBean(ConversionService.class);
AnotherContact anotherContact = conversionService.convert(chris, AnotherContact.class);
System.out.println("AnotherContact info: " + anotherContact);
String[] stringArray = conversionService.convert("a,b,c", String[].class);
System.out.println("String array: " + stringArray[0] + stringArray[1] + stringArray[2]);
List<String> listString = new ArrayList<>();
listString.add("a");
listString.add("b");
listString.add("c");
Set<String> setString = conversionService.convert(listString, HashSet.class);
for (String string : setString) {
System.out.println("Set: " + string);
}
}
}
|
[
"[email protected]"
] | |
61212cc46731e34e278e69d24089275f6102c104
|
6d9a3eea499a04126de93af4923bfe85d25bb339
|
/src/main/java/com/jeecms/cms/entity/assist/CmsDirectiveTpl.java
|
430822cc0ed8ade3bf262ec4bf91aa1243fb57b5
|
[] |
no_license
|
lidong1665/jeecms
|
688cdc3ea22f54286ba0f0d4e6c7727047c63255
|
83c6111460dbfa4c85d08d1739d581c4f48fc0ce
|
refs/heads/master
| 2021-08-28T05:35:35.526058 | 2017-12-11T09:20:48 | 2017-12-11T09:20:48 | 113,838,016 | 1 | 0 | null | 2017-12-11T09:20:32 | 2017-12-11T09:20:32 | null |
UTF-8
|
Java
| false | false | 602 |
java
|
package com.jeecms.cms.entity.assist;
import com.jeecms.cms.entity.assist.base.BaseCmsDirectiveTpl;
public class CmsDirectiveTpl extends BaseCmsDirectiveTpl {
private static final long serialVersionUID = 1L;
/*[CONSTRUCTOR MARKER BEGIN]*/
public CmsDirectiveTpl () {
super();
}
/**
* Constructor for primary key
*/
public CmsDirectiveTpl (Integer id) {
super(id);
}
/**
* Constructor for required fields
*/
public CmsDirectiveTpl (
Integer id,
com.jeecms.core.entity.CmsUser user,
String name) {
super (
id,
user,
name);
}
/*[CONSTRUCTOR MARKER END]*/
}
|
[
"[email protected]"
] | |
318d2cb745dcc53183e386bd5a5d4e04268b9e15
|
3c8d47ac08daae1dd2f973acc1e2899b6e36cbd6
|
/crm-sales-app/src/main/java/org/xujin/crm/sales/interceptor/LoggerPostInterceptor.java
|
933df8a153147fb46d1ac0c5462f78667f7694b4
|
[
"Apache-2.0"
] |
permissive
|
nanaxumu/crm-sales
|
520e8f21b8efaee5f1e39c6ab4ba4137d9ebdabc
|
de7913ef027ff955c9370f49f0798b067e487ad1
|
refs/heads/main
| 2023-05-02T02:56:10.625915 | 2021-05-13T06:51:03 | 2021-05-13T06:51:03 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 2,303 |
java
|
package org.xujin.crm.sales.interceptor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.xujin.halo.command.CommandInterceptorI;
import org.xujin.halo.command.PostInterceptor;
import org.xujin.halo.common.LocalAddress;
import org.xujin.halo.context.PvgContext;
import org.xujin.halo.dto.Command;
import org.xujin.halo.dto.Response;
import org.xujin.halo.logger.Logger;
import org.xujin.halo.logger.LoggerFactory;
/**
* @author xujin
*/
@Order(100)
@PostInterceptor
public class LoggerPostInterceptor implements CommandInterceptorI{
Logger logger = LoggerFactory.getLogger(LoggerPostInterceptor.class);
private static final String MONITOR_LOG_PARAM_CACHE_ENANBLED = "monitor.log.param.cache.enanbled";
@Autowired
private LoggerPreInterceptor logPreInterceptor;
@Override
public void postIntercept(Command command, Response response) {
logger.debug("Finished processing %s Response:%s", command.getClass(), response);
//记录监控日志
handleMonitorLog(command, response);
}
private void handleMonitorLog(Command command, Response response){
Thread th = Thread.currentThread();
boolean status = false;
Long threadId = 0L;
if(th != null){
threadId = th.getId();
}
//操作人
String operator = StringUtils.EMPTY;
if(PvgContext.exist()){
operator = PvgContext.getCrmUserId();
}
//处理状态
if(response != null && response.isSuccess()){
status = true;
}
Boolean cacheEnabled = false;
String params = StringUtils.EMPTY;
if(!status){
params = command.toString();
}
//status=true 情况下默认关闭参数输出
else if(cacheEnabled != null && cacheEnabled){
params = command.toString();
}
//毫秒
long cost = System.currentTimeMillis() - logPreInterceptor.getStartTime();
//|threadId|Command|操作人|处理状态|耗时|ip|params
logger.info("[MonitorLog] |%s|%s|%s|%s|%s|%s|%s", threadId, command.getClass(), operator, status, cost, LocalAddress.IP, params);
}
}
|
[
"[email protected]"
] | |
99c9e803c3eb2d7bd0f3254b56cc2653eb390ac4
|
e27d960b42029e039593ae3f1c284fcb9d00c71b
|
/core/src/com/toddmahoney/xenomorpher/views/EndScreen.java
|
aaf6dd21ddb97485a61405dc420841f10236098f
|
[] |
no_license
|
t0dd/xenomorpher
|
a357dd7dc03a90f8a61b72a6217bbed76c281edc
|
3af33f6c11bf0b88990849b80bffd9ce8a469256
|
refs/heads/master
| 2021-09-03T07:40:05.711031 | 2018-01-06T22:37:55 | 2018-01-06T22:37:55 | 112,991,825 | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 595 |
java
|
package com.toddmahoney.xenomorpher.views;
import com.badlogic.gdx.Screen;
import com.toddmahoney.xenomorpher.Xenomorpher;
public class EndScreen implements Screen {
public EndScreen(Xenomorpher xenomorpher) {
}
@Override
public void show() {
}
@Override
public void render(float delta) {
}
@Override
public void resize(int width, int height) {
}
@Override
public void pause() {
}
@Override
public void resume() {
}
@Override
public void hide() {
}
@Override
public void dispose() {
}
}
|
[
"[email protected]"
] | |
153e5dc8776e879b0f72a71ea9c57354495c8f35
|
12ff5bbfa9b76cb37c5a7a0a5d4759e00fa878bc
|
/src/main/java/comparators/Estudante.java
|
225fb4e7cbda22bfd3faea6431d90029b73424a0
|
[] |
no_license
|
sidneyrdm/testsJunit
|
f2208b390ff9cca4465dfdcb71906c962b499fdf
|
6118d60d1cef9af4dedc1f57677c9b9924d190fa
|
refs/heads/master
| 2023-06-06T03:33:34.239587 | 2021-06-27T23:23:16 | 2021-06-27T23:23:16 | 376,986,527 | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 677 |
java
|
package comparators;
public class Estudante implements Comparable<Estudante> {
private final String nome;
private final Integer idade;
public Estudante(String nome, Integer idade) {
this.nome = nome;
this.idade = idade;
}
public String getNome() {
return nome;
}
public Integer getIdade() {
return idade;
}
@Override
public String toString() {
return "Estudante{" +
"nome='" + nome + '\'' +
", idade=" + idade +
'}';
}
@Override
public int compareTo(Estudante objeto) {
return this.getIdade() - objeto.getIdade();
}
}
|
[
"[email protected]"
] | |
8bad8ba5de1ebf8092ac1955f250465b6539f682
|
f36e34151d8c098ed5c67618f5123b7c662d4c18
|
/app/src/main/java/com/adminpankajmehta/ComplaintDetailActivity.java
|
34549d711f336e7dfb3db508f785e8a4f699df97
|
[] |
no_license
|
Rajuvaghela/AdminPankajMehta
|
774ac08c95c867c0f17ba8bebd6465ca79577f76
|
32a85bd6d6a085d79db49342d2eb21265da693c8
|
refs/heads/master
| 2021-04-12T09:59:55.772343 | 2018-03-24T17:14:55 | 2018-03-24T17:14:55 | 126,622,249 | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 356 |
java
|
package com.adminpankajmehta;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class ComplaintDetailActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_complaint_detail);
}
}
|
[
"[email protected]"
] | |
7c4c9a2936e243f83efe4fb8d4a2e72e52da3268
|
b7116ffc527a9959343f09d0174c170e255341a3
|
/ch27-ssm-xml/src/main/java/com/advice/ExceptionControllerAdvice.java
|
a401c1dcfe099237ef027b1e2e3d8a5fed1db119
|
[] |
no_license
|
GD-yx/spring-my-parent
|
f7275430394f30ea9a386dfe185b0d6a4f896640
|
676261a4367bb7b77c501ad0bea081eb6816be90
|
refs/heads/master
| 2022-12-21T08:10:51.197785 | 2019-11-27T04:09:17 | 2019-11-27T04:09:17 | 224,340,740 | 0 | 0 | null | 2022-12-16T14:51:02 | 2019-11-27T04:00:16 |
Java
|
UTF-8
|
Java
| false | false | 351 |
java
|
package com.advice;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
/**
* @author 南八
*/
@ControllerAdvice
public class ExceptionControllerAdvice {
@ExceptionHandler(RuntimeException.class)
public String handleRuntime(){
return "error";
}
}
|
[
"[email protected]"
] | |
4c62131ca13bd6bec4f885a524a1465cfb02ead8
|
943b8ad370162557fc215d3a8e70f10b1e59ac6a
|
/src/main/java/com/impatient/three/one/IntSequenceDemo.java
|
7c6c76585da758b3a12e3f78e8560ae42907f07e
|
[] |
no_license
|
himanshgadipelli/end-chapter
|
640e7474d8cf4a5fa042dac6a0e890f6c34c4045
|
dcc2c39de9d116d5dbbe48e749005e92762034bf
|
refs/heads/master
| 2021-01-11T19:47:19.769016 | 2017-02-07T16:33:22 | 2017-02-07T16:33:22 | 79,397,129 | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 961 |
java
|
package com.impatient.three.one;
/**
* Created by bobby on 1/25/2017.
*/
public class IntSequenceDemo {
public static double average(IntSequence seq, int n) {
int count = 0;
double sum = 0;
while (seq.hasNext() && count < n) {
count++;
sum += seq.next();
}
return count == 0 ? 0 : sum / count;
}
public static void main(String[] args) {
SquareSequence squares = new SquareSequence();
double avg = average(squares, 100);
System.out.println("Average of first 100 squares: " + avg);
IntSequence digits = new DigitSequence(1729);
while (digits.hasNext())
System.out.print(digits.next() + " ");
System.out.println();
digits = new DigitSequence(1729);
avg = average(digits, 100);
// Will only look at the first four sequence values
System.out.println("Average of the digits: " + avg);
}
}
|
[
"[email protected]"
] | |
f7b52df1554c762ffbffdefd61e902637c9acfed
|
447520f40e82a060368a0802a391697bc00be96f
|
/apks/apks_from_phone/data_app_com_monefy_app_lite-2/source/android/support/a/a/e.java
|
02937e777ecaa1bdc9a00894e7d5941bf29d7614
|
[
"Apache-2.0"
] |
permissive
|
iantal/AndroidPermissions
|
7f3343a9c29d82dbcd4ecd98b3a50ddf8d179465
|
d623b732734243590b5f004d167e542e2e2ae249
|
refs/heads/master
| 2023-07-19T01:29:26.689186 | 2019-09-30T19:01:42 | 2019-09-30T19:01:42 | 107,239,248 | 0 | 0 |
Apache-2.0
| 2023-07-16T07:41:38 | 2017-10-17T08:22:57 | null |
UTF-8
|
Java
| false | false | 1,467 |
java
|
package android.support.a.a;
import android.content.res.TypedArray;
import org.xmlpull.v1.XmlPullParser;
class e
{
public static float a(TypedArray paramTypedArray, XmlPullParser paramXmlPullParser, String paramString, int paramInt, float paramFloat)
{
if (!a(paramXmlPullParser, paramString)) {
return paramFloat;
}
return paramTypedArray.getFloat(paramInt, paramFloat);
}
public static int a(TypedArray paramTypedArray, XmlPullParser paramXmlPullParser, String paramString, int paramInt1, int paramInt2)
{
if (!a(paramXmlPullParser, paramString)) {
return paramInt2;
}
return paramTypedArray.getInt(paramInt1, paramInt2);
}
public static boolean a(TypedArray paramTypedArray, XmlPullParser paramXmlPullParser, String paramString, int paramInt, boolean paramBoolean)
{
if (!a(paramXmlPullParser, paramString)) {
return paramBoolean;
}
return paramTypedArray.getBoolean(paramInt, paramBoolean);
}
public static boolean a(XmlPullParser paramXmlPullParser, String paramString)
{
return paramXmlPullParser.getAttributeValue("http://schemas.android.com/apk/res/android", paramString) != null;
}
public static int b(TypedArray paramTypedArray, XmlPullParser paramXmlPullParser, String paramString, int paramInt1, int paramInt2)
{
if (!a(paramXmlPullParser, paramString)) {
return paramInt2;
}
return paramTypedArray.getColor(paramInt1, paramInt2);
}
}
|
[
"[email protected]"
] | |
05e36c7528eb0cbd2e520268ea2bf82cb9d6224d
|
5597895b1c386f30143c4de9177840b748826fe5
|
/src/main/java/metrics/groups/evolution/EvolutionAdditionsRelativeToManual.java
|
e35aeba5bcd00a3fa30a1c8ea59ab3df8a264736
|
[] |
no_license
|
jwbartel/SharingPredictionEvaluation
|
62608fd53276f4c680f14a51a56b22edc20558b6
|
84372eaa1270939b9c39a0016e55014e1be2f302
|
refs/heads/master
| 2016-09-05T15:14:57.366269 | 2015-03-05T04:33:11 | 2015-03-05T04:33:11 | 19,500,771 | 0 | 1 | null | null | null | null |
UTF-8
|
Java
| false | false | 1,558 |
java
|
package metrics.groups.evolution;
import java.util.Collection;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import metrics.DoubleResult;
import metrics.MetricResult;
import recommendation.groups.evolution.recommendations.RecommendedEvolution;
import recommendation.groups.evolution.recommendations.RecommendedGroupChangeEvolution;
import recommendation.groups.evolution.recommendations.RecommendedGroupCreationEvolution;
public class EvolutionAdditionsRelativeToManual<V> extends GroupEvolutionMetric<V> {
@Override
public String getHeader() {
return "evolution additions relative to manual";
}
@Override
public MetricResult evaluate(Set<V> newMembers, Map<Set<V>, Collection<Set<V>>> oldToNewIdealGroups,
Collection<Set<V>> newlyCreatedIdealGroups,
Map<RecommendedGroupChangeEvolution<V>, Set<V>> groupChangeToIdeal,
Map<RecommendedGroupCreationEvolution<V>, Set<V>> groupCreationToIdeal,
Collection<RecommendedEvolution<V>> unusedRecommendations,
Collection<Set<V>> unusedIdeals) {
int additions = 0;
for (Entry<RecommendedGroupChangeEvolution<V>, Set<V>> entry : groupChangeToIdeal
.entrySet()) {
additions += requiredAdditions(entry.getKey().getMerging(), entry.getValue());
}
int manualAdditions = 0;
for (Set<V> oldIdeal : oldToNewIdealGroups.keySet()) {
for (Set<V> evolvedIdeal : oldToNewIdealGroups.get(oldIdeal)) {
manualAdditions += (int) requiredAdditions(oldIdeal, evolvedIdeal);
}
}
return new DoubleResult(((double) additions) / manualAdditions);
}
}
|
[
"[email protected]"
] | |
1435a2127959196cdfa80790fa3fb5944b381456
|
c885ef92397be9d54b87741f01557f61d3f794f3
|
/results/JacksonDatabind-103/com.fasterxml.jackson.databind.deser.std.StdValueInstantiator/BBC-F0-opt-10/tests/24/com/fasterxml/jackson/databind/deser/std/StdValueInstantiator_ESTest.java
|
f1de246c3ad4548b65c21001b618c1e9e50468cf
|
[
"CC-BY-4.0",
"MIT"
] |
permissive
|
pderakhshanfar/EMSE-BBC-experiment
|
f60ac5f7664dd9a85f755a00a57ec12c7551e8c6
|
fea1a92c2e7ba7080b8529e2052259c9b697bbda
|
refs/heads/main
| 2022-11-25T00:39:58.983828 | 2022-04-12T16:04:26 | 2022-04-12T16:04:26 | 309,335,889 | 0 | 1 | null | 2021-11-05T11:18:43 | 2020-11-02T10:30:38 | null |
UTF-8
|
Java
| false | false | 54,360 |
java
|
/*
* This file was automatically generated by EvoSuite
* Sun Oct 24 03:59:32 GMT 2021
*/
package com.fasterxml.jackson.databind.deser.std;
import org.junit.Test;
import static org.junit.Assert.*;
import static org.evosuite.runtime.EvoAssertions.*;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.databind.AnnotationIntrospector;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.DeserializationConfig;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.Module;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectReader;
import com.fasterxml.jackson.databind.PropertyName;
import com.fasterxml.jackson.databind.cfg.BaseSettings;
import com.fasterxml.jackson.databind.cfg.ConfigOverrides;
import com.fasterxml.jackson.databind.cfg.MapperConfig;
import com.fasterxml.jackson.databind.deser.BeanDeserializerFactory;
import com.fasterxml.jackson.databind.deser.DefaultDeserializationContext;
import com.fasterxml.jackson.databind.deser.SettableBeanProperty;
import com.fasterxml.jackson.databind.deser.std.StdValueInstantiator;
import com.fasterxml.jackson.databind.introspect.AnnotatedParameter;
import com.fasterxml.jackson.databind.introspect.AnnotatedWithParams;
import com.fasterxml.jackson.databind.introspect.AnnotationMap;
import com.fasterxml.jackson.databind.introspect.BasicBeanDescription;
import com.fasterxml.jackson.databind.introspect.ClassIntrospector;
import com.fasterxml.jackson.databind.introspect.POJOPropertyBuilder;
import com.fasterxml.jackson.databind.introspect.SimpleMixInResolver;
import com.fasterxml.jackson.databind.introspect.TypeResolutionContext;
import com.fasterxml.jackson.databind.jsontype.NamedType;
import com.fasterxml.jackson.databind.jsontype.TypeIdResolver;
import com.fasterxml.jackson.databind.jsontype.impl.ClassNameIdResolver;
import com.fasterxml.jackson.databind.jsontype.impl.StdSubtypeResolver;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.node.LongNode;
import com.fasterxml.jackson.databind.ser.DefaultSerializerProvider;
import com.fasterxml.jackson.databind.type.ArrayType;
import com.fasterxml.jackson.databind.type.CollectionType;
import com.fasterxml.jackson.databind.type.MapLikeType;
import com.fasterxml.jackson.databind.type.MapType;
import com.fasterxml.jackson.databind.type.PlaceholderForType;
import com.fasterxml.jackson.databind.type.ReferenceType;
import com.fasterxml.jackson.databind.type.SimpleType;
import com.fasterxml.jackson.databind.type.TypeBindings;
import com.fasterxml.jackson.databind.type.TypeFactory;
import com.fasterxml.jackson.databind.util.RootNameLookup;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.sql.ClientInfoStatus;
import java.sql.SQLClientInfoException;
import java.sql.SQLDataException;
import java.sql.SQLFeatureNotSupportedException;
import java.sql.SQLIntegrityConstraintViolationException;
import java.sql.SQLNonTransientConnectionException;
import java.sql.SQLNonTransientException;
import java.sql.SQLSyntaxErrorException;
import java.sql.SQLTimeoutException;
import java.sql.SQLTransientException;
import java.sql.SQLWarning;
import java.util.HashMap;
import java.util.List;
import java.util.Vector;
import org.evosuite.runtime.EvoRunner;
import org.evosuite.runtime.EvoRunnerParameters;
import org.evosuite.runtime.mock.java.lang.MockException;
import org.junit.runner.RunWith;
@RunWith(EvoRunner.class) @EvoRunnerParameters(mockJVMNonDeterminism = true, useVFS = true, useVNET = true, resetStaticState = true, separateClassLoader = true)
public class StdValueInstantiator_ESTest extends StdValueInstantiator_ESTest_scaffolding {
@Test(timeout = 4000)
public void test00() throws Throwable {
StdValueInstantiator stdValueInstantiator0 = new StdValueInstantiator((DeserializationConfig) null, (JavaType) null);
SettableBeanProperty[] settableBeanPropertyArray0 = new SettableBeanProperty[0];
stdValueInstantiator0.configureFromArraySettings((AnnotatedWithParams) null, (JavaType) null, settableBeanPropertyArray0);
ObjectMapper objectMapper0 = new ObjectMapper();
DeserializationContext deserializationContext0 = objectMapper0.getDeserializationContext();
SQLNonTransientException sQLNonTransientException0 = new SQLNonTransientException("t$4bmz%9='j+)_r/'");
SQLTransientException sQLTransientException0 = new SQLTransientException(sQLNonTransientException0);
InvocationTargetException invocationTargetException0 = new InvocationTargetException(sQLTransientException0, "t$4bmz%9='j+)_r/'");
// Undeclared exception!
try {
stdValueInstantiator0.createUsingArrayDelegate(deserializationContext0, invocationTargetException0);
fail("Expecting exception: IllegalStateException");
} catch(IllegalStateException e) {
//
// No delegate constructor for UNKNOWN TYPE
//
verifyException("com.fasterxml.jackson.databind.deser.std.StdValueInstantiator", e);
}
}
@Test(timeout = 4000)
public void test01() throws Throwable {
StdValueInstantiator stdValueInstantiator0 = new StdValueInstantiator((DeserializationConfig) null, (JavaType) null);
SettableBeanProperty[] settableBeanPropertyArray0 = new SettableBeanProperty[0];
stdValueInstantiator0.configureFromObjectSettings((AnnotatedWithParams) null, (AnnotatedWithParams) null, (JavaType) null, settableBeanPropertyArray0, (AnnotatedWithParams) null, settableBeanPropertyArray0);
SimpleModule simpleModule0 = new SimpleModule(" value failed: ");
// Undeclared exception!
try {
stdValueInstantiator0.createUsingDelegate((DeserializationContext) null, simpleModule0);
fail("Expecting exception: IllegalStateException");
} catch(IllegalStateException e) {
//
// No delegate constructor for UNKNOWN TYPE
//
verifyException("com.fasterxml.jackson.databind.deser.std.StdValueInstantiator", e);
}
}
@Test(timeout = 4000)
public void test02() throws Throwable {
Class<JsonDeserializer> class0 = JsonDeserializer.class;
StdValueInstantiator stdValueInstantiator0 = new StdValueInstantiator((DeserializationConfig) null, class0);
SettableBeanProperty[] settableBeanPropertyArray0 = new SettableBeanProperty[0];
stdValueInstantiator0._constructorArguments = settableBeanPropertyArray0;
SettableBeanProperty[] settableBeanPropertyArray1 = stdValueInstantiator0.getFromObjectArguments((DeserializationConfig) null);
assertNotNull(settableBeanPropertyArray1);
assertEquals("`com.fasterxml.jackson.databind.JsonDeserializer`", stdValueInstantiator0.getValueTypeDesc());
}
@Test(timeout = 4000)
public void test03() throws Throwable {
AnnotationIntrospector annotationIntrospector0 = AnnotationIntrospector.nopInstance();
PropertyName propertyName0 = PropertyName.construct((String) null, "from-long");
POJOPropertyBuilder pOJOPropertyBuilder0 = new POJOPropertyBuilder((MapperConfig<?>) null, annotationIntrospector0, false, propertyName0);
JavaType javaType0 = pOJOPropertyBuilder0.getPrimaryType();
ObjectMapper objectMapper0 = new ObjectMapper((JsonFactory) null);
ObjectReader objectReader0 = objectMapper0.readerFor(javaType0);
assertNotNull(objectReader0);
}
@Test(timeout = 4000)
public void test04() throws Throwable {
Class<Integer> class0 = Integer.class;
StdValueInstantiator stdValueInstantiator0 = new StdValueInstantiator((DeserializationConfig) null, class0);
TypeFactory typeFactory0 = TypeFactory.defaultInstance();
Class<HashMap> class1 = HashMap.class;
MapType mapType0 = typeFactory0.constructRawMapType(class1);
AnnotationMap annotationMap0 = new AnnotationMap();
AnnotatedParameter annotatedParameter0 = new AnnotatedParameter((AnnotatedWithParams) null, mapType0, (TypeResolutionContext) null, annotationMap0, 0);
stdValueInstantiator0.configureIncompleteParameter(annotatedParameter0);
assertEquals("`java.lang.Integer`", stdValueInstantiator0.getValueTypeDesc());
}
@Test(timeout = 4000)
public void test05() throws Throwable {
ObjectMapper objectMapper0 = new ObjectMapper((JsonFactory) null);
Class<JsonMappingException> class0 = JsonMappingException.class;
ObjectReader objectReader0 = objectMapper0.readerFor(class0);
assertNotNull(objectReader0);
}
@Test(timeout = 4000)
public void test06() throws Throwable {
StdValueInstantiator stdValueInstantiator0 = new StdValueInstantiator((DeserializationConfig) null, (JavaType) null);
SettableBeanProperty[] settableBeanPropertyArray0 = new SettableBeanProperty[0];
stdValueInstantiator0.configureFromObjectSettings((AnnotatedWithParams) null, (AnnotatedWithParams) null, (JavaType) null, (SettableBeanProperty[]) null, (AnnotatedWithParams) null, settableBeanPropertyArray0);
assertEquals("UNKNOWN TYPE", stdValueInstantiator0.getValueTypeDesc());
}
@Test(timeout = 4000)
public void test07() throws Throwable {
Class<Module> class0 = Module.class;
StdValueInstantiator stdValueInstantiator0 = new StdValueInstantiator((DeserializationConfig) null, class0);
SettableBeanProperty[] settableBeanPropertyArray0 = new SettableBeanProperty[0];
stdValueInstantiator0._delegateArguments = settableBeanPropertyArray0;
StdValueInstantiator stdValueInstantiator1 = new StdValueInstantiator(stdValueInstantiator0);
assertEquals("`com.fasterxml.jackson.databind.Module`", stdValueInstantiator1.getValueTypeDesc());
}
@Test(timeout = 4000)
public void test08() throws Throwable {
Class<NamedType> class0 = NamedType.class;
StdValueInstantiator stdValueInstantiator0 = new StdValueInstantiator((DeserializationConfig) null, class0);
JavaType javaType0 = TypeFactory.unknownType();
stdValueInstantiator0.configureFromObjectSettings((AnnotatedWithParams) null, (AnnotatedWithParams) null, javaType0, (SettableBeanProperty[]) null, (AnnotatedWithParams) null, (SettableBeanProperty[]) null);
StdValueInstantiator stdValueInstantiator1 = new StdValueInstantiator(stdValueInstantiator0);
assertTrue(stdValueInstantiator0.canCreateUsingDelegate());
assertFalse(stdValueInstantiator1.canCreateUsingArrayDelegate());
}
@Test(timeout = 4000)
public void test09() throws Throwable {
StdValueInstantiator stdValueInstantiator0 = new StdValueInstantiator((DeserializationConfig) null, (JavaType) null);
SettableBeanProperty[] settableBeanPropertyArray0 = new SettableBeanProperty[0];
stdValueInstantiator0.configureFromObjectSettings((AnnotatedWithParams) null, (AnnotatedWithParams) null, (JavaType) null, settableBeanPropertyArray0, (AnnotatedWithParams) null, settableBeanPropertyArray0);
StdValueInstantiator stdValueInstantiator1 = new StdValueInstantiator(stdValueInstantiator0);
assertFalse(stdValueInstantiator1.canCreateFromBoolean());
}
@Test(timeout = 4000)
public void test10() throws Throwable {
StdValueInstantiator stdValueInstantiator0 = new StdValueInstantiator((DeserializationConfig) null, (JavaType) null);
stdValueInstantiator0.configureFromStringCreator((AnnotatedWithParams) null);
assertEquals("UNKNOWN TYPE", stdValueInstantiator0.getValueTypeDesc());
}
@Test(timeout = 4000)
public void test11() throws Throwable {
Class<JsonMappingException> class0 = JsonMappingException.class;
StdValueInstantiator stdValueInstantiator0 = new StdValueInstantiator((DeserializationConfig) null, class0);
stdValueInstantiator0.configureFromLongCreator((AnnotatedWithParams) null);
assertEquals("`com.fasterxml.jackson.databind.JsonMappingException`", stdValueInstantiator0.getValueTypeDesc());
}
@Test(timeout = 4000)
public void test12() throws Throwable {
Class<JsonMappingException> class0 = JsonMappingException.class;
StdValueInstantiator stdValueInstantiator0 = new StdValueInstantiator((DeserializationConfig) null, class0);
stdValueInstantiator0.configureFromIntCreator((AnnotatedWithParams) null);
assertEquals("`com.fasterxml.jackson.databind.JsonMappingException`", stdValueInstantiator0.getValueTypeDesc());
}
@Test(timeout = 4000)
public void test13() throws Throwable {
Class<InvocationTargetException> class0 = InvocationTargetException.class;
StdValueInstantiator stdValueInstantiator0 = new StdValueInstantiator((DeserializationConfig) null, class0);
stdValueInstantiator0.configureFromDoubleCreator((AnnotatedWithParams) null);
assertEquals("`java.lang.reflect.InvocationTargetException`", stdValueInstantiator0.getValueTypeDesc());
}
@Test(timeout = 4000)
public void test14() throws Throwable {
StdValueInstantiator stdValueInstantiator0 = new StdValueInstantiator((DeserializationConfig) null, (JavaType) null);
stdValueInstantiator0.configureFromBooleanCreator((AnnotatedWithParams) null);
assertEquals("UNKNOWN TYPE", stdValueInstantiator0.getValueTypeDesc());
}
@Test(timeout = 4000)
public void test15() throws Throwable {
BeanDeserializerFactory beanDeserializerFactory0 = BeanDeserializerFactory.instance;
DefaultDeserializationContext.Impl defaultDeserializationContext_Impl0 = new DefaultDeserializationContext.Impl(beanDeserializerFactory0);
Class<String> class0 = String.class;
StdValueInstantiator stdValueInstantiator0 = new StdValueInstantiator((DeserializationConfig) null, class0);
SQLClientInfoException sQLClientInfoException0 = new SQLClientInfoException();
JsonMappingException jsonMappingException0 = JsonMappingException.from((DeserializationContext) defaultDeserializationContext_Impl0, "", (Throwable) sQLClientInfoException0);
stdValueInstantiator0.wrapAsJsonMappingException(defaultDeserializationContext_Impl0, jsonMappingException0);
assertEquals("`java.lang.String`", stdValueInstantiator0.getValueTypeDesc());
}
@Test(timeout = 4000)
public void test16() throws Throwable {
Class<Integer> class0 = Integer.TYPE;
StdValueInstantiator stdValueInstantiator0 = new StdValueInstantiator((DeserializationConfig) null, class0);
Class<?> class1 = stdValueInstantiator0.getValueClass();
assertNotNull(class1);
assertEquals("int", class1.toString());
assertEquals("`int`", stdValueInstantiator0.getValueTypeDesc());
}
@Test(timeout = 4000)
public void test17() throws Throwable {
Class<TypeIdResolver> class0 = TypeIdResolver.class;
StdValueInstantiator stdValueInstantiator0 = new StdValueInstantiator((DeserializationConfig) null, class0);
Class<?> class1 = stdValueInstantiator0.getValueClass();
assertNotNull(class1);
assertTrue(class1.isInterface());
assertEquals("`com.fasterxml.jackson.databind.jsontype.TypeIdResolver`", stdValueInstantiator0.getValueTypeDesc());
}
@Test(timeout = 4000)
public void test18() throws Throwable {
Class<ObjectMapper.DefaultTyping> class0 = ObjectMapper.DefaultTyping.class;
StdValueInstantiator stdValueInstantiator0 = new StdValueInstantiator((DeserializationConfig) null, class0);
Class<?> class1 = stdValueInstantiator0.getValueClass();
assertNotNull(class1);
assertTrue(class1.isEnum());
assertEquals("`com.fasterxml.jackson.databind.ObjectMapper$DefaultTyping`", stdValueInstantiator0.getValueTypeDesc());
}
@Test(timeout = 4000)
public void test19() throws Throwable {
TypeFactory typeFactory0 = TypeFactory.defaultInstance();
JavaType javaType0 = TypeFactory.unknownType();
MapLikeType mapLikeType0 = MapLikeType.upgradeFrom(javaType0, javaType0, javaType0);
ArrayType arrayType0 = typeFactory0.constructArrayType((JavaType) mapLikeType0);
StdValueInstantiator stdValueInstantiator0 = new StdValueInstantiator((DeserializationConfig) null, arrayType0);
Class<?> class0 = stdValueInstantiator0.getValueClass();
assertEquals("[array type, component type: [map-like type; class java.lang.Object, [simple type, class java.lang.Object] -> [simple type, class java.lang.Object]]]", stdValueInstantiator0.getValueTypeDesc());
assertEquals("class [Ljava.lang.Object;", class0.toString());
}
@Test(timeout = 4000)
public void test20() throws Throwable {
Class<InvocationTargetException> class0 = InvocationTargetException.class;
StdValueInstantiator stdValueInstantiator0 = new StdValueInstantiator((DeserializationConfig) null, class0);
stdValueInstantiator0.getIncompleteParameter();
assertEquals("`java.lang.reflect.InvocationTargetException`", stdValueInstantiator0.getValueTypeDesc());
}
@Test(timeout = 4000)
public void test21() throws Throwable {
PlaceholderForType placeholderForType0 = new PlaceholderForType((-65));
StdValueInstantiator stdValueInstantiator0 = new StdValueInstantiator((DeserializationConfig) null, placeholderForType0);
stdValueInstantiator0.getFromObjectArguments((DeserializationConfig) null);
assertEquals("$-64", stdValueInstantiator0.getValueTypeDesc());
}
@Test(timeout = 4000)
public void test22() throws Throwable {
Class<ObjectMapper.DefaultTyping> class0 = ObjectMapper.DefaultTyping.class;
StdValueInstantiator stdValueInstantiator0 = new StdValueInstantiator((DeserializationConfig) null, class0);
TypeFactory typeFactory0 = TypeFactory.defaultInstance();
Class<List> class1 = List.class;
CollectionType collectionType0 = typeFactory0.constructCollectionType(class1, class0);
CollectionType collectionType1 = collectionType0.withStaticTyping();
stdValueInstantiator0._delegateType = (JavaType) collectionType1;
JavaType javaType0 = stdValueInstantiator0.getDelegateType((DeserializationConfig) null);
assertNotNull(javaType0);
assertEquals("`com.fasterxml.jackson.databind.ObjectMapper$DefaultTyping`", stdValueInstantiator0.getValueTypeDesc());
}
@Test(timeout = 4000)
public void test23() throws Throwable {
TypeFactory typeFactory0 = TypeFactory.defaultInstance();
JavaType javaType0 = TypeFactory.unknownType();
ArrayType arrayType0 = typeFactory0.constructArrayType(javaType0);
StdValueInstantiator stdValueInstantiator0 = new StdValueInstantiator((DeserializationConfig) null, arrayType0);
stdValueInstantiator0.configureFromObjectSettings((AnnotatedWithParams) null, (AnnotatedWithParams) null, arrayType0, (SettableBeanProperty[]) null, (AnnotatedWithParams) null, (SettableBeanProperty[]) null);
stdValueInstantiator0.getDelegateType((DeserializationConfig) null);
assertTrue(stdValueInstantiator0.canCreateUsingDelegate());
}
@Test(timeout = 4000)
public void test24() throws Throwable {
Class<ObjectMapper.DefaultTyping> class0 = ObjectMapper.DefaultTyping.class;
StdValueInstantiator stdValueInstantiator0 = new StdValueInstantiator((DeserializationConfig) null, class0);
TypeFactory typeFactory0 = TypeFactory.defaultInstance();
Class<List> class1 = List.class;
CollectionType collectionType0 = typeFactory0.constructCollectionType(class1, class0);
CollectionType collectionType1 = collectionType0.withValueHandler(collectionType0);
stdValueInstantiator0._delegateType = (JavaType) collectionType1;
JavaType javaType0 = stdValueInstantiator0.getDelegateType((DeserializationConfig) null);
assertNotNull(javaType0);
assertEquals("`com.fasterxml.jackson.databind.ObjectMapper$DefaultTyping`", stdValueInstantiator0.getValueTypeDesc());
}
@Test(timeout = 4000)
public void test25() throws Throwable {
Class<Module> class0 = Module.class;
StdValueInstantiator stdValueInstantiator0 = new StdValueInstantiator((DeserializationConfig) null, class0);
JavaType javaType0 = TypeFactory.unknownType();
stdValueInstantiator0.configureFromObjectSettings((AnnotatedWithParams) null, (AnnotatedWithParams) null, javaType0, (SettableBeanProperty[]) null, (AnnotatedWithParams) null, (SettableBeanProperty[]) null);
stdValueInstantiator0.getDelegateType((DeserializationConfig) null);
assertTrue(stdValueInstantiator0.canInstantiate());
}
@Test(timeout = 4000)
public void test26() throws Throwable {
Class<JsonMappingException> class0 = JsonMappingException.class;
StdValueInstantiator stdValueInstantiator0 = new StdValueInstantiator((DeserializationConfig) null, class0);
stdValueInstantiator0.getDelegateCreator();
assertEquals("`com.fasterxml.jackson.databind.JsonMappingException`", stdValueInstantiator0.getValueTypeDesc());
}
@Test(timeout = 4000)
public void test27() throws Throwable {
Class<ClassNameIdResolver> class0 = ClassNameIdResolver.class;
StdValueInstantiator stdValueInstantiator0 = new StdValueInstantiator((DeserializationConfig) null, class0);
TypeBindings typeBindings0 = TypeBindings.emptyBindings();
JavaType javaType0 = TypeFactory.unknownType();
ReferenceType referenceType0 = ReferenceType.upgradeFrom(javaType0, javaType0);
JavaType[] javaTypeArray0 = new JavaType[4];
CollectionType collectionType0 = CollectionType.construct((Class<?>) class0, typeBindings0, (JavaType) referenceType0, javaTypeArray0, javaType0);
CollectionType collectionType1 = collectionType0.withStaticTyping();
stdValueInstantiator0.configureFromArraySettings((AnnotatedWithParams) null, collectionType1, (SettableBeanProperty[]) null);
stdValueInstantiator0.getArrayDelegateType((DeserializationConfig) null);
assertTrue(stdValueInstantiator0.canInstantiate());
}
@Test(timeout = 4000)
public void test28() throws Throwable {
Class<ClassNameIdResolver> class0 = ClassNameIdResolver.class;
StdValueInstantiator stdValueInstantiator0 = new StdValueInstantiator((DeserializationConfig) null, class0);
TypeBindings typeBindings0 = TypeBindings.emptyBindings();
JavaType javaType0 = TypeFactory.unknownType();
ReferenceType referenceType0 = ReferenceType.upgradeFrom(javaType0, javaType0);
JavaType[] javaTypeArray0 = new JavaType[4];
CollectionType collectionType0 = CollectionType.construct((Class<?>) class0, typeBindings0, (JavaType) referenceType0, javaTypeArray0, javaType0);
CollectionType collectionType1 = collectionType0.withValueHandler(class0);
stdValueInstantiator0.configureFromArraySettings((AnnotatedWithParams) null, collectionType1, (SettableBeanProperty[]) null);
stdValueInstantiator0.getArrayDelegateType((DeserializationConfig) null);
assertTrue(stdValueInstantiator0.canInstantiate());
}
@Test(timeout = 4000)
public void test29() throws Throwable {
Class<Object> class0 = Object.class;
StdValueInstantiator stdValueInstantiator0 = new StdValueInstantiator((DeserializationConfig) null, class0);
TypeBindings typeBindings0 = TypeBindings.create(class0, (JavaType[]) null);
Class<Module> class1 = Module.class;
SimpleType simpleType0 = SimpleType.constructUnsafe(class0);
CollectionType collectionType0 = CollectionType.construct((Class<?>) class1, typeBindings0, (JavaType) simpleType0, (JavaType[]) null, (JavaType) simpleType0);
MapType mapType0 = MapType.construct((Class<?>) class0, typeBindings0, (JavaType) collectionType0, (JavaType[]) null, (JavaType) simpleType0, (JavaType) simpleType0);
MapType mapType1 = mapType0.withContentTypeHandler(typeBindings0);
stdValueInstantiator0._arrayDelegateType = (JavaType) mapType1;
JavaType javaType0 = stdValueInstantiator0.getArrayDelegateType((DeserializationConfig) null);
assertEquals("`java.lang.Object`", stdValueInstantiator0.getValueTypeDesc());
assertNotNull(javaType0);
}
@Test(timeout = 4000)
public void test30() throws Throwable {
Class<PlaceholderForType> class0 = PlaceholderForType.class;
StdValueInstantiator stdValueInstantiator0 = new StdValueInstantiator((DeserializationConfig) null, class0);
BeanProperty.Bogus beanProperty_Bogus0 = new BeanProperty.Bogus();
JavaType javaType0 = beanProperty_Bogus0.getType();
stdValueInstantiator0._arrayDelegateType = javaType0;
JavaType javaType1 = stdValueInstantiator0.getArrayDelegateType((DeserializationConfig) null);
assertNotNull(javaType1);
assertEquals("`com.fasterxml.jackson.databind.type.PlaceholderForType`", stdValueInstantiator0.getValueTypeDesc());
}
@Test(timeout = 4000)
public void test31() throws Throwable {
PlaceholderForType placeholderForType0 = new PlaceholderForType((-65));
StdValueInstantiator stdValueInstantiator0 = new StdValueInstantiator((DeserializationConfig) null, placeholderForType0);
boolean boolean0 = stdValueInstantiator0.canCreateUsingDelegate();
assertFalse(boolean0);
assertEquals("$-64", stdValueInstantiator0.getValueTypeDesc());
}
@Test(timeout = 4000)
public void test32() throws Throwable {
StdValueInstantiator stdValueInstantiator0 = new StdValueInstantiator((DeserializationConfig) null, (JavaType) null);
boolean boolean0 = stdValueInstantiator0.canCreateUsingDefault();
assertEquals("UNKNOWN TYPE", stdValueInstantiator0.getValueTypeDesc());
assertFalse(boolean0);
}
@Test(timeout = 4000)
public void test33() throws Throwable {
Class<Integer> class0 = Integer.TYPE;
StdValueInstantiator stdValueInstantiator0 = new StdValueInstantiator((DeserializationConfig) null, class0);
boolean boolean0 = stdValueInstantiator0.canCreateUsingArrayDelegate();
assertFalse(boolean0);
assertEquals("`int`", stdValueInstantiator0.getValueTypeDesc());
}
@Test(timeout = 4000)
public void test34() throws Throwable {
Class<String> class0 = String.class;
StdValueInstantiator stdValueInstantiator0 = new StdValueInstantiator((DeserializationConfig) null, class0);
boolean boolean0 = stdValueInstantiator0.canCreateFromObjectWith();
assertEquals("`java.lang.String`", stdValueInstantiator0.getValueTypeDesc());
assertFalse(boolean0);
}
@Test(timeout = 4000)
public void test35() throws Throwable {
Class<ObjectMapper.DefaultTyping> class0 = ObjectMapper.DefaultTyping.class;
StdValueInstantiator stdValueInstantiator0 = new StdValueInstantiator((DeserializationConfig) null, class0);
HashMap<String, ClientInfoStatus> hashMap0 = new HashMap<String, ClientInfoStatus>();
SQLClientInfoException sQLClientInfoException0 = new SQLClientInfoException("", "", (-4274), hashMap0);
SQLFeatureNotSupportedException sQLFeatureNotSupportedException0 = new SQLFeatureNotSupportedException(sQLClientInfoException0);
sQLClientInfoException0.initCause(sQLFeatureNotSupportedException0);
MockException mockException0 = new MockException("7[Bg:\u0003", sQLFeatureNotSupportedException0);
// Undeclared exception!
stdValueInstantiator0.wrapException(mockException0);
}
@Test(timeout = 4000)
public void test36() throws Throwable {
Class<BasicBeanDescription> class0 = BasicBeanDescription.class;
StdValueInstantiator stdValueInstantiator0 = new StdValueInstantiator((DeserializationConfig) null, class0);
// Undeclared exception!
try {
stdValueInstantiator0.wrapException((Throwable) null);
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("com.fasterxml.jackson.databind.deser.std.StdValueInstantiator", e);
}
}
@Test(timeout = 4000)
public void test37() throws Throwable {
TypeFactory typeFactory0 = TypeFactory.defaultInstance();
JavaType javaType0 = TypeFactory.unknownType();
MapLikeType mapLikeType0 = MapLikeType.upgradeFrom(javaType0, javaType0, javaType0);
ArrayType arrayType0 = typeFactory0.constructArrayType((JavaType) mapLikeType0);
StdValueInstantiator stdValueInstantiator0 = new StdValueInstantiator((DeserializationConfig) null, arrayType0);
BeanDeserializerFactory beanDeserializerFactory0 = BeanDeserializerFactory.instance;
DefaultDeserializationContext.Impl defaultDeserializationContext_Impl0 = new DefaultDeserializationContext.Impl(beanDeserializerFactory0);
SQLIntegrityConstraintViolationException sQLIntegrityConstraintViolationException0 = new SQLIntegrityConstraintViolationException();
SQLSyntaxErrorException sQLSyntaxErrorException0 = new SQLSyntaxErrorException(sQLIntegrityConstraintViolationException0);
SQLWarning sQLWarning0 = new SQLWarning("", sQLSyntaxErrorException0);
// Undeclared exception!
try {
stdValueInstantiator0.wrapAsJsonMappingException(defaultDeserializationContext_Impl0, sQLWarning0);
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("com.fasterxml.jackson.databind.DeserializationContext", e);
}
}
@Test(timeout = 4000)
public void test38() throws Throwable {
Class<Object> class0 = Object.class;
StdValueInstantiator stdValueInstantiator0 = new StdValueInstantiator((DeserializationConfig) null, class0);
BeanDeserializerFactory beanDeserializerFactory0 = BeanDeserializerFactory.instance;
DefaultDeserializationContext.Impl defaultDeserializationContext_Impl0 = new DefaultDeserializationContext.Impl(beanDeserializerFactory0);
SQLDataException sQLDataException0 = new SQLDataException("", "");
SQLNonTransientConnectionException sQLNonTransientConnectionException0 = new SQLNonTransientConnectionException("", sQLDataException0);
sQLDataException0.initCause(sQLNonTransientConnectionException0);
// Undeclared exception!
stdValueInstantiator0.unwrapAndWrapException(defaultDeserializationContext_Impl0, sQLDataException0);
}
@Test(timeout = 4000)
public void test39() throws Throwable {
StdValueInstantiator stdValueInstantiator0 = null;
try {
stdValueInstantiator0 = new StdValueInstantiator((StdValueInstantiator) null);
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("com.fasterxml.jackson.databind.deser.std.StdValueInstantiator", e);
}
}
@Test(timeout = 4000)
public void test40() throws Throwable {
Class<String> class0 = String.class;
StdValueInstantiator stdValueInstantiator0 = new StdValueInstantiator((DeserializationConfig) null, class0);
BeanDeserializerFactory beanDeserializerFactory0 = BeanDeserializerFactory.instance;
DefaultDeserializationContext.Impl defaultDeserializationContext_Impl0 = new DefaultDeserializationContext.Impl(beanDeserializerFactory0);
// Undeclared exception!
try {
stdValueInstantiator0.createUsingDefault(defaultDeserializationContext_Impl0);
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("com.fasterxml.jackson.databind.DeserializationContext", e);
}
}
@Test(timeout = 4000)
public void test41() throws Throwable {
Class<String> class0 = String.class;
StdValueInstantiator stdValueInstantiator0 = new StdValueInstantiator((DeserializationConfig) null, class0);
JavaType javaType0 = TypeFactory.unknownType();
stdValueInstantiator0.configureFromObjectSettings((AnnotatedWithParams) null, (AnnotatedWithParams) null, javaType0, (SettableBeanProperty[]) null, (AnnotatedWithParams) null, (SettableBeanProperty[]) null);
boolean boolean0 = stdValueInstantiator0.canCreateUsingDelegate();
assertTrue(stdValueInstantiator0.canInstantiate());
assertTrue(boolean0);
}
@Test(timeout = 4000)
public void test42() throws Throwable {
StdValueInstantiator stdValueInstantiator0 = new StdValueInstantiator((DeserializationConfig) null, (JavaType) null);
boolean boolean0 = stdValueInstantiator0.canCreateFromBoolean();
assertEquals("UNKNOWN TYPE", stdValueInstantiator0.getValueTypeDesc());
assertFalse(boolean0);
}
@Test(timeout = 4000)
public void test43() throws Throwable {
Class<ExceptionInInitializerError> class0 = ExceptionInInitializerError.class;
StdValueInstantiator stdValueInstantiator0 = new StdValueInstantiator((DeserializationConfig) null, class0);
boolean boolean0 = stdValueInstantiator0.canCreateFromDouble();
assertEquals("`java.lang.ExceptionInInitializerError`", stdValueInstantiator0.getValueTypeDesc());
assertFalse(boolean0);
}
@Test(timeout = 4000)
public void test44() throws Throwable {
Class<JsonMappingException> class0 = JsonMappingException.class;
StdValueInstantiator stdValueInstantiator0 = new StdValueInstantiator((DeserializationConfig) null, class0);
boolean boolean0 = stdValueInstantiator0.canCreateFromLong();
assertFalse(boolean0);
assertEquals("`com.fasterxml.jackson.databind.JsonMappingException`", stdValueInstantiator0.getValueTypeDesc());
}
@Test(timeout = 4000)
public void test45() throws Throwable {
Class<String> class0 = String.class;
StdValueInstantiator stdValueInstantiator0 = new StdValueInstantiator((DeserializationConfig) null, class0);
boolean boolean0 = stdValueInstantiator0.canCreateFromInt();
assertFalse(boolean0);
assertEquals("`java.lang.String`", stdValueInstantiator0.getValueTypeDesc());
}
@Test(timeout = 4000)
public void test46() throws Throwable {
Class<ExceptionInInitializerError> class0 = ExceptionInInitializerError.class;
StdValueInstantiator stdValueInstantiator0 = new StdValueInstantiator((DeserializationConfig) null, class0);
boolean boolean0 = stdValueInstantiator0.canCreateFromString();
assertFalse(boolean0);
assertEquals("`java.lang.ExceptionInInitializerError`", stdValueInstantiator0.getValueTypeDesc());
}
@Test(timeout = 4000)
public void test47() throws Throwable {
TypeFactory typeFactory0 = TypeFactory.defaultInstance();
JavaType javaType0 = TypeFactory.unknownType();
ArrayType arrayType0 = typeFactory0.constructArrayType(javaType0);
StdValueInstantiator stdValueInstantiator0 = new StdValueInstantiator((DeserializationConfig) null, arrayType0);
String string0 = stdValueInstantiator0.getValueTypeDesc();
assertEquals("[array type, component type: [simple type, class java.lang.Object]]", string0);
}
@Test(timeout = 4000)
public void test48() throws Throwable {
BeanDeserializerFactory beanDeserializerFactory0 = BeanDeserializerFactory.instance;
DefaultDeserializationContext.Impl defaultDeserializationContext_Impl0 = new DefaultDeserializationContext.Impl(beanDeserializerFactory0);
TypeFactory typeFactory0 = TypeFactory.defaultInstance();
Class<Vector> class0 = Vector.class;
CollectionType collectionType0 = typeFactory0.constructCollectionType(class0, class0);
ExceptionInInitializerError exceptionInInitializerError0 = new ExceptionInInitializerError("oiKS2}PQ?");
StdValueInstantiator stdValueInstantiator0 = new StdValueInstantiator((DeserializationConfig) null, collectionType0);
// Undeclared exception!
try {
stdValueInstantiator0.rewrapCtorProblem(defaultDeserializationContext_Impl0, exceptionInInitializerError0);
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("com.fasterxml.jackson.databind.DeserializationContext", e);
}
}
@Test(timeout = 4000)
public void test49() throws Throwable {
Class<JsonMappingException> class0 = JsonMappingException.class;
StdValueInstantiator stdValueInstantiator0 = new StdValueInstantiator((DeserializationConfig) null, class0);
BeanDeserializerFactory beanDeserializerFactory0 = BeanDeserializerFactory.instance;
DefaultDeserializationContext.Impl defaultDeserializationContext_Impl0 = new DefaultDeserializationContext.Impl(beanDeserializerFactory0);
SQLTimeoutException sQLTimeoutException0 = new SQLTimeoutException("", "3`!t<oS", 0);
InvocationTargetException invocationTargetException0 = new InvocationTargetException(sQLTimeoutException0, "");
// Undeclared exception!
try {
stdValueInstantiator0.rewrapCtorProblem(defaultDeserializationContext_Impl0, invocationTargetException0);
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("com.fasterxml.jackson.databind.DeserializationContext", e);
}
}
@Test(timeout = 4000)
public void test50() throws Throwable {
BeanDeserializerFactory beanDeserializerFactory0 = BeanDeserializerFactory.instance;
DefaultDeserializationContext.Impl defaultDeserializationContext_Impl0 = new DefaultDeserializationContext.Impl(beanDeserializerFactory0);
Class<BasicBeanDescription> class0 = BasicBeanDescription.class;
StdValueInstantiator stdValueInstantiator0 = new StdValueInstantiator((DeserializationConfig) null, class0);
Class<LongNode> class1 = LongNode.class;
JsonMappingException jsonMappingException0 = defaultDeserializationContext_Impl0.weirdKeyException(class1, (String) null, (String) null);
stdValueInstantiator0.rewrapCtorProblem(defaultDeserializationContext_Impl0, jsonMappingException0);
assertEquals("`com.fasterxml.jackson.databind.introspect.BasicBeanDescription`", stdValueInstantiator0.getValueTypeDesc());
}
@Test(timeout = 4000)
public void test51() throws Throwable {
BeanDeserializerFactory beanDeserializerFactory0 = BeanDeserializerFactory.instance;
DefaultDeserializationContext.Impl defaultDeserializationContext_Impl0 = new DefaultDeserializationContext.Impl(beanDeserializerFactory0);
Class<BasicBeanDescription> class0 = BasicBeanDescription.class;
StdValueInstantiator stdValueInstantiator0 = new StdValueInstantiator((DeserializationConfig) null, class0);
Class<LongNode> class1 = LongNode.class;
JsonMappingException jsonMappingException0 = defaultDeserializationContext_Impl0.weirdKeyException(class1, (String) null, (String) null);
SQLNonTransientException sQLNonTransientException0 = new SQLNonTransientException((String) null, jsonMappingException0);
stdValueInstantiator0.unwrapAndWrapException(defaultDeserializationContext_Impl0, sQLNonTransientException0);
assertEquals("`com.fasterxml.jackson.databind.introspect.BasicBeanDescription`", stdValueInstantiator0.getValueTypeDesc());
}
@Test(timeout = 4000)
public void test52() throws Throwable {
BeanDeserializerFactory beanDeserializerFactory0 = BeanDeserializerFactory.instance;
DefaultDeserializationContext.Impl defaultDeserializationContext_Impl0 = new DefaultDeserializationContext.Impl(beanDeserializerFactory0);
Class<Vector> class0 = Vector.class;
StdValueInstantiator stdValueInstantiator0 = new StdValueInstantiator((DeserializationConfig) null, class0);
SQLNonTransientException sQLNonTransientException0 = new SQLNonTransientException();
SQLIntegrityConstraintViolationException sQLIntegrityConstraintViolationException0 = new SQLIntegrityConstraintViolationException("", "", 609, sQLNonTransientException0);
SQLTimeoutException sQLTimeoutException0 = new SQLTimeoutException("", sQLIntegrityConstraintViolationException0);
// Undeclared exception!
try {
stdValueInstantiator0.unwrapAndWrapException(defaultDeserializationContext_Impl0, sQLTimeoutException0);
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("com.fasterxml.jackson.databind.DeserializationContext", e);
}
}
@Test(timeout = 4000)
public void test53() throws Throwable {
BeanDeserializerFactory beanDeserializerFactory0 = BeanDeserializerFactory.instance;
DefaultDeserializationContext.Impl defaultDeserializationContext_Impl0 = new DefaultDeserializationContext.Impl(beanDeserializerFactory0);
Class<InputStream> class0 = InputStream.class;
StdValueInstantiator stdValueInstantiator0 = new StdValueInstantiator((DeserializationConfig) null, class0);
SQLTransientException sQLTransientException0 = new SQLTransientException("java.util.NavigableSet", "java.util.NavigableSet", 0, (Throwable) null);
JsonMappingException jsonMappingException0 = JsonMappingException.from((DeserializationContext) defaultDeserializationContext_Impl0, "com.fasterxml.jackson.databind.ser.std.InetSocketAddressSerializer", (Throwable) sQLTransientException0);
SQLNonTransientException sQLNonTransientException0 = new SQLNonTransientException("", "com.fasterxml.jackson.databind.ser.std.InetSocketAddressSerializer", jsonMappingException0);
JsonMappingException jsonMappingException1 = stdValueInstantiator0.wrapException(sQLNonTransientException0);
assertEquals("`java.io.InputStream`", stdValueInstantiator0.getValueTypeDesc());
assertSame(jsonMappingException1, jsonMappingException0);
}
@Test(timeout = 4000)
public void test54() throws Throwable {
TypeFactory typeFactory0 = TypeFactory.defaultInstance();
Class<Vector> class0 = Vector.class;
CollectionType collectionType0 = typeFactory0.constructCollectionType(class0, class0);
BeanDeserializerFactory beanDeserializerFactory0 = BeanDeserializerFactory.instance;
DefaultDeserializationContext.Impl defaultDeserializationContext_Impl0 = new DefaultDeserializationContext.Impl(beanDeserializerFactory0);
StdValueInstantiator stdValueInstantiator0 = new StdValueInstantiator((DeserializationConfig) null, collectionType0);
// Undeclared exception!
try {
stdValueInstantiator0.createFromDouble(defaultDeserializationContext_Impl0, 0.0);
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("com.fasterxml.jackson.databind.DeserializationContext", e);
}
}
@Test(timeout = 4000)
public void test55() throws Throwable {
StdSubtypeResolver stdSubtypeResolver0 = new StdSubtypeResolver();
SimpleMixInResolver simpleMixInResolver0 = new SimpleMixInResolver((ClassIntrospector.MixInResolver) null);
RootNameLookup rootNameLookup0 = new RootNameLookup();
ConfigOverrides configOverrides0 = new ConfigOverrides();
DeserializationConfig deserializationConfig0 = new DeserializationConfig((BaseSettings) null, stdSubtypeResolver0, simpleMixInResolver0, rootNameLookup0, configOverrides0);
Class<Module> class0 = Module.class;
StdValueInstantiator stdValueInstantiator0 = new StdValueInstantiator(deserializationConfig0, class0);
BeanDeserializerFactory beanDeserializerFactory0 = BeanDeserializerFactory.instance;
DefaultDeserializationContext.Impl defaultDeserializationContext_Impl0 = new DefaultDeserializationContext.Impl(beanDeserializerFactory0);
// Undeclared exception!
try {
stdValueInstantiator0.createFromLong(defaultDeserializationContext_Impl0, 2391L);
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("com.fasterxml.jackson.databind.DeserializationContext", e);
}
}
@Test(timeout = 4000)
public void test56() throws Throwable {
BeanDeserializerFactory beanDeserializerFactory0 = BeanDeserializerFactory.instance;
DefaultDeserializationContext.Impl defaultDeserializationContext_Impl0 = new DefaultDeserializationContext.Impl(beanDeserializerFactory0);
TypeFactory typeFactory0 = TypeFactory.defaultInstance();
Class<Vector> class0 = Vector.class;
CollectionType collectionType0 = typeFactory0.constructCollectionType(class0, class0);
StdValueInstantiator stdValueInstantiator0 = new StdValueInstantiator((DeserializationConfig) null, collectionType0);
// Undeclared exception!
try {
stdValueInstantiator0.createFromInt(defaultDeserializationContext_Impl0, 8233);
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("com.fasterxml.jackson.databind.DeserializationContext", e);
}
}
@Test(timeout = 4000)
public void test57() throws Throwable {
Class<InvocationTargetException> class0 = InvocationTargetException.class;
StdValueInstantiator stdValueInstantiator0 = new StdValueInstantiator((DeserializationConfig) null, class0);
BeanDeserializerFactory beanDeserializerFactory0 = BeanDeserializerFactory.instance;
DefaultDeserializationContext.Impl defaultDeserializationContext_Impl0 = new DefaultDeserializationContext.Impl(beanDeserializerFactory0);
// Undeclared exception!
try {
stdValueInstantiator0.createFromString(defaultDeserializationContext_Impl0, "7\"");
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("com.fasterxml.jackson.databind.DeserializationContext", e);
}
}
@Test(timeout = 4000)
public void test58() throws Throwable {
Class<String> class0 = String.class;
StdValueInstantiator stdValueInstantiator0 = new StdValueInstantiator((DeserializationConfig) null, class0);
BeanDeserializerFactory beanDeserializerFactory0 = BeanDeserializerFactory.instance;
DefaultDeserializationContext.Impl defaultDeserializationContext_Impl0 = new DefaultDeserializationContext.Impl(beanDeserializerFactory0);
Object[] objectArray0 = new Object[1];
// Undeclared exception!
try {
stdValueInstantiator0.createFromObjectWith((DeserializationContext) defaultDeserializationContext_Impl0, objectArray0);
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("com.fasterxml.jackson.databind.DeserializationContext", e);
}
}
@Test(timeout = 4000)
public void test59() throws Throwable {
Class<String> class0 = String.class;
StdValueInstantiator stdValueInstantiator0 = new StdValueInstantiator((DeserializationConfig) null, class0);
JavaType javaType0 = TypeFactory.unknownType();
stdValueInstantiator0.configureFromArraySettings((AnnotatedWithParams) null, javaType0, (SettableBeanProperty[]) null);
boolean boolean0 = stdValueInstantiator0.canInstantiate();
assertTrue(stdValueInstantiator0.canCreateUsingArrayDelegate());
assertTrue(boolean0);
}
@Test(timeout = 4000)
public void test60() throws Throwable {
Class<ExceptionInInitializerError> class0 = ExceptionInInitializerError.class;
StdValueInstantiator stdValueInstantiator0 = new StdValueInstantiator((DeserializationConfig) null, class0);
BeanProperty.Bogus beanProperty_Bogus0 = new BeanProperty.Bogus();
JavaType javaType0 = beanProperty_Bogus0.getType();
stdValueInstantiator0.configureFromArraySettings((AnnotatedWithParams) null, javaType0, (SettableBeanProperty[]) null);
boolean boolean0 = stdValueInstantiator0.canCreateUsingArrayDelegate();
assertTrue(stdValueInstantiator0.canInstantiate());
assertTrue(boolean0);
}
@Test(timeout = 4000)
public void test61() throws Throwable {
TypeFactory typeFactory0 = TypeFactory.defaultInstance();
JavaType javaType0 = TypeFactory.unknownType();
ArrayType arrayType0 = typeFactory0.constructArrayType(javaType0);
StdValueInstantiator stdValueInstantiator0 = new StdValueInstantiator((DeserializationConfig) null, arrayType0);
stdValueInstantiator0.configureFromObjectSettings((AnnotatedWithParams) null, (AnnotatedWithParams) null, arrayType0, (SettableBeanProperty[]) null, (AnnotatedWithParams) null, (SettableBeanProperty[]) null);
boolean boolean0 = stdValueInstantiator0.canInstantiate();
assertTrue(stdValueInstantiator0.canCreateUsingDelegate());
assertTrue(boolean0);
}
@Test(timeout = 4000)
public void test62() throws Throwable {
TypeFactory typeFactory0 = TypeFactory.defaultInstance();
JavaType javaType0 = TypeFactory.unknownType();
ArrayType arrayType0 = typeFactory0.constructArrayType(javaType0);
StdValueInstantiator stdValueInstantiator0 = new StdValueInstantiator((DeserializationConfig) null, arrayType0);
boolean boolean0 = stdValueInstantiator0.canInstantiate();
assertEquals("[array type, component type: [simple type, class java.lang.Object]]", stdValueInstantiator0.getValueTypeDesc());
assertFalse(boolean0);
}
@Test(timeout = 4000)
public void test63() throws Throwable {
StdValueInstantiator stdValueInstantiator0 = new StdValueInstantiator((DeserializationConfig) null, (Class<?>) null);
BeanDeserializerFactory beanDeserializerFactory0 = BeanDeserializerFactory.instance;
DefaultDeserializationContext.Impl defaultDeserializationContext_Impl0 = new DefaultDeserializationContext.Impl(beanDeserializerFactory0);
// Undeclared exception!
try {
stdValueInstantiator0.createFromBoolean(defaultDeserializationContext_Impl0, false);
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("com.fasterxml.jackson.databind.DeserializationContext", e);
}
}
@Test(timeout = 4000)
public void test64() throws Throwable {
TypeFactory typeFactory0 = TypeFactory.defaultInstance();
JavaType javaType0 = TypeFactory.unknownType();
ArrayType arrayType0 = typeFactory0.constructArrayType(javaType0);
StdValueInstantiator stdValueInstantiator0 = new StdValueInstantiator((DeserializationConfig) null, arrayType0);
stdValueInstantiator0.getWithArgsCreator();
assertEquals("[array type, component type: [simple type, class java.lang.Object]]", stdValueInstantiator0.getValueTypeDesc());
}
@Test(timeout = 4000)
public void test65() throws Throwable {
Class<Module> class0 = Module.class;
StdValueInstantiator stdValueInstantiator0 = new StdValueInstantiator((DeserializationConfig) null, class0);
stdValueInstantiator0.getDefaultCreator();
assertEquals("`com.fasterxml.jackson.databind.Module`", stdValueInstantiator0.getValueTypeDesc());
}
@Test(timeout = 4000)
public void test66() throws Throwable {
Class<Object> class0 = Object.class;
StdValueInstantiator stdValueInstantiator0 = new StdValueInstantiator((DeserializationConfig) null, class0);
stdValueInstantiator0.getArrayDelegateType((DeserializationConfig) null);
assertEquals("`java.lang.Object`", stdValueInstantiator0.getValueTypeDesc());
}
@Test(timeout = 4000)
public void test67() throws Throwable {
Class<JsonMappingException> class0 = JsonMappingException.class;
StdValueInstantiator stdValueInstantiator0 = new StdValueInstantiator((DeserializationConfig) null, class0);
stdValueInstantiator0.getArrayDelegateCreator();
assertEquals("`com.fasterxml.jackson.databind.JsonMappingException`", stdValueInstantiator0.getValueTypeDesc());
}
@Test(timeout = 4000)
public void test68() throws Throwable {
DefaultSerializerProvider.Impl defaultSerializerProvider_Impl0 = new DefaultSerializerProvider.Impl();
BeanDeserializerFactory beanDeserializerFactory0 = BeanDeserializerFactory.instance;
DefaultDeserializationContext.Impl defaultDeserializationContext_Impl0 = new DefaultDeserializationContext.Impl(beanDeserializerFactory0);
ObjectMapper objectMapper0 = new ObjectMapper((JsonFactory) null, defaultSerializerProvider_Impl0, defaultDeserializationContext_Impl0);
Class<BasicBeanDescription> class0 = BasicBeanDescription.class;
ObjectReader objectReader0 = objectMapper0.readerFor(class0);
assertNotNull(objectReader0);
}
@Test(timeout = 4000)
public void test69() throws Throwable {
TypeFactory typeFactory0 = TypeFactory.defaultInstance();
JavaType javaType0 = TypeFactory.unknownType();
ArrayType arrayType0 = typeFactory0.constructArrayType(javaType0);
StdValueInstantiator stdValueInstantiator0 = new StdValueInstantiator((DeserializationConfig) null, arrayType0);
stdValueInstantiator0.getDelegateType((DeserializationConfig) null);
assertEquals("[array type, component type: [simple type, class java.lang.Object]]", stdValueInstantiator0.getValueTypeDesc());
}
}
|
[
"[email protected]"
] | |
707e331f189e48e3ea1071718afa47bbaaad3c4d
|
7cc560530e008d05b79316434761a324c6ed377a
|
/NEERC09/data/business/business_re.java
|
a80767fba8fb2b5a5c18a375c2e10ca06a4a7bd1
|
[] |
no_license
|
nbarshay/comp
|
63bcdeaa05cef7c86b25e900bfea72f3bd14a2d1
|
266891fcb950e6da38461a2f7fb21fc7e92827be
|
refs/heads/master
| 2021-01-16T19:35:13.272267 | 2013-05-18T00:04:03 | 2013-05-18T00:04:03 | 9,780,520 | 1 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 4,319 |
java
|
import java.io.*;
import java.util.*;
/**
* Solution for NEERC'2009 Problem B: Business Center
* This solution checks correctness of the input.
* @author Roman Elizarov
*/
public class business_re {
public static void main(String[] args) throws Exception {
new business_re().go();
}
void go() throws Exception {
read();
solve();
write();
}
int n;
int m;
int[] u;
int[] d;
void read() throws Exception {
Scanner in = new Scanner(new File("business.in"));
in.useLocale(Locale.US);
n = in.nextInt();
m = in.nextInt();
in.nextLine();
assert n >= 1 && n <= 1000000;
assert m >= 1 && m <= 2000;
u = new int[m];
d = new int[m];
for (int i = 0; i < m; i++) {
u[i] = in.nextInt();
d[i] = in.nextInt();
in.nextLine();
assert u[i] >= 1 && u[i] <= 1000;
assert d[i] >= 1 && d[i] <= 1000;
}
in.close();
}
int lowest = Integer.MAX_VALUE;
void solve() {
for (int i = 0; i < m; i++) {
// min { a * u - (n - a) * d }
// a * (u + d) = n * d
// a = n * d / (u + d)
int a = n * d[i] / (u[i] + d[i]) + 1;
int res = a * u[i] - (n - a) * d[i];
lowest = Math.min(lowest, res);
}
}
void write() throws Exception {
PrintWriter out = new PrintWriter("business.out");
out.println(lowest);
out.close();
}
//----------------- just for validation ------------------
/**
* Strict scanner to veryfy 100% correspondence between input files and input file format specification.
* It is a drop-in replacement for {@link java.util.Scanner} that could be added to a soulution source
* (cut-and-paste) without breaking its ability to work with {@link java.util.Scanner}.
*/
public class Scanner {
private final BufferedReader in;
private String line = "";
private int pos;
private int lineNo;
private boolean localeset;
public Scanner(File source) throws FileNotFoundException {
in = new BufferedReader(new FileReader(source));
nextLine();
}
public void close() {
assert line == null : "Extra data at the end of file";
try {
in.close();
} catch (IOException e) {
throw new AssertionError("Failed to close with " + e);
}
}
public void nextLine() {
assert line != null : "EOF";
assert pos == line.length() : "Extra characters on line " + lineNo;
try {
line = in.readLine();
} catch (IOException e) {
throw new AssertionError("Failed to read line with " + e);
}
pos = 0;
lineNo++;
}
public String next() {
assert line != null : "EOF";
assert line.length() > 0 : "Empty line " + lineNo;
if (pos == 0)
assert line.charAt(0) > ' ' : "Line " + lineNo + " starts with whitespace";
else {
assert pos < line.length() : "Line " + lineNo + " is over";
assert line.charAt(pos) == ' ' : "Wrong whitespace on line " + lineNo;
pos++;
assert pos < line.length() : "Line " + lineNo + " is over";
assert line.charAt(0) > ' ' : "Line " + lineNo + " has double whitespace";
}
StringBuilder sb = new StringBuilder();
while (pos < line.length() && line.charAt(pos) > ' ')
sb.append(line.charAt(pos++));
return sb.toString();
}
public int nextInt() {
String s = next();
assert s.length() == 1 || s.charAt(0) != '0' : "Extra leading zero in number " + s + " on line " + lineNo;
assert s.charAt(0) != '+' : "Extra leading '+' in number " + s + " on line " + lineNo;
try {
return Integer.parseInt(s);
} catch (NumberFormatException e) {
throw new AssertionError("Malformed number " + s + " on line " + lineNo);
}
}
public double nextDouble() {
assert localeset : "Locale must be set with useLocale(Locale.US)";
String s = next();
assert s.length() == 1 || s.startsWith("0.") || s.charAt(0) != '0' : "Extra leading zero in number " + s + " on line " + lineNo;
assert s.charAt(0) != '+' : "Extra leading '+' in number " + s + " on line " + lineNo;
try {
return Double.parseDouble(s);
} catch (NumberFormatException e) {
throw new AssertionError("Malformed number " + s + " on line " + lineNo);
}
}
public void useLocale(Locale locale) {
assert locale == Locale.US;
localeset = true;
}
}
}
|
[
"[email protected]"
] | |
3fe0833bfe73efa41978beb036dbf068eae19a22
|
fa91450deb625cda070e82d5c31770be5ca1dec6
|
/Diff-Raw-Data/27/27_7b4dc184f71d0184f6992df663307f3d9eeea6ac/Peer/27_7b4dc184f71d0184f6992df663307f3d9eeea6ac_Peer_t.java
|
9c8698e6002bca96af2cee4732f4ce57758832af
|
[] |
no_license
|
zhongxingyu/Seer
|
48e7e5197624d7afa94d23f849f8ea2075bcaec0
|
c11a3109fdfca9be337e509ecb2c085b60076213
|
refs/heads/master
| 2023-07-06T12:48:55.516692 | 2023-06-22T07:55:56 | 2023-06-22T07:55:56 | 259,613,157 | 6 | 2 | null | 2023-06-22T07:55:57 | 2020-04-28T11:07:49 | null |
UTF-8
|
Java
| false | false | 40,093 |
java
|
/**
* Copyright 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.bitcoin.core;
import com.google.bitcoin.store.BlockStore;
import com.google.bitcoin.store.BlockStoreException;
import com.google.bitcoin.utils.EventListenerInvoker;
import com.google.common.base.Objects;
import com.google.common.base.Preconditions;
import org.jboss.netty.channel.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.net.ConnectException;
import java.net.InetSocketAddress;
import java.util.*;
import java.util.concurrent.*;
/**
* A Peer handles the high level communication with a Bitcoin node.
*
* <p>{@link Peer#getHandler()} is part of a Netty Pipeline with a Bitcoin serializer downstream of it.
*/
public class Peer {
interface PeerLifecycleListener {
/** Called when the peer is connected */
public void onPeerConnected(Peer peer);
/** Called when the peer is disconnected */
public void onPeerDisconnected(Peer peer);
}
private static final Logger log = LoggerFactory.getLogger(Peer.class);
private final NetworkParameters params;
private final BlockChain blockChain;
// When an API user explicitly requests a block or transaction from a peer, the InventoryItem is put here
// whilst waiting for the response. Synchronized on itself. Is not used for downloads Peer generates itself.
// TODO: Make this work for transactions as well.
private final List<GetDataFuture<Block>> pendingGetBlockFutures;
private PeerAddress address;
private List<PeerEventListener> eventListeners;
private List<PeerLifecycleListener> lifecycleListeners;
// Whether to try and download blocks and transactions from this peer. Set to false by PeerGroup if not the
// primary peer. This is to avoid redundant work and concurrency problems with downloading the same chain
// in parallel.
private boolean downloadData = true;
// The version data to announce to the other side of the connections we make: useful for setting our "user agent"
// equivalent and other things.
private VersionMessage versionMessage;
// A class that tracks recent transactions that have been broadcast across the network, counts how many
// peers announced them and updates the transaction confidence data. It is passed to each Peer.
private MemoryPool memoryPool;
// A time before which we only download block headers, after that point we download block bodies.
private long fastCatchupTimeSecs;
// Whether we are currently downloading headers only or block bodies. Defaults to true, if the fast catchup time
// is set AND our best block is before that date, switch to false until block headers beyond that point have been
// received at which point it gets set to true again. This isn't relevant unless downloadData is true.
private boolean downloadBlockBodies = true;
// Keeps track of things we requested internally with getdata but didn't receive yet, so we can avoid re-requests.
// It's not quite the same as pendingGetBlockFutures, as this is used only for getdatas done as part of downloading
// the chain and so is lighter weight (we just keep a bunch of hashes not futures).
//
// It is important to avoid a nasty edge case where we can end up with parallel chain downloads proceeding
// simultaneously if we were to receive a newly solved block whilst parts of the chain are streaming to us.
private HashSet<Sha256Hash> pendingBlockDownloads = new HashSet<Sha256Hash>();
private Channel channel;
private VersionMessage peerVersionMessage;
boolean isAcked;
private PeerHandler handler;
/**
* Construct a peer that reads/writes from the given block chain.
*/
public Peer(NetworkParameters params, BlockChain blockChain, VersionMessage ver) {
this.params = params;
this.blockChain = blockChain;
this.versionMessage = ver;
this.pendingGetBlockFutures = new ArrayList<GetDataFuture<Block>>();
this.eventListeners = new CopyOnWriteArrayList<PeerEventListener>();
this.lifecycleListeners = new CopyOnWriteArrayList<PeerLifecycleListener>();
this.fastCatchupTimeSecs = params.genesisBlock.getTimeSeconds();
this.isAcked = false;
this.handler = new PeerHandler();
}
/**
* Construct a peer that reads/writes from the given chain. Automatically creates a VersionMessage for you from the
* given software name/version strings, which should be something like "MySimpleTool", "1.0"
*/
public Peer(NetworkParameters params, BlockChain blockChain, String thisSoftwareName, String thisSoftwareVersion) {
this(params, blockChain, null);
this.versionMessage = new VersionMessage(params, blockChain.getBestChainHeight());
this.versionMessage.appendToSubVer(thisSoftwareName, thisSoftwareVersion, null);
}
public synchronized void addEventListener(PeerEventListener listener) {
eventListeners.add(listener);
}
public synchronized boolean removeEventListener(PeerEventListener listener) {
return eventListeners.remove(listener);
}
synchronized void addLifecycleListener(PeerLifecycleListener listener) {
lifecycleListeners.add(listener);
}
synchronized boolean removeLifecycleListener(PeerLifecycleListener listener) {
return lifecycleListeners.remove(listener);
}
/**
* Tells the peer to insert received transactions/transaction announcements into the given {@link MemoryPool}.
* This is normally done for you by the {@link PeerGroup} so you don't have to think about it. Transactions stored
* in a memory pool will have their confidence levels updated when a peer announces it, to reflect the greater
* likelyhood that the transaction is valid.
*
* @param pool A new pool or null to unlink.
*/
public synchronized void setMemoryPool(MemoryPool pool) {
memoryPool = pool;
}
@Override
public String toString() {
if (address == null) {
// User-provided NetworkConnection object.
return "Peer()";
} else {
return "Peer(" + address.getAddr() + ":" + address.getPort() + ")";
}
}
private void notifyDisconnect() {
for (PeerLifecycleListener listener : lifecycleListeners) {
synchronized (listener) {
listener.onPeerDisconnected(Peer.this);
}
}
}
class PeerHandler extends SimpleChannelHandler {
@Override
public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e)
throws Exception {
super.channelClosed(ctx, e);
notifyDisconnect();
}
@Override
public void connectRequested(ChannelHandlerContext ctx, ChannelStateEvent e)
throws Exception {
super.connectRequested(ctx, e);
channel = e.getChannel();
address = new PeerAddress((InetSocketAddress)e.getValue());
}
/** Catch any exceptions, logging them and then closing the channel. */
@Override
public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e)
throws Exception {
if (e.getCause() instanceof ConnectException || e.getCause() instanceof IOException) {
// Short message for network errors
log.info(toString() + " - " + e.getCause().getMessage());
} else {
log.warn(toString() + " - ", e.getCause());
}
e.getChannel().close();
}
/** Handle incoming Bitcoin messages */
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
Message m = (Message)e.getMessage();
// Allow event listeners to filter the message stream. Listeners are allowed to drop messages by
// returning null.
synchronized (Peer.this) {
for (PeerEventListener listener : eventListeners) {
synchronized (listener) {
m = listener.onPreMessageReceived(Peer.this, m);
if (m == null) break;
}
}
}
if (m == null) return;
if (m instanceof InventoryMessage) {
processInv((InventoryMessage) m);
} else if (m instanceof Block) {
processBlock((Block) m);
} else if (m instanceof Transaction) {
processTransaction((Transaction) m);
} else if (m instanceof GetDataMessage) {
processGetData((GetDataMessage) m);
} else if (m instanceof AddressMessage) {
// We don't care about addresses of the network right now. But in future,
// we should save them in the wallet so we don't put too much load on the seed nodes and can
// properly explore the network.
} else if (m instanceof HeadersMessage) {
processHeaders((HeadersMessage) m);
} else if (m instanceof AlertMessage) {
processAlert((AlertMessage)m);
} else if (m instanceof VersionMessage) {
peerVersionMessage = (VersionMessage)m;
EventListenerInvoker.invoke(lifecycleListeners,
new EventListenerInvoker<PeerLifecycleListener>() {
@Override
public void invoke(PeerLifecycleListener listener) {
listener.onPeerConnected(Peer.this);
}
});
} else if (m instanceof VersionAck) {
if (peerVersionMessage == null) {
throw new ProtocolException("got a version ack before version");
}
if (isAcked) {
throw new ProtocolException("got more than one version ack");
}
isAcked = true;
} else if (m instanceof Ping) {
if (((Ping) m).hasNonce())
sendMessage(new Pong(((Ping) m).getNonce()));
} else if (m instanceof Pong) {
// We don't do anything with pongs right now, leave that to eventListeners
} else {
// TODO: Handle the other messages we can receive.
log.warn("Received unhandled message: {}", m);
}
}
public Peer getPeer() {
return Peer.this;
}
}
private void processAlert(AlertMessage m) {
try {
if (m.isSignatureValid()) {
log.info("Received alert from peer {}: {}", toString(), m.getStatusBar());
} else {
log.warn("Received alert with invalid signature from peer {}: {}", toString(), m.getStatusBar());
}
} catch (Throwable t) {
// Signature checking can FAIL on Android platforms before Gingerbread apparently due to bugs in their
// BigInteger implementations! See issue 160 for discussion. As alerts are just optional and not that
// useful, we just swallow the error here.
log.error("Failed to check signature: bug in platform libraries?", t);
}
}
/** Returns the Netty Pipeline stage handling the high level Bitcoin protocol. */
public PeerHandler getHandler() {
return handler;
}
private void processHeaders(HeadersMessage m) throws IOException, ProtocolException {
// Runs in network loop thread for this peer.
//
// This method can run if a peer just randomly sends us a "headers" message (should never happen), or more
// likely when we've requested them as part of chain download using fast catchup. We need to add each block to
// the chain if it pre-dates the fast catchup time. If we go past it, we can stop processing the headers and
// request the full blocks from that point on instead.
Preconditions.checkState(!downloadBlockBodies, toString());
try {
for (int i = 0; i < m.getBlockHeaders().size(); i++) {
Block header = m.getBlockHeaders().get(i);
if (header.getTimeSeconds() < fastCatchupTimeSecs) {
if (blockChain.add(header)) {
// The block was successfully linked into the chain. Notify the user of our progress.
invokeOnBlocksDownloaded(header);
} else {
// This block is unconnected - we don't know how to get from it back to the genesis block yet.
// That must mean that the peer is buggy or malicious because we specifically requested for
// headers that are part of the best chain.
throw new ProtocolException("Got unconnected header from peer: " + header.getHashAsString());
}
} else {
log.info("Passed the fast catchup time, discarding {} headers and requesting full blocks",
m.getBlockHeaders().size() - i);
downloadBlockBodies = true;
lastGetBlocksBegin = Sha256Hash.ZERO_HASH; // Prevent this request being seen as a duplicate.
blockChainDownload(Sha256Hash.ZERO_HASH);
return;
}
}
// We added all headers in the message to the chain. Request some more if we got up to the limit, otherwise
// we are at the end of the chain.
if (m.getBlockHeaders().size() >= HeadersMessage.MAX_HEADERS)
blockChainDownload(Sha256Hash.ZERO_HASH);
} catch (VerificationException e) {
log.warn("Block header verification failed", e);
} catch (ScriptException e) {
// There are no transactions and thus no scripts in these blocks, so this should never happen.
throw new RuntimeException(e);
}
}
private synchronized void processGetData(GetDataMessage getdata) throws IOException {
log.info("{}: Received getdata message: {}", address, getdata.toString());
ArrayList<Message> items = new ArrayList<Message>();
for (PeerEventListener listener : eventListeners) {
synchronized (listener) {
List<Message> listenerItems = listener.getData(this, getdata);
if (listenerItems == null) continue;
items.addAll(listenerItems);
}
}
if (items.size() == 0) {
return;
}
log.info("{}: Sending {} items gathered from listeners to peer", address, items.size());
for (Message item : items) {
sendMessage(item);
}
}
private synchronized void processTransaction(Transaction tx) {
log.debug("{}: Received broadcast tx {}", address, tx.getHashAsString());
if (memoryPool != null) {
// We may get back a different transaction object.
tx = memoryPool.seen(tx, getAddress());
}
final Transaction ftx = tx;
EventListenerInvoker.invoke(eventListeners, new EventListenerInvoker<PeerEventListener>() {
@Override
public void invoke(PeerEventListener listener) {
listener.onTransaction(Peer.this, ftx);
}
});
}
private void processBlock(Block m) throws IOException {
log.debug("{}: Received broadcast block {}", address, m.getHashAsString());
try {
// Was this block requested by getBlock()?
synchronized (pendingGetBlockFutures) {
for (int i = 0; i < pendingGetBlockFutures.size(); i++) {
GetDataFuture<Block> f = pendingGetBlockFutures.get(i);
if (f.getItem().hash.equals(m.getHash())) {
// Yes, it was. So pass it through the future.
f.setResult(m);
// Blocks explicitly requested don't get sent to the block chain.
pendingGetBlockFutures.remove(i);
return;
}
}
}
if (!downloadData) {
log.warn("Received block we did not ask for: {}", m.getHashAsString());
return;
}
pendingBlockDownloads.remove(m.getHash());
// Otherwise it's a block sent to us because the peer thought we needed it, so add it to the block chain.
// This call will synchronize on blockChain.
if (blockChain.add(m)) {
// The block was successfully linked into the chain. Notify the user of our progress.
invokeOnBlocksDownloaded(m);
} else {
// This block is an orphan - we don't know how to get from it back to the genesis block yet. That
// must mean that there are blocks we are missing, so do another getblocks with a new block locator
// to ask the peer to send them to us. This can happen during the initial block chain download where
// the peer will only send us 500 at a time and then sends us the head block expecting us to request
// the others.
//
// We must do two things here:
// (1) Request from current top of chain to the oldest ancestor of the received block in the orphan set
// (2) Filter out duplicate getblock requests (done in blockChainDownload).
//
// The reason for (1) is that otherwise if new blocks were solved during the middle of chain download
// we'd do a blockChainDownload() on the new best chain head, which would cause us to try and grab the
// chain twice (or more!) on the same connection! The block chain would filter out the duplicates but
// only at a huge speed penalty. By finding the orphan root we ensure every getblocks looks the same
// no matter how many blocks are solved, and therefore that the (2) duplicate filtering can work.
blockChainDownload(blockChain.getOrphanRoot(m.getHash()).getHash());
}
} catch (VerificationException e) {
// We don't want verification failures to kill the thread.
log.warn("Block verification failed", e);
} catch (ScriptException e) {
// We don't want script failures to kill the thread.
log.warn("Script exception", e);
}
}
private synchronized void invokeOnBlocksDownloaded(final Block m) {
// It is possible for the peer block height difference to be negative when blocks have been solved and broadcast
// since the time we first connected to the peer. However, it's weird and unexpected to receive a callback
// with negative "blocks left" in this case, so we clamp to zero so the API user doesn't have to think about it.
final int blocksLeft = Math.max(0, getPeerBlockHeightDifference());
EventListenerInvoker.invoke(eventListeners, new EventListenerInvoker<PeerEventListener>() {
@Override
public void invoke(PeerEventListener listener) {
listener.onBlocksDownloaded(Peer.this, m, blocksLeft);
}
});
}
private void processInv(InventoryMessage inv) throws IOException {
// This should be called in the network loop thread for this peer.
List<InventoryItem> items = inv.getItems();
// Separate out the blocks and transactions, we'll handle them differently
List<InventoryItem> transactions = new LinkedList<InventoryItem>();
List<InventoryItem> blocks = new LinkedList<InventoryItem>();
for (InventoryItem item : items) {
switch (item.type) {
case Transaction: transactions.add(item); break;
case Block: blocks.add(item); break;
default: throw new IllegalStateException("Not implemented: " + item.type);
}
}
GetDataMessage getdata = new GetDataMessage(params);
Iterator<InventoryItem> it = transactions.iterator();
while (it.hasNext()) {
InventoryItem item = it.next();
if (memoryPool == null) {
if (downloadData) {
// If there's no memory pool only download transactions if we're configured to.
getdata.addItem(item);
}
} else {
// Only download the transaction if we are the first peer that saw it be advertised. Other peers will also
// see it be advertised in inv packets asynchronously, they co-ordinate via the memory pool. We could
// potentially download transactions faster by always asking every peer for a tx when advertised, as remote
// peers run at different speeds. However to conserve bandwidth on mobile devices we try to only download a
// transaction once. This means we can miss broadcasts if the peer disconnects between sending us an inv and
// sending us the transaction: currently we'll never try to re-fetch after a timeout.
if (memoryPool.maybeWasSeen(item.hash)) {
// Some other peer already announced this so don't download.
it.remove();
} else {
log.debug("{}: getdata on tx {}", address, item.hash);
getdata.addItem(item);
}
memoryPool.seen(item.hash, this.getAddress());
}
}
if (blocks.size() > 0 && downloadData) {
// Ideally, we'd only ask for the data here if we actually needed it. However that can imply a lot of
// disk IO to figure out what we've got. Normally peers will not send us inv for things we already have
// so we just re-request it here, and if we get duplicates the block chain / wallet will filter them out.
for (InventoryItem item : blocks) {
if (blockChain.isOrphan(item.hash)) {
// If an orphan was re-advertised, ask for more blocks.
blockChainDownload(blockChain.getOrphanRoot(item.hash).getHash());
} else {
// Don't re-request blocks we already requested. Normally this should not happen. However there is
// an edge case: if a block is solved and we complete the inv<->getdata<->block<->getblocks cycle
// whilst other parts of the chain are streaming in, then the new getblocks request won't match the
// previous one: whilst the stopHash is the same (because we use the orphan root), the start hash
// will be different and so the getblocks req won't be dropped as a duplicate. We'll end up
// requesting a subset of what we already requested, which can lead to parallel chain downloads
// and other nastyness. So we just do a quick removal of redundant getdatas here too.
//
// Note that as of June 2012 the Satoshi client won't actually ever interleave blocks pushed as
// part of chain download with newly announced blocks, so it should always be taken care of by
// the duplicate check in blockChainDownload(). But the satoshi client may change in future so
// it's better to be safe here.
if (!pendingBlockDownloads.contains(item.hash)) {
getdata.addItem(item);
pendingBlockDownloads.add(item.hash);
}
}
}
// If we're downloading the chain, doing a getdata on the last block we were told about will cause the
// peer to advertize the head block to us in a single-item inv. When we download THAT, it will be an
// orphan block, meaning we'll re-enter blockChainDownload() to trigger another getblocks between the
// current best block we have and the orphan block. If more blocks arrive in the meantime they'll also
// become orphan.
}
if (!getdata.getItems().isEmpty()) {
// This will cause us to receive a bunch of block or tx messages.
sendMessage(getdata);
}
}
/**
* Asks the connected peer for the block of the given hash, and returns a Future representing the answer.
* If you want the block right away and don't mind waiting for it, just call .get() on the result. Your thread
* will block until the peer answers. You can also use the Future object to wait with a timeout, or just check
* whether it's done later.
*
* @param blockHash Hash of the block you wareare requesting.
* @throws IOException
*/
public Future<Block> getBlock(Sha256Hash blockHash) throws IOException {
log.info("Request to fetch block {}", blockHash);
GetDataMessage getdata = new GetDataMessage(params);
InventoryItem inventoryItem = new InventoryItem(InventoryItem.Type.Block, blockHash);
getdata.addItem(inventoryItem);
GetDataFuture<Block> future = new GetDataFuture<Block>(inventoryItem);
// Add to the list of things we're waiting for. It's important this come before the network send to avoid
// race conditions.
synchronized (pendingGetBlockFutures) {
pendingGetBlockFutures.add(future);
}
sendMessage(getdata);
return future;
}
/**
* When downloading the block chain, the bodies will be skipped for blocks created before the given date. Any
* transactions relevant to the wallet will therefore not be found, but if you know your wallet has no such
* transactions it doesn't matter and can save a lot of bandwidth and processing time. Note that the times of blocks
* isn't known until their headers are available and they are requested in chunks, so some headers may be downloaded
* twice using this scheme, but this optimization can still be a large win for newly created wallets.
*
* @param secondsSinceEpoch Time in seconds since the epoch or 0 to reset to always downloading block bodies.
*/
public void setFastCatchupTime(long secondsSinceEpoch) {
if (secondsSinceEpoch == 0) {
fastCatchupTimeSecs = params.genesisBlock.getTimeSeconds();
downloadBlockBodies = true;
} else {
fastCatchupTimeSecs = secondsSinceEpoch;
// If the given time is before the current chains head block time, then this has no effect (we already
// downloaded everything we need).
if (fastCatchupTimeSecs > blockChain.getChainHead().getHeader().getTimeSeconds()) {
downloadBlockBodies = false;
}
}
}
/**
* Links the given wallet to this peer. If you have multiple peers, you should use a {@link PeerGroup} to manage
* them and use the {@link PeerGroup#addWallet(Wallet)} method instead of registering the wallet with each peer
* independently, otherwise the wallet will receive duplicate notifications.
*/
public void addWallet(Wallet wallet) {
addEventListener(wallet.getPeerEventListener());
}
/** Unlinks the given wallet from peer. See {@link Peer#addWallet(Wallet)}. */
public void removeWallet(Wallet wallet) {
removeEventListener(wallet.getPeerEventListener());
}
// A GetDataFuture wraps the result of a getBlock or (in future) getTransaction so the owner of the object can
// decide whether to wait forever, wait for a short while or check later after doing other work.
private static class GetDataFuture<T extends Message> implements Future<T> {
private boolean cancelled;
private final InventoryItem item;
private final CountDownLatch latch;
private T result;
GetDataFuture(InventoryItem item) {
this.item = item;
this.latch = new CountDownLatch(1);
}
public boolean cancel(boolean b) {
// Cannot cancel a getdata - once sent, it's sent.
cancelled = true;
return false;
}
public boolean isCancelled() {
return cancelled;
}
public boolean isDone() {
return result != null || cancelled;
}
public T get() throws InterruptedException, ExecutionException {
latch.await();
return Preconditions.checkNotNull(result);
}
public T get(long l, TimeUnit timeUnit) throws InterruptedException, ExecutionException, TimeoutException {
if (!latch.await(l, timeUnit))
throw new TimeoutException();
return Preconditions.checkNotNull(result);
}
InventoryItem getItem() {
return item;
}
/** Called by the Peer when the result has arrived. Completes the task. */
void setResult(T result) {
// This should be called in the network loop thread for this peer
this.result = result;
// Now release the thread that is waiting. We don't need to synchronize here as the latch establishes
// a memory barrier.
latch.countDown();
}
}
/**
* Sends the given message on the peers Channel.
*/
public void sendMessage(Message m) throws IOException {
Channels.write(channel, m);
}
// Keep track of the last request we made to the peer in blockChainDownload so we can avoid redundant and harmful
// getblocks requests. This does not have to be synchronized because blockChainDownload cannot be called from
// multiple threads simultaneously.
private Sha256Hash lastGetBlocksBegin, lastGetBlocksEnd;
private void blockChainDownload(Sha256Hash toHash) throws IOException {
// This may run in ANY thread.
// The block chain download process is a bit complicated. Basically, we start with one or more blocks in a
// chain that we have from a previous session. We want to catch up to the head of the chain BUT we don't know
// where that chain is up to or even if the top block we have is even still in the chain - we
// might have got ourselves onto a fork that was later resolved by the network.
//
// To solve this, we send the peer a block locator which is just a list of block hashes. It contains the
// blocks we know about, but not all of them, just enough of them so the peer can figure out if we did end up
// on a fork and if so, what the earliest still valid block we know about is likely to be.
//
// Once it has decided which blocks we need, it will send us an inv with up to 500 block messages. We may
// have some of them already if we already have a block chain and just need to catch up. Once we request the
// last block, if there are still more to come it sends us an "inv" containing only the hash of the head
// block.
//
// That causes us to download the head block but then we find (in processBlock) that we can't connect
// it to the chain yet because we don't have the intermediate blocks. So we rerun this function building a
// new block locator describing where we're up to.
//
// The getblocks with the new locator gets us another inv with another bunch of blocks. We download them once
// again. This time when the peer sends us an inv with the head block, we already have it so we won't download
// it again - but we recognize this case as special and call back into blockChainDownload to continue the
// process.
//
// So this is a complicated process but it has the advantage that we can download a chain of enormous length
// in a relatively stateless manner and with constant memory usage.
//
// All this is made more complicated by the desire to skip downloading the bodies of blocks that pre-date the
// 'fast catchup time', which is usually set to the creation date of the earliest key in the wallet. Because
// we know there are no transactions using our keys before that date, we need only the headers. To do that we
// use the "getheaders" command. Once we find we've gone past the target date, we throw away the downloaded
// headers and then request the blocks from that point onwards. "getheaders" does not send us an inv, it just
// sends us the data we requested in a "headers" message.
// TODO: Block locators should be abstracted out rather than special cased here.
List<Sha256Hash> blockLocator = new ArrayList<Sha256Hash>(51);
// For now we don't do the exponential thinning as suggested here:
//
// https://en.bitcoin.it/wiki/Protocol_specification#getblocks
//
// This is because it requires scanning all the block chain headers, which is very slow. Instead we add the top
// 50 block headers. If there is a re-org deeper than that, we'll end up downloading the entire chain. We
// must always put the genesis block as the first entry.
BlockStore store = blockChain.getBlockStore();
StoredBlock chainHead = blockChain.getChainHead();
Sha256Hash chainHeadHash = chainHead.getHeader().getHash();
// Did we already make this request? If so, don't do it again.
if (Objects.equal(lastGetBlocksBegin, chainHeadHash) && Objects.equal(lastGetBlocksEnd, toHash)) {
log.info("blockChainDownload({}): ignoring duplicated request", toHash.toString());
return;
}
log.info("{}: blockChainDownload({}) current head = {}", new Object[] { toString(),
toHash.toString(), chainHead.getHeader().getHashAsString() });
StoredBlock cursor = chainHead;
for (int i = 100; cursor != null && i > 0; i--) {
blockLocator.add(cursor.getHeader().getHash());
try {
cursor = cursor.getPrev(store);
} catch (BlockStoreException e) {
log.error("Failed to walk the block chain whilst constructing a locator");
throw new RuntimeException(e);
}
}
// Only add the locator if we didn't already do so. If the chain is < 50 blocks we already reached it.
if (cursor != null) {
blockLocator.add(params.genesisBlock.getHash());
}
// Record that we requested this range of blocks so we can filter out duplicate requests in the event of a
// block being solved during chain download.
lastGetBlocksBegin = chainHeadHash;
lastGetBlocksEnd = toHash;
if (downloadBlockBodies) {
GetBlocksMessage message = new GetBlocksMessage(params, blockLocator, toHash);
sendMessage(message);
} else {
// Downloading headers for a while instead of full blocks.
GetHeadersMessage message = new GetHeadersMessage(params, blockLocator, toHash);
sendMessage(message);
}
}
/**
* Starts an asynchronous download of the block chain. The chain download is deemed to be complete once we've
* downloaded the same number of blocks that the peer advertised having in its version handshake message.
*/
public synchronized void startBlockChainDownload() throws IOException {
setDownloadData(true);
// TODO: peer might still have blocks that we don't have, and even have a heavier
// chain even if the chain block count is lower.
if (getPeerBlockHeightDifference() >= 0) {
EventListenerInvoker.invoke(eventListeners, new EventListenerInvoker<PeerEventListener>() {
@Override
public void invoke(PeerEventListener listener) {
listener.onChainDownloadStarted(Peer.this, getPeerBlockHeightDifference());
}
});
// When we just want as many blocks as possible, we can set the target hash to zero.
blockChainDownload(Sha256Hash.ZERO_HASH);
}
}
/**
* Returns the difference between our best chain height and the peers, which can either be positive if we are
* behind the peer, or negative if the peer is ahead of us.
*/
public int getPeerBlockHeightDifference() {
// Chain will overflow signed int blocks in ~41,000 years.
int chainHeight = (int) peerVersionMessage.bestHeight;
// chainHeight should not be zero/negative because we shouldn't have given the user a Peer that is to another
// client-mode node, nor should it be unconnected. If that happens it means the user overrode us somewhere or
// there is a bug in the peer management code.
Preconditions.checkState(chainHeight > 0, "Connected to peer with zero/negative chain height", chainHeight);
return chainHeight - blockChain.getChainHead().getHeight();
}
/**
* Returns true if this peer will try and download things it is sent in "inv" messages. Normally you only need
* one peer to be downloading data. Defaults to true.
*/
public boolean getDownloadData() {
return downloadData;
}
/**
* If set to false, the peer won't try and fetch blocks and transactions it hears about. Normally, only one
* peer should download missing blocks. Defaults to true.
*/
public void setDownloadData(boolean downloadData) {
this.downloadData = downloadData;
}
/**
* @return the IP address and port of peer.
*/
public PeerAddress getAddress() {
return address;
}
/**
* @return various version numbers claimed by peer.
*/
public VersionMessage getPeerVersionMessage() {
return peerVersionMessage;
}
/**
* @return various version numbers we claim.
*/
public VersionMessage getVersionMessage() {
return versionMessage;
}
/**
* @return the height of the best chain as claimed by peer.
*/
public long getBestHeight() {
return peerVersionMessage.bestHeight;
}
}
|
[
"[email protected]"
] | |
d45d6f41bfe50f659ef7bccd3a717b1507027255
|
466d62f9b33ba7a60238e202cfd9ac45f59af885
|
/CHLP_Service_API/src/main/java/com/jci/domain/MtrlDimCn.java
|
c47d3cb8528aa1f29d69efbc30e72f15297af9ea
|
[] |
no_license
|
yaoshixin007/PRJ_API-PROD2.0
|
19942457c4924ce18409235efd5b6504b715b0f8
|
cb711a4742ff0fd2201eeb046babe159c6893f20
|
refs/heads/master
| 2020-05-07T12:41:54.454425 | 2019-04-10T07:54:23 | 2019-04-10T07:54:23 | 180,505,086 | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 9,500 |
java
|
package com.jci.domain;
import java.io.Serializable;
import java.math.BigInteger;
import java.util.Calendar;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.ColumnResult;
import javax.persistence.ConstructorResult;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.SqlResultSetMapping;
import javax.persistence.Table;
import com.jci.transfer.QADProductsResponse;
/**
* The persistent class for the MTRL_DIM_CN database table.
*
*/
@Entity
@Table(name = "MTRL_DIM_CN")
@NamedQuery(name = "MtrlDimCn.findAll", query = "SELECT m FROM MtrlDimCn m")
@SqlResultSetMapping(name = "QADProductsResponse", classes = { @ConstructorResult(targetClass = QADProductsResponse.class, columns = {
@ColumnResult(name = "mtrlDimCnKey", type = int.class),
@ColumnResult(name = "expTstmp", type = Calendar.class),
@ColumnResult(name = "grpSizeCdeCn", type = String.class),
@ColumnResult(name = "grpSizeDescCn", type = String.class),
@ColumnResult(name = "lastMdfdDateQad", type = Calendar.class),
@ColumnResult(name = "minmOrdQty", type = Integer.class),
@ColumnResult(name = "mtrlCmrlNbr", type = BigInteger.class),
@ColumnResult(name = "mtrlDescCn", type = String.class),
@ColumnResult(name = "mtrlDescEn", type = String.class),
@ColumnResult(name = "mtrlPckSize", type = BigInteger.class),
@ColumnResult(name = "mtrlPlmNbr", type = BigInteger.class),
@ColumnResult(name = "mtrlQadNbr", type = String.class),
@ColumnResult(name = "plmQadSyncDate", type = Calendar.class),
@ColumnResult(name = "prdActiveDate", type = Calendar.class),
@ColumnResult(name = "prdBrndCdeCn", type = String.class),
@ColumnResult(name = "prdBrndDescCn", type = String.class),
@ColumnResult(name = "prdExpDate", type = Calendar.class),
@ColumnResult(name = "prdLnCdeCn", type = String.class),
@ColumnResult(name = "prdLnDescCn", type = String.class),
@ColumnResult(name = "prdStatDescPlm", type = String.class),
@ColumnResult(name = "prdStatPlm", type = Integer.class),
@ColumnResult(name = "prdStatQad", type = String.class)
}) })
public class MtrlDimCn implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Column(name = "MTRL_DIM_CN_KEY")
private Integer mtrlDimCnKey;
@Column(name = "EXP_TSTMP")
private Calendar expTstmp;
@Column(name = "GRP_SIZE_CDE_CN")
private String grpSizeCdeCn;
@Column(name = "GRP_SIZE_DESC_CN")
private String grpSizeDescCn;
/*
* @Column(name="INSRT_TSTMP") private Calendar insrtTstmp;
*/
@Column(name = "LAST_MDFD_DATE_QAD")
private Calendar lastMdfdDateQad;
@Column(name = "MINM_ORD_QTY")
private Integer minmOrdQty;
@Column(name = "MTRL_CMRL_NBR")
private BigInteger mtrlCmrlNbr;
@Column(name = "MTRL_DESC_CN")
private String mtrlDescCn;
@Column(name = "MTRL_DESC_EN")
private String mtrlDescEn;
@Column(name = "MTRL_PCK_SIZE")
private BigInteger mtrlPckSize;
@Column(name = "MTRL_PLM_NBR")
private BigInteger mtrlPlmNbr;
@Column(name = "MTRL_QAD_NBR")
private String mtrlQadNbr;
@Column(name = "PLM_QAD_SYNC_DATE")
private Calendar plmQadSyncDate;
@Column(name = "PRD_ACTIVE_DATE")
private Calendar prdActiveDate;
@Column(name = "PRD_BRND_CDE_CN")
private String prdBrndCdeCn;
@Column(name = "PRD_BRND_DESC_CN")
private String prdBrndDescCn;
@Column(name = "PRD_EXP_DATE")
private Calendar prdExpDate;
@Column(name = "PRD_LN_CDE_CN")
private String prdLnCdeCn;
@Column(name = "PRD_LN_DESC_CN")
private String prdLnDescCn;
@Column(name = "PRD_STAT_DESC_PLM")
private String prdStatDescPlm;
@Column(name = "PRD_STAT_PLM")
private Integer prdStatPlm;
@Column(name = "PRD_STAT_QAD")
private String prdStatQad;
// bi-directional many-to-one association to MtrlSnDim1
@OneToMany(mappedBy = "mtrlDimCn", cascade = CascadeType.ALL)
private List<MtrlSnDim> mtrlSnDims;
public MtrlDimCn() {
}
public MtrlDimCn(Integer mtrlDimCnKey, Calendar expTstmp, String grpSizeCdeCn, String grpSizeDescCn,
Calendar lastMdfdDateQad, Integer minmOrdQty, BigInteger mtrlCmrlNbr, String mtrlDescCn, String mtrlDescEn,
BigInteger mtrlPckSize, BigInteger mtrlPlmNbr, String mtrlQadNbr, Calendar plmQadSyncDate,
Calendar prdActiveDate, String prdBrndCdeCn, String prdBrndDescCn, Calendar prdExpDate, String prdLnCdeCn,
String prdLnDescCn, String prdStatDescPlm, Integer prdStatPlm, String prdStatQad,
List<MtrlSnDim> mtrlSnDims) {
super();
this.mtrlDimCnKey = mtrlDimCnKey;
this.expTstmp = expTstmp;
this.grpSizeCdeCn = grpSizeCdeCn;
this.grpSizeDescCn = grpSizeDescCn;
this.lastMdfdDateQad = lastMdfdDateQad;
this.minmOrdQty = minmOrdQty;
this.mtrlCmrlNbr = mtrlCmrlNbr;
this.mtrlDescCn = mtrlDescCn;
this.mtrlDescEn = mtrlDescEn;
this.mtrlPckSize = mtrlPckSize;
this.mtrlPlmNbr = mtrlPlmNbr;
this.mtrlQadNbr = mtrlQadNbr;
this.plmQadSyncDate = plmQadSyncDate;
this.prdActiveDate = prdActiveDate;
this.prdBrndCdeCn = prdBrndCdeCn;
this.prdBrndDescCn = prdBrndDescCn;
this.prdExpDate = prdExpDate;
this.prdLnCdeCn = prdLnCdeCn;
this.prdLnDescCn = prdLnDescCn;
this.prdStatDescPlm = prdStatDescPlm;
this.prdStatPlm = prdStatPlm;
this.prdStatQad = prdStatQad;
this.mtrlSnDims = mtrlSnDims;
}
public Integer getMtrlDimCnKey() {
return this.mtrlDimCnKey;
}
public void setMtrlDimCnKey(Integer mtrlDimCnKey) {
this.mtrlDimCnKey = mtrlDimCnKey;
}
public Calendar getExpTstmp() {
return this.expTstmp;
}
public void setExpTstmp(Calendar expTstmp) {
this.expTstmp = expTstmp;
}
public String getGrpSizeCdeCn() {
return this.grpSizeCdeCn;
}
public void setGrpSizeCdeCn(String grpSizeCdeCn) {
this.grpSizeCdeCn = grpSizeCdeCn;
}
public String getGrpSizeDescCn() {
return this.grpSizeDescCn;
}
public void setGrpSizeDescCn(String grpSizeDescCn) {
this.grpSizeDescCn = grpSizeDescCn;
}
/*
* public Calendar getInsrtTstmp() { return this.insrtTstmp; }
*
* public void setInsrtTstmp(Calendar insrtTstmp) { this.insrtTstmp =
* insrtTstmp; }
*/
public Calendar getLastMdfdDateQad() {
return this.lastMdfdDateQad;
}
public void setLastMdfdDateQad(Calendar lastMdfdDateQad) {
this.lastMdfdDateQad = lastMdfdDateQad;
}
public Integer getMinmOrdQty() {
return this.minmOrdQty;
}
public void setMinmOrdQty(Integer minmOrdQty) {
this.minmOrdQty = minmOrdQty;
}
public BigInteger getMtrlCmrlNbr() {
return this.mtrlCmrlNbr;
}
public void setMtrlCmrlNbr(BigInteger mtrlCmrlNbr) {
this.mtrlCmrlNbr = mtrlCmrlNbr;
}
public String getMtrlDescCn() {
return this.mtrlDescCn;
}
public void setMtrlDescCn(String mtrlDescCn) {
this.mtrlDescCn = mtrlDescCn;
}
public String getMtrlDescEn() {
return this.mtrlDescEn;
}
public void setMtrlDescEn(String mtrlDescEn) {
this.mtrlDescEn = mtrlDescEn;
}
public BigInteger getMtrlPckSize() {
return this.mtrlPckSize;
}
public void setMtrlPckSize(BigInteger mtrlPckSize) {
this.mtrlPckSize = mtrlPckSize;
}
public BigInteger getMtrlPlmNbr() {
return this.mtrlPlmNbr;
}
public void setMtrlPlmNbr(BigInteger mtrlPlmNbr) {
this.mtrlPlmNbr = mtrlPlmNbr;
}
public String getMtrlQadNbr() {
return this.mtrlQadNbr;
}
public void setMtrlQadNbr(String mtrlQadNbr) {
this.mtrlQadNbr = mtrlQadNbr;
}
public Calendar getPlmQadSyncDate() {
return this.plmQadSyncDate;
}
public void setPlmQadSyncDate(Calendar plmQadSyncDate) {
this.plmQadSyncDate = plmQadSyncDate;
}
public Calendar getPrdActiveDate() {
return this.prdActiveDate;
}
public void setPrdActiveDate(Calendar prdActiveDate) {
this.prdActiveDate = prdActiveDate;
}
public String getPrdBrndCdeCn() {
return this.prdBrndCdeCn;
}
public void setPrdBrndCdeCn(String prdBrndCdeCn) {
this.prdBrndCdeCn = prdBrndCdeCn;
}
public String getPrdBrndDescCn() {
return this.prdBrndDescCn;
}
public void setPrdBrndDescCn(String prdBrndDescCn) {
this.prdBrndDescCn = prdBrndDescCn;
}
public Calendar getPrdExpDate() {
return this.prdExpDate;
}
public void setPrdExpDate(Calendar prdExpDate) {
this.prdExpDate = prdExpDate;
}
public String getPrdLnCdeCn() {
return this.prdLnCdeCn;
}
public void setPrdLnCdeCn(String prdLnCdeCn) {
this.prdLnCdeCn = prdLnCdeCn;
}
public String getPrdLnDescCn() {
return this.prdLnDescCn;
}
public void setPrdLnDescCn(String prdLnDescCn) {
this.prdLnDescCn = prdLnDescCn;
}
public String getPrdStatDescPlm() {
return this.prdStatDescPlm;
}
public void setPrdStatDescPlm(String prdStatDescPlm) {
this.prdStatDescPlm = prdStatDescPlm;
}
public Integer getPrdStatPlm() {
return this.prdStatPlm;
}
public void setPrdStatPlm(Integer prdStatPlm) {
this.prdStatPlm = prdStatPlm;
}
public String getPrdStatQad() {
return this.prdStatQad;
}
public void setPrdStatQad(String prdStatQad) {
this.prdStatQad = prdStatQad;
}
public List<MtrlSnDim> getMtrlSnDims() {
return this.mtrlSnDims;
}
public void setMtrlSnDims(List<MtrlSnDim> mtrlSnDims) {
this.mtrlSnDims = mtrlSnDims;
}
public MtrlSnDim addMtrlSnDim(MtrlSnDim mtrlSnDim) {
getMtrlSnDims().add(mtrlSnDim);
mtrlSnDim.setMtrlDimCn(this);
return mtrlSnDim;
}
public MtrlSnDim removeMtrlSnDim(MtrlSnDim mtrlSnDim) {
getMtrlSnDims().remove(mtrlSnDim);
mtrlSnDim.setMtrlDimCn(null);
return mtrlSnDim;
}
}
|
[
"[email protected]"
] | |
1f372068956bf6b52a797fa445ba546ff0e8ff53
|
1a90a3593de8bcdc4c21c49dbe2c7fbae2ab8ab5
|
/src/main/java/com/twinsoft/web/HotelReservationController.java
|
84986aa57e879dfe6f16cc2c2938097cdf16fcdc
|
[] |
no_license
|
twinsoftgit/hotel-reservation-client
|
67ef398e67da64e127c499f8fcd96130975fba33
|
c0df6f9b25ae816340409e57ac7119c93f9ecfc0
|
refs/heads/master
| 2021-01-01T04:41:46.138817 | 2017-07-14T11:14:58 | 2017-07-14T11:14:58 | 97,225,874 | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 3,667 |
java
|
/**
*
*/
package com.twinsoft.web;
import javax.inject.Inject;
import javax.validation.Valid;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.util.UriComponentsBuilder;
import com.twinsoft.dto.HotelReservation;
import com.twinsoft.service.HotelReservationService;
import lombok.extern.slf4j.Slf4j;
/**
* Rest controller for exposing hotel reservation endpoints.
*
* @author Miodrag Pavkovic
*/
@Slf4j
@RestController
@RequestMapping("hotelreservations")
public class HotelReservationController {
private static final String RESOURCE_NOT_FOUND_MESSAGE = null;
/** The hotel service */
private final HotelReservationService hotelReservationService;
@Inject
public HotelReservationController(final HotelReservationService hotelReservationService) {
this.hotelReservationService = hotelReservationService;
}
/**
* Rest endpoint for retrieving all hotel reservations.
*
* @return ResponseEntity<Page<Hotel>>
*/
@GetMapping(produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<HotelReservation[]> findAll(@RequestHeader(value="Authorization") String token) {
return hotelReservationService.findAll(token);
}
/**
* Rest endpoint for creating and saving hotel reservation.
*
* @param hotelReservation
* @param builder
* @return
*/
@PostMapping(consumes = MediaType.APPLICATION_JSON_VALUE)
@ResponseStatus(HttpStatus.CREATED)
public void create(@Valid @RequestBody final HotelReservation hotelReservation, final UriComponentsBuilder builder, @RequestHeader(value="Authorization") String token) {
try {
hotelReservationService.save(hotelReservation, token);
} catch (final Exception e) {
log.error("Hotel reservation not created hotel, Cause:",e);
}
}
/**
* Rest endpoint for updating a hotel reservation with reservation id.
*
* @param hotelReservationId
* @param hotelReservation
* @return
*/
@PutMapping(value="/{hotelReservationId}", consumes = MediaType.APPLICATION_JSON_VALUE)
public void update(@PathVariable final Long hotelReservationId, @Valid @RequestBody final HotelReservation hotelReservation) {
try {
hotelReservation.setId(hotelReservationId);
final HotelReservation updateHotelReservation = hotelReservationService.update(hotelReservation);
} catch (final Exception e) {
log.error("Exception occurred while updating hotel reservation with id {}. Cause: ", hotelReservationId, e);
}
}
/**
* Rest endpoint for deleting a hotel reservation with reservation id.
*
* @param hotelReservationId
*/
@DeleteMapping(value = "/{hotelReservationId}")
@ResponseStatus(HttpStatus.NO_CONTENT)
public void delete(@PathVariable("hotelReservationId") final Long hotelReservationId) {
try {
hotelReservationService.delete(hotelReservationId);
} catch (final Exception e) {
log.error("Exception occurred while deleting hotel reservation with reservation id {}. Cause: ", hotelReservationId, e);
}
}
}
|
[
"[email protected]"
] | |
6ded00c8ab4ee0e5b3420b9223c42e3e5c745653
|
d2f43e9211479d3328ea35080fc026c034c56676
|
/CipherGUI.java
|
9c967fbdfe01a1f39d42582cce2b43cadda38225
|
[] |
no_license
|
2057536a/encryption-decryption
|
48b33935ec93f806f3552b8fac505ae93a82141b
|
70d6f5ea3b85515a40f631a109b76cdbb7b6092f
|
refs/heads/master
| 2021-08-23T16:26:09.985449 | 2017-12-05T17:19:16 | 2017-12-05T17:19:16 | 113,211,491 | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 12,367 |
java
|
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.io.*;
import java.util.Scanner;
/**
* Programming AE2
* Class to display cipher GUI and listen for events
*/
public class CipherGUI extends JFrame implements ActionListener
{
//instance variables which are the components
private JPanel top, bottom, middle;
private JButton monoButton, vigenereButton;
private JTextField keyField, messageField;
private JLabel keyLabel, messageLabel;
// instance variables for parts that have been created
private String keyFieldString, messageFileString, stringToWrite;
//application instance variables
//including the 'core' part of the text file filename
//some way of indicating whether encoding or decoding is to be done
private MonoCipher mcipher;
private VCipher vcipher;
private LetterFrequencies freqs;
private FileWriter writer, writer2,writer3,writer4;
/**
* The constructor adds all the components to the frame
*/
public CipherGUI()
{
this.setSize(400,150);
this.setLocation(500,250);
this.setTitle("Cipher GUI");
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.layoutComponents();
}
/**
* Helper method to add components to the frame
*/
public void layoutComponents()
{
//top panel is yellow and contains a text field of 10 characters
top = new JPanel();
top.setBackground(Color.yellow);
keyLabel = new JLabel("Keyword : ");
top.add(keyLabel);
keyField = new JTextField(10);
top.add(keyField);
this.add(top,BorderLayout.NORTH);
//middle panel is yellow and contains a text field of 10 characters
middle = new JPanel();
middle.setBackground(Color.yellow);
messageLabel = new JLabel("Message file : ");
middle.add(messageLabel);
messageField = new JTextField(10);
middle.add(messageField);
this.add(middle,BorderLayout.CENTER);
//bottom panel is green and contains 2 buttons
bottom = new JPanel();
bottom.setBackground(Color.green);
//create mono button and add it to the top panel
monoButton = new JButton("Process Mono Cipher");
monoButton.addActionListener(this);
bottom.add(monoButton);
//create vigenere button and add it to the top panel
vigenereButton = new JButton("Process Vigenere Cipher");
vigenereButton.addActionListener(this);
bottom.add(vigenereButton);
//add the top panel
this.add(bottom,BorderLayout.SOUTH);
}
/**
* Listen for and react to button press events
* (use helper methods below)
* @param e the event
*/
public void actionPerformed(ActionEvent e)
{
// Depending on which button is clicked
// I will validate the keyword and the message file name
//and the cipher and frequencies object will be created
if(e.getSource() == monoButton) {
if (getKeyword() == true && processFileName() == true) {
mcipher = new MonoCipher(keyFieldString);
//The LetterFrequencies object will be created here
freqs = new LetterFrequencies();
//Processing the file if it is mono cipher
// Encodes or decodes depending on the file
// and writes an output file with the result
processFile(false);
}
}
else if (e.getSource() == vigenereButton) {
if (getKeyword() == true && processFileName() == true) {
vcipher = new VCipher(keyFieldString);
//The LetterFrequencies object will be created here
freqs = new LetterFrequencies();
//Processing the file if it is Vigenere cipher
// Encodes or decodes depending on the file
// and writes an output file with the result
processFile(true);
}
}
}
/**
* Obtains cipher keyword
* If the keyword is invalid, a message is produced
* @return whether a valid keyword was entered
*/
private boolean getKeyword()
{
keyFieldString = keyField.getText();
int length = keyFieldString.length();
//If keyword field is empty user will be notified
if (keyFieldString.equals("")) {
JOptionPane.showMessageDialog(null,"You have to enter a keyword","Error",JOptionPane.ERROR_MESSAGE);
keyField.setText("");
return false;
}
else { //i.e. if the keyword field contains something
if (!keyFieldString.matches("[a-zA-Z]+")) { //if what is contains has something else than letters
JOptionPane.showMessageDialog(null,"Keyword must contain only alphabetic characters","Error",JOptionPane.ERROR_MESSAGE);
keyField.setText("");
return false;
}
else { //if non empty and doesn't contain non letters check capital letters validity and duplicates
for (int index = 0; index < length; index++) {
char myCharacter = keyFieldString.charAt(index);
if (myCharacter >= 90) { //i.e. if it is lower case
JOptionPane.showMessageDialog(null,"You have encounter the lowercase letter: " + myCharacter,"Error",JOptionPane.ERROR_MESSAGE);
keyField.setText("");
return false;
}
else {
for (int i = 0; i < length; i++) {
int count = 0;
for (int j = 0; j < length; j++) {
if (keyFieldString.charAt(i) == keyFieldString.charAt(j)) {
count++;
if (count++ > 1) {
JOptionPane.showMessageDialog(null,"Keyword must not contain any duplicates","Error",JOptionPane.ERROR_MESSAGE);
keyField.setText("");
return false;
}
}
}
}
}
}
}
}
return true;
}
/**
* Obtains filename from GUI
* The details of the filename and the type of coding are extracted
* If the filename is invalid, a message is produced
* The details obtained from the filename must be remembered
* @return whether a valid filename was entered
*/
private boolean processFileName()
{
messageFileString = messageField.getText();
//If the file name is empty user will be notified
if (messageFileString.equals("") ) {
JOptionPane.showMessageDialog(null,"You have to enter a message filename","Error",JOptionPane.ERROR_MESSAGE);
messageField.setText("");
return false;
}
else {
String p = "P";
String c = "C";
int messFileStrLength = messageFileString.length();
//extract the message file last letter
char lastLetter = messageFileString.charAt(messFileStrLength - 1);
//The strings p and c as defined above, as characters
char P = p.charAt(0);
char C = c.charAt(0);
if (lastLetter != P && lastLetter != C){
JOptionPane.showMessageDialog(null,"You have to enter a file of correct type","Error",JOptionPane.ERROR_MESSAGE);
messageField.setText("");
return false;
}
else {
try {
FileReader reader = new FileReader(messageFileString + ".txt");
}
catch (IOException e) {
JOptionPane.showMessageDialog(null,"File not found.","Error",JOptionPane.ERROR_MESSAGE);
messageField.setText("");
return false;
}
}
}
return true;
}
/**
* Reads the input text file character by character
* Each character is encoded or decoded as appropriate
* and written to the output text file
* @param vigenere whether the encoding is Vigenere (true) or Mono (false)
* @return whether the I/O operations were successful
*/
private boolean processFile(boolean vigenere)
{
//Determine the last letter of the file to see if it is P or C
char a_char = messageFileString.charAt(messageFileString.length()-1);
//Extract just the file name without the type letter.
String subMessageName = messageFileString.substring(0, messageFileString.length()-1);
FileReader reader = null;
FileWriter writer = null;
FileWriter writer2 = null;
FileWriter writer3 = null;
FileWriter writer4 = null;
//Conditionals for each file case, P or C ended
if (a_char == 'P') {
//Take the substring of the message file name so a character can be added in
// the end to write an output file, depending on the type of the input file
String outputFileName = subMessageName + "C.txt";
String reportFileName = subMessageName + "F.txt";
try {
try {
reader = new FileReader(messageFileString + ".txt");
// flag indicating whether finished reading
boolean done = false;
stringToWrite ="";
char encrypted = ' ';
while (!done) {
// read a character, represented by an int
int next = reader.read();
// -1 represents end of file
if (next == -1)
done = true;
else {
// convert to character
char c = (char) next;
//Check if the vigenere or mono method will
//be used, so the correct method can be applied
if (vigenere == false) {
//Apply the mono encryption method
encrypted = mcipher.encode(c);
}
else if (vigenere == true) {
//Apply the Vigenere encryption method
encrypted = vcipher.encode(c);
}
//Print the encoded text and calculates frequencies
System.out.print(encrypted );
freqs.addChar(encrypted);
//Change the encrypted message to string, ready to be written later
stringToWrite = stringToWrite + Character.toString(encrypted);
writer = new FileWriter(outputFileName);
writer3 = new FileWriter(reportFileName);
// write the characters to the file
//and the frequency report to another file
writer.write(stringToWrite);
writer3.write(freqs.getReport());
}
}
System.out.println("\n" + "--------------");
System.out.print(freqs.getReport());
writer.close();
writer3.close();
}
finally {
// close the input file assuming it was opened successfully
if (reader != null) reader.close();
}
}
catch (IOException ex) {
System.out.println("Error opening file");
}
}
//If the file ends with C, needs decoding and the outcome will be the P file
else {
//Take the substring of the message file name so a character can be added in
// the end to write an output file, depending on the type of the input file
String outputFileName = subMessageName + "D.txt";
String reportFileName = subMessageName + "F.txt";
try {
try {
reader = new FileReader(messageFileString + ".txt");
// flag indicating whether finished reading
boolean done = false;
stringToWrite ="";
char decoded = ' ';
while (!done) {
// read a character, represented by an int
int next = reader.read();
// -1 represents end of file
if (next == -1)
done = true;
else {
// convert to character
char c = (char) next;
if (vigenere == false) {
//Apply the decoding method method
decoded = mcipher.decode(c);
}
else if (vigenere == true) {
decoded = vcipher.decode(c);
}
//Print the decoded message
System.out.print(decoded);
freqs.addChar(decoded);
//Change the decoded message to string, ready to be written later
stringToWrite = stringToWrite + Character.toString(decoded);
writer2 = new FileWriter(outputFileName);
writer4 = new FileWriter(reportFileName);
// write the characters to the file
writer2.write(stringToWrite);
writer4.write(freqs.getReport());
}
}
System.out.println("\n" + "--------------");
System.out.print(freqs.getReport());
writer2.close();
writer4.close();
}
finally {
// close the input file assuming it was opened successfully
if (reader != null) reader.close();
}
}
catch (IOException ex) {
System.out.println("Error opening file");
}
}
return true;
}
}
|
[
"[email protected]"
] | |
e2ce558d08a00924cc109216bc35e11a3bc0ce0a
|
dc8be010cdcaf7fea0bac405ba956bb76bd6d29a
|
/app/src/main/java/com/movietheaters/TheatersPojo.java
|
16e3955c4bef35e31b9d844ca0e7c07024fdcee4
|
[] |
no_license
|
Harish1695/MovieTheaters
|
447e040e26d1fd737906d123e5d5ff50fc6c9fd1
|
081c3eb7e4124e46518ab086e4b6b6ab64df4b3b
|
refs/heads/master
| 2023-01-24T18:06:43.487254 | 2020-11-25T01:34:01 | 2020-11-25T01:34:01 | 315,500,288 | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 498 |
java
|
package com.movietheaters;
import com.google.gson.annotations.SerializedName;
public class TheatersPojo {
public TheatersPojo(String theater_name) {
this.theater_name = theater_name;
}
public String getTheater_name() {
return theater_name;
}
public void setTheater_name(String theater_name) {
this.theater_name = theater_name;
}
@SerializedName("theater_name")
private String theater_name;
public TheatersPojo()
{
}
}
|
[
"[email protected]"
] | |
21966622db7defe15c335a1ad6fc9da011321c08
|
87139dac39e6005414b74d25196d070320f0ea4b
|
/src/main/java/y/y/d/springboot/service/data/TradeService.java
|
2b973fd746b6c2d5e494ecd7fc9d763e4bc51736
|
[] |
no_license
|
mayflight/spring-boot
|
5161fe3cb9037cd5b16c3752553c746fa7001d72
|
d1c2291899e94ed6ddcdc6b956b2d5592c9e3b03
|
refs/heads/master
| 2020-03-27T23:34:27.390491 | 2018-10-17T08:39:47 | 2018-10-17T08:39:47 | 147,329,205 | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 152 |
java
|
package y.y.d.springboot.service.data;
import y.y.d.springboot.entity.Trade;
public interface TradeService {
Trade selectByPrimaryKey(int key);
}
|
[
"[email protected]"
] | |
8000df54a6e4d9a3363a7e616681365fecc0852a
|
6eaf105e9cddbf4f0b1c2e7cc213837c21148632
|
/code/internet/backend_calculator/CCoAWeb/src/main/java/com/alamutra/CCoAWeb/Core/ModelLogic/ControllerMachines/Hexagon/DeterminantAddressHexagon.java
|
7a46488c987dd279032572d4ff21e71554c96dc3
|
[] |
no_license
|
GeorgiaFrankinStain/Centralized_Control_of_Autopilots_diploma
|
e43470eab80b596c48ccec10c19b91f0cdc79ccf
|
4298151c4c9ab0f795cc5635ecb8d5e661a5aa20
|
refs/heads/master
| 2023-05-31T19:20:06.281653 | 2023-05-14T18:03:18 | 2023-05-14T18:03:18 | 241,713,482 | 0 | 0 | null | 2023-03-15T10:23:04 | 2020-02-19T20:01:52 |
Java
|
UTF-8
|
Java
| false | false | 328 |
java
|
package com.alamutra.CCoAWeb.Core.ModelLogic.ControllerMachines.Hexagon;
import com.alamutra.CCoAWeb.Core.ModelLogic.FootprintSpaceTime.PointCCoA;
public interface DeterminantAddressHexagon {
public PointCCoA detectedCenterHexagonIncludeCoordinate();
public int detectedHashCodeHexagonIncludeCoordinate();
}
|
[
"[email protected]"
] | |
2bb7f94b0f19e63edf591ca56dcc32ab0cf222e8
|
84e62755c84b846b32055226fce5595ef666e94c
|
/MVC/MVCPattern.java
|
bf54265d879bd697b1f4c2e9c5cb819896a78191
|
[] |
no_license
|
hgasimov/Design-Patterns
|
e82ee86bcfe4ad599cbc72d3e061118efb3a2153
|
c6b9d2b7e9096d295a33713e4a2e11bd50d910d9
|
refs/heads/master
| 2016-09-06T02:17:57.156514 | 2014-02-03T12:51:26 | 2014-02-03T12:51:26 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 622 |
java
|
package MVC;
public class MVCPattern {
public static void main(String[] args) {
Student model = retriveStudentFromDatabase();
StudentView view = new StudentView();
StudentController contr = new StudentController(model, view);
contr.updateView();
contr.setStudentName("Sexy");
contr.setStudentRollNo("7");
contr.updateView();
}
private static Student retriveStudentFromDatabase() {
Student student = new Student();
student.setName("Geek");
student.setRollNo("10");
return student;
}
}
|
[
"[email protected]"
] | |
78806665d6befeb8233a133a2f9ac55eadbfde14
|
7afbd7770d9bc289465db4f103ca04b4a6d4e1d6
|
/ladon-s3-server/src/main/java/de/mc/ladon/s3server/entities/api/S3RequestParams.java
|
f69c59d8e08f88a1bd74f7aaee99b342585f6170
|
[] |
no_license
|
makelefy/ladon-s3-server
|
1ad0cd8821a9b0d848fdba40f877d626aaf706a3
|
98ad97be732e2f052165243184dd101cb289d6b6
|
refs/heads/master
| 2021-05-30T20:28:06.740328 | 2016-03-28T00:16:54 | 2016-03-28T00:17:50 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 2,899 |
java
|
/*
* Copyright (c) 2016 Mind Consulting UG(haftungsbeschränkt)
*/
package de.mc.ladon.s3server.entities.api;
import java.util.Map;
/**
* @author Ralf Ulrich on 20.02.16.
*/
public interface S3RequestParams {
/**
* A delimiter is a character you use to group keys.
* All keys that contain the same string between the prefix , if specified, and
* the first occurrence of the delimiter after the prefix are grouped under a single
* result element, CommonPrefixes . If you don't specify the prefix parameter,
* then the substring starts at the beginning of the key. The keys that are grouped
* under CommonPrefixes result element are not returned elsewhere in the re-
* sponse.
* Default: None
*
* @return the delimiter to group keys or null
*/
String getDelimiter();
/**
* Requests Amazon S3 to encode the response and specifies the encoding method to use.
* An object key can contain any Unicode character; however, XML 1.0 parser
* cannot parse some characters, such as characters with an ASCII value from
* 0 to 10. For characters that are not supported in XML 1.0, you can add this
* parameter to request that Amazon S3 encode the keys in the response.
* Default: None
*
* @return the encoding method to use or null
*/
String getEncodingType();
/**
* Specifies the key to start with when listing objects in a bucket. Amazon S3
* returns object keys in alphabetical order, starting with key after the marker in
* order.
* Default : None
*
* @return the key to start with or null
*/
String getMarker();
/**
* Sets the maximum number of keys returned in the response body. You can
* add this to your request if you want to retrieve fewer than the default 1000
* keys.
* The response might contain fewer keys but will never contain more. If there
* are additional keys that satisfy the search criteria but were not returned because
* max-keys was exceeded, the response contains <IsTruncated>true</IsTruncated> .
* To return the additional keys, see getMarker() .
* Default: 1000
*
* @return the max number of keys to return
*/
int getMaxKeys();
/**
* Limits the response to keys that begin with the specified prefix. You can use
* prefixes to separate a bucket into different groupings of keys. (You can think
* of using prefix to make groups in the same way you'd use a folder in a file
* system.)
* Default: None
*
* @return the prefix to use or null
*/
String getPrefix();
/**
* Get all params as a simple Map. Notice: only the first value is added, multivalue is not supported
*
* @return Map with all param keys and the first param value
*/
Map<String, String> getAllParams();
}
|
[
"[email protected]"
] | |
cfa394aab2a73b2b9da6efc6caad00adddf8a09f
|
fbf95d693ad5beddfb6ded0be170a9e810a10677
|
/core-services/egov-user/src/main/java/org/egov/user/web/adapters/errors/UserInvalidUpdatePasswordRequest.java
|
f8e13093597449bbd7a1a1bcc9e08892d06c251a
|
[
"MIT",
"LicenseRef-scancode-generic-cla"
] |
permissive
|
egovernments/DIGIT-OSS
|
330cc364af1b9b66db8914104f64a0aba666426f
|
bf02a2c7eb783bf9fdf4b173faa37f402e05e96e
|
refs/heads/master
| 2023-08-15T21:26:39.992558 | 2023-08-08T10:14:31 | 2023-08-08T10:14:31 | 353,807,330 | 25 | 91 |
MIT
| 2023-09-10T13:23:31 | 2021-04-01T19:35:55 |
Java
|
UTF-8
|
Java
| false | false | 1,204 |
java
|
package org.egov.user.web.adapters.errors;
import java.util.Collections;
import java.util.List;
import org.egov.common.contract.response.Error;
import org.egov.common.contract.response.ErrorField;
import org.egov.common.contract.response.ErrorResponse;
import org.springframework.http.HttpStatus;
public class UserInvalidUpdatePasswordRequest implements ErrorAdapter<Void> {
private static final String INVALIDTOKEN_NAME_CODE = "InvalidPasswordRequest";
private static final String INVALIDTOKEN_FIELD = "InvalidPasswordRequest";
public ErrorResponse adapt(Void model) {
final Error error = getError();
return new ErrorResponse(null, error);
}
private Error getError() {
String error = "Since We configured login otp enabled is true,So we can't update the password.";
return Error.builder().code(HttpStatus.BAD_REQUEST.value()).message(error).fields(getUserNameFieldError(error))
.build();
}
private List<ErrorField> getUserNameFieldError(String error) {
return Collections.singletonList(
ErrorField.builder().field(INVALIDTOKEN_FIELD).code(INVALIDTOKEN_NAME_CODE).message(error).build());
}
}
|
[
"[email protected]"
] | |
f7dc6c680d6e17c76009617fd710f844d1b8784a
|
22e6bf275fdf02a7ff2046e7c37282dde85bb43e
|
/core/src/test/resources/plugin/asset/location/serverrelative/package-info.java
|
c7918257abce9e4915d579c786e3ffc535fd4c39
|
[] |
no_license
|
ybz216/juzu
|
05206904eb7099abaa5a477224e4dcb4de9ed4c2
|
37612ff8b031ec55523fa4654546ab4c2536fc2c
|
refs/heads/master
| 2022-05-11T10:50:40.699471 | 2020-01-14T14:18:50 | 2020-01-29T18:27:40 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 1,049 |
java
|
/*
* Copyright 2013 eXo Platform SAS
*
* 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.
*/
@Application()
@Scripts(@Script(id = "jquery.js", value = "jquery.js", location = AssetLocation.SERVER))
@Stylesheets(@Stylesheet(id = "main.css", value = "main.css", location = AssetLocation.SERVER))
package plugin.asset.location.serverrelative;
import juzu.Application;
import juzu.asset.AssetLocation;
import juzu.plugin.asset.Script;
import juzu.plugin.asset.Scripts;
import juzu.plugin.asset.Stylesheet;
import juzu.plugin.asset.Stylesheets;
|
[
"[email protected]"
] | |
71df3348384897b567f61b618321c37409b321b6
|
c0b7eb226b693b6c56ea6b1d0852dbc2a230aa50
|
/selenuimWebDriverManagerTest/src/main/java/com/bridgelabz/extendsreport/ExtendReportDemo.java
|
7160ab382748eef4caedf33d8b95c61e0bf34432
|
[] |
no_license
|
narayanmestry/SeleniumProgram
|
b05086755c45028f13f3904c4432792b244e78da
|
ee26da2d79994ca257415c73ba0dc2132163c79e
|
refs/heads/master
| 2023-04-16T09:26:25.187320 | 2020-03-27T14:33:05 | 2020-03-27T14:33:05 | 241,107,145 | 0 | 0 | null | 2021-04-26T20:00:57 | 2020-02-17T12:52:55 |
HTML
|
UTF-8
|
Java
| false | false | 1,448 |
java
|
package com.bridgelabz.extendsreport;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import com.aventstack.extentreports.ExtentReports;
import com.aventstack.extentreports.ExtentTest;
import com.aventstack.extentreports.Status;
import com.aventstack.extentreports.reporter.ExtentHtmlReporter;
public class ExtendReportDemo {
static WebDriver driver = null;
public static void main(String[] args) {
ExtentHtmlReporter htmlReporter = new ExtentHtmlReporter("extent_report.html");
ExtentReports extent = new ExtentReports();
extent.attachReporter(htmlReporter);
ExtentTest test1 = extent.createTest("Google search Test ","This is test to ckeck the google Functionlity") ;
String projectPath = System.getProperty("user.dir");
System.setProperty("webdriver.chrome.driver","/home/admin1/eclipse-workspace/SeleniumTutorial/TestNGApp/driver/chromedriver/chromedriver");
driver = new ChromeDriver();
test1.log(Status.INFO, "Start the test");
driver.get("https://www.google.com/");
test1.pass("Navigate to google");
driver.findElement(By.name("q")).sendKeys("Facebook");
test1.pass("Enter the text in Search box");
driver.findElement(By.name("btnK")).click();
test1.pass("Click the Button");
driver.close();
driver.quit();
test1.pass("Close the Browser");
test1.pass("Test Compleated");
extent.flush();
}
}
|
[
"[email protected]"
] | |
f2edbd4523eb1330da506100b2d2c15feb068672
|
2affec82941ffb41db4689bb18b37139f415b89c
|
/app/src/main/java/com/example/admin/walmartchallenge/Model/Temp.java
|
edc1101b8674ab23faa478b16968e6865f8ddd45
|
[] |
no_license
|
RockDrigo10/WalmartChallenge
|
e7e062f251d3d3d44c6ca2aa06ea3310edd6d5b6
|
71f1397521f87c64732efb50670cc256d595b0a7
|
refs/heads/master
| 2021-01-23T08:44:18.137460 | 2017-09-08T00:26:18 | 2017-09-08T00:26:18 | 102,541,767 | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 601 |
java
|
package com.example.admin.walmartchallenge.Model;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Temp {
@SerializedName("english")
@Expose
private String english;
@SerializedName("metric")
@Expose
private String metric;
public String getEnglish() {
return english;
}
public void setEnglish(String english) {
this.english = english;
}
public String getMetric() {
return metric;
}
public void setMetric(String metric) {
this.metric = metric;
}
}
|
[
"[email protected]"
] | |
e39e172a0fbff48c37067c6bd6cb641e09ee9135
|
5f37a88dea66a01f7ea27d361c4160cb5c59772c
|
/hibernate-h2-example/src/com/shoc/afip/wsmtxca/ConsultarPtosVtaCAEANoInformadosRequestType.java
|
511848ffe99cbb96db834f32475282d1f3e57fd6
|
[] |
no_license
|
diegoperezn/shoc
|
222619d2430872a9072c44db591697347b9d561c
|
509a4d776d6bc41017fb172cf76cd9c43f7603d3
|
refs/heads/master
| 2021-04-06T04:23:35.283656 | 2018-07-25T18:36:42 | 2018-07-25T18:36:42 | 124,899,408 | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 2,064 |
java
|
package com.shoc.afip.wsmtxca;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Clase Java para ConsultarPtosVtaCAEANoInformadosRequestType complex type.
*
* <p>El siguiente fragmento de esquema especifica el contenido que se espera que haya en esta clase.
*
* <pre>
* <complexType name="ConsultarPtosVtaCAEANoInformadosRequestType">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="authRequest" type="{http://impl.service.wsmtxca.afip.gov.ar/service/}AuthRequestType"/>
* <element name="CAEA" type="{http://www.w3.org/2001/XMLSchema}long"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "ConsultarPtosVtaCAEANoInformadosRequestType", propOrder = {
"authRequest",
"caea"
})
public class ConsultarPtosVtaCAEANoInformadosRequestType {
@XmlElement(required = true)
protected AuthRequestType authRequest;
@XmlElement(name = "CAEA")
protected long caea;
/**
* Obtiene el valor de la propiedad authRequest.
*
* @return
* possible object is
* {@link AuthRequestType }
*
*/
public AuthRequestType getAuthRequest() {
return authRequest;
}
/**
* Define el valor de la propiedad authRequest.
*
* @param value
* allowed object is
* {@link AuthRequestType }
*
*/
public void setAuthRequest(AuthRequestType value) {
this.authRequest = value;
}
/**
* Obtiene el valor de la propiedad caea.
*
*/
public long getCAEA() {
return caea;
}
/**
* Define el valor de la propiedad caea.
*
*/
public void setCAEA(long value) {
this.caea = value;
}
}
|
[
"[email protected]"
] | |
81f446aacdfe9c99e161a87769ceb0c78b290a9d
|
3e5baf83224c7699401ce3611cdc1585dab3a926
|
/Property_Animation/Value/app/src/androidTest/java/com/example/value/ExampleInstrumentedTest.java
|
dd9cde3d2db8a837548af4a58f2d9831372e8325
|
[] |
no_license
|
lingchen0393/AndroidAnimation-learning-practice
|
b91409f352fad3c3d3e5c3b4858589e63d362821
|
64e77c3916812817217503d5bab35cf17b38f9af
|
refs/heads/master
| 2022-10-23T04:36:25.937024 | 2020-06-10T14:36:25 | 2020-06-10T14:36:25 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 750 |
java
|
package com.example.value;
import android.content.Context;
import androidx.test.platform.app.InstrumentationRegistry;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumented test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext();
assertEquals("com.example.value", appContext.getPackageName());
}
}
|
[
"[email protected]"
] | |
699de5364a2564e24536c9ca9f8a9138bfb09855
|
ad5fcc36c5872e5580e6a67c777eec8fabece9c3
|
/app/src/main/java/com/wf/andos/tab/fragment/SubFragment1.java
|
ac84f7a0076adc365d8da8db4f80af79408bcfad
|
[] |
no_license
|
wangpf2011/platform
|
2cda0549b7ead6cf0ac7c36bcb0ca7e6cad11ac2
|
ee8edacc4f0e28869632479baa98ee7ad0fac0c7
|
refs/heads/master
| 2021-01-21T05:10:13.188377 | 2019-05-22T01:42:11 | 2019-05-22T01:42:11 | 83,135,305 | 1 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 770 |
java
|
package com.wf.andos.tab.fragment;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
public class SubFragment1 extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Toast.makeText(getActivity(), "SubFragment1==onCreateView", Toast.LENGTH_LONG).show();
TextView tv = new TextView(getActivity());
tv.setTextSize(25);
tv.setBackgroundColor(Color.parseColor("#FFA07A"));
tv.setText("SubFragment1");
tv.setGravity(Gravity.CENTER);
return tv;
}
}
|
[
"[email protected]"
] | |
19e473e374c29124ccf02d4690278eaf382572f3
|
6165ed1d0aec9c331acabf376bca820fd75c6c97
|
/src/com/yqh/bsp/business/mvc/trade/TradeController.java
|
c9e718423f58bd7b6c6e50f0f8eb681f41b1005b
|
[] |
no_license
|
17huaProject/Front-end-Project
|
bcf80c8acca5812949cbd07cf5c1888e5206c8a8
|
1d896b3ab1190732b1743d8b47daf0376e612aaa
|
refs/heads/master
| 2021-09-04T08:30:58.548931 | 2018-01-17T09:27:28 | 2018-01-17T09:27:28 | 117,795,669 | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 5,587 |
java
|
package com.yqh.bsp.business.mvc.trade;
import java.util.Date;
import java.util.List;
import com.jfinal.aop.Before;
import com.yqh.bsp.base.annotation.Action;
import com.yqh.bsp.base.mvc.BaseController;
import com.yqh.bsp.base.response.Errcode;
import com.yqh.bsp.business.mvc.account.AccountService;
import com.yqh.bsp.common.dao.UserStatDao;
import com.yqh.bsp.common.entity.LoginUser;
import com.yqh.bsp.common.enums.OrderStatus;
import com.yqh.bsp.common.enums.PayStatus;
import com.yqh.bsp.common.enums.TransactionType;
import com.yqh.bsp.common.interceptor.LoginedAuthInterceptor;
import com.yqh.bsp.common.model.OrderPaid;
import com.yqh.bsp.common.model.OrderRefund;
import com.yqh.bsp.common.model.User;
import com.yqh.bsp.common.tools.IdGenerator;
@Action(controllerKey="/trade")
@Before(LoginedAuthInterceptor.class)
public class TradeController extends BaseController {
private static AccountService accountService = new AccountService();
private static TradeService tradeService = new TradeService();
@Before(TradeValidator.class)
public void payOilCard() {
int amount = getParaToInt("amount");
if (amount<50 || amount%50 != 0) {
returnJson(Errcode.FAIL, "油卡充值金额需50的倍数");
return;
}
int a=1;
if (a ==1) {
returnJson(Errcode.FAIL, "油卡充值服务暂停服务,请选择提现");
return;
}
LoginUser lUser = getSessionAttr("loginUser");
String userId = lUser.getUserId();
User user = accountService.querySecurity(userId);
if (user.getInt("oil_flag")!=1){
returnJson(Errcode.FAIL, "您未绑定油卡");
return;
}
int userRank = AccountService.queryUserRank(userId);
if (userRank < 2) {
returnJson(Errcode.FAIL, "您还未攒油,攒一单就可充油卡啦!");
return;
}
if(tradeService.queryUserChargeOilCardNum(userId)>0) {
returnJson(Errcode.FAIL, "您已有订单在处理中,不能再次申请");
return;
}
OrderRefund order = new OrderRefund();
String orderId = IdGenerator.generateOrderId("C", "");
order.set("order_id",orderId);
order.set("user_id", userId);
order.set("amount", amount);
order.set("oil_card_type", user.getStr("oil_card_type"));
order.set("oil_card", user.getStr("oil_card"));
order.set("create_time", new Date());
order.set("pay_status", PayStatus.WAIT.toString());
order.set("source", getPara("pid"));
order.set("status", OrderStatus.PENDING);
boolean status = tradeService.saveOrderOilCard(order, userId, orderId, amount, TransactionType.PAY_ORDER);
if (status) {
// 更新统计数据
UserStatDao.updateUserStat(userId, TransactionType.PAY_ORDER, 0, amount, 0);
returnJson(Errcode.SUCC, "申请成功,等待处理");
} else {
returnJson(Errcode.FAIL, "申请失败");
}
}
@Before(TradeValidator.class)
public void payBankCard() {
float amount = Float.parseFloat(getPara("amount"));
if (amount<2) {
returnJson(Errcode.FAIL, "提现金额错误");
return;
}
LoginUser lUser = getSessionAttr("loginUser");
String userId = lUser.getUserId();
User user = accountService.querySecurity(userId);
if (user.getInt("bank_flag")!=1){
returnJson(Errcode.FAIL, "您未绑定银行卡");
return;
}
int userRank = AccountService.queryUserRank(userId);
if (userRank < 2) {
returnJson(Errcode.FAIL, "您还未攒油,攒一单就可提现啦!");
return;
}
// float limit = tradeService.queryDrawLimit(userId);
// if (amount > limit) {
// returnJson(Errcode.FAIL, "提现额度剩余:"+limit+"元,其余请充油卡");
// return;
// }
OrderPaid order = new OrderPaid();
String orderId = IdGenerator.generateOrderId("Y", "");
order.set("order_id",orderId);
order.set("user_id", userId);
order.set("amount", amount);
order.set("bank_id", user.get("bank_id"));
order.set("realname", user.getStr("realname"));
order.set("bank_card", user.getStr("bank_card"));
order.set("create_time", new Date());
int fee = 1;
if (amount >= 1000) {
fee = 0;
}
order.set("fee", fee);
order.set("pay_status", PayStatus.WAIT.toString());
order.set("source", getPara("pid"));
order.set("status", OrderStatus.PENDING);
boolean status = tradeService.saveOrderBankCard(order, userId, orderId, amount, TransactionType.PAY_WITHDRAW);
if (status) {
// 更新统计数据
UserStatDao.updateUserStat(userId, TransactionType.PAY_WITHDRAW, 0, amount, 0);
returnJson(Errcode.SUCC, "申请成功,等待处理");
} else {
returnJson(Errcode.FAIL, "申请失败");
}
}
/**
* 充油卡记录
*/
public void showOilCardDetail() {
LoginUser lUser = getSessionAttr("loginUser");
String userId = lUser.getUserId();
int pageNo = 1;
int pageSize = 20;
try{
pageNo = getParaToInt("page_no");
pageSize = getParaToInt("page_size");
}catch (Exception e) {
}
List<OrderRefund> list = tradeService.queryOilCardDetail(userId, pageNo, pageSize);
returnJson(list);
}
/**
* 提现记录
*/
public void showBankCardDetail() {
LoginUser lUser = getSessionAttr("loginUser");
String userId = lUser.getUserId();
int pageNo = 1;
int pageSize = 20;
try{
pageNo = getParaToInt("page_no");
pageSize = getParaToInt("page_size");
}catch (Exception e) {
}
List<OrderPaid> list = tradeService.queryDrawMoneyDetail(userId, pageNo, pageSize);
returnJson(list);
}
}
|
[
"[email protected]"
] | |
17190506e36ad871e79d30dadab7c39b23dcdb25
|
1098b2da0dbb5843657a13d953bef3506f47d532
|
/src/sloth-backend/sloth-api/src/main/java/com/sloth/board/BoardResource.java
|
104ebeb6a87f099f6ecc9c82c6ad7c51aa6b4e9b
|
[] |
no_license
|
alexjoybc/sloth
|
a72e527ca2099bdda1022da40f41b11cbb7fc300
|
3f6afc38784cfff21849206c94c487c366d06332
|
refs/heads/main
| 2023-01-30T22:29:32.223486 | 2020-12-09T05:46:08 | 2020-12-09T05:46:08 | 302,815,039 | 0 | 0 | null | 2020-12-02T07:49:05 | 2020-10-10T04:31:46 |
Java
|
UTF-8
|
Java
| false | false | 823 |
java
|
package com.sloth.board;
import com.sloth.board.models.Board;
import org.eclipse.microprofile.graphql.Description;
import org.eclipse.microprofile.graphql.GraphQLApi;
import org.eclipse.microprofile.graphql.Name;
import org.eclipse.microprofile.graphql.Query;
import java.util.List;
import java.util.UUID;
@GraphQLApi
public class BoardResource {
private final BoardService boardService;
public BoardResource(BoardService boardService) {
this.boardService = boardService;
}
@Query("allBoards")
@Description("Get all boards")
public List<Board> getAllBoards() {
return boardService.getAllBoards();
}
@Query("findBoardById")
@Description("Get board by id")
public Board findBoardById(@Name("boardId") UUID id) {
return boardService.findById(id);
}
}
|
[
"[email protected]"
] | |
0e2ce49c3a4509b401dfe78625d29a46d74a9ff4
|
781e2692049e87a4256320c76e82a19be257a05d
|
/all_data/cs61bl/lab22/cs61bl-dj/IntList.java
|
d6d01354886cd32f3b886b4cbb89d04f2ccef596
|
[] |
no_license
|
itsolutionscorp/AutoStyle-Clustering
|
54bde86fe6dbad35b568b38cfcb14c5ffaab51b0
|
be0e2f635a7558f56c61bc0b36c6146b01d1e6e6
|
refs/heads/master
| 2020-12-11T07:27:19.291038 | 2016-03-16T03:18:00 | 2016-03-16T03:18:42 | 59,454,921 | 4 | 0 | null | 2016-05-23T05:40:56 | 2016-05-23T05:40:56 | null |
UTF-8
|
Java
| false | false | 7,109 |
java
|
public class IntList {
ListNode myHead;
ListNode myTail;
int mySize;
public IntList() {
myHead = null;
myTail = null;
mySize = 0;
}
/**
* Constructs an IntList with one node. Head and tail are the same.
*/
public IntList(ListNode head) {
myHead = myTail = head;
}
/**
* Returns true if this list is empty, false otherwise.
*/
public boolean isEmpty() {
return mySize == 0;
}
/**
* Adds a new node with the given value to the front of this list.
*/
public void addToFront(int k) {
if (myHead == null) {
myHead = myTail = new ListNode(k);
} else {
myHead = new ListNode(k, null, myHead);
myHead.myNext.myPrev = myHead;
}
mySize++;
}
/**
* Adds a new node with the given value to the end of this list.
*/
public void addToEnd(int k) {
if (myHead == null) {
myHead = myTail = new ListNode(k);
} else {
myTail.myNext = new ListNode(k, myTail, null);
myTail = myTail.myNext;
}
mySize++;
}
/**
* Attaches the input list to the end of this list.
*/
public void append(IntList list) {
if (list.isEmpty()) {
return;
}
if (isEmpty()) {
myHead = list.myHead;
myTail = list.myTail;
mySize = list.mySize;
return;
}
myTail.myNext = list.myHead;
list.myHead.myPrev = myTail;
myTail = list.myTail;
mySize += list.mySize;
}
/**
* Removes the node reference by p from this list.
*/
private void remove(ListNode p) {
if (myHead == myTail) {
myHead = myTail = null;
} else if (p == myHead) {
myHead = myHead.myNext;
myHead.myPrev = null;
} else if (p == myTail) {
myTail = myTail.myPrev;
myTail.myNext = null;
} else {
p.myNext.myPrev = p.myPrev;
p.myPrev.myNext = p.myNext;
}
}
@Override
public String toString() {
String s = "";
for (ListNode p = myHead; p != null; p = p.myNext) {
s = s + p.myItem + " ";
}
return s;
}
private class ListNode {
int myItem;
ListNode myPrev;
ListNode myNext;
public ListNode(int k) {
myItem = k;
myPrev = myNext = null;
}
public ListNode(int k, ListNode prev, ListNode next) {
myItem = k;
myPrev = prev;
myNext = next;
}
}
/**
* Returns the result of sorting the values in this list using the insertion
* sort algorithm. This list is no longer usable after this operation; you
* have to use the returned list.
*/
public IntList insertionSort() {
ListNode soFar = null;
for (ListNode p = myHead; p != null; p = p.myNext) {
soFar = insert(p, soFar);
}
return new IntList(soFar);
}
/**
* Inserts the node p into the list headed by head so that the node values
* are in increasing order.
*/
private ListNode insert(ListNode p, ListNode head) {
// TODO you fill this out!
ListNode soFar = head;
if (soFar == null) {
return new ListNode(p.myItem);
}
if (p.myItem > soFar.myItem) {
soFar.myNext = insert(new ListNode(p.myItem), soFar.myNext);
} if (p.myItem < soFar.myItem) {
soFar.myPrev = new ListNode(p.myItem);
soFar.myPrev.myNext = soFar;
soFar = soFar.myPrev;
}
return soFar;
}
/**
* Sorts this list using the selection sort algorithm.
*/
public void selectionSort() {
IntList sorted = new IntList();
while (myHead != null) {
int minSoFar = myHead.myItem;
ListNode minPtr = myHead;
// Find the node in the list pointed to by myHead
// whose value is largest.
for (ListNode p = myHead; p != null; p = p.myNext) {
if (p.myItem < minSoFar) {
minSoFar = p.myItem;
minPtr = p;
}
}
sorted.addToEnd(minSoFar);
remove(minPtr);
}
myHead = sorted.myHead;
}
/**
* Returns the result of sorting the values in this list using the Quicksort
* algorithm. This list is no longer usable after this operation.
*/
public IntList quicksort() {
if (mySize <= 1) {
return this;
}
// Assume first element is the divider.
IntList smallElements = new IntList();
IntList largeElements = new IntList();
int divider = myHead.myItem;
// TODO your code here!
for (ListNode p = myHead.myNext; p!=null; p = p.myNext){
if (p.myItem < divider) {
smallElements.addToEnd(p.myItem);
}
if (p.myItem > divider) {
largeElements.addToEnd(p.myItem);
}
}
IntList sortedSmall = smallElements.quicksort();
sortedSmall.addToEnd(divider);
IntList sortedLarge = largeElements.quicksort();
sortedSmall.append(sortedLarge);
return sortedSmall;
}
/**
* Returns the result of sorting the values in this list using the merge
* sort algorithm. This list is no longer usable after this operation.
*/
public IntList mergeSort() {
if (mySize <= 1) {
return this;
}
IntList oneHalf = new IntList();
IntList otherHalf = new IntList();
// TODO your code here!
for (int i = 0; i < mySize/2; i ++) {
oneHalf.addToEnd(myHead.myItem);
myHead = myHead.myNext;
}
for (int j = mySize/2; j < mySize; j ++) {
otherHalf.addToEnd(myHead.myItem);
myHead = myHead.myNext;
}
IntList sortedLeft = oneHalf.mergeSort();
IntList sortedRight = otherHalf.mergeSort();
return merge(sortedLeft.myHead, sortedRight.myHead);
}
/**
* Returns the result of merging the two sorted lists / represented by list1
* and list2.
*/
private static IntList merge(ListNode list1, ListNode list2) {
IntList rtn = new IntList();
while (list1 != null && list2 != null) {
if (list1.myItem < list2.myItem) {
rtn.addToEnd(list1.myItem);
list1 = list1.myNext;
} else {
rtn.addToEnd(list2.myItem);
list2 = list2.myNext;
}
}
while (list1 != null) {
rtn.addToEnd(list1.myItem);
list1 = list1.myNext;
}
while (list2 != null) {
rtn.addToEnd(list2.myItem);
list2 = list2.myNext;
}
return rtn;
}
/**
* Returns a random integer between 0 and 99.
*/
private static int randomInt() {
return (int) (100 * Math.random());
}
public static void main(String[] args) {
IntList values;
IntList sortedValues;
values = new IntList();
/*
System.out.print("Before selection sort: ");
for (int k = 0; k < 10; k++) {
values.addToFront(randomInt());
}
System.out.println(values);
values.selectionSort();
System.out.print("After selection sort: ");
System.out.println(values);
values = new IntList();
System.out.print("Before insertion sort: ");
for (int k = 0; k < 10; k++) {
values.addToFront(randomInt());
}
System.out.println(values);
sortedValues = values.insertionSort();
System.out.print("After insertion sort: ");
System.out.println(sortedValues);
*/
values = new IntList();
System.out.print("Before quicksort: ");
for (int k = 0; k < 10; k++) {
values.addToFront(randomInt());
}
System.out.println(values);
sortedValues = values.quicksort();
System.out.print("After quicksort: ");
System.out.println(sortedValues);
/*
values = new IntList();
System.out.print("Before merge sort: ");
for (int k = 0; k < 10; k++) {
values.addToFront(randomInt());
}
System.out.println(values);
sortedValues = values.mergeSort();
System.out.print("After merge sort: ");
System.out.println(sortedValues);
*/
}
}
|
[
"[email protected]"
] | |
041c57e70c30f40474346ce6d2760927b5192975
|
c06b6a55e99afae41e6dc30af1c978c67b4503f7
|
/core/src/main/java/com/gamesky/card/core/Page.java
|
18bce92bdf8122196242e1705aa996acfd93b1c6
|
[] |
no_license
|
caprice/cardbox
|
bec1edae064fa2feb451995f9e7062b83c217e47
|
3e9e8539b6936f18c3f73c1e45e7e8584a1b76ea
|
refs/heads/master
| 2020-12-28T23:23:33.028601 | 2015-06-16T15:04:35 | 2015-06-16T15:04:35 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 1,327 |
java
|
package com.gamesky.card.core;
import java.beans.Transient;
/**
* Created on 6/4/15.
*
* @Author lianghongbin
*/
public class Page {
private int count;
private int pagesize;
private int pagenum = 1;
private int total = 1;
public Page() {
this.count = 0;
this.pagesize = Integer.MAX_VALUE;
this.pagenum = 1;
this.total = 1;
}
public Page(int count, int pagesize, int pagenum) {
this.count = count;
this.pagesize = pagesize;
if (pagenum < 1) {
this.pagenum = 1;
} else {
this.pagenum = pagenum;
}
this.total = (int) Math.ceil(count/(float)pagesize);
}
@Transient
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
this.total = (int) Math.ceil(count/(float)pagesize);
}
public int getPagesize() {
return pagesize;
}
public void setPagesize(int pagesize) {
this.pagesize = pagesize;
}
public int getPagenum() {
return pagenum;
}
public void setPagenum(int pagenum) {
this.pagenum = pagenum;
}
public int getOffset() {
return (pagenum -1) * pagesize;
}
public int getTotal() {
return total;
}
}
|
[
"[email protected]"
] | |
5da6b2c15acc134fa71938e2eff5de3c2d37e06e
|
ab28f609ada5f1cbed746a96f56632f7cf1f10e6
|
/BlackjackButton.java
|
cc98164edb390343043c7fb57f2b94c3909c2fb1
|
[] |
no_license
|
mdavidanderson/BlackJack
|
1bcdfab268052648905c12a62d891853f1c55bf1
|
6ec912cb644d529b9eaf646b0ad15302caf20e58
|
refs/heads/master
| 2022-05-08T19:05:46.487432 | 2022-04-12T14:19:39 | 2022-04-12T14:19:39 | 128,568,718 | 0 | 0 | null | 2022-04-12T14:19:40 | 2018-04-07T21:09:50 |
Java
|
UTF-8
|
Java
| false | false | 131 |
java
|
import javax.swing.JButton;
public class BlackjackButton extends JButton
{
public BlackjackButton( String s )
{
super(s);
}
}
|
[
"[email protected]"
] | |
499f5f07b4cfaeddf823612a59c5941457b30a91
|
bbb263605ff729e50eaa115a24d6873456c3aca7
|
/Source/Client/src/edu/mit/coeus/propdev/gui/ProposalOtherElementsAdminForm.java
|
e3a1a527f99d5c4fa17adb16708aaba6ba5c0474
|
[] |
no_license
|
Polus-Software/VUCoeus
|
b7c919ab70ea738baaed27f87d53b1bb6c625357
|
d66c987c6387b458a0e5a7ff1dedeab89225b787
|
refs/heads/master
| 2022-08-30T16:59:29.990885 | 2020-04-29T10:02:57 | 2020-04-29T10:02:57 | 218,743,978 | 0 | 0 | null | null | null | null |
WINDOWS-1252
|
Java
| false | false | 74,028 |
java
|
/**
* @(#)ProposalOtherElementsAdminForm.java 1.0
*
* Copyright (c) Massachusetts Institute of Technology
* 77 Massachusetts Avenue, Cambridge, MA 02139-4307
* All rights reserved.
*/
package edu.mit.coeus.propdev.gui;
import javax.swing.border.CompoundBorder;
import javax.swing.border.EmptyBorder;
import javax.swing.table.*;
import edu.mit.coeus.propdev.bean.*;
import edu.mit.coeus.gui.*;
import java.util.*;
import javax.swing.table.*;
import javax.swing.*;
import java.beans.*;
import java.awt.*;
import java.awt.event.*;
import edu.mit.coeus.search.gui.CoeusSearch;
import edu.mit.coeus.gui.CoeusAppletMDIForm;
import edu.mit.coeus.utils.CoeusGuiConstants;
import edu.mit.coeus.utils.ComboBoxBean;
import edu.mit.coeus.exception.*;
import edu.mit.coeus.utils.EmptyHeaderRenderer;
import edu.mit.coeus.brokers.RequesterBean;
import edu.mit.coeus.brokers.ResponderBean;
import edu.mit.coeus.utils.*;
import edu.mit.coeus.gui.*;
import edu.mit.coeus.departmental.gui.*;
/**
* <CODE>ProposalOtherElementsAdminForm </CODE>is a form object which display
* all the Other column values and it is used to <CODE> add/modify </CODE> the other elements.
* This class will be instantiated from <CODE>ProposalDetailsForm</CODE>.
* @version 1.0 March 13, 2003
* @author Raghunath P.V.
*/
public class ProposalOtherElementsAdminForm extends javax.swing.JComponent implements TypeConstants, LookUpWindowConstants{
//private ProposalCustomElementsInfoBean proposalOthersFormBean;
//private ProposalCustomElementsInfoBean newProposalOthersFormBean;
//private ProposalCustomElementsInfoBean oldProposalOthersFormBean;
private char functionType;
//private boolean canMaintain;
//private Vector vecModuleColumns;
private Vector vecPersonColumnValues;
private edu.mit.coeus.utils.Utils Utils;
private boolean saveRequired;
private String proposalId;
private CoeusMessageResources coeusMessageResources;
private CoeusAppletMDIForm mdiForm;
private static final int DEFAULT__SIZE = 2000;
//private final static int TWO_TABS = 1;
//Case :#3149 – Tabbing between fields does not work on Others tabs - Start
private InputMap inputMap;
private Action oldTabAction,tabAction;
private KeyStroke tab;
// Variable to check TextFiled and Button is Editable or not
private int editableTableField;
//constant assigned for visible button in editor
private final int VISIBLE_BUTTON = 0;
//constant assigned for in-visible button in editor
private final int INVISIBLE_BUTTON = 1;
//constant assigned for editable text field in editor
private final int EDITABLE_TEXT_FIELD = 2;
//constant assigned for non-editable text field in editor
private final int NON_EDITABLE_TEXT_FIELD = 3;
private int mandatoryRow;
private int mandatoryColumn;
private boolean otherTabMandatory = false;
private int previousRow;
private int previousCol;
private int row ;
private int column;
private boolean saveDone = false;
//Case :#3149 - End
//private boolean hasLookUp;
private boolean lookupAvailable[];
/** Creates new form ProposalOtherElementsAdminForm */
public ProposalOtherElementsAdminForm() {
}
/** Creates new form <CODE>ProposalOtherElementsAdminForm</CODE>
*
* @param functionType this will open the different mode like Display
* @param maintainOther is a boolean variable which specifies that the others tab is maintainaable or not
* @param columnModules is a Vector of Custom values for a module
* @param columnValues is a Vector of Custom values for a selected person
* @param id is the String representing the selected Person
* 'D' specifies that the form is in Display Mode
*/
public ProposalOtherElementsAdminForm(char functionType, Vector columnValues, String propId) {
this.functionType = functionType;
this.vecPersonColumnValues = columnValues;
this.proposalId = propId;
this.mdiForm = CoeusGuiConstants.getMDIForm();
coeusMessageResources = CoeusMessageResources.getInstance();
initComponents();
scrPnPersonOtherDetail.setBorder(new javax.swing.border.EmptyBorder(0,0,0,0));
if(functionType == DISPLAY_MODE){
setNotToMaintain();
}
setFormData();
setEditors();
//Case :#3149 - Tabbing between fields does not work on Others tabs -Start
tblProposalOtherDetail.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
int selectedColumn = tblProposalOtherDetail.getSelectedColumn();
if((editableTableField == INVISIBLE_BUTTON) || (selectedColumn <2|| selectedColumn >3)){
setSaveAction(true);
tblProposalOtherDetail.setRowSelectionInterval(getRow(),getRow());
tblProposalOtherDetail.setColumnSelectionInterval(getColumn(),getColumn());
tblProposalOtherDetail.editCellAt(getRow(),getColumn());
}
}
});
//Case :#3149 - End
}
//Case :#3149 - Tabbing between fields does not work on Others tabs -Start
/**
* Method to set tabbing between the fields in the table
*
**/
public void setTabFocus(){
tblProposalOtherDetail.setFocusable(true);
tblProposalOtherDetail.setEnabled(true);
tblProposalOtherDetail.resetKeyboardActions();
// Assigning no action when shift+tab keys are pressed inside table
inputMap = tblProposalOtherDetail.getInputMap(JTable.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
KeyStroke shiftTab=KeyStroke.getKeyStroke(KeyEvent.VK_TAB,InputEvent.SHIFT_MASK);
inputMap.put(shiftTab,"NoAction");
// Assigning no action when enter key is pressed inside table
KeyStroke enter = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0);
inputMap.put(enter,"NoAction");
final Action enterAction = tblProposalOtherDetail.getActionMap().get(inputMap.get(enter));
tab = KeyStroke.getKeyStroke(KeyEvent.VK_TAB, 0);
inputMap.put(tab, inputMap.get(tab));
if(tabAction == null){
setTabAction();
}else{
tabAction.setEnabled(true);
}
}
/**
*Method to set tab action for table
*/
private void setTabAction(){
oldTabAction = tblProposalOtherDetail.getActionMap().get(inputMap.get(tab));
Action tabAction = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
// Auto single tab action is performed
oldTabAction.actionPerformed( e );
JTable table = (JTable)e.getSource();
int row = table.getSelectedRow();
int column = table.getSelectedColumn();
TableCellEditor editor = table.getCellEditor(row,column);
table.editCellAt(row,column);
//Checking for empty cell in the button column
if(editor instanceof ButtonEditor){
if(editableTableField == INVISIBLE_BUTTON){
oldTabAction.actionPerformed(e);
row = table.getSelectedRow();
column = table.getSelectedColumn();
}
}
// To check column non-editable cells and perform auto single tab action
while(!table.isCellEditable(row,column)){
oldTabAction.actionPerformed( e );
row = table.getSelectedRow();
column = table.getSelectedColumn();
}
table.editCellAt(row,column);
// checking non-editable text field and perform auto single tab action
if(editableTableField == NON_EDITABLE_TEXT_FIELD){
oldTabAction.actionPerformed(e);
row = table.getSelectedRow();
column = table.getSelectedColumn();
}
table.editCellAt(row,column);
}
};
tblProposalOtherDetail.getActionMap().put(inputMap.get(tab), tabAction);
}
/**
* Method to set focus to a cell in table when the other tabbed pane is selected
*/
public void setTableFocus(){
tblProposalOtherDetail.setRowSelectionInterval(0,0);
tblProposalOtherDetail.setColumnSelectionInterval(3,3);
boolean buttonFocus = tblProposalOtherDetail.editCellAt(0,3);
tblProposalOtherDetail.setRowSelectionInterval(0,0);
tblProposalOtherDetail.setColumnSelectionInterval(3,3);
previousCol = 3;
previousRow = 0;
// When editCellAt method return null
// Focus is set to the second column component
if(!buttonFocus){
tblProposalOtherDetail.editCellAt(0,2);
tblProposalOtherDetail.setRowSelectionInterval(0,0);
tblProposalOtherDetail.setColumnSelectionInterval(2,2);
previousCol = 2;
previousRow = 0;
}
}
/**
*Method to get JTable object
*/
public JTable getTable(){
return tblProposalOtherDetail;
}
/**
*Method to get LookUpAvailable boolean array
*/
public boolean[] getLookUpAvailable(){
return lookupAvailable;
}
//Case :#3149 - End
/** This method is used to set whether modifications are to be saved or not.
*
* @param saveRequired boolean true if data is to be saved after modifications,
* else false.
*/
public void setSaveRequired(boolean save){
this.saveRequired = save;
}
/** This method is used to find out whether modifications done to the data
* have been saved or not.
*
* @return true if data is not saved after modifications, else false.
*/
public boolean isSaveRequired(){
if(tblProposalOtherDetail.isEditing()){
tblProposalOtherDetail.getCellEditor().stopCellEditing();
}
return this.saveRequired;
}
/** This method is used for Validations.
* @return true if the validation succeed, false otherwise.
* @throws Exception is a exception to be thrown in the client side.
*/
public boolean validateData() throws Exception{
//boolean valid=true;
if(tblProposalOtherDetail.isEditing()){
int selRow = tblProposalOtherDetail.getSelectedRow();
String value = ((javax.swing.text.JTextComponent)
tblProposalOtherDetail.getEditorComponent()).
getText();
tblProposalOtherDetail.setValueAt(value,selRow,2);
((DefaultTableModel)tblProposalOtherDetail.getModel()).
fireTableDataChanged();
tblProposalOtherDetail.getCellEditor().cancelCellEditing();
}
int rowCount = tblProposalOtherDetail.getRowCount();
if(rowCount > 0){
for(int inInd = 0; inInd < rowCount ;inInd++){
boolean isReq = ((Boolean)((DefaultTableModel)
tblProposalOtherDetail.getModel()).getValueAt(inInd,7)).booleanValue();
String cVal = (String)((DefaultTableModel)
tblProposalOtherDetail.getModel()).getValueAt(inInd,2);
String dType = (String)((DefaultTableModel)
tblProposalOtherDetail.getModel()).getValueAt(inInd,8);
int dLen = ((Integer)((DefaultTableModel)
tblProposalOtherDetail.getModel()).getValueAt(inInd,9)).intValue();
String cLabel = (String)((DefaultTableModel)
tblProposalOtherDetail.getModel()).getValueAt(inInd,1);
boolean hLookUp = ((Boolean)((DefaultTableModel)
tblProposalOtherDetail.getModel()).getValueAt(inInd,3)).booleanValue();
if(isReq){
if(cVal == null || cVal.trim().length() <= 0){
tblProposalOtherDetail.requestFocus();
tblProposalOtherDetail.setRowSelectionInterval(inInd,inInd);
if( ! hLookUp ) {
tblProposalOtherDetail.editCellAt(inInd,2);
tblProposalOtherDetail.getEditorComponent().requestFocusInWindow();
}
//Case :#3149 - Tabbing between fields does not work on Others tabs -Start
setMandatoryFields(inInd,2);
setOtherTabMandatory(true);
//Case :#3149 - End
errorMessage(cLabel + " is mandatory. Please enter a value for "+cLabel);
return false;
//break;
}
//Case :#3149 - Tabbing between fields does not work on Others tabs -Start
else{
setOtherTabMandatory(false);
}
//Case :#3149 - End
}
if(dType != null && cVal != null && cVal.trim().length() > 0 ){
if(dType.equalsIgnoreCase("NUMBER")){
try{
Integer.parseInt(cVal);
}catch(NumberFormatException nfe){
tblProposalOtherDetail.requestFocus();
tblProposalOtherDetail.setRowSelectionInterval(inInd,inInd);
if( ! hLookUp ) {
tblProposalOtherDetail.editCellAt(inInd,2);
tblProposalOtherDetail.getEditorComponent().requestFocusInWindow();
}
//Case :#3149 - Tabbing between fields does not work on Others tabs -Start
setMandatoryFields(inInd,2);
setOtherTabMandatory(true);
//Case :#3149 - End
errorMessage("Value for "+cLabel + " should be numeric. ");
return false;
}
}else if(dType.equalsIgnoreCase("DATE")){
DateUtils dateUtils = new DateUtils();
String resultDate = dateUtils.formatDate(cVal,"/-,:","MM/dd/yyyy");
if(resultDate == null){
tblProposalOtherDetail.requestFocus();
tblProposalOtherDetail.setRowSelectionInterval(inInd,inInd);
if( ! hLookUp ) {
tblProposalOtherDetail.editCellAt(inInd,2);
tblProposalOtherDetail.getEditorComponent().requestFocusInWindow();
}
//Case :#3149 - Tabbing between fields does not work on Others tabs -Start
setMandatoryFields(inInd,2);
setOtherTabMandatory(true);
//Case :#3149 - End
errorMessage("Value for "+cLabel + " should be valid date. ");
return false;
}
}
//Case :#3149 - Tabbing between fields does not work on Others tabs -Start
else{
setOtherTabMandatory(false);
}
//Case :#3149 - End
}
int len = cVal.trim().length();
// Bug fix #1460 -start
// if(len > dLen){
// tblProposalOtherDetail.requestFocus();
// tblProposalOtherDetail.setRowSelectionInterval(inInd,inInd);
// if( ! hLookUp ) {
// tblProposalOtherDetail.editCellAt(inInd,2);
// tblProposalOtherDetail.getEditorComponent().requestFocusInWindow();
// }
// errorMessage("Value for "+cLabel + " cannot be more than "+ dLen +" characters long.");
// return false;
// //break;
// }// Bug fix #1460 -end
}
}
return true;
}
//Case :#3149 - Tabbing between fields does not work on Others tabs -Start
/**
* Method to get and set the mandatory row and column
*/
public void setMandatoryFields(int row,int column){
mandatoryRow = row;
mandatoryColumn = 2;
}
/**
* Method to get mandatory row
*/
public int getMandatoryRow(){
return mandatoryRow;
}
/**
* Method to get mandatory column
*/
public int getMandatoryColumn(){
return mandatoryColumn;
}
/**
* Method to set when manadtory dialog box is displayed
*/
private void setOtherTabMandatory(boolean mandatory){
this.otherTabMandatory = mandatory;
}
/**
* Method to get boolean value whether mandatory dialog box is displayed or not
*/
public boolean getOtherTabMandatory(){
return otherTabMandatory;
}
//Case :#3149 - End
/** This method is used to show the alert messages to the user.
* @param mesg is a message to alert the user.
* @throws Exception is the <CODE>Exception</CODE> to throw in the client side.
*/
public static void errorMessage(String mesg) throws Exception {
CoeusUIException coeusUIException = new CoeusUIException(mesg,CoeusUIException.WARNING_MESSAGE);
//modified for the Coeus Enhancement case:#1823 as special review tab is added ,the other tab will be the 7th tab
coeusUIException.setTabIndex(7);
throw coeusUIException;
}
/**
* This method gives you the Vector of ProposalCustomElementsInfoBeans
* @return Vector
*/
public Vector getOtherColumnElementData(){
//printBeanData(getTableData());
return getTableData();
}
/* Method to get all the table data from JTable
@return Vector, a Vector which consists of ProposalCustomElementsInfoBean's */
private Vector getTableData(){
Vector otherTableData = new Vector();
if(tblProposalOtherDetail.getRowCount() > 0){
if(tblProposalOtherDetail.isEditing()){
int selRow = tblProposalOtherDetail.getSelectedRow();
String txtvalue = ((javax.swing.text.JTextComponent)
tblProposalOtherDetail.getEditorComponent()).
getText();
tblProposalOtherDetail.setValueAt(txtvalue,selRow,2);
((DefaultTableModel)tblProposalOtherDetail.getModel()).
fireTableDataChanged();
tblProposalOtherDetail.getCellEditor().cancelCellEditing();
}
int rowCount = tblProposalOtherDetail.getRowCount();
ProposalCustomElementsInfoBean propOthersBean;
for(int inInd = 0 ; inInd < rowCount ; inInd++){
//propOthersBean = new ProposalCustomElementsInfoBean();
propOthersBean = (ProposalCustomElementsInfoBean)vecPersonColumnValues.elementAt(inInd);
String pId = (String)((DefaultTableModel)
tblProposalOtherDetail.getModel()).getValueAt(inInd,0);
String cLabel = (String)((DefaultTableModel)
tblProposalOtherDetail.getModel()).getValueAt(inInd,1);
String cVal = (String)((DefaultTableModel)
tblProposalOtherDetail.getModel()).getValueAt(inInd,2);
boolean hLookUp = ((Boolean)((DefaultTableModel)
tblProposalOtherDetail.getModel()).getValueAt(inInd,3)).booleanValue();
String description = (String)((DefaultTableModel)
tblProposalOtherDetail.getModel()).getValueAt(inInd,4);
String lookWindow = (String)((DefaultTableModel)
tblProposalOtherDetail.getModel()).getValueAt(inInd,5);
String lookArgument = (String)((DefaultTableModel)
tblProposalOtherDetail.getModel()).getValueAt(inInd,6);
boolean isReq = ((Boolean)((DefaultTableModel)
tblProposalOtherDetail.getModel()).getValueAt(inInd,7)).booleanValue();
String dType = (String)((DefaultTableModel)
tblProposalOtherDetail.getModel()).getValueAt(inInd,8);
int dLen = ((Integer)((DefaultTableModel)
tblProposalOtherDetail.getModel()).getValueAt(inInd,9)).intValue();
String colName = (String)((DefaultTableModel)
tblProposalOtherDetail.getModel()).getValueAt(inInd,10);
String acType = (String)((DefaultTableModel)
tblProposalOtherDetail.getModel()).getValueAt(inInd,11);
propOthersBean.setPersonId(pId);
propOthersBean.setColumnName(colName);
propOthersBean.setColumnValue(cVal);
propOthersBean.setColumnLabel(cLabel);
propOthersBean.setDataType(dType);
propOthersBean.setDataLength(dLen);
propOthersBean.setHasLookUp(hLookUp);
propOthersBean.setRequired(isReq);
propOthersBean.setLookUpWindow(lookWindow);
propOthersBean.setLookUpArgument(lookArgument);
propOthersBean.setAcType(acType);
propOthersBean.setProposalNumber(proposalId);
otherTableData.addElement(propOthersBean);
}//END FOR
}//END ROW COUNT
return otherTableData;
}
private void setNotToMaintain(){
tblProposalOtherDetail.setEnabled(false);
}
/* This method is used to set the cell editors to the columns,
set the column width to each individual column, disable the column
resizable feature to the JTable, setting single selection mode to the
JTable */
private void setEditors(){
//createTableColumns();
tblProposalOtherDetail.getTableHeader().setReorderingAllowed(false);
tblProposalOtherDetail.getTableHeader().setResizingAllowed(false);
tblProposalOtherDetail.setSelectionMode(
DefaultListSelectionModel.SINGLE_SELECTION);
tblProposalOtherDetail.setCellSelectionEnabled( false );
tblProposalOtherDetail.setOpaque(true);
TableColumn column = tblProposalOtherDetail.getColumnModel().getColumn(0);
column.setMinWidth(0);
column.setMaxWidth(0);
column.setPreferredWidth(0);
column.setResizable(false);
column = tblProposalOtherDetail.getColumnModel().getColumn(1);
column.setMinWidth(170);
column.setMaxWidth(170);
column.setPreferredWidth(170);
column.setCellRenderer(new ColumnFontRenderer());
// For this Editor should be Text Field.. And Should have Key Listener.
column = tblProposalOtherDetail.getColumnModel().getColumn(2);
column.setMinWidth(150);
column.setMaxWidth(150);
column.setPreferredWidth(150);
column.setCellRenderer(new ColumnValueRenderer());
ColumnValueEditor columnValueEditor =
new ColumnValueEditor(100);
column.setCellEditor(columnValueEditor);
column = tblProposalOtherDetail.getColumnModel().getColumn(3);
column.setMinWidth(25);
column.setMaxWidth(25);
column.setPreferredWidth(25);
column.setCellRenderer(new ButtonRenderer());
column.setCellEditor(new ButtonEditor(new JCheckBox()));
column = tblProposalOtherDetail.getColumnModel().getColumn(4);
column.setMinWidth(300);
column.setMaxWidth(300);
column.setPreferredWidth(300);
column.setCellRenderer(new ColumnFontRenderer());
column = tblProposalOtherDetail.getColumnModel().getColumn(5);
column.setMinWidth(0);
column.setMaxWidth(0);
column.setPreferredWidth(0);
column.setResizable(false);
column = tblProposalOtherDetail.getColumnModel().getColumn(6);
column.setMinWidth(0);
column.setMaxWidth(0);
column.setPreferredWidth(0);
column.setResizable(false);
column = tblProposalOtherDetail.getColumnModel().getColumn(7);
column.setMinWidth(0);
column.setMaxWidth(0);
column.setResizable(false);
column.setPreferredWidth(0);
column = tblProposalOtherDetail.getColumnModel().getColumn(8);
column.setMinWidth(0);
column.setMaxWidth(0);
column.setPreferredWidth(0);
column.setResizable(false);
column = tblProposalOtherDetail.getColumnModel().getColumn(9);
column.setMinWidth(0);
column.setMaxWidth(0);
column.setPreferredWidth(0);
column.setResizable(false);
column = tblProposalOtherDetail.getColumnModel().getColumn(10);
column.setMinWidth(0);
column.setMaxWidth(0);
column.setPreferredWidth(0);
column.setResizable(false);
column = tblProposalOtherDetail.getColumnModel().getColumn(11);
column.setMinWidth(0);
column.setMaxWidth(0);
column.setPreferredWidth(0);
column.setResizable(false);
tblProposalOtherDetail.getTableHeader().setVisible(false);
}
/** Method to set the data in the JTable.
* This method sets the data which is available in ProposalCostElementsInfoBean's
* Vector to JTable.
*/
private void setFormData(){
ProposalCustomElementsInfoBean proposalOthersFormBean = null;
if(vecPersonColumnValues != null){
int size = vecPersonColumnValues.size();
Vector vcDataPopulate = new Vector();
Vector vcData;
lookupAvailable = new boolean[size];
for(int index = 0; index < size; index++){
proposalOthersFormBean = (ProposalCustomElementsInfoBean)vecPersonColumnValues.get(index);
if(proposalOthersFormBean != null){
String personId = proposalOthersFormBean.getPersonId();
String columnName = proposalOthersFormBean.getColumnName();
String columnValue = proposalOthersFormBean.getColumnValue();
String coulmnLabel = proposalOthersFormBean.getColumnLabel();
//Added for case#3148 - Inconsistent UI for custom element tabs
coulmnLabel = coulmnLabel +":";
String dataType = proposalOthersFormBean.getDataType();
int dataLength = proposalOthersFormBean.getDataLength();
String defaultValue = proposalOthersFormBean.getDefaultValue();
boolean hasLookUp = proposalOthersFormBean.isHasLookUp();
lookupAvailable[index] = proposalOthersFormBean.isHasLookUp();
boolean isRequired = proposalOthersFormBean.isRequired();
String lookUpWindow = proposalOthersFormBean.getLookUpWindow();
String lookUpArgument = proposalOthersFormBean.getLookUpArgument();
String acType = proposalOthersFormBean.getAcType();
String description = proposalOthersFormBean.getDescription();
//to fire save required if any of the columns have actype as "I" or
// if in modify mode, if any column is required and there is no data
if( INSERT_RECORD.equals(acType) || (isRequired && ( columnValue == null || columnValue.trim().length() == 0 ) ) ){
saveRequired = true;
}
vcData = new Vector();
vcData.addElement(personId == null ? "" : personId);
vcData.addElement(coulmnLabel == null ? "" : coulmnLabel);
vcData.addElement(columnValue == null ? "" : columnValue);
vcData.addElement(new Boolean(hasLookUp));
vcData.addElement(description == null ? "" : description);
vcData.addElement(lookUpWindow == null ? "" : lookUpWindow);
vcData.addElement(lookUpArgument == null ? "" : lookUpArgument);
vcData.addElement(new Boolean(isRequired));
vcData.addElement(dataType == null ? "" : dataType);
vcData.addElement(new Integer(dataLength));
vcData.addElement(columnName == null ? "" : columnName);
vcData.addElement(acType == null ? "" : acType);
vcDataPopulate.addElement(vcData);
}
}
((DefaultTableModel)tblProposalOtherDetail.getModel()).
setDataVector(vcDataPopulate,getColumnNames());
((DefaultTableModel)tblProposalOtherDetail.getModel()).
fireTableDataChanged();
}
}
/* Method to get all the column names of JTable*/
private Vector getColumnNames(){
Enumeration enumColNames = tblProposalOtherDetail.getColumnModel().getColumns();
Vector vecColNames = new Vector();
while(enumColNames.hasMoreElements()){
String strName = (String)((TableColumn)
enumColNames.nextElement()).getHeaderValue();
vecColNames.addElement(strName);
}
return vecColNames;
}
/**
* This method is used to set the data to the JTable.
* @param columnValues is a vector containing ProposalCostElementsInfoBean's
**/
public void setPersonColumnValues(Vector columnValues){
this.vecPersonColumnValues = columnValues;
if(vecPersonColumnValues != null){
setFormData();
}else{
((DefaultTableModel)tblProposalOtherDetail.getModel()).setDataVector(
new Object[][]{},getColumnNames().toArray());
}
setEditors();
}
/**
* Helper method to display the Lookup Window when the Lookup button is Pressed
*/
private void showLookupSearchWindow(OtherLookupBean otherLookupBean,
String lookUpWindow, Vector vecLookupdata, String columnValue,
int selectedRow){
ComboBoxBean cBean = null;
if(otherLookupBean != null){
if(lookUpWindow.equalsIgnoreCase(COST_ELEMENT_LOOKUP_WINDOW)) {
CostElementsLookupWindow costElementsLookupWindow =
new CostElementsLookupWindow(otherLookupBean);
} else {
/** Sagin **/
CoeusTableWindow coeusTableWindow =
new CoeusTableWindow(otherLookupBean);
}
}
int selRow = otherLookupBean.getSelectedInd();
if(vecLookupdata != null && selRow >= 0){
cBean = (ComboBoxBean)vecLookupdata.elementAt(selRow);
if(cBean != null){
String code = (String)cBean.getCode();
String desc = (String)cBean.getDescription();
if(!code.equalsIgnoreCase(columnValue)){
saveRequired = true;
String acType = (String)((DefaultTableModel)tblProposalOtherDetail.getModel()
).getValueAt(selectedRow,11);
if(acType == null || !acType.equalsIgnoreCase(INSERT_RECORD)){
acType = UPDATE_RECORD;
((DefaultTableModel)tblProposalOtherDetail.getModel()
).setValueAt(acType,selectedRow,11);
}
}
((DefaultTableModel)tblProposalOtherDetail.getModel()
).setValueAt(code,selectedRow,2);
((DefaultTableModel)tblProposalOtherDetail.getModel()
).setValueAt(desc,selectedRow,4);
tblProposalOtherDetail.getSelectionModel().
setLeadSelectionIndex(selectedRow);
if(tblProposalOtherDetail.getCellEditor()!=null){
tblProposalOtherDetail.getCellEditor().cancelCellEditing();
}
}
}
}
//Helper Method to show the Search Window
private void showSearchWindow(String searchType, String colValue, int selectedRow){
try{
CoeusSearch coeusSearch = new CoeusSearch(mdiForm, searchType, 1);
coeusSearch.showSearchWindow();
HashMap personInfo = coeusSearch.getSelectedRow();
String pID = null;
String name = null;
if(personInfo!=null){
pID = Utils.
convertNull(personInfo.get( "ID" ));
name = Utils.
convertNull(personInfo.get( "NAME" ));
if((pID!= null) && (!pID.equalsIgnoreCase(colValue))){
saveRequired = true;
//System.out.println("setting saveReq to true...in showSearch");
String acType = UPDATE_RECORD;
String prevAcT = (String)((DefaultTableModel)tblProposalOtherDetail.getModel()
).getValueAt(selectedRow,11);
if(prevAcT != null){
if(!prevAcT.equalsIgnoreCase(INSERT_RECORD)){
((DefaultTableModel)tblProposalOtherDetail.getModel()
).setValueAt(acType,selectedRow,11);
}
}else{
((DefaultTableModel)
tblProposalOtherDetail.getModel()).setValueAt(acType,selectedRow,11);
}
}
((DefaultTableModel)tblProposalOtherDetail.getModel()
).setValueAt(pID,selectedRow,2);
((DefaultTableModel)tblProposalOtherDetail.getModel()
).setValueAt(name,selectedRow,4);
((DefaultTableModel)tblProposalOtherDetail.getModel()).fireTableRowsUpdated(selectedRow, selectedRow);
tblProposalOtherDetail.getSelectionModel().setLeadSelectionIndex(selectedRow);
if(tblProposalOtherDetail.getCellEditor()!=null){
tblProposalOtherDetail.getCellEditor().cancelCellEditing();
}
}
}catch(Exception exp){
exp.printStackTrace();
}
}
/** 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.
*/
private void initComponents() {//GEN-BEGIN:initComponents
scrPnPersonOtherDetail = new javax.swing.JScrollPane();
tblProposalOtherDetail = new javax.swing.JTable();
setLayout(new java.awt.BorderLayout());
scrPnPersonOtherDetail.setOpaque(false);
tblProposalOtherDetail.setModel(new CustomTableModel());
tblProposalOtherDetail.setFont(CoeusFontFactory.getLabelFont());
tblProposalOtherDetail.setBackground((java.awt.Color) javax.swing.UIManager.getDefaults().get("Panel.background"));
tblProposalOtherDetail.setSelectionForeground(new java.awt.Color(204, 204, 204));
tblProposalOtherDetail.setRowHeight(25);
tblProposalOtherDetail.setShowVerticalLines(false);
tblProposalOtherDetail.setSelectionBackground(new java.awt.Color(204, 204, 204));
tblProposalOtherDetail.setShowHorizontalLines(false);
tblProposalOtherDetail.setRowSelectionAllowed(false);
tblProposalOtherDetail.setRowMargin(3);
tblProposalOtherDetail.setOpaque(false);
scrPnPersonOtherDetail.setViewportView(tblProposalOtherDetail);
add(scrPnPersonOtherDetail, java.awt.BorderLayout.NORTH);
}//GEN-END:initComponents
/** Getter for property functionType.
* @return Value of property functionType.
*/
public char getFunctionType() {
return functionType;
}
/** Setter for property functionType.
* @param functionType New value of property functionType.
*/
public void setFunctionType(char functionType) {
this.functionType = functionType;
}
// Variables declaration - do not modify//GEN-BEGIN:variables
public javax.swing.JScrollPane scrPnPersonOtherDetail;
public javax.swing.JTable tblProposalOtherDetail;
// End of variables declaration//GEN-END:variables
/**
* This inner class creates a custom DefaultTableModel with Columns
*/
public class CustomTableModel extends DefaultTableModel{
public CustomTableModel(){
super(new Object [][] {}, new String [] {
"", "", "", "Button", "", "", "", "", "", "", "", ""});
}
Class[] types = new Class [] {
java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.Object.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.Boolean.class, java.lang.String.class, java.lang.Integer.class, java.lang.String.class, java.lang.String.class
};
boolean[] canEdit = new boolean [] {
false, false, true, true, false, false, false, false, false, false, false, false
};
public Class getColumnClass(int columnIndex) {
return types [columnIndex];
}
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
}
//Case :#3149 - Tabbing between fields does not work on Others tabs - Start
/**
*Method toset selected row and column
*/
private void setRowColumn(int row, int column){
this.row = row;
this.column = column;
}
/**
*Method to get editing row
*/
public int getRow(){
return row;
}
/**
*Method to get editing column
*/
public int getColumn(){
return column;
}
/**
*Method to save action when save is performed
*/
public void setSaveAction(boolean save){
this.saveDone = save;
}
//Case :#3149 - End
/**
* This inner class is used as a Custom Cell editor for the columnValue column in the JTable.
*/
class ColumnValueEditor extends AbstractCellEditor
implements TableCellEditor, Runnable {
private JTextField txtDesc;
private int selectedRow ;
private String personId;
private String columnName;
private String colValue;
private String coulmnLabel;
private String dataType;
private int dataLength;
private String defaultValue;
private boolean hasLookUp;
private boolean isRequired;
private String lookUpWindow;
private String lookUpArgument;
private boolean temporary;
private CoeusSearch coeusSearch;
//Case :#3149 – Tabbing between fields does not work on others tabs - Start
private int editorRow;
private int editorColumn;
private int tempRow = -1;
private int tempColumn = -1;
private JTable otherTabTable;
//Case :#3149 - End
//private final String PERSON_SEARCH = "personSearch";
// Constructor which sets the length to the columnValue TextField
ColumnValueEditor(int len ){
//super(new JTextField());
txtDesc = new JTextField();
txtDesc.setFont(CoeusFontFactory.getNormalFont());
txtDesc.setDocument(new LimitedPlainDocument(len));
txtDesc.addFocusListener(new FocusAdapter(){
public void focusGained(FocusEvent fe){
temporary = false;
}
public void focusLost(FocusEvent fe){
//Case :#3149 - Tabbing between fields does not work on Others tabs - Start
editableTableField = NON_EDITABLE_TEXT_FIELD;
//Case :#3149 - End
if (!fe.isTemporary() ){
if(!temporary){
stopCellEditing();
}
}
}
});
txtDesc.addMouseListener(new MouseAdapter(){
//Modified for COEUSDEV-184 : Need to click twice onb icons - Custom data, YNQ etc - Start
// public void mouseClicked(MouseEvent mouseEvent){
// if(mouseEvent.getClickCount() == 2){
public void mousePressed(MouseEvent mouseEvent){
if(mouseEvent.getClickCount()> 0){//COEUSDEV-184 : END
String windowTitle;
if(lookUpWindow != null && lookUpWindow.trim().length() > 0 ){
// if(lookUpWindow.equalsIgnoreCase(PERSON_LOOKUP_WINDOW)){
// showSearchWindow(PERSON_SEARCH, colValue, selectedRow);
// }else if(lookUpWindow.equalsIgnoreCase(UNIT_LOOKUP_WINDOW)){
// showSearchWindow(UNIT_SEARCH, colValue, selectedRow);
// }else if(lookUpWindow.equalsIgnoreCase(ROLODEX_LOOKUP_WINDOW)){
// showSearchWindow(ROLODEX_SEARCH, colValue, selectedRow);
//
// }
if(lookUpWindow.equalsIgnoreCase(CODE_LOOKUP_WINDOW)){
if(lookUpArgument != null){
windowTitle = "Lookup Values for - "+lookUpArgument.toUpperCase();
Vector vecLookupdata = getLookupValuesFromDB(lookUpArgument, lookUpWindow);
OtherLookupBean otherLookupBean =
new OtherLookupBean(windowTitle, vecLookupdata, CODE_COLUMN_NAMES);
showLookupSearchWindow(otherLookupBean, lookUpWindow, vecLookupdata, colValue, selectedRow);
}
}else if(lookUpWindow.equalsIgnoreCase(VALUE_LOOKUP_WINDOW)){
windowTitle = "Lookup Values";
if(lookUpArgument != null){
// if(lookUpArgument.equalsIgnoreCase("Special review type")){
Vector vecLookupdata = getLookupValuesFromDB(lookUpArgument, lookUpWindow);
OtherLookupBean otherLookupBean =
new OtherLookupBean(windowTitle, vecLookupdata, VALUE_COLUMN_NAMES);
showLookupSearchWindow(otherLookupBean, lookUpWindow, vecLookupdata, colValue, selectedRow);
// }
}
}else if(lookUpWindow.equalsIgnoreCase(COST_ELEMENT_LOOKUP_WINDOW)){
windowTitle = "Cost Elements";
if(lookUpArgument != null){
if( lookUpArgument.trim().length()>0 ) {
windowTitle = "Lookup Values for - "+lookUpArgument.toUpperCase();
}
Vector vecLookupdata = getLookupValuesFromDB(lookUpArgument, lookUpWindow);
OtherLookupBean otherLookupBean =
new OtherLookupBean(windowTitle, vecLookupdata, CODE_COLUMN_NAMES);
showLookupSearchWindow(otherLookupBean, lookUpWindow, vecLookupdata, colValue, selectedRow);
}
}else{
showSearchWindow(lookUpWindow, colValue, selectedRow);
}
}
//fireEditingStopped();
}
}
});
}
/** This overridden to get the custom cell component in the
* JTable.
* @param table JTable instance for which component is derived
* @param value object value.
* @param isSelected particular table cell is selected or not
* @param row row index
* @param column column index
* @return a Component which is a editor component to the JTable cell.
*/
public Component getTableCellEditorComponent(JTable table,
Object value,boolean isSelected,int row,int column){
//saveRequired=true;
colValue = (String)tblProposalOtherDetail.getValueAt(row,2);
if(colValue == null){
colValue = "";
}
this.selectedRow = row;
this.personId = (String)tblProposalOtherDetail.getValueAt(row,0);
this.coulmnLabel = (String)tblProposalOtherDetail.getValueAt(row,1);
this.colValue = (String)tblProposalOtherDetail.getValueAt(row,2);
this.hasLookUp = ((Boolean)tblProposalOtherDetail.getValueAt(row,3)).booleanValue();
this.defaultValue = (String)tblProposalOtherDetail.getValueAt(row,4);
this.lookUpWindow = (String)tblProposalOtherDetail.getValueAt(row,5);
this.lookUpArgument = (String)tblProposalOtherDetail.getValueAt(row,6);
this.isRequired = ((Boolean)tblProposalOtherDetail.getValueAt(row,7)).booleanValue();
this.dataType = (String)tblProposalOtherDetail.getValueAt(row,8);
this.dataLength = ((Integer)tblProposalOtherDetail.getValueAt(row,9)).intValue();
// Bug fix #1460 -start
if(dataLength <= 0)
dataLength = DEFAULT__SIZE;
// Bug fix #1460 -end
if( dataType.equalsIgnoreCase("NUMBER") ){
txtDesc.setDocument(new JTextFieldFilter(JTextFieldFilter.NUMERIC,dataLength));
}else if( dataType.equalsIgnoreCase("DATE") ){
txtDesc.setDocument(new LimitedPlainDocument(11));
}else {
txtDesc.setDocument(new LimitedPlainDocument(dataLength));
}
String newValue = ( String ) value ;
if( newValue != null && newValue.length() > 0 ){
txtDesc.setText( (String)newValue );
}else{
txtDesc.setText("");
}
if(lookupAvailable[row]){
txtDesc.setEnabled(false);
//Case :#3149 - Tabbing between fields does not work on Others tabs - Start
editableTableField = NON_EDITABLE_TEXT_FIELD;
//Case :#3149 - End
return txtDesc;
}else{
txtDesc.setEnabled(true);
//Case :#3149 - Tabbing between fields does not work on Others tabs - Start
editableTableField = EDITABLE_TEXT_FIELD;
editorRow = row;
editorColumn = column;
otherTabTable = table;
SwingUtilities.invokeLater(this);
//Case :#3149 - End
return txtDesc;
}
}
//Case :#3149 - Tabbing between fields does not work on Others tabs - Start
/**
* Method added to set focus for editable textfield
*/
public void run() {
boolean focus = txtDesc.requestFocusInWindow();
if(!focus){
if(tempRow != editorRow || saveDone){
otherTabTable.editCellAt(editorRow,editorColumn);
txtDesc.requestFocusInWindow();
previousRow = editorRow;
previousCol = editorColumn;
tempRow = editorRow;
tempColumn = editorColumn;
saveDone = false;
}
}else{
tempRow = editorRow;
tempColumn = editorColumn;
}
setRowColumn(editorRow,editorColumn);
}
//Case :#3149 - End
//Helper method to set the editing Value to the JTable
private void setEditorValueToTable(String editingValue){
if( (editingValue == null )){
editingValue = (editingValue == null) ? "" : editingValue;
((JTextField)txtDesc).setText( editingValue);
((DefaultTableModel)tblProposalOtherDetail.getModel()).setValueAt(editingValue,selectedRow,2); // Handle
tblProposalOtherDetail.getSelectionModel().
setLeadSelectionIndex(selectedRow);
}else{
editingValue = editingValue.trim();
//colValue = (colValue == null) ? "" : colValue;
if(!editingValue.equalsIgnoreCase(colValue)){
saveRequired = true;
String acType = (String)((DefaultTableModel)tblProposalOtherDetail.getModel()
).getValueAt(selectedRow,11);
if(acType == null || !acType.equalsIgnoreCase(INSERT_RECORD)){
acType = UPDATE_RECORD;
((DefaultTableModel)tblProposalOtherDetail.getModel()
).setValueAt(acType,selectedRow,11);
}
}
}
//Bug fix by bijosh :
// made colValue.trim().length()>=0 to colValue.trim().length()>0 in if condition
if( ((editingValue == null ) || (editingValue.trim().length()== 0 )) &&
(colValue != null) && (colValue.trim().length()> 0 )){
saveRequired = true;
String acType = (String)((DefaultTableModel)tblProposalOtherDetail.getModel()
).getValueAt(selectedRow,11);
if(acType == null || !acType.equalsIgnoreCase(INSERT_RECORD)){
acType = UPDATE_RECORD;
((DefaultTableModel)tblProposalOtherDetail.getModel()
).setValueAt(acType,selectedRow,11);
}
}
((DefaultTableModel)tblProposalOtherDetail.getModel()
).setValueAt(editingValue,selectedRow,2);
((JTextField)txtDesc).setText( editingValue);
tblProposalOtherDetail.getSelectionModel().
setLeadSelectionIndex(selectedRow);
}
// Helper method which is used to get the lookup data from the database based on the lookup argument
private Vector getLookupValuesFromDB(String lookUpArgument, String lookUpWindow){
String connectTo = CoeusGuiConstants.CONNECTION_URL + "/coeusFunctionsServlet";
RequesterBean request = new RequesterBean();
Vector serverLookUpDataObject = null;
if( lookUpWindow.equalsIgnoreCase(VALUE_LOOKUP_WINDOW) ){
request.setDataObject("DW_GET_ARG_VALUE_DESC_TBL_NEW");
}else if(lookUpWindow.equalsIgnoreCase(COST_ELEMENT_LOOKUP_WINDOW)){
request.setDataObject("DW_GET_COST_ELEMENTS");
}else{
request.setDataObject("DW_GET_ARG_CODE_TBL_NEW");
}
request.setId(lookUpArgument);
AppletServletCommunicator comm
= new AppletServletCommunicator(connectTo, request);
comm.send();
ResponderBean response = comm.getResponse();
if (response!=null){
if (response.isSuccessfulResponse()){
serverLookUpDataObject = (Vector)response.getDataObject();
}
}
return serverLookUpDataObject;
}
public int getClickCountToStart(){
return 1;
}
/** Returns the value contained in the editor.
* @return the value contained in the editor
*/
public Object getCellEditorValue() {
return ((JTextField)txtDesc).getText();
}
/**
* Forwards the message from the CellEditor to the delegate. Tell the
* editor to stop editing and accept any partially edited value as the
* value of the editor.
* @return true if editing was stopped; false otherwise
*/
public boolean stopCellEditing() {
String editingValue = (String)getCellEditorValue();
setEditorValueToTable(editingValue);
return super.stopCellEditing();
}
protected void fireEditingStopped() {
super.fireEditingStopped();
}
}
//TextField Cell Renderer
public class ColumnValueRenderer extends JTextField implements TableCellRenderer {
public ColumnValueRenderer() {
setOpaque(true);
setFont(CoeusFontFactory.getNormalFont());
}
/** An overridden method to render the component(icon) in cell.
* foreground/background for this cell and Font too.
*
* @param table the JTable that is asking the renderer to draw;
* can be null
* @param value the value of the cell to be rendered. It is up to the
* specific renderer to interpret and draw the value. For example,
* if value is the string "true", it could be rendered as a string or
* it could be rendered as a check box that is checked. null is a
* valid value
* @param isSelected true if the cell is to be rendered with the
* selection highlighted; otherwise false
* @param hasFocus if true, render cell appropriately. For example,
* put a special border on the cell, if the cell can be edited, render
* in the color used to indicate editing
* @param row the row index of the cell being drawn. When drawing the
* header, the value of row is -1
* @param column the column index of the cell being drawn
* @return Component which is to be rendered.
* @see TableCellRenderer#getTableCellRendererComponent(JTable, Object,
* boolean, boolean, int, int)
*/
public Component getTableCellRendererComponent(JTable table,
Object value, boolean isSelected, boolean hasFocus, int row, int column) {
setText( (value ==null) ? "" : value.toString() );
//Added by Amit 11/19/2003
if(functionType == CoeusGuiConstants.DISPLAY_MODE)
{
java.awt.Color bgListColor = (java.awt.Color)javax.swing.UIManager.getDefaults().get("Panel.background");
setBackground(bgListColor);
}
else
{
setBackground(Color.white);
}
//End Amit
return this;
}
}
/**
* This inner class is used as a Custom Cell editor for the hasLookup column in the JTable.
*/
public class ButtonEditor extends DefaultCellEditor implements Runnable{
protected JButton button;
private int selRow ;
private String personId;
private String columnName;
private String cValue;
private String coulmnLabel;
private String dataType;
private int dataLength;
private String defaultValue;
private boolean isRequired;
private boolean hasLookUp;
private String lookUpWindow;
private String lookUpArgument;
//Case :#3149 – Tabbing between fields does not work on others tabs - Start
private int editorRow;
private int editorColumn;
private int tempRow = -1;
private int tempColumn = -1;
private JTable otherTabTable;
//Case :#3149 - End
private CoeusSearch coeusSearch;
CoeusAppletMDIForm mdiForm = CoeusGuiConstants.getMDIForm();
public ButtonEditor(JCheckBox cf ) {
super(cf);
button = new JButton();
//Bug Fix:1077 Start 1
button.setIcon(new ImageIcon(getClass().getClassLoader().getResource(CoeusGuiConstants.SEARCH_ICON)));
//Bug Fix:1077 End 1
button.setMaximumSize(new java.awt.Dimension(23, 23));
button.setMinimumSize(new java.awt.Dimension(23, 23));
button.setPreferredSize(new java.awt.Dimension(23, 23));
button.setOpaque(true);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//Case :#3149 - Tabbing between fields does not work on Others tabs - Start
showDialog();
//Case :#3149 - End
}
});
}
//Case :#3149 – Tabbing between fields does not work on others tabs - Start
/**
* Methos to display the dialog window
*/
private void showDialog(){
fireEditingStopped();
String windowTitle;
if(lookUpWindow != null && lookUpWindow.trim().length() > 0 ){
// if(lookUpWindow.equalsIgnoreCase(PERSON_LOOKUP_WINDOW)){
//
// showSearchWindow(PERSON_SEARCH, cValue, selRow);
// }else if(lookUpWindow.equalsIgnoreCase(UNIT_LOOKUP_WINDOW)){
//
// showSearchWindow(UNIT_SEARCH, cValue, selRow);
// }else if(lookUpWindow.equalsIgnoreCase(ROLODEX_LOOKUP_WINDOW)){
//
// showSearchWindow(ROLODEX_SEARCH, cValue, selRow);
// }
if(lookUpWindow.equalsIgnoreCase(CODE_LOOKUP_WINDOW)){
if(lookUpArgument != null){
windowTitle = "Lookup Values for - "+lookUpArgument.toUpperCase();
Vector vecLookupdata = getLookupValuesFromDB(lookUpArgument, lookUpWindow);
OtherLookupBean otherLookupBean =
new OtherLookupBean(windowTitle, vecLookupdata, CODE_COLUMN_NAMES);
showLookupSearchWindow(otherLookupBean, lookUpWindow, vecLookupdata, cValue, selRow);
}
}else if(lookUpWindow.equalsIgnoreCase(VALUE_LOOKUP_WINDOW)){
windowTitle = "Lookup Values";
if(lookUpArgument != null){
// if(lookUpArgument.equalsIgnoreCase("Special review type")){
Vector vecLookupdata = getLookupValuesFromDB(lookUpArgument, lookUpWindow);
OtherLookupBean otherLookupBean =
new OtherLookupBean(windowTitle, vecLookupdata, VALUE_COLUMN_NAMES);
showLookupSearchWindow(otherLookupBean, lookUpWindow, vecLookupdata, cValue, selRow);
// }
}
}else if(lookUpWindow.equalsIgnoreCase(COST_ELEMENT_LOOKUP_WINDOW)){
windowTitle = "Cost Elements";
if(lookUpArgument != null){
if( lookUpArgument.trim().length() > 0){
windowTitle = "Lookup Values for - "+lookUpArgument.toUpperCase();
}
Vector vecLookupdata = getLookupValuesFromDB(lookUpArgument, lookUpWindow);
OtherLookupBean otherLookupBean =
new OtherLookupBean(windowTitle, vecLookupdata, CODE_COLUMN_NAMES);
showLookupSearchWindow(otherLookupBean, lookUpWindow, vecLookupdata, cValue, selRow);
}
}else{
showSearchWindow(lookUpWindow, cValue, selRow);
}
}
//Case :#3149 – Tabbing between fields does not work on others tabs - Start
final JTable otherTabTable = tblProposalOtherDetail;
final int selectedRow = otherTabTable.getSelectedRow();
final int selectedColumn = otherTabTable.getSelectedColumn();
SwingUtilities.invokeLater(new Runnable() {
public void run() {
otherTabTable.editCellAt(selectedRow,selectedColumn);
previousCol = selectedColumn;
previousRow = selectedRow;
button.requestFocusInWindow();
}
});
//Case :#3149 - End
fireEditingStopped();
}
private Vector getLookupValuesFromDB(String lookUpArgument, String lookUpWindow){
String connectTo = CoeusGuiConstants.CONNECTION_URL + "/coeusFunctionsServlet";
RequesterBean request = new RequesterBean();
Vector serverLookUpDataObject = null;
if( lookUpWindow.equalsIgnoreCase(VALUE_LOOKUP_WINDOW) ){
request.setDataObject("DW_GET_ARG_VALUE_DESC_TBL_NEW");
}else if(lookUpWindow.equalsIgnoreCase(COST_ELEMENT_LOOKUP_WINDOW)){
request.setDataObject("DW_GET_COST_ELEMENTS");
}else{
request.setDataObject("DW_GET_ARG_CODE_TBL_NEW");
}
request.setId(lookUpArgument);
AppletServletCommunicator comm
= new AppletServletCommunicator(connectTo, request);
comm.send();
ResponderBean response = comm.getResponse();
if (response!=null){
if (response.isSuccessfulResponse()){
serverLookUpDataObject = (Vector)response.getDataObject();
}
}
return serverLookUpDataObject;
}
/** This overridden to get the custom cell component in the
* JTable.
* @param table JTable instance for which component is derived
* @param value object value.
* @param isSelected particular table cell is selected or not
* @param row row index
* @param column column index
* @return a Component which is a editor component to the JTable cell.
*/
public Component getTableCellEditorComponent(JTable table, Object value,
boolean isSelected, int row, int column) {
this.selRow = row;
this.personId = (String)tblProposalOtherDetail.getValueAt(row,0);
this.coulmnLabel = (String)tblProposalOtherDetail.getValueAt(row,1);
this.cValue = (String)tblProposalOtherDetail.getValueAt(row,2);
this.hasLookUp = ((Boolean)tblProposalOtherDetail.getValueAt(row,3)).booleanValue();
this.defaultValue = (String)tblProposalOtherDetail.getValueAt(row,4);
this.lookUpWindow = (String)tblProposalOtherDetail.getValueAt(row,5);
this.lookUpArgument = (String)tblProposalOtherDetail.getValueAt(row,6);
this.isRequired = ((Boolean)tblProposalOtherDetail.getValueAt(row,7)).booleanValue();
this.dataType = (String)tblProposalOtherDetail.getValueAt(row,8);
this.dataLength = ((Integer)tblProposalOtherDetail.getValueAt(row,9)).intValue();
if(lookupAvailable[row]){
//Case :#3149 - Tabbing between fields does not work on Others tabs - Start
tblProposalOtherDetail.setCellSelectionEnabled(true);
editorRow = row;
editorColumn = column;
previousCol = column;
previousRow = row;
otherTabTable = table;
SwingUtilities.invokeLater(this);
editableTableField = VISIBLE_BUTTON;
//Case :#3149 - End
return button;
}else{
//Case :#3149 - Tabbing between fields does not work on Others tabs - Start
editableTableField = INVISIBLE_BUTTON;
//Case :#3149 - End
return null;
}
}
//Case :#3149 - Tabbing between fields does not work on Others tabs - Start
/**
* Method added to set focus for editable textfield
*/
public void run() {
boolean focus = button.requestFocusInWindow();
if(!focus){
if(tempRow != editorRow){
otherTabTable.editCellAt(editorRow,editorColumn);
previousCol = editorColumn;
previousRow = editorRow;
button.requestFocusInWindow();
tempRow = editorRow;
tempColumn = editorColumn;
}
}else{
tempRow = editorRow;
tempColumn = editorColumn;
}
setRowColumn(editorRow,editorColumn);
}
//Case :#3149 - End
public int getClickCountToStart(){
return 1;
}
/**
* Forwards the message from the CellEditor to the delegate. Tell the
* editor to stop editing and accept any partially edited value as the
* value of the editor.
* @return true if editing was stopped; false otherwise
*/
public boolean stopCellEditing() {
return super.stopCellEditing();
}
protected void fireEditingStopped() {
super.fireEditingStopped();
}
}
//Button Cell Renderer for haslookup button
public class ButtonRenderer extends JButton implements TableCellRenderer {
public ButtonRenderer() {
setOpaque(true);
//Bug Fix:1077 Start 2
setIcon(new ImageIcon(getClass().getClassLoader().getResource(CoeusGuiConstants.SEARCH_ICON)));
//Bug Fix:1077 End 2
}
/** An overridden method to render the component(icon) in cell.
* foreground/background for this cell and Font too.
*
* @param table the JTable that is asking the renderer to draw;
* can be null
* @param value the value of the cell to be rendered. It is up to the
* specific renderer to interpret and draw the value. For example,
* if value is the string "true", it could be rendered as a string or
* it could be rendered as a check box that is checked. null is a
* valid value
* @param isSelected true if the cell is to be rendered with the
* selection highlighted; otherwise false
* @param hasFocus if true, render cell appropriately. For example,
* put a special border on the cell, if the cell can be edited, render
* in the color used to indicate editing
* @param row the row index of the cell being drawn. When drawing the
* header, the value of row is -1
* @param column the column index of the cell being drawn
* @return Component which is to be rendered.
* @see TableCellRenderer#getTableCellRendererComponent(JTable, Object,
* boolean, boolean, int, int)
*/
public Component getTableCellRendererComponent(JTable table,
Object value, boolean isSelected, boolean hasFocus, int row, int column) {
if(lookupAvailable[row]){
return this;
}else{
return null;
}
}
}
// custom renderer for setting custom font for the description column in the JTable.
public class ColumnFontRenderer extends DefaultTableCellRenderer {
JLabel lblDesc = new JLabel(){
public boolean isFocusTraversable() {
return false;
}
};
public ColumnFontRenderer() {
super();
}
/** An overridden method to render the component(icon) in cell.
* foreground/background for this cell and Font too.
*
* @param table the JTable that is asking the renderer to draw;
* can be null
* @param value the value of the cell to be rendered. It is up to the
* specific renderer to interpret and draw the value. For example,
* if value is the string "true", it could be rendered as a string or
* it could be rendered as a check box that is checked. null is a
* valid value
* @param isSelected true if the cell is to be rendered with the
* selection highlighted; otherwise false
* @param hasFocus if true, render cell appropriately. For example,
* put a special border on the cell, if the cell can be edited, render
* in the color used to indicate editing
* @param row the row index of the cell being drawn. When drawing the
* header, the value of row is -1
* @param column the column index of the cell being drawn
* @return Component which is to be rendered.
* @see TableCellRenderer#getTableCellRendererComponent(JTable, Object,
* boolean, boolean, int, int)
*/
public Component getTableCellRendererComponent(JTable table,
Object value, boolean isSelected, boolean hasFocus, int row, int column) {
/*Component cell = super.getTableCellRendererComponent
(table, value, isSelected, hasFocus, row, column);
cell.setFont(CoeusFontFactory.getNormalFont());
return cell;*/
//Added for case# 3148 - Inconsistent UI for custom element tabs
lblDesc.setBorder(null);
if( column == 4) {
lblDesc.setFont(CoeusFontFactory.getNormalFont());
//Added for case# 3148 - Inconsistent UI for custom element tabs
lblDesc.setBorder(new CompoundBorder(new EmptyBorder(new Insets(1,4,1,4)),
lblDesc.getBorder()));
}else if( column == 1 ) {
lblDesc.setFont(CoeusFontFactory.getLabelFont());
//Added for case# 3148 - Inconsistent UI for custom element tabs
lblDesc.setHorizontalAlignment(SwingConstants.RIGHT);
}
if( value == null ){
lblDesc.setText( "" );
}else{
lblDesc.setText( value.toString() );
}
return lblDesc;
}
}
}
|
[
"[email protected]"
] | |
a06ca3eb4292ae03d703bd92f287b9df5c4d954f
|
01f5192febf4ffe1936f8a9642922db723a94b2e
|
/app/src/main/java/com/daviazevedodev/getninjaclone/model/Service.java
|
ccae2c8fd06494ed38254159d7042a0103ff18c7
|
[] |
no_license
|
daviaze/GetNinjaFeed
|
bfd37254021b698d1224708778e5691a27854b30
|
923ccfb6397cc52b7aeed9045828227eb67ef3f7
|
refs/heads/master
| 2022-12-23T21:47:49.799610 | 2020-10-07T19:17:17 | 2020-10-07T19:17:17 | 302,133,632 | 0 | 1 | null | null | null | null |
UTF-8
|
Java
| false | false | 1,599 |
java
|
package com.daviazevedodev.getninjaclone.model;
public class Service {
private String nameService;
private String namePerson;
private String status;
public String getNameService() {
return nameService;
}
public void setNameService(String nameService) {
this.nameService = nameService;
}
public String getNamePerson() {
return namePerson;
}
public void setNamePerson(String namePerson) {
this.namePerson = namePerson;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public static class ServiceBuilder {
private String nameService;
private String namePerson;
private String status;
public ServiceBuilder setNameService(String nameService) {
this.nameService = nameService;
return this;
}
public ServiceBuilder setNamePerson(String namePerson) {
this.namePerson = namePerson;
return this;
}
public ServiceBuilder setStatus(String status) {
this.status = status;
return this;
}
private ServiceBuilder() {}
public static ServiceBuilder builder(){
return new ServiceBuilder();
}
public Service build() {
Service service = new Service();
service.namePerson = namePerson;
service.nameService = nameService;
service.status = status;
return service;
}
}
}
|
[
"[email protected]"
] | |
df5beb4dc4d2d73a6213c43a1682712272c0d3c6
|
9a3b734d08f934f55d084b398bf326c137b62695
|
/formyournotes-parent/formyournotes-android-commons/src/main/java/at/ahammer/formyournotes/security/MD5Helper.java
|
ce8b601853dd62f7a9ec454cd14ed0b79b945f2a
|
[] |
no_license
|
andi-git/formyournotes
|
18df4f99730c0f417b883a6680d2affa79b6c834
|
d0493b492af67f5b13f21c68b835c3cd2145b200
|
refs/heads/master
| 2020-05-17T18:31:13.122591 | 2013-06-19T20:49:40 | 2013-06-19T20:49:40 | 32,631,630 | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 642 |
java
|
package at.ahammer.formyournotes.security;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class MD5Helper {
public String generateHash(String passwordPlain) {
MessageDigest md5 = null;
try {
md5 = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
md5.reset();
md5.update(passwordPlain.getBytes());
byte[] result = md5.digest();
StringBuffer hexString = new StringBuffer();
for (int i = 0; i < result.length; i++) {
hexString.append(Integer.toHexString(0xFF & result[i]));
}
return hexString.toString();
}
}
|
[
"[email protected]"
] | |
15af0367383d834661ea50caf1cef72b103452c5
|
23139ddc2168d87bc09b2206c942ebb87c451cb9
|
/src/Tree_Questions/Size_Of_Tree.java
|
ce1f9ed491cdcee97d79f38ad4c14d3b356f38d1
|
[] |
no_license
|
dhananjayandayalan/Geekster-Works
|
a3282bade335003aeb840f8e85bcb1b1562c8e45
|
fd2d8ad842dc35e11874d6cfc406af84291547cb
|
refs/heads/master
| 2023-06-16T17:24:44.697739 | 2021-06-30T09:13:58 | 2021-06-30T09:13:58 | 354,461,890 | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 1,061 |
java
|
package Tree_Questions;
public class Size_Of_Tree {
public static void main(String[] args) {
TreeNode root = new TreeNode(50);
Tree_Functions.add(new TreeNode(25), 50, root, 'L');
Tree_Functions.add(new TreeNode(75), 50, root, 'R');
Tree_Functions.add(new TreeNode(12), 25, root, 'L');
Tree_Functions.add(new TreeNode(37), 25, root, 'R');
Tree_Functions.add(new TreeNode(30), 37, root, 'L');
Tree_Functions.add(new TreeNode(40), 37, root, 'R');
Tree_Functions.add(new TreeNode(62), 75, root, 'L');
Tree_Functions.add(new TreeNode(87), 75, root, 'R');
Tree_Functions.add(new TreeNode(60), 62, root, 'L');
Tree_Functions.add(new TreeNode(70), 62, root, 'R');
System.out.println(solve(root));
Tree_Functions.display(root);
}
private static int solve(TreeNode root) {
if(root == null) {
return 0;
}
int left = solve(root.left);
int right = solve(root.right);
return left + right + 1;
}
}
|
[
"[email protected]"
] | |
ba9d44f16cf3b91f77c9c09ca19d067668d0288c
|
a5f06feb050fc0daeab331aa1eeda94069c1492c
|
/src/main/java/org/apache/ibatis/io/DefaultVFS.java
|
fec3fe6562cdaabe3d1492659767c2cd47d81016
|
[
"Apache-2.0",
"BSD-3-Clause"
] |
permissive
|
aiguoxin/mybatis-3-study
|
d8e6cb16e860f8c064bb9a82e8d295c8348f8f41
|
79128bab36613883777875546239b1d892bc84d3
|
refs/heads/master
| 2023-02-16T19:36:14.954704 | 2023-02-06T13:54:40 | 2023-02-06T13:54:40 | 221,410,454 | 0 | 0 |
Apache-2.0
| 2022-09-08T01:04:01 | 2019-11-13T08:33:13 |
Java
|
UTF-8
|
Java
| false | false | 11,503 |
java
|
/**
* Copyright 2009-2019 the original author or authors.
*
* 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.apache.ibatis.io;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.jar.JarEntry;
import java.util.jar.JarInputStream;
import org.apache.ibatis.logging.Log;
import org.apache.ibatis.logging.LogFactory;
/**
* A default implementation of {@link VFS} that works for most application servers.
*
* @author Ben Gunter
*/
public class DefaultVFS extends VFS {
private static final Log log = LogFactory.getLog(DefaultVFS.class);
/** The magic header that indicates a JAR (ZIP) file. */
private static final byte[] JAR_MAGIC = { 'P', 'K', 3, 4 };
@Override
public boolean isValid() {
return true;
}
@Override
public List<String> list(URL url, String path) throws IOException {
InputStream is = null;
try {
List<String> resources = new ArrayList<>();
// First, try to find the URL of a JAR file containing the requested resource. If a JAR
// file is found, then we'll list child resources by reading the JAR.
URL jarUrl = findJarForResource(url);
if (jarUrl != null) {
is = jarUrl.openStream();
if (log.isDebugEnabled()) {
log.debug("Listing " + url);
}
resources = listResources(new JarInputStream(is), path);
}
else {
List<String> children = new ArrayList<>();
try {
if (isJar(url)) {
// Some versions of JBoss VFS might give a JAR stream even if the resource
// referenced by the URL isn't actually a JAR
is = url.openStream();
try (JarInputStream jarInput = new JarInputStream(is)) {
if (log.isDebugEnabled()) {
log.debug("Listing " + url);
}
for (JarEntry entry; (entry = jarInput.getNextJarEntry()) != null; ) {
if (log.isDebugEnabled()) {
log.debug("Jar entry: " + entry.getName());
}
children.add(entry.getName());
}
}
}
else {
/*
* Some servlet containers allow reading from directory resources like a
* text file, listing the child resources one per line. However, there is no
* way to differentiate between directory and file resources just by reading
* them. To work around that, as each line is read, try to look it up via
* the class loader as a child of the current resource. If any line fails
* then we assume the current resource is not a directory.
*/
is = url.openStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
List<String> lines = new ArrayList<>();
for (String line; (line = reader.readLine()) != null;) {
if (log.isDebugEnabled()) {
log.debug("Reader entry: " + line);
}
lines.add(line);
if (getResources(path + "/" + line).isEmpty()) {
lines.clear();
break;
}
}
if (!lines.isEmpty()) {
if (log.isDebugEnabled()) {
log.debug("Listing " + url);
}
children.addAll(lines);
}
}
} catch (FileNotFoundException e) {
/*
* For file URLs the openStream() call might fail, depending on the servlet
* container, because directories can't be opened for reading. If that happens,
* then list the directory directly instead.
*/
if ("file".equals(url.getProtocol())) {
File file = new File(url.getFile());
if (log.isDebugEnabled()) {
log.debug("Listing directory " + file.getAbsolutePath());
}
if (file.isDirectory()) {
if (log.isDebugEnabled()) {
log.debug("Listing " + url);
}
children = Arrays.asList(file.list());
}
}
else {
// No idea where the exception came from so rethrow it
throw e;
}
}
// The URL prefix to use when recursively listing child resources
String prefix = url.toExternalForm();
if (!prefix.endsWith("/")) {
prefix = prefix + "/";
}
// Iterate over immediate children, adding files and recursing into directories
for (String child : children) {
String resourcePath = path + "/" + child;
resources.add(resourcePath);
URL childUrl = new URL(prefix + child);
resources.addAll(list(childUrl, resourcePath));
}
}
return resources;
} finally {
if (is != null) {
try {
is.close();
} catch (Exception e) {
// Ignore
}
}
}
}
/**
* List the names of the entries in the given {@link JarInputStream} that begin with the
* specified {@code path}. Entries will match with or without a leading slash.
*
* @param jar The JAR input stream
* @param path The leading path to match
* @return The names of all the matching entries
* @throws IOException If I/O errors occur
*/
protected List<String> listResources(JarInputStream jar, String path) throws IOException {
// Include the leading and trailing slash when matching names
if (!path.startsWith("/")) {
path = "/" + path;
}
if (!path.endsWith("/")) {
path = path + "/";
}
// Iterate over the entries and collect those that begin with the requested path
List<String> resources = new ArrayList<>();
for (JarEntry entry; (entry = jar.getNextJarEntry()) != null;) {
if (!entry.isDirectory()) {
// Add leading slash if it's missing
String name = entry.getName();
if (!name.startsWith("/")) {
name = "/" + name;
}
// Check file name
if (name.startsWith(path)) {
if (log.isDebugEnabled()) {
log.debug("Found resource: " + name);
}
// Trim leading slash
resources.add(name.substring(1));
}
}
}
return resources;
}
/**
* Attempts to deconstruct the given URL to find a JAR file containing the resource referenced
* by the URL. That is, assuming the URL references a JAR entry, this method will return a URL
* that references the JAR file containing the entry. If the JAR cannot be located, then this
* method returns null.
*
* @param url The URL of the JAR entry.
* @return The URL of the JAR file, if one is found. Null if not.
* @throws MalformedURLException
*/
protected URL findJarForResource(URL url) throws MalformedURLException {
if (log.isDebugEnabled()) {
log.debug("Find JAR URL: " + url);
}
// If the file part of the URL is itself a URL, then that URL probably points to the JAR
try {
for (;;) {
url = new URL(url.getFile());
if (log.isDebugEnabled()) {
log.debug("Inner URL: " + url);
}
}
} catch (MalformedURLException e) {
// This will happen at some point and serves as a break in the loop
}
// Look for the .jar extension and chop off everything after that
StringBuilder jarUrl = new StringBuilder(url.toExternalForm());
int index = jarUrl.lastIndexOf(".jar");
if (index >= 0) {
jarUrl.setLength(index + 4);
if (log.isDebugEnabled()) {
log.debug("Extracted JAR URL: " + jarUrl);
}
}
else {
if (log.isDebugEnabled()) {
log.debug("Not a JAR: " + jarUrl);
}
return null;
}
// Try to open and test it
try {
URL testUrl = new URL(jarUrl.toString());
if (isJar(testUrl)) {
return testUrl;
}
else {
// WebLogic fix: check if the URL's file exists in the filesystem.
if (log.isDebugEnabled()) {
log.debug("Not a JAR: " + jarUrl);
}
jarUrl.replace(0, jarUrl.length(), testUrl.getFile());
File file = new File(jarUrl.toString());
// File name might be URL-encoded
if (!file.exists()) {
try {
file = new File(URLEncoder.encode(jarUrl.toString(), "UTF-8"));
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("Unsupported encoding? UTF-8? That's unpossible.");
}
}
if (file.exists()) {
if (log.isDebugEnabled()) {
log.debug("Trying real file: " + file.getAbsolutePath());
}
testUrl = file.toURI().toURL();
if (isJar(testUrl)) {
return testUrl;
}
}
}
} catch (MalformedURLException e) {
log.warn("Invalid JAR URL: " + jarUrl);
}
if (log.isDebugEnabled()) {
log.debug("Not a JAR: " + jarUrl);
}
return null;
}
/**
* Converts a Java package name to a path that can be looked up with a call to
* {@link ClassLoader#getResources(String)}.
*
* @param packageName The Java package name to convert to a path
*/
protected String getPackagePath(String packageName) {
return packageName == null ? null : packageName.replace('.', '/');
}
/**
* Returns true if the resource located at the given URL is a JAR file.
*
* @param url The URL of the resource to test.
*/
protected boolean isJar(URL url) {
return isJar(url, new byte[JAR_MAGIC.length]);
}
/**
* Returns true if the resource located at the given URL is a JAR file.
*
* @param url The URL of the resource to test.
* @param buffer A buffer into which the first few bytes of the resource are read. The buffer
* must be at least the size of {@link #JAR_MAGIC}. (The same buffer may be reused
* for multiple calls as an optimization.)
*/
protected boolean isJar(URL url, byte[] buffer) {
InputStream is = null;
try {
is = url.openStream();
is.read(buffer, 0, JAR_MAGIC.length);
if (Arrays.equals(buffer, JAR_MAGIC)) {
if (log.isDebugEnabled()) {
log.debug("Found JAR: " + url);
}
return true;
}
} catch (Exception e) {
// Failure to read the stream means this is not a JAR
} finally {
if (is != null) {
try {
is.close();
} catch (Exception e) {
// Ignore
}
}
}
return false;
}
}
|
[
"[email protected]"
] | |
fe99eca32f1ddcf817d09129060442c5dacf5147
|
e856f7626533230de6ed43b149ad969986799734
|
/src/main/java/a_theory/question5/ApplicationLayers.java
|
081ff3e9ff9db0dea6cbd51108bf1fe43eb0c155
|
[] |
no_license
|
rokopp/autoBackEnd
|
6a84b90d5e07353a366831b6e4c0549b67e67312
|
5635f68db67fd2623c14e244751f5beecc9f8647
|
refs/heads/master
| 2023-04-08T13:07:17.757977 | 2021-01-12T14:12:33 | 2021-01-12T14:12:33 | 357,143,092 | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 1,369 |
java
|
package a_theory.question5;
public class ApplicationLayers {
//todo
// Architects insist on having layered architecture in the back-end... ¯\_(ツ)_/¯
//todo p1
// Name 3 layers of back-end architecture. Give a brief description for each.
// 1 Application layer
// Description: Provides services to the software through which the user requests network services.
// 2 Domain layer
// Description: Interacts with the Data and Presentation layer using interfaces and interactors
// 3 Data access layer
// Description: Provides a simple interface that allows an application to access a persistent data store.
//todo p2
// Do you agree with the architects? Why?
// Yes
// Because: Easier to read. Makes more structured which helps with readability.
//todo p3
// We use objects to transport data between different layers.
// What is the difference between Entity and Dto? What is same between them?
// Answer: Entities should encapsulate their state, which is why they say getter/setters are evil,
// since they break encapsulation. DTOs allow Entities to export data based on their internal state.
// DTOs are pure data structures, just getters/setters, and encapsulate nothing.
// source: https://www.reddit.com/r/java/comments/6ph54x/entities_or_dtos_when_should_you_use_which/
}
|
[
"[email protected]"
] | |
f57e436b00140a3ffe79779243c51a0b5cd8f6c2
|
15c549b7909d5971cf3f7dc932f41bb9ac478836
|
/read-service/src/main/java/io/github/nikodc/services/read/HystrixStorageServiceInvoker.java
|
286fe1bac0689ed2cca3a7d64e05a194a4dceaea
|
[] |
no_license
|
nikodc/spring-cloud-playground
|
408d8a79354ebcfa469118429e9116581c52aa92
|
d2c7231ea21fc1c96bc93e6c0c94793f4c30a3e4
|
refs/heads/master
| 2020-12-25T10:59:39.962907 | 2016-07-24T00:01:06 | 2016-07-24T00:01:06 | 63,658,489 | 1 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 1,990 |
java
|
package io.github.nikodc.services.read;
import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandGroupKey;
import com.netflix.hystrix.HystrixCommandKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.consul.ConditionalOnConsulEnabled;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;
@Primary
@Component
@ConditionalOnConsulEnabled
public class HystrixStorageServiceInvoker implements StorageServiceInvoker {
private static final Logger log = LoggerFactory.getLogger(HystrixStorageServiceInvoker.class);
@Autowired
DirectStorageServiceInvoker directStorageServiceInvoker;
@Value("${application.hystrixCommandName}")
private String hystrixCommandName;
@Override
public StorageServiceResponse getItems(String db) {
return new StorageServiceCommand(db).execute();
}
private String getConcreteHystrixCommandName(String db) {
try {
return String.format(hystrixCommandName, db);
} catch (Exception e) {
log.error("Exception getting concrete hystrix command name, hystrixCommandName: {}, db: {}",
hystrixCommandName, db);
throw new RuntimeException(e);
}
}
public class StorageServiceCommand extends HystrixCommand<StorageServiceResponse> {
private final String db;
public StorageServiceCommand(String db) {
super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("PlaygroundGroup"))
.andCommandKey(HystrixCommandKey.Factory.asKey(getConcreteHystrixCommandName(db))));
this.db = db;
}
@Override
protected StorageServiceResponse run() {
return directStorageServiceInvoker.getItems(db);
}
}
}
|
[
"[email protected]"
] | |
34fd354f687aafb05c20cdb6aa97d4631685485d
|
78986a58001ce6ca197212a98d8f0fca3136e9ed
|
/src/main/java/reconf/server/repository/UserProductRepository.java
|
f79842ca4d5e519bb38d184c92ea39dac8e71aed
|
[
"Apache-2.0"
] |
permissive
|
MensMarket/reconf-server
|
3bf79a45fffa64ffdc8dbabb0eee5263354fd4b4
|
8e256c14b1feed07d47f05577714b94cb71bd8c3
|
refs/heads/master
| 2021-01-10T16:20:44.247129 | 2016-03-22T14:55:19 | 2016-03-22T14:55:19 | 54,481,851 | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 1,065 |
java
|
/*
* Copyright 2013-2014 ReConf Team
*
* 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 reconf.server.repository;
import java.util.*;
import org.springframework.data.repository.*;
import reconf.server.domain.security.*;
public interface UserProductRepository extends CrudRepository<UserProduct, UserProductKey> {
void deleteByKeyProduct(String product);
void deleteByKeyUsername(String username);
List<UserProduct> findByKeyProduct(String product);
List<UserProduct> findByKeyUsername(String username);
}
|
[
"[email protected]"
] | |
45188531920b0c115cf2f35473861fbaef01dab4
|
9e0b84d33065a7a132cc63280af14a695477b7d3
|
/library/src/main/java/com/huangstudio/liteui/ldialog/ProgressHelper.java
|
cc9c6f0627c52cf5826c1a575e8bb34ea9142879
|
[
"Apache-2.0"
] |
permissive
|
fghjhuang/LiteUI_android
|
9a7b2a86f60de9b77cd2f3cb96f9b4cea35044e9
|
2572898957946f925e64eb435c58fbfd3a288363
|
refs/heads/master
| 2020-06-07T13:53:26.720005 | 2019-08-19T09:29:48 | 2019-08-19T09:29:48 | 193,036,692 | 2 | 1 | null | null | null | null |
UTF-8
|
Java
| false | false | 4,513 |
java
|
package com.huangstudio.liteui.ldialog;
import android.content.Context;
import com.huangstudio.liteui.R;
public class ProgressHelper {
private ProgressWheel mProgressWheel;
private boolean mToSpin;
private float mSpinSpeed;
private int mBarWidth;
private int mBarColor;
private int mRimWidth;
private int mRimColor;
private boolean mIsInstantProgress;
private float mProgressVal;
private int mCircleRadius;
public ProgressHelper(Context ctx) {
mToSpin = true;
mSpinSpeed = 0.75f;
mBarWidth = ctx.getResources().getDimensionPixelSize(R.dimen.alert_dialog_common_circle_width) + 1;
mBarColor = ctx.getResources().getColor(R.color.alert_dialog_success_stroke_color);
mRimWidth = 0;
mRimColor = 0x00000000;
mIsInstantProgress = false;
mProgressVal = -1;
mCircleRadius = ctx.getResources().getDimensionPixelOffset(R.dimen.alert_dialog_progress_circle_radius);
}
public ProgressWheel getProgressWheel () {
return mProgressWheel;
}
public void setProgressWheel (ProgressWheel progressWheel) {
mProgressWheel = progressWheel;
updatePropsIfNeed();
}
private void updatePropsIfNeed () {
if (mProgressWheel != null) {
if (!mToSpin && mProgressWheel.isSpinning()) {
mProgressWheel.stopSpinning();
} else if (mToSpin && !mProgressWheel.isSpinning()) {
mProgressWheel.spin();
}
if (mSpinSpeed != mProgressWheel.getSpinSpeed()) {
mProgressWheel.setSpinSpeed(mSpinSpeed);
}
if (mBarWidth != mProgressWheel.getBarWidth()) {
mProgressWheel.setBarWidth(mBarWidth);
}
if (mBarColor != mProgressWheel.getBarColor()) {
mProgressWheel.setBarColor(mBarColor);
}
if (mRimWidth != mProgressWheel.getRimWidth()) {
mProgressWheel.setRimWidth(mRimWidth);
}
if (mRimColor != mProgressWheel.getRimColor()) {
mProgressWheel.setRimColor(mRimColor);
}
if (mProgressVal != mProgressWheel.getProgress()) {
if (mIsInstantProgress) {
mProgressWheel.setInstantProgress(mProgressVal);
} else {
mProgressWheel.setProgress(mProgressVal);
}
}
if (mCircleRadius != mProgressWheel.getCircleRadius()) {
mProgressWheel.setCircleRadius(mCircleRadius);
}
}
}
public void resetCount() {
if (mProgressWheel != null) {
mProgressWheel.resetCount();
}
}
public boolean isSpinning() {
return mToSpin;
}
public void spin() {
mToSpin = true;
updatePropsIfNeed();
}
public void stopSpinning() {
mToSpin = false;
updatePropsIfNeed();
}
public float getProgress() {
return mProgressVal;
}
public void setProgress(float progress) {
mIsInstantProgress = false;
mProgressVal = progress;
updatePropsIfNeed();
}
public void setInstantProgress(float progress) {
mProgressVal = progress;
mIsInstantProgress = true;
updatePropsIfNeed();
}
public int getCircleRadius() {
return mCircleRadius;
}
/**
* @param circleRadius units using pixel
* **/
public void setCircleRadius(int circleRadius) {
mCircleRadius = circleRadius;
updatePropsIfNeed();
}
public int getBarWidth() {
return mBarWidth;
}
public void setBarWidth(int barWidth) {
mBarWidth = barWidth;
updatePropsIfNeed();
}
public int getBarColor() {
return mBarColor;
}
public void setBarColor(int barColor) {
mBarColor = barColor;
updatePropsIfNeed();
}
public int getRimWidth() {
return mRimWidth;
}
public void setRimWidth(int rimWidth) {
mRimWidth = rimWidth;
updatePropsIfNeed();
}
public int getRimColor() {
return mRimColor;
}
public void setRimColor(int rimColor) {
mRimColor = rimColor;
updatePropsIfNeed();
}
public float getSpinSpeed() {
return mSpinSpeed;
}
public void setSpinSpeed(float spinSpeed) {
mSpinSpeed = spinSpeed;
updatePropsIfNeed();
}
}
|
[
"[email protected]"
] | |
d20cb0975fb7d5214515577fcf6d87cdc90cbdfd
|
f42d7da85f9633cfb84371ae67f6d3469f80fdcb
|
/com4j-20120426-2/samples/excel/build/src/excel/IGridlines.java
|
b8fd61cc91e0877016dfba6cc6c5acc3094cfbce
|
[
"BSD-2-Clause"
] |
permissive
|
LoongYou/Wanda
|
ca89ac03cc179cf761f1286172d36ead41f036b5
|
2c2c4d1d14e95e98c0a3af365495ec53775cc36b
|
refs/heads/master
| 2023-03-14T13:14:38.476457 | 2021-03-06T10:20:37 | 2021-03-06T10:20:37 | 231,610,760 | 1 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 1,697 |
java
|
package excel ;
import com4j.*;
@IID("{000208C3-0001-0000-C000-000000000046}")
public interface IGridlines extends Com4jObject {
// Methods:
/**
* <p>
* Getter method for the COM property "Application"
* </p>
* @return Returns a value of type excel._Application
*/
@VTID(7)
excel._Application getApplication();
/**
* <p>
* Getter method for the COM property "Creator"
* </p>
* @return Returns a value of type excel.XlCreator
*/
@VTID(8)
excel.XlCreator getCreator();
/**
* <p>
* Getter method for the COM property "Parent"
* </p>
* @return Returns a value of type com4j.Com4jObject
*/
@VTID(9)
@ReturnValue(type=NativeType.Dispatch)
com4j.Com4jObject getParent();
/**
* <p>
* Getter method for the COM property "Name"
* </p>
* @return Returns a value of type java.lang.String
*/
@VTID(10)
java.lang.String getName();
/**
* @return Returns a value of type java.lang.Object
*/
@VTID(11)
@ReturnValue(type=NativeType.VARIANT)
java.lang.Object select();
/**
* <p>
* Getter method for the COM property "Border"
* </p>
* @return Returns a value of type excel.Border
*/
@VTID(12)
excel.Border getBorder();
/**
* @return Returns a value of type java.lang.Object
*/
@VTID(13)
@ReturnValue(type=NativeType.VARIANT)
java.lang.Object delete();
/**
* <p>
* Getter method for the COM property "Format"
* </p>
* @return Returns a value of type excel.ChartFormat
*/
@VTID(14)
excel.ChartFormat getFormat();
// Properties:
}
|
[
"[email protected]"
] | |
d8415e34f85550de384a38fae58ed8d4b617d91a
|
c3445da9eff3501684f1e22dd8709d01ff414a15
|
/LIS/sinosoft-parents/lis-business/src/main/java/com/sinosoft/lis/tbgrp/GroupContUI.java
|
6c2ca3c2f05e5ca7ccc5de0991bca2403ac4b46c
|
[] |
no_license
|
zhanght86/HSBC20171018
|
954403d25d24854dd426fa9224dfb578567ac212
|
c1095c58c0bdfa9d79668db9be4a250dd3f418c5
|
refs/heads/master
| 2021-05-07T03:30:31.905582 | 2017-11-08T08:54:46 | 2017-11-08T08:54:46 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 3,751 |
java
|
package com.sinosoft.lis.tbgrp;
import org.apache.log4j.Logger;
import com.sinosoft.lis.db.LCGrpAddressDB;
import com.sinosoft.lis.db.LCGrpAppntDB;
import com.sinosoft.lis.db.LCGrpContDB;
import com.sinosoft.lis.db.LDGrpDB;
import com.sinosoft.lis.pubfun.GlobalInput;
import com.sinosoft.lis.schema.LCGrpAddressSchema;
import com.sinosoft.lis.schema.LCGrpAppntSchema;
import com.sinosoft.lis.schema.LCGrpContSchema;
import com.sinosoft.lis.schema.LDGrpSchema;
import com.sinosoft.utility.CErrors;
import com.sinosoft.utility.TransferData;
import com.sinosoft.utility.VData;
import com.sinosoft.service.BusinessService;
/**
* <p>
* Title:团单保存(IUD)UI层
* </p>
* <p>
* Description:
* </p>
* <p>
* Copyright: Copyright (c) 2004
* </p>
* <p>
* Company:
* </p>
*
* @author wzw
* @version 1.0
*/
public class GroupContUI implements BusinessService{
private static Logger logger = Logger.getLogger(GroupContUI.class);
/** 传入数据的容器 */
private VData mInputData = new VData();
/** 往前面传输数据的容器 */
private VData mResult = new VData();
/** 数据操作字符串 */
private String mOperate;
/** 错误处理类 */
public CErrors mErrors = new CErrors();
public GroupContUI() {
}
/**
* 不执行任何操作,只传递数据给下一层
*
* @param cInputData
* VData
* @param cOperate
* String
* @return boolean
*/
public boolean submitData(VData cInputData, String cOperate) {
// 数据操作字符串拷贝到本类中
this.mOperate = cOperate;
GroupContBL tGroupContBL = new GroupContBL();
if (tGroupContBL.submitData(cInputData, mOperate) == false) {
// @@错误处理
this.mErrors.copyAllErrors(tGroupContBL.mErrors);
return false;
} else {
mResult = tGroupContBL.getResult();
}
return true;
}
/**
* 获取从BL层取得的结果
*
* @return VData
*/
public VData getResult() {
return mResult;
}
public static void main(String agrs[]) {
LCGrpContSchema tLCGrpContSchema = new LCGrpContSchema(); // 集体保单
LCGrpAppntSchema tLCGrpAppntSchema = new LCGrpAppntSchema(); // 团单投保人
LDGrpSchema tLDGrpSchema = new LDGrpSchema(); // 团体客户
LCGrpAddressSchema tLCGrpAddressSchema = new LCGrpAddressSchema(); // 团体客户地址
LCGrpContDB tLCGrpContDB = new LCGrpContDB(); // 集体保单
LCGrpAppntDB tLCGrpAppntDB = new LCGrpAppntDB(); // 团单投保人
LDGrpDB tLDGrpDB = new LDGrpDB(); // 团体客户
LCGrpAddressDB tLCGrpAddressDB = new LCGrpAddressDB(); // 团体客户地址
GlobalInput mGlobalInput = new GlobalInput();
TransferData tTransferData = new TransferData();
mGlobalInput.ManageCom = "86";
mGlobalInput.Operator = "001";
tLCGrpContDB.setGrpContNo("120110000000064");
tLCGrpContDB.getInfo();
tLCGrpAppntDB.setGrpContNo("120110000000064");
tLCGrpAppntDB.setCustomerNo("0000001660");
tLCGrpAppntDB.getInfo();
tLDGrpDB.setCustomerNo("0000001660");
tLDGrpDB.getInfo();
tLCGrpAddressDB.setAddressNo("86110000000169");
tLCGrpAddressDB.setCustomerNo("0000001660");
tLCGrpAddressDB.getInfo();
tLCGrpAppntDB
.setAddressNo("00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000");
VData tVData = new VData();
tVData.add(tLCGrpContDB.getSchema());
tVData.add(tLCGrpAppntDB.getSchema());
tVData.add(tLDGrpDB.getSchema());
tVData.add(tLCGrpAddressDB.getSchema());
tVData.add(mGlobalInput);
GroupContBL tgrlbl = new GroupContBL();
tgrlbl.submitData(tVData, "UPDATE||GROUPPOL");
if (tgrlbl.mErrors.needDealError()) {
logger.debug(tgrlbl.mErrors.getFirstError());
}
}
public CErrors getErrors() {
// TODO Auto-generated method stub
return mErrors;
}
}
|
[
"[email protected]"
] | |
1a84c95508a6b3f1772bce3f37f7016c3c2e3272
|
39b7e86a2b5a61a1f7befb47653f63f72e9e4092
|
/src/main/java/com/alipay/api/domain/FundBillListEco.java
|
15325e03206fa3aad0b8ad344b9a7b3009ffb553
|
[
"Apache-2.0"
] |
permissive
|
slin1972/alipay-sdk-java-all
|
dbec0604c2d0b76d8a1ebf3fd8b64d4dd5d21708
|
63095792e900bbcc0e974fc242d69231ec73689a
|
refs/heads/master
| 2020-08-12T14:18:07.203276 | 2019-10-13T09:00:11 | 2019-10-13T09:00:11 | 214,782,009 | 0 | 0 |
Apache-2.0
| 2019-10-13T07:56:34 | 2019-10-13T07:56:34 | null |
UTF-8
|
Java
| false | false | 976 |
java
|
package com.alipay.api.domain;
import com.alipay.api.AlipayObject;
import com.alipay.api.internal.mapping.ApiField;
/**
* 交易支付的渠道属性
*
* @author auto create
* @since 1.0, 2017-09-08 11:37:41
*/
public class FundBillListEco extends AlipayObject {
private static final long serialVersionUID = 5218252184642853281L;
/**
* 该支付工具类型所使用的金额
*/
@ApiField("amount")
private String amount;
/**
* 交易使用的资金渠道,详见 <a href="https://doc.open.alipay.com/doc2/detail?treeId=26&articleId=103259&docType=1">支付渠道列表</a>
*/
@ApiField("fund_channel")
private String fundChannel;
public String getAmount() {
return this.amount;
}
public void setAmount(String amount) {
this.amount = amount;
}
public String getFundChannel() {
return this.fundChannel;
}
public void setFundChannel(String fundChannel) {
this.fundChannel = fundChannel;
}
}
|
[
"[email protected]"
] | |
306de5c0bea1a52631dd4d0c72b1b2f6494b51fe
|
c381be3b9dcd330593cd447eedd67dd539a433aa
|
/2013-OOProgrammingWithJava-PART1/week2-028.FromHundredToOne/src/FromHundredToOne.java
|
c3e38295cb30969d640b9d21a0e2c4fcaa831b9c
|
[] |
no_license
|
angiepammy/JAVA-MOOC-HELSINKI-UNI
|
9c1fa261616e45c8275d338c2db32db0f5d0d648
|
35d6d984ad3b6f2f42cad26b7607eeda068f75f4
|
refs/heads/master
| 2021-01-21T10:42:16.720366 | 2016-08-25T21:50:40 | 2016-08-25T21:50:40 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 242 |
java
|
public class FromHundredToOne {
public static void main(String[] args) {
// Write your program here
int i = 100;
while(i>0){
System.out.println(i);
--i;
}
}
}
|
[
"[email protected]"
] | |
d3997acb94f44fc1d6846ee0f54021956e988109
|
a07839877e84db55274da286bef17ae41dd096f1
|
/app/src/main/java/com/example/uidesign/TravelLoacationAdapter.java
|
df7b49d2129b5116c129df6eea91cd95eaa78039
|
[] |
no_license
|
Karan-Bathani/UI-Design
|
ffb8df0e9cad596e16494616d9d500d2e5a48b64
|
cac67eeff72c497c01f02759c76fed9dd168cbd3
|
refs/heads/main
| 2023-04-25T06:39:33.679100 | 2021-05-06T11:18:57 | 2021-05-06T11:18:57 | 364,879,566 | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 2,168 |
java
|
package com.example.uidesign;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.flaviofaria.kenburnsview.KenBurnsView;
import java.util.List;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
public class TravelLoacationAdapter extends RecyclerView.Adapter<TravelLoacationAdapter.TravelLocationViewHolder> {
private List<TravelLocation> travelLocations;
public TravelLoacationAdapter(List<TravelLocation> travelLocations) {
this.travelLocations = travelLocations;
}
@NonNull
@Override
public TravelLocationViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
return new TravelLocationViewHolder(
LayoutInflater.from(parent.getContext()).inflate(
R.layout.item_container_location,
parent,
false
)
);
}
@Override
public void onBindViewHolder(@NonNull TravelLocationViewHolder holder, int position) {
holder.setLocationData(travelLocations.get(position));
}
@Override
public int getItemCount() {
return travelLocations.size();
}
static class TravelLocationViewHolder extends RecyclerView.ViewHolder{
private KenBurnsView kbvLocation;
private TextView textTitle, textLocation, textStarRating;
TravelLocationViewHolder(@NonNull View itemView) {
super(itemView);
kbvLocation = itemView.findViewById(R.id.kbvLocation);
textTitle = itemView.findViewById(R.id.textTitle);
textLocation = itemView.findViewById(R.id.textLocation);
textStarRating = itemView.findViewById(R.id.textStarRating);
}
void setLocationData(TravelLocation travelLocation) {
kbvLocation.setImageResource(travelLocation.image);
textTitle.setText(travelLocation.title);
textLocation.setText(travelLocation.location);
textStarRating.setText(String.valueOf(travelLocation.starRating));
}
}
}
|
[
"[email protected]"
] | |
035a2bfe31ec16d2ec4a4fa3b57b2c0d63bfcc9b
|
78f1dd1c38bc491345b5515776298a03a844e7eb
|
/AndroidClient/app/src/main/java/acoustically/pessenger/sign/SignUpActivity.java
|
53542e2d79e9be5d738966df003459daf714c43f
|
[] |
no_license
|
acoustically/PessengerAndroidClient
|
08324ac07f5da7da1033410cd61d875bac3d3b7e
|
61df623736af2eeda220c9ec737fe587579408ef
|
refs/heads/master
| 2021-01-01T19:37:31.691808 | 2017-11-01T14:42:55 | 2017-11-01T14:42:55 | 98,631,699 | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 2,561 |
java
|
package acoustically.pessenger.sign;
import android.app.Activity;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import org.json.JSONException;
import org.json.JSONObject;
import AndroidHttpRequest.HttpRequestor;
import AndroidHttpRequest.HttpRequestorBuilder;
import AndroidHttpRequest.HttpResponseListener;
import acoustically.pessenger.tools.Environment;
import acoustically.pessenger.MainActivity;
import acoustically.pessenger.R;
public class SignUpActivity extends AppCompatActivity {
Activity activity = this;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_up);
}
public void signUpClick(View view) {
EditText passwordBox = (EditText)findViewById(R.id.password);
String password = passwordBox.getText().toString();
String phoneNumber = Environment.getPhoneNumber(this);
signUp(phoneNumber, password);
}
private JSONObject buildJson(String phoneNumber, String password) throws JSONException{
JSONObject json = new JSONObject();
json.put("phone_number", phoneNumber);
json.put("password", password);
return json;
}
private void signUp(String phone_number, String password) {
HttpRequestorBuilder builder = new HttpRequestorBuilder(Environment.getUrl("/user/new"));
HttpRequestor requestor = builder.build();
try {
Log.e("test", "test");
requestor.post(buildJson(phone_number, password), new HttpResponseListener() {
@Override
protected void httpResponse(String data) {
try {
JSONObject json = new JSONObject(data);
if(json.getString("response").equals("success")){
activity.startActivity(new Intent(activity, MainActivity.class));
activity.finish();
} else {
Toast.makeText(activity, "Server Error", Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
Log.e("Error", e.getMessage(), e.fillInStackTrace());
}
}
@Override
protected void httpExcepted(Exception e) {
Log.e("Error", e.getMessage(), e.fillInStackTrace());
Toast.makeText(activity, e.getMessage(), Toast.LENGTH_LONG).show();
}
});
} catch (JSONException e) {
Log.e("Error", e.getMessage(), e.fillInStackTrace());
}
}
}
|
[
"[email protected]"
] | |
bcfc8e9de69cbfc33fe8989cece40201c8921ab3
|
eb5af3e0f13a059749b179c988c4c2f5815feb0f
|
/cloud/auth/src/main/java/com/woniu/auth/mbg/Generator.java
|
5d63ed2c8f1407f8033c8bc7b4b3c7a85f06f792
|
[] |
no_license
|
xiakai007/wokniuxcode
|
ae686753da5ec3dd607b0246ec45fb11cf6b8968
|
d9918fb349bc982f0ee9d3ea3bf7537e11d062a2
|
refs/heads/master
| 2023-04-13T02:54:15.675440 | 2021-05-02T05:09:47 | 2021-05-02T05:09:47 | 363,570,147 | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 1,052 |
java
|
package com.woniu.auth.mbg;
import org.mybatis.generator.api.MyBatisGenerator;
import org.mybatis.generator.config.Configuration;
import org.mybatis.generator.config.xml.ConfigurationParser;
import org.mybatis.generator.internal.DefaultShellCallback;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
public class Generator {
public static void main(String[] args) throws Exception {
List<String> warnings=new ArrayList<String>();
boolean overwrite=true;
InputStream is = Generator.class.getResourceAsStream("/generatorConfig.xml");
ConfigurationParser cp = new ConfigurationParser(warnings);
Configuration config = cp.parseConfiguration(is);
is.close();
DefaultShellCallback callback = new DefaultShellCallback(overwrite);
MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
myBatisGenerator.generate(null);
for (String warning : warnings) {
System.out.println(warning);
}
}
}
|
[
"[email protected]"
] | |
f57822d1be6e14dcf8580285b3d05366c44b78a5
|
05a6128e36f2feb3bd0d8984883481501126b7ce
|
/test/AutoTraderFraudCalculator/CarListingsTest.java
|
d8b412423a2d1d0c0c78e8f7b91973d9bdda0489
|
[] |
no_license
|
sugataach/AutoTraderFraudDetector
|
61e666ff88cfa6aa2dc8eabe89a387ee3908342e
|
afc4151aba08bbdd7fa378773b82218887350a8b
|
refs/heads/master
| 2021-05-26T19:38:58.801183 | 2013-01-07T17:31:57 | 2013-01-07T17:31:57 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 2,191 |
java
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package AutoTraderFraudCalculator;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
/**
*
* @author
*/
public class CarListingsTest {
/**
* Provides test methods for class CarListings.
*/
public CarListingsTest() {
}
/**
* Initialize the test method for all the methods within the class Analysis.
*
* @throws Exception
*/
@BeforeClass
public static void setUpClass() throws Exception {
}
/**
* Finish up the test method for all methods within the class Analysis.
*
* @throws Exception
*/
@AfterClass
public static void tearDownClass() throws Exception {
}
/**
* Initialize methods.
*/
@Before
public void setUp() {
}
/**
* Finish up methods.
*/
@After
public void tearDown() {
}
/**
* Test of pushAdvertisement method, of class CarListings.
*/
@Test
public void testPushAdvertisement() {
System.out.println("Test case for pushAdvertisement");
Listing carAdvertisement = null;
CarListings instance = new CarListings();
instance.pushAdvertisement(carAdvertisement);
}
/**
* Test of getAdvertisement method, of class CarListings.
*/
@Test
public void testGetAdvertisement() {
System.out.println("Test case for getAdvertisement");
int index = 0;
CarListings instance = null;
try {
instance.getAdvertisement(index);
} catch (NullPointerException npe) {
return;
}
fail("Expected NullPointerException");
}
/**
* Test of getSize method, of class CarListings.
*/
@Test
public void testGetSize() {
System.out.println("Test case for getSize");
CarListings instance = new CarListings();
int expResult = 0;
int result = instance.getSize();
assertEquals(expResult, result);
}
}
|
[
"[email protected]"
] | |
96b98ef4a5383dd758e5b38993a1741a9d1fc752
|
28782b4bb020e0432261d835ac4e36597ca9502e
|
/flink-libraries/flink-state-processing-api/src/test/java/org/apache/flink/state/api/BootstrapTransformationTest.java
|
64994c471623a3a3e30c4645d6b0e9a6d032ed70
|
[
"EPL-1.0",
"Classpath-exception-2.0",
"CC0-1.0",
"BSD-3-Clause",
"LicenseRef-scancode-free-unknown",
"LicenseRef-scancode-jdom",
"CC-BY-3.0",
"LicenseRef-scancode-unknown-license-reference",
"Unlicense",
"BSD-2-Clause-Views",
"MPL-2.0",
"CC-PDDC",
"CC-BY-2.5",
"LicenseRef-scancode-proprietary-license",
"LGPL-2.1-only",
"LicenseRef-scancode-other-permissive",
"OFL-1.1",
"AGPL-3.0-only",
"LicenseRef-scancode-warranty-disclaimer",
"MIT-0",
"GCC-exception-3.1",
"MPL-2.0-no-copyleft-exception",
"CDDL-1.1",
"ISC",
"GPL-2.0-only",
"Apache-2.0",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause",
"CDDL-1.0",
"MIT"
] |
permissive
|
lijobs/flink
|
f50401b1f3686e1427493617980568341a52914f
|
c601cfd662c2839f8ebc81b80879ecce55a8cbaf
|
refs/heads/master
| 2020-06-23T09:18:04.598927 | 2019-07-22T05:42:40 | 2019-07-24T05:11:06 | 198,580,410 | 1 | 0 |
Apache-2.0
| 2019-07-24T07:18:38 | 2019-07-24T07:18:38 | null |
UTF-8
|
Java
| false | false | 5,819 |
java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.flink.state.api;
import org.apache.flink.api.common.ExecutionConfig;
import org.apache.flink.api.java.DataSet;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.api.java.operators.DataSource;
import org.apache.flink.api.java.operators.Operator;
import org.apache.flink.core.fs.Path;
import org.apache.flink.runtime.state.FunctionInitializationContext;
import org.apache.flink.runtime.state.FunctionSnapshotContext;
import org.apache.flink.runtime.state.memory.MemoryStateBackend;
import org.apache.flink.state.api.functions.BroadcastStateBootstrapFunction;
import org.apache.flink.state.api.functions.StateBootstrapFunction;
import org.apache.flink.state.api.output.TaggedOperatorSubtaskState;
import org.apache.flink.state.api.runtime.OperatorIDGenerator;
import org.apache.flink.test.util.AbstractTestBase;
import org.junit.Assert;
import org.junit.Test;
/**
* Tests for bootstrap transformations.
*/
public class BootstrapTransformationTest extends AbstractTestBase {
@Test
public void testBroadcastStateTransformationParallelism() {
ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
env.setParallelism(10);
DataSet<Integer> input = env.fromElements(0);
BootstrapTransformation<Integer> transformation = OperatorTransformation
.bootstrapWith(input)
.transform(new ExampleBroadcastStateBootstrapFunction());
int maxParallelism = transformation.getMaxParallelism(4);
DataSet<TaggedOperatorSubtaskState> result = transformation.writeOperatorSubtaskStates(
OperatorIDGenerator.fromUid("uid"),
new MemoryStateBackend(),
new Path(),
maxParallelism
);
Assert.assertEquals("Broadcast transformations should always be run at parallelism 1",
1,
getParallelism(result));
}
@Test
public void testDefaultParallelismRespectedWhenLessThanMaxParallelism() {
ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
env.setParallelism(4);
DataSource<Integer> input = env.fromElements(0);
BootstrapTransformation<Integer> transformation = OperatorTransformation
.bootstrapWith(input)
.transform(new ExampleStateBootstrapFunction());
int maxParallelism = transformation.getMaxParallelism(10);
DataSet<TaggedOperatorSubtaskState> result = transformation.writeOperatorSubtaskStates(
OperatorIDGenerator.fromUid("uid"),
new MemoryStateBackend(),
new Path(),
maxParallelism
);
Assert.assertEquals(
"The parallelism of a data set should not change when less than the max parallelism of the savepoint",
ExecutionConfig.PARALLELISM_DEFAULT,
getParallelism(result));
}
@Test
public void testMaxParallelismRespected() {
ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
env.setParallelism(10);
DataSource<Integer> input = env.fromElements(0);
BootstrapTransformation<Integer> transformation = OperatorTransformation
.bootstrapWith(input)
.transform(new ExampleStateBootstrapFunction());
int maxParallelism = transformation.getMaxParallelism(4);
DataSet<TaggedOperatorSubtaskState> result = transformation.writeOperatorSubtaskStates(
OperatorIDGenerator.fromUid("uid"),
new MemoryStateBackend(),
new Path(),
maxParallelism
);
Assert.assertEquals(
"The parallelism of a data set should be constrained my the savepoint max parallelism",
4,
getParallelism(result));
}
@Test
public void testOperatorSpecificMaxParallelismRespected() {
ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
env.setParallelism(4);
DataSource<Integer> input = env.fromElements(0);
BootstrapTransformation<Integer> transformation = OperatorTransformation
.bootstrapWith(input)
.setMaxParallelism(1)
.transform(new ExampleStateBootstrapFunction());
int maxParallelism = transformation.getMaxParallelism(4);
DataSet<TaggedOperatorSubtaskState> result = transformation.writeOperatorSubtaskStates(
OperatorIDGenerator.fromUid("uid"),
new MemoryStateBackend(),
new Path(),
maxParallelism
);
Assert.assertEquals("The parallelism of a data set should be constrained my the savepoint max parallelism", 1, getParallelism(result));
}
private static <T> int getParallelism(DataSet<T> dataSet) {
//All concrete implementations of DataSet are operators so this should always be safe.
return ((Operator) dataSet).getParallelism();
}
private static class ExampleBroadcastStateBootstrapFunction extends BroadcastStateBootstrapFunction<Integer> {
@Override
public void processElement(Integer value, Context ctx) throws Exception {
}
}
private static class ExampleStateBootstrapFunction extends StateBootstrapFunction<Integer> {
@Override
public void processElement(Integer value, Context ctx) throws Exception {
}
@Override
public void snapshotState(FunctionSnapshotContext context) throws Exception {
}
@Override
public void initializeState(FunctionInitializationContext context) throws Exception {
}
}
}
|
[
"[email protected]"
] | |
b796abf09b64b2aaa2477cd1ea6b42b60833e0f8
|
7cc39b1ee93832aed70e14224f8a3d991570cca6
|
/aws-java-sdk-kafka/src/main/java/com/amazonaws/services/kafka/model/transform/GetBootstrapBrokersResultJsonUnmarshaller.java
|
c3c662077028595fc3910edf7d449e708adc0673
|
[
"Apache-2.0"
] |
permissive
|
yijiangliu/aws-sdk-java
|
74e626e096fe4cee22291809576bb7dc70aef94d
|
b75779a2ab0fe14c91da1e54be25b770385affac
|
refs/heads/master
| 2022-12-17T10:24:59.549226 | 2020-08-19T23:46:40 | 2020-08-19T23:46:40 | 289,107,793 | 1 | 0 |
Apache-2.0
| 2020-08-20T20:49:17 | 2020-08-20T20:49:16 | null |
UTF-8
|
Java
| false | false | 3,179 |
java
|
/*
* Copyright 2015-2020 Amazon.com, Inc. or its affiliates. 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. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.amazonaws.services.kafka.model.transform;
import java.math.*;
import javax.annotation.Generated;
import com.amazonaws.services.kafka.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;
import com.fasterxml.jackson.core.JsonToken;
import static com.fasterxml.jackson.core.JsonToken.*;
/**
* GetBootstrapBrokersResult JSON Unmarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class GetBootstrapBrokersResultJsonUnmarshaller implements Unmarshaller<GetBootstrapBrokersResult, JsonUnmarshallerContext> {
public GetBootstrapBrokersResult unmarshall(JsonUnmarshallerContext context) throws Exception {
GetBootstrapBrokersResult getBootstrapBrokersResult = new GetBootstrapBrokersResult();
int originalDepth = context.getCurrentDepth();
String currentParentElement = context.getCurrentParentElement();
int targetDepth = originalDepth + 1;
JsonToken token = context.getCurrentToken();
if (token == null)
token = context.nextToken();
if (token == VALUE_NULL) {
return getBootstrapBrokersResult;
}
while (true) {
if (token == null)
break;
if (token == FIELD_NAME || token == START_OBJECT) {
if (context.testExpression("bootstrapBrokerString", targetDepth)) {
context.nextToken();
getBootstrapBrokersResult.setBootstrapBrokerString(context.getUnmarshaller(String.class).unmarshall(context));
}
if (context.testExpression("bootstrapBrokerStringTls", targetDepth)) {
context.nextToken();
getBootstrapBrokersResult.setBootstrapBrokerStringTls(context.getUnmarshaller(String.class).unmarshall(context));
}
} else if (token == END_ARRAY || token == END_OBJECT) {
if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) {
if (context.getCurrentDepth() <= originalDepth)
break;
}
}
token = context.nextToken();
}
return getBootstrapBrokersResult;
}
private static GetBootstrapBrokersResultJsonUnmarshaller instance;
public static GetBootstrapBrokersResultJsonUnmarshaller getInstance() {
if (instance == null)
instance = new GetBootstrapBrokersResultJsonUnmarshaller();
return instance;
}
}
|
[
""
] | |
836598ac8a408caef560ff46d16a0091fcfb4c5c
|
e62419162eb9377d4d8e05ccd53336aea81b645f
|
/cognitiveservices/azure-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/contentmoderator/implementation/OCRInner.java
|
f65b96f5384c2de284692b1bd34f22b7d536bd41
|
[
"MIT"
] |
permissive
|
pgbhagat/azure-sdk-for-java
|
7c1511e7c37c39c7689b6c27a153031c7084b0dc
|
86f5e099ab5cd4f87139992e49d3e86d1fd48087
|
refs/heads/master
| 2023-08-24T14:08:58.354824 | 2018-02-28T15:29:57 | 2018-02-28T15:29:57 | 122,472,102 | 0 | 0 |
MIT
| 2018-02-22T11:53:44 | 2018-02-22T11:53:43 | null |
UTF-8
|
Java
| false | false | 4,352 |
java
|
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*/
package com.microsoft.azure.cognitiveservices.contentmoderator.implementation;
import com.microsoft.azure.cognitiveservices.contentmoderator.Status;
import java.util.List;
import com.microsoft.azure.cognitiveservices.contentmoderator.KeyValuePair;
import com.microsoft.azure.cognitiveservices.contentmoderator.Candidate;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
* Contains the text found in image for the language specified.
*/
public class OCRInner {
/**
* The evaluate status.
*/
@JsonProperty(value = "Status")
private Status status;
/**
* Array of KeyValue.
*/
@JsonProperty(value = "Metadata")
private List<KeyValuePair> metadata;
/**
* The tracking id.
*/
@JsonProperty(value = "TrackingId")
private String trackingId;
/**
* The cache id.
*/
@JsonProperty(value = "CacheId")
private String cacheId;
/**
* The ISO 639-3 code.
*/
@JsonProperty(value = "Language")
private String language;
/**
* The found text.
*/
@JsonProperty(value = "Text")
private String text;
/**
* The list of candidate text.
*/
@JsonProperty(value = "Candidates")
private List<Candidate> candidates;
/**
* Get the status value.
*
* @return the status value
*/
public Status status() {
return this.status;
}
/**
* Set the status value.
*
* @param status the status value to set
* @return the OCRInner object itself.
*/
public OCRInner withStatus(Status status) {
this.status = status;
return this;
}
/**
* Get the metadata value.
*
* @return the metadata value
*/
public List<KeyValuePair> metadata() {
return this.metadata;
}
/**
* Set the metadata value.
*
* @param metadata the metadata value to set
* @return the OCRInner object itself.
*/
public OCRInner withMetadata(List<KeyValuePair> metadata) {
this.metadata = metadata;
return this;
}
/**
* Get the trackingId value.
*
* @return the trackingId value
*/
public String trackingId() {
return this.trackingId;
}
/**
* Set the trackingId value.
*
* @param trackingId the trackingId value to set
* @return the OCRInner object itself.
*/
public OCRInner withTrackingId(String trackingId) {
this.trackingId = trackingId;
return this;
}
/**
* Get the cacheId value.
*
* @return the cacheId value
*/
public String cacheId() {
return this.cacheId;
}
/**
* Set the cacheId value.
*
* @param cacheId the cacheId value to set
* @return the OCRInner object itself.
*/
public OCRInner withCacheId(String cacheId) {
this.cacheId = cacheId;
return this;
}
/**
* Get the language value.
*
* @return the language value
*/
public String language() {
return this.language;
}
/**
* Set the language value.
*
* @param language the language value to set
* @return the OCRInner object itself.
*/
public OCRInner withLanguage(String language) {
this.language = language;
return this;
}
/**
* Get the text value.
*
* @return the text value
*/
public String text() {
return this.text;
}
/**
* Set the text value.
*
* @param text the text value to set
* @return the OCRInner object itself.
*/
public OCRInner withText(String text) {
this.text = text;
return this;
}
/**
* Get the candidates value.
*
* @return the candidates value
*/
public List<Candidate> candidates() {
return this.candidates;
}
/**
* Set the candidates value.
*
* @param candidates the candidates value to set
* @return the OCRInner object itself.
*/
public OCRInner withCandidates(List<Candidate> candidates) {
this.candidates = candidates;
return this;
}
}
|
[
"[email protected]"
] | |
8e963841e87bb06d5f5e49db5c326a1eb27f552d
|
7e9593dd15d6550502e8119d6c7ea5176b61d2a7
|
/Day58_ZeroSpringMVC/src/main/java/com/yy/controller/ConverterController.java
|
772beba65fdc50aae97027fec95837dd12166fd1
|
[] |
no_license
|
FineDreams/JavaStudy
|
67ec98fc3a6c086ffb717b19af1dfcc52585e245
|
b513b9a3df332673f445e2fd2b900b6b123e7460
|
refs/heads/master
| 2021-09-10T21:55:45.059112 | 2018-04-03T01:22:33 | 2018-04-03T01:22:33 | 113,833,680 | 1 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 509 |
java
|
package com.yy.controller;
import com.yy.domain.DemoObj;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class ConverterController {
@RequestMapping(value = "/convert",produces = {"application/x-yy"})
public @ResponseBody DemoObj convert(@RequestBody DemoObj obj){
return obj;
}
}
|
[
"[email protected]"
] | |
05d68f6762455cd83a3a08cb3b5dab04882a156f
|
1465bbefeaf484c893d72b95b2996a504ce30577
|
/zcommon/src/org/zkoss/lang/SystemException.java
|
c49e92a32d2ed246bca9bfd684a55ab577542c5a
|
[] |
no_license
|
dije/zk
|
a2c74889d051f988e23cb056096d07f8b41133e9
|
17b8d24a970d63f65f1f3a9ffe4be999b5000304
|
refs/heads/master
| 2021-01-15T19:40:42.842829 | 2011-10-21T03:23:53 | 2011-10-21T03:23:53 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 5,018 |
java
|
/* SystemException.java
Purpose: Thrown if a caught exception is not in the exception list.
Description:
History:
2001/5/15, Tom M. Yeh: Created.
Copyright (C) 2001 Potix Corporation. All Rights Reserved.
{{IS_RIGHT
This program is distributed under LGPL Version 3.0 in the hope that
it will be useful, but WITHOUT ANY WARRANTY.
}}IS_RIGHT
*/
package org.zkoss.lang;
import org.zkoss.mesg.Messageable;
/**
* Indicates a system exception.
*
* @author tomyeh
*/
public class SystemException extends RuntimeException implements Messageable {
/** Utilities.
*
* <p>The reason to use a class to hold static utilities is we can
* override the method's return type later.
*/
public static class Aide {
/** Converts an exception to SystemException or OperationException
* depending on whether t implements Expetable.
* @see Exceptions#wrap
*/
public static SystemException wrap(Throwable t) {
t = Exceptions.unwrap(t);
if (t instanceof Warning)
return (WarningException)
Exceptions.wrap(t, WarningException.class);
if (t instanceof Expectable)
return (OperationException)
Exceptions.wrap(t, OperationException.class);
return (SystemException)
Exceptions.wrap(t, SystemException.class);
}
/** Converts an exception to SystemException or OperationException
* depending on whether t implements Expetable.
* @see Exceptions#wrap
*/
public static SystemException wrap(Throwable t, String msg) {
t = Exceptions.unwrap(t);
if (t instanceof Warning)
return (WarningException)
Exceptions.wrap(t, WarningException.class, msg);
if (t instanceof Expectable)
return (OperationException)
Exceptions.wrap(t, OperationException.class, msg);
return (SystemException)
Exceptions.wrap(t, SystemException.class, msg);
}
/** Converts an exception to SystemException or OperationException
* depending on whether t implements Expetable.
* @see Exceptions#wrap
*/
public static SystemException wrap(Throwable t, int code, Object[] fmtArgs) {
t = Exceptions.unwrap(t);
if (t instanceof Warning)
return (WarningException)
Exceptions.wrap(t, WarningException.class, code, fmtArgs);
if (t instanceof Expectable)
return (OperationException)
Exceptions.wrap(t, OperationException.class, code, fmtArgs);
return (SystemException)
Exceptions.wrap(t, SystemException.class, code, fmtArgs);
}
/** Converts an exception to SystemException or OperationException
* depending on whether t implements Expetable.
* @see Exceptions#wrap
*/
public static SystemException wrap(Throwable t, int code, Object fmtArg) {
t = Exceptions.unwrap(t);
if (t instanceof Warning)
return (WarningException)
Exceptions.wrap(t, WarningException.class, code, fmtArg);
if (t instanceof Expectable)
return (OperationException)
Exceptions.wrap(t, OperationException.class, code, fmtArg);
return (SystemException)
Exceptions.wrap(t, SystemException.class, code, fmtArg);
}
/** Converts an exception to SystemException or OperationException
* depending on whether t implements Expetable.
* @see Exceptions#wrap
*/
public static SystemException wrap(Throwable t, int code) {
t = Exceptions.unwrap(t);
if (t instanceof Warning)
return (WarningException)
Exceptions.wrap(t, WarningException.class, code);
if (t instanceof Expectable)
return (OperationException)
Exceptions.wrap(t, OperationException.class, code);
return (SystemException)
Exceptions.wrap(t, SystemException.class, code);
}
}
protected int _code = NULL_CODE;
/**
* Constructs a SystemException by specifying message directly.
*/
public SystemException(String msg, Throwable cause) {
super(msg, cause);
}
public SystemException(String msg) {
super(msg);
}
public SystemException(Throwable cause) {
super(cause);
}
public SystemException() {
}
/**
* Constructs an SystemException by use of an error code.
* The error code must be defined in
* one of properties files, e.g., msgsys.properties.
*
* @param code the error code
* @param fmtArgs the format arguments
* @param cause the chained throwable object
*/
public SystemException(int code, Object[] fmtArgs, Throwable cause) {
super(Exceptions.getMessage(code, fmtArgs), cause);
_code = code;
}
public SystemException(int code, Object fmtArg, Throwable cause) {
super(Exceptions.getMessage(code, fmtArg), cause);
_code = code;
}
public SystemException(int code, Object[] fmtArgs) {
super(Exceptions.getMessage(code, fmtArgs));
_code = code;
}
public SystemException(int code, Object fmtArg) {
super(Exceptions.getMessage(code, fmtArg));
_code = code;
}
public SystemException(int code, Throwable cause) {
super(Exceptions.getMessage(code), cause);
_code = code;
}
public SystemException(int code) {
super(Exceptions.getMessage(code));
_code = code;
}
//-- Messageable --//
public final int getCode() {
return _code;
}
}
|
[
"[email protected]"
] | |
ee969feedc769a3776583efc26e336c84116c04e
|
ec6087bfcfba20306748b2ff5cd559cb32b35ff6
|
/leetcode/191.number-of-1-bits.281228005.ac.java
|
cb4d4ef3ac552afc559248c89332aa8611554d51
|
[
"BSD-3-Clause"
] |
permissive
|
lang010/acit
|
20bc1ea2956f83853551e398d86e3a14672e0aeb
|
5c43d6400e55992e9cf059d2bdf05536b776f71b
|
refs/heads/master
| 2021-01-20T09:45:24.832154 | 2020-12-16T04:05:10 | 2020-12-16T04:05:10 | 25,975,369 | 1 | 1 | null | null | null | null |
UTF-8
|
Java
| false | false | 1,974 |
java
|
/*
* @lc app=leetcode id=191 lang=java
*
* [191] Number of 1 Bits
*
* https://leetcode.com/problems/number-of-1-bits/description/
*
* algorithms
* Easy (51.53%)
* Total Accepted: 409.5K
* Total Submissions: 794.7K
* Testcase Example: '00000000000000000000000000001011'
*
* Write a function that takes an unsigned integer and returns the number of
* '1' bits it has (also known as the Hamming weight).
*
* Note:
*
*
* Note that in some languages such as Java, there is no unsigned integer type.
* In this case, the input will be given as a signed integer type. It should
* not affect your implementation, as the integer's internal binary
* representation is the same, whether it is signed or unsigned.
* In Java, the compiler represents the signed integers using 2's complement
* notation. Therefore, in Example 3 above, the input represents the signed
* integer. -3.
*
*
* Follow up: If this function is called many times, how would you optimize
* it?
*
*
* Example 1:
*
*
* Input: n = 00000000000000000000000000001011
* Output: 3
* Explanation: The input binary string 00000000000000000000000000001011 has a
* total of three '1' bits.
*
*
* Example 2:
*
*
* Input: n = 00000000000000000000000010000000
* Output: 1
* Explanation: The input binary string 00000000000000000000000010000000 has a
* total of one '1' bit.
*
*
* Example 3:
*
*
* Input: n = 11111111111111111111111111111101
* Output: 31
* Explanation: The input binary string 11111111111111111111111111111101 has a
* total of thirty one '1' bits.
*
*
*
* Constraints:
*
*
* The input must be a binary string of length 32
*
*
*/
public class Solution {
// you need to treat n as an unsigned value
public int hammingWeight(int n) {
int cnt = 0;
while (n != 0) {
if ((n & 1) > 0) {
cnt++;
}
n = n >>> 1;
}
return cnt;
}
}
|
[
"[email protected]"
] | |
ea91687a06e18994711b98a404eea7deb5f45fa9
|
aaec57c704bc2021d58e07b47fd19a626e0c634f
|
/backend/src/main/java/com/quickbase/devint/PopulationStatisticsService.java
|
c35eb542f0fc03b77114075c9d641c9bddfb1103
|
[] |
no_license
|
halexiev-softcivilization/interview-demos
|
32bb821304b56c9f6a676a5e3de708d6f2a93127
|
fbf626168861b168a87dfe4dcaa9ffb573cff3a6
|
refs/heads/master
| 2023-05-25T20:41:20.650160 | 2021-06-08T21:44:06 | 2021-06-08T21:44:06 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 208 |
java
|
package com.quickbase.devint;
import java.util.List;
import org.apache.commons.lang3.tuple.Pair;
public interface PopulationStatisticsService {
List<Pair<String, Integer>> getCountryPopulations();
}
|
[
"[email protected]"
] | |
fc42928e6caedd891fe99896a56e8fca0eba0560
|
1041b45945aaa6f3aa3cb6c5fafa3fa9e0b2dbfc
|
/evaluator-service/src/main/java/com/stackroute/plasma/EvaluatorApplication.java
|
119277c61dafd14a9e5410777a9ac2a8022415bd
|
[
"Apache-2.0"
] |
permissive
|
sunigu11/154
|
e446ec535648c7771fafa0eeb39d72f6416fdbbc
|
b9e906628e9d1933c88bf6f25ec4eff5d1b0fe1a
|
refs/heads/master
| 2020-05-02T02:47:34.592167 | 2019-03-26T04:01:39 | 2019-03-26T04:01:39 | 177,712,202 | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 320 |
java
|
package com.stackroute.plasma;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class EvaluatorApplication {
public static void main(String[] args) {
SpringApplication.run(EvaluatorApplication.class, args);
}
}
|
[
"[email protected]"
] | |
72bf041eabe3ba15306f5883002d3e8725cfad3d
|
a3791f819758004253019a7f0cb6d765eafdff51
|
/grpc_server/grpc_client/src/main/java/com/learn/yzh/grpcclient/LogGrpcInterceptor.java
|
24fef9a101293507d8d5c2dc5977d7e63e0de93c
|
[] |
no_license
|
yangzhanghuigithub/yzh
|
2e53de40d94aeac64e17844d4d03475adcbf2e06
|
f81358d292a918dcbde155e3115b45d01b4374de
|
refs/heads/master
| 2022-10-25T17:46:25.493205 | 2019-08-25T02:10:24 | 2019-08-25T02:10:27 | 158,818,433 | 1 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 592 |
java
|
package com.learn.yzh.grpcclient;
import io.grpc.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* emil:[email protected]
* Created by forezp on 2018/8/11.
*/
public class LogGrpcInterceptor implements ClientInterceptor {
private static final Logger log = LoggerFactory.getLogger(LogGrpcInterceptor.class);
@Override
public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(MethodDescriptor<ReqT, RespT> method, CallOptions callOptions, Channel next) {
log.info(method.getFullMethodName());
return next.newCall(method, callOptions);
}
}
|
[
"[email protected]"
] | |
1b9204ea22c3d6a3ea7d1a5f6cb548213a84d49c
|
bb7454e9347a4c219e7582830c72dfd71cbc6503
|
/src/Arrays/Arys.java
|
346d0e4d138c0b012dbbc468f48c811aad09999a
|
[] |
no_license
|
yichunzhao/Cases-for-Oracle-OCPJP-Certificate
|
1fdd38dd728c86cfec40264f563639d83cca4601
|
09c8755ba12fee994444e5a50b5edf2ab3d84642
|
refs/heads/master
| 2020-12-28T19:34:54.469593 | 2017-10-01T21:30:01 | 2017-10-01T21:30:01 | 54,158,776 | 0 | 1 | null | null | null | null |
UTF-8
|
Java
| false | false | 1,323 |
java
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package Arrays;
/**
*
* @author YNZ
*/
class MDArray {
double[][] d = new double[3][];
{
for (int i = 0; i < d.length; i++) {
//d[i][]={1, 2, 3}
}
}
}
public class Arys {
int[] a1 = new int[10];
int[][] am;
String[] s1 = new String[3];
public Arys() {
for (int i = 0; i < a1.length; i++) {
a1[i] = i;
}
am = new int[][]{{1, 2}, {3, 4}, {4, 5, 6}};
s1[1] = "shut up!";
}
public void printMatrix(int[][] vs) {
for (int[] v : vs) {
printVec(v);
}
}
public void printVec(int[] v) {
for (int e : v) {
System.out.print(e);
}
}
public static void main(String[] args) {
Arys as = new Arys();
System.out.println("a1 length=" + as.a1.length);
System.out.println("s1 length=" + as.s1.length + as.s1.toString());
System.out.println(as.am.length);
as.printMatrix(as.am);
for (String s : as.s1) {
System.out.println(s);
}
}
}
|
[
"[email protected]"
] | |
1ef42b3a634bfeac3bce0ff69a0cfe91b37ecd4d
|
d29d02ebfc68c235ed5a23d53226e869577c379d
|
/final_project/src/main/webapp/WEB-INF/program/GroupWare-master/src/main/java/com/sangheon/groupware/repository/BoardDao.java
|
2c42eea7a8a9dbab9e53f7642b5b356e95489c58
|
[] |
no_license
|
torra3167/hkedu_project
|
5378225be47f6898a9b2be8a123f52cb53f6e67d
|
d5e4022b87f872c3adb1a796389875ef5a734334
|
refs/heads/master
| 2020-04-04T19:33:21.005078 | 2018-12-07T08:07:05 | 2018-12-07T08:07:05 | 156,211,404 | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 1,803 |
java
|
package com.sangheon.groupware.repository;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.session.SqlSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.sangheon.groupware.vo.BoardVo;
@Repository
public class BoardDao {
@Autowired
private SqlSession sqlSession;
public BoardVo getContent(BoardVo boardVo) {
return sqlSession.selectOne("board.getContent" ,boardVo);
}
public List<BoardVo> getBoardList( ) {
return sqlSession.selectList( "board.getBoardList" );
}
public int newContent( BoardVo boardVo ) {
Map<String, Object> map = new HashMap<String, Object>();
map.put( "employeeNo", boardVo.getEmployeeNo() );
map.put( "contentTitle", boardVo.getContentTitle() );
map.put( "contentContent", boardVo.getContentContent() );
map.put( "teamId", boardVo.getTeamId() );
map.put( "boardId", boardVo.getBoardId() );
Calendar calendar = Calendar.getInstance();
map.put( "contentId", boardVo.getEmployeeNo()+calendar.get( Calendar.YEAR )+calendar.get( Calendar.MONTH )+
calendar.get( Calendar.DATE )+calendar.get( Calendar.HOUR )+calendar.get( Calendar.MINUTE )+
calendar.get( Calendar.SECOND )+calendar.get( Calendar.MILLISECOND ));
int count = sqlSession.insert("board.newContent", map);
return count;
}
public List<BoardVo> getContentList(BoardVo boardVo ) {
return sqlSession.selectList( "board.getContentList",boardVo );
}
public List<BoardVo> getContentListByTeam(BoardVo boardVo ) {
return sqlSession.selectList( "board.getContentListByTeam",boardVo );
}
public int deleteContent( BoardVo boardVo ) {
return sqlSession.delete("board.deleteContent",boardVo);
}
}
|
[
"[email protected]"
] | |
44396eb7a9b1f022c1de1c3d555271e94cca2eba
|
e9d635da4ece9776c14cc222a5ee1fdeae5e6412
|
/ThePoint/src/DTO/M_Info_DTO.java
|
2632012bd1a93ae046755a4e8ba139d05965d655
|
[] |
no_license
|
DanMooG/ThePoint
|
36cf20d6d6525ea7c51a3a4cf056cf77a7e4bdbd
|
de5aa91e3927578618b733debc40e5b142c4b0fa
|
refs/heads/master
| 2022-11-14T19:17:08.228203 | 2020-07-07T09:15:42 | 2020-07-07T09:15:42 | 265,187,890 | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 2,366 |
java
|
package DTO;
public class M_Info_DTO {
private String m_Name = "";
private String m_Goal = "";
private String m_LKind = "";
private String m_SKind = "";
private int m_StartYear = 0;
private int m_StartMonth = 0;
private int m_StartDate = 0;
private int m_EndYear = 0;
private int m_EndMonth = 0;
private int m_EndDate = 0;
private String m_Determin = "";
public M_Info_DTO() {}
public M_Info_DTO(String m_Name, String m_Goal, String m_LKind, String m_SKind, int m_StartYear, int m_StartMonth, int m_StartDate, int m_EndYear, int m_EndMonth, int m_EndDate, String m_Determin) {
this.m_Name = m_Name;
this.m_Goal = m_Goal;
this.m_LKind = m_LKind;
this.m_SKind = m_SKind;
this.m_StartYear = m_StartYear;
this.m_StartMonth = m_StartMonth;
this.m_StartDate = m_StartDate;
this.m_EndYear = m_EndYear;
this.m_EndMonth = m_EndMonth;
this.m_EndDate = m_EndDate;
this.m_Determin = m_Determin;
}
public String getM_Name() {
return m_Name;
}
public void setM_Name(String m_Name) {
this.m_Name = m_Name;
}
public String getM_Goal() {
return m_Goal;
}
public void setM_Goal(String m_Goal) {
this.m_Goal = m_Goal;
}
public String getM_LKind() {
return m_LKind;
}
public void setM_LKind(String m_LKind) {
this.m_LKind = m_LKind;
}
public String getM_SKind() {
return m_SKind;
}
public void setM_SKind(String m_SKind) {
this.m_SKind = m_SKind;
}
public int getM_StartYear() {
return m_StartYear;
}
public void setM_StartYear(int m_StartYear) {
this.m_StartYear = m_StartYear;
}
public int getM_StartMonth() {
return m_StartMonth;
}
public void setM_StartMonth(int m_StartMonth) {
this.m_StartMonth = m_StartMonth;
}
public int getM_StartDate() {
return m_StartDate;
}
public void setM_StartDate(int m_StartDate) {
this.m_StartDate = m_StartDate;
}
public int getM_EndYear() {
return m_EndYear;
}
public void setM_EndYear(int m_EndYear) {
this.m_EndYear = m_EndYear;
}
public int getM_EndMonth() {
return m_EndMonth;
}
public void setM_EndMonth(int m_EndMonth) {
this.m_EndMonth = m_EndMonth;
}
public int getM_EndDate() {
return m_EndDate;
}
public void setM_EndDate(int m_EndDate) {
this.m_EndDate = m_EndDate;
}
public String getM_Determin() {
return m_Determin;
}
public void setM_Determin(String m_Determin) {
this.m_Determin = m_Determin;
}
}
|
[
"[email protected]"
] | |
0e368f6302ae3857ac1318b6709534cbebe2c78c
|
113f9d23b27a07cac2caee11feb36fd9d42a49a8
|
/src/_02_Java_Object_Oriented_Programming/_23_supermarket/interfaces/Merchandise.java
|
518ed9bacfdfb4d70d70322ac040a392743ed434
|
[] |
no_license
|
pastgonex/GeekForever
|
90d5c9b74e7181ebdf8723917f38610f4911e234
|
4c49bbc7035e705c92f8684bf2917e2798f0dad0
|
refs/heads/master
| 2023-07-24T05:45:29.827549 | 2020-07-26T11:56:10 | 2020-07-26T11:56:10 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 295 |
java
|
package _02_Java_Object_Oriented_Programming._23_supermarket.interfaces;
public interface Merchandise {
String getName();
double getSoldPrice();
double getPurchasePrice();
int buy(int count);
void putBack(int count);
Category getCategory();
int getCount();
}
|
[
"[email protected]"
] | |
4d74312d2752309e5ea5a77f40fa94b30074b502
|
7cc83350cab361cad544ac75f0b72de31345d03e
|
/src/br/com/facility/dao/LocalAtendimentoDAO.java
|
dea7bda8840f20cffdd352a80025b07a6ba2cb8b
|
[] |
no_license
|
m7portella/ProjetoFacility
|
3fb3ad139439862c96930adb85d2b580279038a5
|
ec24269c420a7ca3da24bc22a9cb6cab9b6b5a23
|
refs/heads/master
| 2021-01-22T21:17:01.454973 | 2014-10-23T07:39:13 | 2014-10-23T07:39:13 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 350 |
java
|
package br.com.facility.dao;
import java.util.List;
import br.com.facility.to.LocalAtendimento;
public interface LocalAtendimentoDAO extends DAO<LocalAtendimento, Integer>{
List<LocalAtendimento> listarTodos();
List<LocalAtendimento> listarPorCidade(String estado, String cidade);
List<LocalAtendimento> listarPorEstado(String estado);
}
|
[
"[email protected]"
] | |
19078117edcd067d4e0b357f33cfa4384c0e84d6
|
1d84bc380bf577cc363b57def005794d15aa7e43
|
/src/jabberwocky/letterBased/Jabberwocky.java
|
09fcebcb227675d8836ea8d572221c3d16132188
|
[
"BSD-3-Clause"
] |
permissive
|
diegobugmann/Java-Projects-Diego
|
de914d9cc8aea1169c5cb269b2d0f71b0301b454
|
7ebd6e899da390abd3386a1a317bd733a66cdc6e
|
refs/heads/master
| 2020-04-29T00:06:53.060526 | 2020-02-18T15:01:18 | 2020-02-18T15:01:18 | 175,681,752 | 2 | 1 | null | null | null | null |
UTF-8
|
Java
| false | false | 5,110 |
java
|
package jabberwocky.letterBased;
import jabberwocky.letterBased.appClasses.App_Controller;
import jabberwocky.letterBased.appClasses.App_Model;
import jabberwocky.letterBased.appClasses.App_View;
import jabberwocky.letterBased.splashScreen.Splash_Controller;
import jabberwocky.letterBased.splashScreen.Splash_Model;
import jabberwocky.letterBased.splashScreen.Splash_View;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.stage.Stage;
/**
* Copyright 2015, FHNW, Prof. Dr. Brad Richards. All rights reserved. This code
* is licensed under the terms of the BSD 3-clause license (see the file
* license.txt).
*
* @author Brad Richards
*/
public class Jabberwocky extends Application {
private static Jabberwocky mainProgram; // singleton
private Splash_View splashView;
private App_View view;
private ServiceLocator serviceLocator; // resources, after initialization
public static void main(String[] args) {
launch(args);
}
/**
* Note: This method is called on the main thread, not the JavaFX
* Application Thread. This means that we cannot display anything to the
* user at this point. Since we want to show a splash screen, this means
* that we cannot do any real initialization here.
*
* This implementation ensures that the application is a singleton; only one
* per JVM-instance. On client installations this is not necessary (each
* application runs in its own JVM). However, it can be important on server
* installations.
*
* Why is it important that only one instance run in the JVM? Because our
* initialized resources are a singleton - if two programs instances were
* running, they would use (and overwrite) each other's resources!
*/
@Override
public void init() {
if (mainProgram == null) {
mainProgram = this;
} else {
Platform.exit();
}
}
/**
* This method is called after init(), and is called on the JavaFX
* Application Thread, so we can display a GUI. We have two GUIs: a splash
* screen and the application. Both of these follow the MVC model.
*
* We first display the splash screen. The model is where all initialization
* for the application takes place. The controller updates a progress-bar in
* the view, and (after initialization is finished) calls the startApp()
* method in this class.
*/
@Override
public void start(Stage primaryStage) {
// Create and display the splash screen and model
Splash_Model splashModel = new Splash_Model();
splashView = new Splash_View(primaryStage, splashModel);
new Splash_Controller(this, splashModel, splashView);
// Display the splash screen and begin the initialization
splashView.start();
splashModel.initialize();
}
/**
* This method is called when the splash screen has finished initializing
* the application. The initialized resources are in a ServiceLocator
* singleton. Our task is to now create the application MVC components, to
* hide the splash screen, and to display the application GUI.
*
* Multitasking note: This method is called from an event-handler in the
* Splash_Controller, which means that it is on the JavaFX Application
* Thread, which means that it is allowed to work with GUI components.
* http://docs.oracle.com/javafx/2/threads/jfxpub-threads.htm
*/
public void startApp() {
Stage appStage = new Stage();
// Initialize the application MVC components. Note that these components
// can only be initialized now, because they may depend on the
// resources initialized by the splash screen
App_Model model = new App_Model();
view = new App_View(appStage, model);
new App_Controller(model, view);
// Resources are now initialized
serviceLocator = ServiceLocator.getServiceLocator();
// Close the splash screen, and set the reference to null, so that all
// Splash_XXX objects can be garbage collected
splashView.stop();
splashView = null;
view.start();
}
/**
* The stop method is the opposite of the start method. It provides an
* opportunity to close down the program, including GUI components. If the
* start method has never been called, the stop method may or may not be
* called.
*
* Make the GUI invisible first. This prevents the user from taking any
* actions while the program is ending.
*/
@Override
public void stop() {
serviceLocator.getConfiguration().save();
if (view != null) {
// Make the view invisible
view.stop();
}
// More cleanup code as needed
serviceLocator.getLogger().info("Application terminated");
}
// Static getter for a reference to the main program object
protected static Jabberwocky getMainProgram() {
return mainProgram;
}
}
|
[
"[email protected]"
] | |
2cdc73f4df3784d0196f4c32c7eb8956ca727326
|
258a8585ed637342645b56ab76a90a1256ecbb45
|
/Folitics/src/main/java/com/ohmuk/folitics/hibernate/service/pollOption/distribution/PollOptionQualificationService.java
|
243ed70e98edd97ce09da7a7cbf9bb5417060f56
|
[] |
no_license
|
exatip407/folitics
|
06e899aae2dbfdeda981c40c0ce578d223979568
|
aff3392e09c35f5f799e3fb1c4534b5343a22f01
|
refs/heads/master
| 2021-01-01T16:23:14.684470 | 2017-07-20T10:27:08 | 2017-07-20T10:27:08 | 97,819,592 | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 5,657 |
java
|
package com.ohmuk.folitics.hibernate.service.pollOption.distribution;
import javax.transaction.Transactional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ohmuk.folitics.exception.MessageException;
import com.ohmuk.folitics.hibernate.entity.poll.PollOptionQualification;
import com.ohmuk.folitics.hibernate.entity.poll.PollOptionQualificationId;
import com.ohmuk.folitics.hibernate.repository.pollOption.distribution.IPollOptionDistributionRepository;
/**
* Service implementation for {@link PollOptionQualification}
* @author Abhishek
*
*/
@Service
@Transactional
public class PollOptionQualificationService implements
IPollOptionDistributionService<PollOptionQualification, PollOptionQualificationId> {
private static Logger logger = LoggerFactory.getLogger(PollOptionQualificationService.class);
@Autowired
private IPollOptionDistributionRepository<PollOptionQualification, PollOptionQualificationId> repository;
@Override
public PollOptionQualification addDistribution(PollOptionQualification pollOptionQualification)
throws MessageException {
logger.debug("Entered PollOptionQualificationService addDistribution method");
if (pollOptionQualification == null) {
logger.error("PollOptionQualification object found null in PollOptionQualificationService.addDistribution method");
throw (new MessageException("PollOptionQualification object can't be null"));
}
if (pollOptionQualification.getId() == null) {
logger.error("Id in PollOptionQualification object found null in PollOptionQualificationService.addDistribution method");
throw (new MessageException("Id in PollOptionQualification object can't be null"));
}
logger.debug("Trying to save the PollOptionQualification object for poll option id = "
+ pollOptionQualification.getId().getPollOption().getId() + " and qualification id = "
+ pollOptionQualification.getId().getQualification().getId());
pollOptionQualification = repository.save(pollOptionQualification);
logger.debug("PollOptionQualification saved successfully. Exiting PollOptionQualificationService addDistribution method");
return pollOptionQualification;
}
@Override
public PollOptionQualification getDistribution(PollOptionQualificationId pollOptionQualificationId)
throws MessageException {
logger.debug("Entered PollOptionQualificationService getDistribution method");
if (pollOptionQualificationId == null) {
logger.error("PollOptionQualificationId object found null in PollOptionQualificationService.getDistribution method");
throw (new MessageException("PollOptionQualificationId object can't be null"));
}
if (pollOptionQualificationId.getPollOption() == null) {
logger.error("PollOption in PollOptionQualificationId object found null in PollOptionQualificationService.getDistribution method");
throw (new MessageException("PollOption in PollOptionQualificationId object can't be null"));
}
if (pollOptionQualificationId.getQualification() == null) {
logger.error("Qualification in PollOptionQualificationId object found null in PollOptionQualificationService.getDistribution method");
throw (new MessageException("Qualification in PollOptionQualificationId object can't be null"));
}
logger.debug("Trying to get the PollOptionQualification object for poll option id = "
+ pollOptionQualificationId.getPollOption().getId() + " and qualification id = "
+ pollOptionQualificationId.getQualification().getId());
PollOptionQualification pollOptionQualification = repository.find(pollOptionQualificationId);
logger.debug("Got PollOptionQualification from database. Exiting PollOptionQualificationService getDistribution method");
return pollOptionQualification;
}
@Override
public PollOptionQualification updateDistribution(PollOptionQualification pollOptionQualification)
throws MessageException {
logger.debug("Entered PollOptionQualificationService updateDistribution method");
if (pollOptionQualification == null) {
logger.error("PollOptionQualification object found null in PollOptionQualificationService.updateDistribution method");
throw (new MessageException("PollOptionQualification object can't be null"));
}
if (pollOptionQualification.getId() == null) {
logger.error("Id in PollOptionQualification object found null in PollOptionQualificationService.updateDistribution method");
throw (new MessageException("Id in PollOptionQualification object can't be null"));
}
logger.debug("Trying to get the PollOptionQualification object for poll option id = "
+ pollOptionQualification.getId().getPollOption().getId() + " and qualification id = "
+ pollOptionQualification.getId().getQualification().getId());
pollOptionQualification = repository.update(pollOptionQualification);
logger.debug("Updated PollOptionQualification in database. Exiting PollOptionQualificationService updateDistribution method");
return pollOptionQualification;
}
}
|
[
"[email protected]"
] | |
66d47ec3f154949353336edeae26dc727a82d682
|
62a20101ea1affb4dd78679c6c62a7487c3d0301
|
/src-jogl/de/jreality/jogl/pick/PickPointComparator.java
|
c53083cea665e93e96137e7c8c84e428f9f871c1
|
[] |
no_license
|
iee/org.eclipse.iee.jreality.test
|
c2fc38efedb8c21b8f64bc12909922633bb70dc1
|
95463912968dd4c8035e20f23fd41d4ecdcb8083
|
refs/heads/master
| 2020-05-17T08:30:44.506323 | 2011-11-23T10:05:04 | 2011-11-23T10:05:04 | 2,834,751 | 1 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 2,368 |
java
|
/**
*
* This file is part of jReality. jReality is open source software, made
* available under a BSD license:
*
* Copyright (c) 2003-2006, jReality Group: Charles Gunn, Tim Hoffmann, Markus
* Schmies, Steffen Weissmann.
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* - Neither the name of jReality nor the names of its contributors nor the
* names of their associated organizations may be used to endorse or promote
* products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
package de.jreality.jogl.pick;
import java.util.Comparator;
/**
* @author gunn
*
*/
public class PickPointComparator implements Comparator {
private PickPointComparator() {
super();
}
public static PickPointComparator sharedInstance = null;
static {
sharedInstance = new PickPointComparator();
}
public int compare(Object o1, Object o2) {
if (((PickPoint) o1).pointNDC[2] > ((PickPoint) o2).pointNDC[2]) return 1;
else if (((PickPoint) o1).pointNDC[2] == ((PickPoint) o2).pointNDC[2]) return 0;
else return -1;
}
}
|
[
"[email protected]"
] | |
0ce9c9b9b795bf0704f0842c70c6c4e91f4b1063
|
c0ebaf41405f597cbc78682d86fe480f4ef9ead0
|
/Account/src/main/java/br/com/hubfintech/account/config/ServletSpringMVC.java
|
a9fb9ae8c310dcbd717b1403123cbaaa4890376b
|
[] |
no_license
|
daniloJava/api-Conta
|
e76188899066dc8b7d92b47ccdf7b8f7f69af564
|
a1e4fa77e8e6eca7d38d7e4a7acda024d22f3c16
|
refs/heads/master
| 2020-12-30T12:44:01.970920 | 2017-05-15T15:09:08 | 2017-05-15T15:09:08 | 91,351,045 | 1 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 1,088 |
java
|
package br.com.hubfintech.account.config;
import javax.servlet.Filter;
import javax.servlet.MultipartConfigElement;
import javax.servlet.ServletRegistration.Dynamic;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
public class ServletSpringMVC extends AbstractAnnotationConfigDispatcherServletInitializer{
@Override
protected Class<?>[] getRootConfigClasses() {
return null;
}
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class[]{AppWebConfiguration.class, JPAConfiguration.class};
}
@Override
protected String[] getServletMappings() {
return new String[] {"/"};
}
@Override
protected Filter[] getServletFilters() {
CharacterEncodingFilter encodingFilter = new CharacterEncodingFilter();
encodingFilter.setEncoding("UTF-8");
return new Filter[] {encodingFilter};
}
@Override
protected void customizeRegistration(Dynamic registration) {
registration.setMultipartConfig(new MultipartConfigElement(""));
}
}
|
[
"[email protected]"
] | |
96d06638282499fdd7a71db5f197e6cfff636e32
|
0d598eebbf0969e58b0484260407693d256a2a9b
|
/src/snackBar/Main.java
|
dc16f825b68ce962f81241a97a3e5fa4c280b317
|
[] |
no_license
|
rrrbba/snackBar
|
75aaa788aeda44e6b273c93c3b8b55817dbf4cce
|
b95d996516e9ffd6dfd071116062e25fec9ca00b
|
refs/heads/master
| 2022-10-28T06:07:03.210988 | 2020-06-15T01:47:51 | 2020-06-15T01:47:51 | 269,240,903 | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 2,456 |
java
|
package snackBar;
public class Main {
private static void opensnackBar()
{
System.out.println("Test");
Customer c1 = new Customer("Jane", 45.25);
Customer c2 = new Customer("Bob", 33.14);
VendingMachine v1 = new VendingMachine("Food");
VendingMachine v2 = new VendingMachine("Drink");
VendingMachine v3 = new VendingMachine("Office");
Snack s1 = new Snack("Chips", 36, 1.75, v1.getId());
Snack s2 = new Snack("Chocolate Bar", 36, 1.00, v1.getId());
Snack s3 = new Snack("Pretzel", 30, 2.00, v1.getId());
Snack s4 = new Snack("Soda", 24, 2.50, v2.getId());
Snack s5 = new Snack("Water", 20, 2.75, v2.getId());
System.out.println("***Processing");
c1.cashReduce(s4.getCost() * 3);
s4.reduceQuantity(3);
System.out.print("Customer 1 cash on hand " + c1.cashOnHand);
System.out.println();
System.out.println("Quantity of snack 4 is " + s4.getQuantity());
System.out.println();
c1.cashReduce(s3.getCost());
s3.reduceQuantity(1);
System.out.print("Customer 1 cash on hand " + c1.cashOnHand);
System.out.println();
System.out.println("Quantity of snack 3 is " + s3.getQuantity());
System.out.println();
c2.cashReduce(s4.getCost() * 2);
s4.reduceQuantity(2);
System.out.print("Customer 2 cash on hand " + c2.cashOnHand);
System.out.println();
System.out.println("Quantity of snack 4 is " + s4.getQuantity());
System.out.println();
c1.cashAdd(10.00);
System.out.print("Customer 1 cash on hand " + c1.cashOnHand);
System.out.println();
c1.cashReduce(s2.getCost());
s2.reduceQuantity(1);
System.out.print("Customer 1 cash on hand " + c1.cashOnHand);
System.out.println();
System.out.println("Quantity of snack 2 is " + s2.getQuantity());
System.out.println();
s3.addQuantity(12);
System.out.println("Quantity of snack 3 is " + s3.getQuantity());
System.out.println();
c2.cashReduce(s3.getCost() * 3);
s3.reduceQuantity(3);
System.out.print("Customer 2 cash on hand " + c2.cashOnHand);
System.out.println();
System.out.println("Quantity of snack 3 is " + s3.getQuantity());
}
public static void main(String[] args){
opensnackBar();
}
}
|
[
"[email protected]"
] | |
23a7247f9b677520e05a212308a08e374e843c81
|
f8e2ddc4e20a16b178d2cb59b35422386deb97da
|
/src/main/java/com/mightyjava/Application.java
|
f23f53617f598848fc8ccdf1af5a85c115f74727
|
[] |
no_license
|
CiprianBeldean/money-monster
|
da030dc8b0ea4a9608112dff27e62541a269f94f
|
1d4ccaa37a57403cb5b24f5d19980273df41f4dd
|
refs/heads/master
| 2022-08-27T16:12:55.764552 | 2020-05-29T16:15:23 | 2020-05-29T16:15:23 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 295 |
java
|
package com.mightyjava;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
|
[
"[email protected]"
] | |
f62bff2a1d65b89dd08982be9a862728908e3523
|
1637b42bfe66763990223d674aa470aa239a240b
|
/ttsd-mobile-api/src/main/java/com/tuotiansudai/api/filter/LogGenerateFilter.java
|
a6698d733f8cdf3a992fec4d48da8f6f0e4b6d9b
|
[] |
no_license
|
haifeiforwork/tuotiansudai
|
11feef3e42f02c3e590ca2b7c081f106b706f7da
|
891fefef783a96f86c3283ce377ba18e80db0c81
|
refs/heads/master
| 2020-12-12T09:16:06.320791 | 2019-03-08T09:34:26 | 2019-03-08T09:34:26 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 1,335 |
java
|
package com.tuotiansudai.api.filter;
import com.tuotiansudai.util.UUIDGenerator;
import org.apache.log4j.MDC;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class LogGenerateFilter implements Filter {
private static final String REQUEST_ID = "requestId";
private static final String USER_ID = "userId";
private static final String ANONYMOUS = "anonymous";
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
try {
MDC.put(REQUEST_ID, UUIDGenerator.generate());
Object currentLoginName = request.getAttribute("currentLoginName");
String loginName = (currentLoginName != null && currentLoginName instanceof String) ? currentLoginName.toString() : ANONYMOUS;
MDC.put(USER_ID, loginName);
chain.doFilter(request, response);
} finally {
MDC.remove(REQUEST_ID);
MDC.remove(USER_ID);
}
}
@Override
public void destroy() {
}
}
|
[
"[email protected]"
] | |
1b6b746b52e30579a7a2edbd809f37be2dad1383
|
fb81d22987981440a6e43746248244f32302f2a2
|
/src/insuredValue/Housing.java
|
c945cdb408f07e73697295f74206f9d4442b8900
|
[] |
no_license
|
gozdekurtulmus/InsurancePolicyCharge_OOP_2
|
76f9a809a6866d0769b509e4ed49593c38c9bee7
|
b9e5a41013bd3f723ecddf3fda537eb1dc883ccc
|
refs/heads/main
| 2023-05-02T01:16:41.055783 | 2021-05-20T09:32:55 | 2021-05-20T09:32:55 | 367,478,674 | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 740 |
java
|
package insuredValue;
public class Housing extends Premises {
private String residentSituation;
public Housing(String[] properties) {
super(properties[0], Integer.parseInt(properties[1]), properties[2], Integer.parseInt(properties[3]),
Integer.parseInt(properties[4]), properties[5], Double.parseDouble(properties[6]));
this.residentSituation = properties[7];
}
public double calculateRiskFactor() {
double value = super.calculateRiskFactor();
return value / values.residentSituation(residentSituation) ;
}
public String getResidentSituation() {
return residentSituation;
}
public void setResidentSituation(String residentSituation) {
this.residentSituation = residentSituation;
}
}
|
[
"[email protected]"
] | |
2185f1c46dae530baa8a82d161a4136b547f03f9
|
133bc3d9243620e8f5f21000b10e935e0296ca0d
|
/app/src/main/java/com/tauhidmonwar/prowriting/S11.java
|
b552c3db3c7bd7c179bcbddee91820c1bb66c68d
|
[] |
no_license
|
tauhidmonwar111/ProWriting
|
93d79ea87ae61b28d1693891b7dd4ae2a39584db
|
02ba54edb3d0a13ebbf5f2759edbc30f07d767da
|
refs/heads/master
| 2020-07-29T11:32:20.890194 | 2019-09-20T12:16:12 | 2019-09-20T12:16:12 | 209,776,916 | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 331 |
java
|
package com.tauhidmonwar.prowriting;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
public class S11 extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_s11);
}
}
|
[
"[email protected]"
] | |
2ab23cfe8cd3bd8da74f844e8063f699afbe26e8
|
3bd776a3c9ec127e987234d33cd41b827f8d3bef
|
/src/main/java/com/power/oj/mail/MailModel.java
|
a5016330a23cd7541642a08df70a9e77fe2ecc80
|
[] |
no_license
|
w703710691d/oj
|
f7a6dffb660ff8ab0fd639c4bd5d49aad109a921
|
cd604533ee1c8bc50148acd4f824b7c5d8715fe0
|
refs/heads/master
| 2021-07-09T17:37:11.272792 | 2020-10-08T07:53:51 | 2020-10-08T07:54:33 | 54,821,894 | 0 | 2 | null | 2017-11-25T03:20:25 | 2016-03-27T09:42:57 |
Java
|
UTF-8
|
Java
| false | false | 2,620 |
java
|
package com.power.oj.mail;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Model;
import java.util.List;
public class MailModel extends Model<MailModel> {
public static final MailModel dao = new MailModel();
public static final String ID = "id";
public static final String MID = "mid";
public static final String USER = "user";
public static final String PEER = "peer";
public static final String STATUS = "status";
/**
*
*/
private static final long serialVersionUID = 854677482560407471L;
public List<MailModel> findUserNewMails(Integer uid) {
return find("SELECT * FROM mail WHERE user=? AND status=0", uid);
}
public Long countUserNewMails(Integer uid) {
return findFirst("SELECT COUNT(*) AS count FROM mail WHERE user=? AND status=0", uid).getLong("count");
}
public Long countUserNewMails(Integer user, Integer peer) {
return findFirst("SELECT COUNT(*) AS count FROM mail WHERE user=? AND peer=? AND status=0", user, peer)
.getLong("count");
}
public boolean hasNewMails(Integer user, Integer peer) {
return findFirst("SELECT 1 FROM mail WHERE user=? AND peer=? AND status=0 LIMIT 1", user, peer) != null;
}
public int resetUserNewMails(Integer user, Integer peer) {
return Db.update("UPDATE mail SET status=1 WHERE user=? AND peer=? AND status=0", user, peer);
}
public int deleteMail(Integer uid, Integer id) {
return Db.update("DELETE FROM mail WHERE user=? AND id=?", uid, id);
}
public int deleteMailGroup(Integer user, Integer peer) {
return Db.update("DELETE FROM mail WHERE user=? AND peer=?", user, peer);
}
public int deleteUserAllMails(Integer uid) {
return Db.update("DELETE FROM mail WHERE user=?", uid);
}
public Integer getId() {
return getInt(ID);
}
public MailModel setId(Integer value) {
return set(ID, value);
}
public Integer getMid() {
return getInt(MID);
}
public MailModel setMid(Integer value) {
return set(MID, value);
}
public Integer getUser() {
return getInt(USER);
}
public MailModel setUser(Integer value) {
return set(USER, value);
}
public Integer getPeer() {
return getInt(PEER);
}
public MailModel setPeer(Integer value) {
return set(PEER, value);
}
public Boolean getStatus() {
return getBoolean(STATUS);
}
public MailModel setStatus(Boolean value) {
return set(STATUS, value);
}
}
|
[
"[email protected]"
] | |
0b1d15642be7f904dd356788510b71fa5f91d580
|
0b96c41df849c8726ab4072e94daa9fabc2125ee
|
/src/main/java/com/hlj/arith/demo00048_单链表反转/单链表反转.java
|
f45d87545661c0804a9c564cc1a7b002f2a4a80b
|
[] |
no_license
|
HealerJean/common-arith
|
5f3e76875377528726b4c9c37e81361b9d3ae9fe
|
ca0afbc262badc6e7bcf9ab585463de3562f9bb2
|
refs/heads/master
| 2021-11-15T18:39:35.955569 | 2021-09-26T08:58:36 | 2021-09-26T08:58:36 | 152,367,524 | 0 | 0 | null | 2021-04-26T20:32:42 | 2018-10-10T05:24:09 |
Java
|
UTF-8
|
Java
| false | false | 2,315 |
java
|
package com.hlj.arith.demo00048_单链表反转;
import org.junit.Test;
/**
作者:HealerJean
题目:单链表反转
解题思路:
*/
public class 单链表反转 {
void printListNode(ListNode listNode){
while (listNode != null){
System.out.printf( listNode.value + ",");
listNode = listNode.next;
}
System.out.println();
}
@Test
public void test(){
ListNode listNode = listNode();
ListNode newListNode = reverseList(listNode);
// printListNode(newListNode);
// ListNode newListNode = dgReverseList(listNode);
printListNode(newListNode);
}
public ListNode reverseList(ListNode head) {
// 定义新链表头结点
ListNode reHead = null;
while (head != null) {
// 先取出,下一个节点。(后面要进行遍历,提前取出防止发生变化)
ListNode next = head.next;
// 将rehead节点怼到head节点上
head.next = reHead;
// 再让head节点作为新节点的头
reHead = head;
// 将head指向下一个节点进行遍历
head = next;
}
return reHead;
}
/**
* 递归实现
*/
public static ListNode dgReverseList(ListNode head) {
if (head.next == null) {
return head;
}
ListNode newHead = dgReverseList(head.next);
// 将头节点置于末端 (比如将4 - > 5 -> next 设置为 4)
head.next.next = head;
// 类似于断开连接,等待下次别人给值 (比如将:4 ->next 设置为 null,等待3到的时候,给值 )
head.next = null;
return newHead;
}
public ListNode listNode(){
ListNode listNode_5 = new ListNode(5, null);
ListNode listNode_4 = new ListNode(4, listNode_5);
ListNode listNode_3 = new ListNode(3, listNode_4);
ListNode listNode_2 = new ListNode(2, listNode_3);
ListNode listNode_1 = new ListNode(1, listNode_2);
return listNode_1;
}
class ListNode{
int value ;
ListNode next ;
public ListNode(int value, ListNode next) {
this.value = value;
this.next = next;
}
}
}
|
[
"[email protected]"
] | |
82f5cc6d56ae4e45f3367373ec61e107a37c5378
|
3394ed29aa46a88979d42376554ecb230f8b90e7
|
/src/pl/bartflor/Dao/DaoFactory.java
|
0ff473857a442724fb367c568566f2523fbbda8c
|
[] |
no_license
|
bartflor/FileUploadServlet
|
ab9028f627b0176af70934783eac3586b6dc4934
|
bb18eed0671acf3170b867b9b6bdbde9563161ac
|
refs/heads/master
| 2021-05-18T20:23:08.765270 | 2020-03-30T19:00:54 | 2020-03-30T19:00:54 | 251,401,917 | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 588 |
java
|
package pl.bartflor.Dao;
import java.sql.Connection;
import javax.servlet.ServletContext;
public class DaoFactory {
ServletContext sContext;
public DaoFactory(ServletContext sContext) {
this.sContext = sContext;
}
public DatabaseAcces createDaoObject() {
ConnectionFactory connectionFactory = new ConnectionFactory(sContext.getInitParameter("url")+sContext.getInitParameter("database"), sContext.getInitParameter("user_name"), sContext.getInitParameter("password"));
Connection connection = connectionFactory.getConnection();
return new DatabaseAcces(connection);
}
}
|
[
"[email protected]"
] | |
e2c646aeb3ba48084982dfe3aa8d8931944ef857
|
961bbc3d788143f2b316a23168476f9b6a398593
|
/CallTestInheritanceWithSuperEx1.java
|
cf2ac704ab9bb802aec6056f12ef2a988393a279
|
[] |
no_license
|
alan11258/Opp
|
888bb45855efc26ade40b75fd76d6144eb57d415
|
3d230f3170bd22716875c2d3f17fcfbe45c990ef
|
refs/heads/master
| 2020-12-02T16:12:29.129259 | 2017-07-07T08:58:25 | 2017-07-07T08:58:25 | 96,519,606 | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 1,129 |
java
|
package tw.alan.myproject.opp.inheritance;
class Fish { //隱藏完整預設為class Fish extends Object{
//呼叫父親的不帶參數建構子extends Object
String name = "Nemo";
public Fish(){ //@ 因為有不帶參數建構子,所以要建個參數來符合語法
super(); //此為 隱藏預設
System.out.println("default action"); //文字打出來只是為了表示這是預設選項
}
public Fish(String name){ //此為 帶參數建構子
// super(); 一樣會有隱藏預設
this.name = name;
}
public void swim(){
System.out.println(name + ", I can forget lot's of thing.");
}
}
class Shark extends Fish{ //@ Shark繼承了有不帶參數建構子的父類別Fish
public Shark(){
super("Dori"); //此為 隱藏預設
}
public void action(){
super.swim(); //呼叫父類別的成員,系統順序23 >> 5 >> 17 >> 34 >> 35
}
}
public class CallTestInheritanceWithSuperEx1 {
public static void main(String[] args) {
Shark tigerShark = new Shark();
tigerShark.action();
System.out.println("Finished");
}
}
|
[
"[email protected]"
] | |
8ac44e7886d9260950a80930bcf2e8cc62b69652
|
c2d8181a8e634979da48dc934b773788f09ffafb
|
/storyteller/output/mazdasalestool/SetExhibitionReportUsedOrderdetailabnewotherAction.java
|
49d102d4d1b6a3b39d280f0bd197340760e6f404
|
[] |
no_license
|
toukubo/storyteller
|
ccb8281cdc17b87758e2607252d2d3c877ffe40c
|
6128b8d275efbf18fd26d617c8503a6e922c602d
|
refs/heads/master
| 2021-05-03T16:30:14.533638 | 2016-04-20T12:52:46 | 2016-04-20T12:52:46 | 9,352,300 | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 1,793 |
java
|
package net.mazdasalestool.web;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.mazdasalestool.model.*;
import net.mazdasalestool.model.crud.*;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.hibernate.Criteria;
import org.hibernate.Transaction;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.web.context.support.WebApplicationContextUtils;
import net.enclosing.util.HibernateSession;
import net.enclosing.util.HTTPGetRedirection;
public class SetExhibitionReportUsedOrderdetailabnewotherAction extends Action{
public ActionForward execute(
ActionMapping mapping,
ActionForm form,
HttpServletRequest req,
HttpServletResponse res) throws Exception{
Session session = new HibernateSession().currentSession(this
.getServlet().getServletContext());
Transaction transaction = session.beginTransaction();
Criteria criteria = session.createCriteria(ExhibitionReportUsed.class);
criteria.add(Restrictions.idEq(Integer.valueOf(req.getParameter("id"))));
ExhibitionReportUsed exhibitionReportUsed = (ExhibitionReportUsed) criteria.uniqueResult();
exhibitionReportUsed.setOrderdetailabnewother(true);
session.saveOrUpdate(exhibitionReportUsed);
transaction.commit();
session.flush();
new HTTPGetRedirection(req, res, "ExhibitionReportUseds.do", exhibitionReportUsed.getId().toString());
return null;
}
}
|
[
"[email protected]"
] | |
503315b183e6e1b751ea2e17bc054e7664ffea1b
|
e24f7a7be4c2aadb1af903274a580b76f53bab7b
|
/Assignment 1_Peters_jpeters/Hangmandemo.java
|
0216844909e2d1b8763e19a009dea91648a3657a
|
[] |
no_license
|
jr538900/Misc
|
dec63cce2cc4c985231fae7a563353f8d27adc1b
|
ef54af089c9b39dedb91c1ec3404e38a704ef0fe
|
refs/heads/master
| 2021-01-20T04:40:11.363940 | 2017-04-28T15:02:22 | 2017-04-28T15:02:22 | 89,715,435 | 0 | 0 | null | null | null | null |
WINDOWS-1252
|
Java
| false | false | 2,925 |
java
|
/*CSCI 1101 – Assignment 1 – Hangmandemo.java
This program uses a "Hangman" object to simulate the game of Hangman.
<Jeremy Peters> <B00707976> <Feb 6, 2017> */
import java.util.Scanner;
public class Hangmandemo
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
Hangman game = new Hangman(); //creates new hangman object
game.generateSecretWord(); //generates the secret word and corresponding hidden word.
char guess; //Stores the user input.
int count = 0; //Counts the number of guessed elements in the array.
boolean alreadyEntered = false; //Determines whether the guess was already entered by the user.
//An array storing the used answers is created and set to spaces.
char[] usedAns = new char[26];
for(int i = 0; i<26; i++)
usedAns[i] = ' ';
//Introduces user to the game.
System.out.println("Welcome to the hangman game.");
System.out.println("I have a secret Pokemon character name. You have to guess it.");
System.out.println("You are allowed only six incorrect guesses.");
//The variable "keepPlaying" is now set up and used to determine whether the game continues.
boolean keepPlaying = true;
while (keepPlaying)
{
//prints out the hidden word, and prompts user for guess.
System.out.println("\nSecret word: " + new String(game.getDisguisedWord()));
System.out.print("Enter the guess: ");
guess = keyboard.next().charAt(0);
//Checks whether the guess is already entered by the user in a previous turn.
//This array will be filled with letters from lower to higher indices.
for(int j = 0; j<26; j++)
{
//The guess was already entered by the user.
if(usedAns[j] == guess)
{
alreadyEntered = true;
j = 26; //stops loop
}
//The guess was not in the array, and will now take the place of an "empty" element.
else if(usedAns[j] == ' ')
{
alreadyEntered = false;
usedAns[j] = guess;
j = 26; //stops loop
}
//The guess was not in this element, but this element was not "empty".
else
alreadyEntered = false;
//In this case, the loop continues.
}
//This will process the user's guess if the guess was not already made.
if(alreadyEntered)
System.out.println("You already guessed " + guess + ". Choose another letter.");
else
keepPlaying = game.makeGuess(guess);
}
}
}
|
[
"[email protected]"
] | |
7777675bc37f6ad5b1b1eebf5442f976c140c48c
|
0a92071bd9cbd1fbf2380e369954ea167862756d
|
/CollatzConjecture.java
|
ab3a9450d42b0936497fe9a367d28d5f62cee998
|
[] |
no_license
|
Mani9723/ProjectEuler
|
3cefd7a40e8845ad86e96ef421fd0a9e4dc1ddb0
|
0576a6a708d5f17e7b2b89216265eadee45e83b5
|
refs/heads/master
| 2021-09-19T02:44:04.593643 | 2018-07-22T16:34:00 | 2018-07-22T16:34:00 | 131,747,858 | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 1,966 |
java
|
import java.util.ArrayList;
import java.util.Collections;
/**
* https://projecteuler.net/problem=14
* PROBLEM 14:
*
* The following iterative sequence is defined for the set of positive integers:
* n → n/2 (n is even)
* n → 3n + 1 (n is odd)
* Using the rule above and starting with 13, we generate the following sequence:
* 13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1
* It can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms.
* Although it has not been proved yet (Collatz Problem),
* it is thought that all starting numbers finish at 1.
* Which starting number, under one million, produces the longest chain?
*
* @author Mani Shah
* @version 1.0
* @since 2/14/18
*/
public class CollatzConjecture
{
static int count = 0, largestCount = 0;
public static void main(String[] args)
{
int specialNum = 0;
// ArrayList<Integer> chain = new ArrayList<>();
long start = System.currentTimeMillis();
for(int i = 13;i<10000000.;i+=2) {
//System.out.println(i);
collatzConjecture(i);
// if(largestCount<count) {
// largestCount = count;
// specialNum = i;
// }
largestCount = Math.max(largestCount,count);
if(largestCount<count) specialNum = 1;
resetCount();
}
// Collections.sort(chain);
//System.out.println(specialNum + ": " +chain.get(chain.size()-1));
System.out.println((specialNum + ": " + largestCount));
System.out.println(System.currentTimeMillis() - start);
}
private static int collatzConjecture(long testValue)
{
++count;
if(testValue == 1 || testValue ==0)
return count;
return testValue % 2 == 0 ? collatzConjecture(testValue /= 2)
: collatzConjecture(testValue*3 + 1);
// else if(testValue%2==0)
// return collatzConjecture(testValue /=2);
// else
// return collatzConjecture(testValue*3 + 1);
}
private static void resetCount()
{
count = 0;
}
}
|
[
"[email protected]"
] | |
dfbca4b14a762e602b63f1db975dd47fd8fff64f
|
96c431e65a96770ac0c3b5def66ef47b6f812d93
|
/code/pony/src/main/java/com/zzy/pony/crm/controller/IndustryController.java
|
d8856214cd110471ac76446397d7d9b0da81e05a
|
[] |
no_license
|
zhangzuoyi/pony
|
fc3a5fdb7061bda90d2e29fffc694328a49c13b5
|
49d57617fbebbb2bafb7492d401223135c629521
|
refs/heads/master
| 2020-05-19T10:43:43.191026 | 2018-09-09T06:10:40 | 2018-09-09T06:10:40 | 184,972,130 | 1 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 742 |
java
|
package com.zzy.pony.crm.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.zzy.pony.crm.model.Industry;
import com.zzy.pony.crm.service.IndustryService;
@Controller
@RequestMapping(value = "/industry")
public class IndustryController {
@Autowired
private IndustryService service;
@RequestMapping(value="list",method=RequestMethod.GET)
@ResponseBody
public List<Industry> list(){
return service.findAll();
}
}
|
[
"zhangzuoyi@zhangzuoyi-PC"
] |
zhangzuoyi@zhangzuoyi-PC
|
fcdc75b696aef23cc60565d4dd63f1f3e08045eb
|
bbebaa880d979b5005c39aaa16bd03a18038efab
|
/generators/hibernate/tests/org.obeonetwork.dsl.entity.gen.java.hibernate.tests/src/inheritance_associations/org/obeonetwork/sample/inheritanceassociations/Class01ManyBI.java
|
15abd735b2c01bbbc077f588c92aa93a7e9443b4
|
[] |
no_license
|
Novi4ekik92/InformationSystem
|
164baf6ec1da05da2f144787a042d85af81d4caa
|
6387d3cf75efffee0c860ab58f7b8127140a5bb2
|
refs/heads/master
| 2020-12-11T09:07:38.255013 | 2015-01-05T16:52:58 | 2015-01-05T16:52:58 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 3,863 |
java
|
package org.obeonetwork.sample.inheritanceassociations;
// Start of user code for imports
import java.io.Serializable;
import java.util.Collection;
import java.util.HashSet;
// End of user code for imports
/**
* */
public class Class01ManyBI implements Serializable {
/**
* serialVersionUID is used for serialization.
*/
private static final long serialVersionUID = 1L;
/**
* Constant representing the name of the automatic primary key field.
*/
public static final String PROP_ID = "id";
/**
* Constant representing the name of the field fakeAttr.
*/
public static final String PROP_FAKEATTR = "fakeAttr";
/**
* Constant representing the name of the field target.
*/
public static final String PROP_TARGET = "target";
/**
* Automatic primary key.
*/
private String id;
/**
* Field fakeAttr.
*/
protected String fakeAttr;
/**
* Field target.
*/
protected Collection<Class01ManyBIEND> target;
/**
* Default constructor.
*/
public Class01ManyBI() {
super();
this.target = new HashSet<Class01ManyBIEND>();
}
/**
* Return the identifier.
* @return id
*/
public String getId() {
return this.id;
}
/**
* Set a value to parameter id.
* @param id Value of the identifier.
*/
public void setId(final String id) {
this.id = id;
}
/**
* Constructor with all parameters initialized.
* @param fakeAttr.
* @param target.
*/
public Class01ManyBI(String fakeAttr, Collection<Class01ManyBIEND> target) {
this();
this.fakeAttr = fakeAttr;
this.target.addAll(target);
}
/**
* Return fakeAttr.
* @return fakeAttr
*/
public String getFakeAttr() {
return fakeAttr;
}
/**
* Set a value to parameter fakeAttr.
* @param fakeAttr
*/
public void setFakeAttr(final String fakeAttr) {
this.fakeAttr = fakeAttr;
}
/**
* Return target.
* @return target
*/
public Collection<Class01ManyBIEND> getTarget() {
return target;
}
/**
* Set a value to parameter target.
* @param target
*/
public void setTarget(final Collection<Class01ManyBIEND> target) {
this.target = target;
}
/**
* Add a target to the target collection.
* Birectional association : add the current Class_01_Many_BI instance to given target parameter.
* @param targetElt Element to add.
*/
public void addTarget(final Class01ManyBIEND targetElt) {
this.target.add(targetElt);
targetElt.setSource(this);
}
/**
* Remove a target to the target collection.
* Birectionnal association : remove the current Class_01_Many_BI instance to given target parameter.
* @param targetElt Element to remove.
*/
public void removeTarget(final Class01ManyBIEND targetElt) {
this.target.remove(targetElt);
targetElt.setSource(null);
}
/**
* Equality test based on identifiers.
* @param value Value to compare.
* @return Returns true if and only if given object is an instance of
* Class01ManyBI and the given object has the same PK as this
* if the PK is not null or their ids are equal.
*/
public boolean equals(final Object other) {
// Start of user code for equals
if (this == other) {
return true;
}
if (id==null) {
return false;
}
if (!(other instanceof Class01ManyBI)) {
return false;
}
final Class01ManyBI castedOther = (Class01ManyBI) other;
if (id != null && castedOther.getId() != null) {
return id.equals(castedOther.getId());
}
return true;
// End of user code for equals
}
/**
* HashTable code based on identifier hash codes.
* @return hash value.
*/
public int hashCode() {
return id==null ? System.identityHashCode(this) : id.hashCode();
}
// Start of user code for private methods
// TODO Remove this line and add your private methods here
// End of user code for private methods
}
|
[
"[email protected]"
] | |
e0d10325e6b09205fe9e45877515f5855946e98d
|
d1237f01e405debf79d93cfe613fa0e6895992c9
|
/Graphics/tresetteGame/core/src/it/ai/tresette/objects/Card.java
|
ae10d039b149b7a81793ff3849e47485b66b99ac
|
[] |
no_license
|
zamma96/AI-Proj
|
55be93b78b9a0c0fb79af794935beed1ef91ddff
|
02b5c2c9aa7dc844a3803d79c4d0443893d46e86
|
refs/heads/master
| 2020-04-03T10:34:52.067871 | 2018-10-29T10:53:30 | 2018-10-29T10:53:30 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 5,658 |
java
|
package it.ai.tresette.objects;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
public class Card extends Entity {
private String path = "";
private Texture texture;
private TextureRegion texRegion;
private int textureWidth = Constants.TABLE_EDGE/10;
private int textureHeight =(int) ((int) (Constants.TABLE_EDGE/10) * 1.5); //cosi facendo le proporzioni sono 6/9 tra larghezze e altezza
private static final Suit[] intToSuit = {Suit.COPPE, Suit.DENARI, Suit.BASTONI, Suit.SPADE};
private static final Val[] intToVal = {Val.ASSO, Val.DUE, Val.TRE, Val.QUATTRO, Val.CINQUE, Val.SEI, Val.SETTE, Val.FANTE, Val.CAVALLO, Val.RE};
public enum Suit {
COPPE(0,"coppe"), DENARI(10,"oro"), BASTONI(20,"bastoni"), SPADE(30,"spade");
private int val;
private String pathString;
private Suit(int value,String path) { this.val = value; this.pathString = path;}
private Suit(int value) {this.val = value;}
public int getVal() { return val; }
@Override
public String toString(){return pathString; }
}
public enum Val
{
//la logica e': stringa per il path della texture - numero della carta - potenza della carta - valore in punti della carta
ASSO("uno",0,7,3), DUE("due",1,8,1), TRE("tre",2,9,1), QUATTRO("quattro",3,0,0), CINQUE("cinque",4,1,0), SEI("sei",5,2,0), SETTE("sette",6,3,0), FANTE("fante",7,4,1), CAVALLO("cavaliere",8,5,1), RE("re",9,6,1);
/**
* the int representation of the card; where Asso is 0 and Re is 9
*/
private int cardNr;
/**
* the dominance of each Card where Dominance(TRE) = 9 and Dominance(Quattro) = 0
*/
private int dominanza;
/**
* the value in points of each Card where Points(ASSO) = 3 and Points(TRE) = 1 and point(CINQUE) = 0
*/
private int punteggio;
/**
* The string used for constructing the path of the texture
*/
private String stringPath;
private Val(String stringPath,int cardNr, int dominanza, int punteggio) {this.stringPath = stringPath; this.cardNr = cardNr; this.dominanza = dominanza; this.punteggio = punteggio; }
private Val(int cardNr) { this.cardNr = cardNr;}
public int getCardNr() {return this.cardNr;}
public int getDominanza() {return this.dominanza;}
public int getPoints() {return this.punteggio;}
@Override
public String toString(){return this.stringPath;}
public int moreDominant(Val other)
{
return this.dominanza - other.getDominanza();
}
}
private Suit suit;
private Val val;
/**
* Return the card represented by the number cardNr.
* 0-9 -> Coppe card from Asso(0) to Re(9)
* 10-19 -> Denari // //
* 20-29 -> Bastoni // //
* 30-39 -> Spade // //
* @param cardNr
*/
public Card(int cardNr)
{
if(cardNr < 0 || cardNr > 39) return;
this.suit = intToSuit[cardNr/10];
this.val = intToVal[cardNr%10];
this.path = "cards/"+suit.toString() + "_" + val.toString() + ".png";
this.texture = new Texture(this.path);
texRegion = new TextureRegion(texture);
}
/**
* Return the card with Suit suit and Val val;
* @param suit the suit of the card
* @param val the val of the card
*/
public Card(Suit suit, Val val)
{
this.suit = suit;
this.val = val;
this.path = "cards/"+suit.toString() + "_" + val.toString() + ".png";
this.texture = new Texture(this.path);
texRegion = new TextureRegion(texture);
}
/**
* this method draws the card in the coordinates x,y
* @param batch
* @param x
*/
public void draw(SpriteBatch batch, int x, int y)
{
//batch.draw(texture, (float)x, (float)y, 0f, 0f, (float)textureWidth, (float)textureHeight, 1f, 1f);
batch.draw(texRegion, x, y, 0, 0, textureWidth, textureHeight, 1, 1, 0);
}
/**
* this method draws the card in the coordinates x,y and with rotation rot
* @param batch
* @param x
*/
public void draw(SpriteBatch batch, int x ,int y,int rot)
{
}
public int toInt()
{
return this.suit.getVal() + this.val.getCardNr();
}
/**
* returns the suit of the card represented by an int
* @return
*/
public int getIntSuit()
{
return this.suit.getVal();
}
public int getPoints() {return this.val.getPoints();}
public int getCardnr() {return this.val.getCardNr()+this.suit.getVal();}
@Override
public boolean equals(Object other)
{
if(this == other) return true;
if(!(other instanceof Card)) return false;
Card temp = (Card)other;
return(this.suit.equals(temp.suit) && this.val.equals(temp.val));
}
public int compareTo(Card dominatingCard) {
if(this.suit.equals(dominatingCard.suit))
return this.val.moreDominant(dominatingCard.val);
return 0;
}
public String toString()
{
return this.val.toString()+" di "+this.suit.toString();
}
public static void main(String[] args) {
//main for tests purpose
// Card a = new Card(Suit.BASTONI, Val.TRE);
// System.out.println(a.suit.getVal() + a.val.getCardNr() );
// System.out.println("the path is "+a.suit.toString()+"_"+a.val.toString()+".png");
Card b = new Card(12);
System.out.println(b.suit.getVal() + b.val.getCardNr() );
System.out.println("the path is "+b.suit.toString()+"_"+b.val.toString()+".png");
System.out.println(b.val.getPoints());
System.out.println(b.equals(b));
System.out.println(b.path);
// System.out.println(b.toString());
}
}
|
[
"[email protected]"
] | |
43c2694132d473a980f4f05bb3d23d950f5e4eb3
|
d58bfa05ccef9359d62179d3966b3d37601b02a5
|
/poly-gateway/src/test/java/com/unidev/polygateway/GatewayApplicationTests.java
|
60e91c17aa4e713891ad77e1bc969841a5a8ada6
|
[
"Apache-2.0"
] |
permissive
|
universal-development/poly-gateway
|
17a0aaa588da3080e68d27eb117953bc0a6e8fe1
|
d084c48f7468a3348c49be8394b5a4fb8cc6c80b
|
refs/heads/master
| 2021-05-02T00:51:32.502319 | 2017-02-18T21:05:44 | 2017-02-18T21:05:44 | 78,410,591 | 0 | 1 | null | 2017-01-25T09:53:55 | 2017-01-09T08:49:10 |
Java
|
UTF-8
|
Java
| false | false | 340 |
java
|
package com.unidev.polygateway;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class GatewayApplicationTests {
@Test
public void contextLoads() {
}
}
|
[
"[email protected]"
] | |
2ed1edec5ef533560457175c553de84b9408ef2a
|
48cf9da1b99de83ae8eae757769952a8165472e3
|
/controller/src/main/java/com/artronics/chapar/controller/sdwn/packet/SdwnPacket.java
|
e293431f712161f20a5679d0bfac74b2f0dc233e
|
[] |
no_license
|
artronics/chapar1
|
c630cebd6a5b663aba8a2141a6c30bdd5e85af10
|
867be2123500c42c2f282e1f25937076b9b5653e
|
refs/heads/master
| 2021-05-30T19:44:11.029855 | 2016-01-25T23:30:12 | 2016-01-25T23:30:12 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 854 |
java
|
package com.artronics.chapar.controller.sdwn.packet;
import java.util.List;
public interface SdwnPacket {
Integer HEADER_LEN = 10;
Integer DEF_NET_ID=1;
Integer DEF_MAX_TTL=20;
List<Integer> getContent();
enum ByteIndex
{
LENGTH(0),
NET_ID(1),
SOURCE_H(2),
SOURCE_L(3),
DESTINATION_H(4),
DESTINATION_L(5),
TYPE(6),
TTL(7),
NEXT_HOP_H(8),
NEXT_HOP_L(9),
// DISTANCE(10),
BATTERY(11),
// NEIGHBOUR(12),
// START_TIME_H(11),
// START_TIME_L(12),
// STOP_TIME_H(13),
// STOP_TIME_L(14),;
;
private int value;
ByteIndex(int value)
{
this.value = value;
}
public int getValue()
{
return value;
}
}
}
|
[
"[email protected]"
] | |
e22059c51882d92f0c4563d1f8e1902e5f7d0ad6
|
0d0b842c0f04691a8ffebd071ca77a501c1d85fc
|
/net/minecraft/src/SpawnerAnimals.java
|
75ec4f52522a44789ba54a2291a0e5e289c168ad
|
[] |
no_license
|
SoupCS/BiboranV4
|
be359a187730c38ddb85dc7310188de6176a787e
|
96dca631a816757104697826f5564b9bd185074c
|
refs/heads/main
| 2023-04-28T18:43:03.778356 | 2021-05-21T15:41:04 | 2021-05-21T15:41:04 | 447,933,385 | 1 | 0 | null | 2022-01-14T10:48:14 | 2022-01-14T10:48:14 | null |
UTF-8
|
Java
| false | false | 14,027 |
java
|
package net.minecraft.src;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
public final class SpawnerAnimals
{
/** The 17x17 area around the player where mobs can spawn */
private static HashMap eligibleChunksForSpawning = new HashMap();
/** An array of entity classes that spawn at night. */
protected static final Class[] nightSpawnEntities = new Class[] {EntitySpider.class, EntityZombie.class, EntitySkeleton.class};
/**
* Given a chunk, find a random position in it.
*/
protected static ChunkPosition getRandomSpawningPointInChunk(World par0World, int par1, int par2)
{
Chunk var3 = par0World.getChunkFromChunkCoords(par1, par2);
int var4 = par1 * 16 + par0World.rand.nextInt(16);
int var5 = par2 * 16 + par0World.rand.nextInt(16);
int var6 = par0World.rand.nextInt(var3 == null ? par0World.getActualHeight() : var3.getTopFilledSegment() + 16 - 1);
return new ChunkPosition(var4, var6, var5);
}
/**
* adds all chunks within the spawn radius of the players to eligibleChunksForSpawning. pars: the world,
* hostileCreatures, passiveCreatures. returns number of eligible chunks.
*/
public static final int findChunksForSpawning(WorldServer par0WorldServer, boolean par1, boolean par2, boolean par3)
{
if (!par1 && !par2)
{
return 0;
}
else
{
eligibleChunksForSpawning.clear();
int var4;
int var7;
for (var4 = 0; var4 < par0WorldServer.playerEntities.size(); ++var4)
{
EntityPlayer var5 = (EntityPlayer)par0WorldServer.playerEntities.get(var4);
int var6 = MathHelper.floor_double(var5.posX / 16.0D);
var7 = MathHelper.floor_double(var5.posZ / 16.0D);
byte var8 = 8;
for (int var9 = -var8; var9 <= var8; ++var9)
{
for (int var10 = -var8; var10 <= var8; ++var10)
{
boolean var11 = var9 == -var8 || var9 == var8 || var10 == -var8 || var10 == var8;
ChunkCoordIntPair var12 = new ChunkCoordIntPair(var9 + var6, var10 + var7);
if (!var11)
{
eligibleChunksForSpawning.put(var12, Boolean.valueOf(false));
}
else if (!eligibleChunksForSpawning.containsKey(var12))
{
eligibleChunksForSpawning.put(var12, Boolean.valueOf(true));
}
}
}
}
var4 = 0;
ChunkCoordinates var32 = par0WorldServer.getSpawnPoint();
EnumCreatureType[] var33 = EnumCreatureType.values();
var7 = var33.length;
for (int var34 = 0; var34 < var7; ++var34)
{
EnumCreatureType var35 = var33[var34];
if ((!var35.getPeacefulCreature() || par2) && (var35.getPeacefulCreature() || par1) && (!var35.getAnimal() || par3) && par0WorldServer.countEntities(var35.getCreatureClass()) <= var35.getMaxNumberOfCreature() * eligibleChunksForSpawning.size() / 256)
{
Iterator var36 = eligibleChunksForSpawning.keySet().iterator();
label110:
while (var36.hasNext())
{
ChunkCoordIntPair var37 = (ChunkCoordIntPair)var36.next();
if (!((Boolean)eligibleChunksForSpawning.get(var37)).booleanValue())
{
ChunkPosition var38 = getRandomSpawningPointInChunk(par0WorldServer, var37.chunkXPos, var37.chunkZPos);
int var13 = var38.x;
int var14 = var38.y;
int var15 = var38.z;
if (!par0WorldServer.isBlockNormalCube(var13, var14, var15) && par0WorldServer.getBlockMaterial(var13, var14, var15) == var35.getCreatureMaterial())
{
int var16 = 0;
int var17 = 0;
while (var17 < 3)
{
int var18 = var13;
int var19 = var14;
int var20 = var15;
byte var21 = 6;
SpawnListEntry var22 = null;
int var23 = 0;
while (true)
{
if (var23 < 4)
{
label103:
{
var18 += par0WorldServer.rand.nextInt(var21) - par0WorldServer.rand.nextInt(var21);
var19 += par0WorldServer.rand.nextInt(1) - par0WorldServer.rand.nextInt(1);
var20 += par0WorldServer.rand.nextInt(var21) - par0WorldServer.rand.nextInt(var21);
if (canCreatureTypeSpawnAtLocation(var35, par0WorldServer, var18, var19, var20))
{
float var24 = (float)var18 + 0.5F;
float var25 = (float)var19;
float var26 = (float)var20 + 0.5F;
if (par0WorldServer.getClosestPlayer((double)var24, (double)var25, (double)var26, 24.0D) == null)
{
float var27 = var24 - (float)var32.posX;
float var28 = var25 - (float)var32.posY;
float var29 = var26 - (float)var32.posZ;
float var30 = var27 * var27 + var28 * var28 + var29 * var29;
if (var30 >= 576.0F)
{
if (var22 == null)
{
var22 = par0WorldServer.spawnRandomCreature(var35, var18, var19, var20);
if (var22 == null)
{
break label103;
}
}
EntityLiving var39;
try
{
var39 = (EntityLiving)var22.entityClass.getConstructor(new Class[] {World.class}).newInstance(new Object[] {par0WorldServer});
}
catch (Exception var31)
{
var31.printStackTrace();
return var4;
}
var39.setLocationAndAngles((double)var24, (double)var25, (double)var26, par0WorldServer.rand.nextFloat() * 360.0F, 0.0F);
if (var39.getCanSpawnHere())
{
++var16;
par0WorldServer.spawnEntityInWorld(var39);
creatureSpecificInit(var39, par0WorldServer, var24, var25, var26);
if (var16 >= var39.getMaxSpawnedInChunk())
{
continue label110;
}
}
var4 += var16;
}
}
}
++var23;
continue;
}
}
++var17;
break;
}
}
}
}
}
}
}
return var4;
}
}
/**
* Returns whether or not the specified creature type can spawn at the specified location.
*/
public static boolean canCreatureTypeSpawnAtLocation(EnumCreatureType par0EnumCreatureType, World par1World, int par2, int par3, int par4)
{
if (par0EnumCreatureType.getCreatureMaterial() == Material.water)
{
return par1World.getBlockMaterial(par2, par3, par4).isLiquid() && par1World.getBlockMaterial(par2, par3 - 1, par4).isLiquid() && !par1World.isBlockNormalCube(par2, par3 + 1, par4);
}
else if (!par1World.doesBlockHaveSolidTopSurface(par2, par3 - 1, par4))
{
return false;
}
else
{
int var5 = par1World.getBlockId(par2, par3 - 1, par4);
return var5 != Block.bedrock.blockID && !par1World.isBlockNormalCube(par2, par3, par4) && !par1World.getBlockMaterial(par2, par3, par4).isLiquid() && !par1World.isBlockNormalCube(par2, par3 + 1, par4);
}
}
/**
* determines if a skeleton spawns on a spider, and if a sheep is a different color
*/
private static void creatureSpecificInit(EntityLiving par0EntityLiving, World par1World, float par2, float par3, float par4)
{
par0EntityLiving.initCreature();
}
/**
* Called during chunk generation to spawn initial creatures.
*/
public static void performWorldGenSpawning(World par0World, BiomeGenBase par1BiomeGenBase, int par2, int par3, int par4, int par5, Random par6Random)
{
List var7 = par1BiomeGenBase.getSpawnableList(EnumCreatureType.creature);
if (!var7.isEmpty())
{
while (par6Random.nextFloat() < par1BiomeGenBase.getSpawningChance())
{
SpawnListEntry var8 = (SpawnListEntry)WeightedRandom.getRandomItem(par0World.rand, var7);
int var9 = var8.minGroupCount + par6Random.nextInt(1 + var8.maxGroupCount - var8.minGroupCount);
int var10 = par2 + par6Random.nextInt(par4);
int var11 = par3 + par6Random.nextInt(par5);
int var12 = var10;
int var13 = var11;
for (int var14 = 0; var14 < var9; ++var14)
{
boolean var15 = false;
for (int var16 = 0; !var15 && var16 < 4; ++var16)
{
int var17 = par0World.getTopSolidOrLiquidBlock(var10, var11);
if (canCreatureTypeSpawnAtLocation(EnumCreatureType.creature, par0World, var10, var17, var11))
{
float var18 = (float)var10 + 0.5F;
float var19 = (float)var17;
float var20 = (float)var11 + 0.5F;
EntityLiving var21;
try
{
var21 = (EntityLiving)var8.entityClass.getConstructor(new Class[] {World.class}).newInstance(new Object[] {par0World});
}
catch (Exception var23)
{
var23.printStackTrace();
continue;
}
var21.setLocationAndAngles((double)var18, (double)var19, (double)var20, par6Random.nextFloat() * 360.0F, 0.0F);
par0World.spawnEntityInWorld(var21);
creatureSpecificInit(var21, par0World, var18, var19, var20);
var15 = true;
}
var10 += par6Random.nextInt(5) - par6Random.nextInt(5);
for (var11 += par6Random.nextInt(5) - par6Random.nextInt(5); var10 < par2 || var10 >= par2 + par4 || var11 < par3 || var11 >= par3 + par4; var11 = var13 + par6Random.nextInt(5) - par6Random.nextInt(5))
{
var10 = var12 + par6Random.nextInt(5) - par6Random.nextInt(5);
}
}
}
}
}
}
}
|
[
"[email protected]"
] | |
5ee8b99800ce7227a1f6ce96e186064f0f9b540d
|
f5d554ab665c875ce1e816662bb9bf7dc6e568d2
|
/SmbDemo/app/src/main/java/com/ider/smbtest/SmbUtil.java
|
ea06199ad23c3cd1c415d966e374444a75bad1ec
|
[] |
no_license
|
ericzhaowei/SmbDemo
|
af61258d75da8bb30d4ec64742ac540a580c213b
|
3c72576ae161d29b624f26945e7faa5d738e0500
|
refs/heads/master
| 2021-01-18T20:30:11.855224 | 2016-10-28T09:15:44 | 2016-10-28T09:15:44 | 72,192,613 | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 26,106 |
java
|
package com.ider.smbtest;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.InterfaceAddress;
import java.net.MalformedURLException;
import java.net.NetworkInterface;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Vector;
import java.util.concurrent.Exchanger;
import jcifs.smb.SmbFile;
/**
* Created by ider-eric on 2016/7/13.
*/
public class SmbUtil {
static boolean DEBUG = true;
static String TAG = "SmbUtil";
private final int THREAD_MAX = 16;
private int startThread, overThread;
private Context context;
private Handler mHandler;
private SharedPreferences preferences;
private boolean searchInterrupt = false;
public static final String SMB_MOUNTPOINT_ROOT = "/data/smb";
public static final String SHELL_ROOT = "/data/etc";
public static final String SHELL_PATH = "/data/etc/cifsmanager.sh";
public static final String SHELL_LOG_PATH = "/data/etc/log";
public static final String SHELL_HEAD = "#!/system/bin/sh";
private Map<String, MyFile> MountSmbMap;
private static void LOG(String str) {
if (DEBUG) {
Log.d(TAG, str);
}
}
public SmbUtil(Context context, Handler mHandler) {
this.context = context;
this.mHandler = mHandler;
preferences = context.getSharedPreferences("smb_sp", Context.MODE_PRIVATE);
MountSmbMap = new HashMap<>();
}
public void stopSearch() {
this.searchInterrupt = true;
}
public void searchSmbHost() {
searchInterrupt = false;
startThread = 0;
overThread = 0;
LOG("start search..");
Vector<Vector<InetAddress>> vectorList = getsubnetAddress();
for (int i = 0; i < vectorList.size(); i++) {
if (searchInterrupt) return;
Vector<InetAddress> vector = vectorList.get(i);
for (int j = 0; j < vector.size(); ) {
if (searchInterrupt) return;
int activeThread = startThread - overThread;
if (activeThread < THREAD_MAX) {
InetAddress pingIp = vector.get(j);
LOG("PING : " + pingIp.getHostAddress());
Thread scan = new Thread(new ConnectHost(pingIp));
scan.setPriority(10);
scan.start();
startThread++;
j++;
} else {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
// 根据InterfaceAddress的长度获取到mask子网掩码
public String calcMaskByPrefixLength(int length) {
int mask = -1 << (32 - length);
int partsNum = 4;
int bitsOfPart = 8;
int maskParts[] = new int[partsNum];
int selector = 0x000000ff;
for (int i = 0; i < maskParts.length; i++) {
int pos = maskParts.length - 1 - i;
maskParts[pos] = (mask >> (i * bitsOfPart)) & selector;
}
String result = "";
result = result + maskParts[0];
for (int i = 1; i < maskParts.length; i++) {
result = result + "." + maskParts[i];
}
return result;
}
public ArrayList<String> getIpAndMask() {
ArrayList<String> ipAndMastList = new ArrayList<>();
try {
Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces();
while (en.hasMoreElements()) {
NetworkInterface intf = en.nextElement();
List<InterfaceAddress> listIAddr = intf.getInterfaceAddresses();
Iterator<InterfaceAddress> IAddrIterator = listIAddr.iterator();
while (IAddrIterator.hasNext()) {
InterfaceAddress IAddr = IAddrIterator.next();
InetAddress inetAddress = IAddr.getAddress();
// 非127.0.0.1...等
if (!inetAddress.isLoopbackAddress()) {
String ip = inetAddress.getHostAddress();
String subnetmask = calcMaskByPrefixLength(IAddr.getNetworkPrefixLength());
String ipAndMask = ip + ";" + subnetmask;
ipAndMastList.add(ipAndMask);
}
}
}
} catch (SocketException e) {
e.printStackTrace();
}
return ipAndMastList;
}
// 获取此设备所在网段下所有的ip地址
public Vector<Vector<InetAddress>> getsubnetAddress() {
int[] hostParts = new int[4];
int[] maskParts = new int[4];
int[] hostStart = new int[4];
int[] hostEnd = new int[4];
Vector<Vector<InetAddress>> vectorList = new Vector<>();
ArrayList<String> ipAndMaskList = getIpAndMask();
for (int i = 0; i < ipAndMaskList.size(); i++) {
String[] maskAndIpSplit = ipAndMaskList.get(i).split(";");
String host = maskAndIpSplit[0];
String subnetmask = maskAndIpSplit[1];
String[] split = host.split("\\.");
if (split.length != 4) {
continue;
}
hostParts[0] = Integer.parseInt(split[0]);
hostParts[1] = Integer.parseInt(split[1]);
hostParts[2] = Integer.parseInt(split[2]);
hostParts[3] = Integer.parseInt(split[3]);
split = subnetmask.split("\\.");
maskParts[0] = Integer.parseInt(split[0]);
maskParts[1] = Integer.parseInt(split[1]);
maskParts[2] = Integer.parseInt(split[2]);
maskParts[3] = Integer.parseInt(split[3]);
hostStart[0] = maskParts[0] & hostParts[0]; //1&[0] = [0] 192
hostStart[1] = maskParts[1] & hostParts[1]; //1&[1] = [1] 168
hostStart[2] = maskParts[2] & hostParts[2]; //1&[2] = [2] 1
hostStart[3] = maskParts[3] & hostParts[3]; //0&[3] = 0 0
hostEnd[0] = hostParts[0] | (maskParts[0] ^ 0XFF); //[0]|0 = [0] 192
hostEnd[1] = hostParts[1] | (maskParts[1] ^ 0XFF); //[1]|0 = [1] 168
hostEnd[2] = hostParts[2] | (maskParts[2] ^ 0XFF); //[2]|0 = [2] 1
hostEnd[3] = hostParts[3] | (maskParts[3] ^ 0XFF); //[3]|1 = 0xff 255
Vector<InetAddress> vector = new Vector<>();
for (int a = hostStart[0]; a <= hostEnd[0]; a++) {
for (int b = hostStart[1]; b <= hostEnd[1]; b++) {
for (int c = hostStart[2]; c <= hostEnd[2]; c++) {
for (int d = hostStart[3]; d <= hostEnd[3]; d++) {
byte[] inetAddrhost = new byte[4];
inetAddrhost[0] = (byte) a;
inetAddrhost[1] = (byte) b;
inetAddrhost[2] = (byte) c;
inetAddrhost[3] = (byte) d;
try {
InetAddress inetAddress = InetAddress.getByAddress(inetAddrhost);
vector.add(inetAddress);
// LOG("getsubnetAddress : " + inetAddress.getHostAddress());
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
}
}
}
vectorList.add(vector);
}
return vectorList;
}
private class ConnectHost implements Runnable {
private InetAddress host; // ping的地址,如ping 192.168.1.250
public ConnectHost(InetAddress host) {
this.host = host;
}
@Override
public void run() {
if (ping(host.getHostAddress())) {
if (searchInterrupt) return;
smbSort(host);
}
overThread++;
}
}
public boolean ping(String ip) {
try {
Socket server = new Socket();
InetSocketAddress address = new InetSocketAddress(ip,
445);
server.connect(address, 4000);
server.close();
} catch (UnknownHostException e) {
try {
Socket server = new Socket();
InetSocketAddress address = new InetSocketAddress(ip,
139);
server.connect(address, 4000);
server.close();
} catch (UnknownHostException e1) {
return false;
} catch (IOException e1) {
return false;
}
return true;
} catch (IOException e) {
try {
Socket server = new Socket();
InetSocketAddress address = new InetSocketAddress(ip,
139);
server.connect(address, 4000);
server.close();
} catch (UnknownHostException e1) {
return false;
} catch (IOException e1) {
return false;
}
return true;
}
return true;
}
// 同步块,将SmbFile加入集合
public synchronized void smbSort(InetAddress file) {
// handler.send..
LOG("ping OK : " + file.getHostAddress());
Message msg = new Message();
msg.what = Constant.SCAN_UPDATE;
msg.obj = Constant.mDirSmb + "/" + file.getHostAddress();
mHandler.sendMessage(msg);
}
public String checkAndMount(MyFile smbinfo) {
String path = smbinfo.getmPath().substring(4);
String[] smbSplit = path.split("/");
String smbpath = "//"+smbSplit[0]+"/"+smbSplit[1];
ArrayList<String> mountlist = SmbUtil.getMountMsg();
ArrayList<String> cifslist = new ArrayList<>();
ArrayList<String> mountpointlist = new ArrayList<>();
for(String str : mountlist) {
String[] split = str.split(" ");
if(split[2].equals("cifs")) {
cifslist.add(split[0].replace("\\"+"040", " ").replace("\\"+"134", "/"));
mountpointlist.add(split[1]);
}
}
if(cifslist.contains(smbpath)) {
String mountpoint = mountpointlist.get(cifslist.indexOf(smbpath));
smbinfo.setmMountpoint(mountpoint);
File files = new File(mountpoint);
LOG("file read:" + files.canRead()+" file exists:"+files.exists()+" file list:"+files.list().length);
if(!files.exists() || !files.canRead() || files.list() == null || files.list().length == 0) {
LOG("remote sharefolder can not read or null");
umount(mountpoint);
} else {
smbinfo.setmIsMount(true);
return mountpoint;
}
}
String result = mount(smbinfo);
if(result == null) {
ArrayList<String> mountlist1 = getMountMsg();
ArrayList<String> cifslist1 = new ArrayList<>();
for(String str: mountlist1) {
String split[] = str.split(" ");
if(split[2].equals("cifs")) {
cifslist1.add(split[0].replace("\\"+"040", " ").replace("\\"+"134", "/"));
}
}
if(!cifslist1.contains(smbpath)) {
smbinfo.setmIsMount(false);
Toast.makeText(context, "mount failed", Toast.LENGTH_SHORT).show();
String mountPoint = smbinfo.getmMountpoint();
SmbUtil.deleteMountPoint(mountPoint);
return null;
}
String mountPoint = smbinfo.getmMountpoint();
smbinfo.setmIsMount(true);
MountSmbMap.put(mountPoint, smbinfo);
Toast.makeText(context, "mount success", Toast.LENGTH_SHORT).show();
return mountPoint;
} else {
Toast.makeText(context, "mount failed " + result, Toast.LENGTH_SHORT).show();
return null;
}
}
public String umount(String mountpoint){
String allline;
String mountPoint = mountpoint;
if (!new File(mountPoint.replace("\"", "")).exists()){
allline = "mount point lost";
return allline;
}
try
{
String command = "busybox umount -fl "+mountPoint+" > "+SHELL_LOG_PATH+" 2>&1";
LOG("umount command:"+command);
String []cmd = {SHELL_HEAD,command};
if (!ShellFileWrite(cmd)){
allline = "write shell error";
return allline;
}
}catch (Exception ex){
System.out.println(ex.getMessage());
allline = "write shell error";
return allline;
}
PropertyReader.set("ctl.start", "cifsmanager");
while(true)
{
String mount_rt = PropertyReader.getString("init.svc.cifsmanager");
if(mount_rt != null && mount_rt.equals("stopped"))
{
allline = ShellLogRead();
break;
}
try
{
Thread.sleep(1000);
}catch(Exception ex){
Log.e(TAG, "Exception: " + ex.getMessage());
allline = "mount exception";
}
}
if(allline == null){
if(!deleteMountPoint(mountpoint)){
allline = "mount point delete error";
}
}
return allline;
}
private String mount(MyFile smbinfo) {
String username = smbinfo.getmUsername();
String password = smbinfo.getmPassword();
boolean anonymous = smbinfo.ismAnonymous();
String smbPath = "//" + smbinfo.getmPath().substring(4);
String line = null;
String allline = null;
String mountPoint;
if (smbinfo.getmMountpoint() != null) {
mountPoint = smbinfo.getmMountpoint();
} else {
SimpleDateFormat sf = new SimpleDateFormat("yyMMddHHmmss");
mountPoint = Constant.mSmbMountPoint + sf.format(new Date());
}
StringBuilder smbpathbuilder = new StringBuilder("\"");
smbpathbuilder.append(smbPath);
smbpathbuilder.append("\"");
String newSmbpath = smbpathbuilder.toString();
Log.i(TAG, "smbPath = " + newSmbpath);
File shellDir = new File(SHELL_ROOT);
if (!shellDir.exists()) {
if (!shellDir.mkdirs()) {
allline = "mkdir shell error";
return allline;
}
}
String result = null;
File shellLog = new File(SHELL_LOG_PATH);
if (!shellLog.exists()) {
try {
shellLog.createNewFile();
shellLog.setExecutable(true);
} catch (IOException e) {
e.printStackTrace();
result = "mount shell log fail";
return result;
}
}
if (anonymous) {
try {
String command = "busybox mount -t cifs -o iocharset=utf8,username=guest,uid=1000,gid=1015,file_mode=0775,dir_mode=0775,rw "
+ newSmbpath + " " + mountPoint + " > " + SHELL_LOG_PATH + " 2>&1";
LOG("mount command : " + command);
String[] cmd = {SHELL_HEAD, command};
if(!ShellFileWrite(cmd)) {
allline = "write shell file fail";
return allline;
}
} catch (Exception e) {
e.printStackTrace();
allline = "write shell file fail";
return allline;
}
} else {
try {
String user = username;
String pass = password;
if(username.contains(" ")) {
StringBuilder userbuilder = new StringBuilder("\"");
userbuilder.append(username);
userbuilder.append("\"");
user = userbuilder.toString();
}
if(password.contains(" ")) {
StringBuilder passbuilder = new StringBuilder("\"");
passbuilder.append(password);
passbuilder.append("\"");
pass = passbuilder.toString();
}
String command = "busybox mount -t cifs -o iocharset=utf8,username="+user+",password="+pass+
",uid=1000,gid=1015,file_mode=0775,dir_mode=0775,rw "+newSmbpath+" "+mountPoint+" > "+SHELL_LOG_PATH+" 2>&1";
LOG("mount command : " + command);
String[] cmd = {SHELL_HEAD, command};
if(!ShellFileWrite(cmd)) {
allline = "write shell file fail";
return allline;
}
} catch (Exception e) {
e.printStackTrace();
allline = "write shell file fail";
return allline;
}
}
if(!creatMountPoint(mountPoint)) {
allline = "mount point create error";
return allline;
}
int timeout = 0;
while(true) {
if(timeout > 2) {
break;
}
allline = null;
PropertyReader.set("ctl.start", "cifsmanager");
try{
Thread.sleep(3000);
} catch(Exception e) {
e.printStackTrace();
allline = "mount error";
timeout++;
continue;
}
String mount_rt = PropertyReader.getString("init.svc.cifsmanager");
LOG("mount runtime:" + mount_rt + " timeout:"+timeout);
if(mount_rt != null && mount_rt.equals("running")) {
allline = "connect timeout";
PropertyReader.set("ctl.stop", "cifsmanager");
timeout++;
continue;
}
if(mount_rt != null && mount_rt.equals("stopped")) {
allline = ShellLogRead();
if(allline == null) {
break;
}
}
timeout++;
}
if(allline != null) {
deleteMountPoint(mountPoint);
} else {
smbinfo.setmMountpoint(mountPoint);
}
return allline;
}
public boolean creatMountPoint(String path){
try{
File root_smb = new File(Constant.mSmbMountPoint);
if(!root_smb.exists()){
if(!root_smb.mkdirs()){
return false;
}else{
root_smb.setReadable(true,false);
root_smb.setExecutable(true, false);
}
}
String abpath = new String(path).replace("\"", "");
if(!new File(abpath).exists()){
if(!new File(abpath).mkdirs()){
return false;
}else{
LOG("creat mount point:"+abpath);
}
}
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return true;
}
private static String ShellLogRead(){
String result = null;
File shellLog = new File(SHELL_LOG_PATH);
if (!shellLog.exists()){
try {
shellLog.createNewFile();
shellLog.setExecutable(true);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
result = "create shell log fail";
return result;
}
}
try {
BufferedReader buffrd = new BufferedReader(new FileReader(shellLog));
String str = null;
while((str=buffrd.readLine())!=null){
System.out.println(str);
if(result == null){
result = str+"\n";
}else{
result = result + str + "\n";
}
}
buffrd.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
result = "read shell log fail";
return result;
}
return result;
}
private static boolean ShellFileWrite(String []cmd){
File shell = new File(SHELL_PATH);
if (!shell.exists()){
try {
shell.createNewFile();
shell.setExecutable(true);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}
}
try {
BufferedWriter buffwr = new BufferedWriter(new FileWriter(shell));
for (String str:cmd){
buffwr.write(str);
buffwr.newLine();
buffwr.flush();
}
buffwr.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}
return true;
}
public ArrayList<String> callCommand(String command) {
Process process;
ArrayList<String> processList = new ArrayList<>();
try {
LOG("mount call command:" + command);
process = Runtime.getRuntime().exec("ls");
BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = input.readLine()) != null) {
processList.add(line);
}
input.close();
} catch (IOException e) {
e.printStackTrace();
}
return processList;
}
public static boolean deleteMountPoint(String path){
String abpath = new String(path).replace("\"", "");
if(new File(abpath).exists()){
if (!new File(abpath).delete()){
return false;
}else{
LOG("delete mount point:"+abpath);
}
}
return true;
}
public static ArrayList<String> getMountMsg() {
String line;
ArrayList<String> strlist = new ArrayList<>();
try {
Process pro = Runtime.getRuntime().exec("mount");
BufferedReader br = new BufferedReader(new InputStreamReader(pro.getInputStream()));
while ((line = br.readLine()) != null) {
strlist.add(line);
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
return strlist;
}
public void getContentBySmbhost(MyFile file) {
final String mPath = file.getmPath();
final String username = file.getmUsername();
final String password = file.getmPassword();
final boolean anonymous = file.ismAnonymous();
// host like SMB/IP
new Thread(new Runnable() {
@Override
public void run() {
String host = mPath.substring(4);
if (!ping(host)) {
mHandler.sendEmptyMessage(Constant.ITEM_CONNECT_FAILED);
return;
}
try {
SmbFile smbfile;
if (anonymous) {
smbfile = new SmbFile("smb://guest:@" + host + "/");
} else {
smbfile = new SmbFile("smb://" + username + ":" + password + "@" + host + "/");
}
ArrayList<MyFile> contentPaths = new ArrayList<>();
for (String share : smbfile.list()) {
Log.i(TAG, share);
if (!share.endsWith("$")) {
String contentPath = Constant.mDirSmb + "/" + host + "/" + share;
contentPaths.add(new MyFile(contentPath));
}
}
if (!anonymous) {
SharedPreferences.Editor editor = preferences.edit();
editor.putString("user" + host, username);
editor.putString("password" + host, password);
editor.putBoolean("anonymous" + host, false);
editor.commit();
}
Message msg = new Message();
msg.what = Constant.ITEM_CONTENT;
msg.obj = contentPaths;
mHandler.sendMessage(msg);
} catch (Exception e) {
if (e.getMessage().contains("unknown user name or bad password")) {
Message msg = new Message();
msg.obj = mPath;
msg.what = Constant.ITEM_WRONG_USER;
mHandler.sendMessage(msg);
}
}
}
}).start();
}
}
|
[
"[email protected]"
] | |
cfec260e0313044ba377dba777f3afe6af0a90ad
|
7f33b71f7fe4b4db66b8d5e50c037c89d6e5723b
|
/app/src/main/java/com/example/hppav/kamera/MainActivity.java
|
5fb3922315538b0aa383dbbbdb49284a6ae3718c
|
[] |
no_license
|
kaveenabeywansa/kamera
|
466264b590dd939cf55f51c4f0c3fa20fe162ffa
|
6cd019ee0cb50b0ebb4f4e9028329e6444202a40
|
refs/heads/master
| 2020-04-17T08:45:14.284367 | 2019-01-18T15:23:58 | 2019-01-18T15:23:58 | 166,424,522 | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 1,460 |
java
|
package com.example.hppav.kamera;
import android.content.Intent;
import android.graphics.Bitmap;
import android.media.Image;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
ImageView imageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnCamera = (Button)findViewById(R.id.btnCamera);
imageView = (ImageView)findViewById(R.id.imageView);
// btnCamera.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View view) {
// Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// startActivityForResult(intent,0);
// }
// });
}
@Override
protected void onActivityResult(int requestCode,int resultCode,Intent data){
super.onActivityResult(requestCode,resultCode,data);
Bitmap bitmap = (Bitmap)data.getExtras().get("data");
imageView.setImageBitmap(bitmap);
}
public void takePicture(View v){
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent,0);
}
}
|
[
"[email protected]"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.