blob_id
stringlengths
40
40
__id__
int64
225
39,780B
directory_id
stringlengths
40
40
path
stringlengths
6
313
content_id
stringlengths
40
40
detected_licenses
sequence
license_type
stringclasses
2 values
repo_name
stringlengths
6
132
repo_url
stringlengths
25
151
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
70
visit_date
timestamp[ns]
revision_date
timestamp[ns]
committer_date
timestamp[ns]
github_id
int64
7.28k
689M
star_events_count
int64
0
131k
fork_events_count
int64
0
48k
gha_license_id
stringclasses
23 values
gha_fork
bool
2 classes
gha_event_created_at
timestamp[ns]
gha_created_at
timestamp[ns]
gha_updated_at
timestamp[ns]
gha_pushed_at
timestamp[ns]
gha_size
int64
0
40.4M
gha_stargazers_count
int32
0
112k
gha_forks_count
int32
0
39.4k
gha_open_issues_count
int32
0
11k
gha_language
stringlengths
1
21
gha_archived
bool
2 classes
gha_disabled
bool
1 class
content
stringlengths
7
4.37M
src_encoding
stringlengths
3
16
language
stringclasses
1 value
length_bytes
int64
7
4.37M
extension
stringclasses
24 values
filename
stringlengths
4
174
language_id
stringclasses
1 value
entities
list
contaminating_dataset
stringclasses
0 values
malware_signatures
sequence
redacted_content
stringlengths
7
4.37M
redacted_length_bytes
int64
7
4.37M
alphanum_fraction
float32
0.25
0.94
alpha_fraction
float32
0.25
0.94
num_lines
int32
1
84k
avg_line_length
float32
0.76
99.9
std_line_length
float32
0
220
max_line_length
int32
5
998
is_vendor
bool
2 classes
is_generated
bool
1 class
max_hex_length
int32
0
319
hex_fraction
float32
0
0.38
max_unicode_length
int32
0
408
unicode_fraction
float32
0
0.36
max_base64_length
int32
0
506
base64_fraction
float32
0
0.5
avg_csv_sep_count
float32
0
4
is_autogen_header
bool
1 class
is_empty_html
bool
1 class
shard
stringclasses
16 values
5dbf3063d856e5413db85fd27f578cbb4270c056
22,471,268,917,900
1b3c3d991675b960c672f0ee006094d5dfae2fbc
/src/main/java/com/yangjiachen/cms/service/ArticleService.java
0cdb6804b4e828980cb4608c0645db5035fbb714
[]
no_license
yangjiachen666/yangjiachen-cms
https://github.com/yangjiachen666/yangjiachen-cms
74a89830cf0d6918f6041b3262eecde4962ed524
2b000fda3b2067629f3afe9bd374bcc688614830
refs/heads/master
2022-12-21T23:20:39.312000
2019-11-23T03:21:53
2019-11-23T03:21:53
217,050,120
0
0
null
false
2022-12-16T04:53:32
2019-10-23T12:19:56
2019-11-23T03:21:46
2022-12-16T04:53:29
2,811
0
0
17
JavaScript
false
false
/** * Copyright © 2019 北京八维. All rights reserved. * * @Title: ArticleService.java * @Prject: yangjiachen-cms * @Package: com.yangjiachen.cms.service * @Description: TODO * @author: 杨家琛 * @date: 2019年10月16日 下午7:22:54 */ package com.yangjiachen.cms.service; import java.util.List; import com.github.pagehelper.PageInfo; import com.yangjiachen.cms.domain.Article; import com.yangjiachen.cms.domain.ArticleWithBLOBs; import com.yangjiachen.cms.domain.Category; /** * @ClassName: ArticleService * @Description: TODO * @author:杨家琛 * @date: 2019年10月16日 下午7:22:54 */ public interface ArticleService { PageInfo<ArticleWithBLOBs> selects(Article article,Integer page,Integer pageSize); int insertSelective(ArticleWithBLOBs record); ArticleWithBLOBs selectByPrimaryKey(Integer id); int updateByPrimaryKeySelective(ArticleWithBLOBs record); int deleteByPrimaryKey(Integer id); }
UTF-8
Java
1,003
java
ArticleService.java
Java
[ { "context": ".cms.service \r\n * @Description: TODO\r\n * @author: 杨家琛 \r\n * @date: 2019年10月16日 下午7:22:54 \r\n */\r\npackage", "end": 204, "score": 0.9998522996902466, "start": 201, "tag": "NAME", "value": "杨家琛" }, { "context": "rticleService \r\n * @Description: TODO\r\n * @author:杨家琛\r\n * @date: 2019年10月16日 下午7:22:54 \r\n */\r\npublic i", "end": 572, "score": 0.9998451471328735, "start": 569, "tag": "NAME", "value": "杨家琛" } ]
null
[]
/** * Copyright © 2019 北京八维. All rights reserved. * * @Title: ArticleService.java * @Prject: yangjiachen-cms * @Package: com.yangjiachen.cms.service * @Description: TODO * @author: 杨家琛 * @date: 2019年10月16日 下午7:22:54 */ package com.yangjiachen.cms.service; import java.util.List; import com.github.pagehelper.PageInfo; import com.yangjiachen.cms.domain.Article; import com.yangjiachen.cms.domain.ArticleWithBLOBs; import com.yangjiachen.cms.domain.Category; /** * @ClassName: ArticleService * @Description: TODO * @author:杨家琛 * @date: 2019年10月16日 下午7:22:54 */ public interface ArticleService { PageInfo<ArticleWithBLOBs> selects(Article article,Integer page,Integer pageSize); int insertSelective(ArticleWithBLOBs record); ArticleWithBLOBs selectByPrimaryKey(Integer id); int updateByPrimaryKeySelective(ArticleWithBLOBs record); int deleteByPrimaryKey(Integer id); }
1,003
0.715177
0.683992
37
24
21.06361
83
false
false
0
0
0
0
0
0
0.432432
false
false
11
42a6d10df9631464eba9c287eb02c46aae6ca515
22,213,570,921,424
e6738981f31d0a08f142141352e5b954723bc911
/app/src/main/java/app/miji/com/inventorycheck/adapter/StockTakeRecyclerViewAdapter.java
fc866d4ef347468e826a3b78a4eee12479399992
[]
no_license
leeyc09/InventoryCheck
https://github.com/leeyc09/InventoryCheck
b093e8d3c7d7e0fe5b05f16e8c4f5fc562bf16ee
e4020298fd8c4f8777825ac94e4079a43b9573c9
refs/heads/master
2021-01-21T09:11:41.349000
2017-05-14T15:58:06
2017-05-14T15:58:06
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package app.miji.com.inventorycheck.adapter; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import app.miji.com.inventorycheck.R; import app.miji.com.inventorycheck.model.Item; public class StockTakeRecyclerViewAdapter extends RecyclerView.Adapter<StockTakeRecyclerViewAdapter.ViewHolder> { public StockTakeRecyclerViewAdapter() { } @Override public StockTakeRecyclerViewAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_stock_take, parent, false); return new StockTakeRecyclerViewAdapter.ViewHolder(view); } @Override public void onBindViewHolder(StockTakeRecyclerViewAdapter.ViewHolder holder, int position) { //TODO change dummy items holder.imgItem.setImageResource(R.drawable.cake); holder.txtItem.setText("Shortcake"); holder.txtQty.setText("30"); holder.txtUnit.setText("pcs"); } @Override public int getItemCount() { //TODO change item count based on list return 10; } class ViewHolder extends RecyclerView.ViewHolder { final View mView; final ImageView imgItem; final TextView txtItem; final TextView txtQty; final TextView txtUnit; Item mItem; ViewHolder(View itemView) { super(itemView); mView = itemView; imgItem = (ImageView) mView.findViewById(R.id.img_item); txtItem = (TextView) mView.findViewById(R.id.txt_name); txtQty = (TextView) mView.findViewById(R.id.txt_qty); txtUnit = (TextView) mView.findViewById(R.id.txt_unit); } } }
UTF-8
Java
1,877
java
StockTakeRecyclerViewAdapter.java
Java
[]
null
[]
package app.miji.com.inventorycheck.adapter; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import app.miji.com.inventorycheck.R; import app.miji.com.inventorycheck.model.Item; public class StockTakeRecyclerViewAdapter extends RecyclerView.Adapter<StockTakeRecyclerViewAdapter.ViewHolder> { public StockTakeRecyclerViewAdapter() { } @Override public StockTakeRecyclerViewAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_stock_take, parent, false); return new StockTakeRecyclerViewAdapter.ViewHolder(view); } @Override public void onBindViewHolder(StockTakeRecyclerViewAdapter.ViewHolder holder, int position) { //TODO change dummy items holder.imgItem.setImageResource(R.drawable.cake); holder.txtItem.setText("Shortcake"); holder.txtQty.setText("30"); holder.txtUnit.setText("pcs"); } @Override public int getItemCount() { //TODO change item count based on list return 10; } class ViewHolder extends RecyclerView.ViewHolder { final View mView; final ImageView imgItem; final TextView txtItem; final TextView txtQty; final TextView txtUnit; Item mItem; ViewHolder(View itemView) { super(itemView); mView = itemView; imgItem = (ImageView) mView.findViewById(R.id.img_item); txtItem = (TextView) mView.findViewById(R.id.txt_name); txtQty = (TextView) mView.findViewById(R.id.txt_qty); txtUnit = (TextView) mView.findViewById(R.id.txt_unit); } } }
1,877
0.691529
0.688865
63
28.793652
28.829636
113
false
false
0
0
0
0
0
0
0.507937
false
false
11
ec4343e082f80536fa261c65e104523077dfbb65
22,222,160,789,921
12474dbd53dfae06d8d2552443d96cf6f74dcc4b
/course 3/week 3/huffman.java
7a6d0e23a056288494a77bb56efc9e771b2e7718
[]
no_license
harsh-vt/cources
https://github.com/harsh-vt/cources
7597b84243a229c60fc91d3778e2cd78faa83f17
bb894fce2f976ad7d62238ad81f622f97c772f05
refs/heads/master
2022-01-19T01:38:05.908000
2019-07-29T13:49:03
2019-07-29T13:49:03
99,441,305
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package c3w3; import java.io.*; import java.util.*; public class Huffman { public static void main(String[] args) throws IOException{ BufferedReader br = new BufferedReader(new FileReader("C:\\Users\\MOJO-JOJO\\Desktop\\huffman.txt")); int n = Integer.parseInt(br.readLine()); PriorityQueue<Node> pq = new PriorityQueue<Node>(new Comparator<Node>(){ public int compare(Node n1,Node n2) { if(n1.w < n2.w) return -1; else if(n1.w > n2.w) return 1; else return 0; } }); for(int i=0; i<n; i++) { int w = Integer.parseInt(br.readLine()); pq.add(new Node(w,0,0)); } while(pq.size() > 1) { Node n1 = pq.remove(); Node n2 = pq.remove(); pq.add(new Node(n1.w + n2.w, Math.max(n1.max_bits , n2.max_bits) + 1,Math.min(n1.min_bits, n2.min_bits) + 1)); } System.out.println(pq.peek().max_bits); System.out.println(pq.peek().min_bits); } static class Node{ long w; int max_bits,min_bits; Node(long w,int max_bits,int min_bits) { this.w = w; this.min_bits = min_bits; this.max_bits = max_bits; } } }
UTF-8
Java
1,114
java
huffman.java
Java
[ { "context": "r = new BufferedReader(new FileReader(\"C:\\\\Users\\\\MOJO-JOJO\\\\Desktop\\\\huffman.txt\"));\n\t\t\n\t\tint n = Integer.pa", "end": 219, "score": 0.8658884763717651, "start": 210, "tag": "USERNAME", "value": "MOJO-JOJO" } ]
null
[]
package c3w3; import java.io.*; import java.util.*; public class Huffman { public static void main(String[] args) throws IOException{ BufferedReader br = new BufferedReader(new FileReader("C:\\Users\\MOJO-JOJO\\Desktop\\huffman.txt")); int n = Integer.parseInt(br.readLine()); PriorityQueue<Node> pq = new PriorityQueue<Node>(new Comparator<Node>(){ public int compare(Node n1,Node n2) { if(n1.w < n2.w) return -1; else if(n1.w > n2.w) return 1; else return 0; } }); for(int i=0; i<n; i++) { int w = Integer.parseInt(br.readLine()); pq.add(new Node(w,0,0)); } while(pq.size() > 1) { Node n1 = pq.remove(); Node n2 = pq.remove(); pq.add(new Node(n1.w + n2.w, Math.max(n1.max_bits , n2.max_bits) + 1,Math.min(n1.min_bits, n2.min_bits) + 1)); } System.out.println(pq.peek().max_bits); System.out.println(pq.peek().min_bits); } static class Node{ long w; int max_bits,min_bits; Node(long w,int max_bits,int min_bits) { this.w = w; this.min_bits = min_bits; this.max_bits = max_bits; } } }
1,114
0.599641
0.577199
56
18.892857
23.745434
113
false
false
0
0
0
0
0
0
2.607143
false
false
11
09f18e8f2e51e0095d90425152566e46595ffbce
7,645,041,826,523
157f16e8258121b172fbb926b93ee37e416f3a8b
/spring-boot-jpa-demo/src/main/java/uz/pdp/springbootjpademo/entity/Student.java
3c3fa55c4b4ba99c3427060680dad6fa1b271bb2
[]
no_license
shaxzodprogrammer/spring-boot-demo-projects
https://github.com/shaxzodprogrammer/spring-boot-demo-projects
7f7820b9091da371459467b7f1e4fba1f922d868
09eb8f981a565bc361718a57a2ed787ae2d78670
refs/heads/main
2023-03-28T11:05:35.293000
2021-03-28T13:19:54
2021-03-28T13:19:54
352,334,534
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
//package uz.pdp.springbootjpademo.entity; // //import lombok.AllArgsConstructor; //import lombok.Data; //import lombok.NoArgsConstructor; // //import javax.persistence.*; //import javax.validation.constraints.Email; //import javax.validation.constraints.Pattern; //import java.util.List; // //@Data //@AllArgsConstructor //@NoArgsConstructor //@Where(clause = "deleted is false") //@SQLDelete(sql="update student set deleted=true where id=?") //@Entity //public class Student extends AbsNameEntity { // // // @Email // @Column(nullable = false) // private String email; // // @Pattern(regexp = "^[+][9][9][8][0-9]{9}$", message = "Phone number must be 13 digits.") // private String phoneNumber; // //// @Column(name = "deleted", columnDefinition="BOOLEAN DEFAULT false") //// private boolean deleted; // // @ManyToMany // private List<Course> courses; //}
UTF-8
Java
885
java
Student.java
Java
[]
null
[]
//package uz.pdp.springbootjpademo.entity; // //import lombok.AllArgsConstructor; //import lombok.Data; //import lombok.NoArgsConstructor; // //import javax.persistence.*; //import javax.validation.constraints.Email; //import javax.validation.constraints.Pattern; //import java.util.List; // //@Data //@AllArgsConstructor //@NoArgsConstructor //@Where(clause = "deleted is false") //@SQLDelete(sql="update student set deleted=true where id=?") //@Entity //public class Student extends AbsNameEntity { // // // @Email // @Column(nullable = false) // private String email; // // @Pattern(regexp = "^[+][9][9][8][0-9]{9}$", message = "Phone number must be 13 digits.") // private String phoneNumber; // //// @Column(name = "deleted", columnDefinition="BOOLEAN DEFAULT false") //// private boolean deleted; // // @ManyToMany // private List<Course> courses; //}
885
0.682486
0.673446
33
25.818182
22.238997
94
false
false
0
0
0
0
0
0
0.424242
false
false
11
4ab208ee6771d7729cd5b041384a4e884872ee4e
20,212,116,130,070
0a4012a983d7a500886bc6b301e938ab0378bfa2
/SRM642.java
6f62ba33cc4623f6d75f6d57942ae99f89579506
[]
no_license
ffmm00/Topcoder_div2_250
https://github.com/ffmm00/Topcoder_div2_250
14b4c429e2fccf302922291b31842ed9cf70ee2e
964642cb7a5af1d3352228987437af11614c3dc3
refs/heads/master
2021-01-19T18:55:38.490000
2016-01-13T08:50:42
2016-01-13T08:50:42
37,917,228
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
public class SRM642 { public int minNumber(String ex) { int min = Integer.MAX_VALUE; for (int i = 1; i < ex.length(); i++) { String A = ex.substring(0, i); String B = ex.substring(i); int tm = Integer.parseInt(A) + Integer.parseInt(B); min = Math.min(tm, min); } return min; } }
UTF-8
Java
306
java
SRM642.java
Java
[]
null
[]
public class SRM642 { public int minNumber(String ex) { int min = Integer.MAX_VALUE; for (int i = 1; i < ex.length(); i++) { String A = ex.substring(0, i); String B = ex.substring(i); int tm = Integer.parseInt(A) + Integer.parseInt(B); min = Math.min(tm, min); } return min; } }
306
0.594771
0.578431
17
17
17.289915
54
false
false
0
0
0
0
0
0
1.882353
false
false
11
f563c9edc1504a18d810a0edd8c7aa1464944a01
13,924,283,979,609
a2040da08da28bd5862554e57dcc6e6c70c5afd8
/hn-web/src/main/java/by/romanovich/it/controller/RegistrController.java
759468797bb18e8c90445a8561f6cb3e05828c3e
[]
no_license
romanovichandrey/sf_library
https://github.com/romanovichandrey/sf_library
27012cb415e5a093e7a1011e289d214a2088db25
8053d49810d536f1f80f2f6a3419066c04dff55f
refs/heads/master
2016-06-12T01:22:29.151000
2016-05-26T10:06:15
2016-05-26T10:06:15
59,739,919
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package by.romanovich.it.controller; import by.romanovich.it.pojos.Adress; import by.romanovich.it.pojos.User; import by.romanovich.it.service.exeptions.ServiceExeption; import by.romanovich.it.service.service.UserService; import by.romanovich.it.service.service.UserServiceImpl; import org.apache.log4j.Logger; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.List; public class RegistrController extends HttpServlet { private static Logger log = Logger.getLogger(RegistrController.class); public RegistrController() { super(); } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { RequestDispatcher dispatcher = req.getRequestDispatcher("/WEB-INF/views/registr.jsp"); dispatcher.forward(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { UserService userService = UserServiceImpl.getUserService(); String login = req.getParameter("login"); String password = req.getParameter("password"); String firstname = req.getParameter("firstname"); String lastname = req.getParameter("lastname"); String telephone = req.getParameter("telephone"); String email = req.getParameter("email"); String street = req.getParameter("street"); String city = req.getParameter("city"); String state = req.getParameter("state"); String country = req.getParameter("country"); if(login.length() > 0 && password.length() > 0 && firstname.length() > 0 && lastname.length() > 0 && telephone.length() > 0 && email.length() > 0 && street.length() > 0 && city.length() > 0 && country.length() > 0 ){ Adress adress = new Adress(street, city, state, country); User user = new User(firstname, lastname, telephone, email, login, password); user.setAdress(adress); adress.setUser(user); boolean status; try { List<User> users = userService.getAllUsers(); for(User resultUser : users) { if((user.getLogin()).compareToIgnoreCase(resultUser.getLogin()) == 0) { req.getServletContext().getRequestDispatcher("/WEB-INF/errorJsp/errorRegistrLogin.jsp") .forward(req, resp); } else { status = userService.saveUser(user); if(status) { req.getSession().setAttribute("user", user); req.getServletContext().getRequestDispatcher("/book").forward(req, resp); } } } } catch (ServiceExeption e) { log.error("Cannot save user:", e); } } else req.getServletContext().getRequestDispatcher("/WEB-INF/errorJsp/errorRegistr.jsp") .forward(req, resp); } }
UTF-8
Java
3,304
java
RegistrController.java
Java
[ { "context": "in\");\n String password = req.getParameter(\"password\");\n String firstname = req.getParameter(\"f", "end": 1340, "score": 0.7637743949890137, "start": 1332, "tag": "PASSWORD", "value": "password" } ]
null
[]
package by.romanovich.it.controller; import by.romanovich.it.pojos.Adress; import by.romanovich.it.pojos.User; import by.romanovich.it.service.exeptions.ServiceExeption; import by.romanovich.it.service.service.UserService; import by.romanovich.it.service.service.UserServiceImpl; import org.apache.log4j.Logger; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.List; public class RegistrController extends HttpServlet { private static Logger log = Logger.getLogger(RegistrController.class); public RegistrController() { super(); } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { RequestDispatcher dispatcher = req.getRequestDispatcher("/WEB-INF/views/registr.jsp"); dispatcher.forward(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { UserService userService = UserServiceImpl.getUserService(); String login = req.getParameter("login"); String password = req.getParameter("<PASSWORD>"); String firstname = req.getParameter("firstname"); String lastname = req.getParameter("lastname"); String telephone = req.getParameter("telephone"); String email = req.getParameter("email"); String street = req.getParameter("street"); String city = req.getParameter("city"); String state = req.getParameter("state"); String country = req.getParameter("country"); if(login.length() > 0 && password.length() > 0 && firstname.length() > 0 && lastname.length() > 0 && telephone.length() > 0 && email.length() > 0 && street.length() > 0 && city.length() > 0 && country.length() > 0 ){ Adress adress = new Adress(street, city, state, country); User user = new User(firstname, lastname, telephone, email, login, password); user.setAdress(adress); adress.setUser(user); boolean status; try { List<User> users = userService.getAllUsers(); for(User resultUser : users) { if((user.getLogin()).compareToIgnoreCase(resultUser.getLogin()) == 0) { req.getServletContext().getRequestDispatcher("/WEB-INF/errorJsp/errorRegistrLogin.jsp") .forward(req, resp); } else { status = userService.saveUser(user); if(status) { req.getSession().setAttribute("user", user); req.getServletContext().getRequestDispatcher("/book").forward(req, resp); } } } } catch (ServiceExeption e) { log.error("Cannot save user:", e); } } else req.getServletContext().getRequestDispatcher("/WEB-INF/errorJsp/errorRegistr.jsp") .forward(req, resp); } }
3,306
0.621671
0.618341
75
43.053333
30.73712
114
false
false
0
0
0
0
0
0
0.786667
false
false
11
a5b5ed98bcc272ea8633910de5b0259f2c99e625
30,528,627,585,423
7b0418236bb8a576e3cc387e615f5303c93c7b69
/src/main/java/pl/gda/pg/eti/kio/malicious/configuration/log/LoggerCreator.java
9aa01cc2abd3a50e03526671cd6b2735a86387e1
[ "Apache-2.0" ]
permissive
mrwrob/Malicious
https://github.com/mrwrob/Malicious
250a22c8c9c01c2beecb627867ac97bbbb91be24
e8b5889023b71f593d49354f4bd19d8acb58badc
refs/heads/master
2020-03-21T13:16:27.365000
2017-07-24T19:17:13
2017-07-24T19:17:14
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * Gdańsk University of Technology - Engineering Thesis * Malicious Module for Netbeans * * Cilińdź Michał, Gabryelska Nela, Micał Marek */ package pl.gda.pg.eti.kio.malicious.configuration.log; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.core.Appender; import org.apache.logging.log4j.core.Filter; import org.apache.logging.log4j.core.Layout; import org.apache.logging.log4j.core.Logger; import org.apache.logging.log4j.core.LoggerContext; import org.apache.logging.log4j.core.appender.RandomAccessFileAppender; import org.apache.logging.log4j.core.config.Configuration; import org.apache.logging.log4j.core.filter.ThresholdFilter; import org.apache.logging.log4j.core.layout.PatternLayout; /** * * @author Michał Cilińdź */ public class LoggerCreator { private static final String LOGGER_NAME = "pl.gda.pg.eti.kio.malicious"; private static final String APP_APPENDER_NAME = "reportApender"; private static final String APP_APPENDER_PATTERN = "%d: %m%n"; private static final String ERROR_APPENDER_NAME = "errorApender"; private static final String ERROR_APPENDER_PATTERN = "%d %p %c{1.}: %m%n"; private static final String TRUE = "true"; private static final String FALSE = "false"; private static final String CHARSET = "UTF-8"; private LoggerCreator() { } public static void createAppLogger(String file) { Filter filter = ThresholdFilter.createFilter("ERROR", "DENY", "ACCEPT"); createAppender(file, APP_APPENDER_NAME, APP_APPENDER_PATTERN, filter); } public static void createErrorLogger(String file) { Filter filter = ThresholdFilter.createFilter("ERROR", "ACCEPT", "DENY"); createAppender(file, ERROR_APPENDER_NAME, ERROR_APPENDER_PATTERN, filter); } private static void createAppender(String file, String name, String pattern, Filter filter) { Configuration config = getConfiguration(); Logger logger = getLogger(); Layout layout = PatternLayout.createLayout(pattern, config, null, CHARSET, TRUE); Appender appender = RandomAccessFileAppender.createAppender(file, TRUE, name, TRUE, TRUE, layout, filter, FALSE, "", config); logger.addAppender(appender); appender.start(); } private static Configuration getConfiguration() { LoggerContext ctx = (LoggerContext) LogManager.getContext(); return ctx.getConfiguration(); } private static Logger getLogger() { return (Logger) LogManager.getLogger(LOGGER_NAME); } }
UTF-8
Java
2,560
java
LoggerCreator.java
Java
[ { "context": "ring Thesis\n * Malicious Module for Netbeans\n *\n * Cilińdź Michał, Gabryelska Nela, Micał Marek\n */\npackage pl.gda.", "end": 112, "score": 0.9996979236602783, "start": 98, "tag": "NAME", "value": "Cilińdź Michał" }, { "context": "alicious Module for Netbeans\n *\n * Cilińdź Michał, Gabryelska Nela, Micał Marek\n */\npackage pl.gda.pg.eti.kio.malici", "end": 129, "score": 0.9998615384101868, "start": 114, "tag": "NAME", "value": "Gabryelska Nela" }, { "context": "or Netbeans\n *\n * Cilińdź Michał, Gabryelska Nela, Micał Marek\n */\npackage pl.gda.pg.eti.kio.malicious.configura", "end": 142, "score": 0.9998584389686584, "start": 131, "tag": "NAME", "value": "Micał Marek" }, { "context": "og4j.core.layout.PatternLayout;\n\n/**\n *\n * @author Michał Cilińdź\n */\npublic class LoggerCreator {\n\n private sta", "end": 765, "score": 0.9998409748077393, "start": 751, "tag": "NAME", "value": "Michał Cilińdź" } ]
null
[]
/* * Gdańsk University of Technology - Engineering Thesis * Malicious Module for Netbeans * * <NAME>, <NAME>, <NAME> */ package pl.gda.pg.eti.kio.malicious.configuration.log; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.core.Appender; import org.apache.logging.log4j.core.Filter; import org.apache.logging.log4j.core.Layout; import org.apache.logging.log4j.core.Logger; import org.apache.logging.log4j.core.LoggerContext; import org.apache.logging.log4j.core.appender.RandomAccessFileAppender; import org.apache.logging.log4j.core.config.Configuration; import org.apache.logging.log4j.core.filter.ThresholdFilter; import org.apache.logging.log4j.core.layout.PatternLayout; /** * * @author <NAME> */ public class LoggerCreator { private static final String LOGGER_NAME = "pl.gda.pg.eti.kio.malicious"; private static final String APP_APPENDER_NAME = "reportApender"; private static final String APP_APPENDER_PATTERN = "%d: %m%n"; private static final String ERROR_APPENDER_NAME = "errorApender"; private static final String ERROR_APPENDER_PATTERN = "%d %p %c{1.}: %m%n"; private static final String TRUE = "true"; private static final String FALSE = "false"; private static final String CHARSET = "UTF-8"; private LoggerCreator() { } public static void createAppLogger(String file) { Filter filter = ThresholdFilter.createFilter("ERROR", "DENY", "ACCEPT"); createAppender(file, APP_APPENDER_NAME, APP_APPENDER_PATTERN, filter); } public static void createErrorLogger(String file) { Filter filter = ThresholdFilter.createFilter("ERROR", "ACCEPT", "DENY"); createAppender(file, ERROR_APPENDER_NAME, ERROR_APPENDER_PATTERN, filter); } private static void createAppender(String file, String name, String pattern, Filter filter) { Configuration config = getConfiguration(); Logger logger = getLogger(); Layout layout = PatternLayout.createLayout(pattern, config, null, CHARSET, TRUE); Appender appender = RandomAccessFileAppender.createAppender(file, TRUE, name, TRUE, TRUE, layout, filter, FALSE, "", config); logger.addAppender(appender); appender.start(); } private static Configuration getConfiguration() { LoggerContext ctx = (LoggerContext) LogManager.getContext(); return ctx.getConfiguration(); } private static Logger getLogger() { return (Logger) LogManager.getLogger(LOGGER_NAME); } }
2,523
0.723354
0.718652
65
38.261539
31.066814
133
false
false
0
0
0
0
0
0
0.923077
false
false
11
81767597344078335b43eb8a744f15199073cd18
2,791,728,768,272
5bb953372bd9b65f518ab3993526f039ba13835b
/PK7-Otamendi-Urtzi/Ariketak/7_5_Zoo/ZooApp.java
fcdd3b2d970ee0a0b59bfd80749483af013dd4db
[]
no_license
uotamendi/ProgramacionConcurrente
https://github.com/uotamendi/ProgramacionConcurrente
29ed94a2437825ef022fdb3c49a1a260cd774ba5
6910ef0fff6dda05ea9e68acd5a91c7e4731d459
refs/heads/master
2021-11-29T01:56:31.585000
2019-01-28T16:20:56
2019-01-28T16:20:56
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package Zoo; //Urtzi Otamendi Etxabe //2017/11/30 public class ZooApp { static final int Max=10; static final int LKop=5; public static void main (String args[]) { Lehoia[] lehoiak= new Lehoia[LKop]; Pantaila p= new Pantaila(); Jangela o= new Jangela(p); Zaintzailea z = new Zaintzailea(o); z.start(); for (int i = 0; i<LKop; i++) { lehoiak[i] = new Lehoia(o,i); lehoiak[i].start(); } } }
UTF-8
Java
477
java
ZooApp.java
Java
[ { "context": "package Zoo;\r\n\r\n\r\n//Urtzi Otamendi Etxabe \r\n//2017/11/30\r\npublic class ZooApp {\r\n\r\n\tstatic ", "end": 41, "score": 0.9989511966705322, "start": 20, "tag": "NAME", "value": "Urtzi Otamendi Etxabe" } ]
null
[]
package Zoo; //<NAME> //2017/11/30 public class ZooApp { static final int Max=10; static final int LKop=5; public static void main (String args[]) { Lehoia[] lehoiak= new Lehoia[LKop]; Pantaila p= new Pantaila(); Jangela o= new Jangela(p); Zaintzailea z = new Zaintzailea(o); z.start(); for (int i = 0; i<LKop; i++) { lehoiak[i] = new Lehoia(o,i); lehoiak[i].start(); } } }
462
0.557652
0.532495
24
17.875
13.88138
42
false
false
0
0
0
0
0
0
1.416667
false
false
11
16c17fc34605aa57f9747d8ed7611222592caa53
17,403,207,508,453
a68468b0ee08e1ddc606fb7cde10f24b2f9838c1
/Soft_Church/src/main/java/com/example/demo/services/ChequeRepository.java
164ee578cf7eba6c11f75e07f2db4d21fb938bec
[]
no_license
CharlesWilkenson/Soft-church
https://github.com/CharlesWilkenson/Soft-church
00238fcc66acb14631aec81b624315ec40c76f2e
3f266f43d2dcc8e0f2d39a527690f61010608d4f
refs/heads/master
2023-04-13T23:49:17.371000
2020-07-18T01:39:11
2020-07-18T01:39:11
280,473,066
0
0
null
false
2021-04-26T20:29:45
2020-07-17T16:27:09
2020-07-18T01:39:14
2021-04-26T20:29:43
9,099
0
0
1
JavaScript
false
false
package com.example.demo.services; import org.springframework.data.jpa.repository.JpaRepository; import com.example.demo.entities.Cheque; public interface ChequeRepository extends JpaRepository<Cheque, Long>{ }
UTF-8
Java
215
java
ChequeRepository.java
Java
[]
null
[]
package com.example.demo.services; import org.springframework.data.jpa.repository.JpaRepository; import com.example.demo.entities.Cheque; public interface ChequeRepository extends JpaRepository<Cheque, Long>{ }
215
0.827907
0.827907
9
22.888889
27.208839
70
false
false
0
0
0
0
0
0
0.444444
false
false
11
fe0ce193850ac68574b6c7204a0050e37c864233
23,639,500,016,473
6a517671824b822ef676cf439da539237e5f8c9e
/src/penInteraction/XmlHandler.java
315f5d1fe86b11c72d249ea8154c689bb4ad7b2f
[]
no_license
lawandorder/PenInteraction
https://github.com/lawandorder/PenInteraction
57346274a601398899bc890059117bf39ad18838
55b5929481639478cc13fefcd1549570450cfb86
refs/heads/master
2016-09-06T16:40:55.387000
2015-02-22T03:59:43
2015-02-22T03:59:43
24,061,769
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package penInteraction; import java.io.File; import java.io.IOException; import java.util.HashMap; import java.util.Map; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; public class XmlHandler { Map<String,String[]> aMap=new HashMap<String,String[]>(); public Map<String,String[]> ReadXml(String fileName) { // TODO Auto-generated method stub DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance(); Element root=null; try { factory.setIgnoringElementContentWhitespace(true); DocumentBuilder db=factory.newDocumentBuilder(); Document xmldoc=db.parse(new File(fileName)); root=xmldoc.getDocumentElement(); NodeList sometagTypes=root.getElementsByTagName("tagType"); System.out.println("获得所有图形类别"); System.out.println("--- 共有 "+sometagTypes.getLength()+"个图形类别。 ---"); for(int i=0;i<sometagTypes.getLength();i++) { Element tagType=(Element) sometagTypes.item(i); String key=tagType.getAttribute("name"); NodeList tags= tagType.getElementsByTagName("tag"); String[] temp=new String[tags.getLength()]; for (int j=0;j<tags.getLength();j++){ Element tag=(Element) tags.item(j); temp[j]=tag.getTextContent(); } aMap.put(key, temp); } } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return aMap; } }
GB18030
Java
2,036
java
XmlHandler.java
Java
[]
null
[]
package penInteraction; import java.io.File; import java.io.IOException; import java.util.HashMap; import java.util.Map; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; public class XmlHandler { Map<String,String[]> aMap=new HashMap<String,String[]>(); public Map<String,String[]> ReadXml(String fileName) { // TODO Auto-generated method stub DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance(); Element root=null; try { factory.setIgnoringElementContentWhitespace(true); DocumentBuilder db=factory.newDocumentBuilder(); Document xmldoc=db.parse(new File(fileName)); root=xmldoc.getDocumentElement(); NodeList sometagTypes=root.getElementsByTagName("tagType"); System.out.println("获得所有图形类别"); System.out.println("--- 共有 "+sometagTypes.getLength()+"个图形类别。 ---"); for(int i=0;i<sometagTypes.getLength();i++) { Element tagType=(Element) sometagTypes.item(i); String key=tagType.getAttribute("name"); NodeList tags= tagType.getElementsByTagName("tag"); String[] temp=new String[tags.getLength()]; for (int j=0;j<tags.getLength();j++){ Element tag=(Element) tags.item(j); temp[j]=tag.getTextContent(); } aMap.put(key, temp); } } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return aMap; } }
2,036
0.594406
0.591908
65
29.799999
22.320187
80
false
false
0
0
0
0
0
0
1.584615
false
false
11
f01d40cbb97d46ff0b51618238631e29e3e6f004
2,052,994,398,917
55c6252354276e7632d9dd1a18df1fda3835633d
/src/main/java/com/limai/service/RedisService.java
87789280564f2b01e07b8825b804c81534c9f1c4
[]
no_license
itwliuhh01/bookmanage
https://github.com/itwliuhh01/bookmanage
0ffcffe61a96157f2c3bc8eecffd8c0f893e31d7
eff9bb705f984c370f3406cd58ffac8de7d4cc65
refs/heads/master
2020-05-15T11:16:31.410000
2019-04-19T07:08:10
2019-04-19T07:08:10
182,217,807
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.limai.service; public interface RedisService { public void set(String key, Object value); public void set(String key, Object value, long expireTime); public boolean exists(final String key); public <T> T get(String key, Class<T> clazz); public String get(String key); public void delete(String key); public Object getObject(String key); public boolean setObject(String key,Object object); public boolean setObject(String key,Object object,Long expireTime); }
UTF-8
Java
508
java
RedisService.java
Java
[]
null
[]
package com.limai.service; public interface RedisService { public void set(String key, Object value); public void set(String key, Object value, long expireTime); public boolean exists(final String key); public <T> T get(String key, Class<T> clazz); public String get(String key); public void delete(String key); public Object getObject(String key); public boolean setObject(String key,Object object); public boolean setObject(String key,Object object,Long expireTime); }
508
0.732283
0.732283
13
38.076923
20.112995
71
false
false
0
0
0
0
0
0
1.307692
false
false
11
6cef1296048f6de7c77cb15816cee4e67ca8118c
7,387,343,814,267
eb7ad5b0682fb9ee3a9e2a23e0e68b1aecf06cef
/Module2/Week1/JAVABasic/src/introduction/arrray/SumOfPrincipalDiagonal.java
4a0bea607f5f3849b4acd4063173f542af218fd4
[]
no_license
nphuoc0402/CGHModule2
https://github.com/nphuoc0402/CGHModule2
99cb8136a7143b13f29e242e40e3b68481e1be48
9dd501e356e82c4963b4ee15a725ec165acd1a05
refs/heads/master
2023-06-24T06:52:57.112000
2021-07-22T06:47:10
2021-07-22T06:47:10
373,201,985
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package introduction.arrray; import java.util.Scanner; public class SumOfPrincipalDiagonal { public static void main(String[] args) { int size; int sumOfPrincipalDiagonal = 0; Scanner input = new Scanner(System.in); System.out.printf("Enter the size of Matrix:"); size = input.nextInt(); int matrix[][] = new int[size][size]; System.out.println("Enter the element in Matrix:"); for(int i =0;i<size;i++){ for(int j =0;j<size;j++){ System.out.printf("matrix[%d][%d] = ",i,j); matrix[i][j] = input.nextInt(); } } System.out.printf("Matrix: \n"); for(int i =0;i<size;i++){ for(int j =0;j<size;j++){ System.out.printf("| %d |",matrix[i][j]); } System.out.println(); } for(int i =0;i<size;i++){ for(int j =0;j<size;j++){ if(i==j){ sumOfPrincipalDiagonal+=matrix[i][j]; } } } System.out.printf("Sum of the Principal Diagonal is : %d!",sumOfPrincipalDiagonal); } }
UTF-8
Java
1,177
java
SumOfPrincipalDiagonal.java
Java
[]
null
[]
package introduction.arrray; import java.util.Scanner; public class SumOfPrincipalDiagonal { public static void main(String[] args) { int size; int sumOfPrincipalDiagonal = 0; Scanner input = new Scanner(System.in); System.out.printf("Enter the size of Matrix:"); size = input.nextInt(); int matrix[][] = new int[size][size]; System.out.println("Enter the element in Matrix:"); for(int i =0;i<size;i++){ for(int j =0;j<size;j++){ System.out.printf("matrix[%d][%d] = ",i,j); matrix[i][j] = input.nextInt(); } } System.out.printf("Matrix: \n"); for(int i =0;i<size;i++){ for(int j =0;j<size;j++){ System.out.printf("| %d |",matrix[i][j]); } System.out.println(); } for(int i =0;i<size;i++){ for(int j =0;j<size;j++){ if(i==j){ sumOfPrincipalDiagonal+=matrix[i][j]; } } } System.out.printf("Sum of the Principal Diagonal is : %d!",sumOfPrincipalDiagonal); } }
1,177
0.48853
0.482583
42
27.023809
21.698681
91
false
false
0
0
0
0
0
0
0.809524
false
false
11
0d056f42dec38005c972f572328933e01fc17e9b
7,387,343,812,478
62885036bea56c142d3c18303c2902bfb397edc1
/rec_module/src/ru/phplego/secretary/activities/pages/adapters/GroupExAdapter.java
8e08678d4662287b9919727af149d15346fb3831
[]
no_license
phplego/rec
https://github.com/phplego/rec
d3e77093c6f4b2787ab606d3032a486aed7d19ae
4455342d14fb932294e89441d389f15650035748
refs/heads/master
2023-02-13T23:38:39.417000
2021-01-08T18:44:37
2021-01-08T18:44:37
327,984,908
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ru.phplego.secretary.activities.pages.adapters; import android.content.Context; import android.view.View; import android.view.ViewGroup; import android.widget.*; import ru.phplego.core.db.ActiveQuery; import ru.phplego.core.Cachable; import ru.phplego.secretary.db.ActiveCall; import ru.phplego.core.debug.Log; import ru.phplego.secretary.view.ViewGroupFactory; import ru.phplego.secretary.view.ViewOneGroup; import ru.phplego.secretary.view.ViewOneRecord; import ru.phplego.secretary.view.ViewOneRecord2; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Hashtable; import java.util.LinkedHashMap; import java.util.Vector; /** * Created by IntelliJ IDEA. * User: Admin * Date: 06.01.12 * Time: 9:15 * To change this template use File | Settings | File Templates. */ public class GroupExAdapter extends BaseExpandableListAdapter { private Context mContext; private ActiveQuery <ActiveCall> mActiveQuery; private Grouper mGrouper; private LinkedHashMap <String, Group> mGroupedData; private ViewGroupFactory mViewGroupFactory; public class Group extends Vector <ActiveCall> { public String groupKey; } public interface Grouper { public String getGroupKey(ActiveCall activeCall); } public GroupExAdapter(Context context, ActiveQuery <ActiveCall> activeQuery1, Grouper grouper, ViewGroupFactory groupFactory) { mContext = context; mActiveQuery = activeQuery1; mGrouper = grouper; mGroupedData = new LinkedHashMap<String, Group>(); mViewGroupFactory = groupFactory; if(mGrouper == null) mGrouper = new Grouper() { @Override public String getGroupKey(ActiveCall activeCall) { Date date = activeCall.getCreatedDate(); return new SimpleDateFormat("dd.MM.yyyy").format(date); } }; requery(); } public ActiveQuery getActiveQuery() { return mActiveQuery; } public void requery() { Log.d("requery()"); mGroupedData.clear(); Vector<ActiveCall> calls = mActiveQuery.objects(); for(ActiveCall activeCall: calls){ Group group = new Group(); group.groupKey = mGrouper.getGroupKey(activeCall); if(!mGroupedData.containsKey(group.groupKey)) mGroupedData.put(group.groupKey, group); mGroupedData.get(group.groupKey).add(activeCall); } } public Group [] getGroupedData() { return mGroupedData.values().toArray(new Group[0]); } /** * @param groupPosition * @param childPosition * @return идентификатор записи разговора */ public long getChildId(int groupPosition, int childPosition) { return getGroupedData()[groupPosition].get(childPosition).getId(); } public long getGroupId(int groupPosition) { return -groupPosition; } public Object getGroup(int position) { return position; } public ActiveCall getChild(int groupPosition, int childPosition) { return getGroupedData()[groupPosition].get(childPosition); } public int getGroupCount() { return mGroupedData.size(); } public int getChildrenCount(int groupPosition) { return getCallGroup(groupPosition).size(); } public Group getCallGroup(int groupPosition) { if(groupPosition > getGroupedData().length - 1 || groupPosition < 0) return new Group(); return getGroupedData()[groupPosition]; } private Hashtable <String, View> _group_view_cache =new Hashtable<String, View>(); public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) { // Если вылезли за пределы массива if(mGroupedData.size() <= groupPosition) return new TextView(mContext); String groupKey = getGroupedData()[groupPosition].groupKey; if(_group_view_cache.containsKey(groupKey)){ View view = _group_view_cache.get(groupKey); if(view instanceof Cachable && !((Cachable) view).isInvalid()){ return view; } } /* // Пробовал повторно использовать convertedView, как рекоммендует Гугл - тормозит жутко if(convertView instanceof ViewOneGroup){ ViewOneGroup ooo = (ViewOneGroup)convertView; ooo.fillViewsFromGroup(getGroupedData()[groupPosition]); return ooo; } */ View view = mViewGroupFactory.createView(mContext, getGroupedData()[groupPosition]); ((ViewOneGroup)view).fillViews(); _group_view_cache.put(groupKey, view); return view; } private Hashtable <Long, View> _child_view_cache = new Hashtable<Long, View>(); public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) { if(convertView instanceof ViewOneRecord){ ViewOneRecord ooo = (ViewOneRecord)convertView; ooo.fillFromActiveCall(getChild(groupPosition,childPosition)); return ooo; } /* if(convertView instanceof ViewOneRecord2){ ViewOneRecord2 ooo = (ViewOneRecord2)convertView; ooo.fillFromActiveCall(getChild(groupPosition,childPosition)); return ooo; } */ /* long id = getChildId(groupPosition, childPosition); if(_child_view_cache.containsKey(id)){ View view = _child_view_cache.get(id); if(view instanceof Cachable && !((Cachable) view).isInvalid()){ return view; } } */ ViewOneRecord viewRecord = new ViewOneRecord(mContext, getChild(groupPosition,childPosition)); //ViewOneRecord2 viewRecord = new ViewOneRecord2(mContext, getChild(groupPosition,childPosition)); //_child_view_cache.put(id, viewRecord); return viewRecord; } public boolean isChildSelectable(int groupPosition, int childPosition) { return true; } public boolean hasStableIds() { return true; } public void clearViewCache() { _child_view_cache.clear(); } }
UTF-8
Java
6,397
java
GroupExAdapter.java
Java
[ { "context": "Vector;\n\n/**\n * Created by IntelliJ IDEA.\n * User: Admin\n * Date: 06.01.12\n * Time: 9:15\n * To change this", "end": 707, "score": 0.7694620490074158, "start": 702, "tag": "USERNAME", "value": "Admin" }, { "context": "торно использовать convertedView, как рекоммендует Гугл - тормозит жутко\n if(convertView instanceo", "end": 4298, "score": 0.8618699312210083, "start": 4294, "tag": "NAME", "value": "Гугл" }, { "context": "спользовать convertedView, как рекоммендует Гугл - тормозит жутко\n if(convertView instanceof ViewOneGroup){\n", "end": 4315, "score": 0.6592388153076172, "start": 4301, "tag": "NAME", "value": "тормозит жутко" } ]
null
[]
package ru.phplego.secretary.activities.pages.adapters; import android.content.Context; import android.view.View; import android.view.ViewGroup; import android.widget.*; import ru.phplego.core.db.ActiveQuery; import ru.phplego.core.Cachable; import ru.phplego.secretary.db.ActiveCall; import ru.phplego.core.debug.Log; import ru.phplego.secretary.view.ViewGroupFactory; import ru.phplego.secretary.view.ViewOneGroup; import ru.phplego.secretary.view.ViewOneRecord; import ru.phplego.secretary.view.ViewOneRecord2; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Hashtable; import java.util.LinkedHashMap; import java.util.Vector; /** * Created by IntelliJ IDEA. * User: Admin * Date: 06.01.12 * Time: 9:15 * To change this template use File | Settings | File Templates. */ public class GroupExAdapter extends BaseExpandableListAdapter { private Context mContext; private ActiveQuery <ActiveCall> mActiveQuery; private Grouper mGrouper; private LinkedHashMap <String, Group> mGroupedData; private ViewGroupFactory mViewGroupFactory; public class Group extends Vector <ActiveCall> { public String groupKey; } public interface Grouper { public String getGroupKey(ActiveCall activeCall); } public GroupExAdapter(Context context, ActiveQuery <ActiveCall> activeQuery1, Grouper grouper, ViewGroupFactory groupFactory) { mContext = context; mActiveQuery = activeQuery1; mGrouper = grouper; mGroupedData = new LinkedHashMap<String, Group>(); mViewGroupFactory = groupFactory; if(mGrouper == null) mGrouper = new Grouper() { @Override public String getGroupKey(ActiveCall activeCall) { Date date = activeCall.getCreatedDate(); return new SimpleDateFormat("dd.MM.yyyy").format(date); } }; requery(); } public ActiveQuery getActiveQuery() { return mActiveQuery; } public void requery() { Log.d("requery()"); mGroupedData.clear(); Vector<ActiveCall> calls = mActiveQuery.objects(); for(ActiveCall activeCall: calls){ Group group = new Group(); group.groupKey = mGrouper.getGroupKey(activeCall); if(!mGroupedData.containsKey(group.groupKey)) mGroupedData.put(group.groupKey, group); mGroupedData.get(group.groupKey).add(activeCall); } } public Group [] getGroupedData() { return mGroupedData.values().toArray(new Group[0]); } /** * @param groupPosition * @param childPosition * @return идентификатор записи разговора */ public long getChildId(int groupPosition, int childPosition) { return getGroupedData()[groupPosition].get(childPosition).getId(); } public long getGroupId(int groupPosition) { return -groupPosition; } public Object getGroup(int position) { return position; } public ActiveCall getChild(int groupPosition, int childPosition) { return getGroupedData()[groupPosition].get(childPosition); } public int getGroupCount() { return mGroupedData.size(); } public int getChildrenCount(int groupPosition) { return getCallGroup(groupPosition).size(); } public Group getCallGroup(int groupPosition) { if(groupPosition > getGroupedData().length - 1 || groupPosition < 0) return new Group(); return getGroupedData()[groupPosition]; } private Hashtable <String, View> _group_view_cache =new Hashtable<String, View>(); public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) { // Если вылезли за пределы массива if(mGroupedData.size() <= groupPosition) return new TextView(mContext); String groupKey = getGroupedData()[groupPosition].groupKey; if(_group_view_cache.containsKey(groupKey)){ View view = _group_view_cache.get(groupKey); if(view instanceof Cachable && !((Cachable) view).isInvalid()){ return view; } } /* // Пробовал повторно использовать convertedView, как рекоммендует Гугл - <NAME> if(convertView instanceof ViewOneGroup){ ViewOneGroup ooo = (ViewOneGroup)convertView; ooo.fillViewsFromGroup(getGroupedData()[groupPosition]); return ooo; } */ View view = mViewGroupFactory.createView(mContext, getGroupedData()[groupPosition]); ((ViewOneGroup)view).fillViews(); _group_view_cache.put(groupKey, view); return view; } private Hashtable <Long, View> _child_view_cache = new Hashtable<Long, View>(); public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) { if(convertView instanceof ViewOneRecord){ ViewOneRecord ooo = (ViewOneRecord)convertView; ooo.fillFromActiveCall(getChild(groupPosition,childPosition)); return ooo; } /* if(convertView instanceof ViewOneRecord2){ ViewOneRecord2 ooo = (ViewOneRecord2)convertView; ooo.fillFromActiveCall(getChild(groupPosition,childPosition)); return ooo; } */ /* long id = getChildId(groupPosition, childPosition); if(_child_view_cache.containsKey(id)){ View view = _child_view_cache.get(id); if(view instanceof Cachable && !((Cachable) view).isInvalid()){ return view; } } */ ViewOneRecord viewRecord = new ViewOneRecord(mContext, getChild(groupPosition,childPosition)); //ViewOneRecord2 viewRecord = new ViewOneRecord2(mContext, getChild(groupPosition,childPosition)); //_child_view_cache.put(id, viewRecord); return viewRecord; } public boolean isChildSelectable(int groupPosition, int childPosition) { return true; } public boolean hasStableIds() { return true; } public void clearViewCache() { _child_view_cache.clear(); } }
6,376
0.655365
0.652181
204
29.794117
28.490225
131
false
false
0
0
0
0
0
0
0.563725
false
false
11
a1e4d95bd8480714f8053937844a7bc8079e59dd
14,912,126,508,637
5677ee5834fcd0e632a4d6d08a7728bfe02aa342
/src/main/esgi/ddd/common/repository/BaseRepository.java
0cd6ee32d2266af3c7e6895ef0910778ae6ee878
[]
no_license
mvilalard/DDD
https://github.com/mvilalard/DDD
8137c621995ed6aa848b0a2f7aaa6d98a8f3f0a9
dccd9667c4170b397e06cd22f1b0765c2b687777
refs/heads/master
2022-05-27T16:27:44.497000
2020-04-24T17:12:03
2020-04-24T17:12:03
258,234,074
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package main.esgi.ddd.common.repository; import main.esgi.ddd.common.entity.Entity; import main.esgi.ddd.common.valueObjectId.ValueObjectId; import java.util.HashSet; public abstract class BaseRepository implements IRepository { HashSet<Entity> entities; public BaseRepository(HashSet<Entity> entities) { this.entities = entities; } public BaseRepository() { this(new HashSet<>()); } @Override public HashSet<Entity> getEntities() { return entities; } @Override public Entity getEntity(ValueObjectId id) { for (Entity entity : entities) { if (entity.getId() == id) { return entity; } } return null; } @Override public void add(Entity entity) { this.entities.add(entity); } @Override public void remove(Entity entity) { this.entities.remove(entity); } }
UTF-8
Java
936
java
BaseRepository.java
Java
[]
null
[]
package main.esgi.ddd.common.repository; import main.esgi.ddd.common.entity.Entity; import main.esgi.ddd.common.valueObjectId.ValueObjectId; import java.util.HashSet; public abstract class BaseRepository implements IRepository { HashSet<Entity> entities; public BaseRepository(HashSet<Entity> entities) { this.entities = entities; } public BaseRepository() { this(new HashSet<>()); } @Override public HashSet<Entity> getEntities() { return entities; } @Override public Entity getEntity(ValueObjectId id) { for (Entity entity : entities) { if (entity.getId() == id) { return entity; } } return null; } @Override public void add(Entity entity) { this.entities.add(entity); } @Override public void remove(Entity entity) { this.entities.remove(entity); } }
936
0.61859
0.61859
45
19.799999
18.301912
61
false
false
0
0
0
0
0
0
0.266667
false
false
11
1005c63c94a4ebaa484a5350320cfd08fcea08de
36,507,222,030,248
9e2571e0af67ebf4d1d2f32dd0b5ff63a1e3f94e
/src/main/java/com/team17/bikeworld/controller/ProductController.java
3186f0344eb1b8f886773f7ae33ad156f7644969
[]
no_license
hieplk97/BikeWorld_Capstone
https://github.com/hieplk97/BikeWorld_Capstone
7d1931c15c27ca5abf49e1379ec0b3408f44ab47
efe1124fe3cd987b2591ee9c3f2748935d620717
refs/heads/master
2020-04-02T07:26:50.751000
2018-10-23T19:35:18
2018-10-23T19:35:18
154,196,323
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.team17.bikeworld.controller; import com.team17.bikeworld.common.CoreConstant; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; @Controller public interface ProductController { @GetMapping(CoreConstant.API_PRODUCT + "/create") public void createProduct(@RequestParam(value = "txtName") String txtName, @RequestParam(value = "txtDescription") String txtDescription, @RequestParam(value = "txtPrice") Double txtPrice, @RequestParam(value = "txtLongtitude") String txtLongtitude, @RequestParam(value = "txtLatitude") String txtLatitude, @RequestParam(value = "txtAddress") String txtAddress, @RequestParam(value = "txtSeller") String txtSeller, @RequestParam(value = "txtCategory") Integer txtCategory, @RequestParam(value = "txtBrand") Integer txtBrand, @RequestParam (required = false)MultipartFile images); @GetMapping(CoreConstant.API_PRODUCT + "/update") public void updateProduct(@RequestParam (value="txtId") int txtId, @RequestParam(value = "txtName") String txtName, @RequestParam(value = "txtDescription") String txtDescription, @RequestParam(value = "txtPrice") Double txtPrice, @RequestParam(value = "txtLongtitude") String txtLongtitude, @RequestParam(value = "txtLatitude") String txtLatitude, @RequestParam(value = "txtAddress") String txtAddress, @RequestParam(value = "txtSeller") String txtSeller, @RequestParam(value = "txtCategory") Integer txtCategory, @RequestParam(value = "txtBrand") Integer txtBrand, @RequestParam (required = false)MultipartFile images); }
UTF-8
Java
2,190
java
ProductController.java
Java
[]
null
[]
package com.team17.bikeworld.controller; import com.team17.bikeworld.common.CoreConstant; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; @Controller public interface ProductController { @GetMapping(CoreConstant.API_PRODUCT + "/create") public void createProduct(@RequestParam(value = "txtName") String txtName, @RequestParam(value = "txtDescription") String txtDescription, @RequestParam(value = "txtPrice") Double txtPrice, @RequestParam(value = "txtLongtitude") String txtLongtitude, @RequestParam(value = "txtLatitude") String txtLatitude, @RequestParam(value = "txtAddress") String txtAddress, @RequestParam(value = "txtSeller") String txtSeller, @RequestParam(value = "txtCategory") Integer txtCategory, @RequestParam(value = "txtBrand") Integer txtBrand, @RequestParam (required = false)MultipartFile images); @GetMapping(CoreConstant.API_PRODUCT + "/update") public void updateProduct(@RequestParam (value="txtId") int txtId, @RequestParam(value = "txtName") String txtName, @RequestParam(value = "txtDescription") String txtDescription, @RequestParam(value = "txtPrice") Double txtPrice, @RequestParam(value = "txtLongtitude") String txtLongtitude, @RequestParam(value = "txtLatitude") String txtLatitude, @RequestParam(value = "txtAddress") String txtAddress, @RequestParam(value = "txtSeller") String txtSeller, @RequestParam(value = "txtCategory") Integer txtCategory, @RequestParam(value = "txtBrand") Integer txtBrand, @RequestParam (required = false)MultipartFile images); }
2,190
0.582192
0.580365
37
58.18919
33.371647
92
false
false
0
0
0
0
0
0
0.702703
false
false
11
d9dcd7b809ede500db4e729dbc13c19867370494
19,963,008,048,317
19a7f078b342d934e82778aeeb410217680d37ac
/recrutamento-teste-carrinho-compras-lindomarjunior/src/test/java/br/com/improving/carrinho/CarrinhoComprasTest.java
0798e3cc64cd0c8819cde719311ff7a4616859e8
[]
no_license
lindomarJunior/carrinhoDeCompras
https://github.com/lindomarJunior/carrinhoDeCompras
1f80b3eb651d46338df55f34465f71b5f490202e
4819e35a0118d8ea15b663ce686647793439bd8c
refs/heads/master
2020-03-27T03:44:22.281000
2018-08-23T17:35:36
2018-08-23T17:35:36
145,885,953
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package br.com.improving.carrinho; import static org.junit.Assert.*; import java.math.BigDecimal; import java.util.List; import org.junit.Test; public class CarrinhoComprasTest { @Test public void testAdicionarItem() { CarrinhoComprasFactory CarrinhoComprasFactory = new CarrinhoComprasFactory(); String identificacaoCliente = "Joao"; CarrinhoCompras carrinhoCompras = CarrinhoComprasFactory.criar(identificacaoCliente); Produto produto1 = new Produto(1l, "Sabão"); carrinhoCompras.adicionarItem(produto1, new BigDecimal("15.31"), 2); List<Item> listaItem = (List<Item>) carrinhoCompras.getItens(); Item item = null; try { item = listaItem.get(0); } catch (Exception e) { fail(e.getMessage()); } assertNotNull(item); } @Test public void testRemoverItem() { CarrinhoComprasFactory CarrinhoComprasFactory = new CarrinhoComprasFactory(); String identificacaoCliente = "Joao"; CarrinhoCompras carrinhoCompras = CarrinhoComprasFactory.criar(identificacaoCliente); Produto produto1 = new Produto(1l, "Sabão"); carrinhoCompras.adicionarItem(produto1, new BigDecimal("15.31"), 2); carrinhoCompras.removerItem(produto1); assertTrue(carrinhoCompras.getItens().isEmpty()); } @Test public void testRemoverItemInt() { CarrinhoComprasFactory CarrinhoComprasFactory = new CarrinhoComprasFactory(); String identificacaoCliente = "Joao"; CarrinhoCompras carrinhoCompras = CarrinhoComprasFactory.criar(identificacaoCliente); Produto produto1 = new Produto(1l, "Sabão"); carrinhoCompras.adicionarItem(produto1, new BigDecimal("15.31"), 2); carrinhoCompras.removerItem(0); assertTrue(carrinhoCompras.getItens().isEmpty()); } @Test public void testGetValorTotal() { CarrinhoComprasFactory CarrinhoComprasFactory = new CarrinhoComprasFactory(); String identificacaoCliente = "Joao"; CarrinhoCompras carrinhoCompras = CarrinhoComprasFactory.criar(identificacaoCliente); Produto produto1 = new Produto(1l, "Sabão"); Produto produto2 = new Produto(2l, "Arroz"); carrinhoCompras.adicionarItem(produto1, new BigDecimal("15.31"), 1); carrinhoCompras.adicionarItem(produto2, new BigDecimal("16.31"), 1); BigDecimal expected = new BigDecimal("31.62"); BigDecimal actual = carrinhoCompras.getValorTotal(); assertEquals(expected, actual); } }
UTF-8
Java
2,445
java
CarrinhoComprasTest.java
Java
[ { "context": "mprasFactory();\r\n\t\tString identificacaoCliente = \"Joao\";\r\n\t\tCarrinhoCompras carrinhoCompras = CarrinhoCo", "end": 357, "score": 0.9912838339805603, "start": 353, "tag": "NAME", "value": "Joao" }, { "context": "nte);\r\n\t\t\r\n\t\tProduto produto1 = new Produto(1l, \"Sabão\");\t\t\t\t\t\t\r\n\t\tcarrinhoCompras.adicionarItem(produto", "end": 497, "score": 0.631591796875, "start": 493, "tag": "NAME", "value": "abão" }, { "context": "mprasFactory();\r\n\t\tString identificacaoCliente = \"Joao\";\r\n\t\tCarrinhoCompras carrinhoCompras = CarrinhoCo", "end": 960, "score": 0.9907577037811279, "start": 956, "tag": "NAME", "value": "Joao" }, { "context": "mprasFactory();\r\n\t\tString identificacaoCliente = \"Joao\";\r\n\t\tCarrinhoCompras carrinhoCompras = CarrinhoCo", "end": 1455, "score": 0.9920908212661743, "start": 1451, "tag": "NAME", "value": "Joao" }, { "context": "ente);\r\n\t\t\r\n\t\tProduto produto1 = new Produto(1l, \"Sabão\");\t\r\n\t\t\r\n\t\tcarrinhoCompras.adicionarItem(produto1", "end": 1595, "score": 0.9996066689491272, "start": 1590, "tag": "NAME", "value": "Sabão" }, { "context": "mprasFactory();\r\n\t\tString identificacaoCliente = \"Joao\";\r\n\t\tCarrinhoCompras carrinhoCompras = CarrinhoCo", "end": 1937, "score": 0.9906144142150879, "start": 1933, "tag": "NAME", "value": "Joao" }, { "context": "ente);\r\n\t\t\r\n\t\tProduto produto1 = new Produto(1l, \"Sabão\");\t\r\n\t\tProduto produto2 = new Produto(2l, \"Arroz\"", "end": 2077, "score": 0.9995463490486145, "start": 2072, "tag": "NAME", "value": "Sabão" }, { "context": "\"Sabão\");\t\r\n\t\tProduto produto2 = new Produto(2l, \"Arroz\");\t\r\n\t\t\r\n\t\tcarrinhoCompras.adicionarItem(produto1", "end": 2126, "score": 0.9996775984764099, "start": 2121, "tag": "NAME", "value": "Arroz" } ]
null
[]
package br.com.improving.carrinho; import static org.junit.Assert.*; import java.math.BigDecimal; import java.util.List; import org.junit.Test; public class CarrinhoComprasTest { @Test public void testAdicionarItem() { CarrinhoComprasFactory CarrinhoComprasFactory = new CarrinhoComprasFactory(); String identificacaoCliente = "Joao"; CarrinhoCompras carrinhoCompras = CarrinhoComprasFactory.criar(identificacaoCliente); Produto produto1 = new Produto(1l, "Sabão"); carrinhoCompras.adicionarItem(produto1, new BigDecimal("15.31"), 2); List<Item> listaItem = (List<Item>) carrinhoCompras.getItens(); Item item = null; try { item = listaItem.get(0); } catch (Exception e) { fail(e.getMessage()); } assertNotNull(item); } @Test public void testRemoverItem() { CarrinhoComprasFactory CarrinhoComprasFactory = new CarrinhoComprasFactory(); String identificacaoCliente = "Joao"; CarrinhoCompras carrinhoCompras = CarrinhoComprasFactory.criar(identificacaoCliente); Produto produto1 = new Produto(1l, "Sabão"); carrinhoCompras.adicionarItem(produto1, new BigDecimal("15.31"), 2); carrinhoCompras.removerItem(produto1); assertTrue(carrinhoCompras.getItens().isEmpty()); } @Test public void testRemoverItemInt() { CarrinhoComprasFactory CarrinhoComprasFactory = new CarrinhoComprasFactory(); String identificacaoCliente = "Joao"; CarrinhoCompras carrinhoCompras = CarrinhoComprasFactory.criar(identificacaoCliente); Produto produto1 = new Produto(1l, "Sabão"); carrinhoCompras.adicionarItem(produto1, new BigDecimal("15.31"), 2); carrinhoCompras.removerItem(0); assertTrue(carrinhoCompras.getItens().isEmpty()); } @Test public void testGetValorTotal() { CarrinhoComprasFactory CarrinhoComprasFactory = new CarrinhoComprasFactory(); String identificacaoCliente = "Joao"; CarrinhoCompras carrinhoCompras = CarrinhoComprasFactory.criar(identificacaoCliente); Produto produto1 = new Produto(1l, "Sabão"); Produto produto2 = new Produto(2l, "Arroz"); carrinhoCompras.adicionarItem(produto1, new BigDecimal("15.31"), 1); carrinhoCompras.adicionarItem(produto2, new BigDecimal("16.31"), 1); BigDecimal expected = new BigDecimal("31.62"); BigDecimal actual = carrinhoCompras.getValorTotal(); assertEquals(expected, actual); } }
2,445
0.727161
0.707907
78
29.294872
28.412308
87
false
false
0
0
0
0
0
0
2.371795
false
false
11
6199e6e32310a6b951ec70fab11b8c2bdadd4be9
36,704,790,524,141
9b89724054fadcd47aaa70b8e29a1d2f77edc248
/Android Apps/Wordpedia/app/src/main/java/com/example/android/wordspedia/data/GitHubRepoDao.java
119582e80d99d8fbb9a5530b14bc0d81c40eafe0
[]
no_license
Rohrj/Projects
https://github.com/Rohrj/Projects
ede2644c85ef6ef79acfc90d9d2703150f235e4e
1307d04dd3d3d3b5ef981bf7d128a0e08041fc08
refs/heads/master
2020-06-28T05:19:56.944000
2019-12-24T00:17:02
2019-12-24T00:17:02
200,151,374
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.android.wordspedia.data; import android.arch.persistence.room.Dao; import android.arch.persistence.room.Delete; import android.arch.persistence.room.Insert; @Dao public interface GitHubRepoDao { @Insert void insert(GitHubRepo repo); @Delete void delete(GitHubRepo repo); }
UTF-8
Java
312
java
GitHubRepoDao.java
Java
[]
null
[]
package com.example.android.wordspedia.data; import android.arch.persistence.room.Dao; import android.arch.persistence.room.Delete; import android.arch.persistence.room.Insert; @Dao public interface GitHubRepoDao { @Insert void insert(GitHubRepo repo); @Delete void delete(GitHubRepo repo); }
312
0.769231
0.769231
14
21.285715
18.140045
44
false
false
0
0
0
0
0
0
0.428571
false
false
11
df6f1c2cb0ca4c0bd9ac31189e7108bc0c6fecb0
37,323,265,817,243
3a215e4fda42db78a497c35d063d7230a70c142a
/src/main/java/jp/co/rakus/bbs/repository/ArticlesRepository.java
a1d1a42f5ba19bca48bbaa749c7f737c2e14b2e9
[ "MIT" ]
permissive
nake226/kouenji
https://github.com/nake226/kouenji
618e9a05f35aa2d28c1e8f01f6937b3b752898b3
bfef3bdd582a3303ecbde47f01a3530455fd604f
refs/heads/master
2018-04-02T04:51:36.886000
2017-02-05T03:01:25
2017-02-05T03:01:25
80,904,411
0
1
null
false
2017-02-04T08:48:34
2017-02-04T08:05:31
2017-02-04T08:05:31
2017-02-04T08:48:34
0
0
1
0
null
null
null
package jp.co.rakus.bbs.repository; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.RowMapper; import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource; import org.springframework.jdbc.core.namedparam.MapSqlParameterSource; import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; import org.springframework.jdbc.core.namedparam.SqlParameterSource; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; import jp.co.rakus.bbs.domain.Article; /** * articlesテーブルに対してSQLを実行するクラス(DAO) * @author HirokiHashi * 所属:株式会社ラクス * 作成日:2016.11.14 * */ @Repository @Transactional public class ArticlesRepository { /** * テーブル名 */ private final String TABLE_NAME = "articles"; @Autowired NamedParameterJdbcTemplate template; /** * RowMapperの実装 * SQLの結果からArticleオブジェクトを生成 */ private static final RowMapper<Article> articleRowMapper = (rs ,i) ->{ Integer id = rs.getInt("id"); String name = rs.getString("name"); String content = rs.getString("content"); return new Article(id ,name ,content); }; /** * articleテーブルからカラムを全件取得 * @return List<Article> */ public List<Article> findAll(){ String sql = "select id ,name ,content from " + TABLE_NAME; List<Article> articleList = template.query(sql, articleRowMapper); return articleList; } /** * 引数のAritcleオブジェクトの情報を元にarticleテーブルに1件insert * @param article */ public void insert(Article article){ SqlParameterSource param = new BeanPropertySqlParameterSource(article); String sql = "insert into " + TABLE_NAME + "(name ,content) values(:name ,:content)"; template.update(sql, param); } /** * 引数のidを持つ行をarticleテーブルから削除 * @param id */ public void deleteArticle(Integer id){ String sql ="delete from "+ TABLE_NAME +" where id = :id"; SqlParameterSource param = new MapSqlParameterSource().addValue("id", id); template.update(sql, param); } }
UTF-8
Java
2,305
java
ArticlesRepository.java
Java
[ { "context": "*\r\n * articlesテーブルに対してSQLを実行するクラス(DAO)\r\n * @author HirokiHashi\r\n * 所属:株式会社ラクス\r\n * 作成日:2016.11.14\r\n *\r\n */\r\n@Repo", "end": 702, "score": 0.997918963432312, "start": 691, "tag": "NAME", "value": "HirokiHashi" } ]
null
[]
package jp.co.rakus.bbs.repository; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.RowMapper; import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource; import org.springframework.jdbc.core.namedparam.MapSqlParameterSource; import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; import org.springframework.jdbc.core.namedparam.SqlParameterSource; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; import jp.co.rakus.bbs.domain.Article; /** * articlesテーブルに対してSQLを実行するクラス(DAO) * @author HirokiHashi * 所属:株式会社ラクス * 作成日:2016.11.14 * */ @Repository @Transactional public class ArticlesRepository { /** * テーブル名 */ private final String TABLE_NAME = "articles"; @Autowired NamedParameterJdbcTemplate template; /** * RowMapperの実装 * SQLの結果からArticleオブジェクトを生成 */ private static final RowMapper<Article> articleRowMapper = (rs ,i) ->{ Integer id = rs.getInt("id"); String name = rs.getString("name"); String content = rs.getString("content"); return new Article(id ,name ,content); }; /** * articleテーブルからカラムを全件取得 * @return List<Article> */ public List<Article> findAll(){ String sql = "select id ,name ,content from " + TABLE_NAME; List<Article> articleList = template.query(sql, articleRowMapper); return articleList; } /** * 引数のAritcleオブジェクトの情報を元にarticleテーブルに1件insert * @param article */ public void insert(Article article){ SqlParameterSource param = new BeanPropertySqlParameterSource(article); String sql = "insert into " + TABLE_NAME + "(name ,content) values(:name ,:content)"; template.update(sql, param); } /** * 引数のidを持つ行をarticleテーブルから削除 * @param id */ public void deleteArticle(Integer id){ String sql ="delete from "+ TABLE_NAME +" where id = :id"; SqlParameterSource param = new MapSqlParameterSource().addValue("id", id); template.update(sql, param); } }
2,305
0.72315
0.718854
71
27.507042
24.905384
87
false
false
0
0
0
0
0
0
1.366197
false
false
11
ddfdaaeb91dfae269bb1d4c40164246f8acfac2e
20,993,800,191,661
0c0b9c5f76228ff7052f09e9063c06aa6cc90c6e
/src/main/java/com/example/demo/config/BaseUrlManager.java
f5d7b5caf061796b442abcfc52ff1cf716e78b4f
[]
no_license
UniZhangHaiyan/spring-boot-demo
https://github.com/UniZhangHaiyan/spring-boot-demo
b195aa7151010ae45ba92fea909653850dd6911a
3877fd70c510200a9ba0525d4084ff8d49bc974c
refs/heads/master
2023-08-09T09:05:21.562000
2021-10-28T11:56:43
2021-10-28T11:56:43
172,041,724
0
0
null
false
2023-07-21T10:46:47
2019-02-22T10:00:02
2021-10-28T11:58:54
2023-07-21T10:46:46
94
0
0
1
Java
false
false
package com.example.demo.config; import org.springframework.beans.factory.annotation.Value; /** * @ClassName BaseUrlManager * @Description baseUrl配置管理 * retrofit 的baseUrl必须以"/"结尾 * @Author zhanghaiyan * @Date 2021/8/1 * @Modifier */ public class BaseUrlManager { public static String BAI_DU_URL; public static String GIT_HUB_URL; public static String DEFAULT_URL; @Value("${retrofit.base-url.baidu}") public void setBaiDuUrl(String baiDuUrl) { BAI_DU_URL = endWithSlashForce(baiDuUrl); } @Value("${retrofit.base-url.github}") public void setGitHubUrl(String gitHubUrl) { GIT_HUB_URL = endWithSlashForce(gitHubUrl); } @Value("${retrofit.base-url.baidu}") public void setDefaultUrl(String defaultUrl) { DEFAULT_URL = endWithSlashForce(defaultUrl); } /** * 强制斜杠结尾 * @param baseUrl * @return */ private String endWithSlashForce(String baseUrl) { if (baseUrl.endsWith("/")) return baseUrl; return baseUrl + "/"; } }
UTF-8
Java
1,076
java
BaseUrlManager.java
Java
[ { "context": "aseUrl配置管理\n * retrofit 的baseUrl必须以\"/\"结尾\n * @Author zhanghaiyan\n * @Date 2021/8/1\n * @Modifier\n */\npublic class B", "end": 206, "score": 0.999638020992279, "start": 195, "tag": "USERNAME", "value": "zhanghaiyan" } ]
null
[]
package com.example.demo.config; import org.springframework.beans.factory.annotation.Value; /** * @ClassName BaseUrlManager * @Description baseUrl配置管理 * retrofit 的baseUrl必须以"/"结尾 * @Author zhanghaiyan * @Date 2021/8/1 * @Modifier */ public class BaseUrlManager { public static String BAI_DU_URL; public static String GIT_HUB_URL; public static String DEFAULT_URL; @Value("${retrofit.base-url.baidu}") public void setBaiDuUrl(String baiDuUrl) { BAI_DU_URL = endWithSlashForce(baiDuUrl); } @Value("${retrofit.base-url.github}") public void setGitHubUrl(String gitHubUrl) { GIT_HUB_URL = endWithSlashForce(gitHubUrl); } @Value("${retrofit.base-url.baidu}") public void setDefaultUrl(String defaultUrl) { DEFAULT_URL = endWithSlashForce(defaultUrl); } /** * 强制斜杠结尾 * @param baseUrl * @return */ private String endWithSlashForce(String baseUrl) { if (baseUrl.endsWith("/")) return baseUrl; return baseUrl + "/"; } }
1,076
0.658046
0.652299
42
23.857143
19.123125
58
false
false
0
0
0
0
0
0
0.238095
false
false
11
f5388ce773011d54876cc35c41d86ea8a14c4813
20,993,800,192,083
94311ca7dc6c28c4212b2a7e41782409ee4b96cb
/saas-meter/src/com/logscape/meter/AccountManager.java
2c52b727764451a8e533009ddf88b26755eaa4b2
[ "Apache-2.0", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
logscape/Logscape
https://github.com/logscape/Logscape
5856f3bf55fb1723b57ec9fce7f7546ee4cd27f1
fde9133797b8f1d03f824c65e26e352ae5677063
refs/heads/master
2021-09-01T08:47:12.323000
2021-04-01T07:58:15
2021-04-01T07:58:15
89,608,168
28
10
NOASSERTION
false
2021-08-02T17:19:32
2017-04-27T14:43:31
2021-04-01T07:58:27
2021-08-02T17:19:31
202,484
24
7
4
Java
false
false
package com.logscape.meter; import com.liquidlabs.admin.User; import com.liquidlabs.admin.UserSpace; import com.liquidlabs.transport.proxy.Remotable; /** * Created with IntelliJ IDEA. * User: Neiil * Date: 29/10/14 * Time: 08:38 * To change this template use File | Settings | File Templates. */ public interface AccountManager extends Remotable { String createUserAccount(String email, String pwd, String hostsList, int dailyMb, int dataRetentionDays); User getUserAccount(String userId); String deleteUserAccount(String userId); String addIpToAccount(String uid, String ip); String listAccounts(); int getMaxDataVolume(); int getMaxDataRetention(); String status(); void setStatus(String status); }
UTF-8
Java
754
java
AccountManager.java
Java
[ { "context": "able;\n\n/**\n * Created with IntelliJ IDEA.\n * User: Neiil\n * Date: 29/10/14\n * Time: 08:38\n * To change thi", "end": 201, "score": 0.9967848658561707, "start": 196, "tag": "USERNAME", "value": "Neiil" } ]
null
[]
package com.logscape.meter; import com.liquidlabs.admin.User; import com.liquidlabs.admin.UserSpace; import com.liquidlabs.transport.proxy.Remotable; /** * Created with IntelliJ IDEA. * User: Neiil * Date: 29/10/14 * Time: 08:38 * To change this template use File | Settings | File Templates. */ public interface AccountManager extends Remotable { String createUserAccount(String email, String pwd, String hostsList, int dailyMb, int dataRetentionDays); User getUserAccount(String userId); String deleteUserAccount(String userId); String addIpToAccount(String uid, String ip); String listAccounts(); int getMaxDataVolume(); int getMaxDataRetention(); String status(); void setStatus(String status); }
754
0.736074
0.722812
32
22.5625
24.543249
109
false
false
0
0
0
0
0
0
0.625
false
false
11
1aa885ed4e54106cfd709db0dcd80ffafc3070e9
31,868,657,402,644
8dd2a493193c4e82837a5ca822bee7d0ccb8b7bd
/Implementation/DataMiner/Coordinator/src/main/java/Coordinator/Interface/abstractClasses/AbstractAnalyzer.java
c0bac2abe3842c1bab89695fc35a307b97b7bd2f
[]
no_license
hannibalhh/CAS
https://github.com/hannibalhh/CAS
d9559cfba46a4fab59146723bafc5d25681161be
dad711e246e4553c36913b96532f77ea091e63cf
refs/heads/master
2020-05-30T04:08:34.125000
2014-04-11T15:14:35
2014-04-11T15:14:35
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package Coordinator.Interface.abstractClasses; import Coordinator.Interface.ICoordinator; import DSPersistenceManager.Model.Message; import DataTypes.DataTypeInterfaces.IInfo; import Interfaces.IAnalyzer; import MessageAdapter.Interface.IMessageAdapter; import org.apache.commons.lang3.exception.ExceptionUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import java.util.*; import java.util.concurrent.Semaphore; /** * Created with IntelliJ IDEA. * User: sebastian * Date: 31.10.13 * Time: 14:14 * To change this template use File | Settings | File Templates. */ public abstract class AbstractAnalyzer implements IAnalyzer { private AnalyzerThread analyzerThread = null; private IMessageAdapter messageAdapter = null; private ICoordinator coordinator; private IAnalyzer currentAnalyzer; private Logger logger; private String analyzerName = null; protected AbstractAnalyzer(IMessageAdapter messageAdapter, ICoordinator coordinator) { this.messageAdapter = messageAdapter; this.coordinator = coordinator; messageAdapter.addNewMessageChunkArrivedListener(this::onNewMessageChunkArrived); coordinator.registerAnalyzer(this); this.currentAnalyzer = this; analyzerThread = new AnalyzerThread(); logger = LogManager.getLogger(this.getClass()); } public void onNewMessageChunkArrived(Iterable<Message> messageChunk) { this.analyzerThread.processWorkSet(messageChunk); } protected abstract Map<Message, List<IInfo>> processMessages(Iterable<Message> messages) throws Throwable; public void stopAnalyzer() { analyzerThread.stop(); } public void startAnalyzer() { new Thread(analyzerThread).start(); } private String getAnalyzerNameForLogging() { if (this.analyzerName == null) { this.analyzerName = this.getClass().getSimpleName(); } return analyzerName; } private class AnalyzerThread implements Runnable { private boolean shouldRun = false; private Semaphore waitHandleForMessageChunk = new Semaphore(0); private List<Message> currentWorkSet; @Override public void run() { try { shouldRun = true; while (shouldRun) { logger.debug("Analyzer " + getAnalyzerNameForLogging() + " is waiting for a message chunk to arrive."); waitHandleForMessageChunk.acquire(); logger.debug("Analyzer " + getAnalyzerNameForLogging() + " got a message chunk and will now start to analyze the containing messages."); if (!shouldRun) { return; } Map<String, List<IInfo>> results = new HashMap<>(); try { Map<Message, List<IInfo>> processedMessages = processMessages(currentWorkSet); Iterator<Map.Entry<Message, List<IInfo>>> processedMessagesIterator = processedMessages.entrySet().iterator(); while(processedMessagesIterator.hasNext()){ Map.Entry<Message, List<IInfo>> nextEntry = processedMessagesIterator.next(); Message message = nextEntry.getKey(); List<IInfo> infos = nextEntry.getValue(); results.put(message.getId(), infos); } } catch (Throwable e) { results = new HashMap<>(); for(Message message : currentWorkSet) { results.put(message.getId(), new ArrayList<IInfo>()); } logger.error("Error while processing message chunk in Analyzer: '" + getAnalyzerNameForLogging() + "'. The analyzer will continue running and return an empty result list for this chunk. The error message was:\n\n" + ExceptionUtils.getStackTrace(e)); } coordinator.registerAnalyzerResultForCurrentChunk(currentAnalyzer, results); logger.debug("Analyzer " + getAnalyzerNameForLogging() + " has completed processing the message chunk and his passed its results to the Coordinator."); } } catch (InterruptedException e) { e.printStackTrace(); this.shouldRun = false; } } public void stop() { this.shouldRun = false; } public void processWorkSet(Iterable<Message> workSet) { this.currentWorkSet = new ArrayList<>(); for(Message m : workSet) { currentWorkSet.add(m); } if (this.waitHandleForMessageChunk.availablePermits() > 0) { /** * Todo: Überlegen * Available permits kann > 0 sein, wenn die anderen analyser schneller sind als dieser. dann * beenden die anderen analyzer ihre arbeit vor diesem und bekommen neue arbeit. da jeder analyzer * diese arbeit bekommt, bekommt auch dieser noch arbeitende sie. aus diesem grund wird sein semaphor * um 1 erhöht. * Das ist auch nicht schlimm, da das semaphor ja nur dazu da ist, den process schlafen zu legen falls * noch keine arbeit da ist */ throw new RuntimeException("Fatal error in Analyzer Thread. Too many available permits in semaphore! Something has gone terribly wrong!"); } this.waitHandleForMessageChunk.release(); } } }
UTF-8
Java
5,869
java
AbstractAnalyzer.java
Java
[ { "context": "hore;\n\n/**\n * Created with IntelliJ IDEA.\n * User: sebastian\n * Date: 31.10.13\n * Time: 14:14\n * To change thi", "end": 511, "score": 0.9990325570106506, "start": 502, "tag": "USERNAME", "value": "sebastian" } ]
null
[]
package Coordinator.Interface.abstractClasses; import Coordinator.Interface.ICoordinator; import DSPersistenceManager.Model.Message; import DataTypes.DataTypeInterfaces.IInfo; import Interfaces.IAnalyzer; import MessageAdapter.Interface.IMessageAdapter; import org.apache.commons.lang3.exception.ExceptionUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import java.util.*; import java.util.concurrent.Semaphore; /** * Created with IntelliJ IDEA. * User: sebastian * Date: 31.10.13 * Time: 14:14 * To change this template use File | Settings | File Templates. */ public abstract class AbstractAnalyzer implements IAnalyzer { private AnalyzerThread analyzerThread = null; private IMessageAdapter messageAdapter = null; private ICoordinator coordinator; private IAnalyzer currentAnalyzer; private Logger logger; private String analyzerName = null; protected AbstractAnalyzer(IMessageAdapter messageAdapter, ICoordinator coordinator) { this.messageAdapter = messageAdapter; this.coordinator = coordinator; messageAdapter.addNewMessageChunkArrivedListener(this::onNewMessageChunkArrived); coordinator.registerAnalyzer(this); this.currentAnalyzer = this; analyzerThread = new AnalyzerThread(); logger = LogManager.getLogger(this.getClass()); } public void onNewMessageChunkArrived(Iterable<Message> messageChunk) { this.analyzerThread.processWorkSet(messageChunk); } protected abstract Map<Message, List<IInfo>> processMessages(Iterable<Message> messages) throws Throwable; public void stopAnalyzer() { analyzerThread.stop(); } public void startAnalyzer() { new Thread(analyzerThread).start(); } private String getAnalyzerNameForLogging() { if (this.analyzerName == null) { this.analyzerName = this.getClass().getSimpleName(); } return analyzerName; } private class AnalyzerThread implements Runnable { private boolean shouldRun = false; private Semaphore waitHandleForMessageChunk = new Semaphore(0); private List<Message> currentWorkSet; @Override public void run() { try { shouldRun = true; while (shouldRun) { logger.debug("Analyzer " + getAnalyzerNameForLogging() + " is waiting for a message chunk to arrive."); waitHandleForMessageChunk.acquire(); logger.debug("Analyzer " + getAnalyzerNameForLogging() + " got a message chunk and will now start to analyze the containing messages."); if (!shouldRun) { return; } Map<String, List<IInfo>> results = new HashMap<>(); try { Map<Message, List<IInfo>> processedMessages = processMessages(currentWorkSet); Iterator<Map.Entry<Message, List<IInfo>>> processedMessagesIterator = processedMessages.entrySet().iterator(); while(processedMessagesIterator.hasNext()){ Map.Entry<Message, List<IInfo>> nextEntry = processedMessagesIterator.next(); Message message = nextEntry.getKey(); List<IInfo> infos = nextEntry.getValue(); results.put(message.getId(), infos); } } catch (Throwable e) { results = new HashMap<>(); for(Message message : currentWorkSet) { results.put(message.getId(), new ArrayList<IInfo>()); } logger.error("Error while processing message chunk in Analyzer: '" + getAnalyzerNameForLogging() + "'. The analyzer will continue running and return an empty result list for this chunk. The error message was:\n\n" + ExceptionUtils.getStackTrace(e)); } coordinator.registerAnalyzerResultForCurrentChunk(currentAnalyzer, results); logger.debug("Analyzer " + getAnalyzerNameForLogging() + " has completed processing the message chunk and his passed its results to the Coordinator."); } } catch (InterruptedException e) { e.printStackTrace(); this.shouldRun = false; } } public void stop() { this.shouldRun = false; } public void processWorkSet(Iterable<Message> workSet) { this.currentWorkSet = new ArrayList<>(); for(Message m : workSet) { currentWorkSet.add(m); } if (this.waitHandleForMessageChunk.availablePermits() > 0) { /** * Todo: Überlegen * Available permits kann > 0 sein, wenn die anderen analyser schneller sind als dieser. dann * beenden die anderen analyzer ihre arbeit vor diesem und bekommen neue arbeit. da jeder analyzer * diese arbeit bekommt, bekommt auch dieser noch arbeitende sie. aus diesem grund wird sein semaphor * um 1 erhöht. * Das ist auch nicht schlimm, da das semaphor ja nur dazu da ist, den process schlafen zu legen falls * noch keine arbeit da ist */ throw new RuntimeException("Fatal error in Analyzer Thread. Too many available permits in semaphore! Something has gone terribly wrong!"); } this.waitHandleForMessageChunk.release(); } } }
5,869
0.602182
0.599284
145
39.46207
37.019478
171
false
false
0
0
0
0
0
0
0.496552
false
false
11
6224afc70fd6a3974ee8af2eb231c1e8509ea984
8,495,445,324,336
0c330497a79fee531cfb83a7da89edc27dddec3a
/msv/src/main/java/com/sun/msv/reader/trex/ng/comp/RELAXNGCompReader.java
ba62dfee4a513ec26dbfea3fc05836957a172971
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference", "Apache-1.1" ]
permissive
xmlark/msv
https://github.com/xmlark/msv
63dfd17d9b635eb00c97a28d3529fdaaef698a65
b9316e2f2270bc1606952ea4939ec87fbba157f3
refs/heads/main
2023-08-31T23:39:38.529000
2023-03-03T16:22:12
2023-03-03T17:49:32
216,036,776
18
9
MIT
false
2023-08-17T07:52:18
2019-10-18T14:01:35
2023-07-26T12:46:14
2023-06-30T23:41:34
28,735
15
19
4
Java
false
false
/* * Copyright (c) 2001-2013 Oracle and/or its affiliates. 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 Oracle nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.sun.msv.reader.trex.ng.comp; import java.text.MessageFormat; import java.util.Map; import java.util.ResourceBundle; import javax.xml.parsers.SAXParserFactory; import org.xml.sax.Attributes; import org.xml.sax.InputSource; import org.xml.sax.Locator; import org.xml.sax.SAXException; import com.sun.msv.grammar.AttributeExp; import com.sun.msv.grammar.ExpressionPool; import com.sun.msv.grammar.relaxng.RELAXNGGrammar; import com.sun.msv.grammar.trex.TREXGrammar; import com.sun.msv.reader.GrammarReaderController; import com.sun.msv.reader.State; import com.sun.msv.reader.trex.ng.RELAXNGReader; import com.sun.msv.util.LightStack; import com.sun.msv.util.StartTagInfo; /** * reads RELAX NG grammar with DTD compatibility annotation * and constructs abstract grammar model. * * @author <a href="mailto:kohsuke.kawaguchi@eng.sun.com">Kohsuke KAWAGUCHI</a> */ public class RELAXNGCompReader extends RELAXNGReader { /** loads RELAX NG pattern. * * @return * it always returns {@link RELAXNGGrammar}, but due to the * restriction imposed by Java language, I cannot change the * signature of this method. */ public static TREXGrammar parse( String grammarURL, GrammarReaderController controller ) { RELAXNGCompReader reader = new RELAXNGCompReader(controller); reader.parse(grammarURL); return reader.getResult(); } /** loads RELAX NG pattern. * * @return * it always returns {@link RELAXNGGrammar}, but due to the * restriction imposed by Java language, I cannot change the * signature of this method. */ public static TREXGrammar parse( InputSource grammar, GrammarReaderController controller ) { RELAXNGCompReader reader = new RELAXNGCompReader(controller); reader.parse(grammar); return reader.getResult(); } /** easy-to-use constructor. */ public RELAXNGCompReader( GrammarReaderController controller ) { this(controller,createParserFactory(),new ExpressionPool()); } /** easy-to-use constructor. */ public RELAXNGCompReader( GrammarReaderController controller, SAXParserFactory parserFactory, ExpressionPool pool ) { this(controller,parserFactory,new StateFactory(),pool); } /** full constructor */ public RELAXNGCompReader( GrammarReaderController controller, SAXParserFactory parserFactory, StateFactory stateFactory, ExpressionPool pool ) { super( controller, parserFactory, stateFactory, pool ); lastRNGElement.push(null); } private final Map<AttributeExp,String> defaultedAttributes = new java.util.HashMap<AttributeExp,String>(); /** * note that the specified expression is marked with the default value. * this method is called when a:defaultValue is found. */ protected final void addDefaultValue( AttributeExp exp, String value ) { // record the location where this attribute is declared. setDeclaredLocationOf(exp); if(defaultedAttributes.put(exp,value)!=null) throw new Error(); // it is not possible for one AttributeExp to be processed twice. } protected TREXGrammar getGrammar() { return grammar; } protected String localizeMessage( String propertyName, Object[] args ) { String format; try { format = ResourceBundle.getBundle("com.sun.msv.reader.trex.ng.comp.Messages").getString(propertyName); } catch( Exception e ) { return super.localizeMessage(propertyName,args); } return MessageFormat.format(format, args ); } /** Namespace URI of RELAX NG DTD compatibility annotation */ public static final String AnnotationNamespace = "http://relaxng.org/ns/compatibility/annotations/1.0"; /** * creates various State object, which in turn parses grammar. * parsing behavior can be customized by implementing custom StateFactory. */ public static class StateFactory extends RELAXNGReader.StateFactory { public State attribute ( State parent, StartTagInfo tag ) { return new CompAttributeState(); } public TREXGrammar createGrammar( ExpressionPool pool, TREXGrammar parent ) { return new RELAXNGGrammar(pool,parent); } } // protected StateFactory getStateFactory() { // return (StateFactory)super.sfactory; // } public void wrapUp() { super.wrapUp(); if(!controller.hadError()) { // do not check the compatibilities if some errors // are already reported. new DefAttCompatibilityChecker(this,defaultedAttributes).test(); new IDCompatibilityChecker(this).test(); } } /** * pair of an element name and an attribute name. */ /* private final static class ElemAttrNamePair { public final StringPair element; public final StringPair attribute; public int hashCode() { return element.hashCode()^attribute.hashCode(); } public boolean equals( Object o ) { if(!(o instanceof ElemAttrNamePair)) return false; ElemAttrNamePair rhs = (ElemAttrNamePair)o; return element.equals(rhs.element) && attribute.equals(rhs.attribute); } public ElemAttrNamePair( StringPair e, StringPair a ) { element=e; attribute=a; } public ElemAttrNamePair( String e_uri, String e_local, String a_uri, String a_local ) { this( new StringPair(e_uri,e_local), new StringPair(a_uri,a_local) ); } public ElemAttrNamePair( SimpleNameClass e, SimpleNameClass a ) { this( e.namespaceURI, e.localName, a.namespaceURI, a.localName ); } } */ /** * The local name of the preceding RELAX NG element sibling. */ private final LightStack lastRNGElement = new LightStack(); private boolean inAnnotation = false; public void startElement( String uri, String local, String qname, Attributes atts ) throws SAXException { super.startElement(uri,local,qname,atts); if(inAnnotation) { // we found a child element for a:annotation. // this is not OK. reportWarning( CERR_ANN_CHILD_ELEMENT, null, new Locator[]{getLocator()} ); ((RELAXNGGrammar)grammar).isAnnotationCompatible = false; } if(uri.equals(AnnotationNamespace) && local.equals("annotation")) { // check the compatibility with the annotation feature. for( int i=0; i<atts.getLength(); i++ ) { String attUri = atts.getURI(i); if(attUri.equals("") || attUri.equals(AnnotationNamespace) || attUri.equals(RELAXNGNamespace) ) { // it contains an invalid attribute reportWarning( CERR_ANN_INVALID_ATTRIBUTE, new Object[]{atts.getQName(i)}, new Locator[]{getLocator()} ); ((RELAXNGGrammar)grammar).isAnnotationCompatible = false; break; // abort further check. } } if(lastRNGElement.size()!=0 ) { if(lastRNGElement.top()!=null && !"value".equals(lastRNGElement.top()) && !"param".equals(lastRNGElement.top()) && !"name".equals(lastRNGElement.top())) { reportWarning( CERR_ANN_MISPLACED, new Object[]{lastRNGElement.top()}, new Locator[]{getLocator()} ); ((RELAXNGGrammar)grammar).isAnnotationCompatible = false; } } inAnnotation = true; } lastRNGElement.push(null); } public void endElement( String uri, String local, String qname ) throws SAXException { super.endElement(uri,local,qname); inAnnotation = false; lastRNGElement.pop(); if( uri.equals(RELAXNGNamespace) ) { lastRNGElement.pop(); lastRNGElement.push(local); } } public static final String CERR_ANN_CHILD_ELEMENT = // arg:0 "RELAXNGReader.Compatibility.Annotation.ChildElement"; public static final String CERR_ANN_MISPLACED = // arg:1 "RELAXNGReader.Compatibility.Annotation.Misplaced"; public static final String CERR_ANN_INVALID_ATTRIBUTE = // arg:1 "RELAXNGReader.Compatibility.Annotation.InvalidAttribute"; }
UTF-8
Java
10,453
java
RELAXNGCompReader.java
Java
[ { "context": "act grammar model.\n * \n * @author <a href=\"mailto:kohsuke.kawaguchi@eng.sun.com\">Kohsuke KAWAGUCHI</a>\n */\npublic class RELAXNGCo", "end": 2453, "score": 0.9998676776885986, "start": 2424, "tag": "EMAIL", "value": "kohsuke.kawaguchi@eng.sun.com" }, { "context": "or <a href=\"mailto:kohsuke.kawaguchi@eng.sun.com\">Kohsuke KAWAGUCHI</a>\n */\npublic class RELAXNGCompReader extends RE", "end": 2472, "score": 0.9998661279678345, "start": 2455, "tag": "NAME", "value": "Kohsuke KAWAGUCHI" } ]
null
[]
/* * Copyright (c) 2001-2013 Oracle and/or its affiliates. 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 Oracle nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.sun.msv.reader.trex.ng.comp; import java.text.MessageFormat; import java.util.Map; import java.util.ResourceBundle; import javax.xml.parsers.SAXParserFactory; import org.xml.sax.Attributes; import org.xml.sax.InputSource; import org.xml.sax.Locator; import org.xml.sax.SAXException; import com.sun.msv.grammar.AttributeExp; import com.sun.msv.grammar.ExpressionPool; import com.sun.msv.grammar.relaxng.RELAXNGGrammar; import com.sun.msv.grammar.trex.TREXGrammar; import com.sun.msv.reader.GrammarReaderController; import com.sun.msv.reader.State; import com.sun.msv.reader.trex.ng.RELAXNGReader; import com.sun.msv.util.LightStack; import com.sun.msv.util.StartTagInfo; /** * reads RELAX NG grammar with DTD compatibility annotation * and constructs abstract grammar model. * * @author <a href="mailto:<EMAIL>"><NAME></a> */ public class RELAXNGCompReader extends RELAXNGReader { /** loads RELAX NG pattern. * * @return * it always returns {@link RELAXNGGrammar}, but due to the * restriction imposed by Java language, I cannot change the * signature of this method. */ public static TREXGrammar parse( String grammarURL, GrammarReaderController controller ) { RELAXNGCompReader reader = new RELAXNGCompReader(controller); reader.parse(grammarURL); return reader.getResult(); } /** loads RELAX NG pattern. * * @return * it always returns {@link RELAXNGGrammar}, but due to the * restriction imposed by Java language, I cannot change the * signature of this method. */ public static TREXGrammar parse( InputSource grammar, GrammarReaderController controller ) { RELAXNGCompReader reader = new RELAXNGCompReader(controller); reader.parse(grammar); return reader.getResult(); } /** easy-to-use constructor. */ public RELAXNGCompReader( GrammarReaderController controller ) { this(controller,createParserFactory(),new ExpressionPool()); } /** easy-to-use constructor. */ public RELAXNGCompReader( GrammarReaderController controller, SAXParserFactory parserFactory, ExpressionPool pool ) { this(controller,parserFactory,new StateFactory(),pool); } /** full constructor */ public RELAXNGCompReader( GrammarReaderController controller, SAXParserFactory parserFactory, StateFactory stateFactory, ExpressionPool pool ) { super( controller, parserFactory, stateFactory, pool ); lastRNGElement.push(null); } private final Map<AttributeExp,String> defaultedAttributes = new java.util.HashMap<AttributeExp,String>(); /** * note that the specified expression is marked with the default value. * this method is called when a:defaultValue is found. */ protected final void addDefaultValue( AttributeExp exp, String value ) { // record the location where this attribute is declared. setDeclaredLocationOf(exp); if(defaultedAttributes.put(exp,value)!=null) throw new Error(); // it is not possible for one AttributeExp to be processed twice. } protected TREXGrammar getGrammar() { return grammar; } protected String localizeMessage( String propertyName, Object[] args ) { String format; try { format = ResourceBundle.getBundle("com.sun.msv.reader.trex.ng.comp.Messages").getString(propertyName); } catch( Exception e ) { return super.localizeMessage(propertyName,args); } return MessageFormat.format(format, args ); } /** Namespace URI of RELAX NG DTD compatibility annotation */ public static final String AnnotationNamespace = "http://relaxng.org/ns/compatibility/annotations/1.0"; /** * creates various State object, which in turn parses grammar. * parsing behavior can be customized by implementing custom StateFactory. */ public static class StateFactory extends RELAXNGReader.StateFactory { public State attribute ( State parent, StartTagInfo tag ) { return new CompAttributeState(); } public TREXGrammar createGrammar( ExpressionPool pool, TREXGrammar parent ) { return new RELAXNGGrammar(pool,parent); } } // protected StateFactory getStateFactory() { // return (StateFactory)super.sfactory; // } public void wrapUp() { super.wrapUp(); if(!controller.hadError()) { // do not check the compatibilities if some errors // are already reported. new DefAttCompatibilityChecker(this,defaultedAttributes).test(); new IDCompatibilityChecker(this).test(); } } /** * pair of an element name and an attribute name. */ /* private final static class ElemAttrNamePair { public final StringPair element; public final StringPair attribute; public int hashCode() { return element.hashCode()^attribute.hashCode(); } public boolean equals( Object o ) { if(!(o instanceof ElemAttrNamePair)) return false; ElemAttrNamePair rhs = (ElemAttrNamePair)o; return element.equals(rhs.element) && attribute.equals(rhs.attribute); } public ElemAttrNamePair( StringPair e, StringPair a ) { element=e; attribute=a; } public ElemAttrNamePair( String e_uri, String e_local, String a_uri, String a_local ) { this( new StringPair(e_uri,e_local), new StringPair(a_uri,a_local) ); } public ElemAttrNamePair( SimpleNameClass e, SimpleNameClass a ) { this( e.namespaceURI, e.localName, a.namespaceURI, a.localName ); } } */ /** * The local name of the preceding RELAX NG element sibling. */ private final LightStack lastRNGElement = new LightStack(); private boolean inAnnotation = false; public void startElement( String uri, String local, String qname, Attributes atts ) throws SAXException { super.startElement(uri,local,qname,atts); if(inAnnotation) { // we found a child element for a:annotation. // this is not OK. reportWarning( CERR_ANN_CHILD_ELEMENT, null, new Locator[]{getLocator()} ); ((RELAXNGGrammar)grammar).isAnnotationCompatible = false; } if(uri.equals(AnnotationNamespace) && local.equals("annotation")) { // check the compatibility with the annotation feature. for( int i=0; i<atts.getLength(); i++ ) { String attUri = atts.getURI(i); if(attUri.equals("") || attUri.equals(AnnotationNamespace) || attUri.equals(RELAXNGNamespace) ) { // it contains an invalid attribute reportWarning( CERR_ANN_INVALID_ATTRIBUTE, new Object[]{atts.getQName(i)}, new Locator[]{getLocator()} ); ((RELAXNGGrammar)grammar).isAnnotationCompatible = false; break; // abort further check. } } if(lastRNGElement.size()!=0 ) { if(lastRNGElement.top()!=null && !"value".equals(lastRNGElement.top()) && !"param".equals(lastRNGElement.top()) && !"name".equals(lastRNGElement.top())) { reportWarning( CERR_ANN_MISPLACED, new Object[]{lastRNGElement.top()}, new Locator[]{getLocator()} ); ((RELAXNGGrammar)grammar).isAnnotationCompatible = false; } } inAnnotation = true; } lastRNGElement.push(null); } public void endElement( String uri, String local, String qname ) throws SAXException { super.endElement(uri,local,qname); inAnnotation = false; lastRNGElement.pop(); if( uri.equals(RELAXNGNamespace) ) { lastRNGElement.pop(); lastRNGElement.push(local); } } public static final String CERR_ANN_CHILD_ELEMENT = // arg:0 "RELAXNGReader.Compatibility.Annotation.ChildElement"; public static final String CERR_ANN_MISPLACED = // arg:1 "RELAXNGReader.Compatibility.Annotation.Misplaced"; public static final String CERR_ANN_INVALID_ATTRIBUTE = // arg:1 "RELAXNGReader.Compatibility.Annotation.InvalidAttribute"; }
10,420
0.643356
0.641921
280
36.332142
29.49262
125
false
false
0
0
0
0
0
0
0.571429
false
false
11
d1b26e8806d6e341e1f43dbc8108de8e0f497def
20,607,253,128,726
841b5882f701c1ccd3e5e80e515d4d002d48f572
/src/main/java/edu/illinois/medusa/HintedBlobStore.java
02ef66bbfe441489ef25ad17b410969f57683867
[ "NCSA", "LicenseRef-scancode-unknown-license-reference" ]
permissive
medusa-project/akubra-dell-dx
https://github.com/medusa-project/akubra-dell-dx
40a8e340ac4378ead043f73f940fa4b1e478490e
1b0fc4d5c9a80182b694a849fdf84da200b24122
refs/heads/master
2016-09-05T14:08:26.993000
2013-04-29T05:11:46
2013-04-29T05:11:46
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package edu.illinois.medusa; import javax.transaction.Transaction; import java.io.IOException; import java.net.URI; import java.util.*; /** * Blob Store that can use Akubra hints to maintain Caringo headers * * @author Howard Ding - hding2@illinois.edu */ public class HintedBlobStore extends CaringoBlobStore { /** * Hints to be used over the whole store */ protected CaringoHints hints; /** * HintCopier that will control copying of blobs from this store */ protected HintCopier hintCopier; /** * Construct a new HintedBlobStore * * @param storeId Arbitrary name for the blob store * @param configFilePath Path to properties file with configuration information for the blob store */ protected HintedBlobStore(URI storeId, String configFilePath) { super(storeId, configFilePath); } protected void initializeHintCopier() { this.hintCopier = new HintCopier(); this.hintCopier.addRule(new HintCopyRegexpRule("caringo-meta", true, "^x-.+-meta-.+$")); this.hintCopier.addRule(new HintCopyRegexpRule("caringo-lifepoint", true, "^Lifepoint$")); } /** * Open a connection to Caringo storage * * @param tx For this BlobStore this must be null - transactions are unsupported. * @param hints Any hints to initialize this connection * @return new connection * @throws IOException If there is any problem opening the connection or tx is not null. */ public HintedBlobStoreConnection openConnection(Transaction tx, Map<String, String> hints) throws IOException { if (tx != null) { throw new UnsupportedOperationException(); } return new HintedBlobStoreConnection(this, streamManager, this.hints.copy_and_merge_hints(hints)); } /** * Open a connection to Caringo storage * * @return new connection * @throws IOException If there is any problem opening the connection */ public HintedBlobStoreConnection openConnection() throws IOException { return this.openConnection(null, null); } /** * Configuration from configuration file. * * @param config Properties used to configure the BlobStore */ protected void configFromProperties(Properties config) { this.hints = new CaringoHints(); super.configFromProperties(config); this.initializeHintCopier(); this.addCreatorHeaders(); this.addConfigHeaders(config); } /** * Add headers/hints based on configuration file. * Each property of the form header.x = y (where "header" is literal) gives rise to a header with * name x and value y. Multiple values can be specified as y|z|w, and the \ character serves to quote the * following character. Note that each \ may need another \ to quote itself to satisfy the properties file * syntax. E.g. abc\\\\|de\\|fg in the properties file represents the string abc\\|de\|fg passed to this plugin, * which parses left to right and sees the two values abc\ and de|fg. * * These headers/hints will automatically be ignored when copying hints unless something else modifies the HintCopier * to change that. * * @param config Properties used to configure BlobStore */ protected void addConfigHeaders(Properties config) { Set<String> keys = config.stringPropertyNames(); for (String key : keys) { if (key.startsWith("header.")) { String headerName = key.substring("header.".length()); List<String> values = parseConfigHeaders(config.getProperty(key)); for (String value : values) { this.hints.addHint(":" + headerName, value); } this.hintCopier.addRuleFront(new HintCopyRegexpRule(key, false, "^" + java.util.regex.Pattern.quote(headerName) + "$")); } } } /** * Add some headers identifying this akubra plugin as the creator of objects in storage. Requested by Dell. */ protected void addCreatorHeaders() { this.hints.addHint(":x-Dell-creator-meta", AkubraPlugin.dellCreator); this.hints.addHint(":x-Dell-creator-version-meta", AkubraPlugin.dellCreatorVersion()); } //This is neither pretty nor efficient, but it will only happen once, at start up, so as long as it's //correct it should be fine. //configString is parsed as a | separated string, where \ functions to quote the following character. //A trailing | does not contribute anything - a leading | contributes an empty value. /** * Parse a value passed through the properties file into a set of values. * * @param configString Raw value to be parsed * @return Array of parsed values */ protected ArrayList<String> parseConfigHeaders(String configString) { ArrayList<String> values = new ArrayList<String>(); boolean onBackslash = false; String accumulator = new String(); String rest = new String(configString); while (rest.length() > 0) { Character c = rest.charAt(0); rest = rest.substring(1); if (onBackslash) { accumulator = accumulator + c; onBackslash = false; } else { if (c == '\\') { onBackslash = true; } else if (c == '|') { values.add(accumulator); accumulator = new String(); } else { accumulator = accumulator + c; } } } if (accumulator.length() > 0) values.add(accumulator); return values; } protected HintCopier getHintCopier() { return this.hintCopier; } }
UTF-8
Java
5,877
java
HintedBlobStore.java
Java
[ { "context": "ra hints to maintain Caringo headers\n *\n * @author Howard Ding - hding2@illinois.edu\n */\n\npublic class HintedBlo", "end": 235, "score": 0.9998615980148315, "start": 224, "tag": "NAME", "value": "Howard Ding" }, { "context": "intain Caringo headers\n *\n * @author Howard Ding - hding2@illinois.edu\n */\n\npublic class HintedBlobStore extends Caringo", "end": 257, "score": 0.99992835521698, "start": 238, "tag": "EMAIL", "value": "hding2@illinois.edu" } ]
null
[]
package edu.illinois.medusa; import javax.transaction.Transaction; import java.io.IOException; import java.net.URI; import java.util.*; /** * Blob Store that can use Akubra hints to maintain Caringo headers * * @author <NAME> - <EMAIL> */ public class HintedBlobStore extends CaringoBlobStore { /** * Hints to be used over the whole store */ protected CaringoHints hints; /** * HintCopier that will control copying of blobs from this store */ protected HintCopier hintCopier; /** * Construct a new HintedBlobStore * * @param storeId Arbitrary name for the blob store * @param configFilePath Path to properties file with configuration information for the blob store */ protected HintedBlobStore(URI storeId, String configFilePath) { super(storeId, configFilePath); } protected void initializeHintCopier() { this.hintCopier = new HintCopier(); this.hintCopier.addRule(new HintCopyRegexpRule("caringo-meta", true, "^x-.+-meta-.+$")); this.hintCopier.addRule(new HintCopyRegexpRule("caringo-lifepoint", true, "^Lifepoint$")); } /** * Open a connection to Caringo storage * * @param tx For this BlobStore this must be null - transactions are unsupported. * @param hints Any hints to initialize this connection * @return new connection * @throws IOException If there is any problem opening the connection or tx is not null. */ public HintedBlobStoreConnection openConnection(Transaction tx, Map<String, String> hints) throws IOException { if (tx != null) { throw new UnsupportedOperationException(); } return new HintedBlobStoreConnection(this, streamManager, this.hints.copy_and_merge_hints(hints)); } /** * Open a connection to Caringo storage * * @return new connection * @throws IOException If there is any problem opening the connection */ public HintedBlobStoreConnection openConnection() throws IOException { return this.openConnection(null, null); } /** * Configuration from configuration file. * * @param config Properties used to configure the BlobStore */ protected void configFromProperties(Properties config) { this.hints = new CaringoHints(); super.configFromProperties(config); this.initializeHintCopier(); this.addCreatorHeaders(); this.addConfigHeaders(config); } /** * Add headers/hints based on configuration file. * Each property of the form header.x = y (where "header" is literal) gives rise to a header with * name x and value y. Multiple values can be specified as y|z|w, and the \ character serves to quote the * following character. Note that each \ may need another \ to quote itself to satisfy the properties file * syntax. E.g. abc\\\\|de\\|fg in the properties file represents the string abc\\|de\|fg passed to this plugin, * which parses left to right and sees the two values abc\ and de|fg. * * These headers/hints will automatically be ignored when copying hints unless something else modifies the HintCopier * to change that. * * @param config Properties used to configure BlobStore */ protected void addConfigHeaders(Properties config) { Set<String> keys = config.stringPropertyNames(); for (String key : keys) { if (key.startsWith("header.")) { String headerName = key.substring("header.".length()); List<String> values = parseConfigHeaders(config.getProperty(key)); for (String value : values) { this.hints.addHint(":" + headerName, value); } this.hintCopier.addRuleFront(new HintCopyRegexpRule(key, false, "^" + java.util.regex.Pattern.quote(headerName) + "$")); } } } /** * Add some headers identifying this akubra plugin as the creator of objects in storage. Requested by Dell. */ protected void addCreatorHeaders() { this.hints.addHint(":x-Dell-creator-meta", AkubraPlugin.dellCreator); this.hints.addHint(":x-Dell-creator-version-meta", AkubraPlugin.dellCreatorVersion()); } //This is neither pretty nor efficient, but it will only happen once, at start up, so as long as it's //correct it should be fine. //configString is parsed as a | separated string, where \ functions to quote the following character. //A trailing | does not contribute anything - a leading | contributes an empty value. /** * Parse a value passed through the properties file into a set of values. * * @param configString Raw value to be parsed * @return Array of parsed values */ protected ArrayList<String> parseConfigHeaders(String configString) { ArrayList<String> values = new ArrayList<String>(); boolean onBackslash = false; String accumulator = new String(); String rest = new String(configString); while (rest.length() > 0) { Character c = rest.charAt(0); rest = rest.substring(1); if (onBackslash) { accumulator = accumulator + c; onBackslash = false; } else { if (c == '\\') { onBackslash = true; } else if (c == '|') { values.add(accumulator); accumulator = new String(); } else { accumulator = accumulator + c; } } } if (accumulator.length() > 0) values.add(accumulator); return values; } protected HintCopier getHintCopier() { return this.hintCopier; } }
5,860
0.630764
0.629913
156
36.666668
33.153942
136
false
false
0
0
0
0
0
0
0.474359
false
false
11
4c74340b2746b24b0d0816975a6afd794477de03
19,628,000,591,996
5a134da2c27aca07bac27ed386d87a1ee685f825
/Group E (DataQuality_Debattista)/Dev/eis-lab/eis-lab/src/main/java/de/unibonn/iai/eis/qaentlod/qualitymetrics/ComplexQualityMetric.java
0d82e184b2bcff08ef5a17b742c6919f223362fd
[]
no_license
EIS-Bonn/MA-INF3232-Lab-SS2014
https://github.com/EIS-Bonn/MA-INF3232-Lab-SS2014
0b565c3e2bccfd88797dae4aaffc18d236e64bde
9a41e5d2aa92f58549804246c453a50ed2f1e9a1
refs/heads/master
2021-01-17T08:13:32.022000
2015-09-18T11:35:57
2015-09-18T11:35:57
19,574,141
2
2
null
null
null
null
null
null
null
null
null
null
null
null
null
package de.unibonn.iai.eis.qaentlod.qualitymetrics; /** * @author Jeremy Debattista * * This interface extends the "simpler" Quality Metric. * This gives us the possibility of creating more complex quality metrics * which require further processing of the data in the dataset. * */ public interface ComplexQualityMetric extends QualityMetric { /** * Implement this method if the quality metric * requires any pre-processing. * * If pre-processing is required, it should be done * here rather than in the constructor. */ void before(); /** * Implement this method if the quality metric * requires any post-processing */ void after(); }
UTF-8
Java
674
java
ComplexQualityMetric.java
Java
[ { "context": "n.iai.eis.qaentlod.qualitymetrics;\n\n/**\n * @author Jeremy Debattista\n * \n * This interface extends the \"simpler\" Quali", "end": 85, "score": 0.9998602867126465, "start": 68, "tag": "NAME", "value": "Jeremy Debattista" } ]
null
[]
package de.unibonn.iai.eis.qaentlod.qualitymetrics; /** * @author <NAME> * * This interface extends the "simpler" Quality Metric. * This gives us the possibility of creating more complex quality metrics * which require further processing of the data in the dataset. * */ public interface ComplexQualityMetric extends QualityMetric { /** * Implement this method if the quality metric * requires any pre-processing. * * If pre-processing is required, it should be done * here rather than in the constructor. */ void before(); /** * Implement this method if the quality metric * requires any post-processing */ void after(); }
663
0.719585
0.719585
27
23.962963
23.828836
73
false
false
0
0
0
0
0
0
0.703704
false
false
11
61f555686604ffbd97dea08db0865d03a58f7a08
29,377,576,307,330
dd01287387cb2fcbe28f01938d3757d75c4692ca
/chapter_002/src/main/java/ru/job4j/tracker/MenuTracker.java
f885a78fd03be50edd787add42ce74675dc5efe2
[ "Apache-2.0" ]
permissive
Kuzurik/job4j
https://github.com/Kuzurik/job4j
5747baf1e7c464df56c0c33ff6a0d1163ddfdf49
84eb214ac897070ca68f1a48215d32dbbe47a198
refs/heads/master
2022-09-28T11:06:21.127000
2021-05-23T17:44:10
2021-05-23T17:44:10
187,525,149
1
0
Apache-2.0
false
2022-09-08T01:12:58
2019-05-19T20:32:56
2021-05-23T17:44:22
2022-09-08T01:12:54
356
0
0
3
Java
false
false
package ru.job4j.tracker; import ru.job4j.tracker.actions.*; import java.sql.SQLException; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Random; import java.util.function.Consumer; /** * Menu for tracker * @author Aliaksandr Kuzura (vorota-24@bk.ru) * @version $Id$ * @since 0.1 */ public class MenuTracker { private final Input input; private final Store sqlTracker; private final Consumer<String> output; private final List<UserAction> actions = new ArrayList<>(); public MenuTracker(Input input, Store sqlTracker, Consumer<String> output) { this.input = input; this.sqlTracker = sqlTracker; this.output = output; } /** * store menu */ public void fillActions(StartUI ui) { this.actions.add(0, new AddItem(0, "Add the new item")); this.actions.add(1, new ShowAll(1, "Show all items")); this.actions.add(2, new EditItem(2, "Edit item")); this.actions.add(3, new DeleteItem(3, "Delete item")); this.actions.add(4, new FindItemById(4, "Find item by id")); this.actions.add(5, new FindItemByName(5, "Find item by name")); this.actions.add(6, new Exit(ui, 6, "Exit program")); } /** * performs an action depending on the key * @param key */ public void select(int key) throws SQLException { this.actions.get(key).execute(this.input, this.sqlTracker, this.output); } /** * show menu */ public void show() { this.actions.forEach(i -> this.output.accept(i.info())); } }
UTF-8
Java
1,627
java
MenuTracker.java
Java
[ { "context": "tion.Consumer;\n\n/**\n * Menu for tracker\n * @author Aliaksandr Kuzura (vorota-24@bk.ru)\n * @version $Id$\n * @since 0.1\n", "end": 281, "score": 0.99986732006073, "start": 264, "tag": "NAME", "value": "Aliaksandr Kuzura" }, { "context": " * Menu for tracker\n * @author Aliaksandr Kuzura (vorota-24@bk.ru)\n * @version $Id$\n * @since 0.1\n */\n\npublic class", "end": 298, "score": 0.9999344944953918, "start": 283, "tag": "EMAIL", "value": "vorota-24@bk.ru" } ]
null
[]
package ru.job4j.tracker; import ru.job4j.tracker.actions.*; import java.sql.SQLException; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Random; import java.util.function.Consumer; /** * Menu for tracker * @author <NAME> (<EMAIL>) * @version $Id$ * @since 0.1 */ public class MenuTracker { private final Input input; private final Store sqlTracker; private final Consumer<String> output; private final List<UserAction> actions = new ArrayList<>(); public MenuTracker(Input input, Store sqlTracker, Consumer<String> output) { this.input = input; this.sqlTracker = sqlTracker; this.output = output; } /** * store menu */ public void fillActions(StartUI ui) { this.actions.add(0, new AddItem(0, "Add the new item")); this.actions.add(1, new ShowAll(1, "Show all items")); this.actions.add(2, new EditItem(2, "Edit item")); this.actions.add(3, new DeleteItem(3, "Delete item")); this.actions.add(4, new FindItemById(4, "Find item by id")); this.actions.add(5, new FindItemByName(5, "Find item by name")); this.actions.add(6, new Exit(ui, 6, "Exit program")); } /** * performs an action depending on the key * @param key */ public void select(int key) throws SQLException { this.actions.get(key).execute(this.input, this.sqlTracker, this.output); } /** * show menu */ public void show() { this.actions.forEach(i -> this.output.accept(i.info())); } }
1,608
0.630608
0.618316
64
24.421875
23.834589
80
false
false
0
0
0
0
0
0
0.671875
false
false
11
0d8e47514ff8a672752d8454d9d9e14a3c02554c
10,033,043,647,014
e9c7f8de246d746cef4da4a15a361b3886c094ed
/service/CardIdRangeDomainService.java
a90a168087bb2c8915991134a29fa9b77879e6ff
[]
no_license
BhanumitraJ/SpringJPAExcercise
https://github.com/BhanumitraJ/SpringJPAExcercise
560169583ea9f80ffdb0efc1b586fe44d0d1b445
ee5ee1f9ef7631e542d413acfa43767bf6833ca7
refs/heads/main
2023-06-05T03:02:07.392000
2021-06-29T12:37:45
2021-06-29T12:37:45
381,271,308
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.hbi.oms.digitalloyaltycard.domain.service; import com.hbi.oms.digitalloyaltycard.component.EAN13CheckDigitAppender; import com.hbi.oms.digitalloyaltycard.domain.entity.CardIdRange; import com.hbi.oms.digitalloyaltycard.domain.exception.UnsupportedCountryException; import com.hbi.oms.digitalloyaltycard.domain.repository.CardIdRangeRepository; import lombok.AllArgsConstructor; import org.apache.commons.lang3.StringUtils; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; @Service @AllArgsConstructor public class CardIdRangeDomainService { private final CardIdRangeRepository cardIdRangeRepository; private final EAN13CheckDigitAppender ean13CheckDigitAppender; /** * Generate the next card ID for the given country. * <p> * N.B. that due to Siebel's pre-allocated IDs in the database, the returned ID is not guaranteed to not already to be assigned * to a LoyaltyCardAllocation in the database. This is because the underlying CardIdRanges does not know about these pre-allocations. * The caller is responsible for checking that the ID returned by this method is not in use elsewhere in the database. * * <p> * This method is called in a new transaction to ensure the underlying CardIdRange is always incremented, even if the transaction of * the calling method is rolled back. * * @param country The country get the next card id for * @return The next ID in the range for the given country. N.B. it's not guaranteed for this card-id to not already be * in use by a different LoyaltyCardAllocation as there are some random pre-existing IDs in the database already * from Siebel. */ @Transactional(propagation = Propagation.REQUIRES_NEW) public String generateNextIdForCountry(String country) { CardIdRange range = cardIdRangeRepository.findByCountryAndIncrementCurrentValue(country) .orElseThrow(() -> new UnsupportedCountryException(country)); String currentId = String.valueOf(range.getRangeStart() + range.getCurrentValue()); int requiredPadding = EAN13CheckDigitAppender.INPUT_LENGTH - range.getPrefix().length(); String uncheckedId = range.getPrefix() + StringUtils.leftPad(currentId, requiredPadding, "0"); return ean13CheckDigitAppender.toEAN13CheckedNumber(uncheckedId); } }
UTF-8
Java
2,478
java
CardIdRangeDomainService.java
Java
[]
null
[]
package com.hbi.oms.digitalloyaltycard.domain.service; import com.hbi.oms.digitalloyaltycard.component.EAN13CheckDigitAppender; import com.hbi.oms.digitalloyaltycard.domain.entity.CardIdRange; import com.hbi.oms.digitalloyaltycard.domain.exception.UnsupportedCountryException; import com.hbi.oms.digitalloyaltycard.domain.repository.CardIdRangeRepository; import lombok.AllArgsConstructor; import org.apache.commons.lang3.StringUtils; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; @Service @AllArgsConstructor public class CardIdRangeDomainService { private final CardIdRangeRepository cardIdRangeRepository; private final EAN13CheckDigitAppender ean13CheckDigitAppender; /** * Generate the next card ID for the given country. * <p> * N.B. that due to Siebel's pre-allocated IDs in the database, the returned ID is not guaranteed to not already to be assigned * to a LoyaltyCardAllocation in the database. This is because the underlying CardIdRanges does not know about these pre-allocations. * The caller is responsible for checking that the ID returned by this method is not in use elsewhere in the database. * * <p> * This method is called in a new transaction to ensure the underlying CardIdRange is always incremented, even if the transaction of * the calling method is rolled back. * * @param country The country get the next card id for * @return The next ID in the range for the given country. N.B. it's not guaranteed for this card-id to not already be * in use by a different LoyaltyCardAllocation as there are some random pre-existing IDs in the database already * from Siebel. */ @Transactional(propagation = Propagation.REQUIRES_NEW) public String generateNextIdForCountry(String country) { CardIdRange range = cardIdRangeRepository.findByCountryAndIncrementCurrentValue(country) .orElseThrow(() -> new UnsupportedCountryException(country)); String currentId = String.valueOf(range.getRangeStart() + range.getCurrentValue()); int requiredPadding = EAN13CheckDigitAppender.INPUT_LENGTH - range.getPrefix().length(); String uncheckedId = range.getPrefix() + StringUtils.leftPad(currentId, requiredPadding, "0"); return ean13CheckDigitAppender.toEAN13CheckedNumber(uncheckedId); } }
2,478
0.772397
0.766747
46
52.869564
41.971321
137
false
false
0
0
0
0
0
0
0.456522
false
false
11
02a280a2eb853cb3eaaddaddea7529a781dd7602
10,033,043,646,815
10bd758580d6141ca34a451b0c0f3f3cd7ca5800
/app/src/main/java/com/example/app5/Car.java
ca69924e7a0fa4c7b784e85a6843dd7576109b16
[]
no_license
fihy2001/App5
https://github.com/fihy2001/App5
262b39a954b579a98000dd1bd46ba924d02b4062
f7939356d7e97ce8c303e7395c0f55199435aa64
refs/heads/master
2022-12-11T10:38:27.052000
2020-08-20T15:48:37
2020-08-20T15:48:37
289,046,780
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.app5; public class Car extends Vehicle { public Car(int speed, boolean hasBreakingSystem, int numberOfWheels){ super(speed, hasBreakingSystem, numberOfWheels); } @Override public String toString() { return super.toString(); } }
UTF-8
Java
288
java
Car.java
Java
[]
null
[]
package com.example.app5; public class Car extends Vehicle { public Car(int speed, boolean hasBreakingSystem, int numberOfWheels){ super(speed, hasBreakingSystem, numberOfWheels); } @Override public String toString() { return super.toString(); } }
288
0.677083
0.673611
14
19.571428
22.404446
73
false
false
0
0
0
0
0
0
0.5
false
false
11
26488bfe3713557ff6c5282df852e4c4cfdffa5a
24,421,184,061,191
e3444de0860466de3e964d7d4f9b6a73f7fd3637
/test/testCalcularCostoDeLicencia.java
7a0a2d0429ac90e7b79d1eda0c23b055f3b4ffb2
[]
no_license
emma284/TPMetodosAgiles
https://github.com/emma284/TPMetodosAgiles
f876b54855722f7f2535a59ec7dce95d7df76c85
dd087b4c00e769e693772386c5ada0ff7b233627
refs/heads/master
2020-08-17T05:28:22.461000
2019-12-10T18:25:07
2019-12-10T18:25:07
215,615,358
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.time.LocalDate; import java.time.Month; 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.*; import tpmetodosagiles.gestores.GestorDeLicencias; import tpmetodosagiles.entidades.Licencia; import tpmetodosagiles.entidades.Titular; public class testCalcularCostoDeLicencia { public testCalcularCostoDeLicencia() { } char claseLicencia='E'; @Test public void test1() { Licencia licencia = new Licencia(); licencia.setClaseLicencia(claseLicencia); licencia.setFechaEmision(LocalDate.of(2019, 12, 7)); licencia.setFechaVencimiento(LocalDate.of(2020, 8, 3)); Titular titular = new Titular(); titular.setFechaNacimiento(LocalDate.of(2001, 8, 3)); licencia.setTitular(titular); double resultado[]; resultado = GestorDeLicencias.getArrayCostoLicencia(licencia); assertEquals(resultado[0], 29.,.001); assertEquals(resultado[1], 8.,.001); assertEquals(resultado[2], 37.,.001); } @Test public void test2() { Licencia licencia = new Licencia(); licencia.setClaseLicencia(claseLicencia); licencia.setFechaEmision(LocalDate.of(2019, 5, 21)); licencia.setFechaVencimiento(LocalDate.of(2022, 5, 20)); Titular titular = new Titular(); titular.setFechaNacimiento(LocalDate.of(1999, 5, 20)); licencia.setTitular(titular); double resultado[]; resultado = GestorDeLicencias.getArrayCostoLicencia(licencia); assertEquals(resultado[0], 39.,.001); assertEquals(resultado[1], 8.,.001); assertEquals(resultado[2], 47.,.001); } @Test public void test3() { Licencia licencia = new Licencia(); licencia.setClaseLicencia(claseLicencia); licencia.setFechaEmision(LocalDate.of(2014, 5, 21)); licencia.setFechaVencimiento(LocalDate.of(2019, 7, 20)); Titular titular = new Titular(); titular.setFechaNacimiento(LocalDate.of(1993, 7, 20)); licencia.setTitular(titular); double resultado[]; resultado = GestorDeLicencias.getArrayCostoLicencia(licencia); assertEquals(resultado[0], 59.,.001); assertEquals(resultado[1], 8.,.001); assertEquals(resultado[2], 67.,.001); } @Test public void test4() { Licencia licencia = new Licencia(); licencia.setClaseLicencia(claseLicencia); licencia.setFechaEmision(LocalDate.of(2000, 6, 25)); licencia.setFechaVencimiento(LocalDate.of(2005, 5, 26)); Titular titular = new Titular(); titular.setFechaNacimiento(LocalDate.of(1971, 5, 26)); licencia.setTitular(titular); double resultado[]; resultado = GestorDeLicencias.getArrayCostoLicencia(licencia); assertEquals(resultado[0], 59.,.001); assertEquals(resultado[1], 8.,.001); assertEquals(resultado[2], 67.,.001); } public void test5() { Licencia licencia = new Licencia(); licencia.setClaseLicencia(claseLicencia); licencia.setFechaEmision(LocalDate.of(2047, 3, 27)); licencia.setFechaVencimiento(LocalDate.of(2051, 5, 26)); Titular titular = new Titular(); titular.setFechaNacimiento(LocalDate.of(2000, 5, 26)); licencia.setTitular(titular); double resultado[]; resultado = GestorDeLicencias.getArrayCostoLicencia(licencia); assertEquals(resultado[0], 44.,.001); assertEquals(resultado[1], 8.,.001); assertEquals(resultado[2], 52.,.001); } public void test6() { Licencia licencia = new Licencia(); licencia.setClaseLicencia(claseLicencia); licencia.setFechaEmision(LocalDate.of(2051, 6, 30)); licencia.setFechaVencimiento(LocalDate.of(2055, 3, 19)); Titular titular = new Titular(); titular.setFechaNacimiento(LocalDate.of(2001, 3, 19)); licencia.setTitular(titular); double resultado[]; resultado = GestorDeLicencias.getArrayCostoLicencia(licencia); assertEquals(resultado[0], 44.,.001); assertEquals(resultado[1], 8.,.001); assertEquals(resultado[2], 52.,.001); } public void test7() { Licencia licencia = new Licencia(); licencia.setClaseLicencia(claseLicencia); licencia.setFechaEmision(LocalDate.of(2000, 7, 10)); licencia.setFechaVencimiento(LocalDate.of(2003, 7, 12)); Titular titular = new Titular(); titular.setFechaNacimiento(LocalDate.of(1939, 7, 12)); licencia.setTitular(titular); double resultado[]; resultado = GestorDeLicencias.getArrayCostoLicencia(licencia); assertEquals(resultado[0], 39.,.001); assertEquals(resultado[1], 8.,.001); assertEquals(resultado[2], 47.,.001); } public void test8() { Licencia licencia = new Licencia(); licencia.setClaseLicencia(claseLicencia); licencia.setFechaEmision(LocalDate.of(2005, 7, 20)); licencia.setFechaVencimiento(LocalDate.of(2008, 7, 12)); Titular titular = new Titular(); titular.setFechaNacimiento(LocalDate.of(1940, 7, 12)); licencia.setTitular(titular); double resultado[]; resultado = GestorDeLicencias.getArrayCostoLicencia(licencia); assertEquals(resultado[0], 39.,.001); assertEquals(resultado[1], 8.,.001); assertEquals(resultado[2], 47.,.001); } public void test9() { Licencia licencia = new Licencia(); licencia.setClaseLicencia(claseLicencia); licencia.setFechaEmision(LocalDate.of(2000, 7, 10)); licencia.setFechaVencimiento(LocalDate.of(2001, 7, 12)); Titular titular = new Titular(); titular.setFechaNacimiento(LocalDate.of(1929, 7, 12)); licencia.setTitular(titular); double resultado[]; resultado = GestorDeLicencias.getArrayCostoLicencia(licencia); assertEquals(resultado[0], 29.,.001); assertEquals(resultado[1], 8.,.001); assertEquals(resultado[2], 37.,.001); } public void test10() { Licencia licencia = new Licencia(); licencia.setClaseLicencia(claseLicencia); licencia.setFechaEmision(LocalDate.of(2075, 8, 30)); licencia.setFechaVencimiento(LocalDate.of(2001, 7, 17)); Titular titular = new Titular(); titular.setFechaNacimiento(LocalDate.of(2000, 8, 30)); licencia.setTitular(titular); double resultado[]; resultado = GestorDeLicencias.getArrayCostoLicencia(licencia); assertEquals(resultado[0], 29.,.001); assertEquals(resultado[1], 8.,.001); assertEquals(resultado[2], 37.,.001); } }
UTF-8
Java
6,965
java
testCalcularCostoDeLicencia.java
Java
[]
null
[]
import java.time.LocalDate; import java.time.Month; 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.*; import tpmetodosagiles.gestores.GestorDeLicencias; import tpmetodosagiles.entidades.Licencia; import tpmetodosagiles.entidades.Titular; public class testCalcularCostoDeLicencia { public testCalcularCostoDeLicencia() { } char claseLicencia='E'; @Test public void test1() { Licencia licencia = new Licencia(); licencia.setClaseLicencia(claseLicencia); licencia.setFechaEmision(LocalDate.of(2019, 12, 7)); licencia.setFechaVencimiento(LocalDate.of(2020, 8, 3)); Titular titular = new Titular(); titular.setFechaNacimiento(LocalDate.of(2001, 8, 3)); licencia.setTitular(titular); double resultado[]; resultado = GestorDeLicencias.getArrayCostoLicencia(licencia); assertEquals(resultado[0], 29.,.001); assertEquals(resultado[1], 8.,.001); assertEquals(resultado[2], 37.,.001); } @Test public void test2() { Licencia licencia = new Licencia(); licencia.setClaseLicencia(claseLicencia); licencia.setFechaEmision(LocalDate.of(2019, 5, 21)); licencia.setFechaVencimiento(LocalDate.of(2022, 5, 20)); Titular titular = new Titular(); titular.setFechaNacimiento(LocalDate.of(1999, 5, 20)); licencia.setTitular(titular); double resultado[]; resultado = GestorDeLicencias.getArrayCostoLicencia(licencia); assertEquals(resultado[0], 39.,.001); assertEquals(resultado[1], 8.,.001); assertEquals(resultado[2], 47.,.001); } @Test public void test3() { Licencia licencia = new Licencia(); licencia.setClaseLicencia(claseLicencia); licencia.setFechaEmision(LocalDate.of(2014, 5, 21)); licencia.setFechaVencimiento(LocalDate.of(2019, 7, 20)); Titular titular = new Titular(); titular.setFechaNacimiento(LocalDate.of(1993, 7, 20)); licencia.setTitular(titular); double resultado[]; resultado = GestorDeLicencias.getArrayCostoLicencia(licencia); assertEquals(resultado[0], 59.,.001); assertEquals(resultado[1], 8.,.001); assertEquals(resultado[2], 67.,.001); } @Test public void test4() { Licencia licencia = new Licencia(); licencia.setClaseLicencia(claseLicencia); licencia.setFechaEmision(LocalDate.of(2000, 6, 25)); licencia.setFechaVencimiento(LocalDate.of(2005, 5, 26)); Titular titular = new Titular(); titular.setFechaNacimiento(LocalDate.of(1971, 5, 26)); licencia.setTitular(titular); double resultado[]; resultado = GestorDeLicencias.getArrayCostoLicencia(licencia); assertEquals(resultado[0], 59.,.001); assertEquals(resultado[1], 8.,.001); assertEquals(resultado[2], 67.,.001); } public void test5() { Licencia licencia = new Licencia(); licencia.setClaseLicencia(claseLicencia); licencia.setFechaEmision(LocalDate.of(2047, 3, 27)); licencia.setFechaVencimiento(LocalDate.of(2051, 5, 26)); Titular titular = new Titular(); titular.setFechaNacimiento(LocalDate.of(2000, 5, 26)); licencia.setTitular(titular); double resultado[]; resultado = GestorDeLicencias.getArrayCostoLicencia(licencia); assertEquals(resultado[0], 44.,.001); assertEquals(resultado[1], 8.,.001); assertEquals(resultado[2], 52.,.001); } public void test6() { Licencia licencia = new Licencia(); licencia.setClaseLicencia(claseLicencia); licencia.setFechaEmision(LocalDate.of(2051, 6, 30)); licencia.setFechaVencimiento(LocalDate.of(2055, 3, 19)); Titular titular = new Titular(); titular.setFechaNacimiento(LocalDate.of(2001, 3, 19)); licencia.setTitular(titular); double resultado[]; resultado = GestorDeLicencias.getArrayCostoLicencia(licencia); assertEquals(resultado[0], 44.,.001); assertEquals(resultado[1], 8.,.001); assertEquals(resultado[2], 52.,.001); } public void test7() { Licencia licencia = new Licencia(); licencia.setClaseLicencia(claseLicencia); licencia.setFechaEmision(LocalDate.of(2000, 7, 10)); licencia.setFechaVencimiento(LocalDate.of(2003, 7, 12)); Titular titular = new Titular(); titular.setFechaNacimiento(LocalDate.of(1939, 7, 12)); licencia.setTitular(titular); double resultado[]; resultado = GestorDeLicencias.getArrayCostoLicencia(licencia); assertEquals(resultado[0], 39.,.001); assertEquals(resultado[1], 8.,.001); assertEquals(resultado[2], 47.,.001); } public void test8() { Licencia licencia = new Licencia(); licencia.setClaseLicencia(claseLicencia); licencia.setFechaEmision(LocalDate.of(2005, 7, 20)); licencia.setFechaVencimiento(LocalDate.of(2008, 7, 12)); Titular titular = new Titular(); titular.setFechaNacimiento(LocalDate.of(1940, 7, 12)); licencia.setTitular(titular); double resultado[]; resultado = GestorDeLicencias.getArrayCostoLicencia(licencia); assertEquals(resultado[0], 39.,.001); assertEquals(resultado[1], 8.,.001); assertEquals(resultado[2], 47.,.001); } public void test9() { Licencia licencia = new Licencia(); licencia.setClaseLicencia(claseLicencia); licencia.setFechaEmision(LocalDate.of(2000, 7, 10)); licencia.setFechaVencimiento(LocalDate.of(2001, 7, 12)); Titular titular = new Titular(); titular.setFechaNacimiento(LocalDate.of(1929, 7, 12)); licencia.setTitular(titular); double resultado[]; resultado = GestorDeLicencias.getArrayCostoLicencia(licencia); assertEquals(resultado[0], 29.,.001); assertEquals(resultado[1], 8.,.001); assertEquals(resultado[2], 37.,.001); } public void test10() { Licencia licencia = new Licencia(); licencia.setClaseLicencia(claseLicencia); licencia.setFechaEmision(LocalDate.of(2075, 8, 30)); licencia.setFechaVencimiento(LocalDate.of(2001, 7, 17)); Titular titular = new Titular(); titular.setFechaNacimiento(LocalDate.of(2000, 8, 30)); licencia.setTitular(titular); double resultado[]; resultado = GestorDeLicencias.getArrayCostoLicencia(licencia); assertEquals(resultado[0], 29.,.001); assertEquals(resultado[1], 8.,.001); assertEquals(resultado[2], 37.,.001); } }
6,965
0.641637
0.585786
183
37.060108
20.331184
70
false
false
0
0
0
0
0
0
1.377049
false
false
11
919986068ec90c8672794f644628f634f2800a58
7,301,444,418,407
37496c73384aec6db1660ce98c1b68abeb626e66
/src/test/java/org/rlapi/StateActionValueTableTest.java
ee202b6a984fdae4909ed655c6348d401c16c8f9
[ "Apache-2.0" ]
permissive
alexlimatds/rlAPI
https://github.com/alexlimatds/rlAPI
1ec55208428ab70ecfc555c80011f94f9795e349
0a9a4da7b3ad4ab76c36e5888e6ce3b6b47dc0e5
refs/heads/master
2021-01-12T10:08:30.541000
2017-04-29T13:30:14
2017-04-29T13:30:14
76,369,609
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.rlapi; import java.util.List; import java.util.Set; import org.junit.Assert; import org.junit.Test; /** * * @author Alexandre */ public class StateActionValueTableTest { @Test public void testGetStates(){ ActionValueTableInMemory table = new ActionValueTableInMemory(); String stateA = "A"; String stateB = "B"; table.putValue(stateA, "action", 3.0); table.putValue(stateB, "action", 8.0); Set<String> states = table.getStates(); Assert.assertTrue(states.contains(stateA)); Assert.assertTrue(states.contains(stateB)); } @Test public void testGetValue(){ ActionValueTableInMemory table = new ActionValueTableInMemory(); String stateA = "s1"; String stateB = "s2"; String actionA = "a1"; Double actionAValue = 5.0; String actionB = "a2"; Double actionBValue = 7.0; String actionC = "a3"; Double actionCValue = 1.0; table.putValue(stateA, actionA, actionAValue); table.putValue(stateA, actionB, actionBValue); table.putValue(stateB, actionC, actionCValue); Assert.assertEquals(actionAValue, table.getValue(stateA, actionA), 0.0001); Assert.assertEquals(actionBValue, table.getValue(stateA, actionB), 0.0001); Assert.assertEquals(actionCValue, table.getValue(stateB, actionC), 0.0001); } @Test public void testGetActions_1(){ ActionValueTableInMemory table = new ActionValueTableInMemory(); String stateA = "s1"; String stateB = "s2"; String actionA = "a1"; String actionB = "a2"; String actionC = "a3"; table.putValue(stateA, actionA, 5.0); table.putValue(stateA, actionB, 7.0); table.putValue(stateB, actionA, 9.0); table.putValue(stateB, actionC, 1.0); Set<String> stateAActions = table.getActions(stateA); Assert.assertEquals(2, stateAActions.size()); Assert.assertTrue(stateAActions.contains(actionA)); Assert.assertTrue(stateAActions.contains(actionB)); Set<String> stateABctions = table.getActions(stateB); Assert.assertEquals(2, stateABctions.size()); Assert.assertTrue(stateABctions.contains(actionA)); Assert.assertTrue(stateABctions.contains(actionC)); } @Test public void testGetActions_2(){ ActionValueTableInMemory table = new ActionValueTableInMemory(); Set<String> stateAActions = table.getActions("state"); Assert.assertNotNull(stateAActions); Assert.assertTrue(stateAActions.isEmpty()); } @Test public void testGetBestActions_1(){ ActionValueTableInMemory table = new ActionValueTableInMemory(); table.putValue("s1", "a1", 3.0); table.putValue("s1", "a2", 8.0); List<String> maxActions = table.getBestActions("s1"); Assert.assertEquals(1, maxActions.size()); Assert.assertTrue(maxActions.contains("a2")); } @Test public void testGetBestActions_2(){ ActionValueTableInMemory table = new ActionValueTableInMemory(); table.putValue("s1", "a1", 8.0); table.putValue("s1", "a2", 2.0); table.putValue("s1", "a3", 8.0); List<String> maxActions = table.getBestActions("s1"); Assert.assertEquals(2, maxActions.size()); Assert.assertTrue(maxActions.contains("a1")); Assert.assertTrue(maxActions.contains("a3")); } @Test public void testGetBestActions_3(){ ActionValueTableInMemory table = new ActionValueTableInMemory(); table.putValue("s1", "a1", 8.0); table.putValue("s1", "a2", 2.0); List<String> maxActions = table.getBestActions("s2"); Assert.assertTrue(maxActions.isEmpty()); } @Test public void testPutValue_1(){ //Tests an update ActionValueTableInMemory table = new ActionValueTableInMemory(); table.putValue("s1", "a1", 8.0); table.putValue("s1", "a2", 2.0); table.putValue("s1", "a1", 7.0); Assert.assertEquals(7.0, table.getValue("s1", "a1"), 0.00001); } }
UTF-8
Java
4,351
java
StateActionValueTableTest.java
Java
[ { "context": "rt;\r\nimport org.junit.Test;\r\n\r\n/**\r\n *\r\n * @author Alexandre\r\n */\r\npublic class StateActionValueTableTest {\r\n ", "end": 150, "score": 0.9992997646331787, "start": 141, "tag": "NAME", "value": "Alexandre" } ]
null
[]
package org.rlapi; import java.util.List; import java.util.Set; import org.junit.Assert; import org.junit.Test; /** * * @author Alexandre */ public class StateActionValueTableTest { @Test public void testGetStates(){ ActionValueTableInMemory table = new ActionValueTableInMemory(); String stateA = "A"; String stateB = "B"; table.putValue(stateA, "action", 3.0); table.putValue(stateB, "action", 8.0); Set<String> states = table.getStates(); Assert.assertTrue(states.contains(stateA)); Assert.assertTrue(states.contains(stateB)); } @Test public void testGetValue(){ ActionValueTableInMemory table = new ActionValueTableInMemory(); String stateA = "s1"; String stateB = "s2"; String actionA = "a1"; Double actionAValue = 5.0; String actionB = "a2"; Double actionBValue = 7.0; String actionC = "a3"; Double actionCValue = 1.0; table.putValue(stateA, actionA, actionAValue); table.putValue(stateA, actionB, actionBValue); table.putValue(stateB, actionC, actionCValue); Assert.assertEquals(actionAValue, table.getValue(stateA, actionA), 0.0001); Assert.assertEquals(actionBValue, table.getValue(stateA, actionB), 0.0001); Assert.assertEquals(actionCValue, table.getValue(stateB, actionC), 0.0001); } @Test public void testGetActions_1(){ ActionValueTableInMemory table = new ActionValueTableInMemory(); String stateA = "s1"; String stateB = "s2"; String actionA = "a1"; String actionB = "a2"; String actionC = "a3"; table.putValue(stateA, actionA, 5.0); table.putValue(stateA, actionB, 7.0); table.putValue(stateB, actionA, 9.0); table.putValue(stateB, actionC, 1.0); Set<String> stateAActions = table.getActions(stateA); Assert.assertEquals(2, stateAActions.size()); Assert.assertTrue(stateAActions.contains(actionA)); Assert.assertTrue(stateAActions.contains(actionB)); Set<String> stateABctions = table.getActions(stateB); Assert.assertEquals(2, stateABctions.size()); Assert.assertTrue(stateABctions.contains(actionA)); Assert.assertTrue(stateABctions.contains(actionC)); } @Test public void testGetActions_2(){ ActionValueTableInMemory table = new ActionValueTableInMemory(); Set<String> stateAActions = table.getActions("state"); Assert.assertNotNull(stateAActions); Assert.assertTrue(stateAActions.isEmpty()); } @Test public void testGetBestActions_1(){ ActionValueTableInMemory table = new ActionValueTableInMemory(); table.putValue("s1", "a1", 3.0); table.putValue("s1", "a2", 8.0); List<String> maxActions = table.getBestActions("s1"); Assert.assertEquals(1, maxActions.size()); Assert.assertTrue(maxActions.contains("a2")); } @Test public void testGetBestActions_2(){ ActionValueTableInMemory table = new ActionValueTableInMemory(); table.putValue("s1", "a1", 8.0); table.putValue("s1", "a2", 2.0); table.putValue("s1", "a3", 8.0); List<String> maxActions = table.getBestActions("s1"); Assert.assertEquals(2, maxActions.size()); Assert.assertTrue(maxActions.contains("a1")); Assert.assertTrue(maxActions.contains("a3")); } @Test public void testGetBestActions_3(){ ActionValueTableInMemory table = new ActionValueTableInMemory(); table.putValue("s1", "a1", 8.0); table.putValue("s1", "a2", 2.0); List<String> maxActions = table.getBestActions("s2"); Assert.assertTrue(maxActions.isEmpty()); } @Test public void testPutValue_1(){ //Tests an update ActionValueTableInMemory table = new ActionValueTableInMemory(); table.putValue("s1", "a1", 8.0); table.putValue("s1", "a2", 2.0); table.putValue("s1", "a1", 7.0); Assert.assertEquals(7.0, table.getValue("s1", "a1"), 0.00001); } }
4,351
0.606757
0.581705
120
34.258335
22.929783
83
false
false
0
0
0
0
0
0
1.066667
false
false
11
76e7cd0bbb7679240695fc57d7cf8c9bb132b389
15,144,054,711,689
cd635ce7747761bdf92687cefc4ddbefcf6fd22f
/SalesConnectWebWaffle/src/com/ibm/salesconnect/test/Level1/AT_FavoriteContact.java
f19ffa8aba999a8c96c840a7abb52b3859f75fce
[]
no_license
vasko87/IBM_SCWebWaffle
https://github.com/vasko87/IBM_SCWebWaffle
8faf85055b245ae67a4eaa6e0b1ce499ecf3ced6
32ad0c988ffc8a356a65e546467720a09f984344
refs/heads/master
2021-01-10T02:07:39.431000
2016-03-03T17:07:00
2016-03-03T17:07:00
52,597,648
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.ibm.salesconnect.test.Level1; import java.sql.SQLException; import java.util.Random; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.testng.Assert; import org.testng.annotations.Test; import com.ibm.atmn.waffle.extensions.user.User; import com.ibm.salesconnect.API.SugarAPI; import com.ibm.salesconnect.PoolHandling.Client.PoolClient; import com.ibm.salesconnect.common.GC; import com.ibm.salesconnect.model.adminconsole.ProductBaseTest; import com.ibm.salesconnect.model.standard.Dashboard; import com.ibm.salesconnect.model.standard.Contact.ContactDetailPage; import com.ibm.salesconnect.model.standard.Contact.ViewContactPage; /** * <strong>Description:</strong> * <br/><br/> * Test to validate the Create, Read, Update-Convert to Favorite and Search for the Favorite Contact functionality of the Contacts module * <br/><br/> * * @author * Veena Hurukadli * */ public class AT_FavoriteContact extends ProductBaseTest { Logger log = LoggerFactory.getLogger(AT_Sugar.class); int rand = new Random().nextInt(100000); /** * <br/><br/> * Test steps * <ol> * <li>Open browser and log in</li> * <li>Create Contact</li> * <li>Search for created Contact</li> * <li>Open Contact detail page</li> * <li>Update Contact-Add to Favorites</li> * <li>Search for the Favorite contact</li> * </ol> */ @Test(groups = { "Level1","AT_Sugar","BVT","BVT1"}) public void Test_AT_FavoriteContact() throws SQLException{ log.info("Start of test method Test_AT_Contact"); User user1 = commonUserAllocator.getGroupUser(GC.busAdminGroup,this); log.info("Getting client Via API"); PoolClient poolClient = commonClientAllocator.getGroupClient("SC"); String clientID = poolClient.getCCMS_ID(); log.info("Creating contact Via API"); String contactFirst = "contactFirst"+rand; String contactLast = "contactLast"+rand; String contactID = "22SC-" + rand; SugarAPI sugarAPI = new SugarAPI(); sugarAPI.createContact(testConfig.getBrowserURL(), contactID, clientID, user1.getEmail(), user1.getPassword(), contactFirst, contactLast); log.info("Logging in"); Dashboard dashboard = launchWithLogin(user1); log.info("Searching for API created contact"); ViewContactPage viewContactPage = dashboard.openViewContact(); viewContactPage.searchForContactName(contactFirst); ContactDetailPage contactDetailPage = viewContactPage.selectTextResult(contactFirst); contactDetailPage.addContactToMyFavorites(); log.info("Searching for API created contact"); viewContactPage = dashboard.openViewContact(); viewContactPage.searchForFavoriteContactName(contactFirst); contactDetailPage = viewContactPage.selectTextResult(contactFirst); Assert.assertEquals(contactDetailPage.getdisplayedContactName(),contactFirst +" "+ contactLast, "Incorrect contact detail page displayed"); commonClientAllocator.checkInAllGroupClients("SC"); log.info("End of test method Test_AT_FavoriteContact"); } }
UTF-8
Java
2,980
java
AT_FavoriteContact.java
Java
[ { "context": "e Contacts module\n * <br/><br/>\n * \n * @author \n * Veena Hurukadli\n * \n */\npublic class AT_FavoriteContact extends P", "end": 904, "score": 0.9998536109924316, "start": 889, "tag": "NAME", "value": "Veena Hurukadli" } ]
null
[]
package com.ibm.salesconnect.test.Level1; import java.sql.SQLException; import java.util.Random; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.testng.Assert; import org.testng.annotations.Test; import com.ibm.atmn.waffle.extensions.user.User; import com.ibm.salesconnect.API.SugarAPI; import com.ibm.salesconnect.PoolHandling.Client.PoolClient; import com.ibm.salesconnect.common.GC; import com.ibm.salesconnect.model.adminconsole.ProductBaseTest; import com.ibm.salesconnect.model.standard.Dashboard; import com.ibm.salesconnect.model.standard.Contact.ContactDetailPage; import com.ibm.salesconnect.model.standard.Contact.ViewContactPage; /** * <strong>Description:</strong> * <br/><br/> * Test to validate the Create, Read, Update-Convert to Favorite and Search for the Favorite Contact functionality of the Contacts module * <br/><br/> * * @author * <NAME> * */ public class AT_FavoriteContact extends ProductBaseTest { Logger log = LoggerFactory.getLogger(AT_Sugar.class); int rand = new Random().nextInt(100000); /** * <br/><br/> * Test steps * <ol> * <li>Open browser and log in</li> * <li>Create Contact</li> * <li>Search for created Contact</li> * <li>Open Contact detail page</li> * <li>Update Contact-Add to Favorites</li> * <li>Search for the Favorite contact</li> * </ol> */ @Test(groups = { "Level1","AT_Sugar","BVT","BVT1"}) public void Test_AT_FavoriteContact() throws SQLException{ log.info("Start of test method Test_AT_Contact"); User user1 = commonUserAllocator.getGroupUser(GC.busAdminGroup,this); log.info("Getting client Via API"); PoolClient poolClient = commonClientAllocator.getGroupClient("SC"); String clientID = poolClient.getCCMS_ID(); log.info("Creating contact Via API"); String contactFirst = "contactFirst"+rand; String contactLast = "contactLast"+rand; String contactID = "22SC-" + rand; SugarAPI sugarAPI = new SugarAPI(); sugarAPI.createContact(testConfig.getBrowserURL(), contactID, clientID, user1.getEmail(), user1.getPassword(), contactFirst, contactLast); log.info("Logging in"); Dashboard dashboard = launchWithLogin(user1); log.info("Searching for API created contact"); ViewContactPage viewContactPage = dashboard.openViewContact(); viewContactPage.searchForContactName(contactFirst); ContactDetailPage contactDetailPage = viewContactPage.selectTextResult(contactFirst); contactDetailPage.addContactToMyFavorites(); log.info("Searching for API created contact"); viewContactPage = dashboard.openViewContact(); viewContactPage.searchForFavoriteContactName(contactFirst); contactDetailPage = viewContactPage.selectTextResult(contactFirst); Assert.assertEquals(contactDetailPage.getdisplayedContactName(),contactFirst +" "+ contactLast, "Incorrect contact detail page displayed"); commonClientAllocator.checkInAllGroupClients("SC"); log.info("End of test method Test_AT_FavoriteContact"); } }
2,971
0.760067
0.754362
85
34.058823
30.831364
141
false
false
0
0
0
0
0
0
1.552941
false
false
11
67a582e1239d7d4d13d59c71884b6808d114eceb
33,320,356,336,501
a745530e768371e1f54f1e77e3a737a953438e08
/Constructors/src/com/company/Account.java
7416115700d3cef3e7ac6637a14efa9c3b266cf9
[]
no_license
jefferygraham/java-masterclass
https://github.com/jefferygraham/java-masterclass
4ea1709d6c21c46b7d90d788a201350141bfb3f4
9365fa5e002bed1b4fde5e9e13196bb79292d549
refs/heads/master
2023-01-21T01:27:13.151000
2020-11-19T23:36:33
2020-11-19T23:36:33
312,944,785
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.company; public class Account { private String number; private double balance; private String customerName; private String email; private String phoneNumber; public Account() { this("1234", 0.00, "Default name", "Default email", "Default phone number"); System.out.println("Empty constructor called"); } public Account(String number, double balance, String customerName, String email, String phoneNumber) { System.out.println("Constructor with parameters called"); this.number = number; this.balance = balance; this.customerName = customerName; this.email = email; this.phoneNumber = phoneNumber; } public Account(String customerName, String email, String phoneNumber) { this("00000", 1111.11, customerName, email, phoneNumber); } public void deposit(double amt) { this.balance += amt; System.out.println("Deposited " + amt + ". New balance: " + amt); } public void withdrawal(double amt) { System.out.println("Withdrawing " + amt); if (this.balance - amt < 0) { System.out.println("Insufficient funds! Only " + this.balance + " available."); } else { this.balance -= amt; System.out.println("Withdrew " + amt + ". Remaining balance: " + this.balance); } } public String getNumber() { return number; } public void setNumber(String number) { this.number = number; } public double getBalance() { return balance; } public void setBalance(double balance) { this.balance = balance; } public String getCustomerName() { return customerName; } public void setCustomerName(String customerName) { this.customerName = customerName; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getPhoneNumber() { return phoneNumber; } public void setPhoneNumber(String phoneNumber) { this.phoneNumber = phoneNumber; } // public void setAcctNumber(String number) { // this.number = number; // } // // public void setBalance(double balance) { // this.balance = balance; // } // // public void setCustomerName(String customerName) { // this.customerName = customerName; // } // // public void setEmail(String email) { // this.email = email; // } // // public void setPhoneNumber(String phoneNumber) { // this.phoneNumber = phoneNumber; // } // // public String getAcctNumber() { // return this.number; // } // // public double getBalance() { // return this.balance; // } // // public String getCustomerName() { // return this.customerName; // } // // public String getEmail() { // return this.email; // } // // public String getPhoneNumber() { // return this.phoneNumber; // } // // public double deposit(double amt) { // System.out.println("Depositing " + amt); // return this.balance += amt; // } // // public double withdrawal(double amt) { // if (this.balance - amt > 0) { // System.out.println("Withdrawing " + amt); // return this.balance -= amt; // } else { // System.out.println("Insufficient funds!"); // return -1; // } // } }
UTF-8
Java
3,511
java
Account.java
Java
[]
null
[]
package com.company; public class Account { private String number; private double balance; private String customerName; private String email; private String phoneNumber; public Account() { this("1234", 0.00, "Default name", "Default email", "Default phone number"); System.out.println("Empty constructor called"); } public Account(String number, double balance, String customerName, String email, String phoneNumber) { System.out.println("Constructor with parameters called"); this.number = number; this.balance = balance; this.customerName = customerName; this.email = email; this.phoneNumber = phoneNumber; } public Account(String customerName, String email, String phoneNumber) { this("00000", 1111.11, customerName, email, phoneNumber); } public void deposit(double amt) { this.balance += amt; System.out.println("Deposited " + amt + ". New balance: " + amt); } public void withdrawal(double amt) { System.out.println("Withdrawing " + amt); if (this.balance - amt < 0) { System.out.println("Insufficient funds! Only " + this.balance + " available."); } else { this.balance -= amt; System.out.println("Withdrew " + amt + ". Remaining balance: " + this.balance); } } public String getNumber() { return number; } public void setNumber(String number) { this.number = number; } public double getBalance() { return balance; } public void setBalance(double balance) { this.balance = balance; } public String getCustomerName() { return customerName; } public void setCustomerName(String customerName) { this.customerName = customerName; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getPhoneNumber() { return phoneNumber; } public void setPhoneNumber(String phoneNumber) { this.phoneNumber = phoneNumber; } // public void setAcctNumber(String number) { // this.number = number; // } // // public void setBalance(double balance) { // this.balance = balance; // } // // public void setCustomerName(String customerName) { // this.customerName = customerName; // } // // public void setEmail(String email) { // this.email = email; // } // // public void setPhoneNumber(String phoneNumber) { // this.phoneNumber = phoneNumber; // } // // public String getAcctNumber() { // return this.number; // } // // public double getBalance() { // return this.balance; // } // // public String getCustomerName() { // return this.customerName; // } // // public String getEmail() { // return this.email; // } // // public String getPhoneNumber() { // return this.phoneNumber; // } // // public double deposit(double amt) { // System.out.println("Depositing " + amt); // return this.balance += amt; // } // // public double withdrawal(double amt) { // if (this.balance - amt > 0) { // System.out.println("Withdrawing " + amt); // return this.balance -= amt; // } else { // System.out.println("Insufficient funds!"); // return -1; // } // } }
3,511
0.58217
0.576189
139
24.258993
22.442039
106
false
false
0
0
0
0
0
0
0.438849
false
false
11
9a7d8655496b004e64cfc8b34cbd2cff0d249761
33,320,356,337,429
28b0275267c41a504c441227bda2db8a69000f10
/ScrollView_SinhVien/app/src/main/java/com/example/scrollview_sinhvien/myDBhelper.java
cefd3e1303291933821c4b72c6d5c5828d124470
[]
no_license
minhvu1502/SQLite_ScrollView
https://github.com/minhvu1502/SQLite_ScrollView
8944098e9b0a768a107031ca84262dc45b2d6c2d
954d3791000373a8749c73e6c7dfeace45410dea
refs/heads/master
2022-04-26T16:28:14.239000
2020-04-20T13:39:18
2020-04-20T13:39:18
257,167,908
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.scrollview_sinhvien; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import androidx.annotation.Nullable; public class myDBhelper extends SQLiteOpenHelper { private static final String DBname = "dbsv.db"; private static final int VERSION = 1; private static final String TABLE_NAME = "SinhVien"; private static final String ID = "_id"; private static final String NAME = "name"; private static final String YEAROB = "yearob"; private SQLiteDatabase myDB; public myDBhelper(@Nullable Context context) { super(context, DBname, null, VERSION); } public static String getID() { return ID; } public static String getNAME() { return NAME; } public static String getYEAROB() { return YEAROB; } @Override public void onCreate(SQLiteDatabase db) { String queryTB = "CREATE TABLE "+TABLE_NAME+"( "+ ID + " INTEGER PRIMARY KEY, " + NAME + " TEXT NOT NULL, "+ YEAROB + " INTEGER NOT NULL )"; db.execSQL(queryTB); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { } public void openDB(){ myDB = getWritableDatabase(); } public void closeDB(){ if (myDB!=null && myDB.isOpen()){ myDB.close(); } } public long Insert(int id, String name, int yearob){ ContentValues contentValues = new ContentValues(); contentValues.put(ID ,id); contentValues.put(NAME,name); contentValues.put(YEAROB,yearob); return myDB.insert(TABLE_NAME, null, contentValues); } public long Update(int id, String name, int yearob){ ContentValues contentValues = new ContentValues(); contentValues.put(ID ,id); contentValues.put(NAME,name); contentValues.put(YEAROB,yearob); String where = ID +" = "+id; return myDB.update(TABLE_NAME, contentValues, where, null); } public long Delete(int id){ String where = ID +" = "+id; return myDB.delete(TABLE_NAME, where, null); } public Cursor getAllRecord(){ String query = "SELECT * FROM "+ TABLE_NAME; return myDB.rawQuery(query, null); } }
UTF-8
Java
2,443
java
myDBhelper.java
Java
[]
null
[]
package com.example.scrollview_sinhvien; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import androidx.annotation.Nullable; public class myDBhelper extends SQLiteOpenHelper { private static final String DBname = "dbsv.db"; private static final int VERSION = 1; private static final String TABLE_NAME = "SinhVien"; private static final String ID = "_id"; private static final String NAME = "name"; private static final String YEAROB = "yearob"; private SQLiteDatabase myDB; public myDBhelper(@Nullable Context context) { super(context, DBname, null, VERSION); } public static String getID() { return ID; } public static String getNAME() { return NAME; } public static String getYEAROB() { return YEAROB; } @Override public void onCreate(SQLiteDatabase db) { String queryTB = "CREATE TABLE "+TABLE_NAME+"( "+ ID + " INTEGER PRIMARY KEY, " + NAME + " TEXT NOT NULL, "+ YEAROB + " INTEGER NOT NULL )"; db.execSQL(queryTB); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { } public void openDB(){ myDB = getWritableDatabase(); } public void closeDB(){ if (myDB!=null && myDB.isOpen()){ myDB.close(); } } public long Insert(int id, String name, int yearob){ ContentValues contentValues = new ContentValues(); contentValues.put(ID ,id); contentValues.put(NAME,name); contentValues.put(YEAROB,yearob); return myDB.insert(TABLE_NAME, null, contentValues); } public long Update(int id, String name, int yearob){ ContentValues contentValues = new ContentValues(); contentValues.put(ID ,id); contentValues.put(NAME,name); contentValues.put(YEAROB,yearob); String where = ID +" = "+id; return myDB.update(TABLE_NAME, contentValues, where, null); } public long Delete(int id){ String where = ID +" = "+id; return myDB.delete(TABLE_NAME, where, null); } public Cursor getAllRecord(){ String query = "SELECT * FROM "+ TABLE_NAME; return myDB.rawQuery(query, null); } }
2,443
0.6316
0.631191
86
27.406977
21.15028
78
false
false
0
0
0
0
0
0
0.72093
false
false
11
4089eab2dc5d8e5ae792b31ac8b09337911cb278
6,605,659,769,373
e179f8bb1a11b8d460526bf9923fe57a94312dd5
/openrgb-wrapper/src/main/java/de/lars/openrgbwrapper/utils/BufferUtil.java
b7ec9578c75c012e9c7478d815b49e611c4e54ff
[ "Apache-2.0" ]
permissive
RemoteLight/OpenRGB-Plugin
https://github.com/RemoteLight/OpenRGB-Plugin
fdbe7ccf61cdb4c8b11ec1f0920af2376515a79a
dd5decf5b3f986ec88d8cdb67b3c06a119a16de3
refs/heads/master
2023-06-15T08:55:47.005000
2021-07-13T13:40:24
2021-07-13T13:40:24
291,079,288
3
1
Apache-2.0
false
2021-01-02T12:10:55
2020-08-28T15:20:22
2020-12-23T21:00:45
2021-01-02T12:10:55
229
2
1
1
Java
false
false
package de.lars.openrgbwrapper.utils; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.util.Arrays; public class BufferUtil { /** * Helper method for reading a string from a ByteBuffer. There should be 2 leading bytes * which describes the length of the string. The method will automatically increment the offset. * @param buffer ByteBuffer to read from * @param offset current offset * @return parsed string value and new offset as Pair */ public static Pair<String, Integer> readString(ByteBuffer buffer, int offset) { short length = buffer.getShort(offset); // read the string byte length offset += 2; String text = new String(Arrays.copyOfRange(buffer.array(), offset, offset + length - 1), StandardCharsets.US_ASCII); offset += length; return new Pair<>(text, offset); } }
UTF-8
Java
924
java
BufferUtil.java
Java
[]
null
[]
package de.lars.openrgbwrapper.utils; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.util.Arrays; public class BufferUtil { /** * Helper method for reading a string from a ByteBuffer. There should be 2 leading bytes * which describes the length of the string. The method will automatically increment the offset. * @param buffer ByteBuffer to read from * @param offset current offset * @return parsed string value and new offset as Pair */ public static Pair<String, Integer> readString(ByteBuffer buffer, int offset) { short length = buffer.getShort(offset); // read the string byte length offset += 2; String text = new String(Arrays.copyOfRange(buffer.array(), offset, offset + length - 1), StandardCharsets.US_ASCII); offset += length; return new Pair<>(text, offset); } }
924
0.676407
0.67316
24
37.5
35.535194
125
false
false
0
0
0
0
0
0
0.625
false
false
11
5bc917f35f16402764ff5c57c2df9f56968fc20b
21,311,627,760,100
02328f340cf26fad929cef4864a69e4a9b083255
/springcoreassisment/src/main/java/com/tyss/springcore/beans/Pet.java
f12fb2dd993900b63d9fbdfe260f33c105040e99
[]
no_license
bhavanigmgowda/ELF-06-june-Testyantra-Nilesh
https://github.com/bhavanigmgowda/ELF-06-june-Testyantra-Nilesh
c10d290f9a5d5536c5a00bc02309f8a60dc613d9
e1a2abd8e5b7ca67c21b2c33a4b8b7a4cdb0820a
refs/heads/master
2020-07-18T12:27:34.878000
2019-09-03T12:35:43
2019-09-03T12:35:43
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.tyss.springcore.beans; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import com.tyss.springcore.Interface.Animal; public class Pet { String name; @Autowired //@Qualifier("Monkey") Animal animal; // getter and setter public String getName() { return name; } public void setName(String name) { this.name = name; } public Animal getAnimal() { return animal; } public void setAnimal(Animal animal) { this.animal = animal; } // method public void doSometing() { animal.eat(); animal.makeSound(); } }
UTF-8
Java
630
java
Pet.java
Java
[]
null
[]
package com.tyss.springcore.beans; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import com.tyss.springcore.Interface.Animal; public class Pet { String name; @Autowired //@Qualifier("Monkey") Animal animal; // getter and setter public String getName() { return name; } public void setName(String name) { this.name = name; } public Animal getAnimal() { return animal; } public void setAnimal(Animal animal) { this.animal = animal; } // method public void doSometing() { animal.eat(); animal.makeSound(); } }
630
0.714286
0.714286
38
15.578947
16.491835
62
false
false
0
0
0
0
0
0
1.210526
false
false
11
39b009dd5f49878aa5e236ddc35330afe3508074
2,568,390,485,645
4ddbbbac84cd46d9b324275ea2d51b50b2461d01
/src/com/java/VolatilePractice.java
7b253119c74a900b876791b9c6ee5c8ccad652a4
[]
no_license
andyzju/JavaBasic
https://github.com/andyzju/JavaBasic
4f714a64686b95e79f3cb22ee55b6b813bae1483
c3cb6e37019ffb7f3bdc7043087501eb1a5c386d
refs/heads/master
2021-01-22T04:57:20.947000
2015-10-29T03:12:01
2015-10-29T03:12:01
19,314,255
3
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.java; public class VolatilePractice { }
UTF-8
Java
59
java
VolatilePractice.java
Java
[]
null
[]
package com.java; public class VolatilePractice { }
59
0.694915
0.694915
5
9.8
12.416119
31
false
false
0
0
0
0
0
0
0.2
false
false
11
ed1c515218e78df5ed70ebd78f088ff7880d7be3
21,689,584,868,808
7210059c46af7ca4cff4d03fd546470e7b576e1d
/src/com/scaler/bit/StrangeEquality.java
243342dcfab0542812af78ccb675ba7cb8e7b0b3
[]
no_license
mparida1000/IntelliJ
https://github.com/mparida1000/IntelliJ
365170ab041c1683aeba9380f779d976c1b04d3b
7697625127357a22ce00b76d77a6dc03c880367d
refs/heads/master
2023-09-01T15:04:35.599000
2023-08-19T15:21:05
2023-08-19T15:21:05
156,004,863
0
0
null
false
2020-04-19T13:00:59
2018-11-03T17:03:38
2020-04-19T09:09:11
2020-04-19T13:00:58
3
0
0
0
Java
false
false
package com.scaler.bit; public class StrangeEquality { public static int solve(int A) { int X = 0; int i = 0; while(A > 0) { if((A&1) == 0) { X+=1<<i; } A>>=1; i++; } return X^1<<i; } public static void main(String[] args) { System.out.println(solve(19)); } }
UTF-8
Java
302
java
StrangeEquality.java
Java
[]
null
[]
package com.scaler.bit; public class StrangeEquality { public static int solve(int A) { int X = 0; int i = 0; while(A > 0) { if((A&1) == 0) { X+=1<<i; } A>>=1; i++; } return X^1<<i; } public static void main(String[] args) { System.out.println(solve(19)); } }
302
0.52649
0.493377
22
12.727273
11.970349
41
false
false
0
0
0
0
0
0
1.909091
false
false
11
5cbb559ca07a2b2a509bbf839528df4ffb540fe8
7,275,674,620,090
8a71ea0dc89af70772f924320dd8d39f817f2cf0
/generate/currencyratesetting/baseserviceapi/CurrencyRateSettingQueryDTO.java
3774af07c0b00f7240ada3eb9544970373091c7e
[]
no_license
mofancoder/aerfa-framework
https://github.com/mofancoder/aerfa-framework
3225b285b9004bf92d5d0c923f55987caa5c624c
9d586056fb7b6c120a11d7ea82e3ff7fc3a70cc4
refs/heads/master
2020-05-04T04:50:37.940000
2019-04-02T01:36:25
2019-04-02T01:36:25
178,975,178
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.zhulong.business.system.baseservice.entity.commonbussetting.baseservice.dto.commonbussetting; import com.zhulong.framework.common.dto.PageOrderDTO; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Getter; import lombok.Setter; import java.io.Serializable; /** * 描述:汇率管理数据查询对象 * @author MOFAN889 * @date 2019-04-01 16:21 */ @ApiModel("汇率管理查询数据对象") @Getter @Setter public class CurrencyRateSettingQueryDTO implements Serializable { @ApiModelProperty("分页排序信息") private PageOrderDTO pageOrderDTO; }
UTF-8
Java
630
java
CurrencyRateSettingQueryDTO.java
Java
[ { "context": "va.io.Serializable;\n\n/**\n* 描述:汇率管理数据查询对象\n* @author MOFAN889\n* @date 2019-04-01 16:21\n*/\n@ApiModel(\"汇率管理查询数据对象", "end": 362, "score": 0.9995701909065247, "start": 354, "tag": "USERNAME", "value": "MOFAN889" } ]
null
[]
package com.zhulong.business.system.baseservice.entity.commonbussetting.baseservice.dto.commonbussetting; import com.zhulong.framework.common.dto.PageOrderDTO; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Getter; import lombok.Setter; import java.io.Serializable; /** * 描述:汇率管理数据查询对象 * @author MOFAN889 * @date 2019-04-01 16:21 */ @ApiModel("汇率管理查询数据对象") @Getter @Setter public class CurrencyRateSettingQueryDTO implements Serializable { @ApiModelProperty("分页排序信息") private PageOrderDTO pageOrderDTO; }
630
0.805944
0.77972
24
22.875
25.164976
105
false
false
0
0
0
0
0
0
0.333333
false
false
11
bb3167af11b392b9d39d2936557c50d5f0f67907
5,403,068,886,490
86a117117d213bad78fa6d76fb394a9e2facabaa
/src/main/java/uk/ac/ed/epcc/safe/accounting/reports/ElementSet.java
59750c35b94aba542c412e936cbdf93933847036
[ "Apache-2.0" ]
permissive
spbooth/SAFE-ACCOUNTING
https://github.com/spbooth/SAFE-ACCOUNTING
a4f87b4b532c2cb42725521310d0358cc5bc2b1c
b938bf7490eb3477dfe3f7ebcf15df734005dfd7
refs/heads/master
2023-07-06T09:04:54.967000
2023-06-20T10:39:39
2023-06-20T10:39:39
47,353,267
3
0
NOASSERTION
false
2020-10-13T13:20:42
2015-12-03T18:56:49
2020-01-09T15:21:20
2020-10-13T13:20:41
5,287
2
0
1
Java
false
false
package uk.ac.ed.epcc.safe.accounting.reports; import java.util.TreeSet; import java.util.function.Predicate; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import uk.ac.ed.epcc.webapp.exceptions.ConsistencyError; /** A set of {@link Element}s sorted in document order * * @author Stephen Booth * */ public class ElementSet extends TreeSet<Element> { public ElementSet() { super(new NodeComparator()); } /** Merge an {@link Element} or an {@link ElementSet} into this set. * * @param o * @return modified {@link ElementSet} */ public ElementSet merge(Object o) { if( o instanceof Element) { add((Element)o); return this; } if( o instanceof ElementSet) { addAll((ElementSet) o); return this; } throw new ConsistencyError("Unsupported type "+o.getClass().getCanonicalName()); } /** Select children of an {@link Element} using a {@link Predicate} and add to an existing * {@link ElementSet} * * @param set * @param target * @param rule * @return */ public static ElementSet select(ElementSet set,Element target, Predicate<Element> rule) { NodeList children = target.getChildNodes(); for(int i=0 ; i< children.getLength();i++) { Node child = children.item(i); if( child.getNodeType()==Node.ELEMENT_NODE ) { Element e =(Element)child; if( rule.test(e)) { set.add(e); } } } return set; } /** Select all child elements of this {@link ElementSet} filtered using a {@link Predicate}. * adding the results to an existing {@link ElementSet} * @param set * @param rule * @return */ public ElementSet select(ElementSet set,Predicate<Element> rule) { for(Element e : this) { select(set,e,rule); } return set; } /** Select all child elements of this {@link ElementSet} filtered using a {@link Predicate}. * returning a new {@link ElementSet} * @param rule * @return */ public ElementSet select(Predicate<Element> rule) { return select(new ElementSet(),rule); } public static ElementSet ancestors(Element p) { ElementSet result = new ElementSet(); Node parent = p.getParentNode(); while( parent.getNodeType() == Node.ELEMENT_NODE) { result.add((Element) parent); parent = parent.getParentNode(); } return result; } public static ElementSet ancestors_self(Element p) { ElementSet result = new ElementSet(); result.add(p); Node parent = p.getParentNode(); while( parent.getNodeType() == Node.ELEMENT_NODE) { result.add((Element) parent); parent = parent.getParentNode(); } return result; } public static ElementSet select(Element p,Predicate<Element> rule) { return select(new ElementSet(),p,rule); } }
UTF-8
Java
2,805
java
ElementSet.java
Java
[ { "context": "lement}s sorted in document order\r\n * \r\n * @author Stephen Booth\r\n *\r\n */\r\npublic class ElementSet extends TreeSet", "end": 347, "score": 0.9996433258056641, "start": 334, "tag": "NAME", "value": "Stephen Booth" } ]
null
[]
package uk.ac.ed.epcc.safe.accounting.reports; import java.util.TreeSet; import java.util.function.Predicate; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import uk.ac.ed.epcc.webapp.exceptions.ConsistencyError; /** A set of {@link Element}s sorted in document order * * @author <NAME> * */ public class ElementSet extends TreeSet<Element> { public ElementSet() { super(new NodeComparator()); } /** Merge an {@link Element} or an {@link ElementSet} into this set. * * @param o * @return modified {@link ElementSet} */ public ElementSet merge(Object o) { if( o instanceof Element) { add((Element)o); return this; } if( o instanceof ElementSet) { addAll((ElementSet) o); return this; } throw new ConsistencyError("Unsupported type "+o.getClass().getCanonicalName()); } /** Select children of an {@link Element} using a {@link Predicate} and add to an existing * {@link ElementSet} * * @param set * @param target * @param rule * @return */ public static ElementSet select(ElementSet set,Element target, Predicate<Element> rule) { NodeList children = target.getChildNodes(); for(int i=0 ; i< children.getLength();i++) { Node child = children.item(i); if( child.getNodeType()==Node.ELEMENT_NODE ) { Element e =(Element)child; if( rule.test(e)) { set.add(e); } } } return set; } /** Select all child elements of this {@link ElementSet} filtered using a {@link Predicate}. * adding the results to an existing {@link ElementSet} * @param set * @param rule * @return */ public ElementSet select(ElementSet set,Predicate<Element> rule) { for(Element e : this) { select(set,e,rule); } return set; } /** Select all child elements of this {@link ElementSet} filtered using a {@link Predicate}. * returning a new {@link ElementSet} * @param rule * @return */ public ElementSet select(Predicate<Element> rule) { return select(new ElementSet(),rule); } public static ElementSet ancestors(Element p) { ElementSet result = new ElementSet(); Node parent = p.getParentNode(); while( parent.getNodeType() == Node.ELEMENT_NODE) { result.add((Element) parent); parent = parent.getParentNode(); } return result; } public static ElementSet ancestors_self(Element p) { ElementSet result = new ElementSet(); result.add(p); Node parent = p.getParentNode(); while( parent.getNodeType() == Node.ELEMENT_NODE) { result.add((Element) parent); parent = parent.getParentNode(); } return result; } public static ElementSet select(Element p,Predicate<Element> rule) { return select(new ElementSet(),p,rule); } }
2,798
0.655971
0.654545
102
25.5
23.489151
93
false
false
0
0
0
0
0
0
1.892157
false
false
11
db4e167c2c1b67e0196950214fa76c88233554cd
25,563,645,398,611
db15b9ecff81eb17e4933eae316d6f658a52201b
/17translate/src/org/translate/min/dao/UtilDao.java
48a70e33dccc6b0390e2941c60a83c898e06160b
[]
no_license
shimingit/17translate
https://github.com/shimingit/17translate
2925720a45c5c195b1bb6605df17f3bc6bce753e
3fdfa132c25c58dcad0410241c9a1aed9789658d
refs/heads/master
2016-09-05T17:52:18.823000
2014-10-12T14:48:16
2014-10-12T14:48:16
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.translate.min.dao; import java.util.List; import org.translate.min.entity.*; public interface UtilDao { public List<Language> getLanguage(String languagename); public List<Field> getField(String fieldname); public void addGtfield(String username,String fieldname); public void addGtlanguage(String username, String languagename); public void addFieldAllocate(FieldAllocate fieldAllocate); public boolean checkManager(String username, String password); public List<String> getFieldAllocateResult(); public List<String> getAreaTranslators(int fieldid); public List<LiveinTranslator> getLiveinTranslator(String username); }
UTF-8
Java
664
java
UtilDao.java
Java
[]
null
[]
package org.translate.min.dao; import java.util.List; import org.translate.min.entity.*; public interface UtilDao { public List<Language> getLanguage(String languagename); public List<Field> getField(String fieldname); public void addGtfield(String username,String fieldname); public void addGtlanguage(String username, String languagename); public void addFieldAllocate(FieldAllocate fieldAllocate); public boolean checkManager(String username, String password); public List<String> getFieldAllocateResult(); public List<String> getAreaTranslators(int fieldid); public List<LiveinTranslator> getLiveinTranslator(String username); }
664
0.793675
0.793675
18
34.833332
24.956072
68
false
false
0
0
0
0
0
0
1.333333
false
false
11
64bbb1a0a495115c1b7f98824b2021fc20186f1b
33,380,485,829,849
b33f0b88f0d13ba7ff60757118d326635da72790
/src/main/java/com/netease/data/reports/model/ChannelStatSummary.java
d12775222ea4eccf2492adb39380c1baf91297d2
[]
no_license
wangjian0805/data_reports
https://github.com/wangjian0805/data_reports
9edd71ddae4cbb08f243161d07d7ec183b323aac
e37f665054507c0ff16876e2dbba773b41f6ef3f
refs/heads/master
2018-01-14T11:01:37.952000
2017-06-27T02:41:27
2017-06-27T02:41:27
95,430,903
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.netease.data.reports.model; import com.fasterxml.jackson.annotation.JsonFormat; import java.util.Date; /** * Created by bjjinyalong on 2016/9/12. */ public class ChannelStatSummary { @JsonFormat(shape= JsonFormat.Shape.STRING, pattern="yyyy-MM-dd",timezone = "GMT+8") private Date date; private String platform; private String channel; private long accessnum; private long readnum; private long installnum; private long sumofread; private double avgnumofread; private double avgdurationofread; private double avgdurationofwait; public ChannelStatSummary(Date date, String platform, String channel, long accessnum, long readnum, long installnum, long sumofread, double avgnumofread, double avgdurationofread, double avgdurationofwait) { this.date = date; this.platform = platform; this.channel = channel; this.accessnum = accessnum; this.readnum = readnum; this.installnum = installnum; this.sumofread = sumofread; this.avgnumofread = avgnumofread; this.avgdurationofread = avgdurationofread; this.avgdurationofwait = avgdurationofwait; } public ChannelStatSummary(){ } public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } public String getPlatform() { return platform; } public void setPlatform(String platform) { this.platform = platform; } public String getChannel() { return channel; } public void setChannel(String channel) { this.channel = channel; } public long getAccessnum() { return accessnum; } public void setAccessnum(long accessnum) { this.accessnum = accessnum; } public long getReadnum() { return readnum; } public void setReadnum(long readnum) { this.readnum = readnum; } public long getInstallnum() { return installnum; } public void setInstallnum(long installnum) { this.installnum = installnum; } public long getSumofread() { return sumofread; } public void setSumofread(long sumofread) { this.sumofread = sumofread; } public double getAvgnumofread() { return avgnumofread; } public void setAvgnumofread(double avgnumofread) { this.avgnumofread = avgnumofread; } public double getAvgdurationofread() { return avgdurationofread; } public void setAvgdurationofread(double avgdurationofread) { this.avgdurationofread = avgdurationofread; } public double getAvgdurationofwait() { return avgdurationofwait; } public void setAvgdurationofwait(double avgdurationofwait) { this.avgdurationofwait = avgdurationofwait; } }
UTF-8
Java
2,871
java
ChannelStatSummary.java
Java
[ { "context": "Format;\n\nimport java.util.Date;\n\n/**\n * Created by bjjinyalong on 2016/9/12.\n */\npublic class ChannelStatSummary", "end": 147, "score": 0.9997186660766602, "start": 136, "tag": "USERNAME", "value": "bjjinyalong" } ]
null
[]
package com.netease.data.reports.model; import com.fasterxml.jackson.annotation.JsonFormat; import java.util.Date; /** * Created by bjjinyalong on 2016/9/12. */ public class ChannelStatSummary { @JsonFormat(shape= JsonFormat.Shape.STRING, pattern="yyyy-MM-dd",timezone = "GMT+8") private Date date; private String platform; private String channel; private long accessnum; private long readnum; private long installnum; private long sumofread; private double avgnumofread; private double avgdurationofread; private double avgdurationofwait; public ChannelStatSummary(Date date, String platform, String channel, long accessnum, long readnum, long installnum, long sumofread, double avgnumofread, double avgdurationofread, double avgdurationofwait) { this.date = date; this.platform = platform; this.channel = channel; this.accessnum = accessnum; this.readnum = readnum; this.installnum = installnum; this.sumofread = sumofread; this.avgnumofread = avgnumofread; this.avgdurationofread = avgdurationofread; this.avgdurationofwait = avgdurationofwait; } public ChannelStatSummary(){ } public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } public String getPlatform() { return platform; } public void setPlatform(String platform) { this.platform = platform; } public String getChannel() { return channel; } public void setChannel(String channel) { this.channel = channel; } public long getAccessnum() { return accessnum; } public void setAccessnum(long accessnum) { this.accessnum = accessnum; } public long getReadnum() { return readnum; } public void setReadnum(long readnum) { this.readnum = readnum; } public long getInstallnum() { return installnum; } public void setInstallnum(long installnum) { this.installnum = installnum; } public long getSumofread() { return sumofread; } public void setSumofread(long sumofread) { this.sumofread = sumofread; } public double getAvgnumofread() { return avgnumofread; } public void setAvgnumofread(double avgnumofread) { this.avgnumofread = avgnumofread; } public double getAvgdurationofread() { return avgdurationofread; } public void setAvgdurationofread(double avgdurationofread) { this.avgdurationofread = avgdurationofread; } public double getAvgdurationofwait() { return avgdurationofwait; } public void setAvgdurationofwait(double avgdurationofwait) { this.avgdurationofwait = avgdurationofwait; } }
2,871
0.660049
0.657262
119
23.126051
25.632685
211
false
false
0
0
0
0
0
0
0.453782
false
false
11
b80f83adbbc54c277008c1b76c76d42aef93f7c6
32,349,693,677,181
5e72ae8b1fc8f37f7b4b7fb05ad7f836bba0b425
/rameses-client-ui/src/com/rameses/rcp/control/date/AbstractCalendarModel.java
3d80c6235b016277210cd1b41ff95a81c86383c3
[]
no_license
ramesesinc/platform-desktop
https://github.com/ramesesinc/platform-desktop
10059253e56376dceb213d7df0e3181539fed2f8
eb4d9f6b31f340cddb3e5e33e5ccbee439db35c7
refs/heads/master
2022-07-07T04:38:46.036000
2022-07-01T06:50:22
2022-07-01T06:50:22
170,252,271
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * AbstractCalendarModel.java * * Created on September 21, 2010, 1:55 PM * * To change this template, choose Tools | Template Manager * and open the template in the editor. */ package com.rameses.rcp.control.date; import javax.swing.JComponent; /** * * @author Windhel */ public abstract class AbstractCalendarModel { public abstract void showCalendar(); public abstract void hideCalendar(); public abstract String getSelectedValue(); public abstract JComponent getCalendar(); }
UTF-8
Java
531
java
AbstractCalendarModel.java
Java
[ { "context": "\nimport javax.swing.JComponent;\n\n/**\n *\n * @author Windhel\n */\n\npublic abstract class AbstractCalendarModel ", "end": 282, "score": 0.9994577169418335, "start": 275, "tag": "NAME", "value": "Windhel" } ]
null
[]
/* * AbstractCalendarModel.java * * Created on September 21, 2010, 1:55 PM * * To change this template, choose Tools | Template Manager * and open the template in the editor. */ package com.rameses.rcp.control.date; import javax.swing.JComponent; /** * * @author Windhel */ public abstract class AbstractCalendarModel { public abstract void showCalendar(); public abstract void hideCalendar(); public abstract String getSelectedValue(); public abstract JComponent getCalendar(); }
531
0.696799
0.679849
28
17.964285
19.415535
59
false
false
0
0
0
0
0
0
0.357143
false
false
11
c829a1439e695c6ec4ceacf70f6d9f2368894164
9,938,554,344,598
26b7f30c6640b8017a06786e4a2414ad8a4d71dd
/src/number_of_direct_superinterfaces/i37218.java
c8d662269221dc3318b68368ca46c0bcfc8345af
[]
no_license
vincentclee/jvm-limits
https://github.com/vincentclee/jvm-limits
b72a2f2dcc18caa458f1e77924221d585f23316b
2fd1c26d1f7984ea8163bc103ad14b6d72282281
refs/heads/master
2020-05-18T11:18:41.711000
2014-09-14T04:25:18
2014-09-14T04:25:18
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package number_of_direct_superinterfaces; public interface i37218 {}
UTF-8
Java
69
java
i37218.java
Java
[]
null
[]
package number_of_direct_superinterfaces; public interface i37218 {}
69
0.826087
0.753623
3
22.333334
16.937796
41
false
false
0
0
0
0
0
0
0.333333
false
false
11
cc4540d1129721a0aae53d432d24a0bebf058cf8
30,150,670,442,222
f72746b7242bca90211b8b3199eb508581999599
/src/main/java/com/khh/web/dao/UserMapper.java
58d72097f0ad74c53e6c965368f751629ae46ca6
[]
no_license
kuanghh/bookshop
https://github.com/kuanghh/bookshop
f296f843a6e55abb4f8d45b30ae0fd7f66586e0b
99b499f88b0b09f6d2d0d6416e72f778e39f90e3
refs/heads/master
2020-12-30T15:30:48.810000
2017-06-03T01:01:45
2017-06-03T01:01:45
91,153,298
1
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.khh.web.dao; import com.khh.common.bean.PagerBean; import com.khh.common.bean.UserRegisterBean; import com.khh.web.domain.User; import org.apache.ibatis.annotations.Param; import java.util.List; import java.util.Map; public interface UserMapper { /** * 用户注册时添加新用户 * @param user * @return */ int insert(User user); /** * 根据Id删除 这里是假删除 * @param id * @return */ int deleteById(String id); /** * 获取所有有效的用户 * @return */ List<UserRegisterBean> findAllBean(); /** * 根据关键字获取一共有多少条记录(只查询有效数据) * @param keyMap * @return */ int findCountWithKey(@Param("keyMap") Map<String,String> keyMap); /** * 根据关键字分页查询记录(只查询有效数据) * @param pagerBean * @return */ List<UserRegisterBean> findBeanInPage(PagerBean<UserRegisterBean> pagerBean); /** * 根据id查询用户 * @param id * @return */ User findById(String id); /** * 更新用户信息 * @param user * @return */ int update(User user); }
UTF-8
Java
1,227
java
UserMapper.java
Java
[]
null
[]
package com.khh.web.dao; import com.khh.common.bean.PagerBean; import com.khh.common.bean.UserRegisterBean; import com.khh.web.domain.User; import org.apache.ibatis.annotations.Param; import java.util.List; import java.util.Map; public interface UserMapper { /** * 用户注册时添加新用户 * @param user * @return */ int insert(User user); /** * 根据Id删除 这里是假删除 * @param id * @return */ int deleteById(String id); /** * 获取所有有效的用户 * @return */ List<UserRegisterBean> findAllBean(); /** * 根据关键字获取一共有多少条记录(只查询有效数据) * @param keyMap * @return */ int findCountWithKey(@Param("keyMap") Map<String,String> keyMap); /** * 根据关键字分页查询记录(只查询有效数据) * @param pagerBean * @return */ List<UserRegisterBean> findBeanInPage(PagerBean<UserRegisterBean> pagerBean); /** * 根据id查询用户 * @param id * @return */ User findById(String id); /** * 更新用户信息 * @param user * @return */ int update(User user); }
1,227
0.583412
0.583412
61
16.409836
15.860434
81
false
false
0
0
0
0
0
0
0.245902
false
false
11
3139bee075905b42ac209c5e2ec04a2d35c2e106
28,939,489,661,111
8b63ba33be6e2e45630ebc46cb3a12b199ce89d0
/src/main/java/com/yunpos/payment/alipay/model/AlipayRefundReqData.java
cbd4ceb6e91a4bf3542ee5ebe54a3fa99914a676
[]
no_license
qiaohd/yunpos
https://github.com/qiaohd/yunpos
9bbd19fa9505940209fe687c54908823189c824a
f2c43648d3af509cc7d4a0f99c01239953f88f03
HEAD
2019-07-06T09:17:50.194000
2015-10-19T09:35:05
2015-10-19T09:35:05
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.yunpos.payment.alipay.model; import java.lang.reflect.Field; import java.util.HashMap; import java.util.Map; import com.yunpos.payment.alipay.config.AlipayConfig; /** * * 功能描述:退款请求参数封装 * <p> * 版权所有:小牛信息科技有限公司 * <p> * 未经本公司许可,不得以任何方式复制或使用本程序任何部分 * * @author Devin_Yang 新增日期:2015年8月19日 * @author Devin_Yang 修改日期:2015年8月19日 * */ public class AlipayRefundReqData { // 接口参数说明详细请查看官方文档 private String service = ""; // 接口名称(必填) private String partner = ""; // 合作者身份ID(必填) private String _input_charset = ""; // 参数编码字符集(必填) private String sign_type = ""; // 签名方式(必填) private String sign = ""; // 签名(必填) private String alipay_ca_request = ""; // 签名类型 (非必填) private String out_trade_no = ""; // 商户网站唯一订单号(必填) private String refund_amount = ""; // 退款金额(必填) private String trade_no = ""; // 支付宝交易号(非必填) private String out_request_no = ""; // 商户退款请求单号(非必填) private String operator_type = ""; // 操作员类型(非必填) private String operator_id = ""; // 操作员号 (非必填) private String refund_reason = ""; // 退款原因(非必填) private String ref_ids = ""; // 业务关联 ID集合(非必填) // 业务附加传递信息(非接口参数) private String pay_channel = ""; private String terminal_unique_no = ""; private String merchant_name = ""; private String merchant_num = ""; public AlipayRefundReqData(String partner, String out_trade_no, String refund_amount) { // 接口名称 setService(AlipayConfig.refund); // 合作者身份ID setPartner(partner); // 参数编码字符集 set_input_charset(AlipayConfig.input_charset); // 签名方式 setSign_type(AlipayConfig.sign_type); // 商户网站唯一订单号 setOut_trade_no(out_trade_no); // 退款金额(必填) setRefund_amount(refund_amount); // 支付宝交易号(非必填) // setTrade_no(trade_no); // 商户退款请求单号(非必填) // setOut_request_no(out_request_no); } public String getService() { return service; } public void setService(String service) { this.service = service; } public String getPartner() { return partner; } public void setPartner(String partner) { this.partner = partner; } public String get_input_charset() { return _input_charset; } public void set_input_charset(String _input_charset) { this._input_charset = _input_charset; } public String getSign_type() { return sign_type; } public void setSign_type(String sign_type) { this.sign_type = sign_type; } public String getSign() { return sign; } public void setSign(String sign) { this.sign = sign; } public String getAlipay_ca_request() { return alipay_ca_request; } public void setAlipay_ca_request(String alipay_ca_request) { this.alipay_ca_request = alipay_ca_request; } public String getOut_trade_no() { return out_trade_no; } public void setOut_trade_no(String out_trade_no) { this.out_trade_no = out_trade_no; } public String getRefund_amount() { return refund_amount; } public void setRefund_amount(String refund_amount) { this.refund_amount = refund_amount; } public String getTrade_no() { return trade_no; } public void setTrade_no(String trade_no) { this.trade_no = trade_no; } public String getOut_request_no() { return out_request_no; } public void setOut_request_no(String out_request_no) { this.out_request_no = out_request_no; } public String getOperator_type() { return operator_type; } public void setOperator_type(String operator_type) { this.operator_type = operator_type; } public String getOperator_id() { return operator_id; } public void setOperator_id(String operator_id) { this.operator_id = operator_id; } public String getRefund_reason() { return refund_reason; } public void setRefund_reason(String refund_reason) { this.refund_reason = refund_reason; } public String getRef_ids() { return ref_ids; } public void setRef_ids(String ref_ids) { this.ref_ids = ref_ids; } public String getPay_channel() { return pay_channel; } public void setPay_channel(String pay_channel) { this.pay_channel = pay_channel; } public String getTerminal_unique_no() { return terminal_unique_no; } public void setTerminal_unique_no(String terminal_unique_no) { this.terminal_unique_no = terminal_unique_no; } public String getMerchant_num() { return merchant_num; } public void setMerchant_num(String merchant_num) { this.merchant_num = merchant_num; } public String getMerchant_name() { return merchant_name; } public void setMerchant_name(String merchant_name) { this.merchant_name = merchant_name; } public Map<String, String> toMap() { Map<String, String> map = new HashMap<String, String>(); Field[] fields = this.getClass().getDeclaredFields(); for (Field field : fields) { Object obj; try { obj = field.get(this); if (obj != null && !obj.equals("")) { map.put(field.getName(), (String) obj); } } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } } return map; } }
UTF-8
Java
5,740
java
AlipayRefundReqData.java
Java
[ { "context": ">\r\n * 未经本公司许可,不得以任何方式复制或使用本程序任何部分\r\n * \r\n * @author Devin_Yang 新增日期:2015年8月19日\r\n * @author Devin_Yang 修改日期:2015年", "end": 308, "score": 0.9995487332344055, "start": 298, "tag": "NAME", "value": "Devin_Yang" }, { "context": "\n * @author Devin_Yang 新增日期:2015年8月19日\r\n * @author Devin_Yang 修改日期:2015年8月19日\r\n *\r\n */\r\npublic class AlipayRefu", "end": 347, "score": 0.9993941187858582, "start": 337, "tag": "NAME", "value": "Devin_Yang" } ]
null
[]
package com.yunpos.payment.alipay.model; import java.lang.reflect.Field; import java.util.HashMap; import java.util.Map; import com.yunpos.payment.alipay.config.AlipayConfig; /** * * 功能描述:退款请求参数封装 * <p> * 版权所有:小牛信息科技有限公司 * <p> * 未经本公司许可,不得以任何方式复制或使用本程序任何部分 * * @author Devin_Yang 新增日期:2015年8月19日 * @author Devin_Yang 修改日期:2015年8月19日 * */ public class AlipayRefundReqData { // 接口参数说明详细请查看官方文档 private String service = ""; // 接口名称(必填) private String partner = ""; // 合作者身份ID(必填) private String _input_charset = ""; // 参数编码字符集(必填) private String sign_type = ""; // 签名方式(必填) private String sign = ""; // 签名(必填) private String alipay_ca_request = ""; // 签名类型 (非必填) private String out_trade_no = ""; // 商户网站唯一订单号(必填) private String refund_amount = ""; // 退款金额(必填) private String trade_no = ""; // 支付宝交易号(非必填) private String out_request_no = ""; // 商户退款请求单号(非必填) private String operator_type = ""; // 操作员类型(非必填) private String operator_id = ""; // 操作员号 (非必填) private String refund_reason = ""; // 退款原因(非必填) private String ref_ids = ""; // 业务关联 ID集合(非必填) // 业务附加传递信息(非接口参数) private String pay_channel = ""; private String terminal_unique_no = ""; private String merchant_name = ""; private String merchant_num = ""; public AlipayRefundReqData(String partner, String out_trade_no, String refund_amount) { // 接口名称 setService(AlipayConfig.refund); // 合作者身份ID setPartner(partner); // 参数编码字符集 set_input_charset(AlipayConfig.input_charset); // 签名方式 setSign_type(AlipayConfig.sign_type); // 商户网站唯一订单号 setOut_trade_no(out_trade_no); // 退款金额(必填) setRefund_amount(refund_amount); // 支付宝交易号(非必填) // setTrade_no(trade_no); // 商户退款请求单号(非必填) // setOut_request_no(out_request_no); } public String getService() { return service; } public void setService(String service) { this.service = service; } public String getPartner() { return partner; } public void setPartner(String partner) { this.partner = partner; } public String get_input_charset() { return _input_charset; } public void set_input_charset(String _input_charset) { this._input_charset = _input_charset; } public String getSign_type() { return sign_type; } public void setSign_type(String sign_type) { this.sign_type = sign_type; } public String getSign() { return sign; } public void setSign(String sign) { this.sign = sign; } public String getAlipay_ca_request() { return alipay_ca_request; } public void setAlipay_ca_request(String alipay_ca_request) { this.alipay_ca_request = alipay_ca_request; } public String getOut_trade_no() { return out_trade_no; } public void setOut_trade_no(String out_trade_no) { this.out_trade_no = out_trade_no; } public String getRefund_amount() { return refund_amount; } public void setRefund_amount(String refund_amount) { this.refund_amount = refund_amount; } public String getTrade_no() { return trade_no; } public void setTrade_no(String trade_no) { this.trade_no = trade_no; } public String getOut_request_no() { return out_request_no; } public void setOut_request_no(String out_request_no) { this.out_request_no = out_request_no; } public String getOperator_type() { return operator_type; } public void setOperator_type(String operator_type) { this.operator_type = operator_type; } public String getOperator_id() { return operator_id; } public void setOperator_id(String operator_id) { this.operator_id = operator_id; } public String getRefund_reason() { return refund_reason; } public void setRefund_reason(String refund_reason) { this.refund_reason = refund_reason; } public String getRef_ids() { return ref_ids; } public void setRef_ids(String ref_ids) { this.ref_ids = ref_ids; } public String getPay_channel() { return pay_channel; } public void setPay_channel(String pay_channel) { this.pay_channel = pay_channel; } public String getTerminal_unique_no() { return terminal_unique_no; } public void setTerminal_unique_no(String terminal_unique_no) { this.terminal_unique_no = terminal_unique_no; } public String getMerchant_num() { return merchant_num; } public void setMerchant_num(String merchant_num) { this.merchant_num = merchant_num; } public String getMerchant_name() { return merchant_name; } public void setMerchant_name(String merchant_name) { this.merchant_name = merchant_name; } public Map<String, String> toMap() { Map<String, String> map = new HashMap<String, String>(); Field[] fields = this.getClass().getDeclaredFields(); for (Field field : fields) { Object obj; try { obj = field.get(this); if (obj != null && !obj.equals("")) { map.put(field.getName(), (String) obj); } } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } } return map; } }
5,740
0.6541
0.65138
228
20.570175
19.194283
88
false
false
0
0
0
0
0
0
1.451754
false
false
11
6cdc56ac882e7300675bc63ea92074e8953a3fde
23,682,449,732,780
7e1526acc55d4d92a95fda283bd0a06708a53b42
/206/Lab02/src/StudentScore.java
38306511255b01a69cd135cefdf7a92c54f73e4c
[]
no_license
jamesarmenta/CompSci
https://github.com/jamesarmenta/CompSci
aa7f00b3b0bb80b2e3d1dfdd72d86606d01d0e21
c96cd81e97eba3d4ec3f41117c318db2198cdfc5
refs/heads/master
2020-12-24T15:22:18.346000
2016-10-22T19:34:40
2016-10-22T19:34:40
32,830,824
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
public class StudentScore implements Comparable<StudentScore>{ private String name; private int score; public StudentScore(){ //Default input name = "Student"; score = 0; } public StudentScore(String name, int score) { this.name = name; setScore(score); } public String getName() { return name; } public void setScore(int score) { if (score >= 0 && score <= 100) { this.score = score; } else { this.score = 0; //if score is outside of 0-100, set as 0 } } public int compareTo(StudentScore parmSS) { if (this.score == parmSS.score) { // check the names return this.name.compareTo(parmSS.name); } else { return this.score - parmSS.score; } } public String toString(){ return "Name: " + name + " | Score:" + score; } }
UTF-8
Java
803
java
StudentScore.java
Java
[ { "context": "\tpublic StudentScore(){ //Default input\n\t\tname = \"Student\";\n\t\tscore = 0;\n\t}\n\t\n\tpublic StudentScore(String n", "end": 166, "score": 0.9934160113334656, "start": 159, "tag": "NAME", "value": "Student" } ]
null
[]
public class StudentScore implements Comparable<StudentScore>{ private String name; private int score; public StudentScore(){ //Default input name = "Student"; score = 0; } public StudentScore(String name, int score) { this.name = name; setScore(score); } public String getName() { return name; } public void setScore(int score) { if (score >= 0 && score <= 100) { this.score = score; } else { this.score = 0; //if score is outside of 0-100, set as 0 } } public int compareTo(StudentScore parmSS) { if (this.score == parmSS.score) { // check the names return this.name.compareTo(parmSS.name); } else { return this.score - parmSS.score; } } public String toString(){ return "Name: " + name + " | Score:" + score; } }
803
0.622665
0.608966
54
13.888889
16.89912
62
false
false
0
0
0
0
0
0
1.666667
false
false
11
8cc020580ad157a248bc136f8adf6b5ae4a89873
23,682,449,733,366
6c1718de9e39d0bea94bc20a8c7e86ad7429ff3b
/FlipOrderManageService/src/main/java/com/flip/entity/dto/OrderInfoRequestDto.java
cc0fbf4286fd8db531534aa706ae41eb0ca29f76
[]
no_license
pankamit/flip
https://github.com/pankamit/flip
e3341393606b42971a338a32098190158e82296d
6e34bbd51481e7fc6a2dd3c3a7799c2ceec64f48
refs/heads/master
2022-12-23T15:34:17.649000
2020-03-25T05:38:55
2020-03-25T05:38:55
242,803,731
0
1
null
false
2022-12-15T23:25:11
2020-02-24T17:52:39
2020-03-25T05:43:32
2022-12-15T23:25:08
46,350
0
1
18
Java
false
false
package com.flip.entity.dto; import javax.persistence.EnumType; import javax.persistence.Enumerated; import com.flip.enumeration.OrderStatus; import lombok.Data; @Data public class OrderInfoRequestDto { private String userId; @Enumerated(EnumType.STRING) private OrderStatus effOrderStatus; private Double amount; private Integer quantity; private String[] productIdLst; }
UTF-8
Java
397
java
OrderInfoRequestDto.java
Java
[]
null
[]
package com.flip.entity.dto; import javax.persistence.EnumType; import javax.persistence.Enumerated; import com.flip.enumeration.OrderStatus; import lombok.Data; @Data public class OrderInfoRequestDto { private String userId; @Enumerated(EnumType.STRING) private OrderStatus effOrderStatus; private Double amount; private Integer quantity; private String[] productIdLst; }
397
0.783375
0.783375
24
15.458333
15.113402
40
false
false
0
0
0
0
0
0
0.916667
false
false
11
b56f1d4595cb7c1e5ffa61b0c6ab58c47b2cb643
33,303,176,459,779
55dae64b07133a3c5e48a9bc018681cfced8e745
/devops_admin/src/main/java/com/bee/devops/admin/core/vo/request/DeployJobRequest.java
6295e84fb49ca8c3aa8e2f47e3060bcae776d929
[]
no_license
Git-YHAn/Demo-two
https://github.com/Git-YHAn/Demo-two
53452f262a7121d6e6bd925e17d8a00ce8fdff25
cffcb35b359cee439ff601bf71bc9c42f0cf0359
refs/heads/master
2020-03-28T01:15:38.593000
2018-09-05T09:18:28
2018-09-05T09:18:28
147,490,815
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.bee.devops.admin.core.vo.request; import javax.validation.constraints.NotNull; import javax.validation.constraints.Pattern; import org.hibernate.validator.constraints.NotBlank; import com.bee.devops.admin.common.request.RestRequest; public class DeployJobRequest extends RestRequest{ private static final long serialVersionUID = 3204225517002900590L; private Long depJobId; @NotBlank(message="{base.job.depJobName.notNull}") private String depJobName; @NotBlank(message="{base.job.folderName.notNull}") private String folderName; @NotNull(message="{base.job.operateType.notNull}") private Integer operateType; private Integer enabled; @Pattern(regexp = "^.{0,50}$",message = "{base.job.description.format}") private String description; public Long getDepJobId() { return depJobId; } public void setDepJobId(Long depJobId) { this.depJobId = depJobId; } public String getDepJobName() { return depJobName; } public void setDepJobName(String depJobName) { this.depJobName = depJobName; } public String getFolderName() { return folderName; } public void setFolderName(String folderName) { this.folderName = folderName; } public Integer getOperateType() { return operateType; } public void setOperateType(Integer operateType) { this.operateType = operateType; } public Integer getEnabled() { return enabled; } public void setEnabled(Integer enabled) { this.enabled = enabled; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } }
UTF-8
Java
1,607
java
DeployJobRequest.java
Java
[]
null
[]
package com.bee.devops.admin.core.vo.request; import javax.validation.constraints.NotNull; import javax.validation.constraints.Pattern; import org.hibernate.validator.constraints.NotBlank; import com.bee.devops.admin.common.request.RestRequest; public class DeployJobRequest extends RestRequest{ private static final long serialVersionUID = 3204225517002900590L; private Long depJobId; @NotBlank(message="{base.job.depJobName.notNull}") private String depJobName; @NotBlank(message="{base.job.folderName.notNull}") private String folderName; @NotNull(message="{base.job.operateType.notNull}") private Integer operateType; private Integer enabled; @Pattern(regexp = "^.{0,50}$",message = "{base.job.description.format}") private String description; public Long getDepJobId() { return depJobId; } public void setDepJobId(Long depJobId) { this.depJobId = depJobId; } public String getDepJobName() { return depJobName; } public void setDepJobName(String depJobName) { this.depJobName = depJobName; } public String getFolderName() { return folderName; } public void setFolderName(String folderName) { this.folderName = folderName; } public Integer getOperateType() { return operateType; } public void setOperateType(Integer operateType) { this.operateType = operateType; } public Integer getEnabled() { return enabled; } public void setEnabled(Integer enabled) { this.enabled = enabled; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } }
1,607
0.756689
0.742999
77
19.870131
20.424934
73
false
false
0
0
0
0
0
0
1.116883
false
false
11
ebbbe87f6ca1cd609e0a3368e8bc36c74601f8e8
25,013,889,599,595
1b02ab7178d5c6a48767f73b23fee406ba258e58
/lovesy-core/src/main/java/com/wangzai/lovesy/core/download/MultiThreadDownload.java
a19af222ff2a625126afa051609816dc345908cd
[]
no_license
dawangzai/Android-Unsplash-Wallpaper
https://github.com/dawangzai/Android-Unsplash-Wallpaper
1fbe49f86af82cf4059617cf3c26c617b1a5441f
7dbc06a1bf6693e7d243429cafb36f0a9f9de85d
refs/heads/master
2020-05-20T22:35:05.553000
2018-07-21T03:49:49
2018-07-21T03:49:49
84,537,394
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.wangzai.lovesy.core.download; import android.content.Context; import android.content.Intent; import android.os.Environment; import android.support.annotation.NonNull; import com.wangzai.lovesy.core.download.callback.IError; import com.wangzai.lovesy.core.download.callback.IFailure; import com.wangzai.lovesy.core.download.callback.IProgress; import com.wangzai.lovesy.core.download.entities.FileInfo; import com.wangzai.lovesy.core.util.StringUtil; import com.wangzai.lovesy.core.util.file.FileUtil; /** * Created by wangzai on 2017/11/30 */ public class MultiThreadDownload { private static final String DIR_IMAGE = Environment.getExternalStorageDirectory(). getAbsolutePath() + "/lovesy"; public static final String ACTION_START = "ACTION_START"; public static final String ACTION_STOP = "ACTION_STOP"; public static final String ACTION_UPDATE = "ACTION_UPDATE"; public static final String ACTION_FINISH = "ACTION_FINISH"; public static final String EXTRA_FILE = "EXTRA_FILE"; public static final String EXTRA_UPDATE = "EXTRA_UPDATE"; public static final String EXTRA_FILE_ID = "EXTRA_FILE_ID"; private final String mUrl; private final String mFileName; private final String mDir; private final int mThreadCount; private final Context mContext; private final IProgress mIProgress; private final IError mIError; private final IFailure mIFailure; private FileInfo mFileInfo; private MultiThreadDownload(Context context, String url, String fileName, String dir, int threadCount, IProgress progress, IError error, IFailure failure) { this.mUrl = url; this.mFileName = fileName; this.mDir = dir; this.mThreadCount = threadCount; this.mContext = context; this.mIProgress = progress; this.mIError = error; this.mIFailure = failure; initFile(); } public static Builder builder() { return new Builder(); } private void initFile() { mFileInfo = new FileInfo(mUrl.hashCode(), mUrl, mDir, mFileName, mThreadCount, 0, 0); } public void download() { DownloadService.getDownloadManager().download(mFileInfo, mIProgress, mIError, mIFailure); } public void pause() { } public void delete() { } public static final class Builder { private String url; private String fileName; private String extension; private String dir; private int threadCount = 0; private Context context; private IProgress progress; private IError error; private IFailure failure; public Builder threadCount(int threadCount) { this.threadCount = threadCount; return this; } @NonNull public Builder context(Context context) { this.context = context; return this; } @NonNull public Builder url(String url) { this.url = url; return this; } public Builder fileName(String fileName) { this.fileName = fileName; return this; } public Builder extension(String extension) { this.extension = extension; return this; } public Builder dir(String dir) { this.dir = dir; return this; } public Builder progress(IProgress progress) { this.progress = progress; return this; } public Builder error(IError error) { this.error = error; return this; } public Builder failure(IFailure failure) { this.failure = failure; return this; } @NonNull public MultiThreadDownload build() { if (StringUtil.isEmpty(dir)) { this.dir = DIR_IMAGE; } if (StringUtil.isEmpty(extension)) { this.extension = ""; } if (StringUtil.isEmpty(fileName)) { this.fileName = FileUtil.getFileNameByTime(extension.toUpperCase(), extension); } if (threadCount == 0 || threadCount > 5) { this.threadCount = 3; } return new MultiThreadDownload( context, url, fileName, dir, threadCount, progress, error, failure); } } }
UTF-8
Java
4,838
java
MultiThreadDownload.java
Java
[ { "context": "lovesy.core.util.file.FileUtil;\n\n/**\n * Created by wangzai on 2017/11/30\n */\n\npublic class MultiThreadDownlo", "end": 541, "score": 0.9997339248657227, "start": 534, "tag": "USERNAME", "value": "wangzai" } ]
null
[]
package com.wangzai.lovesy.core.download; import android.content.Context; import android.content.Intent; import android.os.Environment; import android.support.annotation.NonNull; import com.wangzai.lovesy.core.download.callback.IError; import com.wangzai.lovesy.core.download.callback.IFailure; import com.wangzai.lovesy.core.download.callback.IProgress; import com.wangzai.lovesy.core.download.entities.FileInfo; import com.wangzai.lovesy.core.util.StringUtil; import com.wangzai.lovesy.core.util.file.FileUtil; /** * Created by wangzai on 2017/11/30 */ public class MultiThreadDownload { private static final String DIR_IMAGE = Environment.getExternalStorageDirectory(). getAbsolutePath() + "/lovesy"; public static final String ACTION_START = "ACTION_START"; public static final String ACTION_STOP = "ACTION_STOP"; public static final String ACTION_UPDATE = "ACTION_UPDATE"; public static final String ACTION_FINISH = "ACTION_FINISH"; public static final String EXTRA_FILE = "EXTRA_FILE"; public static final String EXTRA_UPDATE = "EXTRA_UPDATE"; public static final String EXTRA_FILE_ID = "EXTRA_FILE_ID"; private final String mUrl; private final String mFileName; private final String mDir; private final int mThreadCount; private final Context mContext; private final IProgress mIProgress; private final IError mIError; private final IFailure mIFailure; private FileInfo mFileInfo; private MultiThreadDownload(Context context, String url, String fileName, String dir, int threadCount, IProgress progress, IError error, IFailure failure) { this.mUrl = url; this.mFileName = fileName; this.mDir = dir; this.mThreadCount = threadCount; this.mContext = context; this.mIProgress = progress; this.mIError = error; this.mIFailure = failure; initFile(); } public static Builder builder() { return new Builder(); } private void initFile() { mFileInfo = new FileInfo(mUrl.hashCode(), mUrl, mDir, mFileName, mThreadCount, 0, 0); } public void download() { DownloadService.getDownloadManager().download(mFileInfo, mIProgress, mIError, mIFailure); } public void pause() { } public void delete() { } public static final class Builder { private String url; private String fileName; private String extension; private String dir; private int threadCount = 0; private Context context; private IProgress progress; private IError error; private IFailure failure; public Builder threadCount(int threadCount) { this.threadCount = threadCount; return this; } @NonNull public Builder context(Context context) { this.context = context; return this; } @NonNull public Builder url(String url) { this.url = url; return this; } public Builder fileName(String fileName) { this.fileName = fileName; return this; } public Builder extension(String extension) { this.extension = extension; return this; } public Builder dir(String dir) { this.dir = dir; return this; } public Builder progress(IProgress progress) { this.progress = progress; return this; } public Builder error(IError error) { this.error = error; return this; } public Builder failure(IFailure failure) { this.failure = failure; return this; } @NonNull public MultiThreadDownload build() { if (StringUtil.isEmpty(dir)) { this.dir = DIR_IMAGE; } if (StringUtil.isEmpty(extension)) { this.extension = ""; } if (StringUtil.isEmpty(fileName)) { this.fileName = FileUtil.getFileNameByTime(extension.toUpperCase(), extension); } if (threadCount == 0 || threadCount > 5) { this.threadCount = 3; } return new MultiThreadDownload( context, url, fileName, dir, threadCount, progress, error, failure); } } }
4,838
0.57007
0.567177
171
27.292398
21.178078
97
false
false
0
0
0
0
0
0
0.573099
false
false
11
c386be408c441f25e40b1c3d9a7fa8e8964bf894
3,023,656,999,722
5b8684e842df22ea07806a11c07b615de28b246b
/SeleniumDay1/src/test/java/com/test/NewTest.java
eb4a3cc7402c1dc83be89c3e38a877c0efb8253f
[]
no_license
sherinagsal/selenium-code
https://github.com/sherinagsal/selenium-code
784387677bfe9f1d36d2c941dab5403a5d75ddc5
cb75564235ee154098c0441de2261a872d4962e3
refs/heads/master
2020-05-07T12:57:00.915000
2019-04-10T07:42:36
2019-04-10T07:42:36
180,527,665
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.test; import java.util.List; import org.openqa.selenium.By; import org.openqa.selenium.Keys; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.interactions.Actions; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import org.testng.Assert; import org.testng.annotations.Test; public class NewTest { @Test public void f() throws InterruptedException { System.setProperty("webdriver.chrome.driver", "C:\\Users\\sherin.raju\\chromedriver_win32\\chromedriver.exe"); WebDriver driver =new ChromeDriver(); driver.get("https://www.cleartrip.com/"); driver.manage().window().maximize(); Thread.sleep(2000); WebElement from = driver.findElement(By.id("FromTag")); // to drag from this //from.sendKeys("h"); //from.sendKeys("y"); //from.sendKeys("d"); Actions act1=new Actions(driver); act1.keyDown(from,Keys.SHIFT).perform(); // for keys to be in caps use keydown for keys to be in small letters act1.sendKeys("h").perform(); Thread.sleep(2000); act1.sendKeys("y").perform(); Thread.sleep(2000); act1.sendKeys("d").perform(); Thread.sleep(5000); act1.sendKeys(Keys.ENTER).perform(); WebElement to = driver.findElement(By.id("ToTag")); // to drop here to.sendKeys("b"); to.sendKeys("a"); to.sendKeys("n"); //Thread.sleep(5000); WebDriverWait wait=new WebDriverWait(driver,10); wait.until(ExpectedConditions.presenceOfNestedElementsLocatedBy(By.id("ui-id-2"),By.className("list")));//to get the count of elements in list WebElement u1=driver.findElement(By.id("ui-id-2")); List<WebElement> list=u1.findElements(By.tagName("li")); // lsit is used e=instead of driver to get list of particular list //Assert.assertEquals(list.size(),10); for(WebElement e:list) // to select the element no matter which position it is present { if(e.getText().contains("HDD")) { e.click(); break; } } Assert.assertTrue(to.getAttribute("value").contains("HDD")); } }
UTF-8
Java
2,161
java
NewTest.java
Java
[ { "context": "etProperty(\"webdriver.chrome.driver\", \"C:\\\\Users\\\\sherin.raju\\\\chromedriver_win32\\\\chromedriver.exe\");\n\t", "end": 599, "score": 0.6917993426322937, "start": 595, "tag": "USERNAME", "value": "sher" }, { "context": "operty(\"webdriver.chrome.driver\", \"C:\\\\Users\\\\sherin.raju\\\\chromedriver_win32\\\\chromedriver.exe\");\n\t ", "end": 601, "score": 0.5430665016174316, "start": 599, "tag": "NAME", "value": "in" }, { "context": "erty(\"webdriver.chrome.driver\", \"C:\\\\Users\\\\sherin.raju\\\\chromedriver_win32\\\\chromedriver.exe\");\n\t W", "end": 601, "score": 0.8195222616195679, "start": 601, "tag": "USERNAME", "value": "" }, { "context": "rty(\"webdriver.chrome.driver\", \"C:\\\\Users\\\\sherin.raju\\\\chromedriver_win32\\\\chromedriver.exe\");\n\t WebDr", "end": 606, "score": 0.699428915977478, "start": 602, "tag": "NAME", "value": "raju" } ]
null
[]
package com.test; import java.util.List; import org.openqa.selenium.By; import org.openqa.selenium.Keys; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.interactions.Actions; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import org.testng.Assert; import org.testng.annotations.Test; public class NewTest { @Test public void f() throws InterruptedException { System.setProperty("webdriver.chrome.driver", "C:\\Users\\sherin.raju\\chromedriver_win32\\chromedriver.exe"); WebDriver driver =new ChromeDriver(); driver.get("https://www.cleartrip.com/"); driver.manage().window().maximize(); Thread.sleep(2000); WebElement from = driver.findElement(By.id("FromTag")); // to drag from this //from.sendKeys("h"); //from.sendKeys("y"); //from.sendKeys("d"); Actions act1=new Actions(driver); act1.keyDown(from,Keys.SHIFT).perform(); // for keys to be in caps use keydown for keys to be in small letters act1.sendKeys("h").perform(); Thread.sleep(2000); act1.sendKeys("y").perform(); Thread.sleep(2000); act1.sendKeys("d").perform(); Thread.sleep(5000); act1.sendKeys(Keys.ENTER).perform(); WebElement to = driver.findElement(By.id("ToTag")); // to drop here to.sendKeys("b"); to.sendKeys("a"); to.sendKeys("n"); //Thread.sleep(5000); WebDriverWait wait=new WebDriverWait(driver,10); wait.until(ExpectedConditions.presenceOfNestedElementsLocatedBy(By.id("ui-id-2"),By.className("list")));//to get the count of elements in list WebElement u1=driver.findElement(By.id("ui-id-2")); List<WebElement> list=u1.findElements(By.tagName("li")); // lsit is used e=instead of driver to get list of particular list //Assert.assertEquals(list.size(),10); for(WebElement e:list) // to select the element no matter which position it is present { if(e.getText().contains("HDD")) { e.click(); break; } } Assert.assertTrue(to.getAttribute("value").contains("HDD")); } }
2,161
0.70199
0.685331
62
33.854839
31.355324
145
false
false
0
0
0
0
0
0
1.564516
false
false
11
0127e56d3977e242ac91b835ed5bfeb5c666e8ab
31,155,692,827,105
ce6dcb42f4136de9106fbd7a131e5530236605bb
/Py4J Program/TransactionQueue.java
a0f586ffefe241384dc8e86ea9923ed13b4a3fc8
[]
no_license
tehspyke/Example-Programs
https://github.com/tehspyke/Example-Programs
e61f1f988b5be946e3189c6035f8f7e0a7c5df2f
ec3310e5eff60d14dce11e1bacb34d08f71ffaf5
refs/heads/master
2021-01-22T23:20:31.551000
2017-04-11T03:40:31
2017-04-11T03:40:31
85,626,943
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/*Mike Rozier*/ import java.util.LinkedList; import java.util.List; public class TransactionQueue{ //Instance variable private List<Transaction> TQueue = new LinkedList<Transaction>(); //Operations public void enqueue(Transaction entry){ this.TQueue.add(entry); } public Transaction dequeue(){ return this.TQueue.remove(0); } public int queueLength(){ return this.TQueue.size(); } //Getter public List<Transaction> getTQueue(){ return this.TQueue; } }
UTF-8
Java
505
java
TransactionQueue.java
Java
[ { "context": "/*Mike Rozier*/\r\nimport java.util.LinkedList;\r\nimport java.util", "end": 13, "score": 0.9998776316642761, "start": 2, "tag": "NAME", "value": "Mike Rozier" } ]
null
[]
/*<NAME>*/ import java.util.LinkedList; import java.util.List; public class TransactionQueue{ //Instance variable private List<Transaction> TQueue = new LinkedList<Transaction>(); //Operations public void enqueue(Transaction entry){ this.TQueue.add(entry); } public Transaction dequeue(){ return this.TQueue.remove(0); } public int queueLength(){ return this.TQueue.size(); } //Getter public List<Transaction> getTQueue(){ return this.TQueue; } }
500
0.687129
0.685149
26
17.5
16.277048
66
false
false
0
0
0
0
0
0
1.192308
false
false
11
066ef756ca6f00e5e52696ce89f7ecb9b19595cf
12,275,016,579,486
d2958b7470d0748d39ab18153d6ff3577553fa14
/app/src/main/java/com/example/iterepi/view/store/OrderFragment.java
5e22800f4adbb89cf90d74a5577e9acfb0a78198
[]
no_license
juanchovelezpro/Iterepi
https://github.com/juanchovelezpro/Iterepi
aa5daf1d2e7d156905209ad41d8937f08f6831e6
82d645a6b8b36c465be8e641237ac76ca4b1ecd2
refs/heads/master
2022-09-10T01:37:01.445000
2020-05-28T21:42:28
2020-05-28T21:42:28
250,406,182
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.iterepi.view.store; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.example.iterepi.R; import com.example.iterepi.adapter.OrderIDAdapter; import com.example.iterepi.adapter.SaleIDAdapter; import com.example.iterepi.model.Seller; import com.example.iterepi.model.Transaction; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.Query; import com.google.firebase.database.ValueEventListener; import java.util.ArrayList; import java.util.Map; public class OrderFragment extends Fragment { private View view; private OrderIDAdapter orderItemAdapter; private ArrayList<String> saleIDs; private RecyclerView listOrderRV; private ImageView emptyOrderIV; private TextView emptyOrderTV; @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { view = inflater.inflate(R.layout.fragment_store_order, container, false); listOrderRV = view.findViewById(R.id.listOrderRV); listOrderRV.setLayoutManager(new LinearLayoutManager(getContext())); emptyOrderIV = view.findViewById(R.id.emptyOrder); emptyOrderTV = view.findViewById(R.id.emptyOrderTV); emptyOrderIV.setVisibility(View.GONE); emptyOrderTV.setVisibility(View.GONE); saleIDs = new ArrayList<>(); Query query= FirebaseDatabase.getInstance().getReference().child("sellers").child(FirebaseAuth.getInstance().getCurrentUser().getUid()); query.addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { Seller s = dataSnapshot.getValue(Seller.class); loadItems(s); } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); return view; } private void loadItems(Seller s) { if(s!=null){ if(s.getSalesID()!=null){ Log.e(">>>","Id de su primer venta"+s.getSalesID()); if(s.getSalesID().size()>0){ emptyOrderIV.setVisibility(View.GONE); emptyOrderTV.setVisibility(View.GONE); for(Map.Entry<String,String> entry : s.getSalesID().entrySet()){ Query query = FirebaseDatabase.getInstance().getReference().child("transactions").child(entry.getValue()); query.addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { Transaction state = dataSnapshot.getValue(Transaction.class); if(!state.getState().equals(Transaction.TO_DELIVER)){ String i = entry.getValue(); saleIDs.add(i); orderItemAdapter = new OrderIDAdapter(saleIDs); listOrderRV.setAdapter(orderItemAdapter); } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); } }else{ emptyOrderTV.setVisibility(View.VISIBLE); emptyOrderIV.setVisibility(View.VISIBLE); } }else{ emptyOrderTV.setVisibility(View.VISIBLE); emptyOrderIV.setVisibility(View.VISIBLE); } }else{ Log.e(">>>","Error: No Sale in SellFragment"); } } }
UTF-8
Java
4,435
java
OrderFragment.java
Java
[]
null
[]
package com.example.iterepi.view.store; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.example.iterepi.R; import com.example.iterepi.adapter.OrderIDAdapter; import com.example.iterepi.adapter.SaleIDAdapter; import com.example.iterepi.model.Seller; import com.example.iterepi.model.Transaction; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.Query; import com.google.firebase.database.ValueEventListener; import java.util.ArrayList; import java.util.Map; public class OrderFragment extends Fragment { private View view; private OrderIDAdapter orderItemAdapter; private ArrayList<String> saleIDs; private RecyclerView listOrderRV; private ImageView emptyOrderIV; private TextView emptyOrderTV; @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { view = inflater.inflate(R.layout.fragment_store_order, container, false); listOrderRV = view.findViewById(R.id.listOrderRV); listOrderRV.setLayoutManager(new LinearLayoutManager(getContext())); emptyOrderIV = view.findViewById(R.id.emptyOrder); emptyOrderTV = view.findViewById(R.id.emptyOrderTV); emptyOrderIV.setVisibility(View.GONE); emptyOrderTV.setVisibility(View.GONE); saleIDs = new ArrayList<>(); Query query= FirebaseDatabase.getInstance().getReference().child("sellers").child(FirebaseAuth.getInstance().getCurrentUser().getUid()); query.addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { Seller s = dataSnapshot.getValue(Seller.class); loadItems(s); } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); return view; } private void loadItems(Seller s) { if(s!=null){ if(s.getSalesID()!=null){ Log.e(">>>","Id de su primer venta"+s.getSalesID()); if(s.getSalesID().size()>0){ emptyOrderIV.setVisibility(View.GONE); emptyOrderTV.setVisibility(View.GONE); for(Map.Entry<String,String> entry : s.getSalesID().entrySet()){ Query query = FirebaseDatabase.getInstance().getReference().child("transactions").child(entry.getValue()); query.addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { Transaction state = dataSnapshot.getValue(Transaction.class); if(!state.getState().equals(Transaction.TO_DELIVER)){ String i = entry.getValue(); saleIDs.add(i); orderItemAdapter = new OrderIDAdapter(saleIDs); listOrderRV.setAdapter(orderItemAdapter); } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); } }else{ emptyOrderTV.setVisibility(View.VISIBLE); emptyOrderIV.setVisibility(View.VISIBLE); } }else{ emptyOrderTV.setVisibility(View.VISIBLE); emptyOrderIV.setVisibility(View.VISIBLE); } }else{ Log.e(">>>","Error: No Sale in SellFragment"); } } }
4,435
0.619166
0.61894
127
33.921261
30.775183
144
false
false
0
0
0
0
0
0
0.527559
false
false
11
d4ca7aa99bff61d17a4c1887b84f38723a4a096e
13,718,125,562,607
73f8303875ec23cbbf9f6a57d8e266043ed7bd3b
/GraduateStudent.java
1924cce87363a9f194d7c6143ccd7dd98473d9e6
[]
no_license
erich-m/project-update
https://github.com/erich-m/project-update
0c85e401d63707957232f6f8c3639fe8ad8d8d67
4680b3408f6f89e766a78c0599dc58f126928f47
refs/heads/main
2023-03-28T17:09:20.907000
2021-03-20T21:49:27
2021-03-20T21:49:27
349,834,863
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/*Author: Erich MacLean CIS2430*0209 Lab Exercise 5 file: Lab5.java GUI designed to implement all previous functions*/ package Lab5; class GraduateStudent extends Student{ private String supervisor; private boolean isPhD; private String undergraduateSchool; public GraduateStudent (String program, int yearIn,String lName,double averageIn,String supervisorIn,int phd,String school) throws Exception{//throw any exceptions in the method and catch them in the main super(program,yearIn,lName,averageIn);//call the student constructor to create a graduate student intance this.supervisor = supervisorIn; if(phd == 0){//set phd status to false if int is 0, and status to true if int is 1 this.isPhD = false; }else if(phd == 1){ this.isPhD = true; }else{//throw an error if neither 1 or 0 throw new Exception("ERROR: PhD should be either 1 (PhD) or 0 (Masters)"); } this.undergraduateSchool = school; } @Override public String toString (int printText){//print text signals the desitination of the concatenatedd string String printOut = ""; if(printText != 2){ printOut = super.program + " " + super.year + " " + super.average; if(printText == 1 && this.isPhD){//print the text version of the phd status printOut += " " + this.supervisor + " PhD " + this.undergraduateSchool; }else if(printText == 1 && !this.isPhD){ printOut += " " + this.supervisor + " Masters " + this.undergraduateSchool; } if(printText == 0 && this.isPhD){//print the number version of the phd status printOut += " " + this.supervisor + " 1 " + this.undergraduateSchool; }else if(printText == 0 && !this.isPhD){ printOut += " " + this.supervisor + " 0 " + this.undergraduateSchool; } printOut += " " + this.lastName; }else{ printOut = super.toString(printText);//if the printText is equal to 2, concat only the program name, year, and last name } return printOut; } }
UTF-8
Java
1,927
java
GraduateStudent.java
Java
[ { "context": "/*Author: Erich MacLean\nCIS2430*0209\nLab Exercise 5\nfile: Lab5.java\nGUI d", "end": 23, "score": 0.999872624874115, "start": 10, "tag": "NAME", "value": "Erich MacLean" } ]
null
[]
/*Author: <NAME> CIS2430*0209 Lab Exercise 5 file: Lab5.java GUI designed to implement all previous functions*/ package Lab5; class GraduateStudent extends Student{ private String supervisor; private boolean isPhD; private String undergraduateSchool; public GraduateStudent (String program, int yearIn,String lName,double averageIn,String supervisorIn,int phd,String school) throws Exception{//throw any exceptions in the method and catch them in the main super(program,yearIn,lName,averageIn);//call the student constructor to create a graduate student intance this.supervisor = supervisorIn; if(phd == 0){//set phd status to false if int is 0, and status to true if int is 1 this.isPhD = false; }else if(phd == 1){ this.isPhD = true; }else{//throw an error if neither 1 or 0 throw new Exception("ERROR: PhD should be either 1 (PhD) or 0 (Masters)"); } this.undergraduateSchool = school; } @Override public String toString (int printText){//print text signals the desitination of the concatenatedd string String printOut = ""; if(printText != 2){ printOut = super.program + " " + super.year + " " + super.average; if(printText == 1 && this.isPhD){//print the text version of the phd status printOut += " " + this.supervisor + " PhD " + this.undergraduateSchool; }else if(printText == 1 && !this.isPhD){ printOut += " " + this.supervisor + " Masters " + this.undergraduateSchool; } if(printText == 0 && this.isPhD){//print the number version of the phd status printOut += " " + this.supervisor + " 1 " + this.undergraduateSchool; }else if(printText == 0 && !this.isPhD){ printOut += " " + this.supervisor + " 0 " + this.undergraduateSchool; } printOut += " " + this.lastName; }else{ printOut = super.toString(printText);//if the printText is equal to 2, concat only the program name, year, and last name } return printOut; } }
1,920
0.699014
0.685003
51
36.803921
40.348007
205
false
false
0
0
0
0
0
0
2.333333
false
false
11
1905cb2d74a0c9ade1960de94cbb1c52b7e7b4d5
8,272,107,028,969
fd64ddc07e029db3e8ac88d27e56ecb0fd69f906
/rongyitui/src/main/java/com/rongyitui/dao/IOfficialTaskkDao.java
ca3bd91d5264223156357921e5e1855d197d730b
[]
no_license
LiuJun0108/rongyitui
https://github.com/LiuJun0108/rongyitui
f0c4f4d18bf35be316cbb6db78875b5ccf613187
bfbf84c3b1ff163835e2ae882d70fce7076d0e1f
refs/heads/master
2020-05-21T11:40:49.314000
2015-07-01T15:59:38
2015-07-01T15:59:38
38,303,080
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.rongyitui.dao; import com.rongyitui.po.OfficialTask; public interface IOfficialTaskkDao extends IBaseDao<OfficialTask, Integer> { }
UTF-8
Java
154
java
IOfficialTaskkDao.java
Java
[]
null
[]
package com.rongyitui.dao; import com.rongyitui.po.OfficialTask; public interface IOfficialTaskkDao extends IBaseDao<OfficialTask, Integer> { }
154
0.779221
0.779221
7
20
26.784857
76
false
false
0
0
0
0
0
0
0.428571
false
false
11
9d880e93a76c333c6d104b8d6789debc07e5891e
30,588,757,114,944
49bb57a11208a43a44840104bcda3d3ed6e116f5
/app/src/main/java/com/guozhe/android/rxandroidbasic03/MainActivity.java
e2f9eaa5d6c2c60cbe096704a2c0c24f19474209
[]
no_license
guozhe0517/RxAndroidBasic03
https://github.com/guozhe0517/RxAndroidBasic03
584d2f6277ef011e7314cde49768f2931540986c
06d4c3a08525b317ee9d89f549edbea81bc30b03
refs/heads/master
2021-01-01T15:46:35.993000
2017-07-19T09:19:59
2017-07-19T09:19:59
97,697,266
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.guozhe.android.rxandroidbasic03; import android.content.Context; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import java.text.DateFormatSymbols; import java.util.ArrayList; import java.util.List; import io.reactivex.Observable; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.schedulers.Schedulers; public class MainActivity extends AppCompatActivity { private RecyclerView recyclerView; RecyclerAdapter adapter; Observable<String> observable; List<String> data = new ArrayList<>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initView(); adapter = new RecyclerAdapter(this, data); recyclerView.setAdapter(adapter); recyclerView.setLayoutManager(new LinearLayoutManager(this)); // 캘린더에서 1월~ 12월까지 텍스트를 추출 DateFormatSymbols dfs = new DateFormatSymbols(); String[] months = dfs.getMonths(); observable = Observable.create(emitter -> { for(String month : months){ emitter.onNext(month); Thread.sleep(1000); } emitter.onComplete(); }); } public void async(View view) { observable .subscribeOn(Schedulers.io()) // 옵저버블의 thread 를 지정 .observeOn(AndroidSchedulers.mainThread()) // 옵저버의 thread를 지정 .subscribe( str -> { data.add(str); // adapter.notifyItemChanged(포지션); // 변경된 데이터만 갱신해준다 adapter.notifyItemInserted(data.size()-1); // 추가된 데이터만 갱신해준다 }, // onNext error -> Log.e("Error",error.getMessage()), // onError () -> { // onComplete data.add("complete!"); adapter.notifyItemInserted(data.size()-1); } ); } private void initView() { recyclerView = (RecyclerView) findViewById(R.id.recyclerView); } } class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.Holder> { LayoutInflater inflater = null; List<String> data = null; public RecyclerAdapter(Context context, List<String> data){ inflater = LayoutInflater.from(context); this.data = data; } @Override public Holder onCreateViewHolder(ViewGroup parent, int viewType) { View view = inflater.inflate(android.R.layout.simple_list_item_1, parent, false); return new Holder(view); } @Override public void onBindViewHolder(Holder holder, int position) { Log.i("Refresh","~~~~~~~~~~~~~~~~~position="+position); holder.textView.setText(data.get(position)); } @Override public int getItemCount() { return data.size(); } class Holder extends RecyclerView.ViewHolder { TextView textView; public Holder(View itemView) { super(itemView); textView = (TextView) itemView.findViewById(android.R.id.text1); } } } //class CustomAdapter extends BaseAdapter { // // LayoutInflater inflater = null; // List<String> data = null; // // public CustomAdapter(Context context, List<String> data){ // inflater = LayoutInflater.from(context); // this.data = data; // } // // @Override // public int getCount() { // return data.size(); // } // // @Override // public Object getItem(int position) { // return data.get(position); // } // // @Override // public long getItemId(int position) { // return position; // } // // private int lastPosition = 7; // @Override // public View getView(int position, View convertView, ViewGroup parent) { // // if(position > lastPosition){ // // 아래 동작... // }else{ // return convertView; // } // // if(convertView == null) // convertView = inflater.inflate(android.R.layout.simple_list_item_1, parent, false); // // TextView textView = (TextView) convertView.findViewById(android.R.id.text1); // textView.setText(data.get(position)); // // Log.i("Refresh","~~~~~~~~~~~~~~~~~position="+position); // // return convertView; // } // // @Override // public boolean hasStableIds() { // return true; // } //}
UTF-8
Java
5,004
java
MainActivity.java
Java
[]
null
[]
package com.guozhe.android.rxandroidbasic03; import android.content.Context; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import java.text.DateFormatSymbols; import java.util.ArrayList; import java.util.List; import io.reactivex.Observable; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.schedulers.Schedulers; public class MainActivity extends AppCompatActivity { private RecyclerView recyclerView; RecyclerAdapter adapter; Observable<String> observable; List<String> data = new ArrayList<>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initView(); adapter = new RecyclerAdapter(this, data); recyclerView.setAdapter(adapter); recyclerView.setLayoutManager(new LinearLayoutManager(this)); // 캘린더에서 1월~ 12월까지 텍스트를 추출 DateFormatSymbols dfs = new DateFormatSymbols(); String[] months = dfs.getMonths(); observable = Observable.create(emitter -> { for(String month : months){ emitter.onNext(month); Thread.sleep(1000); } emitter.onComplete(); }); } public void async(View view) { observable .subscribeOn(Schedulers.io()) // 옵저버블의 thread 를 지정 .observeOn(AndroidSchedulers.mainThread()) // 옵저버의 thread를 지정 .subscribe( str -> { data.add(str); // adapter.notifyItemChanged(포지션); // 변경된 데이터만 갱신해준다 adapter.notifyItemInserted(data.size()-1); // 추가된 데이터만 갱신해준다 }, // onNext error -> Log.e("Error",error.getMessage()), // onError () -> { // onComplete data.add("complete!"); adapter.notifyItemInserted(data.size()-1); } ); } private void initView() { recyclerView = (RecyclerView) findViewById(R.id.recyclerView); } } class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.Holder> { LayoutInflater inflater = null; List<String> data = null; public RecyclerAdapter(Context context, List<String> data){ inflater = LayoutInflater.from(context); this.data = data; } @Override public Holder onCreateViewHolder(ViewGroup parent, int viewType) { View view = inflater.inflate(android.R.layout.simple_list_item_1, parent, false); return new Holder(view); } @Override public void onBindViewHolder(Holder holder, int position) { Log.i("Refresh","~~~~~~~~~~~~~~~~~position="+position); holder.textView.setText(data.get(position)); } @Override public int getItemCount() { return data.size(); } class Holder extends RecyclerView.ViewHolder { TextView textView; public Holder(View itemView) { super(itemView); textView = (TextView) itemView.findViewById(android.R.id.text1); } } } //class CustomAdapter extends BaseAdapter { // // LayoutInflater inflater = null; // List<String> data = null; // // public CustomAdapter(Context context, List<String> data){ // inflater = LayoutInflater.from(context); // this.data = data; // } // // @Override // public int getCount() { // return data.size(); // } // // @Override // public Object getItem(int position) { // return data.get(position); // } // // @Override // public long getItemId(int position) { // return position; // } // // private int lastPosition = 7; // @Override // public View getView(int position, View convertView, ViewGroup parent) { // // if(position > lastPosition){ // // 아래 동작... // }else{ // return convertView; // } // // if(convertView == null) // convertView = inflater.inflate(android.R.layout.simple_list_item_1, parent, false); // // TextView textView = (TextView) convertView.findViewById(android.R.id.text1); // textView.setText(data.get(position)); // // Log.i("Refresh","~~~~~~~~~~~~~~~~~position="+position); // // return convertView; // } // // @Override // public boolean hasStableIds() { // return true; // } //}
5,004
0.590127
0.586235
161
29.322981
24.63084
97
false
false
0
0
0
0
0
0
0.515528
false
false
11
21ba8c94a83d502d5ca153d4c4d6277eb362672c
15,324,443,319,127
86b0d1471f3a3df1e9929106a2be840c52988056
/kafka/src/main/java/com/pkt/kafka/lab4/advanced/producer/StockAppConstants.java
c5ac262a08a6b1fc8564c73f01b97c0d7a0d9335
[]
no_license
pkumarth/merck-code
https://github.com/pkumarth/merck-code
b8bcac2ecffc64ff3f5fe0ddfdf8686d671c036f
ceb0af690115dfe59f57da449694d81137b0049a
refs/heads/master
2020-05-09T22:55:53.296000
2019-04-15T13:01:59
2019-04-15T13:01:59
181,486,957
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.pkt.kafka.lab4.advanced.producer; public class StockAppConstants { public final static String TOPIC = "stock-prices"; public final static String BOOTSTRAP_SERVERS = "localhost:9092,localhost:9093,localhost:9094"; }
UTF-8
Java
230
java
StockAppConstants.java
Java
[]
null
[]
package com.pkt.kafka.lab4.advanced.producer; public class StockAppConstants { public final static String TOPIC = "stock-prices"; public final static String BOOTSTRAP_SERVERS = "localhost:9092,localhost:9093,localhost:9094"; }
230
0.795652
0.73913
6
37.333332
32.437977
95
false
false
0
0
0
0
0
0
1.166667
false
false
11
21eeb25508546c45758828ebec1465db63bd972b
25,116,968,796,704
9abb47176d86e51c1242ceaa8d98ebbb2f16e1f9
/app/src/main/java/com/luoruiyong/caa/bean/ImageBean.java
b49add430efbd2153e06a1a593d20343379348e6
[ "Apache-2.0" ]
permissive
linstick/CAA
https://github.com/linstick/CAA
b91e6c995b50fe037772101fc9a712338e0e7055
f05cb20d958b64fe52b81bb2d4aa6d82b601539b
refs/heads/master
2020-04-27T05:36:10.787000
2019-05-27T12:40:30
2019-05-27T12:40:30
174,084,831
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.luoruiyong.caa.bean; import android.net.Uri; import java.io.File; import java.util.ArrayList; import java.util.List; /** * Author: luoruiyong * Date: 2019/4/15/015 * Description: **/ public class ImageBean { public final static int TYPE_RESOURCE_ID = 0; public final static int TYPE_LOCAL_FILE = 1; public final static int TYPE_REMOTE_FILE = 2; private int type; private String path; private String url; private int resId; public ImageBean() { } public ImageBean(String url) { this.type = TYPE_REMOTE_FILE; this.url = url; } public int getType() { return type; } public void setType(int type) { this.type = type; } public String getPath() { return path; } public void setPath(String path) { this.path = path; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public int getResId() { return resId; } public void setResId(int resId) { this.resId = resId; } @Override public String toString() { if (type == TYPE_RESOURCE_ID) { return String.valueOf(resId); } if (type == TYPE_LOCAL_FILE) { return path; } if (type == TYPE_REMOTE_FILE) { return url; } return null; } public static List<String> toStringList(List<ImageBean> list) { if (list == null) { return null; } List<String> result = new ArrayList<>(); for (ImageBean bean : list) { result.add(bean.toString()); } return result; } }
UTF-8
Java
1,730
java
ImageBean.java
Java
[ { "context": ".ArrayList;\nimport java.util.List;\n\n/**\n * Author: luoruiyong\n * Date: 2019/4/15/015\n * Description:\n **/\npubli", "end": 157, "score": 0.9997029304504395, "start": 147, "tag": "USERNAME", "value": "luoruiyong" } ]
null
[]
package com.luoruiyong.caa.bean; import android.net.Uri; import java.io.File; import java.util.ArrayList; import java.util.List; /** * Author: luoruiyong * Date: 2019/4/15/015 * Description: **/ public class ImageBean { public final static int TYPE_RESOURCE_ID = 0; public final static int TYPE_LOCAL_FILE = 1; public final static int TYPE_REMOTE_FILE = 2; private int type; private String path; private String url; private int resId; public ImageBean() { } public ImageBean(String url) { this.type = TYPE_REMOTE_FILE; this.url = url; } public int getType() { return type; } public void setType(int type) { this.type = type; } public String getPath() { return path; } public void setPath(String path) { this.path = path; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public int getResId() { return resId; } public void setResId(int resId) { this.resId = resId; } @Override public String toString() { if (type == TYPE_RESOURCE_ID) { return String.valueOf(resId); } if (type == TYPE_LOCAL_FILE) { return path; } if (type == TYPE_REMOTE_FILE) { return url; } return null; } public static List<String> toStringList(List<ImageBean> list) { if (list == null) { return null; } List<String> result = new ArrayList<>(); for (ImageBean bean : list) { result.add(bean.toString()); } return result; } }
1,730
0.550867
0.543353
89
18.438202
15.323445
67
false
false
0
0
0
0
0
0
0.337079
false
false
11
9bf8129d1f71bfe6143e60e1f10e136142cca9cd
25,013,889,602,819
3247f2bf3183918a0fbc5d908602f057d9c7869a
/src/sample/SearchController.java
149805d96b06831dad861105ee34aec6211d4226
[]
no_license
natekirsch/database_project
https://github.com/natekirsch/database_project
12f3ba8172598a67c95f2e9774dad9cc2c763c5a
15ef1ab01581c262b8e298eaec9d80c6ff557e86
refs/heads/master
2023-02-01T01:10:45.959000
2020-12-19T09:37:39
2020-12-19T09:37:39
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package sample; /** * This is the primary instance of the application. This screen is presented after logging in, and acts * as the primary hub for all application functionality. */ import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.*; import javafx.scene.control.cell.PropertyValueFactory; import javafx.scene.layout.GridPane; import javafx.stage.Stage; import java.sql.*; import java.util.ArrayList; import java.util.List; public class SearchController { private static Stage window; private int MIN_YEAR = 1965; private int MAX_YEAR = 2015; public Button edit_countries_btn; public Button del_selected_btn; public Button view_editors_btn; public TextField country_search_name; public TextField initial_year; public TextField final_year; public Button select_att_btn; public Label atts_label; public ScrollPane results_pane; public GridPane container; // List for tracking all of the selected Country/Years public List<Country> compared = new ArrayList<>(); // List for determining which items are selected soley on the current search public List<Country> selected; // List of search attributes based on the Attribute Selector private final List<String> search_atts = new ArrayList<>(); /** * Initialize Search Screen and it's associated buttons and items * * @param editor_val */ public void initialize(Boolean editor_val) { try { window = new Stage(); Parent loader = FXMLLoader.load(getClass().getResource("Search.fxml")); Scene search_scene = new Scene(loader, 1000, 900); window.setScene(search_scene); Main.stage_settings(window); initItems(); // Based on the editor_val calulcated when logging in, if the user is not an editor // then remove the following buttons from their display if (!editor_val) { edit_countries_btn.setVisible(false); del_selected_btn.setVisible(false); view_editors_btn.setVisible(false); } window.show(); } catch (Exception e) { e.printStackTrace(); } } /** * Initialize the items on screen to be accessed programmatically */ private void initItems() { edit_countries_btn = (Button) window.getScene().lookup("#edit_countries_btn"); del_selected_btn = (Button) window.getScene().lookup("#del_selected_btn"); view_editors_btn = (Button) window.getScene().lookup("#view_editors_btn"); country_search_name = (TextField) window.getScene().lookup("country_search_name"); initial_year = (TextField) window.getScene().lookup("#initial_year"); final_year = (TextField) window.getScene().lookup("#final_year"); results_pane = (ScrollPane) window.getScene().lookup("#results_pane"); results_pane.setVisible(false); container = (GridPane) window.getScene().lookup("#container"); // Set the min/max years as default search parameters initial_year.setText(MIN_YEAR + ""); final_year.setText(MAX_YEAR + ""); // Clean out the compare table so no data carries over from last application runs cleanCompare(); } /** * cleanCompare deletes everything from the compare table, so that all data added to it are only from * the current app instance */ private void cleanCompare() { String[] creds = GetSQLInfo.getCredentials(); String usr = creds[0]; String pwd = creds[1]; String url = GetSQLInfo.getUrlConnect(); try (Connection cn = DriverManager.getConnection(url, usr, pwd)) { String q = "DELETE FROM compare"; PreparedStatement p_stmt = cn.prepareStatement(q); int ret = p_stmt.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } } // this function is called when the user presses the edit countries button and loads the new window public void editCountries(){ try { FXMLLoader fxmlLoader = new FXMLLoader(); fxmlLoader.setLocation(getClass().getResource("Edit.fxml")); Scene scene = new Scene(fxmlLoader.load(), 600, 400); Stage stage = new Stage(); stage.setTitle("Edit Country"); stage.setScene(scene); stage.show(); } catch (Exception e){ e.printStackTrace(); } } /** * Opens the Attribute Selector Screen so the user can select what attributes to search with their countries */ public void selectAtts() { AttSelectController asc = new AttSelectController(); asc.initialize(search_atts, this); } /** * store Selected gets called from the Attribute Selector as a signal to update the Search Screen to display * the attributes that the user has selected */ public void storeSelected() { // Check if no attributes are selected. Default to searching all attributes if (search_atts.size() < 1) { atts_label.setText("All Attributes (Default)"); } else { // Create a String based on selected attributes to display on screen String search = ""; for (String att : search_atts) { search = search.concat(att); if (search_atts.indexOf(att) != (search_atts.size() - 1)) { search = search.concat(", "); } } atts_label.setText(search); } } /** * Activates when the user presses search button. Performs a vast number of operations to display the * get, and display the results to a table */ public void performSearch() { //Create a new instance of the selected List for every search, as we don't want to delete any items // from a previous search selected = new ArrayList<>(); // The table that we are going to populate TableView<Country> table_view = new TableView<>(); table_view.setMaxHeight(450); // Get the search parameters that the user entered String country = country_search_name.getText(); String init_year = initial_year.getText(); String fin_year = final_year.getText(); // Validate that the entered information is legal boolean ret = validateSearch(country, init_year, fin_year); if (ret) { // Create the query to search. We must create the select clause dynamically // attToSQL is called to convert the List of attribute IDs selected into the appropriate column names String sql_select = attToSQL(); String q = "SELECT " + sql_select + " FROM country c" + " JOIN country_population cp USING (year, abbr)" + " JOIN economy e USING (year, abbr)" + " WHERE c.year >= " + init_year + " AND c.year <= " + fin_year + " AND c.country_name = ?" + " ORDER BY year ASC;"; // The query, table, and country the user entered are passed to create the table getStoreData(q, country, table_view); // The completed table is placed inside the hidden ScrollPane and displayed Parent root = table_view; results_pane.setContent(root); results_pane.setVisible(true); } } /** * getStoreData retrieves searched data from the database and stores it to the table that is displayed on screen * * @param q the query string is passed in missing only the country name to search using prepared statements * @param search_country the country the user wants to search for is passed in to be placed in a prepared statement * @param table_view the table we will be populating with data found */ public void getStoreData(String q, String search_country, TableView<Country> table_view) { String[] creds = GetSQLInfo.getCredentials(); String usr = creds[0]; String pwd = creds[1]; String url = GetSQLInfo.getUrlConnect(); try (Connection cn = DriverManager.getConnection(url, usr, pwd)) { PreparedStatement p_stmt = cn.prepareStatement(q); p_stmt.setString(1, search_country); ResultSet rs = p_stmt.executeQuery(); ResultSetMetaData rsmd = rs.getMetaData(); int cols = rsmd.getColumnCount(); // Boolean flag is used to determine if the user is searching for a specific attribute or not // This is needed because otherwise the table will try to read data from columns that don't exist // in the query boolean flag = false; // A list of countries is created to represent every row of the query ArrayList<Country> data = new ArrayList<>(); while (rs.next()) { Country country = new Country(); // year, abbr, and country_name will always be searched by default CheckBox cb = new CheckBox(); country.setSelect(cb); country.year.set(rs.getInt("year")); country.abbr.set(rs.getString("abbr")); country.country_name.set(rs.getString("country_name")); // We need to check if any countries has been previously selected for comparison // or has been saved to the compare table. If so, mark the checkbox as selected if (checkCompare(country)) { country.select.setSelected(true); selected.add(country); } cb.selectedProperty().addListener(new ChangeListener<Boolean>() { /** * Checkbox is given a state change listener. When the country/year is selected (checked) * we want that info to be sent and stored in the compare table so it is remembered through * searches. If it is unchecked, then we need to remove that info from the compare table * * @param observable Not used * @param oldValue the value that the checkbox was * @param newValue the value that the checkbox now is */ @Override public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) { String[] creds = GetSQLInfo.getCredentials(); String usr = creds[0]; String pwd = creds[1]; String url = GetSQLInfo.getUrlConnect(); try (Connection cn = DriverManager.getConnection(url, usr, pwd)) { // The way that this listener was implemented is by far not the most efficient, // nor the best way to do this task. I would have liked to make the program run faster // and less expensively by not adding removing everytime the checkbox is checked/unchecked // but I simply didn't have time. // In the code below I believe I tried to go for two different approaches unnecessarily if (newValue) { //The check box is selected if (!compared.contains(country)) { compared.add(country); addToCompare(country, cn); selected.add(country); } } else { // The checkbox is not selected if (compared.contains(country)) { compared.remove(country); removeFromCompare(country, cn); selected.remove(country); } } } catch (SQLException throwables) { throwables.printStackTrace(); } } }); /** * Check all of the optional attributes to ensure we don't try to read non-existent data */ // Check if most_populous_city is being searched for for (int i = 1; i < cols; i++) if (rsmd.getColumnName(i).equals("most_populous_city")) flag = true; if (flag) country.most_populous_city.set(rs.getString("most_populous_city")); else country.most_populous_city.set("N/A"); // Check if capital is being searched for flag = false; for (int i = 1; i < cols; i++) if (rsmd.getColumnName(i).equals("capital")) flag = true; if (flag) country.capital.set(rs.getString("capital")); else country.capital.set("N/A"); // Check if land_mass is being searched for flag = false; for (int i = 1; i < cols; i++) if (rsmd.getColumnName(i).equals("land_mass")) flag = true; if (flag) country.land_mass.set(rs.getInt("land_mass")); else country.land_mass.set(0); // Check if pop_size is being searched for flag = false; for (int i = 1; i < cols; i++) if (rsmd.getColumnName(i).equals("pop_size")) flag = true; if (flag) country.pop_size.set(rs.getInt("pop_size")); else country.pop_size.set(0); // Check if country_language is being searched for flag = false; for (int i = 1; i < cols; i++) if (rsmd.getColumnName(i).equals("country_language")) flag = true; if (flag) country.country_language.set(rs.getString("country_language")); else country.country_language.set("N/A"); // Check if pop_density is being searched for flag = false; for (int i = 1; i < cols; i++) if (rsmd.getColumnName(i).equals("pop_density")) flag = true; if (flag) country.pop_density.set(rs.getFloat("pop_density")); else country.pop_density.set(0); // Check if gdp is being searched for flag = false; for (int i = 1; i < cols; i++) if (rsmd.getColumnName(i).equals("gdp")) flag = true; if (flag) country.gdp.set(rs.getFloat("gdp")); else country.gdp.set(0); // Check if currency is being searched for flag = false; for (int i = 1; i < cols; i++) if (rsmd.getColumnName(i).equals("currency")) flag = true; if (flag) country.currency.set(rs.getString("currency")); else country.currency.set("N/A"); // Check if power_consumption_per_capita is being searched for flag = false; for (int i = 1; i < cols; i++) if (rsmd.getColumnName(i).equals("power_consumption_per_capita")) flag = true; if (flag) country.power_consumption_per_capita.set(rs.getFloat("power_consumption_per_capita")); else country.power_consumption_per_capita.set(0); // Check if passenger_air_transport is being searched for flag = false; for (int i = 1; i < cols; i++) if (rsmd.getColumnName(i).equals("passenger_air_transport")) flag = true; if (flag) country.passenger_air_transport.set(rs.getInt("passenger_air_transport")); else country.passenger_air_transport.set(0); // After all data vaules are set, then the country is added to the list of rows (Countries) data.add(country); } //the country list is converted into an ObservableList ObservableList dbData = FXCollections.observableArrayList(data); // The checkbox column is created individually since it is not part of the query results TableColumn check_col = new TableColumn<>(); check_col.setText("Selected"); check_col.setCellValueFactory(new PropertyValueFactory<>("select")); // Column is added to the table table_view.getColumns().add(check_col); // Give columns readable names for (int i = 0; i < rs.getMetaData().getColumnCount(); i++) { TableColumn col = new TableColumn<>(); switch (rs.getMetaData().getColumnName(i+1)) { case "year": col.setText("Year"); break; case "abbr": col.setText("Abbr"); break; case "country_name": col.setText("Country Name"); break; case "most_populous_city": col.setText("Most Pop. City"); break; case "capital": col.setText("Capital"); break; case "land_mass": col.setText("Land Mass"); break; case "pop_size": col.setText("Pop. Size"); break; case "country_language": col.setText("Language"); break; case "pop_density": col.setText("pop. Density"); break; case "gdp": col.setText("GDP"); break; case "currency": col.setText("Currency"); break; case "power_consumption_per_capita": col.setText("Power Cons. Capita"); break; case "passenger_air_transport": col.setText("Passenger Air Trans."); break; default: col.setText(rs.getMetaData().getColumnName(i+1)); break; } // Set the tag of each column and then add to table col.setCellValueFactory(new PropertyValueFactory<>(rs.getMetaData().getColumnName(i+1))); table_view.getColumns().add(col); } // Fill table_view with the columns table_view.setItems(dbData); } catch (Exception e) { e.printStackTrace(); } } /** * Converts the global list of attributes into a String of the associated attribute column names * * @return string of every column name being selected to be added to the main SELECT query */ public String attToSQL() { // If the user selected no attributes, we will search for every attribute if (search_atts.size() < 1) { return "*"; } // The SELECT clause always searches for these 3 attributes withour exception String sql_select = "c.year, c.abbr, c.country_name, "; for (int i = 0; i < search_atts.size(); i++) { String tmp = search_atts.get(i); String title = GetSQLInfo.idToTitle(tmp); sql_select = sql_select.concat(title); if (search_atts.indexOf(tmp) != (search_atts.size() - 1)) { sql_select = sql_select.concat(", "); } } return sql_select; } /** * Simple validator to check that the input the user has entered is valid and searchable. Checks that * - Dates are sequentially in order * - Dates do not exceed the max year or the min year * - The country named is only alphabetic * If one of the conditions fails, a PopUp appears informing of the error * * @param co the country name to search * @param iy the initial year * @param fy the final year * @return boolean on if the search is legal or not */ private boolean validateSearch(String co, String iy, String fy) { if (iy.isEmpty()) { PopUp.init_error("INVALID ENTRY:\nMissing initial year"); return false; } if (fy.isEmpty()) { PopUp.init_error("INVALID ENTRY:\nMissing final year"); return false; } if (co.isEmpty()) { PopUp.init_error("INVALID ENTRY:\nMissing Country to search"); return false; } if (iy.matches("[0-9]+") && fy.matches("[0-9]+")) { int intIY = Integer.parseInt(iy); int intFY = Integer.parseInt(fy); if (intFY - intIY < 0) { PopUp.init_error("INVALID ENTRY:\nFinal year cannot be earlier than initial year"); return false; } if (intFY > MAX_YEAR) { PopUp.init_error("INVALID ENTRY:\nFinal year cannot be greater than " + MAX_YEAR); return false; } if (intIY < MIN_YEAR) { PopUp.init_error("INVALID ENTRY:\nInitial year cannot be less than " + MIN_YEAR); return false; } if (co.matches("[a-zA-Z ]+")) { return true; } } return false; } /** * Incomplete method to display a table of every country stored to the compare table */ public void compareSelected() { System.out.println("Creating Table of compared countries"); } // this function executes when the user presses the edit editors button and calls the editors window public void showEditors() { try { FXMLLoader fxmlLoader = new FXMLLoader(); fxmlLoader.setLocation(getClass().getResource("editors.fxml")); Scene scene = new Scene(fxmlLoader.load(), 500, 300); Stage stage = new Stage(); stage.setTitle("Edit Editors"); stage.setScene(scene); stage.show(); } catch (Exception e){ e.printStackTrace(); } } /** * If a country is selected to compare, it must be added to the compare table to be remembered * * @param country the Country object being selected * @param cn the connection to the database */ public void addToCompare(Country country, Connection cn) { int year = country.year.getValue(); String abbr = country.abbr.getValue(); String cname = country.country_name.getValue(); String mpc = country.most_populous_city.getValue(); String cap = country.capital.getValue(); int ldms = country.land_mass.getValue(); int psz = country.pop_size.getValue(); String lng = country.country_language.getValue(); float pden = country.pop_density.floatValue(); float gdp = country.gdp.floatValue(); String cur = country.currency.getValue(); float pcc = country.power_consumption_per_capita.floatValue(); int pat = country.passenger_air_transport.getValue(); /** Using this method was giving me errors, so I switch back to inserting manually String q = "INSERT INTO compare VALUES (" + year + ", ?, ?, ?, ?, " + ldms + ", " + psz + ", ?, " + pden + ", " + gdp + ", ?, " + pcc + ", " + pat + ");"; **/ String q = "INSERT INTO compare VALUES ("+ year + ", '" + abbr + "', '" + cname + "', '" + mpc + "', '" + cap + "', " + ldms + ", " + psz + ", '" + lng + "', " + pden + ", " + gdp + ", '" + cur + "', " + pcc + ", " + pat + ");"; PreparedStatement ps = null; try { ps = cn.prepareStatement(q); System.out.println(ps.toString()); int ret = ps.executeUpdate(q); } catch (SQLException throwables) { throwables.printStackTrace(); } } /** * If a country is undelected to compare, it must be removed from the compare table * * @param country the COuntry object being selected * @param cn the connection to the database */ public void removeFromCompare(Country country, Connection cn) { int year = country.year.getValue(); String abbr = country.abbr.getValue(); String q = "DELETE FROM compare WHERE year = " + year + " AND abbr = '" + abbr + "';"; Statement st = null; try { st = cn.createStatement(); int ret = st.executeUpdate(q); } catch (SQLException throwables) { throwables.printStackTrace(); } } /** * When a new Search query is created the rows selected need to be checked if any exist in the * compare table * * @param country the Country object being checked * @return returns if the Country is in the compare table or not */ private boolean checkCompare(Country country) { String[] creds = GetSQLInfo.getCredentials(); String usr = creds[0]; String pwd = creds[1]; String url = GetSQLInfo.getUrlConnect(); String abbr = country.abbr.getValue(); int year = country.year.intValue(); try (Connection cn = DriverManager.getConnection(url, usr, pwd)) { String q = "SELECT * FROM compare c WHERE c.year = " + year + " AND c.abbr = ?;"; PreparedStatement p_stmt = cn.prepareStatement(q); p_stmt.setString(1, abbr); ResultSet rs = p_stmt.executeQuery(); if (rs.next()) { return true; } } catch (SQLException e) { e.printStackTrace(); } return false; } /** * Delete the selected Country/Years from the entire database */ public void delSelected() { boolean ans = PopUp.init_confirm("WARNING", "Are you sure you want delete the selected Country entries?"); if (ans) { String[] creds = GetSQLInfo.getCredentials(); String usr = creds[0]; String pwd = creds[1]; String url = GetSQLInfo.getUrlConnect(); try (Connection cn = DriverManager.getConnection(url, usr, pwd)) { // Commented out because removal of data simply stopped // for (Country country: selected) { // String q = "DELETE c, cp, e FROM country c JOIN country_population cp USING (year, abbr)" + // " JOIN economy e USING (year, abbr) WHERE c.year = " + country.year.get() + // " AND c.abbr = ?;"; // PreparedStatement ps = cn.prepareStatement(q); // ps.setString(1, country.abbr.getValue()); // int ret = ps.executeUpdate(); // } } catch (SQLException throwables) { throwables.printStackTrace(); } PopUp.init_error("Database has been updated: Items removed"); performSearch(); } } }
UTF-8
Java
28,559
java
SearchController.java
Java
[ { "context": "r = creds[0];\n String pwd = creds[1];\n String url = GetSQLIn", "end": 10981, "score": 0.9333082437515259, "start": 10976, "tag": "PASSWORD", "value": "creds" } ]
null
[]
package sample; /** * This is the primary instance of the application. This screen is presented after logging in, and acts * as the primary hub for all application functionality. */ import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.*; import javafx.scene.control.cell.PropertyValueFactory; import javafx.scene.layout.GridPane; import javafx.stage.Stage; import java.sql.*; import java.util.ArrayList; import java.util.List; public class SearchController { private static Stage window; private int MIN_YEAR = 1965; private int MAX_YEAR = 2015; public Button edit_countries_btn; public Button del_selected_btn; public Button view_editors_btn; public TextField country_search_name; public TextField initial_year; public TextField final_year; public Button select_att_btn; public Label atts_label; public ScrollPane results_pane; public GridPane container; // List for tracking all of the selected Country/Years public List<Country> compared = new ArrayList<>(); // List for determining which items are selected soley on the current search public List<Country> selected; // List of search attributes based on the Attribute Selector private final List<String> search_atts = new ArrayList<>(); /** * Initialize Search Screen and it's associated buttons and items * * @param editor_val */ public void initialize(Boolean editor_val) { try { window = new Stage(); Parent loader = FXMLLoader.load(getClass().getResource("Search.fxml")); Scene search_scene = new Scene(loader, 1000, 900); window.setScene(search_scene); Main.stage_settings(window); initItems(); // Based on the editor_val calulcated when logging in, if the user is not an editor // then remove the following buttons from their display if (!editor_val) { edit_countries_btn.setVisible(false); del_selected_btn.setVisible(false); view_editors_btn.setVisible(false); } window.show(); } catch (Exception e) { e.printStackTrace(); } } /** * Initialize the items on screen to be accessed programmatically */ private void initItems() { edit_countries_btn = (Button) window.getScene().lookup("#edit_countries_btn"); del_selected_btn = (Button) window.getScene().lookup("#del_selected_btn"); view_editors_btn = (Button) window.getScene().lookup("#view_editors_btn"); country_search_name = (TextField) window.getScene().lookup("country_search_name"); initial_year = (TextField) window.getScene().lookup("#initial_year"); final_year = (TextField) window.getScene().lookup("#final_year"); results_pane = (ScrollPane) window.getScene().lookup("#results_pane"); results_pane.setVisible(false); container = (GridPane) window.getScene().lookup("#container"); // Set the min/max years as default search parameters initial_year.setText(MIN_YEAR + ""); final_year.setText(MAX_YEAR + ""); // Clean out the compare table so no data carries over from last application runs cleanCompare(); } /** * cleanCompare deletes everything from the compare table, so that all data added to it are only from * the current app instance */ private void cleanCompare() { String[] creds = GetSQLInfo.getCredentials(); String usr = creds[0]; String pwd = creds[1]; String url = GetSQLInfo.getUrlConnect(); try (Connection cn = DriverManager.getConnection(url, usr, pwd)) { String q = "DELETE FROM compare"; PreparedStatement p_stmt = cn.prepareStatement(q); int ret = p_stmt.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } } // this function is called when the user presses the edit countries button and loads the new window public void editCountries(){ try { FXMLLoader fxmlLoader = new FXMLLoader(); fxmlLoader.setLocation(getClass().getResource("Edit.fxml")); Scene scene = new Scene(fxmlLoader.load(), 600, 400); Stage stage = new Stage(); stage.setTitle("Edit Country"); stage.setScene(scene); stage.show(); } catch (Exception e){ e.printStackTrace(); } } /** * Opens the Attribute Selector Screen so the user can select what attributes to search with their countries */ public void selectAtts() { AttSelectController asc = new AttSelectController(); asc.initialize(search_atts, this); } /** * store Selected gets called from the Attribute Selector as a signal to update the Search Screen to display * the attributes that the user has selected */ public void storeSelected() { // Check if no attributes are selected. Default to searching all attributes if (search_atts.size() < 1) { atts_label.setText("All Attributes (Default)"); } else { // Create a String based on selected attributes to display on screen String search = ""; for (String att : search_atts) { search = search.concat(att); if (search_atts.indexOf(att) != (search_atts.size() - 1)) { search = search.concat(", "); } } atts_label.setText(search); } } /** * Activates when the user presses search button. Performs a vast number of operations to display the * get, and display the results to a table */ public void performSearch() { //Create a new instance of the selected List for every search, as we don't want to delete any items // from a previous search selected = new ArrayList<>(); // The table that we are going to populate TableView<Country> table_view = new TableView<>(); table_view.setMaxHeight(450); // Get the search parameters that the user entered String country = country_search_name.getText(); String init_year = initial_year.getText(); String fin_year = final_year.getText(); // Validate that the entered information is legal boolean ret = validateSearch(country, init_year, fin_year); if (ret) { // Create the query to search. We must create the select clause dynamically // attToSQL is called to convert the List of attribute IDs selected into the appropriate column names String sql_select = attToSQL(); String q = "SELECT " + sql_select + " FROM country c" + " JOIN country_population cp USING (year, abbr)" + " JOIN economy e USING (year, abbr)" + " WHERE c.year >= " + init_year + " AND c.year <= " + fin_year + " AND c.country_name = ?" + " ORDER BY year ASC;"; // The query, table, and country the user entered are passed to create the table getStoreData(q, country, table_view); // The completed table is placed inside the hidden ScrollPane and displayed Parent root = table_view; results_pane.setContent(root); results_pane.setVisible(true); } } /** * getStoreData retrieves searched data from the database and stores it to the table that is displayed on screen * * @param q the query string is passed in missing only the country name to search using prepared statements * @param search_country the country the user wants to search for is passed in to be placed in a prepared statement * @param table_view the table we will be populating with data found */ public void getStoreData(String q, String search_country, TableView<Country> table_view) { String[] creds = GetSQLInfo.getCredentials(); String usr = creds[0]; String pwd = creds[1]; String url = GetSQLInfo.getUrlConnect(); try (Connection cn = DriverManager.getConnection(url, usr, pwd)) { PreparedStatement p_stmt = cn.prepareStatement(q); p_stmt.setString(1, search_country); ResultSet rs = p_stmt.executeQuery(); ResultSetMetaData rsmd = rs.getMetaData(); int cols = rsmd.getColumnCount(); // Boolean flag is used to determine if the user is searching for a specific attribute or not // This is needed because otherwise the table will try to read data from columns that don't exist // in the query boolean flag = false; // A list of countries is created to represent every row of the query ArrayList<Country> data = new ArrayList<>(); while (rs.next()) { Country country = new Country(); // year, abbr, and country_name will always be searched by default CheckBox cb = new CheckBox(); country.setSelect(cb); country.year.set(rs.getInt("year")); country.abbr.set(rs.getString("abbr")); country.country_name.set(rs.getString("country_name")); // We need to check if any countries has been previously selected for comparison // or has been saved to the compare table. If so, mark the checkbox as selected if (checkCompare(country)) { country.select.setSelected(true); selected.add(country); } cb.selectedProperty().addListener(new ChangeListener<Boolean>() { /** * Checkbox is given a state change listener. When the country/year is selected (checked) * we want that info to be sent and stored in the compare table so it is remembered through * searches. If it is unchecked, then we need to remove that info from the compare table * * @param observable Not used * @param oldValue the value that the checkbox was * @param newValue the value that the checkbox now is */ @Override public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) { String[] creds = GetSQLInfo.getCredentials(); String usr = creds[0]; String pwd = <PASSWORD>[1]; String url = GetSQLInfo.getUrlConnect(); try (Connection cn = DriverManager.getConnection(url, usr, pwd)) { // The way that this listener was implemented is by far not the most efficient, // nor the best way to do this task. I would have liked to make the program run faster // and less expensively by not adding removing everytime the checkbox is checked/unchecked // but I simply didn't have time. // In the code below I believe I tried to go for two different approaches unnecessarily if (newValue) { //The check box is selected if (!compared.contains(country)) { compared.add(country); addToCompare(country, cn); selected.add(country); } } else { // The checkbox is not selected if (compared.contains(country)) { compared.remove(country); removeFromCompare(country, cn); selected.remove(country); } } } catch (SQLException throwables) { throwables.printStackTrace(); } } }); /** * Check all of the optional attributes to ensure we don't try to read non-existent data */ // Check if most_populous_city is being searched for for (int i = 1; i < cols; i++) if (rsmd.getColumnName(i).equals("most_populous_city")) flag = true; if (flag) country.most_populous_city.set(rs.getString("most_populous_city")); else country.most_populous_city.set("N/A"); // Check if capital is being searched for flag = false; for (int i = 1; i < cols; i++) if (rsmd.getColumnName(i).equals("capital")) flag = true; if (flag) country.capital.set(rs.getString("capital")); else country.capital.set("N/A"); // Check if land_mass is being searched for flag = false; for (int i = 1; i < cols; i++) if (rsmd.getColumnName(i).equals("land_mass")) flag = true; if (flag) country.land_mass.set(rs.getInt("land_mass")); else country.land_mass.set(0); // Check if pop_size is being searched for flag = false; for (int i = 1; i < cols; i++) if (rsmd.getColumnName(i).equals("pop_size")) flag = true; if (flag) country.pop_size.set(rs.getInt("pop_size")); else country.pop_size.set(0); // Check if country_language is being searched for flag = false; for (int i = 1; i < cols; i++) if (rsmd.getColumnName(i).equals("country_language")) flag = true; if (flag) country.country_language.set(rs.getString("country_language")); else country.country_language.set("N/A"); // Check if pop_density is being searched for flag = false; for (int i = 1; i < cols; i++) if (rsmd.getColumnName(i).equals("pop_density")) flag = true; if (flag) country.pop_density.set(rs.getFloat("pop_density")); else country.pop_density.set(0); // Check if gdp is being searched for flag = false; for (int i = 1; i < cols; i++) if (rsmd.getColumnName(i).equals("gdp")) flag = true; if (flag) country.gdp.set(rs.getFloat("gdp")); else country.gdp.set(0); // Check if currency is being searched for flag = false; for (int i = 1; i < cols; i++) if (rsmd.getColumnName(i).equals("currency")) flag = true; if (flag) country.currency.set(rs.getString("currency")); else country.currency.set("N/A"); // Check if power_consumption_per_capita is being searched for flag = false; for (int i = 1; i < cols; i++) if (rsmd.getColumnName(i).equals("power_consumption_per_capita")) flag = true; if (flag) country.power_consumption_per_capita.set(rs.getFloat("power_consumption_per_capita")); else country.power_consumption_per_capita.set(0); // Check if passenger_air_transport is being searched for flag = false; for (int i = 1; i < cols; i++) if (rsmd.getColumnName(i).equals("passenger_air_transport")) flag = true; if (flag) country.passenger_air_transport.set(rs.getInt("passenger_air_transport")); else country.passenger_air_transport.set(0); // After all data vaules are set, then the country is added to the list of rows (Countries) data.add(country); } //the country list is converted into an ObservableList ObservableList dbData = FXCollections.observableArrayList(data); // The checkbox column is created individually since it is not part of the query results TableColumn check_col = new TableColumn<>(); check_col.setText("Selected"); check_col.setCellValueFactory(new PropertyValueFactory<>("select")); // Column is added to the table table_view.getColumns().add(check_col); // Give columns readable names for (int i = 0; i < rs.getMetaData().getColumnCount(); i++) { TableColumn col = new TableColumn<>(); switch (rs.getMetaData().getColumnName(i+1)) { case "year": col.setText("Year"); break; case "abbr": col.setText("Abbr"); break; case "country_name": col.setText("Country Name"); break; case "most_populous_city": col.setText("Most Pop. City"); break; case "capital": col.setText("Capital"); break; case "land_mass": col.setText("Land Mass"); break; case "pop_size": col.setText("Pop. Size"); break; case "country_language": col.setText("Language"); break; case "pop_density": col.setText("pop. Density"); break; case "gdp": col.setText("GDP"); break; case "currency": col.setText("Currency"); break; case "power_consumption_per_capita": col.setText("Power Cons. Capita"); break; case "passenger_air_transport": col.setText("Passenger Air Trans."); break; default: col.setText(rs.getMetaData().getColumnName(i+1)); break; } // Set the tag of each column and then add to table col.setCellValueFactory(new PropertyValueFactory<>(rs.getMetaData().getColumnName(i+1))); table_view.getColumns().add(col); } // Fill table_view with the columns table_view.setItems(dbData); } catch (Exception e) { e.printStackTrace(); } } /** * Converts the global list of attributes into a String of the associated attribute column names * * @return string of every column name being selected to be added to the main SELECT query */ public String attToSQL() { // If the user selected no attributes, we will search for every attribute if (search_atts.size() < 1) { return "*"; } // The SELECT clause always searches for these 3 attributes withour exception String sql_select = "c.year, c.abbr, c.country_name, "; for (int i = 0; i < search_atts.size(); i++) { String tmp = search_atts.get(i); String title = GetSQLInfo.idToTitle(tmp); sql_select = sql_select.concat(title); if (search_atts.indexOf(tmp) != (search_atts.size() - 1)) { sql_select = sql_select.concat(", "); } } return sql_select; } /** * Simple validator to check that the input the user has entered is valid and searchable. Checks that * - Dates are sequentially in order * - Dates do not exceed the max year or the min year * - The country named is only alphabetic * If one of the conditions fails, a PopUp appears informing of the error * * @param co the country name to search * @param iy the initial year * @param fy the final year * @return boolean on if the search is legal or not */ private boolean validateSearch(String co, String iy, String fy) { if (iy.isEmpty()) { PopUp.init_error("INVALID ENTRY:\nMissing initial year"); return false; } if (fy.isEmpty()) { PopUp.init_error("INVALID ENTRY:\nMissing final year"); return false; } if (co.isEmpty()) { PopUp.init_error("INVALID ENTRY:\nMissing Country to search"); return false; } if (iy.matches("[0-9]+") && fy.matches("[0-9]+")) { int intIY = Integer.parseInt(iy); int intFY = Integer.parseInt(fy); if (intFY - intIY < 0) { PopUp.init_error("INVALID ENTRY:\nFinal year cannot be earlier than initial year"); return false; } if (intFY > MAX_YEAR) { PopUp.init_error("INVALID ENTRY:\nFinal year cannot be greater than " + MAX_YEAR); return false; } if (intIY < MIN_YEAR) { PopUp.init_error("INVALID ENTRY:\nInitial year cannot be less than " + MIN_YEAR); return false; } if (co.matches("[a-zA-Z ]+")) { return true; } } return false; } /** * Incomplete method to display a table of every country stored to the compare table */ public void compareSelected() { System.out.println("Creating Table of compared countries"); } // this function executes when the user presses the edit editors button and calls the editors window public void showEditors() { try { FXMLLoader fxmlLoader = new FXMLLoader(); fxmlLoader.setLocation(getClass().getResource("editors.fxml")); Scene scene = new Scene(fxmlLoader.load(), 500, 300); Stage stage = new Stage(); stage.setTitle("Edit Editors"); stage.setScene(scene); stage.show(); } catch (Exception e){ e.printStackTrace(); } } /** * If a country is selected to compare, it must be added to the compare table to be remembered * * @param country the Country object being selected * @param cn the connection to the database */ public void addToCompare(Country country, Connection cn) { int year = country.year.getValue(); String abbr = country.abbr.getValue(); String cname = country.country_name.getValue(); String mpc = country.most_populous_city.getValue(); String cap = country.capital.getValue(); int ldms = country.land_mass.getValue(); int psz = country.pop_size.getValue(); String lng = country.country_language.getValue(); float pden = country.pop_density.floatValue(); float gdp = country.gdp.floatValue(); String cur = country.currency.getValue(); float pcc = country.power_consumption_per_capita.floatValue(); int pat = country.passenger_air_transport.getValue(); /** Using this method was giving me errors, so I switch back to inserting manually String q = "INSERT INTO compare VALUES (" + year + ", ?, ?, ?, ?, " + ldms + ", " + psz + ", ?, " + pden + ", " + gdp + ", ?, " + pcc + ", " + pat + ");"; **/ String q = "INSERT INTO compare VALUES ("+ year + ", '" + abbr + "', '" + cname + "', '" + mpc + "', '" + cap + "', " + ldms + ", " + psz + ", '" + lng + "', " + pden + ", " + gdp + ", '" + cur + "', " + pcc + ", " + pat + ");"; PreparedStatement ps = null; try { ps = cn.prepareStatement(q); System.out.println(ps.toString()); int ret = ps.executeUpdate(q); } catch (SQLException throwables) { throwables.printStackTrace(); } } /** * If a country is undelected to compare, it must be removed from the compare table * * @param country the COuntry object being selected * @param cn the connection to the database */ public void removeFromCompare(Country country, Connection cn) { int year = country.year.getValue(); String abbr = country.abbr.getValue(); String q = "DELETE FROM compare WHERE year = " + year + " AND abbr = '" + abbr + "';"; Statement st = null; try { st = cn.createStatement(); int ret = st.executeUpdate(q); } catch (SQLException throwables) { throwables.printStackTrace(); } } /** * When a new Search query is created the rows selected need to be checked if any exist in the * compare table * * @param country the Country object being checked * @return returns if the Country is in the compare table or not */ private boolean checkCompare(Country country) { String[] creds = GetSQLInfo.getCredentials(); String usr = creds[0]; String pwd = creds[1]; String url = GetSQLInfo.getUrlConnect(); String abbr = country.abbr.getValue(); int year = country.year.intValue(); try (Connection cn = DriverManager.getConnection(url, usr, pwd)) { String q = "SELECT * FROM compare c WHERE c.year = " + year + " AND c.abbr = ?;"; PreparedStatement p_stmt = cn.prepareStatement(q); p_stmt.setString(1, abbr); ResultSet rs = p_stmt.executeQuery(); if (rs.next()) { return true; } } catch (SQLException e) { e.printStackTrace(); } return false; } /** * Delete the selected Country/Years from the entire database */ public void delSelected() { boolean ans = PopUp.init_confirm("WARNING", "Are you sure you want delete the selected Country entries?"); if (ans) { String[] creds = GetSQLInfo.getCredentials(); String usr = creds[0]; String pwd = creds[1]; String url = GetSQLInfo.getUrlConnect(); try (Connection cn = DriverManager.getConnection(url, usr, pwd)) { // Commented out because removal of data simply stopped // for (Country country: selected) { // String q = "DELETE c, cp, e FROM country c JOIN country_population cp USING (year, abbr)" + // " JOIN economy e USING (year, abbr) WHERE c.year = " + country.year.get() + // " AND c.abbr = ?;"; // PreparedStatement ps = cn.prepareStatement(q); // ps.setString(1, country.abbr.getValue()); // int ret = ps.executeUpdate(); // } } catch (SQLException throwables) { throwables.printStackTrace(); } PopUp.init_error("Database has been updated: Items removed"); performSearch(); } } }
28,564
0.534543
0.531951
685
40.693432
29.282606
124
false
false
0
0
0
0
0
0
0.585401
false
false
11
a29ba75c47f76459df54f5fd5c3409a99dfc3f8e
25,013,889,602,941
9f741ba02ab1c41a61dcc37d2ec4550a1eb213f6
/src/main/java/com/imaginea/lucene/DocumentExtractor.java
d76f425a6cef24948439b26e1bd7a39904c0cbbf
[]
no_license
ashwin9191/lucenesample
https://github.com/ashwin9191/lucenesample
acd712b027b5f5576df0fd1810849db6adf68f4e
8356b5c8e281c2d3b3a90829687577d050b9e948
refs/heads/master
2020-12-24T15:13:39.178000
2013-11-18T08:13:02
2013-11-18T08:13:02
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.imaginea.lucene; import java.io.File; import java.io.IOException; public abstract class DocumentExtractor { protected File docFile; DocumentExtractor(String filePath) { this.docFile = new File(filePath); } public String getFileName() throws IOException { return this.docFile.getCanonicalPath(); } public abstract String getTextContent() throws IOException; }
UTF-8
Java
386
java
DocumentExtractor.java
Java
[]
null
[]
package com.imaginea.lucene; import java.io.File; import java.io.IOException; public abstract class DocumentExtractor { protected File docFile; DocumentExtractor(String filePath) { this.docFile = new File(filePath); } public String getFileName() throws IOException { return this.docFile.getCanonicalPath(); } public abstract String getTextContent() throws IOException; }
386
0.777202
0.777202
18
20.444445
19.723709
60
false
false
0
0
0
0
0
0
0.944444
false
false
11
5b22bd15b975866e9b409a7fb01a8526d1b59cc0
154,618,829,079
b3afe22b4faa316885b3b4744f6ea4f5a3466cd6
/FusionProject/src/GUI/GUI_test.java
9089c05b34158a76c8856cd443cae029678d9bdb
[]
no_license
Jahwi-0413/FusionProject
https://github.com/Jahwi-0413/FusionProject
35ac782c91f7d02e9fcd852be9f4b09f9da26f69
242e4e94022675e2c4fe934cea85203bf661dd3c
refs/heads/master
2020-09-16T07:52:15.815000
2020-02-15T15:20:06
2020-02-15T15:20:06
240,700,597
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package GUI; public class GUI_test { }
UTF-8
Java
44
java
GUI_test.java
Java
[]
null
[]
package GUI; public class GUI_test { }
44
0.636364
0.636364
7
5.285714
7.886956
22
false
false
0
0
0
0
0
0
0.285714
false
false
11
bdcad227f3c8fab510fecca60d909173883a462b
154,618,830,857
5b325f92e4cc88e922f922cc57619fac8c48eaef
/src/multithreading/Monkeys.java
5d6146d2c25b53e54d885c9e37a3f917001b6062
[]
no_license
anma0/JavaSem4
https://github.com/anma0/JavaSem4
55516099686c84c156702cbc25e2776c919d8349
4030142715474f151cbb62101d5f2d4186cfbe1e
refs/heads/master
2020-04-30T21:35:03.191000
2019-05-22T14:16:43
2019-05-22T14:16:43
177,095,816
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package multithreading; public class Monkeys { //принцип: стараться обходиться без статических методов public static void main(String[] args) { new Monkeys(); //создаём одну программу про обезьянок } private int bananas = 1_000_000; private int total = 0; private Monkeys() { //здесь основная логика программы //Если нужно, чтобы программа одновременно выполняла несколько действий, создаются потоки, по одному на каждое действие. //Нам нужно, чтобы 2 обезянки ели бананы одновременно, поэтому создадим два потока, далее 10 Object monitor = new Object(); //Runnable - произвольный код, у него нет аргументов, не возвращает результат Runnable monkeyAction = () -> { int eaten = 0; while (bananas > 0) { //внутри синхронайзд указывается любой объект. Он называется монитор. //если один поток взял монитор (т.е. вошёл в блок), то другие потоки ждут, когда монитор будет возвращён. //В данном случае можно написать this - это объект Monkeys, или можно создать специальный объект, который нужен как монитор synchronized (monitor) { if (bananas > 0) {//повторная проверка не съели ли уже банан bananas--; //1)узнать значения bananas 2)уменьшить 3)записать обратно eaten++; } } } //используем глобальную переменную, необходима синхронизация synchronized (monitor) { total += eaten; } //%d - подставить число в десятичной системе счисления System.out.println(String.format("A monkey ate %,d bananas; total %,d", eaten, total)); }; for (int i = 0; i < 10; i++) { Thread monkey = new Thread(monkeyAction); monkey.start(); } //если не синхронизировать работу двх обезьян, то в начале каждая решит, что бананов 1_000_000, каждая уменьшит до 999_999 и запишет это число в переменную (поле) bananas. Т.е. бананов 999_999, но каждая обезьяна считает, что съела один банан. //участки кода, которые нельзя выполнять одновременно нескольким потокам, надо синхронизировать, т.е. явно указывать, что только один поток может выполнить участок кода. Для этого есть ключевое слово synchronize. программирование с помощью synchronize чень сложно, особенно если программа большая и потоков много. Это самый низкоуровневый метод программирования. } }
UTF-8
Java
3,739
java
Monkeys.java
Java
[]
null
[]
package multithreading; public class Monkeys { //принцип: стараться обходиться без статических методов public static void main(String[] args) { new Monkeys(); //создаём одну программу про обезьянок } private int bananas = 1_000_000; private int total = 0; private Monkeys() { //здесь основная логика программы //Если нужно, чтобы программа одновременно выполняла несколько действий, создаются потоки, по одному на каждое действие. //Нам нужно, чтобы 2 обезянки ели бананы одновременно, поэтому создадим два потока, далее 10 Object monitor = new Object(); //Runnable - произвольный код, у него нет аргументов, не возвращает результат Runnable monkeyAction = () -> { int eaten = 0; while (bananas > 0) { //внутри синхронайзд указывается любой объект. Он называется монитор. //если один поток взял монитор (т.е. вошёл в блок), то другие потоки ждут, когда монитор будет возвращён. //В данном случае можно написать this - это объект Monkeys, или можно создать специальный объект, который нужен как монитор synchronized (monitor) { if (bananas > 0) {//повторная проверка не съели ли уже банан bananas--; //1)узнать значения bananas 2)уменьшить 3)записать обратно eaten++; } } } //используем глобальную переменную, необходима синхронизация synchronized (monitor) { total += eaten; } //%d - подставить число в десятичной системе счисления System.out.println(String.format("A monkey ate %,d bananas; total %,d", eaten, total)); }; for (int i = 0; i < 10; i++) { Thread monkey = new Thread(monkeyAction); monkey.start(); } //если не синхронизировать работу двх обезьян, то в начале каждая решит, что бананов 1_000_000, каждая уменьшит до 999_999 и запишет это число в переменную (поле) bananas. Т.е. бананов 999_999, но каждая обезьяна считает, что съела один банан. //участки кода, которые нельзя выполнять одновременно нескольким потокам, надо синхронизировать, т.е. явно указывать, что только один поток может выполнить участок кода. Для этого есть ключевое слово synchronize. программирование с помощью synchronize чень сложно, особенно если программа большая и потоков много. Это самый низкоуровневый метод программирования. } }
3,739
0.638737
0.623539
55
45.654545
63.913925
370
false
false
0
0
0
0
0
0
0.781818
false
false
11
f43da9a57ffb9c67deda64e495de4a0375ece082
32,684,701,173,397
4f79e0d2f13c063a9d39706de31ec37ee34d4e61
/blockchain_main/src/main/java/net/xdclass/product_service/service/EthereumService.java
066ecb2cebda3608642e9933df17d94a308edbae
[]
no_license
shipingchen/BlockView
https://github.com/shipingchen/BlockView
bfa58b10e1cafd2ab5b78c19738f4b957122e3ed
fb405c1eb7cb14bad8059308bfae5e9c10c7c006
refs/heads/master
2023-01-13T17:11:00.941000
2019-11-20T11:48:11
2019-11-20T11:48:11
213,173,439
1
0
null
false
2023-01-04T12:33:02
2019-10-06T13:27:26
2019-11-20T11:48:14
2023-01-04T12:33:01
8,123
0
0
50
Vue
false
false
package net.xdclass.product_service.service; import net.xdclass.product_service.domain.Ethereum; import java.util.List; public interface EthereumService { List<Ethereum> listBlock(); void addBlock(); }
UTF-8
Java
216
java
EthereumService.java
Java
[]
null
[]
package net.xdclass.product_service.service; import net.xdclass.product_service.domain.Ethereum; import java.util.List; public interface EthereumService { List<Ethereum> listBlock(); void addBlock(); }
216
0.75463
0.75463
13
15.615385
18.332561
51
false
false
0
0
0
0
0
0
0.384615
false
false
11
769d417a48e4e87f455b61ccf677da62bbf903dc
30,683,246,392,835
05ad0ed1a2eb6cd3f3b2234513295d483c21e099
/src/linkedlist/MyLinkedList.java
950c16cdfb836965c99b5bb4ec1492438b57e430
[]
no_license
dgandhi98/JavaCalculator
https://github.com/dgandhi98/JavaCalculator
cde0d39bc93508a8b196084b27e9309a1c792fa0
0e6a2a84cdbd65df846e78a86b896eb109f20260
refs/heads/master
2021-01-12T02:11:13.605000
2017-05-24T14:18:51
2017-05-24T14:18:51
78,484,518
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package linkedlist; /** * @Author Divyanshu Gandhi * Custom LinkedList that implements the SimpleLinkedList interface. */ public class MyLinkedList<AnyType> implements SimpleLinkedList<AnyType> { private MyNode<AnyType> head; public MyLinkedList () { head = null; } // New method for Lab 6 public AnyType getHeadData() { if(head != null) return head.data; else return null; } // This will run in O(n) time public void insert(AnyType x) { if(isEmpty()) { head = new MyNode<AnyType>(); head.data = x; return; } MyNode<AnyType> current = head; while( current.next != null ) { current = current.next; } current.next = new MyNode<AnyType>(); current.next.data = x; } // This will run in constant time // New method for Lab 6 public void insertFirst(AnyType x) { MyNode<AnyType> current = new MyNode<AnyType>(); current.data = x; if(isEmpty()) { head = current; } else { current.next = head; head = current; } } public void delete(AnyType x) { if(head.data == x) { head = head.next; return; } MyNode<AnyType> current = head; while(current.next != null) { if(current.next.data == x) { current.next = current.next.next; return; } current = current.next; } System.out.println("Did not find anything to delete."); } // This will run in constant time // New method for Lab 6 public AnyType deleteFirst() { AnyType x = head.data; head = head.next; return x; } public boolean contains(AnyType x) { MyNode<AnyType> current = head; while(current != null) { if(current.data == x) return true; current = current.next; } return false; } public AnyType lookup(AnyType x) { MyNode<AnyType> current = head; while(current != null) { if(current.data == x) return current.data; current = current.next; } return null; } public boolean isEmpty() { if(head == null) return true; return false; } // This will run in O(n) time public void printList() { MyNode<AnyType> current = head; while(current != null) { System.out.print(current.data + " "); current = current.next; } System.out.println(); } }
UTF-8
Java
2,180
java
MyLinkedList.java
Java
[ { "context": "package linkedlist;\n/**\n * @Author Divyanshu Gandhi\n * Custom LinkedList that implements the SimpleLi", "end": 51, "score": 0.9998770356178284, "start": 35, "tag": "NAME", "value": "Divyanshu Gandhi" } ]
null
[]
package linkedlist; /** * @Author <NAME> * Custom LinkedList that implements the SimpleLinkedList interface. */ public class MyLinkedList<AnyType> implements SimpleLinkedList<AnyType> { private MyNode<AnyType> head; public MyLinkedList () { head = null; } // New method for Lab 6 public AnyType getHeadData() { if(head != null) return head.data; else return null; } // This will run in O(n) time public void insert(AnyType x) { if(isEmpty()) { head = new MyNode<AnyType>(); head.data = x; return; } MyNode<AnyType> current = head; while( current.next != null ) { current = current.next; } current.next = new MyNode<AnyType>(); current.next.data = x; } // This will run in constant time // New method for Lab 6 public void insertFirst(AnyType x) { MyNode<AnyType> current = new MyNode<AnyType>(); current.data = x; if(isEmpty()) { head = current; } else { current.next = head; head = current; } } public void delete(AnyType x) { if(head.data == x) { head = head.next; return; } MyNode<AnyType> current = head; while(current.next != null) { if(current.next.data == x) { current.next = current.next.next; return; } current = current.next; } System.out.println("Did not find anything to delete."); } // This will run in constant time // New method for Lab 6 public AnyType deleteFirst() { AnyType x = head.data; head = head.next; return x; } public boolean contains(AnyType x) { MyNode<AnyType> current = head; while(current != null) { if(current.data == x) return true; current = current.next; } return false; } public AnyType lookup(AnyType x) { MyNode<AnyType> current = head; while(current != null) { if(current.data == x) return current.data; current = current.next; } return null; } public boolean isEmpty() { if(head == null) return true; return false; } // This will run in O(n) time public void printList() { MyNode<AnyType> current = head; while(current != null) { System.out.print(current.data + " "); current = current.next; } System.out.println(); } }
2,170
0.637615
0.636239
111
18.639639
14.967107
73
false
false
0
0
0
0
0
0
2.09009
false
false
11
3d8ef0a0b48500902445523ec855393efd5b4127
23,656,679,920,074
143089f3d485c8b3ddb0aadbd818801dee93806e
/de.uka.ipd.sdq.pcm.componentinternaldependencies/src/de/uka/ipd/sdq/componentInternalDependencies/impl/OperationToOperationDependencyImpl.java
6560a7a0f7c40cce0fa2c570b7ec5473018d8113
[ "Apache-2.0" ]
permissive
SebastianWeberKamp/KAMP4IS
https://github.com/SebastianWeberKamp/KAMP4IS
a58155d504562132a3b124934adf086f6e51aa4d
3ce896786cf24fd6d03f376c7127920866259666
refs/heads/master
2020-09-20T08:14:00.135000
2019-12-15T09:22:53
2019-12-15T09:22:53
224,419,717
0
0
Apache-2.0
true
2019-11-27T11:54:15
2019-11-27T11:54:14
2017-06-02T08:46:33
2017-06-10T19:02:28
2,661
0
0
0
null
false
false
/** */ package de.uka.ipd.sdq.componentInternalDependencies.impl; import de.uka.ipd.sdq.componentInternalDependencies.ComponentInternalDependenciesPackage; import de.uka.ipd.sdq.componentInternalDependencies.OperationToOperationDependency; import de.uka.ipd.sdq.componentInternalDependencies.RoleToRoleDependency; import de.uka.ipd.sdq.identifier.impl.IdentifierImpl; import java.util.Collection; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.common.notify.NotificationChain; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.InternalEObject; import org.eclipse.emf.ecore.impl.ENotificationImpl; import org.eclipse.emf.ecore.util.EObjectResolvingEList; import org.eclipse.emf.ecore.util.EcoreUtil; import org.palladiosimulator.pcm.repository.Signature; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>Operation To Operation Dependency</b></em>'. * <!-- end-user-doc --> * <p> * The following features are implemented: * </p> * <ul> * <li>{@link de.uka.ipd.sdq.componentInternalDependencies.impl.OperationToOperationDependencyImpl#getProvidedSignatures <em>Provided Signatures</em>}</li> * <li>{@link de.uka.ipd.sdq.componentInternalDependencies.impl.OperationToOperationDependencyImpl#getRequiredSignatures <em>Required Signatures</em>}</li> * <li>{@link de.uka.ipd.sdq.componentInternalDependencies.impl.OperationToOperationDependencyImpl#getParentRoleToRoleDependency <em>Parent Role To Role Dependency</em>}</li> * </ul> * * @generated */ public class OperationToOperationDependencyImpl extends IdentifierImpl implements OperationToOperationDependency { /** * The cached value of the '{@link #getProvidedSignatures() <em>Provided Signatures</em>}' reference list. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getProvidedSignatures() * @generated * @ordered */ protected EList<Signature> providedSignatures; /** * The cached value of the '{@link #getRequiredSignatures() <em>Required Signatures</em>}' reference list. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getRequiredSignatures() * @generated * @ordered */ protected EList<Signature> requiredSignatures; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected OperationToOperationDependencyImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return ComponentInternalDependenciesPackage.Literals.OPERATION_TO_OPERATION_DEPENDENCY; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EList<Signature> getProvidedSignatures() { if (providedSignatures == null) { providedSignatures = new EObjectResolvingEList<Signature>(Signature.class, this, ComponentInternalDependenciesPackage.OPERATION_TO_OPERATION_DEPENDENCY__PROVIDED_SIGNATURES); } return providedSignatures; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EList<Signature> getRequiredSignatures() { if (requiredSignatures == null) { requiredSignatures = new EObjectResolvingEList<Signature>(Signature.class, this, ComponentInternalDependenciesPackage.OPERATION_TO_OPERATION_DEPENDENCY__REQUIRED_SIGNATURES); } return requiredSignatures; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public RoleToRoleDependency getParentRoleToRoleDependency() { if (eContainerFeatureID() != ComponentInternalDependenciesPackage.OPERATION_TO_OPERATION_DEPENDENCY__PARENT_ROLE_TO_ROLE_DEPENDENCY) return null; return (RoleToRoleDependency)eInternalContainer(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public NotificationChain basicSetParentRoleToRoleDependency(RoleToRoleDependency newParentRoleToRoleDependency, NotificationChain msgs) { msgs = eBasicSetContainer((InternalEObject)newParentRoleToRoleDependency, ComponentInternalDependenciesPackage.OPERATION_TO_OPERATION_DEPENDENCY__PARENT_ROLE_TO_ROLE_DEPENDENCY, msgs); return msgs; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setParentRoleToRoleDependency(RoleToRoleDependency newParentRoleToRoleDependency) { if (newParentRoleToRoleDependency != eInternalContainer() || (eContainerFeatureID() != ComponentInternalDependenciesPackage.OPERATION_TO_OPERATION_DEPENDENCY__PARENT_ROLE_TO_ROLE_DEPENDENCY && newParentRoleToRoleDependency != null)) { if (EcoreUtil.isAncestor(this, newParentRoleToRoleDependency)) throw new IllegalArgumentException("Recursive containment not allowed for " + toString()); NotificationChain msgs = null; if (eInternalContainer() != null) msgs = eBasicRemoveFromContainer(msgs); if (newParentRoleToRoleDependency != null) msgs = ((InternalEObject)newParentRoleToRoleDependency).eInverseAdd(this, ComponentInternalDependenciesPackage.ROLE_TO_ROLE_DEPENDENCY__OPERATION_TO_OPERATION_DEPENDENCY, RoleToRoleDependency.class, msgs); msgs = basicSetParentRoleToRoleDependency(newParentRoleToRoleDependency, msgs); if (msgs != null) msgs.dispatch(); } else if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, ComponentInternalDependenciesPackage.OPERATION_TO_OPERATION_DEPENDENCY__PARENT_ROLE_TO_ROLE_DEPENDENCY, newParentRoleToRoleDependency, newParentRoleToRoleDependency)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public NotificationChain eInverseAdd(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case ComponentInternalDependenciesPackage.OPERATION_TO_OPERATION_DEPENDENCY__PARENT_ROLE_TO_ROLE_DEPENDENCY: if (eInternalContainer() != null) msgs = eBasicRemoveFromContainer(msgs); return basicSetParentRoleToRoleDependency((RoleToRoleDependency)otherEnd, msgs); } return super.eInverseAdd(otherEnd, featureID, msgs); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case ComponentInternalDependenciesPackage.OPERATION_TO_OPERATION_DEPENDENCY__PARENT_ROLE_TO_ROLE_DEPENDENCY: return basicSetParentRoleToRoleDependency(null, msgs); } return super.eInverseRemove(otherEnd, featureID, msgs); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public NotificationChain eBasicRemoveFromContainerFeature(NotificationChain msgs) { switch (eContainerFeatureID()) { case ComponentInternalDependenciesPackage.OPERATION_TO_OPERATION_DEPENDENCY__PARENT_ROLE_TO_ROLE_DEPENDENCY: return eInternalContainer().eInverseRemove(this, ComponentInternalDependenciesPackage.ROLE_TO_ROLE_DEPENDENCY__OPERATION_TO_OPERATION_DEPENDENCY, RoleToRoleDependency.class, msgs); } return super.eBasicRemoveFromContainerFeature(msgs); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case ComponentInternalDependenciesPackage.OPERATION_TO_OPERATION_DEPENDENCY__PROVIDED_SIGNATURES: return getProvidedSignatures(); case ComponentInternalDependenciesPackage.OPERATION_TO_OPERATION_DEPENDENCY__REQUIRED_SIGNATURES: return getRequiredSignatures(); case ComponentInternalDependenciesPackage.OPERATION_TO_OPERATION_DEPENDENCY__PARENT_ROLE_TO_ROLE_DEPENDENCY: return getParentRoleToRoleDependency(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @SuppressWarnings("unchecked") @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case ComponentInternalDependenciesPackage.OPERATION_TO_OPERATION_DEPENDENCY__PROVIDED_SIGNATURES: getProvidedSignatures().clear(); getProvidedSignatures().addAll((Collection<? extends Signature>)newValue); return; case ComponentInternalDependenciesPackage.OPERATION_TO_OPERATION_DEPENDENCY__REQUIRED_SIGNATURES: getRequiredSignatures().clear(); getRequiredSignatures().addAll((Collection<? extends Signature>)newValue); return; case ComponentInternalDependenciesPackage.OPERATION_TO_OPERATION_DEPENDENCY__PARENT_ROLE_TO_ROLE_DEPENDENCY: setParentRoleToRoleDependency((RoleToRoleDependency)newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case ComponentInternalDependenciesPackage.OPERATION_TO_OPERATION_DEPENDENCY__PROVIDED_SIGNATURES: getProvidedSignatures().clear(); return; case ComponentInternalDependenciesPackage.OPERATION_TO_OPERATION_DEPENDENCY__REQUIRED_SIGNATURES: getRequiredSignatures().clear(); return; case ComponentInternalDependenciesPackage.OPERATION_TO_OPERATION_DEPENDENCY__PARENT_ROLE_TO_ROLE_DEPENDENCY: setParentRoleToRoleDependency((RoleToRoleDependency)null); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case ComponentInternalDependenciesPackage.OPERATION_TO_OPERATION_DEPENDENCY__PROVIDED_SIGNATURES: return providedSignatures != null && !providedSignatures.isEmpty(); case ComponentInternalDependenciesPackage.OPERATION_TO_OPERATION_DEPENDENCY__REQUIRED_SIGNATURES: return requiredSignatures != null && !requiredSignatures.isEmpty(); case ComponentInternalDependenciesPackage.OPERATION_TO_OPERATION_DEPENDENCY__PARENT_ROLE_TO_ROLE_DEPENDENCY: return getParentRoleToRoleDependency() != null; } return super.eIsSet(featureID); } } //OperationToOperationDependencyImpl
UTF-8
Java
10,067
java
OperationToOperationDependencyImpl.java
Java
[]
null
[]
/** */ package de.uka.ipd.sdq.componentInternalDependencies.impl; import de.uka.ipd.sdq.componentInternalDependencies.ComponentInternalDependenciesPackage; import de.uka.ipd.sdq.componentInternalDependencies.OperationToOperationDependency; import de.uka.ipd.sdq.componentInternalDependencies.RoleToRoleDependency; import de.uka.ipd.sdq.identifier.impl.IdentifierImpl; import java.util.Collection; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.common.notify.NotificationChain; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.InternalEObject; import org.eclipse.emf.ecore.impl.ENotificationImpl; import org.eclipse.emf.ecore.util.EObjectResolvingEList; import org.eclipse.emf.ecore.util.EcoreUtil; import org.palladiosimulator.pcm.repository.Signature; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>Operation To Operation Dependency</b></em>'. * <!-- end-user-doc --> * <p> * The following features are implemented: * </p> * <ul> * <li>{@link de.uka.ipd.sdq.componentInternalDependencies.impl.OperationToOperationDependencyImpl#getProvidedSignatures <em>Provided Signatures</em>}</li> * <li>{@link de.uka.ipd.sdq.componentInternalDependencies.impl.OperationToOperationDependencyImpl#getRequiredSignatures <em>Required Signatures</em>}</li> * <li>{@link de.uka.ipd.sdq.componentInternalDependencies.impl.OperationToOperationDependencyImpl#getParentRoleToRoleDependency <em>Parent Role To Role Dependency</em>}</li> * </ul> * * @generated */ public class OperationToOperationDependencyImpl extends IdentifierImpl implements OperationToOperationDependency { /** * The cached value of the '{@link #getProvidedSignatures() <em>Provided Signatures</em>}' reference list. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getProvidedSignatures() * @generated * @ordered */ protected EList<Signature> providedSignatures; /** * The cached value of the '{@link #getRequiredSignatures() <em>Required Signatures</em>}' reference list. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getRequiredSignatures() * @generated * @ordered */ protected EList<Signature> requiredSignatures; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected OperationToOperationDependencyImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return ComponentInternalDependenciesPackage.Literals.OPERATION_TO_OPERATION_DEPENDENCY; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EList<Signature> getProvidedSignatures() { if (providedSignatures == null) { providedSignatures = new EObjectResolvingEList<Signature>(Signature.class, this, ComponentInternalDependenciesPackage.OPERATION_TO_OPERATION_DEPENDENCY__PROVIDED_SIGNATURES); } return providedSignatures; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EList<Signature> getRequiredSignatures() { if (requiredSignatures == null) { requiredSignatures = new EObjectResolvingEList<Signature>(Signature.class, this, ComponentInternalDependenciesPackage.OPERATION_TO_OPERATION_DEPENDENCY__REQUIRED_SIGNATURES); } return requiredSignatures; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public RoleToRoleDependency getParentRoleToRoleDependency() { if (eContainerFeatureID() != ComponentInternalDependenciesPackage.OPERATION_TO_OPERATION_DEPENDENCY__PARENT_ROLE_TO_ROLE_DEPENDENCY) return null; return (RoleToRoleDependency)eInternalContainer(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public NotificationChain basicSetParentRoleToRoleDependency(RoleToRoleDependency newParentRoleToRoleDependency, NotificationChain msgs) { msgs = eBasicSetContainer((InternalEObject)newParentRoleToRoleDependency, ComponentInternalDependenciesPackage.OPERATION_TO_OPERATION_DEPENDENCY__PARENT_ROLE_TO_ROLE_DEPENDENCY, msgs); return msgs; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setParentRoleToRoleDependency(RoleToRoleDependency newParentRoleToRoleDependency) { if (newParentRoleToRoleDependency != eInternalContainer() || (eContainerFeatureID() != ComponentInternalDependenciesPackage.OPERATION_TO_OPERATION_DEPENDENCY__PARENT_ROLE_TO_ROLE_DEPENDENCY && newParentRoleToRoleDependency != null)) { if (EcoreUtil.isAncestor(this, newParentRoleToRoleDependency)) throw new IllegalArgumentException("Recursive containment not allowed for " + toString()); NotificationChain msgs = null; if (eInternalContainer() != null) msgs = eBasicRemoveFromContainer(msgs); if (newParentRoleToRoleDependency != null) msgs = ((InternalEObject)newParentRoleToRoleDependency).eInverseAdd(this, ComponentInternalDependenciesPackage.ROLE_TO_ROLE_DEPENDENCY__OPERATION_TO_OPERATION_DEPENDENCY, RoleToRoleDependency.class, msgs); msgs = basicSetParentRoleToRoleDependency(newParentRoleToRoleDependency, msgs); if (msgs != null) msgs.dispatch(); } else if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, ComponentInternalDependenciesPackage.OPERATION_TO_OPERATION_DEPENDENCY__PARENT_ROLE_TO_ROLE_DEPENDENCY, newParentRoleToRoleDependency, newParentRoleToRoleDependency)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public NotificationChain eInverseAdd(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case ComponentInternalDependenciesPackage.OPERATION_TO_OPERATION_DEPENDENCY__PARENT_ROLE_TO_ROLE_DEPENDENCY: if (eInternalContainer() != null) msgs = eBasicRemoveFromContainer(msgs); return basicSetParentRoleToRoleDependency((RoleToRoleDependency)otherEnd, msgs); } return super.eInverseAdd(otherEnd, featureID, msgs); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case ComponentInternalDependenciesPackage.OPERATION_TO_OPERATION_DEPENDENCY__PARENT_ROLE_TO_ROLE_DEPENDENCY: return basicSetParentRoleToRoleDependency(null, msgs); } return super.eInverseRemove(otherEnd, featureID, msgs); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public NotificationChain eBasicRemoveFromContainerFeature(NotificationChain msgs) { switch (eContainerFeatureID()) { case ComponentInternalDependenciesPackage.OPERATION_TO_OPERATION_DEPENDENCY__PARENT_ROLE_TO_ROLE_DEPENDENCY: return eInternalContainer().eInverseRemove(this, ComponentInternalDependenciesPackage.ROLE_TO_ROLE_DEPENDENCY__OPERATION_TO_OPERATION_DEPENDENCY, RoleToRoleDependency.class, msgs); } return super.eBasicRemoveFromContainerFeature(msgs); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case ComponentInternalDependenciesPackage.OPERATION_TO_OPERATION_DEPENDENCY__PROVIDED_SIGNATURES: return getProvidedSignatures(); case ComponentInternalDependenciesPackage.OPERATION_TO_OPERATION_DEPENDENCY__REQUIRED_SIGNATURES: return getRequiredSignatures(); case ComponentInternalDependenciesPackage.OPERATION_TO_OPERATION_DEPENDENCY__PARENT_ROLE_TO_ROLE_DEPENDENCY: return getParentRoleToRoleDependency(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @SuppressWarnings("unchecked") @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case ComponentInternalDependenciesPackage.OPERATION_TO_OPERATION_DEPENDENCY__PROVIDED_SIGNATURES: getProvidedSignatures().clear(); getProvidedSignatures().addAll((Collection<? extends Signature>)newValue); return; case ComponentInternalDependenciesPackage.OPERATION_TO_OPERATION_DEPENDENCY__REQUIRED_SIGNATURES: getRequiredSignatures().clear(); getRequiredSignatures().addAll((Collection<? extends Signature>)newValue); return; case ComponentInternalDependenciesPackage.OPERATION_TO_OPERATION_DEPENDENCY__PARENT_ROLE_TO_ROLE_DEPENDENCY: setParentRoleToRoleDependency((RoleToRoleDependency)newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case ComponentInternalDependenciesPackage.OPERATION_TO_OPERATION_DEPENDENCY__PROVIDED_SIGNATURES: getProvidedSignatures().clear(); return; case ComponentInternalDependenciesPackage.OPERATION_TO_OPERATION_DEPENDENCY__REQUIRED_SIGNATURES: getRequiredSignatures().clear(); return; case ComponentInternalDependenciesPackage.OPERATION_TO_OPERATION_DEPENDENCY__PARENT_ROLE_TO_ROLE_DEPENDENCY: setParentRoleToRoleDependency((RoleToRoleDependency)null); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case ComponentInternalDependenciesPackage.OPERATION_TO_OPERATION_DEPENDENCY__PROVIDED_SIGNATURES: return providedSignatures != null && !providedSignatures.isEmpty(); case ComponentInternalDependenciesPackage.OPERATION_TO_OPERATION_DEPENDENCY__REQUIRED_SIGNATURES: return requiredSignatures != null && !requiredSignatures.isEmpty(); case ComponentInternalDependenciesPackage.OPERATION_TO_OPERATION_DEPENDENCY__PARENT_ROLE_TO_ROLE_DEPENDENCY: return getParentRoleToRoleDependency() != null; } return super.eIsSet(featureID); } } //OperationToOperationDependencyImpl
10,067
0.75077
0.75077
271
36.147602
44.059841
236
false
false
0
0
0
0
0
0
1.785978
false
false
11
2faafdc5e1d706d335ea6b5dcb4ec20f18fe0188
38,491,496,930,953
2fefc7e67cc2cf1e66536562a2816bd7afa4313a
/src/com/rian/difficultycalculator/beatmap/hitobject/HitObject.java
46773ab8e9d45ade20609cf5ca38a4aabaa657bc
[ "Apache-2.0" ]
permissive
osudroid/osu-droid
https://github.com/osudroid/osu-droid
035da6042552f93d655f635863455ab73161189b
63ab29bc523b22bf33f37a9f495c4ef4dc6c94e2
refs/heads/master
2023-09-01T16:41:43.810000
2023-08-24T09:44:13
2023-08-24T09:44:13
248,937,035
575
104
Apache-2.0
false
2023-09-13T02:22:14
2020-03-21T08:39:39
2023-09-08T18:04:49
2023-09-13T02:22:13
19,879
450
71
18
Java
false
false
package com.rian.difficultycalculator.beatmap.hitobject; import com.rian.difficultycalculator.math.Vector2; /** * Represents a hit object. */ public abstract class HitObject { /** * The radius of hit objects (i.e. the radius of a circle) relative to osu!standard. */ public static final float OBJECT_RADIUS = 64; /** * The time at which this hit object starts, in milliseconds. */ protected double startTime; /** * The position of this hit object. */ protected Vector2 position; /** * The end position of this hit object. */ protected Vector2 endPosition; /** * The stack height of this hit object. */ private int stackHeight; /** * The osu!standard scale of this hit object. */ private float scale; /** * @param startTime The time at which this hit object starts, in milliseconds. * @param position The position of the hit object relative to the play field. */ public HitObject(double startTime, Vector2 position) { this.startTime = startTime; this.position = position; endPosition = position; } /** * @param startTime The time at which this hit object starts, in milliseconds. * @param x The X position of the hit object relative to the play field. * @param y The Y position of the hit object relative to the play field. */ public HitObject(double startTime, float x, float y) { this(startTime, new Vector2(x, y)); } /** * Copy constructor. * * @param source The source to copy from. */ protected HitObject(HitObject source) { startTime = source.startTime; position = new Vector2(source.position.x, source.position.y); endPosition = new Vector2(source.endPosition.x, source.endPosition.y); stackHeight = source.stackHeight; scale = source.scale; } /** * Gets the osu!standard scale of this hit object. */ public float getScale() { return scale; } /** * Sets the osu!standard scale of this hit object. * * @param scale The new osu!standard scale. */ public void setScale(float scale) { this.scale = scale; } /** * Gets the time at which this hit object starts, in milliseconds. */ public double getStartTime() { return startTime; } /** * Gets the osu!standard stack height of this hit object. */ public int getStackHeight() { return stackHeight; } /** * Sets the osu!standard stack height of this hit object. * * @param stackHeight The new stack height. */ public void setStackHeight(int stackHeight) { this.stackHeight = stackHeight; } /** * Gets the position of this hit object. */ public Vector2 getPosition() { return position; } /** * Gets the end position of this hit object. */ public Vector2 getEndPosition() { return endPosition; } /** * Gets the radius of this hit object. */ public double getRadius() { return OBJECT_RADIUS * scale; } /** * Gets the stack offset vector of this hit object. */ public Vector2 getStackOffset() { return new Vector2(stackHeight * scale * -6.4f); } /** * Gets the stacked position of this hit object. */ public Vector2 getStackedPosition() { return evaluateStackedPosition(position); } /** * Gets the stacked end position of this slider. */ public Vector2 getStackedEndPosition() { return evaluateStackedPosition(endPosition); } /** * Evaluates a stacked position relative to this hit object. * * @return The evaluated stacked position. */ protected Vector2 evaluateStackedPosition(Vector2 position) { return position.add(getStackOffset()); } /** * Deep clones this hit object. * <br><br> * This method only deep clones fields that may be changed during difficulty calculation. * * @return The deep cloned hit object. */ public HitObject deepClone() { return null; } }
UTF-8
Java
4,263
java
HitObject.java
Java
[]
null
[]
package com.rian.difficultycalculator.beatmap.hitobject; import com.rian.difficultycalculator.math.Vector2; /** * Represents a hit object. */ public abstract class HitObject { /** * The radius of hit objects (i.e. the radius of a circle) relative to osu!standard. */ public static final float OBJECT_RADIUS = 64; /** * The time at which this hit object starts, in milliseconds. */ protected double startTime; /** * The position of this hit object. */ protected Vector2 position; /** * The end position of this hit object. */ protected Vector2 endPosition; /** * The stack height of this hit object. */ private int stackHeight; /** * The osu!standard scale of this hit object. */ private float scale; /** * @param startTime The time at which this hit object starts, in milliseconds. * @param position The position of the hit object relative to the play field. */ public HitObject(double startTime, Vector2 position) { this.startTime = startTime; this.position = position; endPosition = position; } /** * @param startTime The time at which this hit object starts, in milliseconds. * @param x The X position of the hit object relative to the play field. * @param y The Y position of the hit object relative to the play field. */ public HitObject(double startTime, float x, float y) { this(startTime, new Vector2(x, y)); } /** * Copy constructor. * * @param source The source to copy from. */ protected HitObject(HitObject source) { startTime = source.startTime; position = new Vector2(source.position.x, source.position.y); endPosition = new Vector2(source.endPosition.x, source.endPosition.y); stackHeight = source.stackHeight; scale = source.scale; } /** * Gets the osu!standard scale of this hit object. */ public float getScale() { return scale; } /** * Sets the osu!standard scale of this hit object. * * @param scale The new osu!standard scale. */ public void setScale(float scale) { this.scale = scale; } /** * Gets the time at which this hit object starts, in milliseconds. */ public double getStartTime() { return startTime; } /** * Gets the osu!standard stack height of this hit object. */ public int getStackHeight() { return stackHeight; } /** * Sets the osu!standard stack height of this hit object. * * @param stackHeight The new stack height. */ public void setStackHeight(int stackHeight) { this.stackHeight = stackHeight; } /** * Gets the position of this hit object. */ public Vector2 getPosition() { return position; } /** * Gets the end position of this hit object. */ public Vector2 getEndPosition() { return endPosition; } /** * Gets the radius of this hit object. */ public double getRadius() { return OBJECT_RADIUS * scale; } /** * Gets the stack offset vector of this hit object. */ public Vector2 getStackOffset() { return new Vector2(stackHeight * scale * -6.4f); } /** * Gets the stacked position of this hit object. */ public Vector2 getStackedPosition() { return evaluateStackedPosition(position); } /** * Gets the stacked end position of this slider. */ public Vector2 getStackedEndPosition() { return evaluateStackedPosition(endPosition); } /** * Evaluates a stacked position relative to this hit object. * * @return The evaluated stacked position. */ protected Vector2 evaluateStackedPosition(Vector2 position) { return position.add(getStackOffset()); } /** * Deep clones this hit object. * <br><br> * This method only deep clones fields that may be changed during difficulty calculation. * * @return The deep cloned hit object. */ public HitObject deepClone() { return null; } }
4,263
0.607319
0.602862
171
23.929825
23.875793
93
false
false
0
0
0
0
0
0
0.239766
false
false
11
9cce79b3d4bbcd9a6e39e352faee8e2b705ee33c
38,379,827,778,660
a267873b3fc5bf12b8d1c6acce230e8dd6cf0676
/src/main/java/com/tt/teach22/service/StudentService.java
3b5432a2a5f23b6a5f5013ece0a79bbb2b8c20fd
[]
no_license
ZhuJunGui/teach22
https://github.com/ZhuJunGui/teach22
4a3ea4bc926e5746441567262fe2a332914f799a
d07ae39f168dd395733b22542b9aa70cf38675eb
refs/heads/master
2020-04-18T02:20:45.523000
2019-01-23T10:35:15
2019-01-23T10:35:15
167,158,951
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.tt.teach22.service; import com.tt.teach22.pojo.Student; public interface StudentService { Student doLogin(Student student); }
UTF-8
Java
144
java
StudentService.java
Java
[]
null
[]
package com.tt.teach22.service; import com.tt.teach22.pojo.Student; public interface StudentService { Student doLogin(Student student); }
144
0.777778
0.75
7
19.571428
16.749048
37
false
false
0
0
0
0
0
0
0.428571
false
false
11
5f30bcc0229abd88cbc691fb8c354fd2d614e19e
39,350,490,404,901
4320c0495ede4a065267cc1b3bd708081f4c1c28
/src/main/java/net/zuobin/common/mail/MailSenderUtil.java
6a88d6523276a15f5ff3c2c72e6fb46938a27501
[]
no_license
ericzuobin/cancer
https://github.com/ericzuobin/cancer
f8032fec982632ff90b33cb02babbe9836590fb9
c2566ee968f8ba88696855b607d379565c57e453
refs/heads/master
2021-01-09T20:27:38.680000
2017-07-18T12:44:40
2017-07-18T12:44:40
63,317,492
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package net.zuobin.common.mail; import freemarker.template.Configuration; import freemarker.template.Template; import freemarker.template.TemplateException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.io.ClassPathResource; import org.springframework.mail.SimpleMailMessage; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.mail.javamail.MimeMessageHelper; import org.springframework.stereotype.Component; import org.springframework.ui.freemarker.FreeMarkerTemplateUtils; import org.springframework.util.StringUtils; import javax.mail.MessagingException; import javax.mail.internet.MimeMessage; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Map; /** * @author Sahinn * @date 16/7/22 */ @Component("mailSendUtil") public class MailSenderUtil { protected final Logger logger = LoggerFactory.getLogger(MailSenderUtil.class); @Autowired Configuration configuration; @Autowired (required = false) private JavaMailSender mailSender; public String generateEmailContentByFreeMarker(String templateName, Map<?, ?> map) { try { if (StringUtils.isEmpty(templateName)) { templateName = "mailDefault.ftl"; } Template template = configuration.getTemplate(templateName); return FreeMarkerTemplateUtils.processTemplateIntoString(template, map); } catch (TemplateException e) { logger.error("Error while processing FreeMarker template ", e); } catch (FileNotFoundException e) { logger.error("Error while open template file ", e); } catch (IOException e) { logger.error("Error while generate Email Content ", e); } return null; } /** * 发送邮件 * * @param emailAddresses * 收件人Email地址的数组 * @param fromEmail * 寄件人Email地址, null为默认寄件人web@vnvtrip.com * @param bodyText 邮件正文 * @param subject * 邮件主题 * @param attachmentName * 附件名 * @param resource * 附件 * @throws MessagingException */ public void sendMessageAndResource(String[] emailAddresses, String fromEmail, String bodyText, String subject, String attachmentName, ClassPathResource resource) throws MessagingException { MimeMessage message = mailSender.createMimeMessage(); // a multipart message MimeMessageHelper helper = null; helper = new MimeMessageHelper(message, true); helper.setTo(emailAddresses); if (fromEmail != null) { helper.setFrom(fromEmail); } helper.setText(bodyText, true); helper.setSubject(subject); if (attachmentName != null && resource != null) { helper.addAttachment(attachmentName, resource); } mailSender.send(message); } /** * 使用模版发送HTML格式的邮件 * * @param msg * 装有to,from,subject信息的SimpleMailMessage * @param templateName * 模版名,模版根路径已在配置文件定义于freemakarengine中 * @param model * 渲染模版所需的数据 */ public void send(SimpleMailMessage msg, String templateName, Map<?, ?> model) throws Exception { // 生成html邮件内容 String content = generateEmailContentByFreeMarker(templateName, model); MimeMessage mimeMsg = null; mimeMsg = mailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(mimeMsg, true, "utf-8"); helper.setTo(msg.getTo()); if (msg.getSubject() != null) helper.setSubject(msg.getSubject()); if (msg.getFrom() != null) helper.setFrom(msg.getFrom()); helper.setText(content, true); mailSender.send(mimeMsg); } /** * 使用模版发送HTML格式的邮件 * * @param emailAddresses * @param fromEmail * @param subject * 装有to,from,subject信息 * @param templateName * 模版名,模版根路径已在配置文件定义于freemakarengine中 * @param model * 渲染模版所需的数据 */ public void send(String[] emailAddresses, String fromEmail, String subject, String templateName, Map<?, ?> model) throws Exception { // 生成html邮件内容 String content = generateEmailContentByFreeMarker(templateName, model); MimeMessage mimeMsg = null; mimeMsg = mailSender.createMimeMessage(); MimeMessageHelper helper = null; helper = new MimeMessageHelper(mimeMsg, true); helper.setTo(emailAddresses); if (fromEmail != null) { helper.setFrom(fromEmail); } helper.setText(content, true); helper.setSubject(subject); mailSender.send(mimeMsg); } /** * 发送邮件 * * @param emailAddresses * 收件人Email地址的数组 * @param fromEmail * 寄件人Email地址, null为默认寄件人web@vnvtrip.com * @param bodyText 邮件正文 * @param subject * 邮件主题 * @throws MessagingException */ public void sendMessage(String[] emailAddresses, String fromEmail, String bodyText, String subject) throws MessagingException { MimeMessage message = mailSender.createMimeMessage(); // a multipart message MimeMessageHelper helper = null; helper = new MimeMessageHelper(message, true); helper.setTo(emailAddresses); if (fromEmail != null) { helper.setFrom(fromEmail); } helper.setText(bodyText, true); helper.setSubject(subject); mailSender.send(message); } public void send(SimpleMailMessage msg) throws Exception{ mailSender.send(msg); } }
UTF-8
Java
6,261
java
MailSenderUtil.java
Java
[ { "context": "IOException;\nimport java.util.Map;\n\n/**\n * @author Sahinn\n * @date 16/7/22\n */\n@Component(\"mailSendUtil\")\np", "end": 849, "score": 0.8477498888969421, "start": 843, "tag": "NAME", "value": "Sahinn" }, { "context": "fromEmail\n * 寄件人Email地址, null为默认寄件人web@vnvtrip.com * @param bodyText 邮件正文\n * @param subject\n ", "end": 2098, "score": 0.9999136328697205, "start": 2083, "tag": "EMAIL", "value": "web@vnvtrip.com" }, { "context": "fromEmail\n * 寄件人Email地址, null为默认寄件人web@vnvtrip.com * @param bodyText 邮件正文\n * @param subject\n ", "end": 5131, "score": 0.9990561604499817, "start": 5116, "tag": "EMAIL", "value": "web@vnvtrip.com" } ]
null
[]
package net.zuobin.common.mail; import freemarker.template.Configuration; import freemarker.template.Template; import freemarker.template.TemplateException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.io.ClassPathResource; import org.springframework.mail.SimpleMailMessage; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.mail.javamail.MimeMessageHelper; import org.springframework.stereotype.Component; import org.springframework.ui.freemarker.FreeMarkerTemplateUtils; import org.springframework.util.StringUtils; import javax.mail.MessagingException; import javax.mail.internet.MimeMessage; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Map; /** * @author Sahinn * @date 16/7/22 */ @Component("mailSendUtil") public class MailSenderUtil { protected final Logger logger = LoggerFactory.getLogger(MailSenderUtil.class); @Autowired Configuration configuration; @Autowired (required = false) private JavaMailSender mailSender; public String generateEmailContentByFreeMarker(String templateName, Map<?, ?> map) { try { if (StringUtils.isEmpty(templateName)) { templateName = "mailDefault.ftl"; } Template template = configuration.getTemplate(templateName); return FreeMarkerTemplateUtils.processTemplateIntoString(template, map); } catch (TemplateException e) { logger.error("Error while processing FreeMarker template ", e); } catch (FileNotFoundException e) { logger.error("Error while open template file ", e); } catch (IOException e) { logger.error("Error while generate Email Content ", e); } return null; } /** * 发送邮件 * * @param emailAddresses * 收件人Email地址的数组 * @param fromEmail * 寄件人Email地址, null为默认寄件人<EMAIL> * @param bodyText 邮件正文 * @param subject * 邮件主题 * @param attachmentName * 附件名 * @param resource * 附件 * @throws MessagingException */ public void sendMessageAndResource(String[] emailAddresses, String fromEmail, String bodyText, String subject, String attachmentName, ClassPathResource resource) throws MessagingException { MimeMessage message = mailSender.createMimeMessage(); // a multipart message MimeMessageHelper helper = null; helper = new MimeMessageHelper(message, true); helper.setTo(emailAddresses); if (fromEmail != null) { helper.setFrom(fromEmail); } helper.setText(bodyText, true); helper.setSubject(subject); if (attachmentName != null && resource != null) { helper.addAttachment(attachmentName, resource); } mailSender.send(message); } /** * 使用模版发送HTML格式的邮件 * * @param msg * 装有to,from,subject信息的SimpleMailMessage * @param templateName * 模版名,模版根路径已在配置文件定义于freemakarengine中 * @param model * 渲染模版所需的数据 */ public void send(SimpleMailMessage msg, String templateName, Map<?, ?> model) throws Exception { // 生成html邮件内容 String content = generateEmailContentByFreeMarker(templateName, model); MimeMessage mimeMsg = null; mimeMsg = mailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(mimeMsg, true, "utf-8"); helper.setTo(msg.getTo()); if (msg.getSubject() != null) helper.setSubject(msg.getSubject()); if (msg.getFrom() != null) helper.setFrom(msg.getFrom()); helper.setText(content, true); mailSender.send(mimeMsg); } /** * 使用模版发送HTML格式的邮件 * * @param emailAddresses * @param fromEmail * @param subject * 装有to,from,subject信息 * @param templateName * 模版名,模版根路径已在配置文件定义于freemakarengine中 * @param model * 渲染模版所需的数据 */ public void send(String[] emailAddresses, String fromEmail, String subject, String templateName, Map<?, ?> model) throws Exception { // 生成html邮件内容 String content = generateEmailContentByFreeMarker(templateName, model); MimeMessage mimeMsg = null; mimeMsg = mailSender.createMimeMessage(); MimeMessageHelper helper = null; helper = new MimeMessageHelper(mimeMsg, true); helper.setTo(emailAddresses); if (fromEmail != null) { helper.setFrom(fromEmail); } helper.setText(content, true); helper.setSubject(subject); mailSender.send(mimeMsg); } /** * 发送邮件 * * @param emailAddresses * 收件人Email地址的数组 * @param fromEmail * 寄件人Email地址, null为默认寄件人<EMAIL> * @param bodyText 邮件正文 * @param subject * 邮件主题 * @throws MessagingException */ public void sendMessage(String[] emailAddresses, String fromEmail, String bodyText, String subject) throws MessagingException { MimeMessage message = mailSender.createMimeMessage(); // a multipart message MimeMessageHelper helper = null; helper = new MimeMessageHelper(message, true); helper.setTo(emailAddresses); if (fromEmail != null) { helper.setFrom(fromEmail); } helper.setText(bodyText, true); helper.setSubject(subject); mailSender.send(message); } public void send(SimpleMailMessage msg) throws Exception{ mailSender.send(msg); } }
6,245
0.630204
0.628856
191
30.062828
25.056089
136
false
false
0
0
0
0
0
0
0.565445
false
false
11
1629fcc21f7625f15688b643b36191df491b0fc5
36,292,473,690,806
e8154376e44f4ceb8849ad1550b511cf0afc9786
/src/main/java/ublu/util/TN5250Helper.java
bab74ac9069ff0b21eff9e52f77d3218d7b97041
[ "LicenseRef-scancode-proprietary-license", "BSD-2-Clause", "BSD-3-Clause", "LicenseRef-scancode-warranty-disclaimer", "LicenseRef-scancode-free-unknown", "GPL-2.0-only", "JSON", "LicenseRef-scancode-unknown-license-reference" ]
permissive
jwoehr/ublu
https://github.com/jwoehr/ublu
0bf1ae8a35e4dc9034f52382769bff45444b3d53
5abe161bdfdfabc3e36c8aa9564fd12f7edb6ce2
refs/heads/main
2023-08-31T05:45:49.166000
2023-08-24T03:53:11
2023-08-24T03:53:11
51,802,764
19
4
BSD-2-Clause
false
2023-08-24T03:53:12
2016-02-16T02:45:46
2022-11-03T14:43:24
2023-08-24T03:53:11
28,821
13
3
2
Java
false
false
/* * Copyright (c) 2015, Absolute Performance, Inc. http://www.absolute-performance.com * Copyright (c) 2016, Jack J. Woehr jwoehr@softwoehr.com * SoftWoehr LLC PO Box 82, Beulah CO 81023-0082 http://www.softwoehr.com * 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. * * 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 HOLDER 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 ublu.util; import org.tn5250j.My5250; import org.tn5250j.framework.common.SessionManager; import org.tn5250j.tools.LangTool; import ublu.util.Generics.Session5250ArrayList; import ublu.util.Generics.StringArrayList; /** * A class to encapsulate tn5250j * * @author jwoehr */ public class TN5250Helper extends Thread { private My5250 my5250; /** * Return subapp instance * * @return subapp instance */ public My5250 getMy5250() { return my5250; } /** * Get subapp instance SessionManage * * @return subapp instance SessionManage */ public SessionManager getSessionManager() { return my5250.getSessionManager(); } ////////////////////////////// // Stuff for connect ////////////////////////////// private String system; // private String user; // private String password; private Generics.StringArrayList args; /** * Args to the subapp invocation * * @return Args to the subapp invocation */ public StringArrayList getArgs() { return args; } /** * Set Args to the subapp invocation * * @param args Args to the subapp invocation */ public void setArgs(StringArrayList args) { this.args = args; } /** * Instance with an empty array of args */ public TN5250Helper() { args = new Generics.StringArrayList(); } /** * Instance with a system name and an array of args * * @param system system name or ip * @param args array of args for subapp invocation */ public TN5250Helper(String system, StringArrayList args) { this(); this.system = system; this.args = args; } /** * * @param system */ public TN5250Helper(String system) { this(); this.system = system; } @Override public void run() { StringArrayList sal = new StringArrayList(system); sal.addAll(args); my5250 = new My5250(); /* Debug */ System.out.println("args to tn5250 : " + args); LangTool.init(); my5250.startNewUbluSession(sal.toStringArray()); } /** * Return list of Sessions in tn5250 * * @return list of Sessions in tn5250 */ public Session5250ArrayList getSessionList() { return new Session5250ArrayList(getSessionManager().getSessions().getSessionsList()); } @Override public String toString() { StringBuilder sb = new StringBuilder(super.toString()).append(" "); sb.append("System: ").append(system).append(" "); sb.append("Args : ").append(args).append(" "); return sb.toString(); } /** * Thread which can run an independent regular TN5250J instance * * @author jwoehr */ public static class My5250Thread extends Thread { /** * Create an instance of the full TN5250J emulator. Calls System.exit() * when it closes! * * @param name Name of thread * @param args Args to the emulator */ public My5250Thread(String name, String[] args) { super(name); this.args = args; } private String[] args = new String[0]; @Override public void run() { My5250.main(args); } } }
UTF-8
Java
4,946
java
TN5250Helper.java
Java
[ { "context": "ww.absolute-performance.com\n * Copyright (c) 2016, Jack J. Woehr jwoehr@softwoehr.com \n * SoftWoehr LLC PO Box 82,", "end": 125, "score": 0.9998833537101746, "start": 112, "tag": "NAME", "value": "Jack J. Woehr" }, { "context": "rformance.com\n * Copyright (c) 2016, Jack J. Woehr jwoehr@softwoehr.com \n * SoftWoehr LLC PO Box 82, Beulah CO 81023-0082", "end": 146, "score": 0.9999229907989502, "start": 126, "tag": "EMAIL", "value": "jwoehr@softwoehr.com" }, { "context": "**\n * A class to encapsulate tn5250j\n *\n * @author jwoehr\n */\npublic class TN5250Helper extends Thread {\n\n ", "end": 1834, "score": 0.999590277671814, "start": 1828, "tag": "USERNAME", "value": "jwoehr" }, { "context": "ent regular TN5250J instance\n *\n * @author jwoehr\n */\n public static class My5250Thread exte", "end": 4392, "score": 0.9995253086090088, "start": 4386, "tag": "USERNAME", "value": "jwoehr" } ]
null
[]
/* * Copyright (c) 2015, Absolute Performance, Inc. http://www.absolute-performance.com * Copyright (c) 2016, <NAME> <EMAIL> * SoftWoehr LLC PO Box 82, Beulah CO 81023-0082 http://www.softwoehr.com * 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. * * 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 HOLDER 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 ublu.util; import org.tn5250j.My5250; import org.tn5250j.framework.common.SessionManager; import org.tn5250j.tools.LangTool; import ublu.util.Generics.Session5250ArrayList; import ublu.util.Generics.StringArrayList; /** * A class to encapsulate tn5250j * * @author jwoehr */ public class TN5250Helper extends Thread { private My5250 my5250; /** * Return subapp instance * * @return subapp instance */ public My5250 getMy5250() { return my5250; } /** * Get subapp instance SessionManage * * @return subapp instance SessionManage */ public SessionManager getSessionManager() { return my5250.getSessionManager(); } ////////////////////////////// // Stuff for connect ////////////////////////////// private String system; // private String user; // private String password; private Generics.StringArrayList args; /** * Args to the subapp invocation * * @return Args to the subapp invocation */ public StringArrayList getArgs() { return args; } /** * Set Args to the subapp invocation * * @param args Args to the subapp invocation */ public void setArgs(StringArrayList args) { this.args = args; } /** * Instance with an empty array of args */ public TN5250Helper() { args = new Generics.StringArrayList(); } /** * Instance with a system name and an array of args * * @param system system name or ip * @param args array of args for subapp invocation */ public TN5250Helper(String system, StringArrayList args) { this(); this.system = system; this.args = args; } /** * * @param system */ public TN5250Helper(String system) { this(); this.system = system; } @Override public void run() { StringArrayList sal = new StringArrayList(system); sal.addAll(args); my5250 = new My5250(); /* Debug */ System.out.println("args to tn5250 : " + args); LangTool.init(); my5250.startNewUbluSession(sal.toStringArray()); } /** * Return list of Sessions in tn5250 * * @return list of Sessions in tn5250 */ public Session5250ArrayList getSessionList() { return new Session5250ArrayList(getSessionManager().getSessions().getSessionsList()); } @Override public String toString() { StringBuilder sb = new StringBuilder(super.toString()).append(" "); sb.append("System: ").append(system).append(" "); sb.append("Args : ").append(args).append(" "); return sb.toString(); } /** * Thread which can run an independent regular TN5250J instance * * @author jwoehr */ public static class My5250Thread extends Thread { /** * Create an instance of the full TN5250J emulator. Calls System.exit() * when it closes! * * @param name Name of thread * @param args Args to the emulator */ public My5250Thread(String name, String[] args) { super(name); this.args = args; } private String[] args = new String[0]; @Override public void run() { My5250.main(args); } } }
4,926
0.63708
0.609583
168
28.440475
25.154688
93
false
false
0
0
0
0
0
0
0.380952
false
false
11
00d70d979082b460a6e04d8f0d5ba774a9118bea
37,761,352,494,713
ca8629baa1160347637d733b5c7aa547298f54cd
/src/java_20210503/WhileDemo.java
4c06b8c03e81b82edbb854d5ab180236607c451f
[]
no_license
lsb4740/Java_Fundamental
https://github.com/lsb4740/Java_Fundamental
418a9788cd0f6aa2588cba3c0c236900a61e0ac9
318535f9d2c3e62616f7a9018ef0e2528141610e
refs/heads/master
2023-04-29T00:24:08.576000
2021-05-14T02:36:53
2021-05-14T02:36:53
363,824,784
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package java_20210503; public class WhileDemo { public static void main(String[] args) { int sum = 0; int i = 1; // 초기값 while (i <= 10) { // 조건 sum += i; i++;// 증감 } System.out.printf("1부터 10까지의 합은 %d 입니다.\n", sum); int j = 1; sum = 0; for (; j <= 10;) { sum += j; j++; } System.out.printf("1부터 10까지의 합은 %d 입니다.\n", sum); // while을 사용한 구구단 만들기 int first = 1; while (first <= 10) { System.err.println(first + "단입니다"); int second = 1; while (second <= 10) { System.out.printf("%dX%d:%d%n", first, second, first * second); second++; } first++; } } }
UTF-8
Java
696
java
WhileDemo.java
Java
[]
null
[]
package java_20210503; public class WhileDemo { public static void main(String[] args) { int sum = 0; int i = 1; // 초기값 while (i <= 10) { // 조건 sum += i; i++;// 증감 } System.out.printf("1부터 10까지의 합은 %d 입니다.\n", sum); int j = 1; sum = 0; for (; j <= 10;) { sum += j; j++; } System.out.printf("1부터 10까지의 합은 %d 입니다.\n", sum); // while을 사용한 구구단 만들기 int first = 1; while (first <= 10) { System.err.println(first + "단입니다"); int second = 1; while (second <= 10) { System.out.printf("%dX%d:%d%n", first, second, first * second); second++; } first++; } } }
696
0.527687
0.482085
34
17.058823
16.089714
67
false
false
0
0
0
0
0
0
2.588235
false
false
11
cb591e5e6ad075fee0be6d46b560e17fcc35f98c
39,067,022,539,911
34182a13cd6291fc4657546e196c6447553b5eb0
/corejava/corejava_1/src/main/java/com/xubh01/sort/innerType/Demo02.java
d68a360a55183dfe875c0a0d9f9d9dd8cb3a8aeb
[]
no_license
786991884/sxnd-study
https://github.com/786991884/sxnd-study
9bf3d417879680f94b012867ef71ba880a19e4fc
8c1f8e8823c077f095dc4be0c89522b6f0eb1457
refs/heads/master
2021-01-12T08:49:59.493000
2018-04-03T09:17:54
2018-04-03T09:17:54
76,701,131
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.xubh01.sort.innerType; import java.util.Arrays; public class Demo02 { public static void main(String[] args) { String[] arr = {"a", "abcd", "abc", "def"}; //从到小排序 降序 boolean sorted = true; int len = arr.length; for (int j = 0; j < len - 1; j++) { //趟数 sorted = true; //假定有序 for (int i = 0; i < len - 1 - j; i++) { //次数 if (((Comparable) arr[i]).compareTo(arr[i + 1]) < 0) { String temp = arr[i]; arr[i] = arr[i + 1]; arr[i + 1] = temp; sorted = false; //假定失败 } } if (sorted) { //减少趟数 break; } } System.out.println(Arrays.toString(arr)); } }
UTF-8
Java
856
java
Demo02.java
Java
[]
null
[]
package com.xubh01.sort.innerType; import java.util.Arrays; public class Demo02 { public static void main(String[] args) { String[] arr = {"a", "abcd", "abc", "def"}; //从到小排序 降序 boolean sorted = true; int len = arr.length; for (int j = 0; j < len - 1; j++) { //趟数 sorted = true; //假定有序 for (int i = 0; i < len - 1 - j; i++) { //次数 if (((Comparable) arr[i]).compareTo(arr[i + 1]) < 0) { String temp = arr[i]; arr[i] = arr[i + 1]; arr[i + 1] = temp; sorted = false; //假定失败 } } if (sorted) { //减少趟数 break; } } System.out.println(Arrays.toString(arr)); } }
856
0.407407
0.392593
30
26
19.197222
70
false
false
0
0
0
0
0
0
0.633333
false
false
11
50f7b08ddc3f382a916681fe21befc3f6f38d2cd
35,175,782,210,291
38fc4a0be654948d34a26e59b8c58fcf1140788e
/src/test/java/de/krueger/pierre/nimspiel/nim/NimControllerTest.java
294ad686d14d1539bf3a2af0193e0d1e3986eebc
[]
no_license
pkrger/nim-spiel
https://github.com/pkrger/nim-spiel
96030ed8419378dafda8675263ddec0b3f26cb26
783476999ed6543d3ac0d88272c6d2d6393c3c5c
refs/heads/main
2023-03-01T10:06:37.375000
2021-02-02T12:31:17
2021-02-02T12:31:17
335,280,148
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package de.krueger.pierre.nimspiel.nim; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.http.MediaType; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import static org.mockito.BDDMockito.given; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @RunWith(SpringRunner.class) @WebMvcTest(NimController.class) public class NimControllerTest { @Autowired private MockMvc mockMvc; @MockBean private NimService nimService; @Autowired private ObjectMapper objectMapper; private NimRequest nimRequest = new NimRequest(); @Before public void setUp() { nimRequest.setCountMatches(1); } /** * Testet die Init-Methode und erwartet einen 200 OK. */ @Test public void initTest() throws Exception { given(nimService.init()).willReturn(new NimResponse(0, "Test")); mockMvc.perform(get("/play")) .andExpect(status().isOk()); } /** * Testet die Play-Methode und erwartet einen 200 OK. */ @Test public void playTest() throws Exception { given(nimService.play(nimRequest)).willReturn(new NimResponse(0, "Test")); mockMvc.perform(post("/play").contentType(MediaType.APPLICATION_JSON).content(objectMapper.writeValueAsBytes(nimRequest))) .andExpect(status().isOk()); } }
UTF-8
Java
1,832
java
NimControllerTest.java
Java
[]
null
[]
package de.krueger.pierre.nimspiel.nim; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.http.MediaType; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import static org.mockito.BDDMockito.given; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @RunWith(SpringRunner.class) @WebMvcTest(NimController.class) public class NimControllerTest { @Autowired private MockMvc mockMvc; @MockBean private NimService nimService; @Autowired private ObjectMapper objectMapper; private NimRequest nimRequest = new NimRequest(); @Before public void setUp() { nimRequest.setCountMatches(1); } /** * Testet die Init-Methode und erwartet einen 200 OK. */ @Test public void initTest() throws Exception { given(nimService.init()).willReturn(new NimResponse(0, "Test")); mockMvc.perform(get("/play")) .andExpect(status().isOk()); } /** * Testet die Play-Methode und erwartet einen 200 OK. */ @Test public void playTest() throws Exception { given(nimService.play(nimRequest)).willReturn(new NimResponse(0, "Test")); mockMvc.perform(post("/play").contentType(MediaType.APPLICATION_JSON).content(objectMapper.writeValueAsBytes(nimRequest))) .andExpect(status().isOk()); } }
1,832
0.770742
0.765284
61
29.032787
28.802303
126
false
false
0
0
0
0
0
0
0.42623
false
false
11
f205e2cba962717dd9f6dc042b995d82ee3cf2d8
4,535,485,535,048
406993a7f0aa1d8b5904ed1ef1050664a0d8f87f
/8.8 Permutations with Duplicates/Solution2.java
cf98dee603cb1370121db02115c06fb1c0ee2103
[]
no_license
Edward-Saf/Cracking_the_Coding_Interview
https://github.com/Edward-Saf/Cracking_the_Coding_Interview
f5eb715c20a797de9ac5e843025232aae14d0edd
7b952fdf6cf28619655911cf59e08caab7def5ae
refs/heads/master
2020-03-26T03:32:52.963000
2018-09-01T17:07:37
2018-09-01T17:07:37
144,460,039
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.util.ArrayList; import java.util.HashMap; public class Solution2 { public static HashMap<Character, Integer> buildFreqTable(String s) { HashMap<Character, Integer> map = new HashMap(); for (char c : s.toCharArray()) { if (!map.containsKey(c)) { map.put(c, 0); } map.put(c, map.get(c) + 1); } return map; } public static void printPerms(HashMap<Character, Integer> map, String prefix, int remaining, ArrayList<String> result) { if (remaining == 0) { result.add(prefix); return; } for (Character c : map.keySet()) { int count = map.get(c); if (count > 0) { map.put(c, count - 1); printPerms(map, prefix + c, remaining - 1, result); map.put(c, count); } } } public static ArrayList<String> printPerms(String s) { ArrayList<String> result = new ArrayList(); HashMap<Character, Integer> map = buildFreqTable(s); printPerms(map, "", s.length(), result); return result; } public static void main(String[] args) { long _t0 = System.nanoTime(); ArrayList<String> result = printPerms("aabbccc"); long _t1 = System.nanoTime(); System.out.println("Count: " + result.size() + " -> " + result); System.out.printf("%.3f" + " ms\n\n", (double) (_t1 - _t0) / 1000000); _t0 = System.nanoTime(); result = printPerms("aaaaa"); _t1 = System.nanoTime(); System.out.println("Count: " + result.size() + " -> " + result); System.out.printf("%.3f" + " ms\n\n", (double) (_t1 - _t0) / 1000000); _t0 = System.nanoTime(); result = printPerms(""); _t1 = System.nanoTime(); System.out.println("Count: " + result.size() + " -> " + result); System.out.printf("%.3f" + " ms\n\n", (double) (_t1 - _t0) / 1000000); _t0 = System.nanoTime(); result = printPerms("abcde"); _t1 = System.nanoTime(); System.out.println("Count: " + result.size() + " -> " + result); System.out.printf("%.3f" + " ms\n", (double) (_t1 - _t0) / 1000000); } }
UTF-8
Java
2,335
java
Solution2.java
Java
[]
null
[]
import java.util.ArrayList; import java.util.HashMap; public class Solution2 { public static HashMap<Character, Integer> buildFreqTable(String s) { HashMap<Character, Integer> map = new HashMap(); for (char c : s.toCharArray()) { if (!map.containsKey(c)) { map.put(c, 0); } map.put(c, map.get(c) + 1); } return map; } public static void printPerms(HashMap<Character, Integer> map, String prefix, int remaining, ArrayList<String> result) { if (remaining == 0) { result.add(prefix); return; } for (Character c : map.keySet()) { int count = map.get(c); if (count > 0) { map.put(c, count - 1); printPerms(map, prefix + c, remaining - 1, result); map.put(c, count); } } } public static ArrayList<String> printPerms(String s) { ArrayList<String> result = new ArrayList(); HashMap<Character, Integer> map = buildFreqTable(s); printPerms(map, "", s.length(), result); return result; } public static void main(String[] args) { long _t0 = System.nanoTime(); ArrayList<String> result = printPerms("aabbccc"); long _t1 = System.nanoTime(); System.out.println("Count: " + result.size() + " -> " + result); System.out.printf("%.3f" + " ms\n\n", (double) (_t1 - _t0) / 1000000); _t0 = System.nanoTime(); result = printPerms("aaaaa"); _t1 = System.nanoTime(); System.out.println("Count: " + result.size() + " -> " + result); System.out.printf("%.3f" + " ms\n\n", (double) (_t1 - _t0) / 1000000); _t0 = System.nanoTime(); result = printPerms(""); _t1 = System.nanoTime(); System.out.println("Count: " + result.size() + " -> " + result); System.out.printf("%.3f" + " ms\n\n", (double) (_t1 - _t0) / 1000000); _t0 = System.nanoTime(); result = printPerms("abcde"); _t1 = System.nanoTime(); System.out.println("Count: " + result.size() + " -> " + result); System.out.printf("%.3f" + " ms\n", (double) (_t1 - _t0) / 1000000); } }
2,335
0.504497
0.480942
66
33.348484
26.601715
124
false
false
0
0
0
0
0
0
0.863636
false
false
11
222dd7ee7607c8e3a93217295c0993e028e0948f
17,824,114,300,568
08df5d055b5eedd502d773609338595252105e8f
/NBA/src/main/java/businesslogic/playerbl/PlayerBLController.java
e342eeec99c4145e701dc191bb9198c4dec1bc27
[]
no_license
cristph/NBA_SE-III
https://github.com/cristph/NBA_SE-III
5fb1c3f1e1f252a8da19860021db323cc4cfdf00
c6a0d812176e7998b84ec616a2e3b59ac59eda67
refs/heads/master
2016-09-05T22:14:46.380000
2016-03-08T08:26:33
2016-03-08T08:26:33
31,887,510
4
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package businesslogic.playerbl; import java.util.ArrayList; import businesslogicservice.playerblservice.PlayerBLService; import test.data.PlayerHighInfo; import test.data.PlayerHotInfo; import test.data.PlayerKingInfo; import test.data.PlayerNormalInfo; import value.PlayerStandard; import value.Value.Age; import value.Value.Field; import value.Value.League; import value.Value.Order; import value.Value.Position; import vo.PlayerVO; public class PlayerBLController implements PlayerBLService{ PlayerCalculate pc; public PlayerBLController(){ pc=new PlayerCalculate(); } /* * now begin new lines * @date 2015-4-13 */ /* * 获取进步最快球员 * @param field:排序依据,可取值Field枚举类 * @param num:返回球员个数 * @return ArrayList<PlayerHotInfo> */ public ArrayList<PlayerHotInfo> getHotPlayer(Field field,int num){ ArrayList<PlayerHotInfo> list=pc.getHotPlayer(field, num); return list; } /* * 获取当天热点球员 * @param field:排序依据,可取值Field枚举类 * @param num:返回球员个数 * @return ArrayList<PlayerKingInfo> */ public ArrayList<PlayerKingInfo> getSeasonKingPlayer(Field field,int num){ ArrayList<PlayerKingInfo> list=pc.getSeasonKingPlayer(field, num); return list; } /* * 获取赛季热点球员 * @param field:排序依据,可取值Field枚举类 * @param num:返回球员个数 * @return ArrayList<PlayerKingInfo> */ public ArrayList<PlayerKingInfo> getDailyKingPlayer(Field field,int num){ ArrayList<PlayerKingInfo> list=pc.getDailyKingPlayer(field, num); return list; } /* * 获取球员赛季高阶数据 * @param ps 排序依据,枚举类 * @param order 排序方式(升序/降序) * @param num 返回 球员个数 * @return ArrayList<PlayerHighInfo> */ public ArrayList<PlayerHighInfo> getPlayerHighInfo(PlayerStandard ps,Order order,int num){ ArrayList<PlayerHighInfo> list=pc.getPlayerHighInfo(ps, order, num); return list; } /* * 获取球员赛季 平均 基本数据 * @param pos 筛选条件:位置 * @param lea 筛选条件:赛区 * @param age 筛选条件:年龄 * @param ps 排序依据,枚举类 * @param order 排序方式(升序/降序) * @param num 返回 球员个数 * @return ArrayList<PlayerNormalInfo> */ public ArrayList<PlayerNormalInfo> getPlayerAvgNormalInfo(Position pos,League lea,Age age, PlayerStandard ps,Order order,int num){ ArrayList<PlayerNormalInfo> list=pc.getPlayerAvgNormalInfo(pos, lea, age, ps, order, num); return list; } /* * 获取球员赛季 总和 基本数据 * @param pos 筛选条件:位置 * @param lea 筛选条件:赛区 * @param age 筛选条件:年龄 * @param ps 排序依据,枚举类 * @param order 排序方式(升序/降序) * @param num 返回 球员个数 * @return ArrayList<PlayerNormalInfo> */ public ArrayList<PlayerNormalInfo> getPlayerTotalNormalInfo(Position pos,League lea,Age age, PlayerStandard ps,Order order,int num){ ArrayList<PlayerNormalInfo> list=pc.getPlayerTotalNormalInfo(pos, lea, age, ps, order, num); return list; } /* * 获取球员基本信息,如身高体重、照片等 * @param name:球员名 * @return PlayerVO */ public PlayerVO getPlayerInfo(String name){ PlayerVO pv=pc.getPlayerInfo(name); return pv; } public PlayerNormalInfo getSinglePlayerNormalInfo(String name) { // TODO Auto-generated method stub PlayerNormalInfo pni=pc.getSinglePlayerNormalInfo(name); return pni; } public PlayerHighInfo getSinglePlayerHighInfo(String name) { // TODO Auto-generated method stub PlayerHighInfo phi=pc.getSinglePlayerHighInfo(name); return phi; } }
UTF-8
Java
3,725
java
PlayerBLController.java
Java
[]
null
[]
package businesslogic.playerbl; import java.util.ArrayList; import businesslogicservice.playerblservice.PlayerBLService; import test.data.PlayerHighInfo; import test.data.PlayerHotInfo; import test.data.PlayerKingInfo; import test.data.PlayerNormalInfo; import value.PlayerStandard; import value.Value.Age; import value.Value.Field; import value.Value.League; import value.Value.Order; import value.Value.Position; import vo.PlayerVO; public class PlayerBLController implements PlayerBLService{ PlayerCalculate pc; public PlayerBLController(){ pc=new PlayerCalculate(); } /* * now begin new lines * @date 2015-4-13 */ /* * 获取进步最快球员 * @param field:排序依据,可取值Field枚举类 * @param num:返回球员个数 * @return ArrayList<PlayerHotInfo> */ public ArrayList<PlayerHotInfo> getHotPlayer(Field field,int num){ ArrayList<PlayerHotInfo> list=pc.getHotPlayer(field, num); return list; } /* * 获取当天热点球员 * @param field:排序依据,可取值Field枚举类 * @param num:返回球员个数 * @return ArrayList<PlayerKingInfo> */ public ArrayList<PlayerKingInfo> getSeasonKingPlayer(Field field,int num){ ArrayList<PlayerKingInfo> list=pc.getSeasonKingPlayer(field, num); return list; } /* * 获取赛季热点球员 * @param field:排序依据,可取值Field枚举类 * @param num:返回球员个数 * @return ArrayList<PlayerKingInfo> */ public ArrayList<PlayerKingInfo> getDailyKingPlayer(Field field,int num){ ArrayList<PlayerKingInfo> list=pc.getDailyKingPlayer(field, num); return list; } /* * 获取球员赛季高阶数据 * @param ps 排序依据,枚举类 * @param order 排序方式(升序/降序) * @param num 返回 球员个数 * @return ArrayList<PlayerHighInfo> */ public ArrayList<PlayerHighInfo> getPlayerHighInfo(PlayerStandard ps,Order order,int num){ ArrayList<PlayerHighInfo> list=pc.getPlayerHighInfo(ps, order, num); return list; } /* * 获取球员赛季 平均 基本数据 * @param pos 筛选条件:位置 * @param lea 筛选条件:赛区 * @param age 筛选条件:年龄 * @param ps 排序依据,枚举类 * @param order 排序方式(升序/降序) * @param num 返回 球员个数 * @return ArrayList<PlayerNormalInfo> */ public ArrayList<PlayerNormalInfo> getPlayerAvgNormalInfo(Position pos,League lea,Age age, PlayerStandard ps,Order order,int num){ ArrayList<PlayerNormalInfo> list=pc.getPlayerAvgNormalInfo(pos, lea, age, ps, order, num); return list; } /* * 获取球员赛季 总和 基本数据 * @param pos 筛选条件:位置 * @param lea 筛选条件:赛区 * @param age 筛选条件:年龄 * @param ps 排序依据,枚举类 * @param order 排序方式(升序/降序) * @param num 返回 球员个数 * @return ArrayList<PlayerNormalInfo> */ public ArrayList<PlayerNormalInfo> getPlayerTotalNormalInfo(Position pos,League lea,Age age, PlayerStandard ps,Order order,int num){ ArrayList<PlayerNormalInfo> list=pc.getPlayerTotalNormalInfo(pos, lea, age, ps, order, num); return list; } /* * 获取球员基本信息,如身高体重、照片等 * @param name:球员名 * @return PlayerVO */ public PlayerVO getPlayerInfo(String name){ PlayerVO pv=pc.getPlayerInfo(name); return pv; } public PlayerNormalInfo getSinglePlayerNormalInfo(String name) { // TODO Auto-generated method stub PlayerNormalInfo pni=pc.getSinglePlayerNormalInfo(name); return pni; } public PlayerHighInfo getSinglePlayerHighInfo(String name) { // TODO Auto-generated method stub PlayerHighInfo phi=pc.getSinglePlayerHighInfo(name); return phi; } }
3,725
0.736484
0.734322
130
23.907692
23.352631
94
false
false
0
0
0
0
0
0
1.530769
false
false
11
06a5816766495c7a04372c145708857be23e9eed
27,315,992,031,719
2e74562f5f72b37cf460f4436f5053a3b670dd6c
/src/main/java/com/challenge/model/Persona.java
da5a93433e05a07f45bfef16e7832de9660a59ff
[]
no_license
dalexander1992/Challenge
https://github.com/dalexander1992/Challenge
ce416b067ed411dc9c85c24f33d2b475c6f77859
0a5c16dfd5d897bc2bea9c83597b5cf31d1c244f
refs/heads/master
2021-01-19T05:03:29.394000
2015-08-24T04:56:18
2015-08-24T04:56:18
41,279,500
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.challenge.model; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; /** * @author David A. Artavia Cerdas * dalexander1992@gmail.com * 87872624 */ @SuppressWarnings("serial") @Entity @Table(name="persona") public class Persona implements Serializable { @Id @Column(name="ID") private String id; @Column(name="NOMBRE") private String nombre; @Column(name="APELLIDOS") private String apellidos; @Column(name="TELEFONO") private String telefono; @Column(name="DIRECCION") private String direccion; @Column(name="CORREO") private String correo; /** * @return the id */ public String getId() { return id; } /** * @param id the id to set */ public void setId(String id) { this.id = id; } /** * @return the nombre */ public String getNombre() { return nombre; } /** * @param nombre the nombre to set */ public void setNombre(String nombre) { this.nombre = nombre; } /** * @return the apellidos */ public String getApellidos() { return apellidos; } /** * @param apellidos the apellidos to set */ public void setApellidos(String apellidos) { this.apellidos = apellidos; } /** * @return the telefono */ public String getTelefono() { return telefono; } /** * @param telefono the telefono to set */ public void setTelefono(String telefono) { this.telefono = telefono; } /** * @return the direccion */ public String getDireccion() { return direccion; } /** * @param direccion the direccion to set */ public void setDireccion(String direccion) { this.direccion = direccion; } /** * @return the correo */ public String getCorreo() { return correo; } /** * @param correo the correo to set */ public void setCorreo(String correo) { this.correo = correo; } }
UTF-8
Java
1,914
java
Persona.java
Java
[ { "context": "d;\nimport javax.persistence.Table;\n\n/**\n * @author David A. Artavia Cerdas \n * dalexander1992@gmail.com\n * 87872624\n */\n@Sup", "end": 226, "score": 0.9990460276603699, "start": 203, "tag": "NAME", "value": "David A. Artavia Cerdas" }, { "context": "Table;\n\n/**\n * @author David A. Artavia Cerdas \n * dalexander1992@gmail.com\n * 87872624\n */\n@SuppressWarnings(\"serial\")\n@Enti", "end": 255, "score": 0.9999213814735413, "start": 231, "tag": "EMAIL", "value": "dalexander1992@gmail.com" } ]
null
[]
package com.challenge.model; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; /** * @author <NAME> * <EMAIL> * 87872624 */ @SuppressWarnings("serial") @Entity @Table(name="persona") public class Persona implements Serializable { @Id @Column(name="ID") private String id; @Column(name="NOMBRE") private String nombre; @Column(name="APELLIDOS") private String apellidos; @Column(name="TELEFONO") private String telefono; @Column(name="DIRECCION") private String direccion; @Column(name="CORREO") private String correo; /** * @return the id */ public String getId() { return id; } /** * @param id the id to set */ public void setId(String id) { this.id = id; } /** * @return the nombre */ public String getNombre() { return nombre; } /** * @param nombre the nombre to set */ public void setNombre(String nombre) { this.nombre = nombre; } /** * @return the apellidos */ public String getApellidos() { return apellidos; } /** * @param apellidos the apellidos to set */ public void setApellidos(String apellidos) { this.apellidos = apellidos; } /** * @return the telefono */ public String getTelefono() { return telefono; } /** * @param telefono the telefono to set */ public void setTelefono(String telefono) { this.telefono = telefono; } /** * @return the direccion */ public String getDireccion() { return direccion; } /** * @param direccion the direccion to set */ public void setDireccion(String direccion) { this.direccion = direccion; } /** * @return the correo */ public String getCorreo() { return correo; } /** * @param correo the correo to set */ public void setCorreo(String correo) { this.correo = correo; } }
1,880
0.663532
0.657262
123
14.552846
13.815982
46
false
false
0
0
0
0
0
0
1.04065
false
false
11
edfadd867c86a888e4494295566a7681070856f7
12,189,117,196,995
bdea62f524ceff610c16206a5ace6dac2454698d
/app/src/main/java/unimelb/cis/spatialanalytics/sensorreader/views/CustomizedTImePicker.java
87134e51e8ab631e507b7676c5e3e2bec4514a96
[]
no_license
lsx1988/SensorReader
https://github.com/lsx1988/SensorReader
ac4c1890e2268a4ca8fabc640965a1eade93f5d8
d90aa740b19bf7f4bcc94c8da98f7570ab5bd180
refs/heads/master
2020-06-10T19:25:53.966000
2016-12-08T05:11:26
2016-12-08T05:11:26
75,897,218
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package unimelb.cis.spatialanalytics.sensorreader.views; import android.widget.TimePicker; import unimelb.cis.spatialanalytics.sensorreader.config.SettingConfig; /** * Created by hanl4 on 24/03/2015. */ public class CustomizedTimePicker { private TimePicker timePicker; private static int hour; private static int minute; public CustomizedTimePicker(TimePicker timePicker) { this.timePicker=timePicker; ini(); timePicker.setOnTimeChangedListener(new TimePicker.OnTimeChangedListener() { @Override public void onTimeChanged(TimePicker view, int hourOfDay, int min) { hour=hourOfDay; minute=min; } }); } /** * save the times to the pref */ public static boolean setClockTimes() { return SettingConfig.setClock(hour, minute); } public int getHour() { return hour; } public int getMinute() { return minute; } public TimePicker getTimePicker() { return this.timePicker; } /** * initialize the values of the clock */ public void ini() { timePicker.setCurrentHour(SettingConfig.getClockHour()); timePicker.setCurrentMinute(SettingConfig.getClockMinute()); } }
UTF-8
Java
1,408
java
CustomizedTImePicker.java
Java
[ { "context": "reader.config.SettingConfig;\r\n\r\n/**\r\n * Created by hanl4 on 24/03/2015.\r\n */\r\npublic class CustomizedTimeP", "end": 195, "score": 0.9995566010475159, "start": 190, "tag": "USERNAME", "value": "hanl4" } ]
null
[]
package unimelb.cis.spatialanalytics.sensorreader.views; import android.widget.TimePicker; import unimelb.cis.spatialanalytics.sensorreader.config.SettingConfig; /** * Created by hanl4 on 24/03/2015. */ public class CustomizedTimePicker { private TimePicker timePicker; private static int hour; private static int minute; public CustomizedTimePicker(TimePicker timePicker) { this.timePicker=timePicker; ini(); timePicker.setOnTimeChangedListener(new TimePicker.OnTimeChangedListener() { @Override public void onTimeChanged(TimePicker view, int hourOfDay, int min) { hour=hourOfDay; minute=min; } }); } /** * save the times to the pref */ public static boolean setClockTimes() { return SettingConfig.setClock(hour, minute); } public int getHour() { return hour; } public int getMinute() { return minute; } public TimePicker getTimePicker() { return this.timePicker; } /** * initialize the values of the clock */ public void ini() { timePicker.setCurrentHour(SettingConfig.getClockHour()); timePicker.setCurrentMinute(SettingConfig.getClockMinute()); } }
1,408
0.590199
0.583807
69
18.347826
21.759439
84
false
false
0
0
0
0
0
0
0.289855
false
false
11
fe5bf4bb9a0faf2c99f4fb41700d867260157128
16,045,997,826,866
7caf5dbf816be2cddb0794350ed7e6133b963acf
/blatt6/src/Spiel.java
c8480c9224a824ba5c7be04d15cda9fd3640efa7
[]
no_license
domso/infouebung
https://github.com/domso/infouebung
ffbcac1c3a2163962eecdc6741b234e1343c9257
e537eabf550487151540668e1fab3b27180515f4
refs/heads/master
2016-09-11T09:41:38.925000
2014-06-24T18:05:39
2014-06-24T18:05:39
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
public class Spiel { public static final int WASSER = 0; public static final int TREFFER = 1; public static final int SCHUSS = 2; public static final int VERSENKT = 3; public static final int ENDE = 4; private static int maxVersuche = 1000000; private int feldlaenge; private Spieler spieler; private Konfiguration konfiguration; private Spielfeld spielfeld; private SchiffContainer sc; private Punkt[] schiff; public Spiel(Spieler spieler, Konfiguration konfiguration) { setLinkKonfiguration(konfiguration); feldlaenge = getLinkKonfiguration().getFeldlaenge(); spielfeld = new Spielfeld(feldlaenge); setLinkSpieler(spieler); sc = SchiffContainer.instance(); init(); for (int i = getLinkKonfiguration().getMaxSchifflaenge(); i >= getLinkKonfiguration() .getMinSchifflaenge(); --i) { if (increment(i) == false) { System.out.println("Zu viele Schiffe"); return; } } setzeSchiffe(); } public Konfiguration getLinkKonfiguration() { return konfiguration; } public void setLinkKonfiguration(Konfiguration konfiguration) { this.konfiguration = konfiguration; } public Spieler getLinkSpieler() { return spieler; } public void setLinkSpieler(Spieler spieler) { this.spieler = spieler; } public Spielfeld getLinkSpielfeld() { return spielfeld; } private Punkt[] createSchiff(int laenge) { int zeile, spalte, ausrichtung; schiff = new Punkt[laenge]; zeile = (int) random(0, feldlaenge - 1); spalte = (int) random(0, feldlaenge - 1); ausrichtung = (int) random(0, 3); int i; switch (ausrichtung) { // links case 0: for (i = 0; i < laenge; i++) { schiff[i] = new Punkt(zeile, spalte - laenge + 1 + i); } break; // rechts case 1: for (i = 0; i < laenge; i++) { schiff[i] = new Punkt(zeile, spalte + i); } break; // oben case 2: for (i = 0; i < laenge; i++) { schiff[i] = new Punkt(zeile - laenge + 1 + i, spalte); } break; // unten case 3: for (i = 0; i < laenge; i++) { schiff[i] = new Punkt(zeile + i, spalte); } break; } return schiff; } private boolean increment(int laenge) { Punkt[] schiff; int i = 0; do { schiff = createSchiff(laenge); ++i; } while (positionOk(schiff) == false && i < maxVersuche); if (i < maxVersuche) { Schiff s = new Schiff(schiff); sc.addAlleSchiffe(s); return true; } else return false; } private void init() { int i, j; for (i = 0; i < getLinkKonfiguration().getFeldlaenge(); i++) { for (j = 0; j < getLinkKonfiguration().getFeldlaenge(); j++) { getLinkSpielfeld().setFeld(i, j, Spielfeld.WASSER); } } } private boolean positionOk(Punkt[] schiff) { if (grenze(schiff) == true) return false; if (konflikt(schiff) == true) return false; if (nachbar(schiff) == true) return false; return true; } private void setzeSchiffe() { for (Schiff s : sc) { for (int n = 0; n < s.getLaenge(); n++) { Teil[] akt = s.getTeile(); for (int i = 0; i < akt.length; i++) { getLinkSpielfeld().setFeld(akt[i].getPosition().getX(), akt[i].getPosition().getY(), Spielfeld.SCHIFF); } } } } private boolean grenze(Punkt[] schiff) { return ((schiff[0].getX() < 0) || (schiff[0].getY() < 0) || (schiff[schiff.length - 1].getX() > feldlaenge - 1) || (schiff[schiff.length - 1] .getY() > feldlaenge - 1)); } private boolean konflikt(Punkt[] schiff) { int i, k; for (Schiff s : sc) { for (int n = 0; n < s.getLaenge(); n++) { Teil[] akt = s.getTeile(); for (i = 0; i < akt.length; i++) { for (k = 0; k < schiff.length; k++) { if ((akt[i].getPosition().getX() == schiff[k].getX()) && (akt[i].getPosition().getY() == schiff[k] .getY())) return true; } } } } return false; } private boolean nachbar(Punkt[] schiff) { int i, k; for (Schiff s : sc) { for (int n = 0; n < s.getLaenge(); n++) { Teil[] akt = s.getTeile(); for (i = 0; i < akt.length; i++) { for (k = 0; k < schiff.length; k++) { if ((akt[i].getPosition().getX() == schiff[k].getX() - 1) && (akt[i].getPosition().getY() == schiff[k] .getY())) return true; if ((akt[i].getPosition().getX() == schiff[k].getX() + 1) && (akt[i].getPosition().getY() == schiff[k] .getY())) return true; if ((akt[i].getPosition().getX() == schiff[k].getX()) && (akt[i].getPosition().getY() == schiff[k] .getY() - 1)) return true; if ((akt[i].getPosition().getX() == schiff[k].getX()) && (akt[i].getPosition().getY() == schiff[k] .getY() + 1)) return true; } } } } return false; } private long random(int u, int o) { if (u < o) return Math.round((Math.random() * (o - u)) + u); else return -1; } public int verarbeiteSchuss(int x, int y) { int i = getLinkSpielfeld().getFeld(x, y); if (i != Spielfeld.SCHUSSW && i != Spielfeld.SCHUSST) { getLinkSpieler().increaseAnzahlSchuesse(); if (i == Spielfeld.WASSER) getLinkSpielfeld().setFeld(x, y, Spielfeld.SCHUSSW); else getLinkSpielfeld().setFeld(x, y, Spielfeld.SCHUSST); if (i == Spielfeld.WASSER) return Spiel.WASSER; else { if (spielfeld.hatGewonnen()) return Spiel.ENDE; else { int j, feld; i = x; j = y; feld = getLinkSpielfeld().getFeld(i, j); while (feld != Spielfeld.WASSER && feld != Spielfeld.SCHUSSW && feld != -1) { if (feld == Spielfeld.SCHIFF) return Spiel.TREFFER; ++i; feld = getLinkSpielfeld().getFeld(i, j); } i = x; j = y; feld = getLinkSpielfeld().getFeld(i, j); while (feld != Spielfeld.WASSER && feld != Spielfeld.SCHUSSW && feld != -1) { if (feld == Spielfeld.SCHIFF) return Spiel.TREFFER; --i; feld = getLinkSpielfeld().getFeld(i, j); } i = x; j = y; feld = getLinkSpielfeld().getFeld(i, j); while (feld != Spielfeld.WASSER && feld != Spielfeld.SCHUSSW && feld != -1) { if (feld == Spielfeld.SCHIFF) return Spiel.TREFFER; ++j; feld = getLinkSpielfeld().getFeld(i, j); } i = x; j = y; feld = getLinkSpielfeld().getFeld(i, j); while (feld != Spielfeld.WASSER && feld != Spielfeld.SCHUSSW && feld != -1) { if (feld == Spielfeld.SCHIFF) return Spiel.TREFFER; --j; feld = getLinkSpielfeld().getFeld(i, j); } return Spiel.VERSENKT; } } } return Spiel.SCHUSS; } }
UTF-8
Java
6,555
java
Spiel.java
Java
[]
null
[]
public class Spiel { public static final int WASSER = 0; public static final int TREFFER = 1; public static final int SCHUSS = 2; public static final int VERSENKT = 3; public static final int ENDE = 4; private static int maxVersuche = 1000000; private int feldlaenge; private Spieler spieler; private Konfiguration konfiguration; private Spielfeld spielfeld; private SchiffContainer sc; private Punkt[] schiff; public Spiel(Spieler spieler, Konfiguration konfiguration) { setLinkKonfiguration(konfiguration); feldlaenge = getLinkKonfiguration().getFeldlaenge(); spielfeld = new Spielfeld(feldlaenge); setLinkSpieler(spieler); sc = SchiffContainer.instance(); init(); for (int i = getLinkKonfiguration().getMaxSchifflaenge(); i >= getLinkKonfiguration() .getMinSchifflaenge(); --i) { if (increment(i) == false) { System.out.println("Zu viele Schiffe"); return; } } setzeSchiffe(); } public Konfiguration getLinkKonfiguration() { return konfiguration; } public void setLinkKonfiguration(Konfiguration konfiguration) { this.konfiguration = konfiguration; } public Spieler getLinkSpieler() { return spieler; } public void setLinkSpieler(Spieler spieler) { this.spieler = spieler; } public Spielfeld getLinkSpielfeld() { return spielfeld; } private Punkt[] createSchiff(int laenge) { int zeile, spalte, ausrichtung; schiff = new Punkt[laenge]; zeile = (int) random(0, feldlaenge - 1); spalte = (int) random(0, feldlaenge - 1); ausrichtung = (int) random(0, 3); int i; switch (ausrichtung) { // links case 0: for (i = 0; i < laenge; i++) { schiff[i] = new Punkt(zeile, spalte - laenge + 1 + i); } break; // rechts case 1: for (i = 0; i < laenge; i++) { schiff[i] = new Punkt(zeile, spalte + i); } break; // oben case 2: for (i = 0; i < laenge; i++) { schiff[i] = new Punkt(zeile - laenge + 1 + i, spalte); } break; // unten case 3: for (i = 0; i < laenge; i++) { schiff[i] = new Punkt(zeile + i, spalte); } break; } return schiff; } private boolean increment(int laenge) { Punkt[] schiff; int i = 0; do { schiff = createSchiff(laenge); ++i; } while (positionOk(schiff) == false && i < maxVersuche); if (i < maxVersuche) { Schiff s = new Schiff(schiff); sc.addAlleSchiffe(s); return true; } else return false; } private void init() { int i, j; for (i = 0; i < getLinkKonfiguration().getFeldlaenge(); i++) { for (j = 0; j < getLinkKonfiguration().getFeldlaenge(); j++) { getLinkSpielfeld().setFeld(i, j, Spielfeld.WASSER); } } } private boolean positionOk(Punkt[] schiff) { if (grenze(schiff) == true) return false; if (konflikt(schiff) == true) return false; if (nachbar(schiff) == true) return false; return true; } private void setzeSchiffe() { for (Schiff s : sc) { for (int n = 0; n < s.getLaenge(); n++) { Teil[] akt = s.getTeile(); for (int i = 0; i < akt.length; i++) { getLinkSpielfeld().setFeld(akt[i].getPosition().getX(), akt[i].getPosition().getY(), Spielfeld.SCHIFF); } } } } private boolean grenze(Punkt[] schiff) { return ((schiff[0].getX() < 0) || (schiff[0].getY() < 0) || (schiff[schiff.length - 1].getX() > feldlaenge - 1) || (schiff[schiff.length - 1] .getY() > feldlaenge - 1)); } private boolean konflikt(Punkt[] schiff) { int i, k; for (Schiff s : sc) { for (int n = 0; n < s.getLaenge(); n++) { Teil[] akt = s.getTeile(); for (i = 0; i < akt.length; i++) { for (k = 0; k < schiff.length; k++) { if ((akt[i].getPosition().getX() == schiff[k].getX()) && (akt[i].getPosition().getY() == schiff[k] .getY())) return true; } } } } return false; } private boolean nachbar(Punkt[] schiff) { int i, k; for (Schiff s : sc) { for (int n = 0; n < s.getLaenge(); n++) { Teil[] akt = s.getTeile(); for (i = 0; i < akt.length; i++) { for (k = 0; k < schiff.length; k++) { if ((akt[i].getPosition().getX() == schiff[k].getX() - 1) && (akt[i].getPosition().getY() == schiff[k] .getY())) return true; if ((akt[i].getPosition().getX() == schiff[k].getX() + 1) && (akt[i].getPosition().getY() == schiff[k] .getY())) return true; if ((akt[i].getPosition().getX() == schiff[k].getX()) && (akt[i].getPosition().getY() == schiff[k] .getY() - 1)) return true; if ((akt[i].getPosition().getX() == schiff[k].getX()) && (akt[i].getPosition().getY() == schiff[k] .getY() + 1)) return true; } } } } return false; } private long random(int u, int o) { if (u < o) return Math.round((Math.random() * (o - u)) + u); else return -1; } public int verarbeiteSchuss(int x, int y) { int i = getLinkSpielfeld().getFeld(x, y); if (i != Spielfeld.SCHUSSW && i != Spielfeld.SCHUSST) { getLinkSpieler().increaseAnzahlSchuesse(); if (i == Spielfeld.WASSER) getLinkSpielfeld().setFeld(x, y, Spielfeld.SCHUSSW); else getLinkSpielfeld().setFeld(x, y, Spielfeld.SCHUSST); if (i == Spielfeld.WASSER) return Spiel.WASSER; else { if (spielfeld.hatGewonnen()) return Spiel.ENDE; else { int j, feld; i = x; j = y; feld = getLinkSpielfeld().getFeld(i, j); while (feld != Spielfeld.WASSER && feld != Spielfeld.SCHUSSW && feld != -1) { if (feld == Spielfeld.SCHIFF) return Spiel.TREFFER; ++i; feld = getLinkSpielfeld().getFeld(i, j); } i = x; j = y; feld = getLinkSpielfeld().getFeld(i, j); while (feld != Spielfeld.WASSER && feld != Spielfeld.SCHUSSW && feld != -1) { if (feld == Spielfeld.SCHIFF) return Spiel.TREFFER; --i; feld = getLinkSpielfeld().getFeld(i, j); } i = x; j = y; feld = getLinkSpielfeld().getFeld(i, j); while (feld != Spielfeld.WASSER && feld != Spielfeld.SCHUSSW && feld != -1) { if (feld == Spielfeld.SCHIFF) return Spiel.TREFFER; ++j; feld = getLinkSpielfeld().getFeld(i, j); } i = x; j = y; feld = getLinkSpielfeld().getFeld(i, j); while (feld != Spielfeld.WASSER && feld != Spielfeld.SCHUSSW && feld != -1) { if (feld == Spielfeld.SCHIFF) return Spiel.TREFFER; --j; feld = getLinkSpielfeld().getFeld(i, j); } return Spiel.VERSENKT; } } } return Spiel.SCHUSS; } }
6,555
0.581693
0.57315
262
24.019083
20.933456
88
false
false
0
0
0
0
0
0
3.645038
false
false
11
c0174d52dc046e50dfb17fca8c79047da3c9df8b
30,760,555,791,120
6f0b00bc5e1502c60eb52354cf34f54613b8bd7a
/app/src/main/java/com/delaroystudios/alarmreminder/SettingsActivity.java
efa3e6990ebcf285de055af9e97cac4495b0373d
[]
no_license
Imran-Khalid/SSP
https://github.com/Imran-Khalid/SSP
84d6d52a354b296984c1799bcccedcad36cd1c03
6eed0af0644111bb322a7d4d66e9275c73de9148
refs/heads/master
2020-06-16T08:26:33.738000
2019-07-08T19:02:26
2019-07-08T19:02:26
195,523,263
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.delaroystudios.alarmreminder; import android.content.Intent; import android.support.annotation.NonNull; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.text.TextUtils; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import java.util.HashMap; import de.hdodenhof.circleimageview.CircleImageView; public class SettingsActivity extends AppCompatActivity { private Button UpdateAccountSettings; private EditText userName; private CircleImageView userProfileImage; private String currentUserID; private FirebaseAuth mAuth; private DatabaseReference RootRef; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_settings); mAuth=FirebaseAuth.getInstance(); currentUserID=mAuth.getCurrentUser().getUid(); RootRef= FirebaseDatabase.getInstance().getReference(); InitializeFields(); UpdateAccountSettings.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { UpdateSetting(); } }); } private void InitializeFields() { UpdateAccountSettings=(Button)findViewById(R.id.update_settings_button); userName=(EditText)findViewById(R.id.set_user_name); userProfileImage=(CircleImageView)findViewById(R.id.set_profile_image); } private void UpdateSetting() { String setUserName=userName.getText().toString(); if (TextUtils.isEmpty(setUserName)){ Toast.makeText(this, "Please Choose User name", Toast.LENGTH_SHORT).show(); } else{ HashMap<String,String> profileMap=new HashMap<>(); profileMap.put("uid",currentUserID); profileMap.put("name",setUserName); RootRef.child("Users").child(currentUserID).setValue(profileMap) .addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if (task.isSuccessful()){ SendUserToMainActivity(); //Toast.makeText(SettingsActivity.this, "Updated", Toast.LENGTH_SHORT).show(); }else { String message=task.getException().toString(); Toast.makeText(SettingsActivity.this, "Error : "+message, Toast.LENGTH_SHORT).show(); } } }); } } private void SendUserToMainActivity() { Intent mainIntent=new Intent(SettingsActivity.this,DiscussionGroups.class); mainIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); startActivity(mainIntent); finish(); } }
UTF-8
Java
3,298
java
SettingsActivity.java
Java
[]
null
[]
package com.delaroystudios.alarmreminder; import android.content.Intent; import android.support.annotation.NonNull; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.text.TextUtils; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import java.util.HashMap; import de.hdodenhof.circleimageview.CircleImageView; public class SettingsActivity extends AppCompatActivity { private Button UpdateAccountSettings; private EditText userName; private CircleImageView userProfileImage; private String currentUserID; private FirebaseAuth mAuth; private DatabaseReference RootRef; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_settings); mAuth=FirebaseAuth.getInstance(); currentUserID=mAuth.getCurrentUser().getUid(); RootRef= FirebaseDatabase.getInstance().getReference(); InitializeFields(); UpdateAccountSettings.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { UpdateSetting(); } }); } private void InitializeFields() { UpdateAccountSettings=(Button)findViewById(R.id.update_settings_button); userName=(EditText)findViewById(R.id.set_user_name); userProfileImage=(CircleImageView)findViewById(R.id.set_profile_image); } private void UpdateSetting() { String setUserName=userName.getText().toString(); if (TextUtils.isEmpty(setUserName)){ Toast.makeText(this, "Please Choose User name", Toast.LENGTH_SHORT).show(); } else{ HashMap<String,String> profileMap=new HashMap<>(); profileMap.put("uid",currentUserID); profileMap.put("name",setUserName); RootRef.child("Users").child(currentUserID).setValue(profileMap) .addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if (task.isSuccessful()){ SendUserToMainActivity(); //Toast.makeText(SettingsActivity.this, "Updated", Toast.LENGTH_SHORT).show(); }else { String message=task.getException().toString(); Toast.makeText(SettingsActivity.this, "Error : "+message, Toast.LENGTH_SHORT).show(); } } }); } } private void SendUserToMainActivity() { Intent mainIntent=new Intent(SettingsActivity.this,DiscussionGroups.class); mainIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); startActivity(mainIntent); finish(); } }
3,298
0.649485
0.649181
84
38.261906
26.774685
117
false
false
0
0
0
0
0
0
0.702381
false
false
11
717e483461eafadaae903f58e79dc36482294972
7,550,552,517,605
6da7665421a90967251f24f825c440a252a0f429
/labb6/src/tow/CornerOut.java
3a68af2df3d8546f513dc5d03a8324831d82d245
[]
no_license
equadon/sts-programmering
https://github.com/equadon/sts-programmering
3ccef8eed29c40644691a68365aca67849c73779
eb443e71425631f7f45eb67c13022deb4af1f737
refs/heads/master
2020-04-01T11:21:11.646000
2015-12-11T10:50:06
2015-12-11T10:50:06
153,158,419
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package tow; class CornerOut extends Level { CornerOut() { goals.add(new Goal(50, 300)); obstacles.add(new RectangleObstacle(0, 0, 400, 225)); obstacles.add(new RectangleObstacle(0, 400, 400, 1000 - 400)); obstacles.add(new RectangleObstacle(700, 0, 1000 - 700, 1000)); theCar = newCar(100, 300, LEFT); theTrailer = newTrailer(LEFT, theCar); name = "Out of corner"; } }
UTF-8
Java
440
java
CornerOut.java
Java
[]
null
[]
package tow; class CornerOut extends Level { CornerOut() { goals.add(new Goal(50, 300)); obstacles.add(new RectangleObstacle(0, 0, 400, 225)); obstacles.add(new RectangleObstacle(0, 400, 400, 1000 - 400)); obstacles.add(new RectangleObstacle(700, 0, 1000 - 700, 1000)); theCar = newCar(100, 300, LEFT); theTrailer = newTrailer(LEFT, theCar); name = "Out of corner"; } }
440
0.602273
0.493182
18
23.444445
24.98271
71
false
false
0
0
0
0
0
0
1.166667
false
false
11
fddd414598e1e950acb310b596710e1f5fc164f7
11,252,814,334,874
0ac05e3da06d78292fdfb64141ead86ff6ca038f
/OSWE/oswe/openCRX/rtjar/rt.jar.src/sun/java2d/pipe/CompositePipe.java
7f504ddc05655de0524a73137359b24ceac341af
[]
no_license
qoo7972365/timmy
https://github.com/qoo7972365/timmy
31581cdcbb8858ac19a8bb7b773441a68b6c390a
2fc8baba4f53d38dfe9c2b3afd89dcf87cbef578
refs/heads/master
2023-07-26T12:26:35.266000
2023-07-17T12:35:19
2023-07-17T12:35:19
353,889,195
7
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package sun.java2d.pipe; import java.awt.Rectangle; import java.awt.Shape; import sun.java2d.SunGraphics2D; public interface CompositePipe { Object startSequence(SunGraphics2D paramSunGraphics2D, Shape paramShape, Rectangle paramRectangle, int[] paramArrayOfint); boolean needTile(Object paramObject, int paramInt1, int paramInt2, int paramInt3, int paramInt4); void renderPathTile(Object paramObject, byte[] paramArrayOfbyte, int paramInt1, int paramInt2, int paramInt3, int paramInt4, int paramInt5, int paramInt6); void skipTile(Object paramObject, int paramInt1, int paramInt2); void endSequence(Object paramObject); } /* Location: /Users/timmy/timmy/OSWE/oswe/openCRX/rt.jar!/sun/java2d/pipe/CompositePipe.class * Java compiler version: 8 (52.0) * JD-Core Version: 1.1.3 */
UTF-8
Java
826
java
CompositePipe.java
Java
[ { "context": "aramObject);\n}\n\n\n/* Location: /Users/timmy/timmy/OSWE/oswe/openCRX/rt.jar!/sun/java2d/pipe/C", "end": 687, "score": 0.8488330841064453, "start": 682, "tag": "USERNAME", "value": "timmy" } ]
null
[]
package sun.java2d.pipe; import java.awt.Rectangle; import java.awt.Shape; import sun.java2d.SunGraphics2D; public interface CompositePipe { Object startSequence(SunGraphics2D paramSunGraphics2D, Shape paramShape, Rectangle paramRectangle, int[] paramArrayOfint); boolean needTile(Object paramObject, int paramInt1, int paramInt2, int paramInt3, int paramInt4); void renderPathTile(Object paramObject, byte[] paramArrayOfbyte, int paramInt1, int paramInt2, int paramInt3, int paramInt4, int paramInt5, int paramInt6); void skipTile(Object paramObject, int paramInt1, int paramInt2); void endSequence(Object paramObject); } /* Location: /Users/timmy/timmy/OSWE/oswe/openCRX/rt.jar!/sun/java2d/pipe/CompositePipe.class * Java compiler version: 8 (52.0) * JD-Core Version: 1.1.3 */
826
0.75908
0.728814
23
34.95652
44.114948
157
false
false
0
0
0
0
0
0
1.086957
false
false
11
6e3374f79605de0115f99c951bde5682b2bc27f1
22,986,665,013,038
ed8b024803110d60e274a93bb0371a622fba03be
/3D_Store/src/com/runmit/sweedee/util/Constant.java
d1dfd1a939b5056915ffe3a196ad001b44dbd44a
[]
no_license
ShibinHuang/3DStore
https://github.com/ShibinHuang/3DStore
b861a36c6ba486ff03492c0551a641643b9cd7ce
00be34f2c16e589324bf9162e8a8071197cceff3
refs/heads/master
2020-06-11T03:21:19.895000
2018-08-14T12:04:38
2018-08-14T12:04:38
76,016,614
1
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.runmit.sweedee.util; public class Constant { // 产品ID product ID public static int PRODUCT_ID = 1; // 1.android 2.iphone 3.androidpad /** * 项目id,包含不同端产品,比如sweedee android和ios端共用一个id,和上面的PRODUCT_ID不同,这个是粗粒度的 */ public static int superProjectId = 1; public static final int MANUAL = 1; //播放清晰度 public static final int ORIN_VOD_URL = 0; //原始,针对本地播放 public static final int NORMAL_VOD_URL = 1; //标清720P public static final int HIGH_VOD_URL = 2; //高清1080P //缓存字幕类型 中/英 public static final String DOWNLOAD_LAN_CH = "zh"; //中文 public static final String DOWNLOAD_LAN_EN = "en"; //英文 //音轨优先类型 public static final String AUDIO_TRACK_SETTING = "audio_track";//播放音轨选择 public static final int AUDIO_FIRST_ORIN = 0; //优先原生音轨 public static final int AUDIO_FIRST_LOCAL = 1; //优先系统设置语言音轨 public static final String GAME_SETTING = "game_setting";//游戏设置 //网络类型相关 public static final String NETWORK_NONE = "none"; public static final String NETWORK_WIFI = "wifi"; public static final String NETWORK_2G_WAP = "2g_wap"; public static final String NETWORK_2G_NET = "2g_net"; public static final String NETWORK_3G = "3g"; public static final String NETWORK_4G = "4g"; public static final String NETWORK_OTHER = "other"; public static final int NETWORK_CLASS_UNKNOWN = 0; public static final int NETWORK_CLASS_2G = 1; public static final int NETWORK_CLASS_3G = 2; public static final int NETWORK_CLASS_4G = 3; //屏幕长宽的全局变量 public static int SCREEN_HEIGHT = 0; public static int SCREEN_WIDTH = 0; public static float DENSITY = 1.0f; //同时缓存数量 public static final String DOWNLOAD_NUM = "downloadNum"; //视频后缀名集合 public static String[] VEDIO_SUFFIX = new String[] {"mpeg", "mpg", "mpe", "dat", "m1v", "m2v", "m2p", "m2ts", "mp2v", "mpeg1", "mpeg2", "tp", "ts", "avi", "asf", "wmv", "wm", "wmp", "3gp", "3g2", "3gp2", "3gpp", "flv", "f4v", "swf", "hlv", "rmvb", "rm", "m4b", "m4p", "m4v", "mpeg4", "mp4", "amv", "divx", "xv", "mkv", "xlmv", "pmp", "ogm", "ogv", "ogx", "mts", "mov", "voB", "dvd"}; // 友盟事件名称 public static final String PlayClick = "clickPlay"; // 点击播放事件 public static final String PurchaseClick = "purchaseClick"; // 点击购买事件 public static final String MonPurchaseClick = "cashPurchaseClick"; // 现金支付 }
UTF-8
Java
2,782
java
Constant.java
Java
[]
null
[]
package com.runmit.sweedee.util; public class Constant { // 产品ID product ID public static int PRODUCT_ID = 1; // 1.android 2.iphone 3.androidpad /** * 项目id,包含不同端产品,比如sweedee android和ios端共用一个id,和上面的PRODUCT_ID不同,这个是粗粒度的 */ public static int superProjectId = 1; public static final int MANUAL = 1; //播放清晰度 public static final int ORIN_VOD_URL = 0; //原始,针对本地播放 public static final int NORMAL_VOD_URL = 1; //标清720P public static final int HIGH_VOD_URL = 2; //高清1080P //缓存字幕类型 中/英 public static final String DOWNLOAD_LAN_CH = "zh"; //中文 public static final String DOWNLOAD_LAN_EN = "en"; //英文 //音轨优先类型 public static final String AUDIO_TRACK_SETTING = "audio_track";//播放音轨选择 public static final int AUDIO_FIRST_ORIN = 0; //优先原生音轨 public static final int AUDIO_FIRST_LOCAL = 1; //优先系统设置语言音轨 public static final String GAME_SETTING = "game_setting";//游戏设置 //网络类型相关 public static final String NETWORK_NONE = "none"; public static final String NETWORK_WIFI = "wifi"; public static final String NETWORK_2G_WAP = "2g_wap"; public static final String NETWORK_2G_NET = "2g_net"; public static final String NETWORK_3G = "3g"; public static final String NETWORK_4G = "4g"; public static final String NETWORK_OTHER = "other"; public static final int NETWORK_CLASS_UNKNOWN = 0; public static final int NETWORK_CLASS_2G = 1; public static final int NETWORK_CLASS_3G = 2; public static final int NETWORK_CLASS_4G = 3; //屏幕长宽的全局变量 public static int SCREEN_HEIGHT = 0; public static int SCREEN_WIDTH = 0; public static float DENSITY = 1.0f; //同时缓存数量 public static final String DOWNLOAD_NUM = "downloadNum"; //视频后缀名集合 public static String[] VEDIO_SUFFIX = new String[] {"mpeg", "mpg", "mpe", "dat", "m1v", "m2v", "m2p", "m2ts", "mp2v", "mpeg1", "mpeg2", "tp", "ts", "avi", "asf", "wmv", "wm", "wmp", "3gp", "3g2", "3gp2", "3gpp", "flv", "f4v", "swf", "hlv", "rmvb", "rm", "m4b", "m4p", "m4v", "mpeg4", "mp4", "amv", "divx", "xv", "mkv", "xlmv", "pmp", "ogm", "ogv", "ogx", "mts", "mov", "voB", "dvd"}; // 友盟事件名称 public static final String PlayClick = "clickPlay"; // 点击播放事件 public static final String PurchaseClick = "purchaseClick"; // 点击购买事件 public static final String MonPurchaseClick = "cashPurchaseClick"; // 现金支付 }
2,782
0.623392
0.600884
62
39.129032
32.807594
148
false
false
0
0
0
0
0
0
1.258065
false
false
11
26183a8283e16eaee1d6434cd64b5670242975e8
22,986,665,011,705
b27525da5262619a5caafdaa53d6eeecac6cc4f8
/logController/src/main/java/com/nykj/socket/ServerSocketUtil.java
bda424921ac3c028fa695c0f1b1a7395a75be09f
[]
no_license
lanfeng1989/gitRepository
https://github.com/lanfeng1989/gitRepository
9e2993d12d9005f8fb744b0da20748aa4346fac7
cc4e11c05ddfbd839a699c7b27a588a230ff5c42
refs/heads/master
2015-08-24T01:16:48.962000
2015-06-04T02:35:22
2015-06-04T02:35:22
35,078,599
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.nykj.socket; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.util.Date; import java.util.Timer; import com.nykj.hadoop.utils.HDFSUtil; import com.nykj.logController.CreateFileTask; import com.nykj.protobuf.DebugLogProbuf; import com.nykj.protobuf.DebugLogProbuf.DebugLog; /** * *<p>文件名称:ServerSocketUtil.java *<p> *<p>文件描述:本类描述 *<p>版权所有:湖南省蓝蜻蜓网络科技有限公司版权所有(C)2015</p> *<p>内容摘要:简要描述本文件的内容,包括主要模块、函数及能的说明 </p> *<p>其他说明:其它内容的说明 </p> *<p>完成日期:2015年4月30日上午10:07:00</p> *<p> *@author */ public class ServerSocketUtil { public static void writeStr2Stream(String str, OutputStream out) throws IOException { try { // add buffered writer BufferedOutputStream writer = new BufferedOutputStream(out); if(str !=null && str.getBytes().length>0){ // write writer.write(str.getBytes()); writer.flush(); } } catch (IOException ex) { System.out.println(ex); throw ex; } } public static String readStrFromStream(InputStream in) throws IOException { //System.out.println(getNowTime() + " : start to read string from stream"); StringBuffer result = new StringBuffer(); // build buffered reader BufferedReader reader = new BufferedReader(new InputStreamReader(in)); // read 1024 bytes per time char[] chars = new char[2048]; int len; try { while ((len = reader.read(chars)) != -1) { // if the length of array is 1M if (2048 == len) { //then append all chars of the array result.append(chars); // System.out.println("readStrFromStream : " + result.toString()); } // if the length of array is less then 1M else { //then append the valid chars for (int i = 0; i < len; i++) { result.append(chars[i]); //System.out.println("readStrFromStream : " + result.toString()); } break; } } } catch (IOException e) { System.out.println(e); throw e; } //System.out.println("end reading string from stream"); return result.toString(); } public static String getNowTime() { return new Date().toString(); } public static void createDir(){ //启动先创建debug日志文件夹 try { if(!HDFSUtil.isDirExist("hdfs://vm131:9000/debug_log")){ HDFSUtil.mkdirs("hdfs://vm131:9000/debug_log"); System.out.println("------------创建debug日志文件夹成功!------------"); } } catch (Exception e) { System.out.println("------------创建debug日志文件夹失败!------------"); } } public static void createFile(){ //启动创建文件任务,每天创建1个文件 new Timer().schedule(new CreateFileTask(),2000, 24*60*60*1000); System.out.println("------------创建debug日志文件成功!------------"); } // public static String parseDebugLog2String(DebugLog logDest){ // StringBuffer sb = new StringBuffer(); // sb.append(logDest.getClassName()).append("|").append(logDest.getIp()).append("|") // .append(logDest.getServiceId()).append("|").append(logDest.getText()); // return sb.toString(); // } public static String formatString(String str) throws IOException{ StringBuffer sb = new StringBuffer(); DebugLogProbuf.DebugLog logDest = DebugLogProbuf.DebugLog.parseFrom(str.getBytes()); sb.append(logDest.getClassName()).append("|").append(logDest.getIp()).append("|") .append(logDest.getServiceId()).append("|").append(logDest.getText()); return sb.toString(); } }
UTF-8
Java
3,706
java
ServerSocketUtil.java
Java
[]
null
[]
package com.nykj.socket; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.util.Date; import java.util.Timer; import com.nykj.hadoop.utils.HDFSUtil; import com.nykj.logController.CreateFileTask; import com.nykj.protobuf.DebugLogProbuf; import com.nykj.protobuf.DebugLogProbuf.DebugLog; /** * *<p>文件名称:ServerSocketUtil.java *<p> *<p>文件描述:本类描述 *<p>版权所有:湖南省蓝蜻蜓网络科技有限公司版权所有(C)2015</p> *<p>内容摘要:简要描述本文件的内容,包括主要模块、函数及能的说明 </p> *<p>其他说明:其它内容的说明 </p> *<p>完成日期:2015年4月30日上午10:07:00</p> *<p> *@author */ public class ServerSocketUtil { public static void writeStr2Stream(String str, OutputStream out) throws IOException { try { // add buffered writer BufferedOutputStream writer = new BufferedOutputStream(out); if(str !=null && str.getBytes().length>0){ // write writer.write(str.getBytes()); writer.flush(); } } catch (IOException ex) { System.out.println(ex); throw ex; } } public static String readStrFromStream(InputStream in) throws IOException { //System.out.println(getNowTime() + " : start to read string from stream"); StringBuffer result = new StringBuffer(); // build buffered reader BufferedReader reader = new BufferedReader(new InputStreamReader(in)); // read 1024 bytes per time char[] chars = new char[2048]; int len; try { while ((len = reader.read(chars)) != -1) { // if the length of array is 1M if (2048 == len) { //then append all chars of the array result.append(chars); // System.out.println("readStrFromStream : " + result.toString()); } // if the length of array is less then 1M else { //then append the valid chars for (int i = 0; i < len; i++) { result.append(chars[i]); //System.out.println("readStrFromStream : " + result.toString()); } break; } } } catch (IOException e) { System.out.println(e); throw e; } //System.out.println("end reading string from stream"); return result.toString(); } public static String getNowTime() { return new Date().toString(); } public static void createDir(){ //启动先创建debug日志文件夹 try { if(!HDFSUtil.isDirExist("hdfs://vm131:9000/debug_log")){ HDFSUtil.mkdirs("hdfs://vm131:9000/debug_log"); System.out.println("------------创建debug日志文件夹成功!------------"); } } catch (Exception e) { System.out.println("------------创建debug日志文件夹失败!------------"); } } public static void createFile(){ //启动创建文件任务,每天创建1个文件 new Timer().schedule(new CreateFileTask(),2000, 24*60*60*1000); System.out.println("------------创建debug日志文件成功!------------"); } // public static String parseDebugLog2String(DebugLog logDest){ // StringBuffer sb = new StringBuffer(); // sb.append(logDest.getClassName()).append("|").append(logDest.getIp()).append("|") // .append(logDest.getServiceId()).append("|").append(logDest.getText()); // return sb.toString(); // } public static String formatString(String str) throws IOException{ StringBuffer sb = new StringBuffer(); DebugLogProbuf.DebugLog logDest = DebugLogProbuf.DebugLog.parseFrom(str.getBytes()); sb.append(logDest.getClassName()).append("|").append(logDest.getIp()).append("|") .append(logDest.getServiceId()).append("|").append(logDest.getText()); return sb.toString(); } }
3,706
0.668805
0.649854
126
26.222221
24.204449
86
false
false
0
0
0
0
0
0
2.246032
false
false
11
0aa259568d389bf3b5ea64b53d998d54479f82ac
4,604,204,968,414
d14ffd2c5e861e063379b4fcc399cb51d88ae6e3
/OldBook/src/action/BookAction.java
30db45cabc2b0b53826ea6774c5656284f216f98
[]
no_license
smallsunnyfox/OldBook
https://github.com/smallsunnyfox/OldBook
b56093eae7a74a76f608a8e39a92533d3555f71a
7096d8c9bd7c66407a2de6db021a43a8f655007a
refs/heads/master
2020-03-18T11:03:29.775000
2019-05-13T05:24:51
2019-05-13T05:24:51
134,644,656
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package action; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.apache.struts2.ServletActionContext; import service.BookService; import com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.ActionSupport; import com.opensymphony.xwork2.util.ValueStack; import entity.Book; public class BookAction extends ActionSupport{ private Book b; private HttpServletRequest request = ServletActionContext.getRequest(); private HttpSession session = request.getSession(); private String username = (String) session.getAttribute("username"); private String msg=""; private BookService bookservice; private Book up; public Book getBookById(int id){ return bookservice.getBookById(id); } public Book getUp() { return up; } public void setUp(Book up) { this.up = up; } public BookService getBookservice() { return bookservice; } public void setBookservice(BookService bookservice) { this.bookservice = bookservice; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public Book getB() { return b; } public void setB(Book b) { this.b = b; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String index(){ System.out.println(username); if(username.equals("") || username.equals(null)){ return "failed"; }else{ List<Book> allbooks = bookservice.getAllBooks(username); ValueStack vs = ActionContext.getContext().getValueStack(); vs.setValue("#request.allbooks", allbooks); System.out.println("进入主界面"); return "index"; } } public String addbook(){ String price = String.valueOf(b.getPrice()); System.out.println(price); if(b.getBookname().equals("") || b.getBookname().equals(null)){ msg="书名不能为空!请填写完整!"; session.setAttribute("msg", msg); return "input"; }else if(b.getAuthor().equals("") || b.getAuthor().equals(null)){ msg="作者名不能为空!请填写完整!"; session.setAttribute("msg", msg); return "input"; }else if(b.getDamage().equals(null) || b.getDamage().equals("")){ msg="破损度不能为空!请填写完整!"; session.setAttribute("msg", msg); return "input"; }else if(price.equals("0.0") ||price.equals("") || price.equals(null)){ msg="价格不能为空!请填写完整!"; session.setAttribute("msg", msg); return "input"; }else{ b.setUsername(username); boolean flag = bookservice.addBook(b); if(flag==false){ msg="你已经发布过这本书了!"; session.setAttribute("msg", msg); return "input"; }else{ return "success"; } } } public String mybooks(){ if(username.equals("") || username.equals(null)){ return "failed"; }else{ List<Book> mybooks = bookservice.getMyBooks(username); ValueStack vs = ActionContext.getContext().getValueStack(); vs.setValue("#request.mybooks", mybooks); System.out.println("进入我的书库页面"); return "mybooks"; } } public String deletemybook(){ String bid = request.getParameter("bid"); System.out.println("要删除的书籍编号为:"+bid); int id = Integer.parseInt(bid); Book b = getBookById(id); if(b.getStatus().equals("已卖出")){ msg="该书已卖出,无法删除" + ""; session.setAttribute("msg", msg); return "input"; }else{ bookservice.deleteBook(id); return "success"; } } public String updatemybook(){ if(username.equals("") || username.equals(null)){ return "failed"; }else{ ValueStack vs = ActionContext.getContext().getValueStack(); String upid = request.getParameter("upid"); int id = Integer.parseInt(upid); Book b = bookservice.getBookById(id); vs.setValue("#session.upbook", b); vs.setValue("#session.upid",id); System.out.println("进入我的书库页面"); return "success"; } } public String updatebooksuccess(){ String price = String.valueOf(up.getPrice()); ValueStack vs = ActionContext.getContext().getValueStack(); int id = (Integer) vs.findValue("#session.upid"); Book b = bookservice.getBookById(id); if(up.getBookname().equals("") || up.getBookname().equals(null)){ msg="书名不能为空!请填写完整!"; session.setAttribute("msg", msg); return "input"; }else if(up.getAuthor().equals("") || up.getAuthor().equals(null)){ msg="作者名不能为空!请填写完整!"; session.setAttribute("msg", msg); return "input"; }else if(up.getDamage().equals(null) || up.getDamage().equals("")){ msg="破损度不能为空!请填写完整!"; session.setAttribute("msg", msg); return "input"; }else if(price.equals("") || price.equals(null)){ msg="价格不能为空!请填写完整!"; session.setAttribute("msg", msg); return "input"; }else if(b.getStatus().equals("已卖出")){ msg="该书已卖出,无法修改"; session.setAttribute("msg", msg); return "input"; }else{ bookservice.updateBook(id, up); return "success"; } } }
UTF-8
Java
5,169
java
BookAction.java
Java
[]
null
[]
package action; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.apache.struts2.ServletActionContext; import service.BookService; import com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.ActionSupport; import com.opensymphony.xwork2.util.ValueStack; import entity.Book; public class BookAction extends ActionSupport{ private Book b; private HttpServletRequest request = ServletActionContext.getRequest(); private HttpSession session = request.getSession(); private String username = (String) session.getAttribute("username"); private String msg=""; private BookService bookservice; private Book up; public Book getBookById(int id){ return bookservice.getBookById(id); } public Book getUp() { return up; } public void setUp(Book up) { this.up = up; } public BookService getBookservice() { return bookservice; } public void setBookservice(BookService bookservice) { this.bookservice = bookservice; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public Book getB() { return b; } public void setB(Book b) { this.b = b; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String index(){ System.out.println(username); if(username.equals("") || username.equals(null)){ return "failed"; }else{ List<Book> allbooks = bookservice.getAllBooks(username); ValueStack vs = ActionContext.getContext().getValueStack(); vs.setValue("#request.allbooks", allbooks); System.out.println("进入主界面"); return "index"; } } public String addbook(){ String price = String.valueOf(b.getPrice()); System.out.println(price); if(b.getBookname().equals("") || b.getBookname().equals(null)){ msg="书名不能为空!请填写完整!"; session.setAttribute("msg", msg); return "input"; }else if(b.getAuthor().equals("") || b.getAuthor().equals(null)){ msg="作者名不能为空!请填写完整!"; session.setAttribute("msg", msg); return "input"; }else if(b.getDamage().equals(null) || b.getDamage().equals("")){ msg="破损度不能为空!请填写完整!"; session.setAttribute("msg", msg); return "input"; }else if(price.equals("0.0") ||price.equals("") || price.equals(null)){ msg="价格不能为空!请填写完整!"; session.setAttribute("msg", msg); return "input"; }else{ b.setUsername(username); boolean flag = bookservice.addBook(b); if(flag==false){ msg="你已经发布过这本书了!"; session.setAttribute("msg", msg); return "input"; }else{ return "success"; } } } public String mybooks(){ if(username.equals("") || username.equals(null)){ return "failed"; }else{ List<Book> mybooks = bookservice.getMyBooks(username); ValueStack vs = ActionContext.getContext().getValueStack(); vs.setValue("#request.mybooks", mybooks); System.out.println("进入我的书库页面"); return "mybooks"; } } public String deletemybook(){ String bid = request.getParameter("bid"); System.out.println("要删除的书籍编号为:"+bid); int id = Integer.parseInt(bid); Book b = getBookById(id); if(b.getStatus().equals("已卖出")){ msg="该书已卖出,无法删除" + ""; session.setAttribute("msg", msg); return "input"; }else{ bookservice.deleteBook(id); return "success"; } } public String updatemybook(){ if(username.equals("") || username.equals(null)){ return "failed"; }else{ ValueStack vs = ActionContext.getContext().getValueStack(); String upid = request.getParameter("upid"); int id = Integer.parseInt(upid); Book b = bookservice.getBookById(id); vs.setValue("#session.upbook", b); vs.setValue("#session.upid",id); System.out.println("进入我的书库页面"); return "success"; } } public String updatebooksuccess(){ String price = String.valueOf(up.getPrice()); ValueStack vs = ActionContext.getContext().getValueStack(); int id = (Integer) vs.findValue("#session.upid"); Book b = bookservice.getBookById(id); if(up.getBookname().equals("") || up.getBookname().equals(null)){ msg="书名不能为空!请填写完整!"; session.setAttribute("msg", msg); return "input"; }else if(up.getAuthor().equals("") || up.getAuthor().equals(null)){ msg="作者名不能为空!请填写完整!"; session.setAttribute("msg", msg); return "input"; }else if(up.getDamage().equals(null) || up.getDamage().equals("")){ msg="破损度不能为空!请填写完整!"; session.setAttribute("msg", msg); return "input"; }else if(price.equals("") || price.equals(null)){ msg="价格不能为空!请填写完整!"; session.setAttribute("msg", msg); return "input"; }else if(b.getStatus().equals("已卖出")){ msg="该书已卖出,无法修改"; session.setAttribute("msg", msg); return "input"; }else{ bookservice.updateBook(id, up); return "success"; } } }
5,169
0.672618
0.671372
200
23.084999
19.619831
73
false
false
0
0
0
0
0
0
2.47
false
false
11
caf75ca95d9dc3e93f2cbdf44a773282e9b8675d
14,190,571,991,027
adba0786820682aadbc632ca620c8036b41bc897
/app/src/main/java/com/example/nasa_test_app/adapter/NasaAdapter.java
ec46491ca2decacdbe5f45748c717b34c6e87ca8
[]
no_license
WhatsUp20/Nasa-Test-App
https://github.com/WhatsUp20/Nasa-Test-App
3cc1bae14a4cab791a7799166013ad15f9b20db2
95acbdb02ee0de45f3a653722ffeab375f840266
refs/heads/master
2023-03-01T21:58:20.423000
2021-02-07T21:18:15
2021-02-07T21:18:15
334,461,742
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.nasa_test_app.adapter; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import com.example.nasa_test_app.R; import com.example.nasa_test_app.data.Datum; import com.example.nasa_test_app.data.Link; import com.squareup.picasso.Picasso; import java.util.ArrayList; import java.util.List; public class NasaAdapter extends RecyclerView.Adapter<NasaAdapter.NasaViewHolder> { private List<Link> linkList = new ArrayList<>(); private List<Datum> datumList = new ArrayList<>(); private OnImageClickListener onImageClickListener; public void setLinkList(List<Link> linkList) { this.linkList = linkList; notifyDataSetChanged(); } public List<Datum> getDatumList() { return datumList; } public void setDatumList(List<Datum> datumList) { this.datumList = datumList; notifyDataSetChanged(); } public List<Link> getLinkList() { return linkList; } public void setOnImageClickListener(OnImageClickListener onImageClickListener) { this.onImageClickListener = onImageClickListener; } public interface OnImageClickListener { void onImageClick(int position); } @NonNull @Override public NasaViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.nasa_item, parent, false); return new NasaViewHolder(view); } @Override public void onBindViewHolder(@NonNull NasaViewHolder holder, int position) { Link link = linkList.get(position); Datum datum = datumList.get(position); holder.textViewTitle.setText(datum.getTitle()); holder.textViewDescription.setText(datum.getDescription()); Picasso.get().load(link.getHref()).into(holder.imageView); } @Override public int getItemCount() { return linkList.size(); } class NasaViewHolder extends RecyclerView.ViewHolder{ private ImageView imageView; private TextView textViewTitle; private TextView textViewDescription; public NasaViewHolder(@NonNull View itemView) { super(itemView); imageView = itemView.findViewById(R.id.imageView); textViewTitle = itemView.findViewById(R.id.titleToDetail); textViewDescription = itemView.findViewById(R.id.descriptionToDetail); itemView.setOnClickListener((View v) -> { if (onImageClickListener != null) { onImageClickListener.onImageClick(getAdapterPosition()); } }); } } }
UTF-8
Java
2,852
java
NasaAdapter.java
Java
[]
null
[]
package com.example.nasa_test_app.adapter; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import com.example.nasa_test_app.R; import com.example.nasa_test_app.data.Datum; import com.example.nasa_test_app.data.Link; import com.squareup.picasso.Picasso; import java.util.ArrayList; import java.util.List; public class NasaAdapter extends RecyclerView.Adapter<NasaAdapter.NasaViewHolder> { private List<Link> linkList = new ArrayList<>(); private List<Datum> datumList = new ArrayList<>(); private OnImageClickListener onImageClickListener; public void setLinkList(List<Link> linkList) { this.linkList = linkList; notifyDataSetChanged(); } public List<Datum> getDatumList() { return datumList; } public void setDatumList(List<Datum> datumList) { this.datumList = datumList; notifyDataSetChanged(); } public List<Link> getLinkList() { return linkList; } public void setOnImageClickListener(OnImageClickListener onImageClickListener) { this.onImageClickListener = onImageClickListener; } public interface OnImageClickListener { void onImageClick(int position); } @NonNull @Override public NasaViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.nasa_item, parent, false); return new NasaViewHolder(view); } @Override public void onBindViewHolder(@NonNull NasaViewHolder holder, int position) { Link link = linkList.get(position); Datum datum = datumList.get(position); holder.textViewTitle.setText(datum.getTitle()); holder.textViewDescription.setText(datum.getDescription()); Picasso.get().load(link.getHref()).into(holder.imageView); } @Override public int getItemCount() { return linkList.size(); } class NasaViewHolder extends RecyclerView.ViewHolder{ private ImageView imageView; private TextView textViewTitle; private TextView textViewDescription; public NasaViewHolder(@NonNull View itemView) { super(itemView); imageView = itemView.findViewById(R.id.imageView); textViewTitle = itemView.findViewById(R.id.titleToDetail); textViewDescription = itemView.findViewById(R.id.descriptionToDetail); itemView.setOnClickListener((View v) -> { if (onImageClickListener != null) { onImageClickListener.onImageClick(getAdapterPosition()); } }); } } }
2,852
0.690042
0.690042
94
29.340425
26.03825
104
false
false
0
0
0
0
0
0
0.489362
false
false
11
a131905b457e48f3348082017fd63ecafe3b2024
17,635,135,739,545
860bb1996bad12d90284956264b331cae0331289
/src/main/java/com/accenture/business/service/impl/HttpServiceImpl.java
5c02c685ae67ddfe3779391b240fdf02bddc670d
[]
no_license
k-onbfans/BusinessService
https://github.com/k-onbfans/BusinessService
bb1dd34571ab940f3bd27f64a8124785a55972bf
68d92400fc815f8b51f9280bec6d06204ca0359e
refs/heads/master
2022-07-21T18:59:35.113000
2019-11-12T11:06:42
2019-11-12T11:06:42
215,013,378
0
0
null
false
2021-04-26T19:38:53
2019-10-14T10:24:39
2019-11-12T11:07:06
2021-04-26T19:38:53
153
0
0
1
Java
false
false
package com.accenture.business.service.impl; import com.accenture.business.request.FindByFlightNumberReq; import com.accenture.business.response.v1.FlightV1Res; import com.accenture.business.response.v1.FlightV1Reses; import com.accenture.business.service.HttpService; import com.accenture.business.bean.Port; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; import org.springframework.web.client.RestTemplate; @Service public class HttpServiceImpl implements HttpService { @Value("${flightStatusByFDV1Url}") private String flightStatusUrl; @Value("${flightTimeByFDV1Url}") private String flightTimeUrl; @Value("${flightInfoByODV1Url}") private String flightInfoByRouteUrl; @Autowired private RestTemplate restTemplate; @Override public FlightV1Res getFlightV1(String url){ ResponseEntity<FlightV1Res> entity = restTemplate.getForEntity(url,FlightV1Res.class); return entity.getBody(); } @Override public FlightV1Res postFlightTimeV1(FindByFlightNumberReq request) { ResponseEntity<FlightV1Res> entity = restTemplate.postForEntity(flightTimeUrl,request,FlightV1Res.class); return entity.getBody(); } @Override public FlightV1Res postFlightStatusV1(FindByFlightNumberReq request) { ResponseEntity<FlightV1Res> entity = restTemplate.postForEntity(flightStatusUrl,request,FlightV1Res.class); return entity.getBody(); } @Override public FlightV1Reses postFlightByRouteV1(Port request) { ResponseEntity<FlightV1Reses> entity = restTemplate.postForEntity(flightInfoByRouteUrl,request,FlightV1Reses.class); return entity.getBody(); } }
UTF-8
Java
1,861
java
HttpServiceImpl.java
Java
[]
null
[]
package com.accenture.business.service.impl; import com.accenture.business.request.FindByFlightNumberReq; import com.accenture.business.response.v1.FlightV1Res; import com.accenture.business.response.v1.FlightV1Reses; import com.accenture.business.service.HttpService; import com.accenture.business.bean.Port; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; import org.springframework.web.client.RestTemplate; @Service public class HttpServiceImpl implements HttpService { @Value("${flightStatusByFDV1Url}") private String flightStatusUrl; @Value("${flightTimeByFDV1Url}") private String flightTimeUrl; @Value("${flightInfoByODV1Url}") private String flightInfoByRouteUrl; @Autowired private RestTemplate restTemplate; @Override public FlightV1Res getFlightV1(String url){ ResponseEntity<FlightV1Res> entity = restTemplate.getForEntity(url,FlightV1Res.class); return entity.getBody(); } @Override public FlightV1Res postFlightTimeV1(FindByFlightNumberReq request) { ResponseEntity<FlightV1Res> entity = restTemplate.postForEntity(flightTimeUrl,request,FlightV1Res.class); return entity.getBody(); } @Override public FlightV1Res postFlightStatusV1(FindByFlightNumberReq request) { ResponseEntity<FlightV1Res> entity = restTemplate.postForEntity(flightStatusUrl,request,FlightV1Res.class); return entity.getBody(); } @Override public FlightV1Reses postFlightByRouteV1(Port request) { ResponseEntity<FlightV1Reses> entity = restTemplate.postForEntity(flightInfoByRouteUrl,request,FlightV1Reses.class); return entity.getBody(); } }
1,861
0.771628
0.759269
62
29.016129
31.529041
124
false
false
0
0
0
0
0
0
0.483871
false
false
11
53f7d76cd1829a5bca84767d783cda7a75ebabb1
27,315,992,056,629
6771e4c081f843cec82fcb2634eea15a69b85b96
/basic_ds_algo_java/src/main/java/trees/search/questions/SumsOfOddAndEven.java
2d693db51089dc73bdb38cf15ed7d555479739fc
[ "Apache-2.0" ]
permissive
abilashgt/study_ds_algorithms
https://github.com/abilashgt/study_ds_algorithms
1985a155544429a4a8a4213b2d1c28377f055614
4bc4f2dd975cfc2344c7ef91a9f39fb3d28040f2
refs/heads/master
2022-10-21T06:47:16.926000
2022-09-27T19:04:04
2022-09-27T19:04:04
144,614,304
0
0
Apache-2.0
false
2020-10-12T23:16:54
2018-08-13T17:49:04
2020-04-07T02:35:32
2020-10-12T23:16:53
34
0
0
1
Java
false
false
/* Difference between sums of odd level and even level nodes of a Binary Tree https://www.geeksforgeeks.org/difference-between-sums-of-odd-and-even-levels/ */ package trees.search.questions; import trees.Node; public class SumsOfOddAndEven { Node root; int sumOdd = 0; int sumEven = 0; public static void main(String[] args) throws Exception { SumsOfOddAndEven tree = new SumsOfOddAndEven(); tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.left = new Node(4); tree.root.left.right = new Node(5); tree.totalSum(); } public void totalSum() throws Exception{ int n = findHeight(root); for(int i=1; i<=n; i++){ if(i%2==0) sumEven += sumLevel(root, i); else sumOdd += sumLevel(root, i); } System.out.println("Sum of Odd = "+sumOdd); System.out.println("Sum of Even = "+sumEven); } public static int findHeight(Node root){ if(root==null) return 0; int lh = findHeight(root.left); int rh = findHeight(root.right); if(lh>rh) return lh+1; else return rh+1; } public static int sumLevel(Node root, int level) throws Exception { if(root==null) return 0; else if(level==1) return root.value; else if(level>1) { int ls = sumLevel(root.left, level-1); int rs = sumLevel(root.right, level-1); return ls+rs; } throw new Exception("algorithm error"); } }
UTF-8
Java
1,588
java
SumsOfOddAndEven.java
Java
[]
null
[]
/* Difference between sums of odd level and even level nodes of a Binary Tree https://www.geeksforgeeks.org/difference-between-sums-of-odd-and-even-levels/ */ package trees.search.questions; import trees.Node; public class SumsOfOddAndEven { Node root; int sumOdd = 0; int sumEven = 0; public static void main(String[] args) throws Exception { SumsOfOddAndEven tree = new SumsOfOddAndEven(); tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.left = new Node(4); tree.root.left.right = new Node(5); tree.totalSum(); } public void totalSum() throws Exception{ int n = findHeight(root); for(int i=1; i<=n; i++){ if(i%2==0) sumEven += sumLevel(root, i); else sumOdd += sumLevel(root, i); } System.out.println("Sum of Odd = "+sumOdd); System.out.println("Sum of Even = "+sumEven); } public static int findHeight(Node root){ if(root==null) return 0; int lh = findHeight(root.left); int rh = findHeight(root.right); if(lh>rh) return lh+1; else return rh+1; } public static int sumLevel(Node root, int level) throws Exception { if(root==null) return 0; else if(level==1) return root.value; else if(level>1) { int ls = sumLevel(root.left, level-1); int rs = sumLevel(root.right, level-1); return ls+rs; } throw new Exception("algorithm error"); } }
1,588
0.583753
0.572418
62
24.612904
22.180603
77
false
false
0
0
0
0
0
0
0.564516
false
false
11
5f46bbdd8f2cd9fd6357f9d35e04f25b8163c450
33,870,112,115,551
b34ff26fb0e0b7b68dd482a2a328ee7cd8c2982d
/biblicando-dao-jpa/src/main/java/br/com/biblicando/dao/jpa/UserDaoImpl.java
2fa4a7af6a6fe8f9802f9be5bfe712bcae427b68
[]
no_license
douglascvas/biblicando-java-old
https://github.com/douglascvas/biblicando-java-old
b0ee21cfc891037788bc83ff36f7e347bbb6a4de
0f0734a078736a8afc4f9f57c7571eb95e2e0ed9
refs/heads/master
2016-09-23T23:41:23.040000
2016-03-12T21:14:39
2016-03-12T21:14:39
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package br.com.biblicando.dao.jpa; import br.com.biblicando.dao.UserDao; import br.com.biblicando.model.User; import javax.persistence.EntityManager; import javax.persistence.NoResultException; import javax.persistence.PersistenceContext; import javax.persistence.Query; public class UserDaoImpl extends DaoImpl<User> implements UserDao { public UserDaoImpl() { super(User.class); } @PersistenceContext private EntityManager entityManager; public EntityManager getEntityManager() { return entityManager; } public void setEntityManager(EntityManager entityManager) { this.entityManager = entityManager; } /* * (non-Javadoc) * @see br.com.biblicando.dao.UserDao#findOne(java.lang.String, * java.lang.String) */ @Override public User findOne(String username, String password) { try { Query query = entityManager .createQuery("select u from User u where u.username = :username and u.password = :password"); query.setParameter("username", username); query.setParameter("password", password); return (User) query.getSingleResult(); } catch (NoResultException e) { return null; } catch (Exception e) { e.printStackTrace(); return null; } } }
UTF-8
Java
1,372
java
UserDaoImpl.java
Java
[ { "context": "rname);\n query.setParameter(\"password\", password);\n return (User) query.getSingleResult", "end": 1144, "score": 0.9978185296058655, "start": 1136, "tag": "PASSWORD", "value": "password" } ]
null
[]
package br.com.biblicando.dao.jpa; import br.com.biblicando.dao.UserDao; import br.com.biblicando.model.User; import javax.persistence.EntityManager; import javax.persistence.NoResultException; import javax.persistence.PersistenceContext; import javax.persistence.Query; public class UserDaoImpl extends DaoImpl<User> implements UserDao { public UserDaoImpl() { super(User.class); } @PersistenceContext private EntityManager entityManager; public EntityManager getEntityManager() { return entityManager; } public void setEntityManager(EntityManager entityManager) { this.entityManager = entityManager; } /* * (non-Javadoc) * @see br.com.biblicando.dao.UserDao#findOne(java.lang.String, * java.lang.String) */ @Override public User findOne(String username, String password) { try { Query query = entityManager .createQuery("select u from User u where u.username = :username and u.password = :password"); query.setParameter("username", username); query.setParameter("password", <PASSWORD>); return (User) query.getSingleResult(); } catch (NoResultException e) { return null; } catch (Exception e) { e.printStackTrace(); return null; } } }
1,374
0.653061
0.653061
49
27
23.749544
113
false
false
0
0
0
0
0
0
0.44898
false
false
11
eb2052850d425c9ca3610ebed63c439e989efbdc
27,994,596,878,022
f99f6ccd65f344d4c8651f4e4b058ec7f440f60c
/main5/project_jmgo/japp_xps_sales_order/src/main/java/com/yhglobal/gongxiao/sales/dao/SalesOutboundOrderDao.java
fc1cab5bcd5ae6b2bbd57e5018e406d61344d3c4
[]
no_license
wilnd/gongxiao
https://github.com/wilnd/gongxiao
fa60c9d5d57c3cbbb69d39e3848b42850bf22e12
f18bc2f48b4041ab09ee46876fd9f7a0dcb57a52
refs/heads/master
2020-03-28T05:50:50.258000
2018-09-07T09:32:00
2018-09-07T09:32:00
147,799,238
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.yhglobal.gongxiao.sales.dao; import com.yhglobal.gongxiao.sales.dao.mapping.SalesOutboundOrderMapper; import com.yhglobal.gongxiao.sales.model.SalesOutboundOrder; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import java.util.Date; import java.util.List; /** * @author 葛灿 */ @Repository public class SalesOutboundOrderDao { @Autowired SalesOutboundOrderMapper salesOutboundOrderMapper; public SalesOutboundOrder getOrderByOutboundNo(String prefix,String outboundNo) { return salesOutboundOrderMapper.getOrderByOutboundNo(prefix,outboundNo); } public int insert(String prefix,SalesOutboundOrder order) { return salesOutboundOrderMapper.insert(prefix,order); } // public int update(SalesOutboundOrder order) { // return salesOutboundOrderMapper.update(order); // } /** * 根据同步tms状态状态 查找所有的单号 * * @param status 同步tms状态 * @return List<出库单号> */ public List<String> selectListByTmsStatus(String prefix,int status) { return salesOutboundOrderMapper.selectListByTmsStatus(prefix,status); } /** * 修改同步tms状态 * * @param oid 主键id * @param dataVersion 数据版本 * @param syncTms 同步tms状态 * @return 更新成功条数 */ public int updateSyncTmsStatus(String prefix,long oid, long dataVersion, int syncTms) { return salesOutboundOrderMapper.updateSyncTmsStatus(prefix,oid, dataVersion, syncTms); } /** * 修改出库完成时间 * * @param oid 主键id * @param dataVersion 数据版本 * @param outboundOrderStatus 出库单状态 * @param outboundTime 出库时间 * @return 更新成功条数 */ public int updateOutboundTime(String prefix,long oid, long dataVersion, int outboundOrderStatus, Date outboundTime) { return salesOutboundOrderMapper.updateOutboundTime(prefix,oid, dataVersion, outboundOrderStatus, outboundTime); } /** * 更新签收信息 * * @param oid 主键 * @param dataVersion 数据版本 * @param tmsOrderNo tms运单号 * @param tmsRemark 备注 * @param signedBy 签收人 * @param postedBy 签收人 * @param signed 签收时间 * @param signedPhone 签收电话 * @param transporter 运输商 * @return */ public int updateWhenSigned(String prefix,long oid, long dataVersion, int orderStatus,String tmsOrderNo, String tmsRemark, String signedBy, String postedBy, Date signed, String signedPhone, String transporter) { return salesOutboundOrderMapper.updateWhenSigned(prefix,oid, dataVersion,orderStatus, tmsOrderNo, tmsRemark, signedBy, postedBy, signed, signedPhone, transporter); } }
UTF-8
Java
2,931
java
SalesOutboundOrderDao.java
Java
[ { "context": "util.Date;\nimport java.util.List;\n\n/**\n * @author 葛灿\n */\n@Repository\npublic class SalesOutboundOrderDa", "end": 354, "score": 0.8100107908248901, "start": 352, "tag": "NAME", "value": "葛灿" } ]
null
[]
package com.yhglobal.gongxiao.sales.dao; import com.yhglobal.gongxiao.sales.dao.mapping.SalesOutboundOrderMapper; import com.yhglobal.gongxiao.sales.model.SalesOutboundOrder; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import java.util.Date; import java.util.List; /** * @author 葛灿 */ @Repository public class SalesOutboundOrderDao { @Autowired SalesOutboundOrderMapper salesOutboundOrderMapper; public SalesOutboundOrder getOrderByOutboundNo(String prefix,String outboundNo) { return salesOutboundOrderMapper.getOrderByOutboundNo(prefix,outboundNo); } public int insert(String prefix,SalesOutboundOrder order) { return salesOutboundOrderMapper.insert(prefix,order); } // public int update(SalesOutboundOrder order) { // return salesOutboundOrderMapper.update(order); // } /** * 根据同步tms状态状态 查找所有的单号 * * @param status 同步tms状态 * @return List<出库单号> */ public List<String> selectListByTmsStatus(String prefix,int status) { return salesOutboundOrderMapper.selectListByTmsStatus(prefix,status); } /** * 修改同步tms状态 * * @param oid 主键id * @param dataVersion 数据版本 * @param syncTms 同步tms状态 * @return 更新成功条数 */ public int updateSyncTmsStatus(String prefix,long oid, long dataVersion, int syncTms) { return salesOutboundOrderMapper.updateSyncTmsStatus(prefix,oid, dataVersion, syncTms); } /** * 修改出库完成时间 * * @param oid 主键id * @param dataVersion 数据版本 * @param outboundOrderStatus 出库单状态 * @param outboundTime 出库时间 * @return 更新成功条数 */ public int updateOutboundTime(String prefix,long oid, long dataVersion, int outboundOrderStatus, Date outboundTime) { return salesOutboundOrderMapper.updateOutboundTime(prefix,oid, dataVersion, outboundOrderStatus, outboundTime); } /** * 更新签收信息 * * @param oid 主键 * @param dataVersion 数据版本 * @param tmsOrderNo tms运单号 * @param tmsRemark 备注 * @param signedBy 签收人 * @param postedBy 签收人 * @param signed 签收时间 * @param signedPhone 签收电话 * @param transporter 运输商 * @return */ public int updateWhenSigned(String prefix,long oid, long dataVersion, int orderStatus,String tmsOrderNo, String tmsRemark, String signedBy, String postedBy, Date signed, String signedPhone, String transporter) { return salesOutboundOrderMapper.updateWhenSigned(prefix,oid, dataVersion,orderStatus, tmsOrderNo, tmsRemark, signedBy, postedBy, signed, signedPhone, transporter); } }
2,931
0.693102
0.693102
85
30.894117
37.88311
215
false
false
0
0
0
0
0
0
0.647059
false
false
11
6c8062537ae627656817bf72537a186369dc7321
27,994,596,875,583
ab356469abdfbbd58fbbea08395b111370d815f2
/PARALLEL/src/com/capg/cms/dao/CustomerDAOImp.java
8bf357fe93ca80b84bda507e988956bb04a06ed6
[]
no_license
Hitee/p
https://github.com/Hitee/p
b56c10f3ed6aeb1bee6659586d83d93f3f44b3b5
4cad990ccd27cb0472d3b9b60f36f10a3762b85c
refs/heads/master
2020-04-02T13:42:05.467000
2019-08-06T04:55:08
2019-08-06T04:55:08
154,492,714
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.capg.cms.dao; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import com.capg.cms.beans.Customer; public class CustomerDAOImp implements ICustomerDAO { //for database use collections public static List<Customer> custList = new ArrayList<Customer>(); @Override public boolean addCustomer(Customer c) { // TODO Auto-generated method stub boolean isAdded = false; // add - predefined method of collections, returns boolean value isAdded = custList.add(c); return isAdded; } //@Override public Customer displayCustomer(long accountNo , int pin) { // TODO Auto-generated method stub Customer cust = null; for(Customer c : custList) { if(c.getAccountNo() == accountNo && c.getPin() == pin) { cust = c; } } return cust; } public Customer deposit(long accountNo , double depositAmount, StringBuffer sb ) { // TODO Auto-generated method stub Customer cust = null; for(Customer c : custList) { if(c.getAccountNo() == accountNo) { double amt = c.getBalance(); String numberAsString = Double.toString(depositAmount); System.out.println("inside deposit"); //String str = "a string"; StringBuffer strbuf; strbuf = new StringBuffer(numberAsString); c.setSb(sb.append(strbuf)); amt = amt + depositAmount; c.setBalance(amt); //c.setSb(sb); System.out.println("this id c.getsb" + c.getSb()); //c.getSb(); //StringBuffer a = c.getSb(); /*sb.append(" amount DEPOSITED is: " + depositAmount); c.setSb(sb); System.out.println("this is a " + c.getSb()); */ cust = c; } } return cust; } public Customer withdraw(long accountNo , int pin , double withdrawAmount, StringBuffer sb) { // TODO Auto-generated method stub Customer cust = null; for(Customer c : custList) { if(c.getAccountNo() == accountNo && c.getPin() == pin ) { double amt = c.getBalance(); if(withdrawAmount < amt) { amt = amt - withdrawAmount; StringBuffer a = c.getSb(); a.append(" amount WITHDRAWN is: " + withdrawAmount); System.out.println(a); c.setBalance(amt); cust = c; } } } return cust; } public Customer fundTransfer(long accountNo , int pin, long accountNoTransfer , double amountTransfer, StringBuffer sb, StringBuffer sbT) { Customer cust = null; for(Customer c : custList) { if(c.getAccountNo() == accountNo && c.getPin() == pin ) { double amt = c.getBalance(); if(amountTransfer < amt) { System.out.println("dwdwdwe"); double from = c.getBalance(); from = from - amountTransfer; c.setBalance(from); for(Customer c1 : custList) { if(c1.getAccountNo() == accountNoTransfer) { double to = c1.getBalance(); to = to + amountTransfer; c1.setBalance(to); cust = c1; System.out.println("aaaaaaaaa"); System.out.println(c1.getBalance()); } else { System.out.println("sssssssss"); } } } } } return cust; } public Customer printTransactions(long accountNo , int pin) { Customer cust = null; for(Customer c : custList) { if(c.getAccountNo() == accountNo && c.getPin() == pin) { System.out.println("this is printing transactions"); System.out.println(c.getSb()); cust = c; } } return cust; } /*public Customer displayAll() { Customer c = null; Iterator<Customer> it = custList.iterator(); while(it.hasNext()) { c = it.next(); //System.out.println(c + " "); } return c; }*/ public void displayAll() { Customer c = null; Iterator<Customer> it = custList.iterator(); while(it.hasNext()) { c = it.next(); System.out.println(c + " "); } //return c; } /*public boolean isValidEmailAddress(String email) { String ePattern = "^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$"; java.util.regex.Pattern p = java.util.regex.Pattern.compile(ePattern); java.util.regex.Matcher m = p.matcher(email); return m.matches(); }*/ }
UTF-8
Java
4,538
java
CustomerDAOImp.java
Java
[]
null
[]
package com.capg.cms.dao; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import com.capg.cms.beans.Customer; public class CustomerDAOImp implements ICustomerDAO { //for database use collections public static List<Customer> custList = new ArrayList<Customer>(); @Override public boolean addCustomer(Customer c) { // TODO Auto-generated method stub boolean isAdded = false; // add - predefined method of collections, returns boolean value isAdded = custList.add(c); return isAdded; } //@Override public Customer displayCustomer(long accountNo , int pin) { // TODO Auto-generated method stub Customer cust = null; for(Customer c : custList) { if(c.getAccountNo() == accountNo && c.getPin() == pin) { cust = c; } } return cust; } public Customer deposit(long accountNo , double depositAmount, StringBuffer sb ) { // TODO Auto-generated method stub Customer cust = null; for(Customer c : custList) { if(c.getAccountNo() == accountNo) { double amt = c.getBalance(); String numberAsString = Double.toString(depositAmount); System.out.println("inside deposit"); //String str = "a string"; StringBuffer strbuf; strbuf = new StringBuffer(numberAsString); c.setSb(sb.append(strbuf)); amt = amt + depositAmount; c.setBalance(amt); //c.setSb(sb); System.out.println("this id c.getsb" + c.getSb()); //c.getSb(); //StringBuffer a = c.getSb(); /*sb.append(" amount DEPOSITED is: " + depositAmount); c.setSb(sb); System.out.println("this is a " + c.getSb()); */ cust = c; } } return cust; } public Customer withdraw(long accountNo , int pin , double withdrawAmount, StringBuffer sb) { // TODO Auto-generated method stub Customer cust = null; for(Customer c : custList) { if(c.getAccountNo() == accountNo && c.getPin() == pin ) { double amt = c.getBalance(); if(withdrawAmount < amt) { amt = amt - withdrawAmount; StringBuffer a = c.getSb(); a.append(" amount WITHDRAWN is: " + withdrawAmount); System.out.println(a); c.setBalance(amt); cust = c; } } } return cust; } public Customer fundTransfer(long accountNo , int pin, long accountNoTransfer , double amountTransfer, StringBuffer sb, StringBuffer sbT) { Customer cust = null; for(Customer c : custList) { if(c.getAccountNo() == accountNo && c.getPin() == pin ) { double amt = c.getBalance(); if(amountTransfer < amt) { System.out.println("dwdwdwe"); double from = c.getBalance(); from = from - amountTransfer; c.setBalance(from); for(Customer c1 : custList) { if(c1.getAccountNo() == accountNoTransfer) { double to = c1.getBalance(); to = to + amountTransfer; c1.setBalance(to); cust = c1; System.out.println("aaaaaaaaa"); System.out.println(c1.getBalance()); } else { System.out.println("sssssssss"); } } } } } return cust; } public Customer printTransactions(long accountNo , int pin) { Customer cust = null; for(Customer c : custList) { if(c.getAccountNo() == accountNo && c.getPin() == pin) { System.out.println("this is printing transactions"); System.out.println(c.getSb()); cust = c; } } return cust; } /*public Customer displayAll() { Customer c = null; Iterator<Customer> it = custList.iterator(); while(it.hasNext()) { c = it.next(); //System.out.println(c + " "); } return c; }*/ public void displayAll() { Customer c = null; Iterator<Customer> it = custList.iterator(); while(it.hasNext()) { c = it.next(); System.out.println(c + " "); } //return c; } /*public boolean isValidEmailAddress(String email) { String ePattern = "^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$"; java.util.regex.Pattern p = java.util.regex.Pattern.compile(ePattern); java.util.regex.Matcher m = p.matcher(email); return m.matches(); }*/ }
4,538
0.565668
0.559718
216
19.00926
22.862915
159
false
false
0
0
0
0
0
0
2.967592
false
false
11
be61b97765911a8f4a6280f49ce7ead432342e9c
27,453,431,003,767
9c750098fad7111dcc0a6f231258f9bfa9d95a11
/Sean/src/tw/org/iii/mytest/Brad77.java
91460a8659964c73643ffd13f1c0002972cf6698
[]
no_license
Seanhhe/FSIT05_Java
https://github.com/Seanhhe/FSIT05_Java
556fc7253c261c78cb7e7d21921d9bad3de4e040
75fdd848a843972fe700105c0486dc1bff934fd9
refs/heads/master
2020-03-23T17:32:47.199000
2018-09-09T15:17:50
2018-09-09T15:17:50
141,864,184
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * 檔案的IO及網際網路的處理常運用執行緒 */ package tw.org.iii.mytest; import java.util.TimerTask; public class Brad77 { public static void main(String[] args) { Brad771 obj1 = new Brad771();//是執行緒 Brad772 obj2 = new Brad772();//此用法比執行緒彈性,可認別的父類別 Brad773 obj3 = new Brad773(); obj1.start();//是執行緒,有start()可用 //obj2沒實作start可用 //Thread t2 = new Thread(obj2);//用java.lang.Thread的建構式Thread(Runnable) //t2.start(); Thread t3 = new Thread(obj3); t3.start(); Thread t4 = new Thread(obj2) {//不寫class,改寫在裏頭的執行緒(註解掉19,20行後存檔執行測試) public void run() { System.out.println("t4"); } }; t4.start(); new Thread() { public void run() {//override for (int i=10000; i<10020; i++) { System.out.println(i); try { Thread.sleep(100); }catch (InterruptedException e) { } } } }.start(); System.out.println("OK"); } } //只能繼承一個父類別Thread class Brad771 extends Thread { @Override public void run() { super.run(); for (int i = 0; i<20; i++) { System.out.println(i); try { Thread.sleep(100); }catch(Exception e) { } } } } //實作Runnable,不代表執行緒Thread class Brad772 implements Runnable { @Override public void run() { for (int i = 100; i<120; i++) { System.out.println(i); try { Thread.sleep(100); }catch(Exception e) { } } } } class Brad773 extends TimerTask { @Override public void run() { // TODO Auto-generated method stub for (int i = 100; i<220; i++) { System.out.println(i); try { Thread.sleep(100); }catch(Exception e) { } } } }
UTF-8
Java
1,886
java
Brad77.java
Java
[]
null
[]
/* * 檔案的IO及網際網路的處理常運用執行緒 */ package tw.org.iii.mytest; import java.util.TimerTask; public class Brad77 { public static void main(String[] args) { Brad771 obj1 = new Brad771();//是執行緒 Brad772 obj2 = new Brad772();//此用法比執行緒彈性,可認別的父類別 Brad773 obj3 = new Brad773(); obj1.start();//是執行緒,有start()可用 //obj2沒實作start可用 //Thread t2 = new Thread(obj2);//用java.lang.Thread的建構式Thread(Runnable) //t2.start(); Thread t3 = new Thread(obj3); t3.start(); Thread t4 = new Thread(obj2) {//不寫class,改寫在裏頭的執行緒(註解掉19,20行後存檔執行測試) public void run() { System.out.println("t4"); } }; t4.start(); new Thread() { public void run() {//override for (int i=10000; i<10020; i++) { System.out.println(i); try { Thread.sleep(100); }catch (InterruptedException e) { } } } }.start(); System.out.println("OK"); } } //只能繼承一個父類別Thread class Brad771 extends Thread { @Override public void run() { super.run(); for (int i = 0; i<20; i++) { System.out.println(i); try { Thread.sleep(100); }catch(Exception e) { } } } } //實作Runnable,不代表執行緒Thread class Brad772 implements Runnable { @Override public void run() { for (int i = 100; i<120; i++) { System.out.println(i); try { Thread.sleep(100); }catch(Exception e) { } } } } class Brad773 extends TimerTask { @Override public void run() { // TODO Auto-generated method stub for (int i = 100; i<220; i++) { System.out.println(i); try { Thread.sleep(100); }catch(Exception e) { } } } }
1,886
0.559102
0.508865
95
15.810526
15.008976
72
false
false
0
0
0
0
0
0
2.357895
false
false
11
b23793cfe193a40a57a4f1903ccb5006efaf2365
13,280,038,932,402
ab1986e98d958b0f79c746447d6fba7ee83571cb
/CoreJavaTraining/src/com/visalab/day/two/TestGitSettingInIntelliJ.java
605ee2849337ce55fe8911a7e59d9b12418fda16
[]
no_license
charan1312/VisaLabs
https://github.com/charan1312/VisaLabs
919354b5573defa816db0e409e0cef0adac0cace
152bd89fc03b06d2653e467891b1a6df87f19927
refs/heads/master
2021-01-19T02:21:58.861000
2016-07-15T23:25:17
2016-07-15T23:25:17
62,839,124
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.visalab.day.two; /** * Created by CAWARE on 7/6/2016. */ public class TestGitSettingInIntelliJ { }
UTF-8
Java
114
java
TestGitSettingInIntelliJ.java
Java
[ { "context": "package com.visalab.day.two;\n\n/**\n * Created by CAWARE on 7/6/2016.\n */\npublic class TestGitSettingInInt", "end": 54, "score": 0.9993114471435547, "start": 48, "tag": "USERNAME", "value": "CAWARE" } ]
null
[]
package com.visalab.day.two; /** * Created by CAWARE on 7/6/2016. */ public class TestGitSettingInIntelliJ { }
114
0.710526
0.657895
7
15.285714
15.934816
39
false
false
0
0
0
0
0
0
0.142857
false
false
11
f8a67492ffdb6f0c16539ebb679de6e3cab813ea
24,721,831,762,122
057b56e7b7e8a2e9147dbe31cb0664551b39ffeb
/src/cs10/common/unit/base/temperature/absolute/Kelvin.java
4a78395bf0004ae8472f79eb117775b0c5f82849
[]
no_license
sergiocarp10/cs10-common-libraries
https://github.com/sergiocarp10/cs10-common-libraries
cc53eb14cbbdbccda8058f2469386b0ed5469ca3
30d6938f745d938ab5657b17f6f3fe663ae22e2e
refs/heads/master
2023-02-12T02:53:48.882000
2021-01-08T02:39:40
2021-01-08T02:39:40
327,751,210
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package cs10.common.unit.base.temperature.absolute; import cs10.common.unit.Conversion; import cs10.common.unit.base.temperature.relative.Celsius; public class Kelvin extends AbsoluteTemperature { public static String ABBREV = "K"; public Kelvin(){} public Kelvin(double value){ setValue(value); } public Kelvin(Celsius celsius){ setValue(celsius.getValue() + Conversion.CELSIUS_KELVIN.getNumber()); } @Override public Celsius getInCelsius() { return new Celsius(this); } @Override public Kelvin getInKelvin() { return this; } @Override public String getAbbreviation() { return ABBREV; } }
UTF-8
Java
698
java
Kelvin.java
Java
[]
null
[]
package cs10.common.unit.base.temperature.absolute; import cs10.common.unit.Conversion; import cs10.common.unit.base.temperature.relative.Celsius; public class Kelvin extends AbsoluteTemperature { public static String ABBREV = "K"; public Kelvin(){} public Kelvin(double value){ setValue(value); } public Kelvin(Celsius celsius){ setValue(celsius.getValue() + Conversion.CELSIUS_KELVIN.getNumber()); } @Override public Celsius getInCelsius() { return new Celsius(this); } @Override public Kelvin getInKelvin() { return this; } @Override public String getAbbreviation() { return ABBREV; } }
698
0.661891
0.653295
33
20.151516
19.937965
77
false
false
0
0
0
0
0
0
0.272727
false
false
11
9a97c02d118f143324d14de8227f874bf8511e0c
26,199,300,511,989
034ced4b9e5ae5d8057f3eb893199550cfe13fd2
/src/java/main/com/identiticoders/assignment/mapper/DepartmentMapper.java
aa32df8cc7ee64c9d07d856394b5021dfbfd84aa
[]
no_license
manilacoffee/Identiticoders
https://github.com/manilacoffee/Identiticoders
2f149a03c29d36d5315909aa6b09c2c2f82789fa
8d71fb27a32601ac5ebe7d1b93b9e272290b8194
refs/heads/master
2020-04-28T08:32:39.118000
2019-03-12T10:14:58
2019-03-12T10:14:58
175,131,848
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.identiticoders.assignment.mapper; import com.identiticoders.assignment.beans.Department; import com.identiticoders.assignment.extractor.DepartmentExtractor; import java.sql.ResultSet; import java.sql.SQLException; import org.springframework.jdbc.core.RowMapper; public class DepartmentMapper implements RowMapper<Department> { public Department mapRow(ResultSet rs, int rowNum) throws SQLException { DepartmentExtractor departmentExtractor = new DepartmentExtractor(); return departmentExtractor.extractData(rs); } }
UTF-8
Java
571
java
DepartmentMapper.java
Java
[]
null
[]
package com.identiticoders.assignment.mapper; import com.identiticoders.assignment.beans.Department; import com.identiticoders.assignment.extractor.DepartmentExtractor; import java.sql.ResultSet; import java.sql.SQLException; import org.springframework.jdbc.core.RowMapper; public class DepartmentMapper implements RowMapper<Department> { public Department mapRow(ResultSet rs, int rowNum) throws SQLException { DepartmentExtractor departmentExtractor = new DepartmentExtractor(); return departmentExtractor.extractData(rs); } }
571
0.789842
0.789842
19
28.052631
23.893345
72
false
false
0
0
0
0
0
0
0.473684
false
false
11
15975dc726a48581de4c3492f9398299d77f801c
20,864,951,195,214
b2c839764f0148622a92d16b444f48608ff87d92
/lld/machinecoding/src/main/java/lld/authentication/stateless/StateLessAuthentication.java
dbc3879442f0c2aeb1e29d30728d7fa535c89a94
[]
no_license
anantiit/reachgoal
https://github.com/anantiit/reachgoal
718507c2b68a3c8cf29a82c7bb9391306cd7e410
c7f70aade379c9b557fb195a6138c7861e9e8b56
refs/heads/master
2023-07-09T08:24:09.749000
2023-07-04T17:29:42
2023-07-04T17:29:42
75,408,803
0
0
null
false
2023-06-22T13:18:27
2016-12-02T15:45:06
2023-06-01T11:45:24
2023-06-22T13:18:26
154,681
0
0
20
Java
false
false
package lld.authentication.stateless; @RestController public class UserController { @Autowired private JwtTokenUtil jwtTokenUtil; @PostMapping("/login") public String login(@RequestBody UserCredentials credentials) { // TODO: Implement login logic and validate user credentials if (isValidUser(credentials.getUsername(), credentials.getPassword())) { // Generate and return a JWT token String token = jwtTokenUtil.generateToken(credentials.getUsername()); return token; } else { // Return an error response return "Invalid credentials"; } } @PostMapping("/logout") public String logout() { // TODO: Implement logout logic // Perform any necessary cleanup or session management // Return a success message return "Logged out successfully"; } private boolean isValidUser(String username, String password) { // TODO: Implement user validation logic // Check if the provided username and password are valid // Return true if valid, false otherwise return true; // Placeholder implementation } }
UTF-8
Java
1,048
java
StateLessAuthentication.java
Java
[]
null
[]
package lld.authentication.stateless; @RestController public class UserController { @Autowired private JwtTokenUtil jwtTokenUtil; @PostMapping("/login") public String login(@RequestBody UserCredentials credentials) { // TODO: Implement login logic and validate user credentials if (isValidUser(credentials.getUsername(), credentials.getPassword())) { // Generate and return a JWT token String token = jwtTokenUtil.generateToken(credentials.getUsername()); return token; } else { // Return an error response return "Invalid credentials"; } } @PostMapping("/logout") public String logout() { // TODO: Implement logout logic // Perform any necessary cleanup or session management // Return a success message return "Logged out successfully"; } private boolean isValidUser(String username, String password) { // TODO: Implement user validation logic // Check if the provided username and password are valid // Return true if valid, false otherwise return true; // Placeholder implementation } }
1,048
0.744275
0.744275
39
25.871796
23.145227
74
false
false
0
0
0
0
0
0
1.51282
false
false
11
62560d7e295d36be6bc670a3829bd764f28c838a
10,170,482,606,276
0f1b2f36ee2698d78b35d3145bf406eef22f3b98
/AS03/Sistema/LocacaoVeiculos/src/view/ViewVeiculo.java
515921b17526933a3d8c6740709ff194f8dbb18e
[]
no_license
kayo08/IApl-2019-1-LocV
https://github.com/kayo08/IApl-2019-1-LocV
57a7af0cb9c9a21a9031d401abd6506f7179009f
a1f9fe99e60116fcde4819842670c7d0d999fb15
refs/heads/master
2020-05-02T01:31:57.440000
2019-06-17T20:15:53
2019-06-17T20:15:53
177,687,678
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package view; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import javax.swing.JOptionPane; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableRowSorter; import json.JSONArray; import json.JSONObject; import model.bean.Veiculo; import model.dao.VeiculoDAO; /** * * @author Murilo */ public class ViewVeiculo extends javax.swing.JFrame { String modo; String caso; /** * Creates new form viewVeiculo */ public ViewVeiculo() { initComponents(); setLocationRelativeTo(null); iniciarJanelaVeiculo(); readJTable(); modo = "Navegar"; manipulaInterfaceVeiculo(); DefaultTableModel modelo = (DefaultTableModel) table_veiculo_veiculos.getModel(); table_veiculo_veiculos.setRowSorter(new TableRowSorter(modelo)); } /** * 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. */ public void readJTable() { DefaultTableModel modelo = (DefaultTableModel) table_veiculo_veiculos.getModel(); modelo.setNumRows(0); VeiculoDAO pdao = new VeiculoDAO(); for (Veiculo p : pdao.read()) { modelo.addRow(new Object[]{ p.getMarca(), p.getModelo(), p.getPlaca(), p.getCor(), p.getAno() }); } } public void manipulaInterfaceVeiculo() { switch (modo) { case "Navegar": botao_veiculo_salvar.setEnabled(false); botao_veiculo_cancelar.setEnabled(false); botao_veiculo_novo.setEnabled(true); botao_veiculo_editar.setEnabled(false); botao_veiculo_excluir.setEnabled(false); campo_veiculo_marca.setEnabled(false); campo_veiculo_modelo.setEnabled(false); campo_veiculo_placa.setEnabled(false); campo_veiculo_cor.setEnabled(false); campo_veiculo_ano.setEnabled(false); break; case "Novo": botao_veiculo_salvar.setEnabled(true); botao_veiculo_cancelar.setEnabled(true); botao_veiculo_novo.setEnabled(false); botao_veiculo_editar.setEnabled(false); botao_veiculo_excluir.setEnabled(false); campo_veiculo_marca.setEnabled(true); campo_veiculo_modelo.setEnabled(true); campo_veiculo_placa.setEnabled(true); campo_veiculo_cor.setEnabled(true); campo_veiculo_ano.setEnabled(true); break; case "Editar": botao_veiculo_salvar.setEnabled(true); botao_veiculo_cancelar.setEnabled(true); botao_veiculo_novo.setEnabled(false); botao_veiculo_editar.setEnabled(false); botao_veiculo_excluir.setEnabled(false); campo_veiculo_marca.setEnabled(true); campo_veiculo_modelo.setEnabled(true); campo_veiculo_placa.setEnabled(true); campo_veiculo_cor.setEnabled(true); campo_veiculo_ano.setEnabled(true); break; case "Excluir": botao_veiculo_salvar.setEnabled(false); botao_veiculo_cancelar.setEnabled(false); botao_veiculo_novo.setEnabled(true); botao_veiculo_editar.setEnabled(false); botao_veiculo_excluir.setEnabled(false); campo_veiculo_marca.setEnabled(false); campo_veiculo_modelo.setEnabled(false); campo_veiculo_placa.setEnabled(false); campo_veiculo_cor.setEnabled(false); campo_veiculo_ano.setEnabled(false); break; case "Selecao": botao_veiculo_salvar.setEnabled(false); botao_veiculo_cancelar.setEnabled(false); botao_veiculo_novo.setEnabled(true); botao_veiculo_editar.setEnabled(true); botao_veiculo_excluir.setEnabled(true); campo_veiculo_marca.setEnabled(false); campo_veiculo_modelo.setEnabled(false); campo_veiculo_placa.setEnabled(false); campo_veiculo_cor.setEnabled(false); campo_veiculo_ano.setEnabled(false); break; default: System.out.println("Modo inválido"); } } public void iniciarJanelaVeiculo() { campo_veiculo_marca.setText(""); campo_veiculo_modelo.setText(""); campo_veiculo_placa.setText(""); campo_veiculo_cor.setText(""); campo_veiculo_ano.setText(""); botao_veiculo_menu.setEnabled(true); botao_veiculo_importar.setEnabled(true); botao_veiculo_exportar.setEnabled(true); } public void gravarInformacaoVeiculo() { File file = new File("Veiculo.json"); String conteudo; try { VeiculoDAO pdao = new VeiculoDAO(); FileWriter f = new FileWriter(file, true); for (Veiculo p : pdao.read()) { JSONObject json = new JSONObject(); conteudo = p.toJson().toString(); conteudo += "\r\n"; f.write(conteudo); } f.close(); JOptionPane.showMessageDialog(null, "Dados Exportados com sucesso!"); } catch (IOException e) { JOptionPane.showMessageDialog(null, "Não foi possível realizar esta ação"); } } public void carregarInformacaoVeiculo() { try { VeiculoDAO pdao = new VeiculoDAO(); FileReader fr = new FileReader("Veiculo.json"); BufferedReader br = new BufferedReader(fr); String str; while ((str = br.readLine()) != null) { Veiculo p = new Veiculo(); JSONArray json = new JSONArray(str.toString()); for (int i = 0; i < json.length(); i++) { JSONObject obj = json.getJSONObject(i); p.setMarca(obj.getString("marca")); p.setModelo(obj.getString("modelo")); p.setPlaca(obj.getString("placa")); p.setCor(obj.getString("cor")); p.setAno(obj.getInt("ano")); if (i + 1 == json.length()) { pdao.create(p); } } } br.close(); JOptionPane.showMessageDialog(null, "Dados Importados com sucesso!"); } catch (IOException e) { JOptionPane.showMessageDialog(null, "Não foi possível realizar esta ação"); } } public void limparCamposVeiculo() { campo_veiculo_marca.setText(""); campo_veiculo_modelo.setText(""); campo_veiculo_placa.setText(""); campo_veiculo_cor.setText(""); campo_veiculo_ano.setText(""); } public void lerTabelaPorMarca(String marca) { DefaultTableModel modelo = (DefaultTableModel) table_veiculo_veiculos.getModel(); modelo.setNumRows(0); VeiculoDAO pdao = new VeiculoDAO(); for (Veiculo p : pdao.lerPorMarca(marca)) { modelo.addRow(new Object[]{ p.getMarca(), p.getModelo(), p.getPlaca(), p.getCor(), p.getAno() }); } } @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel5 = new javax.swing.JPanel(); jLabel8 = new javax.swing.JLabel(); campo_veiculo_marca = new javax.swing.JTextField(); jLabel9 = new javax.swing.JLabel(); campo_veiculo_modelo = new javax.swing.JTextField(); jLabel10 = new javax.swing.JLabel(); jLabel11 = new javax.swing.JLabel(); jLabel12 = new javax.swing.JLabel(); campo_veiculo_placa = new javax.swing.JTextField(); campo_veiculo_cor = new javax.swing.JTextField(); campo_veiculo_ano = new javax.swing.JTextField(); botao_veiculo_salvar = new javax.swing.JButton(); botao_veiculo_cancelar = new javax.swing.JButton(); botao_veiculo_menu = new javax.swing.JButton(); botao_veiculo_exportar = new javax.swing.JButton(); botao_veiculo_importar = new javax.swing.JButton(); jScrollPane2 = new javax.swing.JScrollPane(); table_veiculo_veiculos = new javax.swing.JTable(); botao_veiculo_editar = new javax.swing.JButton(); botao_veiculo_novo = new javax.swing.JButton(); botao_veiculo_excluir = new javax.swing.JButton(); botao_veiculo_buscar = new javax.swing.JButton(); campo_veiculo_buscar = new javax.swing.JTextField(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jPanel5.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)), "Veículo", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 0, 18))); // NOI18N jPanel5.setPreferredSize(new java.awt.Dimension(750, 260)); jLabel8.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel8.setText("Marca:"); campo_veiculo_marca.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { campo_veiculo_marcaActionPerformed(evt); } }); jLabel9.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel9.setText("Modelo:"); jLabel10.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel10.setText("Placa:"); jLabel11.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel11.setText("Cor:"); jLabel12.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel12.setText("Ano:"); campo_veiculo_placa.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { campo_veiculo_placaActionPerformed(evt); } }); campo_veiculo_cor.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { campo_veiculo_corActionPerformed(evt); } }); botao_veiculo_salvar.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N botao_veiculo_salvar.setText("Salvar"); botao_veiculo_salvar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { botao_veiculo_salvarActionPerformed(evt); } }); botao_veiculo_cancelar.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N botao_veiculo_cancelar.setText("Cancelar"); botao_veiculo_cancelar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { botao_veiculo_cancelarActionPerformed(evt); } }); botao_veiculo_menu.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N botao_veiculo_menu.setText("Menu principal"); botao_veiculo_menu.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { botao_veiculo_menuActionPerformed(evt); } }); botao_veiculo_exportar.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N botao_veiculo_exportar.setText("Exportar Dados"); botao_veiculo_exportar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { botao_veiculo_exportarActionPerformed(evt); } }); botao_veiculo_importar.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N botao_veiculo_importar.setText("Importar Dados"); botao_veiculo_importar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { botao_veiculo_importarActionPerformed(evt); } }); javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5); jPanel5.setLayout(jPanel5Layout); jPanel5Layout.setHorizontalGroup( jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel5Layout.createSequentialGroup() .addGap(25, 25, 25) .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabel12) .addComponent(jLabel11) .addComponent(jLabel8) .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addGroup(jPanel5Layout.createSequentialGroup() .addGap(10, 10, 10) .addComponent(jLabel10, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addComponent(jLabel9, javax.swing.GroupLayout.Alignment.TRAILING))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(campo_veiculo_ano, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 167, Short.MAX_VALUE) .addComponent(campo_veiculo_placa) .addComponent(campo_veiculo_modelo) .addComponent(campo_veiculo_marca) .addComponent(campo_veiculo_cor)) .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel5Layout.createSequentialGroup() .addGap(142, 142, 142) .addComponent(botao_veiculo_menu, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel5Layout.createSequentialGroup() .addGap(53, 53, 53) .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(botao_veiculo_exportar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(botao_veiculo_salvar, javax.swing.GroupLayout.DEFAULT_SIZE, 130, Short.MAX_VALUE)) .addGap(41, 41, 41) .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(botao_veiculo_cancelar, javax.swing.GroupLayout.DEFAULT_SIZE, 130, Short.MAX_VALUE) .addComponent(botao_veiculo_importar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))) .addGap(82, 82, 82)) ); jPanel5Layout.setVerticalGroup( jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel5Layout.createSequentialGroup() .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel5Layout.createSequentialGroup() .addGap(82, 82, 82) .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(botao_veiculo_cancelar) .addComponent(botao_veiculo_salvar)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 33, Short.MAX_VALUE) .addComponent(botao_veiculo_menu)) .addGroup(jPanel5Layout.createSequentialGroup() .addGap(27, 27, 27) .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(botao_veiculo_exportar) .addComponent(botao_veiculo_importar)) .addGap(0, 0, Short.MAX_VALUE))) .addContainerGap()) .addGroup(jPanel5Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel8) .addComponent(campo_veiculo_marca, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(campo_veiculo_modelo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel9)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel10) .addComponent(campo_veiculo_placa, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel11) .addComponent(campo_veiculo_cor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel12) .addComponent(campo_veiculo_ano, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); table_veiculo_veiculos.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N table_veiculo_veiculos.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { }, new String [] { " Marca", "Modelo", "Placa", "Cor", "Ano" } ) { boolean[] canEdit = new boolean [] { false, false, false, false, false }; public boolean isCellEditable(int rowIndex, int columnIndex) { return canEdit [columnIndex]; } }); table_veiculo_veiculos.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { table_veiculo_veiculosMouseClicked(evt); } }); table_veiculo_veiculos.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { table_veiculo_veiculosKeyReleased(evt); } }); jScrollPane2.setViewportView(table_veiculo_veiculos); botao_veiculo_editar.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N botao_veiculo_editar.setText("Editar"); botao_veiculo_editar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { botao_veiculo_editarActionPerformed(evt); } }); botao_veiculo_novo.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N botao_veiculo_novo.setText("Novo"); botao_veiculo_novo.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { botao_veiculo_novoActionPerformed(evt); } }); botao_veiculo_excluir.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N botao_veiculo_excluir.setText("Excluir"); botao_veiculo_excluir.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { botao_veiculo_excluirActionPerformed(evt); } }); botao_veiculo_buscar.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N botao_veiculo_buscar.setText("Buscar por marca"); botao_veiculo_buscar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { botao_veiculo_buscarActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(botao_veiculo_novo, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(botao_veiculo_editar, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(botao_veiculo_excluir, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 26, Short.MAX_VALUE) .addComponent(campo_veiculo_buscar, javax.swing.GroupLayout.PREFERRED_SIZE, 140, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(27, 27, 27) .addComponent(botao_veiculo_buscar) .addContainerGap()) .addComponent(jScrollPane2) .addComponent(jPanel5, javax.swing.GroupLayout.DEFAULT_SIZE, 690, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(campo_veiculo_buscar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(botao_veiculo_novo) .addComponent(botao_veiculo_editar) .addComponent(botao_veiculo_excluir) .addComponent(botao_veiculo_buscar))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jPanel5, javax.swing.GroupLayout.DEFAULT_SIZE, 205, Short.MAX_VALUE)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void campo_veiculo_marcaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_campo_veiculo_marcaActionPerformed // TODO add your handling code here: }//GEN-LAST:event_campo_veiculo_marcaActionPerformed private void campo_veiculo_placaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_campo_veiculo_placaActionPerformed // TODO add your handling code here: }//GEN-LAST:event_campo_veiculo_placaActionPerformed private void campo_veiculo_corActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_campo_veiculo_corActionPerformed // TODO add your handling code here: }//GEN-LAST:event_campo_veiculo_corActionPerformed private void botao_veiculo_salvarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botao_veiculo_salvarActionPerformed if (caso == "Editar") { if (table_veiculo_veiculos.getSelectedRow() != -1) { Veiculo p = new Veiculo(); VeiculoDAO dao = new VeiculoDAO(); p.setMarca(campo_veiculo_marca.getText()); p.setModelo(campo_veiculo_modelo.getText()); p.setPlaca(campo_veiculo_placa.getText()); p.setCor(campo_veiculo_cor.getText()); p.setAno(Integer.parseInt(campo_veiculo_ano.getText())); dao.update(p); readJTable(); caso = ""; modo = "Navegar"; manipulaInterfaceVeiculo(); limparCamposVeiculo(); } } if(caso == "Salvar"){ Veiculo p = new Veiculo(); VeiculoDAO dao = new VeiculoDAO(); p.setMarca(campo_veiculo_marca.getText()); p.setModelo(campo_veiculo_modelo.getText()); p.setPlaca(campo_veiculo_placa.getText()); p.setCor(campo_veiculo_cor.getText()); p.setAno(Integer.parseInt(campo_veiculo_ano.getText())); dao.create(p); limparCamposVeiculo(); readJTable(); caso = ""; modo = "Navegar"; manipulaInterfaceVeiculo(); } }//GEN-LAST:event_botao_veiculo_salvarActionPerformed private void botao_veiculo_cancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botao_veiculo_cancelarActionPerformed limparCamposVeiculo(); modo = "Navegar"; manipulaInterfaceVeiculo(); }//GEN-LAST:event_botao_veiculo_cancelarActionPerformed private void table_veiculo_veiculosMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_table_veiculo_veiculosMouseClicked modo = "Selecao"; manipulaInterfaceVeiculo(); if (table_veiculo_veiculos.getSelectedRow() != -1) { campo_veiculo_marca.setText(table_veiculo_veiculos.getValueAt(table_veiculo_veiculos.getSelectedRow(), 0).toString()); campo_veiculo_modelo.setText(table_veiculo_veiculos.getValueAt(table_veiculo_veiculos.getSelectedRow(), 1).toString()); campo_veiculo_placa.setText(table_veiculo_veiculos.getValueAt(table_veiculo_veiculos.getSelectedRow(), 2).toString()); campo_veiculo_cor.setText(table_veiculo_veiculos.getValueAt(table_veiculo_veiculos.getSelectedRow(), 3).toString()); campo_veiculo_ano.setText(table_veiculo_veiculos.getValueAt(table_veiculo_veiculos.getSelectedRow(), 4).toString()); } }//GEN-LAST:event_table_veiculo_veiculosMouseClicked private void botao_veiculo_editarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botao_veiculo_editarActionPerformed modo = "Editar"; manipulaInterfaceVeiculo(); caso = "Editar"; }//GEN-LAST:event_botao_veiculo_editarActionPerformed private void botao_veiculo_novoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botao_veiculo_novoActionPerformed limparCamposVeiculo(); caso = "Salvar"; modo = "Novo"; manipulaInterfaceVeiculo(); }//GEN-LAST:event_botao_veiculo_novoActionPerformed private void botao_veiculo_excluirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botao_veiculo_excluirActionPerformed if (table_veiculo_veiculos.getSelectedRow() != -1) { int index = table_veiculo_veiculos.getSelectedRow(); Veiculo p = new Veiculo(); VeiculoDAO dao = new VeiculoDAO(); p.setPlaca((String) table_veiculo_veiculos.getValueAt(table_veiculo_veiculos.getSelectedRow(), 2)); dao.delete(p); limparCamposVeiculo(); readJTable(); } else { JOptionPane.showMessageDialog(null, "Selecione um produto para excluir."); } modo = "Navegar"; }//GEN-LAST:event_botao_veiculo_excluirActionPerformed private void table_veiculo_veiculosKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_table_veiculo_veiculosKeyReleased if (table_veiculo_veiculos.getSelectedRow() != -1) { campo_veiculo_marca.setText(table_veiculo_veiculos.getValueAt(table_veiculo_veiculos.getSelectedRow(), 0).toString()); campo_veiculo_modelo.setText(table_veiculo_veiculos.getValueAt(table_veiculo_veiculos.getSelectedRow(), 1).toString()); campo_veiculo_placa.setText(table_veiculo_veiculos.getValueAt(table_veiculo_veiculos.getSelectedRow(), 2).toString()); campo_veiculo_cor.setText(table_veiculo_veiculos.getValueAt(table_veiculo_veiculos.getSelectedRow(), 3).toString()); campo_veiculo_ano.setText(table_veiculo_veiculos.getValueAt(table_veiculo_veiculos.getSelectedRow(), 4).toString()); } }//GEN-LAST:event_table_veiculo_veiculosKeyReleased private void botao_veiculo_buscarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botao_veiculo_buscarActionPerformed lerTabelaPorMarca(campo_veiculo_buscar.getText()); }//GEN-LAST:event_botao_veiculo_buscarActionPerformed private void botao_veiculo_menuActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botao_veiculo_menuActionPerformed this.dispose(); new ViewHome().setVisible(true); }//GEN-LAST:event_botao_veiculo_menuActionPerformed private void botao_veiculo_exportarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botao_veiculo_exportarActionPerformed // gravarInformacaoVeiculo(); String janela = "Veiculo"; new ViewExport(janela).setVisible(true); this.dispose(); }//GEN-LAST:event_botao_veiculo_exportarActionPerformed private void botao_veiculo_importarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botao_veiculo_importarActionPerformed //carregarInformacaoVeiculo(); String janela = "Veiculo"; new ViewImport(janela).setVisible(true); this.dispose(); }//GEN-LAST:event_botao_veiculo_importarActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(ViewVeiculo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(ViewVeiculo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(ViewVeiculo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(ViewVeiculo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new ViewVeiculo().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton botao_veiculo_buscar; private javax.swing.JButton botao_veiculo_cancelar; private javax.swing.JButton botao_veiculo_editar; private javax.swing.JButton botao_veiculo_excluir; private javax.swing.JButton botao_veiculo_exportar; private javax.swing.JButton botao_veiculo_importar; private javax.swing.JButton botao_veiculo_menu; private javax.swing.JButton botao_veiculo_novo; private javax.swing.JButton botao_veiculo_salvar; private javax.swing.JTextField campo_veiculo_ano; private javax.swing.JTextField campo_veiculo_buscar; private javax.swing.JTextField campo_veiculo_cor; private javax.swing.JTextField campo_veiculo_marca; private javax.swing.JTextField campo_veiculo_modelo; private javax.swing.JTextField campo_veiculo_placa; private javax.swing.JLabel jLabel10; private javax.swing.JLabel jLabel11; private javax.swing.JLabel jLabel12; private javax.swing.JLabel jLabel8; private javax.swing.JLabel jLabel9; private javax.swing.JPanel jPanel5; private javax.swing.JScrollPane jScrollPane2; private javax.swing.JTable table_veiculo_veiculos; // End of variables declaration//GEN-END:variables }
UTF-8
Java
34,658
java
ViewVeiculo.java
Java
[ { "context": "o;\nimport model.dao.VeiculoDAO;\n\n/**\n *\n * @author Murilo\n */\npublic class ViewVeiculo extends javax.swing.", "end": 579, "score": 0.9996750354766846, "start": 573, "tag": "NAME", "value": "Murilo" } ]
null
[]
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package view; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import javax.swing.JOptionPane; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableRowSorter; import json.JSONArray; import json.JSONObject; import model.bean.Veiculo; import model.dao.VeiculoDAO; /** * * @author Murilo */ public class ViewVeiculo extends javax.swing.JFrame { String modo; String caso; /** * Creates new form viewVeiculo */ public ViewVeiculo() { initComponents(); setLocationRelativeTo(null); iniciarJanelaVeiculo(); readJTable(); modo = "Navegar"; manipulaInterfaceVeiculo(); DefaultTableModel modelo = (DefaultTableModel) table_veiculo_veiculos.getModel(); table_veiculo_veiculos.setRowSorter(new TableRowSorter(modelo)); } /** * 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. */ public void readJTable() { DefaultTableModel modelo = (DefaultTableModel) table_veiculo_veiculos.getModel(); modelo.setNumRows(0); VeiculoDAO pdao = new VeiculoDAO(); for (Veiculo p : pdao.read()) { modelo.addRow(new Object[]{ p.getMarca(), p.getModelo(), p.getPlaca(), p.getCor(), p.getAno() }); } } public void manipulaInterfaceVeiculo() { switch (modo) { case "Navegar": botao_veiculo_salvar.setEnabled(false); botao_veiculo_cancelar.setEnabled(false); botao_veiculo_novo.setEnabled(true); botao_veiculo_editar.setEnabled(false); botao_veiculo_excluir.setEnabled(false); campo_veiculo_marca.setEnabled(false); campo_veiculo_modelo.setEnabled(false); campo_veiculo_placa.setEnabled(false); campo_veiculo_cor.setEnabled(false); campo_veiculo_ano.setEnabled(false); break; case "Novo": botao_veiculo_salvar.setEnabled(true); botao_veiculo_cancelar.setEnabled(true); botao_veiculo_novo.setEnabled(false); botao_veiculo_editar.setEnabled(false); botao_veiculo_excluir.setEnabled(false); campo_veiculo_marca.setEnabled(true); campo_veiculo_modelo.setEnabled(true); campo_veiculo_placa.setEnabled(true); campo_veiculo_cor.setEnabled(true); campo_veiculo_ano.setEnabled(true); break; case "Editar": botao_veiculo_salvar.setEnabled(true); botao_veiculo_cancelar.setEnabled(true); botao_veiculo_novo.setEnabled(false); botao_veiculo_editar.setEnabled(false); botao_veiculo_excluir.setEnabled(false); campo_veiculo_marca.setEnabled(true); campo_veiculo_modelo.setEnabled(true); campo_veiculo_placa.setEnabled(true); campo_veiculo_cor.setEnabled(true); campo_veiculo_ano.setEnabled(true); break; case "Excluir": botao_veiculo_salvar.setEnabled(false); botao_veiculo_cancelar.setEnabled(false); botao_veiculo_novo.setEnabled(true); botao_veiculo_editar.setEnabled(false); botao_veiculo_excluir.setEnabled(false); campo_veiculo_marca.setEnabled(false); campo_veiculo_modelo.setEnabled(false); campo_veiculo_placa.setEnabled(false); campo_veiculo_cor.setEnabled(false); campo_veiculo_ano.setEnabled(false); break; case "Selecao": botao_veiculo_salvar.setEnabled(false); botao_veiculo_cancelar.setEnabled(false); botao_veiculo_novo.setEnabled(true); botao_veiculo_editar.setEnabled(true); botao_veiculo_excluir.setEnabled(true); campo_veiculo_marca.setEnabled(false); campo_veiculo_modelo.setEnabled(false); campo_veiculo_placa.setEnabled(false); campo_veiculo_cor.setEnabled(false); campo_veiculo_ano.setEnabled(false); break; default: System.out.println("Modo inválido"); } } public void iniciarJanelaVeiculo() { campo_veiculo_marca.setText(""); campo_veiculo_modelo.setText(""); campo_veiculo_placa.setText(""); campo_veiculo_cor.setText(""); campo_veiculo_ano.setText(""); botao_veiculo_menu.setEnabled(true); botao_veiculo_importar.setEnabled(true); botao_veiculo_exportar.setEnabled(true); } public void gravarInformacaoVeiculo() { File file = new File("Veiculo.json"); String conteudo; try { VeiculoDAO pdao = new VeiculoDAO(); FileWriter f = new FileWriter(file, true); for (Veiculo p : pdao.read()) { JSONObject json = new JSONObject(); conteudo = p.toJson().toString(); conteudo += "\r\n"; f.write(conteudo); } f.close(); JOptionPane.showMessageDialog(null, "Dados Exportados com sucesso!"); } catch (IOException e) { JOptionPane.showMessageDialog(null, "Não foi possível realizar esta ação"); } } public void carregarInformacaoVeiculo() { try { VeiculoDAO pdao = new VeiculoDAO(); FileReader fr = new FileReader("Veiculo.json"); BufferedReader br = new BufferedReader(fr); String str; while ((str = br.readLine()) != null) { Veiculo p = new Veiculo(); JSONArray json = new JSONArray(str.toString()); for (int i = 0; i < json.length(); i++) { JSONObject obj = json.getJSONObject(i); p.setMarca(obj.getString("marca")); p.setModelo(obj.getString("modelo")); p.setPlaca(obj.getString("placa")); p.setCor(obj.getString("cor")); p.setAno(obj.getInt("ano")); if (i + 1 == json.length()) { pdao.create(p); } } } br.close(); JOptionPane.showMessageDialog(null, "Dados Importados com sucesso!"); } catch (IOException e) { JOptionPane.showMessageDialog(null, "Não foi possível realizar esta ação"); } } public void limparCamposVeiculo() { campo_veiculo_marca.setText(""); campo_veiculo_modelo.setText(""); campo_veiculo_placa.setText(""); campo_veiculo_cor.setText(""); campo_veiculo_ano.setText(""); } public void lerTabelaPorMarca(String marca) { DefaultTableModel modelo = (DefaultTableModel) table_veiculo_veiculos.getModel(); modelo.setNumRows(0); VeiculoDAO pdao = new VeiculoDAO(); for (Veiculo p : pdao.lerPorMarca(marca)) { modelo.addRow(new Object[]{ p.getMarca(), p.getModelo(), p.getPlaca(), p.getCor(), p.getAno() }); } } @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel5 = new javax.swing.JPanel(); jLabel8 = new javax.swing.JLabel(); campo_veiculo_marca = new javax.swing.JTextField(); jLabel9 = new javax.swing.JLabel(); campo_veiculo_modelo = new javax.swing.JTextField(); jLabel10 = new javax.swing.JLabel(); jLabel11 = new javax.swing.JLabel(); jLabel12 = new javax.swing.JLabel(); campo_veiculo_placa = new javax.swing.JTextField(); campo_veiculo_cor = new javax.swing.JTextField(); campo_veiculo_ano = new javax.swing.JTextField(); botao_veiculo_salvar = new javax.swing.JButton(); botao_veiculo_cancelar = new javax.swing.JButton(); botao_veiculo_menu = new javax.swing.JButton(); botao_veiculo_exportar = new javax.swing.JButton(); botao_veiculo_importar = new javax.swing.JButton(); jScrollPane2 = new javax.swing.JScrollPane(); table_veiculo_veiculos = new javax.swing.JTable(); botao_veiculo_editar = new javax.swing.JButton(); botao_veiculo_novo = new javax.swing.JButton(); botao_veiculo_excluir = new javax.swing.JButton(); botao_veiculo_buscar = new javax.swing.JButton(); campo_veiculo_buscar = new javax.swing.JTextField(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jPanel5.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)), "Veículo", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 0, 18))); // NOI18N jPanel5.setPreferredSize(new java.awt.Dimension(750, 260)); jLabel8.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel8.setText("Marca:"); campo_veiculo_marca.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { campo_veiculo_marcaActionPerformed(evt); } }); jLabel9.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel9.setText("Modelo:"); jLabel10.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel10.setText("Placa:"); jLabel11.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel11.setText("Cor:"); jLabel12.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel12.setText("Ano:"); campo_veiculo_placa.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { campo_veiculo_placaActionPerformed(evt); } }); campo_veiculo_cor.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { campo_veiculo_corActionPerformed(evt); } }); botao_veiculo_salvar.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N botao_veiculo_salvar.setText("Salvar"); botao_veiculo_salvar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { botao_veiculo_salvarActionPerformed(evt); } }); botao_veiculo_cancelar.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N botao_veiculo_cancelar.setText("Cancelar"); botao_veiculo_cancelar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { botao_veiculo_cancelarActionPerformed(evt); } }); botao_veiculo_menu.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N botao_veiculo_menu.setText("Menu principal"); botao_veiculo_menu.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { botao_veiculo_menuActionPerformed(evt); } }); botao_veiculo_exportar.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N botao_veiculo_exportar.setText("Exportar Dados"); botao_veiculo_exportar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { botao_veiculo_exportarActionPerformed(evt); } }); botao_veiculo_importar.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N botao_veiculo_importar.setText("Importar Dados"); botao_veiculo_importar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { botao_veiculo_importarActionPerformed(evt); } }); javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5); jPanel5.setLayout(jPanel5Layout); jPanel5Layout.setHorizontalGroup( jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel5Layout.createSequentialGroup() .addGap(25, 25, 25) .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabel12) .addComponent(jLabel11) .addComponent(jLabel8) .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addGroup(jPanel5Layout.createSequentialGroup() .addGap(10, 10, 10) .addComponent(jLabel10, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addComponent(jLabel9, javax.swing.GroupLayout.Alignment.TRAILING))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(campo_veiculo_ano, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 167, Short.MAX_VALUE) .addComponent(campo_veiculo_placa) .addComponent(campo_veiculo_modelo) .addComponent(campo_veiculo_marca) .addComponent(campo_veiculo_cor)) .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel5Layout.createSequentialGroup() .addGap(142, 142, 142) .addComponent(botao_veiculo_menu, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel5Layout.createSequentialGroup() .addGap(53, 53, 53) .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(botao_veiculo_exportar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(botao_veiculo_salvar, javax.swing.GroupLayout.DEFAULT_SIZE, 130, Short.MAX_VALUE)) .addGap(41, 41, 41) .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(botao_veiculo_cancelar, javax.swing.GroupLayout.DEFAULT_SIZE, 130, Short.MAX_VALUE) .addComponent(botao_veiculo_importar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))) .addGap(82, 82, 82)) ); jPanel5Layout.setVerticalGroup( jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel5Layout.createSequentialGroup() .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel5Layout.createSequentialGroup() .addGap(82, 82, 82) .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(botao_veiculo_cancelar) .addComponent(botao_veiculo_salvar)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 33, Short.MAX_VALUE) .addComponent(botao_veiculo_menu)) .addGroup(jPanel5Layout.createSequentialGroup() .addGap(27, 27, 27) .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(botao_veiculo_exportar) .addComponent(botao_veiculo_importar)) .addGap(0, 0, Short.MAX_VALUE))) .addContainerGap()) .addGroup(jPanel5Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel8) .addComponent(campo_veiculo_marca, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(campo_veiculo_modelo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel9)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel10) .addComponent(campo_veiculo_placa, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel11) .addComponent(campo_veiculo_cor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel12) .addComponent(campo_veiculo_ano, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); table_veiculo_veiculos.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N table_veiculo_veiculos.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { }, new String [] { " Marca", "Modelo", "Placa", "Cor", "Ano" } ) { boolean[] canEdit = new boolean [] { false, false, false, false, false }; public boolean isCellEditable(int rowIndex, int columnIndex) { return canEdit [columnIndex]; } }); table_veiculo_veiculos.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { table_veiculo_veiculosMouseClicked(evt); } }); table_veiculo_veiculos.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { table_veiculo_veiculosKeyReleased(evt); } }); jScrollPane2.setViewportView(table_veiculo_veiculos); botao_veiculo_editar.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N botao_veiculo_editar.setText("Editar"); botao_veiculo_editar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { botao_veiculo_editarActionPerformed(evt); } }); botao_veiculo_novo.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N botao_veiculo_novo.setText("Novo"); botao_veiculo_novo.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { botao_veiculo_novoActionPerformed(evt); } }); botao_veiculo_excluir.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N botao_veiculo_excluir.setText("Excluir"); botao_veiculo_excluir.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { botao_veiculo_excluirActionPerformed(evt); } }); botao_veiculo_buscar.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N botao_veiculo_buscar.setText("Buscar por marca"); botao_veiculo_buscar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { botao_veiculo_buscarActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(botao_veiculo_novo, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(botao_veiculo_editar, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(botao_veiculo_excluir, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 26, Short.MAX_VALUE) .addComponent(campo_veiculo_buscar, javax.swing.GroupLayout.PREFERRED_SIZE, 140, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(27, 27, 27) .addComponent(botao_veiculo_buscar) .addContainerGap()) .addComponent(jScrollPane2) .addComponent(jPanel5, javax.swing.GroupLayout.DEFAULT_SIZE, 690, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(campo_veiculo_buscar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(botao_veiculo_novo) .addComponent(botao_veiculo_editar) .addComponent(botao_veiculo_excluir) .addComponent(botao_veiculo_buscar))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jPanel5, javax.swing.GroupLayout.DEFAULT_SIZE, 205, Short.MAX_VALUE)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void campo_veiculo_marcaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_campo_veiculo_marcaActionPerformed // TODO add your handling code here: }//GEN-LAST:event_campo_veiculo_marcaActionPerformed private void campo_veiculo_placaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_campo_veiculo_placaActionPerformed // TODO add your handling code here: }//GEN-LAST:event_campo_veiculo_placaActionPerformed private void campo_veiculo_corActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_campo_veiculo_corActionPerformed // TODO add your handling code here: }//GEN-LAST:event_campo_veiculo_corActionPerformed private void botao_veiculo_salvarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botao_veiculo_salvarActionPerformed if (caso == "Editar") { if (table_veiculo_veiculos.getSelectedRow() != -1) { Veiculo p = new Veiculo(); VeiculoDAO dao = new VeiculoDAO(); p.setMarca(campo_veiculo_marca.getText()); p.setModelo(campo_veiculo_modelo.getText()); p.setPlaca(campo_veiculo_placa.getText()); p.setCor(campo_veiculo_cor.getText()); p.setAno(Integer.parseInt(campo_veiculo_ano.getText())); dao.update(p); readJTable(); caso = ""; modo = "Navegar"; manipulaInterfaceVeiculo(); limparCamposVeiculo(); } } if(caso == "Salvar"){ Veiculo p = new Veiculo(); VeiculoDAO dao = new VeiculoDAO(); p.setMarca(campo_veiculo_marca.getText()); p.setModelo(campo_veiculo_modelo.getText()); p.setPlaca(campo_veiculo_placa.getText()); p.setCor(campo_veiculo_cor.getText()); p.setAno(Integer.parseInt(campo_veiculo_ano.getText())); dao.create(p); limparCamposVeiculo(); readJTable(); caso = ""; modo = "Navegar"; manipulaInterfaceVeiculo(); } }//GEN-LAST:event_botao_veiculo_salvarActionPerformed private void botao_veiculo_cancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botao_veiculo_cancelarActionPerformed limparCamposVeiculo(); modo = "Navegar"; manipulaInterfaceVeiculo(); }//GEN-LAST:event_botao_veiculo_cancelarActionPerformed private void table_veiculo_veiculosMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_table_veiculo_veiculosMouseClicked modo = "Selecao"; manipulaInterfaceVeiculo(); if (table_veiculo_veiculos.getSelectedRow() != -1) { campo_veiculo_marca.setText(table_veiculo_veiculos.getValueAt(table_veiculo_veiculos.getSelectedRow(), 0).toString()); campo_veiculo_modelo.setText(table_veiculo_veiculos.getValueAt(table_veiculo_veiculos.getSelectedRow(), 1).toString()); campo_veiculo_placa.setText(table_veiculo_veiculos.getValueAt(table_veiculo_veiculos.getSelectedRow(), 2).toString()); campo_veiculo_cor.setText(table_veiculo_veiculos.getValueAt(table_veiculo_veiculos.getSelectedRow(), 3).toString()); campo_veiculo_ano.setText(table_veiculo_veiculos.getValueAt(table_veiculo_veiculos.getSelectedRow(), 4).toString()); } }//GEN-LAST:event_table_veiculo_veiculosMouseClicked private void botao_veiculo_editarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botao_veiculo_editarActionPerformed modo = "Editar"; manipulaInterfaceVeiculo(); caso = "Editar"; }//GEN-LAST:event_botao_veiculo_editarActionPerformed private void botao_veiculo_novoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botao_veiculo_novoActionPerformed limparCamposVeiculo(); caso = "Salvar"; modo = "Novo"; manipulaInterfaceVeiculo(); }//GEN-LAST:event_botao_veiculo_novoActionPerformed private void botao_veiculo_excluirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botao_veiculo_excluirActionPerformed if (table_veiculo_veiculos.getSelectedRow() != -1) { int index = table_veiculo_veiculos.getSelectedRow(); Veiculo p = new Veiculo(); VeiculoDAO dao = new VeiculoDAO(); p.setPlaca((String) table_veiculo_veiculos.getValueAt(table_veiculo_veiculos.getSelectedRow(), 2)); dao.delete(p); limparCamposVeiculo(); readJTable(); } else { JOptionPane.showMessageDialog(null, "Selecione um produto para excluir."); } modo = "Navegar"; }//GEN-LAST:event_botao_veiculo_excluirActionPerformed private void table_veiculo_veiculosKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_table_veiculo_veiculosKeyReleased if (table_veiculo_veiculos.getSelectedRow() != -1) { campo_veiculo_marca.setText(table_veiculo_veiculos.getValueAt(table_veiculo_veiculos.getSelectedRow(), 0).toString()); campo_veiculo_modelo.setText(table_veiculo_veiculos.getValueAt(table_veiculo_veiculos.getSelectedRow(), 1).toString()); campo_veiculo_placa.setText(table_veiculo_veiculos.getValueAt(table_veiculo_veiculos.getSelectedRow(), 2).toString()); campo_veiculo_cor.setText(table_veiculo_veiculos.getValueAt(table_veiculo_veiculos.getSelectedRow(), 3).toString()); campo_veiculo_ano.setText(table_veiculo_veiculos.getValueAt(table_veiculo_veiculos.getSelectedRow(), 4).toString()); } }//GEN-LAST:event_table_veiculo_veiculosKeyReleased private void botao_veiculo_buscarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botao_veiculo_buscarActionPerformed lerTabelaPorMarca(campo_veiculo_buscar.getText()); }//GEN-LAST:event_botao_veiculo_buscarActionPerformed private void botao_veiculo_menuActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botao_veiculo_menuActionPerformed this.dispose(); new ViewHome().setVisible(true); }//GEN-LAST:event_botao_veiculo_menuActionPerformed private void botao_veiculo_exportarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botao_veiculo_exportarActionPerformed // gravarInformacaoVeiculo(); String janela = "Veiculo"; new ViewExport(janela).setVisible(true); this.dispose(); }//GEN-LAST:event_botao_veiculo_exportarActionPerformed private void botao_veiculo_importarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botao_veiculo_importarActionPerformed //carregarInformacaoVeiculo(); String janela = "Veiculo"; new ViewImport(janela).setVisible(true); this.dispose(); }//GEN-LAST:event_botao_veiculo_importarActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(ViewVeiculo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(ViewVeiculo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(ViewVeiculo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(ViewVeiculo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new ViewVeiculo().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton botao_veiculo_buscar; private javax.swing.JButton botao_veiculo_cancelar; private javax.swing.JButton botao_veiculo_editar; private javax.swing.JButton botao_veiculo_excluir; private javax.swing.JButton botao_veiculo_exportar; private javax.swing.JButton botao_veiculo_importar; private javax.swing.JButton botao_veiculo_menu; private javax.swing.JButton botao_veiculo_novo; private javax.swing.JButton botao_veiculo_salvar; private javax.swing.JTextField campo_veiculo_ano; private javax.swing.JTextField campo_veiculo_buscar; private javax.swing.JTextField campo_veiculo_cor; private javax.swing.JTextField campo_veiculo_marca; private javax.swing.JTextField campo_veiculo_modelo; private javax.swing.JTextField campo_veiculo_placa; private javax.swing.JLabel jLabel10; private javax.swing.JLabel jLabel11; private javax.swing.JLabel jLabel12; private javax.swing.JLabel jLabel8; private javax.swing.JLabel jLabel9; private javax.swing.JPanel jPanel5; private javax.swing.JScrollPane jScrollPane2; private javax.swing.JTable table_veiculo_veiculos; // End of variables declaration//GEN-END:variables }
34,658
0.633803
0.624971
701
48.426533
37.581703
307
false
false
0
0
0
0
0
0
0.718973
false
false
11
beccc2cd8cd1ed0379ba42ce942847ec4b20c60e
12,154,757,491,275
70cab389f4547498f5b0fc961b47bbe7b9a01839
/src/main/java/com/javalab/clothshop/service/order/OrderRetrievalService.java
f2ce3f091252ebf2105a041e4092fa198ceebb77
[]
no_license
aliya2409/cloth-shop
https://github.com/aliya2409/cloth-shop
6ea620ccca30c775edf0c1c2c5f77e1ed4191c69
308066393ca543f27484a4371206c0476e6f14b0
refs/heads/master
2020-08-18T07:06:13.495000
2019-10-31T08:04:36
2019-10-31T08:04:36
215,761,987
0
1
null
false
2019-10-23T04:04:23
2019-10-17T10:07:53
2019-10-22T10:09:05
2019-10-23T04:04:19
91
0
1
0
Java
false
false
package com.javalab.clothshop.service.order; import com.javalab.clothshop.model.Order; import java.util.List; public interface OrderRetrievalService { Order retrieveById(Long id); List<Order> retrieveAll(); }
UTF-8
Java
222
java
OrderRetrievalService.java
Java
[]
null
[]
package com.javalab.clothshop.service.order; import com.javalab.clothshop.model.Order; import java.util.List; public interface OrderRetrievalService { Order retrieveById(Long id); List<Order> retrieveAll(); }
222
0.765766
0.765766
12
17.5
18.145247
44
false
false
0
0
0
0
0
0
0.416667
false
false
11
ed1afaa5679c88895676b0c91f9cf049508838d0
26,834,955,716,047
575035d0224bd0d8bd1dfbbfdad36c2e84df8805
/src/main/java/com/qubikapp/app/ws/model/response/MestoRest.java
0865009b223dadf00f74f97d989fd0a581666381
[]
no_license
jovanlzc/autobuska-app-ws
https://github.com/jovanlzc/autobuska-app-ws
4875d0fefa4711b77baacb89d92a705d418a8b3c
17fbfc470ce0822cef04310e1cb8c08fe3f6ac57
refs/heads/master
2020-07-22T19:46:28.515000
2019-09-09T18:00:19
2019-09-09T18:00:19
207,308,692
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.qubikapp.app.ws.model.response; public class MestoRest { private Long mestoId; private String naziv; public Long getMestoId() { return mestoId; } public void setMestoId(Long mestoId) { this.mestoId = mestoId; } public String getNaziv() { return naziv; } public void setNaziv(String naziv) { this.naziv = naziv; } }
UTF-8
Java
381
java
MestoRest.java
Java
[]
null
[]
package com.qubikapp.app.ws.model.response; public class MestoRest { private Long mestoId; private String naziv; public Long getMestoId() { return mestoId; } public void setMestoId(Long mestoId) { this.mestoId = mestoId; } public String getNaziv() { return naziv; } public void setNaziv(String naziv) { this.naziv = naziv; } }
381
0.650919
0.650919
24
13.875
14.033628
43
false
false
0
0
0
0
0
0
1.25
false
false
11
e494fd45cf9b08bc7bc04b8b2fa0c3d5b132b9c2
4,183,298,211,568
63b756a57026a333258dfddb24cb3239319e9281
/src/main/java/mvp/stuff/Element.java
250fc27b2a8c485a4668e0bdaa0c14dadca85eb6
[]
no_license
Julian-Arnaud/TBTRPG
https://github.com/Julian-Arnaud/TBTRPG
9fe358d548a36833be782c12aee92a3274827a80
1b65f59de446f2229bb78c5c713cb42afbfd8baa
refs/heads/master
2021-01-10T15:53:54.801000
2016-11-19T14:28:35
2016-11-19T14:28:35
51,147,189
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package mvp.stuff; /** * @author Julian ARNAUD * @date 09/04/2016 **/ public enum Element { FIRE("FIRE"), WATER("WATER"), EARTH("EARTH"), THUNDER("THUNDER"), AIR("AIR"), DARK("DARK"), LIGHT("LIGHT"); private Element element; private String elementName; Element(String name) { elementName = name; } public static Element parse(String name) { Element d = null; switch (name) { case "FIRE": d = FIRE; break; case "WATER": d = WATER; break; case "THUNDER": d = THUNDER; break; case "EARTH": d = EARTH; break; case "AIR": d = AIR; break; case "DARK": d = DARK; break; case "LIGHT": d = LIGHT; break; default: break; } return d; } }
UTF-8
Java
1,062
java
Element.java
Java
[ { "context": "package mvp.stuff;\n\n/**\n * @author Julian ARNAUD\n * @date 09/04/2016\n **/\npublic enum Element {\n ", "end": 48, "score": 0.9998647570610046, "start": 35, "tag": "NAME", "value": "Julian ARNAUD" } ]
null
[]
package mvp.stuff; /** * @author <NAME> * @date 09/04/2016 **/ public enum Element { FIRE("FIRE"), WATER("WATER"), EARTH("EARTH"), THUNDER("THUNDER"), AIR("AIR"), DARK("DARK"), LIGHT("LIGHT"); private Element element; private String elementName; Element(String name) { elementName = name; } public static Element parse(String name) { Element d = null; switch (name) { case "FIRE": d = FIRE; break; case "WATER": d = WATER; break; case "THUNDER": d = THUNDER; break; case "EARTH": d = EARTH; break; case "AIR": d = AIR; break; case "DARK": d = DARK; break; case "LIGHT": d = LIGHT; break; default: break; } return d; } }
1,055
0.391714
0.384181
52
19.423077
9.365128
46
false
false
0
0
0
0
0
0
0.538462
false
false
11
5a8936b6dabe75e2433d886d36e39c57ea88b93e
29,575,144,862,936
38a6795a6a384e43b8d1ae8c7fd8c6a40671f83f
/youlai-admin/admin-boot/src/main/java/com/youlai/admin/mapper/SysDictItemMapper.java
9a951c038157be603d6a85b0d2da33055bc4e1a8
[ "Apache-2.0" ]
permissive
zhlog1024/youlai-mall
https://github.com/zhlog1024/youlai-mall
43a53c7591ddc1cf1fbc6a644f06e5f42ea3b830
7cd5ebe9f48e2c87e3cb0f15356f1ff95f81e7ea
refs/heads/master
2023-07-11T00:31:20.174000
2021-08-14T12:20:25
2021-08-14T12:20:25
394,536,585
0
0
Apache-2.0
true
2021-08-14T12:20:26
2021-08-10T05:33:36
2021-08-10T05:33:36
2021-08-14T12:20:25
247,000
0
0
0
null
false
false
package com.youlai.admin.mapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.youlai.admin.pojo.entity.SysDictItem; import org.apache.ibatis.annotations.Mapper; import java.util.List; @Mapper public interface SysDictItemMapper extends BaseMapper<SysDictItem> { List<SysDictItem> list(Page<SysDictItem> page, SysDictItem dictItem); }
UTF-8
Java
430
java
SysDictItemMapper.java
Java
[]
null
[]
package com.youlai.admin.mapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.youlai.admin.pojo.entity.SysDictItem; import org.apache.ibatis.annotations.Mapper; import java.util.List; @Mapper public interface SysDictItemMapper extends BaseMapper<SysDictItem> { List<SysDictItem> list(Page<SysDictItem> page, SysDictItem dictItem); }
430
0.82093
0.82093
14
29.714285
27.737104
73
false
false
0
0
0
0
0
0
0.571429
false
false
11
ca08fd0420c4f1bc8c28d53af9e0ef89ec97ad38
2,018,634,667,110
d89bd45626d952c4a8fde96cadbdf43808188420
/src/test/java/it/davidenastri/clouddrive/page/SignUpPage.java
7aa0b5502f607f4f26cb155d43859e28e3c42fea
[ "MIT" ]
permissive
ltpitt/java-spring-cloud-drive
https://github.com/ltpitt/java-spring-cloud-drive
c7f47ea0494be48653e3907009b1c8083c71acd2
dad614a7eb308ee53a08388e3742171914dc45f3
refs/heads/master
2023-02-18T05:15:16.935000
2021-01-18T13:53:32
2021-01-18T13:53:32
281,430,614
2
2
MIT
false
2020-12-17T11:10:22
2020-07-21T15:09:40
2020-12-10T14:36:21
2020-12-17T11:10:22
215
0
0
0
Java
false
false
package it.davidenastri.clouddrive.page; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.PageFactory; public class SignUpPage { @FindBy(id = "inputFirstName") private WebElement firstNameField; @FindBy(id = "inputLastName") private WebElement lastNameField; @FindBy(id = "inputUsername") private WebElement usernameField; @FindBy(id = "inputPassword") private WebElement passwordField; @FindBy(id = "submit-button") private WebElement signUpButton; @FindBy(id = "login-link") private WebElement loginLink; @FindBy(id = "success-msg") private WebElement successMessage; public SignUpPage(WebDriver driver) { PageFactory.initElements(driver, this); } public void signUp(String firstName, String lastName, String username, String password) { firstNameField.clear(); firstNameField.sendKeys(firstName); lastNameField.clear(); lastNameField.sendKeys(lastName); usernameField.clear(); usernameField.sendKeys(username); passwordField.clear(); passwordField.sendKeys(password); signUpButton.click(); } public WebElement getSuccessMessage() { return successMessage; } }
UTF-8
Java
1,348
java
SignUpPage.java
Java
[ { "context": "ameField.clear();\n firstNameField.sendKeys(firstName);\n lastNameField.clear();\n lastName", "end": 1006, "score": 0.9792847633361816, "start": 997, "tag": "NAME", "value": "firstName" }, { "context": "NameField.clear();\n lastNameField.sendKeys(lastName);\n usernameField.clear();\n username", "end": 1079, "score": 0.9600122570991516, "start": 1071, "tag": "NAME", "value": "lastName" }, { "context": "nameField.clear();\n usernameField.sendKeys(username);\n passwordField.clear();\n password", "end": 1152, "score": 0.9956360459327698, "start": 1144, "tag": "USERNAME", "value": "username" }, { "context": "wordField.clear();\n passwordField.sendKeys(password);\n signUpButton.click();\n }\n\n public", "end": 1225, "score": 0.9838630557060242, "start": 1217, "tag": "PASSWORD", "value": "password" } ]
null
[]
package it.davidenastri.clouddrive.page; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.PageFactory; public class SignUpPage { @FindBy(id = "inputFirstName") private WebElement firstNameField; @FindBy(id = "inputLastName") private WebElement lastNameField; @FindBy(id = "inputUsername") private WebElement usernameField; @FindBy(id = "inputPassword") private WebElement passwordField; @FindBy(id = "submit-button") private WebElement signUpButton; @FindBy(id = "login-link") private WebElement loginLink; @FindBy(id = "success-msg") private WebElement successMessage; public SignUpPage(WebDriver driver) { PageFactory.initElements(driver, this); } public void signUp(String firstName, String lastName, String username, String password) { firstNameField.clear(); firstNameField.sendKeys(firstName); lastNameField.clear(); lastNameField.sendKeys(lastName); usernameField.clear(); usernameField.sendKeys(username); passwordField.clear(); passwordField.sendKeys(<PASSWORD>); signUpButton.click(); } public WebElement getSuccessMessage() { return successMessage; } }
1,350
0.699555
0.699555
50
25.959999
19.404081
93
false
false
0
0
0
0
0
0
0.54
false
false
11
57bef4cc21d1c743a3f6e7a9349ca88742f96d29
17,119,739,677,025
97c74c8ebba0018c380842d14127e2c24199fa22
/app/src/main/java/com/example/android/rugbyscorecounter/MainActivity.java
be0b0325003b9221b31f9f1a7f687f870e8c3f58
[]
no_license
nsicilia/RugbyScoreCounter
https://github.com/nsicilia/RugbyScoreCounter
667c56f30a277e10cb7a0949452a77d68f88d9fd
4b7346ee219236cec7d1881db3a4197103d72bc2
refs/heads/master
2020-03-29T06:15:00.874000
2018-09-25T02:38:15
2018-09-25T02:38:15
149,616,468
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.android.rugbyscorecounter; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; public class MainActivity extends AppCompatActivity { int HomeScore = 0; int AwayScore = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } @Override protected void onResume() { super.onResume(); ScoreForHomeTeam(); } public void ScoreForHomeTeam(){ /** * This is the button for the Home Try adding 5 to the score * and updating score display */ Button HomeTry = findViewById(R.id.HomeTry); HomeTry.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { HomeScore += 5; DisplayHomeScore(HomeScore); } }); /** * The button for Home Conversion adding 2 to the score * and updating score display */ Button HomeConversion = findViewById(R.id.HomeConversion); HomeConversion.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { HomeScore += 2; DisplayHomeScore(HomeScore); } }); /** * The button for Home Drop Goal adding 3 to the score * and updating score display */ Button HomeDropGoal = findViewById(R.id.HomeDropGoal); HomeDropGoal.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { HomeScore += 3; DisplayHomeScore(HomeScore); } }); /** * The button for Home Drop Goal adding 3 to the score * and updating score display */ Button HomePenalty = findViewById(R.id.HomePenalty); HomePenalty.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { HomeScore += 3; DisplayHomeScore(HomeScore); } }); } public void DisplayHomeScore(int score){ TextView scoreView = (TextView) findViewById(R.id.team_a_score); scoreView.setText(String.valueOf(score)); } public void DisplayAwayScore(int score){ TextView scoreView = (TextView) findViewById(R.id.team_b_score); scoreView.setText(String.valueOf(score)); } }
UTF-8
Java
2,686
java
MainActivity.java
Java
[]
null
[]
package com.example.android.rugbyscorecounter; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; public class MainActivity extends AppCompatActivity { int HomeScore = 0; int AwayScore = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } @Override protected void onResume() { super.onResume(); ScoreForHomeTeam(); } public void ScoreForHomeTeam(){ /** * This is the button for the Home Try adding 5 to the score * and updating score display */ Button HomeTry = findViewById(R.id.HomeTry); HomeTry.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { HomeScore += 5; DisplayHomeScore(HomeScore); } }); /** * The button for Home Conversion adding 2 to the score * and updating score display */ Button HomeConversion = findViewById(R.id.HomeConversion); HomeConversion.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { HomeScore += 2; DisplayHomeScore(HomeScore); } }); /** * The button for Home Drop Goal adding 3 to the score * and updating score display */ Button HomeDropGoal = findViewById(R.id.HomeDropGoal); HomeDropGoal.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { HomeScore += 3; DisplayHomeScore(HomeScore); } }); /** * The button for Home Drop Goal adding 3 to the score * and updating score display */ Button HomePenalty = findViewById(R.id.HomePenalty); HomePenalty.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { HomeScore += 3; DisplayHomeScore(HomeScore); } }); } public void DisplayHomeScore(int score){ TextView scoreView = (TextView) findViewById(R.id.team_a_score); scoreView.setText(String.valueOf(score)); } public void DisplayAwayScore(int score){ TextView scoreView = (TextView) findViewById(R.id.team_b_score); scoreView.setText(String.valueOf(score)); } }
2,686
0.590097
0.586002
96
26.979166
22.374641
72
false
false
0
0
0
0
0
0
0.333333
false
false
11
1e7f34e1206b6df875ade55fd712bb4ec2e26336
9,259,949,519,267
48c2d4b8f4594eb79012ef56082b061cdccd8f4e
/TweetFiltrr/src/main/java/com/sun/tweetfiltrr/twitter/twitterretrievers/impl/AccessTokenRetrieverFromPref.java
596a8f987b73c2653b34c81dd4ff8abc16507efc
[]
no_license
SundeepK/TwitterFilttr
https://github.com/SundeepK/TwitterFilttr
9fd25af5822344ab0201877bab714cfb4970e551
1a24e5ab47d0293d05fa79375ad87d7bcd476aa1
refs/heads/master
2021-01-23T02:34:26.630000
2015-02-26T11:36:23
2015-02-26T11:36:23
16,056,328
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.sun.tweetfiltrr.twitter.twitterretrievers.impl; import android.content.SharedPreferences; import android.util.Log; import com.sun.tweetfiltrr.database.dao.impl.FriendDao; import com.sun.tweetfiltrr.database.tables.FriendTable; import com.sun.tweetfiltrr.parcelable.ParcelableUser; import com.sun.tweetfiltrr.twitter.twitterretrievers.api.IAccessTokenRetrieverFromPref; import com.sun.tweetfiltrr.twitter.twitterretrievers.api.UserBundle; import com.sun.tweetfiltrr.utils.TwitterConstants; import com.sun.tweetfiltrr.utils.TwitterUtil; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import twitter4j.Twitter; import twitter4j.TwitterException; import twitter4j.auth.AccessToken; /** * Created by Sundeep on 13/02/14. */ public class AccessTokenRetrieverFromPref implements IAccessTokenRetrieverFromPref { private static final String TAG = AccessTokenRetrieverFromPref.class.getName(); private FriendDao _userDao; public AccessTokenRetrieverFromPref(FriendDao userDao_) { _userDao = userDao_; } @Override public Collection<UserBundle> retrieveAccessTokenFromSharedPref(SharedPreferences sharedPreferences_) { ArrayList<UserBundle> userBundles = new ArrayList<UserBundle>(); try { final AccessToken accessToken = new AccessToken(TwitterConstants.TWITTER_OAUTH_KEY, TwitterConstants.TWITTER_OAUTH_SECRET); //TODO THE ABOVE LINE NEEDS TO BE REMOVED, ONLY SUED THIS FOR DEBUGGING // final AccessToken accessToken = retrieveAccessTokenFromPreferences(sharedPreferences_); TwitterUtil.getInstance().setTwitterFactories(accessToken); Twitter twitter = TwitterUtil.getInstance().getTwitter(); Log.v(TAG, "accessToken" + accessToken); final ParcelableUser parcelableUserFromTwitter = new ParcelableUser(twitter.showUser(accessToken .getUserId())); Log.v(TAG, "got user from twitter" + parcelableUserFromTwitter); insertUpdatedTwitterUser(parcelableUserFromTwitter); //attempt to get user from DB, we should almost always get a user if we are here final Collection<ParcelableUser> parcelableUser = getParcelableUserFromDB(sharedPreferences_, parcelableUserFromTwitter); ParcelableUser userFromDb = null; if(!parcelableUser.isEmpty()){ userFromDb = parcelableUser.iterator().next(); } Log.v(TAG, "user from db" + parcelableUser); final UserBundle user = new UserBundle(userFromDb, accessToken); userBundles.add(user); } catch (TwitterException e) { e.printStackTrace(); } return userBundles; } private AccessToken retrieveAccessTokenFromPreferences(SharedPreferences sharedPreferences_) { String accessTokenString = sharedPreferences_.getString( TwitterConstants.PREFERENCE_TWITTER_OAUTH_TOKEN, ""); String accessTokenSecret = sharedPreferences_.getString( TwitterConstants.PREFERENCE_TWITTER_OAUTH_TOKEN_SECRET, ""); Log.v(TAG, "accessTokenString " + accessTokenString + " secret" + accessTokenSecret); return new AccessToken(accessTokenString, accessTokenSecret); } private void insertUpdatedTwitterUser(ParcelableUser user_){ String[] cols = new String[]{FriendTable.FriendColumn.FRIEND_ID.s(), FriendTable.FriendColumn.TWEET_COUNT.s(), FriendTable.FriendColumn.FOLLOWER_COUNT.s(), FriendTable.FriendColumn.FRIEND_COUNT.s(), FriendTable.FriendColumn.FRIEND_NAME.s(), FriendTable.FriendColumn.FRIEND_SCREENNAME.s(), FriendTable.FriendColumn.PROFILE_IMAGE_URL.s(),FriendTable.FriendColumn.BACKGROUND_PROFILE_IMAGE_URL.s(), FriendTable.FriendColumn.BANNER_PROFILE_IMAE_URL.s(), FriendTable.FriendColumn.DESCRIPTION.s()}; Collection<ParcelableUser> users = new ArrayList<ParcelableUser>(); users.add(user_); _userDao.insertOrUpdate(users, cols); } private Collection<ParcelableUser> getParcelableUserFromDB(SharedPreferences sharedPreferences_, ParcelableUser twitterSearchedUser_) { ParcelableUser parcelableUser = null; final Collection<ParcelableUser> users = new ArrayList<ParcelableUser>(1); long userId = -1l; if(twitterSearchedUser_ != null){ userId = twitterSearchedUser_.getUserId(); }else{ userId = sharedPreferences_.getLong( TwitterConstants.AUTH_USER_ID, -1l); } if (userId > -1) { users.addAll(_userDao.getEntries(FriendTable.FriendColumn.FRIEND_ID.s() + " = ? ", new String[]{Long.toString(userId)}, null)); } //we only expect one user since userid is always unique if (!users.isEmpty()) { Log.v(TAG, "Found user from DB"); if (users.size() > 1) { Log.w(TAG, "Found more then 1 user from DB for some reason, picking first in collection: " + Arrays.toString(users.toArray())); } } return users; } }
UTF-8
Java
5,262
java
AccessTokenRetrieverFromPref.java
Java
[ { "context": "ort twitter4j.auth.AccessToken;\n\n/**\n * Created by Sundeep on 13/02/14.\n */\npublic class AccessTokenRetrieve", "end": 755, "score": 0.9093570709228516, "start": 748, "tag": "NAME", "value": "Sundeep" } ]
null
[]
package com.sun.tweetfiltrr.twitter.twitterretrievers.impl; import android.content.SharedPreferences; import android.util.Log; import com.sun.tweetfiltrr.database.dao.impl.FriendDao; import com.sun.tweetfiltrr.database.tables.FriendTable; import com.sun.tweetfiltrr.parcelable.ParcelableUser; import com.sun.tweetfiltrr.twitter.twitterretrievers.api.IAccessTokenRetrieverFromPref; import com.sun.tweetfiltrr.twitter.twitterretrievers.api.UserBundle; import com.sun.tweetfiltrr.utils.TwitterConstants; import com.sun.tweetfiltrr.utils.TwitterUtil; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import twitter4j.Twitter; import twitter4j.TwitterException; import twitter4j.auth.AccessToken; /** * Created by Sundeep on 13/02/14. */ public class AccessTokenRetrieverFromPref implements IAccessTokenRetrieverFromPref { private static final String TAG = AccessTokenRetrieverFromPref.class.getName(); private FriendDao _userDao; public AccessTokenRetrieverFromPref(FriendDao userDao_) { _userDao = userDao_; } @Override public Collection<UserBundle> retrieveAccessTokenFromSharedPref(SharedPreferences sharedPreferences_) { ArrayList<UserBundle> userBundles = new ArrayList<UserBundle>(); try { final AccessToken accessToken = new AccessToken(TwitterConstants.TWITTER_OAUTH_KEY, TwitterConstants.TWITTER_OAUTH_SECRET); //TODO THE ABOVE LINE NEEDS TO BE REMOVED, ONLY SUED THIS FOR DEBUGGING // final AccessToken accessToken = retrieveAccessTokenFromPreferences(sharedPreferences_); TwitterUtil.getInstance().setTwitterFactories(accessToken); Twitter twitter = TwitterUtil.getInstance().getTwitter(); Log.v(TAG, "accessToken" + accessToken); final ParcelableUser parcelableUserFromTwitter = new ParcelableUser(twitter.showUser(accessToken .getUserId())); Log.v(TAG, "got user from twitter" + parcelableUserFromTwitter); insertUpdatedTwitterUser(parcelableUserFromTwitter); //attempt to get user from DB, we should almost always get a user if we are here final Collection<ParcelableUser> parcelableUser = getParcelableUserFromDB(sharedPreferences_, parcelableUserFromTwitter); ParcelableUser userFromDb = null; if(!parcelableUser.isEmpty()){ userFromDb = parcelableUser.iterator().next(); } Log.v(TAG, "user from db" + parcelableUser); final UserBundle user = new UserBundle(userFromDb, accessToken); userBundles.add(user); } catch (TwitterException e) { e.printStackTrace(); } return userBundles; } private AccessToken retrieveAccessTokenFromPreferences(SharedPreferences sharedPreferences_) { String accessTokenString = sharedPreferences_.getString( TwitterConstants.PREFERENCE_TWITTER_OAUTH_TOKEN, ""); String accessTokenSecret = sharedPreferences_.getString( TwitterConstants.PREFERENCE_TWITTER_OAUTH_TOKEN_SECRET, ""); Log.v(TAG, "accessTokenString " + accessTokenString + " secret" + accessTokenSecret); return new AccessToken(accessTokenString, accessTokenSecret); } private void insertUpdatedTwitterUser(ParcelableUser user_){ String[] cols = new String[]{FriendTable.FriendColumn.FRIEND_ID.s(), FriendTable.FriendColumn.TWEET_COUNT.s(), FriendTable.FriendColumn.FOLLOWER_COUNT.s(), FriendTable.FriendColumn.FRIEND_COUNT.s(), FriendTable.FriendColumn.FRIEND_NAME.s(), FriendTable.FriendColumn.FRIEND_SCREENNAME.s(), FriendTable.FriendColumn.PROFILE_IMAGE_URL.s(),FriendTable.FriendColumn.BACKGROUND_PROFILE_IMAGE_URL.s(), FriendTable.FriendColumn.BANNER_PROFILE_IMAE_URL.s(), FriendTable.FriendColumn.DESCRIPTION.s()}; Collection<ParcelableUser> users = new ArrayList<ParcelableUser>(); users.add(user_); _userDao.insertOrUpdate(users, cols); } private Collection<ParcelableUser> getParcelableUserFromDB(SharedPreferences sharedPreferences_, ParcelableUser twitterSearchedUser_) { ParcelableUser parcelableUser = null; final Collection<ParcelableUser> users = new ArrayList<ParcelableUser>(1); long userId = -1l; if(twitterSearchedUser_ != null){ userId = twitterSearchedUser_.getUserId(); }else{ userId = sharedPreferences_.getLong( TwitterConstants.AUTH_USER_ID, -1l); } if (userId > -1) { users.addAll(_userDao.getEntries(FriendTable.FriendColumn.FRIEND_ID.s() + " = ? ", new String[]{Long.toString(userId)}, null)); } //we only expect one user since userid is always unique if (!users.isEmpty()) { Log.v(TAG, "Found user from DB"); if (users.size() > 1) { Log.w(TAG, "Found more then 1 user from DB for some reason, picking first in collection: " + Arrays.toString(users.toArray())); } } return users; } }
5,262
0.68339
0.68054
114
45.166668
36.775974
145
false
false
0
0
0
0
0
0
0.719298
false
false
11