blob_id
stringlengths 40
40
| __id__
int64 225
39,780B
| directory_id
stringlengths 40
40
| path
stringlengths 6
313
| content_id
stringlengths 40
40
| detected_licenses
list | license_type
stringclasses 2
values | repo_name
stringlengths 6
132
| repo_url
stringlengths 25
151
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringlengths 4
70
| visit_date
timestamp[ns] | revision_date
timestamp[ns] | committer_date
timestamp[ns] | github_id
int64 7.28k
689M
⌀ | star_events_count
int64 0
131k
| fork_events_count
int64 0
48k
| gha_license_id
stringclasses 23
values | gha_fork
bool 2
classes | gha_event_created_at
timestamp[ns] | gha_created_at
timestamp[ns] | gha_updated_at
timestamp[ns] | gha_pushed_at
timestamp[ns] | gha_size
int64 0
40.4M
⌀ | gha_stargazers_count
int32 0
112k
⌀ | gha_forks_count
int32 0
39.4k
⌀ | gha_open_issues_count
int32 0
11k
⌀ | gha_language
stringlengths 1
21
⌀ | gha_archived
bool 2
classes | gha_disabled
bool 1
class | content
stringlengths 7
4.37M
| src_encoding
stringlengths 3
16
| language
stringclasses 1
value | length_bytes
int64 7
4.37M
| extension
stringclasses 24
values | filename
stringlengths 4
174
| language_id
stringclasses 1
value | entities
list | contaminating_dataset
stringclasses 0
values | malware_signatures
list | redacted_content
stringlengths 7
4.37M
| redacted_length_bytes
int64 7
4.37M
| alphanum_fraction
float32 0.25
0.94
| alpha_fraction
float32 0.25
0.94
| num_lines
int32 1
84k
| avg_line_length
float32 0.76
99.9
| std_line_length
float32 0
220
| max_line_length
int32 5
998
| is_vendor
bool 2
classes | is_generated
bool 1
class | max_hex_length
int32 0
319
| hex_fraction
float32 0
0.38
| max_unicode_length
int32 0
408
| unicode_fraction
float32 0
0.36
| max_base64_length
int32 0
506
| base64_fraction
float32 0
0.5
| avg_csv_sep_count
float32 0
4
| is_autogen_header
bool 1
class | is_empty_html
bool 1
class | shard
stringclasses 16
values |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
c52babbf02cb1053e9897c662f7d3a2ee4aca909 | 6,313,601,942,402 | cad0713738d05e19d8f33ced03366a2ca4faae34 | /src/main/java/ones/autowork/util/JdbcOptPgUtilsV2.java | dcde27efd7346254f8025277eea9f9be3b719a05 | []
| no_license | arraycto/ones.autowork.task | https://github.com/arraycto/ones.autowork.task | 9a5498d1d05ea75019e02fa82a7ddb4ed23f0483 | 98579be1bdd9a066b6fee82284f749a1149d88ae | refs/heads/master | 2022-12-15T06:35:52.362000 | 2020-09-03T08:23:22 | 2020-09-03T08:23:22 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package ones.autowork.util;
import ones.autowork.model.*;
import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import static ones.autowork.util.postgresql.PgJdbcConn.getConn;
/**
* Created by liYueYang on 2020/6/9.
*/
public class JdbcOptPgUtilsV2 {
/**
* 查询所涉及的表今天是否有数据更新
*
* @param reportDate
* @return
*/
public static int getUpdateCount(String reportDate) {
Connection c = getConn();
Statement stmt = null;
int count = 0;
try {
stmt = c.createStatement();
String sql = "SELECT (" +
"(SELECT count(*) FROM zh_returnedinfo a where a.report_date = '" + reportDate + "')" +
"+ (SELECT count(*) FROM zh_workinfo b where b.report_date = '" + reportDate + "')" +
"+(SELECT count(*) FROM zh_subpayment c where c.report_date = '" + reportDate + "')" +
"+(SELECT count(*) FROM zh_expendinfo d where d.report_date = '" + reportDate + "')" +
"+(SELECT count(*) FROM zh_disbursementplan e where e.report_date = '" + reportDate + "')" +
") as count";
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
count = rs.getInt("count");
}
rs.close();
stmt.close();
c.close();
return count;
} catch (Exception e) {
e.printStackTrace();
}
return count;
}
// 获取所有项目列表
public static List<ZH_Project> getAllProject() {
Connection c = getConn();
Statement stmt = null;
List<ZH_Project> zh_projects = new ArrayList<>();
try {
stmt = c.createStatement();
String sql = "SELECT * FROM zh_project";
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
zh_projects.add(new ZH_Project(rs.getString("project_id"), rs.getString("project_name"),
rs.getString("project_code"), rs.getString("owner_id"),
rs.getBigDecimal("sign_time"), rs.getBigDecimal("amount"),
rs.getString("project_leader"), rs.getString("leader_id"),
rs.getBigDecimal("leader_phone"), rs.getString("address"),
rs.getBigDecimal("citycode"), rs.getBigDecimal("date_start"),
rs.getBigDecimal("date_end"), rs.getString("department"),
rs.getString("department_id"), rs.getString("type_project"),
rs.getString("type_work"), rs.getString("stage"),
rs.getString("contract_no"), rs.getString("discription"),
rs.getString("marketer"), rs.getString("marketer_id"),
rs.getBigDecimal("m_phone"), rs.getString("pre_saler"),
rs.getString("pre_saler_id"), rs.getBigDecimal("p_phone"),
rs.getString("remark"), rs.getBigDecimal("winning_date"),
rs.getBigDecimal("start_date"), rs.getBigDecimal("completion_date"),
rs.getBigDecimal("acceptance_date"), rs.getBigDecimal("finish_date"),
rs.getBigDecimal("commence_date"), rs.getBigDecimal("budget")));
}
rs.close();
stmt.close();
c.close();
return zh_projects;
} catch (Exception e) {
e.printStackTrace();
}
return zh_projects;
}
// 项目回款信息表
public static List<ZH_ReturnedInfo> getReturnedInfo(String nowDate, String projectId) {
Connection c = getConn();
Statement stmt = null;
List<ZH_ReturnedInfo> zh_returnedInfos = new ArrayList<>();
try {
stmt = c.createStatement();
// todo 项目回款信息表 根据提交日期(report_date)查询
String sql = "SELECT * FROM zh_returnedinfo where returned_month = '" + nowDate + "' and project_id = '" + projectId + "'";
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
zh_returnedInfos.add(new ZH_ReturnedInfo(rs.getString("returned_id"), rs.getString("project_id"),
rs.getBigDecimal("trade_date"), rs.getBigDecimal("returned_month"),
rs.getBigDecimal("amount_returned"), rs.getString("use"),
rs.getString("nature_payment"), rs.getString("postscript"),
rs.getString("remark"), rs.getString("returned_unit")));
}
rs.close();
stmt.close();
c.close();
return zh_returnedInfos;
} catch (Exception e) {
e.printStackTrace();
}
return zh_returnedInfos;
}
// 项目月报信息表
public static List<ZH_WorkInfo> getWorkInfo(String nowDate, String projectId) {
Connection c = getConn();
Statement stmt = null;
List<ZH_WorkInfo> zh_workInfos = new ArrayList<>();
try {
stmt = c.createStatement();
String sql = "SELECT * FROM zh_workinfo where report_month = '" + nowDate + "' and project_id = '" + projectId + "'";
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
zh_workInfos.add(new ZH_WorkInfo(rs.getString("work_id"), rs.getString("project_id"),
rs.getBigDecimal("report_date"), rs.getBigDecimal("report_month"),
rs.getString("problem"), rs.getString("financial_status"),
rs.getString("work_status"), rs.getString("work_plan"),
rs.getString("safety_status"), rs.getString("safety_plan"),
rs.getString("remark"), rs.getString("proposal"),
rs.getBigDecimal("current_output_value"), rs.getBigDecimal("year_output_value"),
rs.getBigDecimal("comulative_output_value"), rs.getBigDecimal("next_plan_receipt"),
rs.getBigDecimal("current_progress"), rs.getBigDecimal("next_progress"),
rs.getString("progress_status"), rs.getString("reason_delay"),
rs.getString("measures")));
}
rs.close();
stmt.close();
c.close();
return zh_workInfos;
} catch (Exception e) {
e.printStackTrace();
}
return zh_workInfos;
}
// 分包付款信息表通过申请日期
public static List<ZH_SubPayment> getSubPaymentByReportDate(String nowDate, String projectId) {
Connection c = getConn();
Statement stmt = null;
List<ZH_SubPayment> zh_subPayments = new ArrayList<>();
try {
stmt = c.createStatement();
String sql = "SELECT * FROM zh_subpayment where pay_month = '" + nowDate + "' and project_id = '" + projectId + "'";
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
zh_subPayments.add(new ZH_SubPayment(rs.getString("payment_id"), rs.getString("project_id"),
rs.getString("contract_id"), rs.getBigDecimal("report_date"),
rs.getBigDecimal("pay_month"), rs.getBigDecimal("pay_times"),
rs.getBigDecimal("amount_invoice"), rs.getBigDecimal("amount_receivable"),
rs.getBigDecimal("pay_date"), rs.getBigDecimal("amount_payment"),
rs.getString("remark"), rs.getString("handledby"),
rs.getString("reason"), ""));
}
rs.close();
stmt.close();
c.close();
return zh_subPayments;
} catch (Exception e) {
e.printStackTrace();
}
return zh_subPayments;
}
// 分包付款信息表通过付款月份
public static List<ZH_SubPayment> getSubPaymentByPayMonth(BigDecimal payMonth, String projectId) {
Connection c = getConn();
Statement stmt = null;
List<ZH_SubPayment> zh_subPayments = new ArrayList<>();
try {
stmt = c.createStatement();
String sql = "SELECT a.*,b.contract_name FROM zh_subpayment a, zh_subcontract b " +
"where a.contract_id = b.contract_id and a.pay_month = '" + payMonth + "' and a.project_id = '" + projectId + "'";
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
zh_subPayments.add(new ZH_SubPayment(rs.getString("payment_id"), rs.getString("project_id"),
rs.getString("contract_id"), rs.getBigDecimal("report_date"),
rs.getBigDecimal("pay_month"), rs.getBigDecimal("pay_times"),
rs.getBigDecimal("amount_invoice"), rs.getBigDecimal("amount_receivable"),
rs.getBigDecimal("pay_date"), rs.getBigDecimal("amount_payment"),
rs.getString("remark"), rs.getString("handledby"),
rs.getString("reason"), rs.getString("contract_name")));
}
rs.close();
stmt.close();
c.close();
return zh_subPayments;
} catch (Exception e) {
e.printStackTrace();
}
return zh_subPayments;
}
// 分包付款 - 下月预计支出
public static List<ZH_DisBursementPlan> getDisBursementPlanByPayMonth(BigDecimal applyMonth, String projectId) {
Connection c = getConn();
Statement stmt = null;
List<ZH_DisBursementPlan> zh_disBursementPlans = new ArrayList<>();
try {
stmt = c.createStatement();
String sql = "SELECT a.*,b.contract_name FROM zh_disbursementplan a,zh_subcontract b " +
"where a.contract_id = b.contract_id and a.apply_month = '" + applyMonth + "' and a.project_id = '" + projectId + "'";
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
zh_disBursementPlans.add(new ZH_DisBursementPlan(rs.getString("plan_id"), rs.getString("project_id"),
rs.getString("contract_id"), rs.getBigDecimal("report_date"),
rs.getBigDecimal("apply_month"), rs.getBigDecimal("estimate_payment"),
rs.getString("remark"), rs.getString("proportion"),
rs.getBigDecimal("paid_amount"), rs.getString("contract_name")));
}
rs.close();
stmt.close();
c.close();
return zh_disBursementPlans;
} catch (Exception e) {
e.printStackTrace();
}
return zh_disBursementPlans;
}
// 项目支出用款表,通过上报日期
public static List<ZH_ExpendInfo> getExpendInfoByReportDate(String nowDate, String projectId) {
Connection c = getConn();
Statement stmt = null;
List<ZH_ExpendInfo> zh_expendInfos = new ArrayList<>();
try {
stmt = c.createStatement();
String sql = "SELECT * FROM zh_expendinfo where spend_month = '" + nowDate + "' and project_id = '" + projectId + "'";
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
zh_expendInfos.add(new ZH_ExpendInfo(rs.getString("expend_id"), rs.getString("project_id"),
rs.getBigDecimal("report_date"), rs.getBigDecimal("spend_month"),
rs.getString("spend_type"), rs.getString("remark")));
}
rs.close();
stmt.close();
c.close();
return zh_expendInfos;
} catch (Exception e) {
e.printStackTrace();
}
return zh_expendInfos;
}
// 项目支出用款表,通过支出月份
public static List<ZH_ExpendMoney> getExpendInfoBySpeedMonth(BigDecimal nowDate, String projectId, String speedType) {
Connection c = getConn();
Statement stmt = null;
List<ZH_ExpendMoney> zh_expendMoneyList = new ArrayList<>();
try {
stmt = c.createStatement();
String sql = "SELECT * from zh_expendmoney where expend_id in" +
"(SELECT expend_id FROM zh_expendinfo " +
"where spend_type = '" + speedType + "' and spend_month = '"
+ nowDate + "' and project_id = '" + projectId + "')";
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
zh_expendMoneyList.add(new ZH_ExpendMoney(rs.getString("money_id"), rs.getString("expend_id"),
rs.getString("expend_type"), rs.getBigDecimal("amount_expend"),
rs.getString("expend_typename")));
}
rs.close();
stmt.close();
c.close();
return zh_expendMoneyList;
} catch (Exception e) {
e.printStackTrace();
}
return zh_expendMoneyList;
}
// 用款申请计划表
public static List<ZH_DisBursementPlan> getDisBurseMentPlan(String nowDate, String projectId) {
Connection c = getConn();
Statement stmt = null;
List<ZH_DisBursementPlan> zh_disBursementPlans = new ArrayList<>();
try {
stmt = c.createStatement();
String sql = "SELECT * FROM zh_disbursementplan where apply_month = '" + nowDate + "' and project_id = '" + projectId + "'";
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
zh_disBursementPlans.add(new ZH_DisBursementPlan(rs.getString("plan_id"), rs.getString("project_id"),
rs.getString("contract_id"), rs.getBigDecimal("report_date"),
rs.getBigDecimal("apply_month"), rs.getBigDecimal("estimate_payment"),
rs.getString("remark"), rs.getString("proportion"),
rs.getBigDecimal("paid_amount"), ""));
}
rs.close();
stmt.close();
c.close();
return zh_disBursementPlans;
} catch (Exception e) {
e.printStackTrace();
}
return zh_disBursementPlans;
}
// 根据项目id、回款月份查询项目经营台账表
public static ZH_Management getManagementByProIdAndMonth(String projectId, BigDecimal returnedMonth) {
Connection c = getConn();
Statement stmt = null;
ZH_Management zh_management = null;
try {
stmt = c.createStatement();
String sql = "SELECT * FROM zh_management where project_id = '" + projectId + "' and report_date = '" + returnedMonth + "'";
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
zh_management = new ZH_Management(rs.getString("management_id"), rs.getString("project_id"),
rs.getBigDecimal("report_date"), rs.getBigDecimal("current_actual_receipt"),
rs.getBigDecimal("current_output_value"), rs.getBigDecimal("current_expenditure"),
rs.getBigDecimal("last_plan_return"), rs.getBigDecimal("last_plan_expenditure"),
rs.getBigDecimal("next_plan_receipt"), rs.getBigDecimal("next_plan_expenditure"),
rs.getString("info_current"), rs.getString("info_next"),
rs.getString("remark"));
}
rs.close();
stmt.close();
c.close();
return zh_management;
} catch (Exception e) {
e.printStackTrace();
}
return zh_management;
}
// 分包付款信息表 - AMOUNT_PAYMENT + 项目支出用款表 - AMOUNT_EXPEND(支出ID为本月实际支出的)
public static BigDecimal getCurrentExpenditureSum(BigDecimal spendMonth, String projectId) {
Connection c = getConn();
Statement stmt = null;
BigDecimal amountReturnSum = null;
try {
stmt = c.createStatement();
String sql = "SELECT sum(COALESCE((SELECT sum(amount_payment) FROM zh_subpayment where " +
" pay_month = '" + spendMonth + "'" +
"and project_id = '" + projectId + "'),0) + COALESCE((SELECT sum(a.amount_expend) " +
"FROM zh_expendmoney a,zh_expendinfo b where " +
"a.expend_id = b.expend_id and b.spend_type = 'current' " +
"and b.project_id = '" + projectId + "'" +
"and b.spend_month = '" + spendMonth + "'),0)) AS sum";
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
amountReturnSum = rs.getBigDecimal("sum");
}
rs.close();
stmt.close();
c.close();
return amountReturnSum;
} catch (Exception e) {
e.printStackTrace();
}
return amountReturnSum;
}
// 本月完成产值
public static BigDecimal getCurrentOutPutValueThisMonth(BigDecimal reportMonth, String projectId) {
Connection c = getConn();
Statement stmt = null;
BigDecimal amountReturnSum = null;
try {
stmt = c.createStatement();
String sql = "SELECT current_output_value " +
"from zh_workinfo where report_month = '" + reportMonth + "' and project_id = '" + projectId + "'";
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
amountReturnSum = rs.getBigDecimal("current_output_value");
}
rs.close();
stmt.close();
c.close();
return amountReturnSum;
} catch (Exception e) {
e.printStackTrace();
}
return amountReturnSum;
}
// 下月预计回款
public static BigDecimal getNextPlanReceipt(BigDecimal reportMonth, String projectId) {
Connection c = getConn();
Statement stmt = null;
BigDecimal amountReturnSum = null;
try {
stmt = c.createStatement();
String sql = "SELECT next_plan_receipt " +
"from zh_workinfo where report_month = '" + reportMonth + "' and project_id = '" + projectId + "'";
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
amountReturnSum = rs.getBigDecimal("next_plan_receipt");
}
rs.close();
stmt.close();
c.close();
return amountReturnSum;
} catch (Exception e) {
e.printStackTrace();
}
return amountReturnSum;
}
// 本月实际回款
public static BigDecimal getCurrentActualReceipt(BigDecimal returnedMonth, String projectId) {
Connection c = getConn();
Statement stmt = null;
BigDecimal amountReturnSum = null;
try {
stmt = c.createStatement();
String sql = "SELECT amount_returned from zh_returnedinfo " +
"WHERE project_id = '" + projectId + "' and returned_month = '" + returnedMonth + "'";
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
amountReturnSum = rs.getBigDecimal("amount_returned");
}
rs.close();
stmt.close();
c.close();
return amountReturnSum;
} catch (Exception e) {
e.printStackTrace();
}
return amountReturnSum;
}
// 下月预计支出 - 分包付款
public static BigDecimal getNextPlanExpenditureFenBaoSum(BigDecimal spendMonth, String projectId) {
Connection c = getConn();
Statement stmt = null;
BigDecimal amountReturnSum = null;
try {
stmt = c.createStatement();
String sql = "SELECT sum(estimate_payment) as estimatePaymentSum FROM zh_disbursementplan where " +
" project_id = '" + projectId + "' and apply_month = '" + spendMonth + "'";
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
amountReturnSum = rs.getBigDecimal("estimatePaymentSum");
}
rs.close();
stmt.close();
c.close();
return amountReturnSum;
} catch (Exception e) {
e.printStackTrace();
}
return amountReturnSum;
}
// 下月预计支出 - 其他支出
public static BigDecimal getNextPlanExpenditureOtherSum(BigDecimal spendMonth, String projectId) {
Connection c = getConn();
Statement stmt = null;
BigDecimal amountReturnSum = null;
try {
stmt = c.createStatement();
String sql = "SELECT sum(a.amount_expend) as amountExpendSum FROM zh_expendmoney a,zh_expendinfo b where " +
" a.expend_id = b.expend_id and b.spend_type = 'next' " +
" and b.project_id = '" + projectId + "'" +
" and b.spend_month = '" + spendMonth + "'";
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
amountReturnSum = rs.getBigDecimal("amountExpendSum");
}
rs.close();
stmt.close();
c.close();
return amountReturnSum;
} catch (Exception e) {
e.printStackTrace();
}
return amountReturnSum;
}
// 台账表:更新‘累计回款’、‘本月实际回款’字段
public static void updateManagementByReturnInfo(String managementId, BigDecimal currentActualReceiptSum, BigDecimal NextPlanReceipt, BigDecimal NextPlanExpenditure) {
Connection c = getConn();
Statement stmt = null;
try {
stmt = c.createStatement();
String sql = "UPDATE zh_management SET " +
"current_actual_receipt = '" + currentActualReceiptSum + "'" +
", last_plan_return = '" + NextPlanReceipt + "'" +
", last_plan_expenditure = '" + NextPlanExpenditure + "'" +
" WHERE management_id = '" + managementId + "'";
stmt.executeUpdate(sql);
c.commit();
stmt.close();
c.close();
} catch (Exception e) {
e.printStackTrace();
}
}
// 台账表:更新‘本月完成产值’、‘下月预计回款’字段
public static void updateManagementByWorkInfo(String managementId, BigDecimal currentOutPutValueThisSum,
BigDecimal nextPlanReceiptSum, BigDecimal NextPlanReceipt, BigDecimal NextPlanExpenditure) {
Connection c = getConn();
Statement stmt = null;
try {
stmt = c.createStatement();
String sql = "UPDATE zh_management SET " +
"current_output_value = '" + currentOutPutValueThisSum + "'" +
", next_plan_receipt = '" + nextPlanReceiptSum + "'" +
", last_plan_return = '" + NextPlanReceipt + "'" +
", last_plan_expenditure = '" + NextPlanExpenditure + "'" +
" WHERE management_id = '" + managementId + "'";
stmt.executeUpdate(sql);
c.commit();
stmt.close();
c.close();
} catch (Exception e) {
e.printStackTrace();
}
}
// 台账表:更新‘本月实际支出’、‘备注’字段
public static void updateManagementBySubPayMent(String managementId, BigDecimal currentOutPutValueThisSum,
String infoCurrent, BigDecimal NextPlanReceipt, BigDecimal NextPlanExpenditure) {
Connection c = getConn();
Statement stmt = null;
try {
stmt = c.createStatement();
String sql = "UPDATE zh_management SET " +
"current_expenditure = '" + currentOutPutValueThisSum + "'" +
", info_current = '" + infoCurrent + "'" +
", last_plan_return = '" + NextPlanReceipt + "'" +
", last_plan_expenditure = '" + NextPlanExpenditure + "'" +
" WHERE management_id = '" + managementId + "'";
stmt.executeUpdate(sql);
c.commit();
stmt.close();
c.close();
} catch (Exception e) {
e.printStackTrace();
}
}
// 台账表:更新‘下月预计支出’、'本月实际支出'字段
public static void updateManagementByExpendInfo(String managementId, BigDecimal nextPlanExpenditureSum,
BigDecimal currentOutPutValueThisSum, String infoCurrent,
String infoNext, BigDecimal NextPlanReceipt, BigDecimal NextPlanExpenditure) {
Connection c = getConn();
Statement stmt = null;
try {
stmt = c.createStatement();
String sql = "UPDATE zh_management SET " +
"next_plan_expenditure = '" + nextPlanExpenditureSum +
"',current_expenditure = '" + currentOutPutValueThisSum +
"',info_current = '" + infoCurrent +
"', info_next = '" + infoNext +
"', last_plan_return = '" + NextPlanReceipt +
"', last_plan_expenditure = '" + NextPlanExpenditure +
"' WHERE management_id = '" + managementId + "'";
stmt.executeUpdate(sql);
c.commit();
stmt.close();
c.close();
} catch (Exception e) {
e.printStackTrace();
}
}
// 台账表:更新‘下月预计支出’字段
public static void updateManagementByDisBursementPlan(String managementId, BigDecimal nextPlanExpenditureSum,
String infoNext, BigDecimal NextPlanReceipt, BigDecimal NextPlanExpenditure) {
Connection c = getConn();
Statement stmt = null;
try {
stmt = c.createStatement();
String sql = "UPDATE zh_management SET " +
"next_plan_expenditure = '" + nextPlanExpenditureSum +
"', info_next = '" + infoNext +
"', last_plan_return = '" + NextPlanReceipt +
"', last_plan_expenditure = '" + NextPlanExpenditure +
"' WHERE management_id = '" + managementId + "'";
stmt.executeUpdate(sql);
c.commit();
stmt.close();
c.close();
} catch (Exception e) {
e.printStackTrace();
}
}
// 新增台账记录
public static void insertManagement(ZH_Management zh_management) {
Connection c = getConn();
Statement stmt = null;
try {
stmt = c.createStatement();
String sql = "INSERT INTO zh_management(management_id,project_id,report_date,current_actual_receipt,current_output_value" +
",current_expenditure,last_plan_return,last_plan_expenditure,next_plan_receipt" +
",next_plan_expenditure,info_current,info_next,remark) VALUES(" +
"'" + UUID.randomUUID().toString() + "'," +
"'" + zh_management.getProject_id() + "'," +
"'" + zh_management.getReport_date() + "'," +
"'" + zh_management.getCurrent_actual_receipt() + "'," +
"'" + zh_management.getCurrent_output_value() + "'," +
"'" + zh_management.getCurrent_expenditure() + "'," +
"'" + zh_management.getLast_plan_return() + "'," +
"'" + zh_management.getLast_plan_expenditure() + "'," +
"'" + zh_management.getNext_plan_receipt() + "'," +
"'" + zh_management.getNext_plan_expenditure() + "'," +
"'" + zh_management.getInfo_current() + "'," +
"'" + zh_management.getInfo_next() + "'," +
"'" + zh_management.getRemark() + "')";
stmt.executeUpdate(sql);
c.commit();
stmt.close();
c.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static List<ZH_UpdateStatus> getUpdateCountNew() {
Connection c = getConn();
Statement stmt = null;
List<ZH_UpdateStatus> zh_updateStatuses = new ArrayList<>();
try {
stmt = c.createStatement();
String sql = "SELECT * FROM zh_update_status";
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
zh_updateStatuses.add(new ZH_UpdateStatus(rs.getString("status_id"), rs.getString("project_id"),
rs.getBigDecimal("month")));
}
rs.close();
stmt.close();
c.close();
return zh_updateStatuses;
} catch (Exception e) {
e.printStackTrace();
}
return zh_updateStatuses;
}
// 删除一条记录
public static void deleteIt(String statusId) {
Connection c = getConn();
Statement stmt = null;
try {
stmt = c.createStatement();
String sql = "DELETE from zh_update_status where status_id = '" + statusId + "'";
stmt.executeUpdate(sql);
c.commit();
stmt.close();
c.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
| UTF-8 | Java | 30,050 | java | JdbcOptPgUtilsV2.java | Java | [
{
"context": ".postgresql.PgJdbcConn.getConn;\n\n/**\n * Created by liYueYang on 2020/6/9.\n */\npublic class JdbcOptPgUtilsV2 {\n",
"end": 338,
"score": 0.909131646156311,
"start": 329,
"tag": "NAME",
"value": "liYueYang"
}
]
| null | []
| package ones.autowork.util;
import ones.autowork.model.*;
import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import static ones.autowork.util.postgresql.PgJdbcConn.getConn;
/**
* Created by liYueYang on 2020/6/9.
*/
public class JdbcOptPgUtilsV2 {
/**
* 查询所涉及的表今天是否有数据更新
*
* @param reportDate
* @return
*/
public static int getUpdateCount(String reportDate) {
Connection c = getConn();
Statement stmt = null;
int count = 0;
try {
stmt = c.createStatement();
String sql = "SELECT (" +
"(SELECT count(*) FROM zh_returnedinfo a where a.report_date = '" + reportDate + "')" +
"+ (SELECT count(*) FROM zh_workinfo b where b.report_date = '" + reportDate + "')" +
"+(SELECT count(*) FROM zh_subpayment c where c.report_date = '" + reportDate + "')" +
"+(SELECT count(*) FROM zh_expendinfo d where d.report_date = '" + reportDate + "')" +
"+(SELECT count(*) FROM zh_disbursementplan e where e.report_date = '" + reportDate + "')" +
") as count";
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
count = rs.getInt("count");
}
rs.close();
stmt.close();
c.close();
return count;
} catch (Exception e) {
e.printStackTrace();
}
return count;
}
// 获取所有项目列表
public static List<ZH_Project> getAllProject() {
Connection c = getConn();
Statement stmt = null;
List<ZH_Project> zh_projects = new ArrayList<>();
try {
stmt = c.createStatement();
String sql = "SELECT * FROM zh_project";
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
zh_projects.add(new ZH_Project(rs.getString("project_id"), rs.getString("project_name"),
rs.getString("project_code"), rs.getString("owner_id"),
rs.getBigDecimal("sign_time"), rs.getBigDecimal("amount"),
rs.getString("project_leader"), rs.getString("leader_id"),
rs.getBigDecimal("leader_phone"), rs.getString("address"),
rs.getBigDecimal("citycode"), rs.getBigDecimal("date_start"),
rs.getBigDecimal("date_end"), rs.getString("department"),
rs.getString("department_id"), rs.getString("type_project"),
rs.getString("type_work"), rs.getString("stage"),
rs.getString("contract_no"), rs.getString("discription"),
rs.getString("marketer"), rs.getString("marketer_id"),
rs.getBigDecimal("m_phone"), rs.getString("pre_saler"),
rs.getString("pre_saler_id"), rs.getBigDecimal("p_phone"),
rs.getString("remark"), rs.getBigDecimal("winning_date"),
rs.getBigDecimal("start_date"), rs.getBigDecimal("completion_date"),
rs.getBigDecimal("acceptance_date"), rs.getBigDecimal("finish_date"),
rs.getBigDecimal("commence_date"), rs.getBigDecimal("budget")));
}
rs.close();
stmt.close();
c.close();
return zh_projects;
} catch (Exception e) {
e.printStackTrace();
}
return zh_projects;
}
// 项目回款信息表
public static List<ZH_ReturnedInfo> getReturnedInfo(String nowDate, String projectId) {
Connection c = getConn();
Statement stmt = null;
List<ZH_ReturnedInfo> zh_returnedInfos = new ArrayList<>();
try {
stmt = c.createStatement();
// todo 项目回款信息表 根据提交日期(report_date)查询
String sql = "SELECT * FROM zh_returnedinfo where returned_month = '" + nowDate + "' and project_id = '" + projectId + "'";
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
zh_returnedInfos.add(new ZH_ReturnedInfo(rs.getString("returned_id"), rs.getString("project_id"),
rs.getBigDecimal("trade_date"), rs.getBigDecimal("returned_month"),
rs.getBigDecimal("amount_returned"), rs.getString("use"),
rs.getString("nature_payment"), rs.getString("postscript"),
rs.getString("remark"), rs.getString("returned_unit")));
}
rs.close();
stmt.close();
c.close();
return zh_returnedInfos;
} catch (Exception e) {
e.printStackTrace();
}
return zh_returnedInfos;
}
// 项目月报信息表
public static List<ZH_WorkInfo> getWorkInfo(String nowDate, String projectId) {
Connection c = getConn();
Statement stmt = null;
List<ZH_WorkInfo> zh_workInfos = new ArrayList<>();
try {
stmt = c.createStatement();
String sql = "SELECT * FROM zh_workinfo where report_month = '" + nowDate + "' and project_id = '" + projectId + "'";
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
zh_workInfos.add(new ZH_WorkInfo(rs.getString("work_id"), rs.getString("project_id"),
rs.getBigDecimal("report_date"), rs.getBigDecimal("report_month"),
rs.getString("problem"), rs.getString("financial_status"),
rs.getString("work_status"), rs.getString("work_plan"),
rs.getString("safety_status"), rs.getString("safety_plan"),
rs.getString("remark"), rs.getString("proposal"),
rs.getBigDecimal("current_output_value"), rs.getBigDecimal("year_output_value"),
rs.getBigDecimal("comulative_output_value"), rs.getBigDecimal("next_plan_receipt"),
rs.getBigDecimal("current_progress"), rs.getBigDecimal("next_progress"),
rs.getString("progress_status"), rs.getString("reason_delay"),
rs.getString("measures")));
}
rs.close();
stmt.close();
c.close();
return zh_workInfos;
} catch (Exception e) {
e.printStackTrace();
}
return zh_workInfos;
}
// 分包付款信息表通过申请日期
public static List<ZH_SubPayment> getSubPaymentByReportDate(String nowDate, String projectId) {
Connection c = getConn();
Statement stmt = null;
List<ZH_SubPayment> zh_subPayments = new ArrayList<>();
try {
stmt = c.createStatement();
String sql = "SELECT * FROM zh_subpayment where pay_month = '" + nowDate + "' and project_id = '" + projectId + "'";
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
zh_subPayments.add(new ZH_SubPayment(rs.getString("payment_id"), rs.getString("project_id"),
rs.getString("contract_id"), rs.getBigDecimal("report_date"),
rs.getBigDecimal("pay_month"), rs.getBigDecimal("pay_times"),
rs.getBigDecimal("amount_invoice"), rs.getBigDecimal("amount_receivable"),
rs.getBigDecimal("pay_date"), rs.getBigDecimal("amount_payment"),
rs.getString("remark"), rs.getString("handledby"),
rs.getString("reason"), ""));
}
rs.close();
stmt.close();
c.close();
return zh_subPayments;
} catch (Exception e) {
e.printStackTrace();
}
return zh_subPayments;
}
// 分包付款信息表通过付款月份
public static List<ZH_SubPayment> getSubPaymentByPayMonth(BigDecimal payMonth, String projectId) {
Connection c = getConn();
Statement stmt = null;
List<ZH_SubPayment> zh_subPayments = new ArrayList<>();
try {
stmt = c.createStatement();
String sql = "SELECT a.*,b.contract_name FROM zh_subpayment a, zh_subcontract b " +
"where a.contract_id = b.contract_id and a.pay_month = '" + payMonth + "' and a.project_id = '" + projectId + "'";
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
zh_subPayments.add(new ZH_SubPayment(rs.getString("payment_id"), rs.getString("project_id"),
rs.getString("contract_id"), rs.getBigDecimal("report_date"),
rs.getBigDecimal("pay_month"), rs.getBigDecimal("pay_times"),
rs.getBigDecimal("amount_invoice"), rs.getBigDecimal("amount_receivable"),
rs.getBigDecimal("pay_date"), rs.getBigDecimal("amount_payment"),
rs.getString("remark"), rs.getString("handledby"),
rs.getString("reason"), rs.getString("contract_name")));
}
rs.close();
stmt.close();
c.close();
return zh_subPayments;
} catch (Exception e) {
e.printStackTrace();
}
return zh_subPayments;
}
// 分包付款 - 下月预计支出
public static List<ZH_DisBursementPlan> getDisBursementPlanByPayMonth(BigDecimal applyMonth, String projectId) {
Connection c = getConn();
Statement stmt = null;
List<ZH_DisBursementPlan> zh_disBursementPlans = new ArrayList<>();
try {
stmt = c.createStatement();
String sql = "SELECT a.*,b.contract_name FROM zh_disbursementplan a,zh_subcontract b " +
"where a.contract_id = b.contract_id and a.apply_month = '" + applyMonth + "' and a.project_id = '" + projectId + "'";
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
zh_disBursementPlans.add(new ZH_DisBursementPlan(rs.getString("plan_id"), rs.getString("project_id"),
rs.getString("contract_id"), rs.getBigDecimal("report_date"),
rs.getBigDecimal("apply_month"), rs.getBigDecimal("estimate_payment"),
rs.getString("remark"), rs.getString("proportion"),
rs.getBigDecimal("paid_amount"), rs.getString("contract_name")));
}
rs.close();
stmt.close();
c.close();
return zh_disBursementPlans;
} catch (Exception e) {
e.printStackTrace();
}
return zh_disBursementPlans;
}
// 项目支出用款表,通过上报日期
public static List<ZH_ExpendInfo> getExpendInfoByReportDate(String nowDate, String projectId) {
Connection c = getConn();
Statement stmt = null;
List<ZH_ExpendInfo> zh_expendInfos = new ArrayList<>();
try {
stmt = c.createStatement();
String sql = "SELECT * FROM zh_expendinfo where spend_month = '" + nowDate + "' and project_id = '" + projectId + "'";
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
zh_expendInfos.add(new ZH_ExpendInfo(rs.getString("expend_id"), rs.getString("project_id"),
rs.getBigDecimal("report_date"), rs.getBigDecimal("spend_month"),
rs.getString("spend_type"), rs.getString("remark")));
}
rs.close();
stmt.close();
c.close();
return zh_expendInfos;
} catch (Exception e) {
e.printStackTrace();
}
return zh_expendInfos;
}
// 项目支出用款表,通过支出月份
public static List<ZH_ExpendMoney> getExpendInfoBySpeedMonth(BigDecimal nowDate, String projectId, String speedType) {
Connection c = getConn();
Statement stmt = null;
List<ZH_ExpendMoney> zh_expendMoneyList = new ArrayList<>();
try {
stmt = c.createStatement();
String sql = "SELECT * from zh_expendmoney where expend_id in" +
"(SELECT expend_id FROM zh_expendinfo " +
"where spend_type = '" + speedType + "' and spend_month = '"
+ nowDate + "' and project_id = '" + projectId + "')";
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
zh_expendMoneyList.add(new ZH_ExpendMoney(rs.getString("money_id"), rs.getString("expend_id"),
rs.getString("expend_type"), rs.getBigDecimal("amount_expend"),
rs.getString("expend_typename")));
}
rs.close();
stmt.close();
c.close();
return zh_expendMoneyList;
} catch (Exception e) {
e.printStackTrace();
}
return zh_expendMoneyList;
}
// 用款申请计划表
public static List<ZH_DisBursementPlan> getDisBurseMentPlan(String nowDate, String projectId) {
Connection c = getConn();
Statement stmt = null;
List<ZH_DisBursementPlan> zh_disBursementPlans = new ArrayList<>();
try {
stmt = c.createStatement();
String sql = "SELECT * FROM zh_disbursementplan where apply_month = '" + nowDate + "' and project_id = '" + projectId + "'";
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
zh_disBursementPlans.add(new ZH_DisBursementPlan(rs.getString("plan_id"), rs.getString("project_id"),
rs.getString("contract_id"), rs.getBigDecimal("report_date"),
rs.getBigDecimal("apply_month"), rs.getBigDecimal("estimate_payment"),
rs.getString("remark"), rs.getString("proportion"),
rs.getBigDecimal("paid_amount"), ""));
}
rs.close();
stmt.close();
c.close();
return zh_disBursementPlans;
} catch (Exception e) {
e.printStackTrace();
}
return zh_disBursementPlans;
}
// 根据项目id、回款月份查询项目经营台账表
public static ZH_Management getManagementByProIdAndMonth(String projectId, BigDecimal returnedMonth) {
Connection c = getConn();
Statement stmt = null;
ZH_Management zh_management = null;
try {
stmt = c.createStatement();
String sql = "SELECT * FROM zh_management where project_id = '" + projectId + "' and report_date = '" + returnedMonth + "'";
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
zh_management = new ZH_Management(rs.getString("management_id"), rs.getString("project_id"),
rs.getBigDecimal("report_date"), rs.getBigDecimal("current_actual_receipt"),
rs.getBigDecimal("current_output_value"), rs.getBigDecimal("current_expenditure"),
rs.getBigDecimal("last_plan_return"), rs.getBigDecimal("last_plan_expenditure"),
rs.getBigDecimal("next_plan_receipt"), rs.getBigDecimal("next_plan_expenditure"),
rs.getString("info_current"), rs.getString("info_next"),
rs.getString("remark"));
}
rs.close();
stmt.close();
c.close();
return zh_management;
} catch (Exception e) {
e.printStackTrace();
}
return zh_management;
}
// 分包付款信息表 - AMOUNT_PAYMENT + 项目支出用款表 - AMOUNT_EXPEND(支出ID为本月实际支出的)
public static BigDecimal getCurrentExpenditureSum(BigDecimal spendMonth, String projectId) {
Connection c = getConn();
Statement stmt = null;
BigDecimal amountReturnSum = null;
try {
stmt = c.createStatement();
String sql = "SELECT sum(COALESCE((SELECT sum(amount_payment) FROM zh_subpayment where " +
" pay_month = '" + spendMonth + "'" +
"and project_id = '" + projectId + "'),0) + COALESCE((SELECT sum(a.amount_expend) " +
"FROM zh_expendmoney a,zh_expendinfo b where " +
"a.expend_id = b.expend_id and b.spend_type = 'current' " +
"and b.project_id = '" + projectId + "'" +
"and b.spend_month = '" + spendMonth + "'),0)) AS sum";
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
amountReturnSum = rs.getBigDecimal("sum");
}
rs.close();
stmt.close();
c.close();
return amountReturnSum;
} catch (Exception e) {
e.printStackTrace();
}
return amountReturnSum;
}
// 本月完成产值
public static BigDecimal getCurrentOutPutValueThisMonth(BigDecimal reportMonth, String projectId) {
Connection c = getConn();
Statement stmt = null;
BigDecimal amountReturnSum = null;
try {
stmt = c.createStatement();
String sql = "SELECT current_output_value " +
"from zh_workinfo where report_month = '" + reportMonth + "' and project_id = '" + projectId + "'";
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
amountReturnSum = rs.getBigDecimal("current_output_value");
}
rs.close();
stmt.close();
c.close();
return amountReturnSum;
} catch (Exception e) {
e.printStackTrace();
}
return amountReturnSum;
}
// 下月预计回款
public static BigDecimal getNextPlanReceipt(BigDecimal reportMonth, String projectId) {
Connection c = getConn();
Statement stmt = null;
BigDecimal amountReturnSum = null;
try {
stmt = c.createStatement();
String sql = "SELECT next_plan_receipt " +
"from zh_workinfo where report_month = '" + reportMonth + "' and project_id = '" + projectId + "'";
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
amountReturnSum = rs.getBigDecimal("next_plan_receipt");
}
rs.close();
stmt.close();
c.close();
return amountReturnSum;
} catch (Exception e) {
e.printStackTrace();
}
return amountReturnSum;
}
// 本月实际回款
public static BigDecimal getCurrentActualReceipt(BigDecimal returnedMonth, String projectId) {
Connection c = getConn();
Statement stmt = null;
BigDecimal amountReturnSum = null;
try {
stmt = c.createStatement();
String sql = "SELECT amount_returned from zh_returnedinfo " +
"WHERE project_id = '" + projectId + "' and returned_month = '" + returnedMonth + "'";
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
amountReturnSum = rs.getBigDecimal("amount_returned");
}
rs.close();
stmt.close();
c.close();
return amountReturnSum;
} catch (Exception e) {
e.printStackTrace();
}
return amountReturnSum;
}
// 下月预计支出 - 分包付款
public static BigDecimal getNextPlanExpenditureFenBaoSum(BigDecimal spendMonth, String projectId) {
Connection c = getConn();
Statement stmt = null;
BigDecimal amountReturnSum = null;
try {
stmt = c.createStatement();
String sql = "SELECT sum(estimate_payment) as estimatePaymentSum FROM zh_disbursementplan where " +
" project_id = '" + projectId + "' and apply_month = '" + spendMonth + "'";
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
amountReturnSum = rs.getBigDecimal("estimatePaymentSum");
}
rs.close();
stmt.close();
c.close();
return amountReturnSum;
} catch (Exception e) {
e.printStackTrace();
}
return amountReturnSum;
}
// 下月预计支出 - 其他支出
public static BigDecimal getNextPlanExpenditureOtherSum(BigDecimal spendMonth, String projectId) {
Connection c = getConn();
Statement stmt = null;
BigDecimal amountReturnSum = null;
try {
stmt = c.createStatement();
String sql = "SELECT sum(a.amount_expend) as amountExpendSum FROM zh_expendmoney a,zh_expendinfo b where " +
" a.expend_id = b.expend_id and b.spend_type = 'next' " +
" and b.project_id = '" + projectId + "'" +
" and b.spend_month = '" + spendMonth + "'";
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
amountReturnSum = rs.getBigDecimal("amountExpendSum");
}
rs.close();
stmt.close();
c.close();
return amountReturnSum;
} catch (Exception e) {
e.printStackTrace();
}
return amountReturnSum;
}
// 台账表:更新‘累计回款’、‘本月实际回款’字段
public static void updateManagementByReturnInfo(String managementId, BigDecimal currentActualReceiptSum, BigDecimal NextPlanReceipt, BigDecimal NextPlanExpenditure) {
Connection c = getConn();
Statement stmt = null;
try {
stmt = c.createStatement();
String sql = "UPDATE zh_management SET " +
"current_actual_receipt = '" + currentActualReceiptSum + "'" +
", last_plan_return = '" + NextPlanReceipt + "'" +
", last_plan_expenditure = '" + NextPlanExpenditure + "'" +
" WHERE management_id = '" + managementId + "'";
stmt.executeUpdate(sql);
c.commit();
stmt.close();
c.close();
} catch (Exception e) {
e.printStackTrace();
}
}
// 台账表:更新‘本月完成产值’、‘下月预计回款’字段
public static void updateManagementByWorkInfo(String managementId, BigDecimal currentOutPutValueThisSum,
BigDecimal nextPlanReceiptSum, BigDecimal NextPlanReceipt, BigDecimal NextPlanExpenditure) {
Connection c = getConn();
Statement stmt = null;
try {
stmt = c.createStatement();
String sql = "UPDATE zh_management SET " +
"current_output_value = '" + currentOutPutValueThisSum + "'" +
", next_plan_receipt = '" + nextPlanReceiptSum + "'" +
", last_plan_return = '" + NextPlanReceipt + "'" +
", last_plan_expenditure = '" + NextPlanExpenditure + "'" +
" WHERE management_id = '" + managementId + "'";
stmt.executeUpdate(sql);
c.commit();
stmt.close();
c.close();
} catch (Exception e) {
e.printStackTrace();
}
}
// 台账表:更新‘本月实际支出’、‘备注’字段
public static void updateManagementBySubPayMent(String managementId, BigDecimal currentOutPutValueThisSum,
String infoCurrent, BigDecimal NextPlanReceipt, BigDecimal NextPlanExpenditure) {
Connection c = getConn();
Statement stmt = null;
try {
stmt = c.createStatement();
String sql = "UPDATE zh_management SET " +
"current_expenditure = '" + currentOutPutValueThisSum + "'" +
", info_current = '" + infoCurrent + "'" +
", last_plan_return = '" + NextPlanReceipt + "'" +
", last_plan_expenditure = '" + NextPlanExpenditure + "'" +
" WHERE management_id = '" + managementId + "'";
stmt.executeUpdate(sql);
c.commit();
stmt.close();
c.close();
} catch (Exception e) {
e.printStackTrace();
}
}
// 台账表:更新‘下月预计支出’、'本月实际支出'字段
public static void updateManagementByExpendInfo(String managementId, BigDecimal nextPlanExpenditureSum,
BigDecimal currentOutPutValueThisSum, String infoCurrent,
String infoNext, BigDecimal NextPlanReceipt, BigDecimal NextPlanExpenditure) {
Connection c = getConn();
Statement stmt = null;
try {
stmt = c.createStatement();
String sql = "UPDATE zh_management SET " +
"next_plan_expenditure = '" + nextPlanExpenditureSum +
"',current_expenditure = '" + currentOutPutValueThisSum +
"',info_current = '" + infoCurrent +
"', info_next = '" + infoNext +
"', last_plan_return = '" + NextPlanReceipt +
"', last_plan_expenditure = '" + NextPlanExpenditure +
"' WHERE management_id = '" + managementId + "'";
stmt.executeUpdate(sql);
c.commit();
stmt.close();
c.close();
} catch (Exception e) {
e.printStackTrace();
}
}
// 台账表:更新‘下月预计支出’字段
public static void updateManagementByDisBursementPlan(String managementId, BigDecimal nextPlanExpenditureSum,
String infoNext, BigDecimal NextPlanReceipt, BigDecimal NextPlanExpenditure) {
Connection c = getConn();
Statement stmt = null;
try {
stmt = c.createStatement();
String sql = "UPDATE zh_management SET " +
"next_plan_expenditure = '" + nextPlanExpenditureSum +
"', info_next = '" + infoNext +
"', last_plan_return = '" + NextPlanReceipt +
"', last_plan_expenditure = '" + NextPlanExpenditure +
"' WHERE management_id = '" + managementId + "'";
stmt.executeUpdate(sql);
c.commit();
stmt.close();
c.close();
} catch (Exception e) {
e.printStackTrace();
}
}
// 新增台账记录
public static void insertManagement(ZH_Management zh_management) {
Connection c = getConn();
Statement stmt = null;
try {
stmt = c.createStatement();
String sql = "INSERT INTO zh_management(management_id,project_id,report_date,current_actual_receipt,current_output_value" +
",current_expenditure,last_plan_return,last_plan_expenditure,next_plan_receipt" +
",next_plan_expenditure,info_current,info_next,remark) VALUES(" +
"'" + UUID.randomUUID().toString() + "'," +
"'" + zh_management.getProject_id() + "'," +
"'" + zh_management.getReport_date() + "'," +
"'" + zh_management.getCurrent_actual_receipt() + "'," +
"'" + zh_management.getCurrent_output_value() + "'," +
"'" + zh_management.getCurrent_expenditure() + "'," +
"'" + zh_management.getLast_plan_return() + "'," +
"'" + zh_management.getLast_plan_expenditure() + "'," +
"'" + zh_management.getNext_plan_receipt() + "'," +
"'" + zh_management.getNext_plan_expenditure() + "'," +
"'" + zh_management.getInfo_current() + "'," +
"'" + zh_management.getInfo_next() + "'," +
"'" + zh_management.getRemark() + "')";
stmt.executeUpdate(sql);
c.commit();
stmt.close();
c.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static List<ZH_UpdateStatus> getUpdateCountNew() {
Connection c = getConn();
Statement stmt = null;
List<ZH_UpdateStatus> zh_updateStatuses = new ArrayList<>();
try {
stmt = c.createStatement();
String sql = "SELECT * FROM zh_update_status";
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
zh_updateStatuses.add(new ZH_UpdateStatus(rs.getString("status_id"), rs.getString("project_id"),
rs.getBigDecimal("month")));
}
rs.close();
stmt.close();
c.close();
return zh_updateStatuses;
} catch (Exception e) {
e.printStackTrace();
}
return zh_updateStatuses;
}
// 删除一条记录
public static void deleteIt(String statusId) {
Connection c = getConn();
Statement stmt = null;
try {
stmt = c.createStatement();
String sql = "DELETE from zh_update_status where status_id = '" + statusId + "'";
stmt.executeUpdate(sql);
c.commit();
stmt.close();
c.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
| 30,050 | 0.528815 | 0.528475 | 663 | 43.334843 | 32.82045 | 170 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.785822 | false | false | 1 |
68c95478a0c6954ceb2da84389900fa6640f1a11 | 987,842,527,455 | 81b3984cce8eab7e04a5b0b6bcef593bc0181e5a | /android/CarLife/app/src/main/java/com/facebook/drawee/p144a/p145a/C5380f.java | 49bc65c46a40adb76f61581a51a24e51844cbe57 | []
| no_license | ausdruck/Demo | https://github.com/ausdruck/Demo | 20ee124734d3a56b99b8a8e38466f2adc28024d6 | e11f8844f4852cec901ba784ce93fcbb4200edc6 | refs/heads/master | 2020-04-10T03:49:24.198000 | 2018-07-27T10:14:56 | 2018-07-27T10:14:56 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.facebook.drawee.p144a.p145a;
import android.content.res.Resources;
import com.facebook.common.internal.C5273m;
import com.facebook.common.p140h.C2921a;
import com.facebook.drawee.p266b.C5391a;
import com.facebook.imagepipeline.p149d.C2944p;
import com.facebook.imagepipeline.p152i.C5534b;
import com.facebook.imagepipeline.p271a.p272a.C5442a;
import com.facebook.p135b.p136a.C5247d;
import com.facebook.p138c.C2918d;
import java.util.concurrent.Executor;
/* compiled from: PipelineDraweeControllerFactory */
/* renamed from: com.facebook.drawee.a.a.f */
public class C5380f {
/* renamed from: a */
private Resources f21988a;
/* renamed from: b */
private C5391a f21989b;
/* renamed from: c */
private C5442a f21990c;
/* renamed from: d */
private Executor f21991d;
/* renamed from: e */
private C2944p<C5247d, C5534b> f21992e;
public C5380f(Resources resources, C5391a deferredReleaser, C5442a animatedDrawableFactory, Executor uiThreadExecutor, C2944p<C5247d, C5534b> memoryCache) {
this.f21988a = resources;
this.f21989b = deferredReleaser;
this.f21990c = animatedDrawableFactory;
this.f21991d = uiThreadExecutor;
this.f21992e = memoryCache;
}
/* renamed from: a */
public C2927c m18435a(C5273m<C2918d<C2921a<C5534b>>> dataSourceSupplier, String id, C5247d cacheKey, Object callerContext) {
return new C2927c(this.f21988a, this.f21989b, this.f21990c, this.f21991d, this.f21992e, dataSourceSupplier, id, cacheKey, callerContext);
}
}
| UTF-8 | Java | 1,559 | java | C5380f.java | Java | []
| null | []
| package com.facebook.drawee.p144a.p145a;
import android.content.res.Resources;
import com.facebook.common.internal.C5273m;
import com.facebook.common.p140h.C2921a;
import com.facebook.drawee.p266b.C5391a;
import com.facebook.imagepipeline.p149d.C2944p;
import com.facebook.imagepipeline.p152i.C5534b;
import com.facebook.imagepipeline.p271a.p272a.C5442a;
import com.facebook.p135b.p136a.C5247d;
import com.facebook.p138c.C2918d;
import java.util.concurrent.Executor;
/* compiled from: PipelineDraweeControllerFactory */
/* renamed from: com.facebook.drawee.a.a.f */
public class C5380f {
/* renamed from: a */
private Resources f21988a;
/* renamed from: b */
private C5391a f21989b;
/* renamed from: c */
private C5442a f21990c;
/* renamed from: d */
private Executor f21991d;
/* renamed from: e */
private C2944p<C5247d, C5534b> f21992e;
public C5380f(Resources resources, C5391a deferredReleaser, C5442a animatedDrawableFactory, Executor uiThreadExecutor, C2944p<C5247d, C5534b> memoryCache) {
this.f21988a = resources;
this.f21989b = deferredReleaser;
this.f21990c = animatedDrawableFactory;
this.f21991d = uiThreadExecutor;
this.f21992e = memoryCache;
}
/* renamed from: a */
public C2927c m18435a(C5273m<C2918d<C2921a<C5534b>>> dataSourceSupplier, String id, C5247d cacheKey, Object callerContext) {
return new C2927c(this.f21988a, this.f21989b, this.f21990c, this.f21991d, this.f21992e, dataSourceSupplier, id, cacheKey, callerContext);
}
}
| 1,559 | 0.737011 | 0.595253 | 40 | 37.974998 | 34.018734 | 160 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.975 | false | false | 1 |
c454d1bceb3ebb3b39b9bbd6e01652ce42d6a8e9 | 28,252,294,920,781 | d5f09c7b0e954cd20dd613af600afd91b039c48a | /sources/androidx/preference/UnPressableLinearLayout.java | fb3349cdc3b460c43b51937e6bff92f4b7c04f06 | []
| no_license | t0HiiBwn/CoolapkRelease | https://github.com/t0HiiBwn/CoolapkRelease | af5e00c701bf82c4e90b1033f5c5f9dc8526f4b3 | a6a2b03e32cde0e5163016e0078391271a8d33ab | refs/heads/main | 2022-07-29T23:28:35.867000 | 2021-03-26T11:41:18 | 2021-03-26T11:41:18 | 345,290,891 | 5 | 2 | null | null | null | null | null | null | null | null | null | null | null | null | null | package androidx.preference;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.LinearLayout;
public class UnPressableLinearLayout extends LinearLayout {
@Override // android.view.View, android.view.ViewGroup
protected void dispatchSetPressed(boolean z) {
}
public UnPressableLinearLayout(Context context) {
this(context, null);
}
public UnPressableLinearLayout(Context context, AttributeSet attributeSet) {
super(context, attributeSet);
}
}
| UTF-8 | Java | 527 | java | UnPressableLinearLayout.java | Java | []
| null | []
| package androidx.preference;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.LinearLayout;
public class UnPressableLinearLayout extends LinearLayout {
@Override // android.view.View, android.view.ViewGroup
protected void dispatchSetPressed(boolean z) {
}
public UnPressableLinearLayout(Context context) {
this(context, null);
}
public UnPressableLinearLayout(Context context, AttributeSet attributeSet) {
super(context, attributeSet);
}
}
| 527 | 0.751423 | 0.751423 | 19 | 26.736841 | 24.343683 | 80 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.526316 | false | false | 1 |
8fd4897ef56111999e0165ba34c8b688c0882f53 | 3,599,182,639,200 | 2ef61d7d8167fac486fa3e958ffdb4349e39f74f | /design/src/com/aganzo/design/zzl/bean/ConcreteHandler1.java | 1fa78ac8db9f9b3da5f49e1042f7396fc6bbe132 | []
| no_license | game4dream/java.me.rep | https://github.com/game4dream/java.me.rep | 064932fdcf702659b22f8029b70c80cbea088f26 | da379dd4b0e74abc30d706a4450ce82041f37c64 | refs/heads/master | 2021-09-09T00:30:07.435000 | 2015-01-14T13:58:08 | 2015-01-14T13:58:08 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**
*
*/
package com.aganzo.design.zzl.bean;
/**
* 具体审核人1
*
* @author chenming
*
*/
public class ConcreteHandler1 extends Handler {
@Override
public void handleRequest(int request) {
System.out.println("ConcreteHandler1.handleRequest(int request)");
if (request >= 0 && request < 10) {
System.out.println(" 处理请求 " + request);
} else if (successor != null) {
successor.handleRequest(request);
}
}
}
| UTF-8 | Java | 448 | java | ConcreteHandler1.java | Java | [
{
"context": "nzo.design.zzl.bean;\n\n/**\n * 具体审核人1\n * \n * @author chenming\n * \n */\n\npublic class ConcreteHandler1 extends Ha",
"end": 86,
"score": 0.9992043375968933,
"start": 78,
"tag": "USERNAME",
"value": "chenming"
}
]
| null | []
| /**
*
*/
package com.aganzo.design.zzl.bean;
/**
* 具体审核人1
*
* @author chenming
*
*/
public class ConcreteHandler1 extends Handler {
@Override
public void handleRequest(int request) {
System.out.println("ConcreteHandler1.handleRequest(int request)");
if (request >= 0 && request < 10) {
System.out.println(" 处理请求 " + request);
} else if (successor != null) {
successor.handleRequest(request);
}
}
}
| 448 | 0.651163 | 0.637209 | 25 | 16.200001 | 19.303886 | 68 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.88 | false | false | 1 |
bddfafc664ebd772a8f17d9f679c1725b84694f1 | 13,091,060,382,566 | 539c6f876354a7c294dc33049958a4f000494c7b | /src/main/java/leetcode/leet1545.java | ec1e867c97c9ad9fadc4a98b9601e6e39a298fff | []
| no_license | ZLBer/DaliyOfProgramme | https://github.com/ZLBer/DaliyOfProgramme | 3392dd9a0ba4d749da6291123892e73f7b5cb981 | 738dec918d659e98c74be2c177dc5b259e05b9b9 | refs/heads/master | 2022-10-19T03:09:14.066000 | 2021-01-03T11:48:16 | 2021-01-03T11:48:16 | 164,304,274 | 1 | 0 | null | false | 2022-09-01T23:01:21 | 2019-01-06T12:20:06 | 2021-07-27T10:15:20 | 2022-09-01T23:01:18 | 1,253 | 0 | 0 | 9 | Java | false | false | package leetcode;
public class leet1545 {
public char findKthBit(int n, int k) {
if(n==1) return '0';
int mid=1<<(n-1);
if(k<mid){
return findKthBit(n-1,k);
}else if(k==mid){
return '1';
}else {
k=k-mid;
k=mid-k;
return findKthBit(n-1,k)=='0'?'1':'0';
}
}
}
| UTF-8 | Java | 293 | java | leet1545.java | Java | []
| null | []
| package leetcode;
public class leet1545 {
public char findKthBit(int n, int k) {
if(n==1) return '0';
int mid=1<<(n-1);
if(k<mid){
return findKthBit(n-1,k);
}else if(k==mid){
return '1';
}else {
k=k-mid;
k=mid-k;
return findKthBit(n-1,k)=='0'?'1':'0';
}
}
}
| 293 | 0.546075 | 0.498294 | 17 | 16.235294 | 12.445313 | 42 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.647059 | false | false | 1 |
442c598049ef78fce6823972310b927fdc233417 | 13,872,744,409,357 | 69d9e765abd364a447c49de6b0c765089d4e2423 | /OOP/DefiningClasses/src/info/Display.java | 1bbf3ce09ca75fe91fb640c1410775d0a1efece9 | []
| no_license | quoioln/trainning | https://github.com/quoioln/trainning | 2bc1dc0e17c493ea2ed96de0ba9073f5185e0be6 | b2c4cc517f060aeae9b5a6789a08fb1bd75d62ee | refs/heads/master | 2021-01-19T06:12:47.505000 | 2017-05-18T08:40:10 | 2017-05-18T08:40:10 | 60,591,320 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package info;
public class Display {
// size of dispaly
private float size;
// number of color display
private int numColor;
/**
* Contructor
*/
public Display() {
size = 0;
numColor = 0;
}
/**
* contructor include 2 param:
* @param size
* @param numColor
*/
public Display(final float size, final int numColor) {
this.size = size;
this.numColor = numColor;
}
/**
* @return the size
*/
public final float getSize() {
return size;
}
/**
* @param size the size to set
*/
public final void setSize(float size) {
this.size = size;
}
/**
* @return the numColor
*/
public final int getNumColor() {
return numColor;
}
/**
* @param numColor the numColor to set
*/
public final void setNumColor(int numColor) {
this.numColor = numColor;
}
public final String toString() {
StringBuilder result = new StringBuilder();
result.append("Infomation of display:\n");
result.append("\tSize: " + size + "\n");
result.append("\tNumber of color: " + numColor);
return result.toString();
}
} | UTF-8 | Java | 1,056 | java | Display.java | Java | []
| null | []
| package info;
public class Display {
// size of dispaly
private float size;
// number of color display
private int numColor;
/**
* Contructor
*/
public Display() {
size = 0;
numColor = 0;
}
/**
* contructor include 2 param:
* @param size
* @param numColor
*/
public Display(final float size, final int numColor) {
this.size = size;
this.numColor = numColor;
}
/**
* @return the size
*/
public final float getSize() {
return size;
}
/**
* @param size the size to set
*/
public final void setSize(float size) {
this.size = size;
}
/**
* @return the numColor
*/
public final int getNumColor() {
return numColor;
}
/**
* @param numColor the numColor to set
*/
public final void setNumColor(int numColor) {
this.numColor = numColor;
}
public final String toString() {
StringBuilder result = new StringBuilder();
result.append("Infomation of display:\n");
result.append("\tSize: " + size + "\n");
result.append("\tNumber of color: " + numColor);
return result.toString();
}
} | 1,056 | 0.637311 | 0.63447 | 59 | 16.915255 | 15.077526 | 55 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.440678 | false | false | 1 |
50ccdabb05023254b8314e3c83e63902028fa969 | 15,874,199,184,312 | cfaf2d559c6ba73b67c16ce29290a36624c8a71d | /src/main/java/com/blueferdi/concurrent/railway/second/Station.java | 43cee4322988508d058fd7457182c6088cee0689 | []
| no_license | ferdiknight/railway | https://github.com/ferdiknight/railway | 8df60e34234e448a879d70278347dac9f8e3032b | ba08d8e75a7c60422e50a4754fcd97b3b4ffb2c5 | refs/heads/master | 2021-01-10T19:30:41.139000 | 2014-02-28T09:36:06 | 2014-02-28T09:36:06 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.blueferdi.concurrent.railway.second;
import java.util.concurrent.BlockingQueue;
/**
*
* @author tongyin.ty
*/
public class Station<E> {
private final BlockingQueue<E> railway;
public Station(BlockingQueue<E> railway){
this.railway = railway;
}
public E exit(){
return railway.poll();
}
public void enter(E e){
railway.offer(e);
}
}
| UTF-8 | Java | 592 | java | Station.java | Java | [
{
"context": ".util.concurrent.BlockingQueue;\n\n/**\n *\n * @author tongyin.ty\n */\npublic class Station<E> {\n\n private final ",
"end": 308,
"score": 0.9606889486312866,
"start": 298,
"tag": "USERNAME",
"value": "tongyin.ty"
}
]
| null | []
| /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.blueferdi.concurrent.railway.second;
import java.util.concurrent.BlockingQueue;
/**
*
* @author tongyin.ty
*/
public class Station<E> {
private final BlockingQueue<E> railway;
public Station(BlockingQueue<E> railway){
this.railway = railway;
}
public E exit(){
return railway.poll();
}
public void enter(E e){
railway.offer(e);
}
}
| 592 | 0.663851 | 0.663851 | 31 | 18.096775 | 20.939783 | 79 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.290323 | false | false | 1 |
3a04e6247b159940ec21f80686f725a49ac60902 | 8,976,481,687,320 | 49498257f988cd511eaac9b92332df99ecb37116 | /src/hardware/controller/TVController.java | 1a712817a3db95e526d8b71be48a93beba9a2d73 | []
| no_license | zino1187/SpringMVC | https://github.com/zino1187/SpringMVC | 4acfc1502bbdccf45b89d748731fa1dfc505c414 | 995319433c0b0b9e19f2b6130a18291ee720fb72 | refs/heads/master | 2020-04-24T22:08:09.847000 | 2019-02-24T05:59:05 | 2019-02-24T05:59:05 | 172,302,049 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package hardware.controller;
import org.springframework.web.bind.annotation.RequestMapping;
public class TVController {
@RequestMapping("/tv")
public String execute() {
System.out.println("TV 요청을 처리할께요");
//tv 수리에 대한 결과 보여주기!!
return "tv/result";
}
}
| UHC | Java | 308 | java | TVController.java | Java | []
| null | []
| package hardware.controller;
import org.springframework.web.bind.annotation.RequestMapping;
public class TVController {
@RequestMapping("/tv")
public String execute() {
System.out.println("TV 요청을 처리할께요");
//tv 수리에 대한 결과 보여주기!!
return "tv/result";
}
}
| 308 | 0.707407 | 0.707407 | 13 | 19.384615 | 17.683275 | 62 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.076923 | false | false | 1 |
521f0a0d1724901f86e9a49553ac6a049f927846 | 23,450,521,465,312 | 9e95c1e6412b11491c62a0b77e392d400d5f427b | /src/main/java/com/everis/bcn/controller/BookingController.java | 8e58a9d382801d2207e5b05c029361f4bdb914d7 | [
"Apache-2.0"
]
| permissive | jmichaels1/Scummb4r_v2 | https://github.com/jmichaels1/Scummb4r_v2 | 03350adf67ed5cfabf0acb96d491b55d8d6b5768 | 6c4dfac3b148ab02e55dcc77aecbe20e842bb09c | refs/heads/master | 2020-04-14T10:21:24.774000 | 2019-01-15T00:18:02 | 2019-01-15T00:18:02 | 163,784,776 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.everis.bcn.controller;
import java.util.ArrayList;
import java.util.stream.Collectors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.servlet.ModelAndView;
import com.everis.bcn.model.DaoByDto;
import com.everis.bcn.dto.BookingDto;
import com.everis.bcn.model.ReserveValidate;
import com.everis.bcn.serviceImp.IResturantBusinessImp;
/**
*
* @author J Michael
*
*/
@Controller("/booking")
public class BookingController {
@Autowired private IResturantBusinessImp iResturantBusinessImp;
@Autowired private ReserveValidate reserveValidate;
@Autowired private DaoByDto daoByDto;
/**
* Método Constructor
*/
public BookingController() {
reserveValidate = new ReserveValidate();
}
/**
* ModelAndView booking
* @return
*/
@RequestMapping(value="booking", method=RequestMethod.GET)
public ModelAndView booking() {
return new ModelAndView("booking", "command", new BookingDto());
}
/**
* ModelAndView infRegBooking or booking
* Depends on registration validation
* @param dto
* @param result
* @param session
* @return
*/
@RequestMapping(value="booking", method=RequestMethod.POST)
public ModelAndView form(@ModelAttribute("command") BookingDto dto, BindingResult result, SessionStatus session){
ModelAndView mv = new ModelAndView();
reserveValidate.validate(dto, result);
if (!result.hasErrors()) {
mv.setViewName("infReserve");
mv.addObject("message", iResturantBusinessImp.manageReserve(dto));
} else {
mv.setViewName("booking");
mv.addObject("command", new BookingDto());
}
return mv;
}
/**
*
* @return
*/
@ModelAttribute("aListRestaurant")
public ArrayList<String> getRestaurantIdList(){
return (ArrayList<String>) iResturantBusinessImp.getRestaurants().stream()
.map(restaurant->restaurant.getName()).collect(Collectors.toList());
}
/**
*
* @return
*/
@ModelAttribute("aListTurn")
public ArrayList<Integer> getTurnList(){
return (ArrayList<Integer>) iResturantBusinessImp.getTurns().stream()
.map(turn->turn.getTurnId()).collect(Collectors.toList());
}
}
| ISO-8859-2 | Java | 2,597 | java | BookingController.java | Java | [
{
"context": "Imp.IResturantBusinessImp;\r\n\r\n/**\r\n * \r\n * @author J Michael\r\n *\r\n */\r\n@Controller(\"/booking\")\r\npublic class Boo",
"end": 795,
"score": 0.9972599148750305,
"start": 786,
"tag": "NAME",
"value": "J Michael"
}
]
| null | []
| package com.everis.bcn.controller;
import java.util.ArrayList;
import java.util.stream.Collectors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.servlet.ModelAndView;
import com.everis.bcn.model.DaoByDto;
import com.everis.bcn.dto.BookingDto;
import com.everis.bcn.model.ReserveValidate;
import com.everis.bcn.serviceImp.IResturantBusinessImp;
/**
*
* @author <NAME>
*
*/
@Controller("/booking")
public class BookingController {
@Autowired private IResturantBusinessImp iResturantBusinessImp;
@Autowired private ReserveValidate reserveValidate;
@Autowired private DaoByDto daoByDto;
/**
* Método Constructor
*/
public BookingController() {
reserveValidate = new ReserveValidate();
}
/**
* ModelAndView booking
* @return
*/
@RequestMapping(value="booking", method=RequestMethod.GET)
public ModelAndView booking() {
return new ModelAndView("booking", "command", new BookingDto());
}
/**
* ModelAndView infRegBooking or booking
* Depends on registration validation
* @param dto
* @param result
* @param session
* @return
*/
@RequestMapping(value="booking", method=RequestMethod.POST)
public ModelAndView form(@ModelAttribute("command") BookingDto dto, BindingResult result, SessionStatus session){
ModelAndView mv = new ModelAndView();
reserveValidate.validate(dto, result);
if (!result.hasErrors()) {
mv.setViewName("infReserve");
mv.addObject("message", iResturantBusinessImp.manageReserve(dto));
} else {
mv.setViewName("booking");
mv.addObject("command", new BookingDto());
}
return mv;
}
/**
*
* @return
*/
@ModelAttribute("aListRestaurant")
public ArrayList<String> getRestaurantIdList(){
return (ArrayList<String>) iResturantBusinessImp.getRestaurants().stream()
.map(restaurant->restaurant.getName()).collect(Collectors.toList());
}
/**
*
* @return
*/
@ModelAttribute("aListTurn")
public ArrayList<Integer> getTurnList(){
return (ArrayList<Integer>) iResturantBusinessImp.getTurns().stream()
.map(turn->turn.getTurnId()).collect(Collectors.toList());
}
}
| 2,594 | 0.719954 | 0.719954 | 94 | 25.617022 | 25.123993 | 117 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.393617 | false | false | 1 |
570986fc1502324bf6db1569f2ff85ea6665dd44 | 5,274,219,883,973 | c2d9bdf76424afdb8b9cb333d4285f93ef03531f | /src/Registration/RegisterTeachers.java | 1af24fd5c184473f08d3887c38eae503c51580b0 | []
| no_license | samotashiwen/ShoolManagementSystem | https://github.com/samotashiwen/ShoolManagementSystem | 61e21d563dcdbf1f82d99a36ddc6c2dfdad5736a | fa6bb01df7e48e6a6f577053191045af895bf2d1 | refs/heads/master | 2020-12-03T06:24:48.377000 | 2020-01-11T01:47:29 | 2020-01-11T01:47:29 | 231,229,546 | 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 Registration;
import MainApp.Utility;
import dbconnect.DB_OPS;
import java.sql.ResultSet;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import javax.swing.DefaultListModel;
import javax.swing.JOptionPane;
/**
*
* @author sogobanjo
*/
public class RegisterTeachers extends javax.swing.JDialog {
/**
* Creates new form RegisterTeachers
*/
DefaultListModel listModel = new DefaultListModel();
DefaultListModel listModel2 = new DefaultListModel();
DateFormat df = new SimpleDateFormat("dd-MM-yyyy");
public RegisterTeachers(java.awt.Frame parent, boolean modal) {
super(parent, modal);
initComponents();
SimpleDateFormat thedate;
comboYearObtained.removeAllItems();
comboYearObtained.addItem("Select a Year");
for (int i = 1930; i <= LocalDate.now().getYear(); i++)
{
comboYearObtained.addItem("" + i);
}
DB_OPS ops = new DB_OPS();
ops.createConnection();
// MARITAL STATUS DROP DOWN
String stmt ="select name from marital_status";
ResultSet Rset = ops.sel_data(stmt);
comboMaritalStatus.removeAllItems();
comboMaritalStatus.addItem("Select a Marital Status");
fill_list(comboMaritalStatus,Rset);
// SEX DROP DOWN
stmt ="select name from sex";
Rset = ops.sel_data(stmt);
comboSex.removeAllItems();
comboSex.addItem("Select a Gender");
fill_list(comboSex,Rset);
// RELIGION DROP DOWN
stmt ="select name from religion";
Rset = ops.sel_data(stmt);
comboReligion.removeAllItems();
comboReligion.addItem("Select a Religion");
fill_list(comboReligion,Rset);
// STATE OF ORIGIN DROP DOWN
stmt ="select name from state";
Rset = ops.sel_data(stmt);
comboStateOfOrigin.removeAllItems();
comboStateOfOrigin.addItem("Select a State");
fill_list(comboStateOfOrigin,Rset);
// COUNTRY DROP DOWN
stmt ="select name from country";
Rset = ops.sel_data(stmt);
comboNationality.removeAllItems();
comboNationality.addItem("Select a Country");
fill_list(comboNationality,Rset);
// TEACHERS POSITION DROP DOWN
stmt ="select name from teachers_position";
Rset = ops.sel_data(stmt);
comboPosition.removeAllItems();
comboPosition.addItem("Select a Position");
fill_list(comboPosition,Rset);
// SPECIAL AILMENT DROP DOWN
stmt ="select name from special_ailment";
Rset = ops.sel_data(stmt);
comboSpecialAilment.removeAllItems();
comboSpecialAilment.addItem("Select Ailment");
fill_list(comboSpecialAilment,Rset);
// Tribal Group DROP DOWN
stmt ="select name from tribal_group";
Rset = ops.sel_data(stmt);
comboTribalGroup.removeAllItems();
comboTribalGroup.addItem("Select a Tribal Group");
fill_list(comboTribalGroup,Rset);
// Language DROP DOWN
stmt ="select name from language";
Rset = ops.sel_data(stmt);
comboLanguage.removeAllItems();
comboLanguage.addItem("Select a Language");
fill_list(comboLanguage,Rset);
// Level of Education DROP DOWN
stmt ="select name from level_of_education";
Rset = ops.sel_data(stmt);
comboLevelOfEducation.removeAllItems();
comboLevelOfEducation.addItem("Select Level of education");
fill_list(comboLevelOfEducation,Rset);
// Discipline DROP DOWN
stmt ="select name from discipline";
Rset = ops.sel_data(stmt);
comboDiscipline.removeAllItems();
comboDiscipline.addItem("Select Discipline");
fill_list(comboDiscipline,Rset);
// Grade Obtained DROP DOWN
stmt ="select name from grade_obtained";
Rset = ops.sel_data(stmt);
comboGrade.removeAllItems();
comboGrade.addItem("Select Grade");
fill_list(comboGrade,Rset);
// School Attended DROP DOWN
stmt ="select name from school_attended";
Rset = ops.sel_data(stmt);
comboSchoolAttended.removeAllItems();
comboSchoolAttended.addItem("Select School Attended");
fill_list(comboSchoolAttended,Rset);
listDisplayEducation.setModel(listModel);
ops.close_conn();
}
private void fill_list(javax.swing.JComboBox JBox, ResultSet Rset)
{
try
{
while (Rset.next())
{
JBox.addItem(Rset.getString(1));
}
}
catch(Exception ex)
{
}
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
txtFirstName = new javax.swing.JTextField();
jLabel2 = new javax.swing.JLabel();
txtMiddleName = new javax.swing.JTextField();
jLabel3 = new javax.swing.JLabel();
txtLastName = new javax.swing.JTextField();
jLabel4 = new javax.swing.JLabel();
comboMaritalStatus = new javax.swing.JComboBox<>();
jLabel5 = new javax.swing.JLabel();
comboTribalGroup = new javax.swing.JComboBox<>();
jLabel6 = new javax.swing.JLabel();
comboLanguage = new javax.swing.JComboBox<>();
jLabel9 = new javax.swing.JLabel();
comboSpecialAilment = new javax.swing.JComboBox<>();
jLabel10 = new javax.swing.JLabel();
comboPosition = new javax.swing.JComboBox<>();
jLabel11 = new javax.swing.JLabel();
date_joined = new org.jdesktop.swingx.JXDatePicker();
jLabel12 = new javax.swing.JLabel();
comboReligion = new javax.swing.JComboBox<>();
buttonRegisterTeacher = new javax.swing.JButton();
jLabel13 = new javax.swing.JLabel();
comboSex = new javax.swing.JComboBox<>();
jLabel15 = new javax.swing.JLabel();
txtAddress = new javax.swing.JTextField();
jLabel16 = new javax.swing.JLabel();
jXDatePicker1 = new org.jdesktop.swingx.JXDatePicker();
jLabel17 = new javax.swing.JLabel();
jLabel18 = new javax.swing.JLabel();
comboStateOfOrigin = new javax.swing.JComboBox<>();
txtPhoneNumber = new javax.swing.JTextField();
jLabel19 = new javax.swing.JLabel();
comboNationality = new javax.swing.JComboBox<>();
jLabel20 = new javax.swing.JLabel();
jLabel21 = new javax.swing.JLabel();
txtStaffID = new javax.swing.JTextField();
jPanel2 = new javax.swing.JPanel();
comboLevelOfEducation = new javax.swing.JComboBox<>();
jLabel7 = new javax.swing.JLabel();
jLabel8 = new javax.swing.JLabel();
comboDiscipline = new javax.swing.JComboBox<>();
jLabel14 = new javax.swing.JLabel();
jScrollPane1 = new javax.swing.JScrollPane();
listDisplayEducation = new javax.swing.JList<>();
jLabel22 = new javax.swing.JLabel();
comboGrade = new javax.swing.JComboBox<>();
CGPA = new javax.swing.JLabel();
jFormattedTextField1 = new javax.swing.JFormattedTextField();
jLabel23 = new javax.swing.JLabel();
jFormattedTextField2 = new javax.swing.JFormattedTextField();
jButton1 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
jLabel31 = new javax.swing.JLabel();
comboSchoolAttended = new javax.swing.JComboBox<>();
comboYearObtained = new javax.swing.JComboBox<>();
jPanel3 = new javax.swing.JPanel();
jLabel24 = new javax.swing.JLabel();
jLabel25 = new javax.swing.JLabel();
jLabel26 = new javax.swing.JLabel();
jScrollPane2 = new javax.swing.JScrollPane();
listDisplayWorkExperience = new javax.swing.JList<>();
jLabel27 = new javax.swing.JLabel();
CGPA1 = new javax.swing.JLabel();
jButton3 = new javax.swing.JButton();
jButton4 = new javax.swing.JButton();
txtPlaceOfWork = new javax.swing.JTextField();
txtPositionAtWork = new javax.swing.JTextField();
jXDatePicker2 = new org.jdesktop.swingx.JXDatePicker();
jXDatePicker3 = new org.jdesktop.swingx.JXDatePicker();
comboReason = new javax.swing.JComboBox<>();
jLabel29 = new javax.swing.JLabel();
jLabel30 = new javax.swing.JLabel();
radioNo = new javax.swing.JRadioButton();
radioYes = new javax.swing.JRadioButton();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
jLabel1.setText("First Name");
txtFirstName.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtFirstNameActionPerformed(evt);
}
});
jLabel2.setText("Middle Name");
jLabel3.setText("Last Name");
jLabel4.setText("Marital Status");
comboMaritalStatus.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jLabel5.setText("Tribal Group");
comboTribalGroup.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
comboTribalGroup.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
comboTribalGroupActionPerformed(evt);
}
});
jLabel6.setText("Language");
comboLanguage.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jLabel9.setText("Special Ailment");
comboSpecialAilment.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jLabel10.setText("Position");
comboPosition.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jLabel11.setText("Date Joined");
jLabel12.setText("Religion");
comboReligion.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
buttonRegisterTeacher.setText("Register Teacher");
buttonRegisterTeacher.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
buttonRegisterTeacherActionPerformed(evt);
}
});
jLabel13.setText("Sex");
comboSex.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jLabel15.setText("Address");
jLabel16.setText("Date of Birth");
jXDatePicker1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jXDatePicker1ActionPerformed(evt);
}
});
jLabel17.setText("Phone No.");
jLabel18.setText("State of Origin");
comboStateOfOrigin.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jLabel19.setText("Nationality");
comboNationality.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
comboNationality.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
comboNationalityActionPerformed(evt);
}
});
jLabel20.setText("Disability");
jLabel21.setText("Staff ID");
jPanel2.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0), 2));
comboLevelOfEducation.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jLabel7.setText(" Level of Education");
jLabel8.setText("Discipline");
comboDiscipline.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jLabel14.setText("Year Obtained");
jScrollPane1.setViewportView(listDisplayEducation);
jLabel22.setText("Grade Obtained");
comboGrade.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
CGPA.setText("CGPA");
jFormattedTextField1.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.NumberFormatter(new java.text.DecimalFormat("#0.00"))));
jLabel23.setText("Out of");
jButton1.setText("Remove");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jButton2.setText("Add");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
jLabel31.setText("School Attended");
comboSchoolAttended.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
comboYearObtained.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGap(33, 33, 33)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jLabel7, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel8)
.addComponent(jLabel14)
.addComponent(jLabel22)
.addComponent(CGPA)
.addComponent(jLabel31, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGap(26, 26, 26)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jButton2)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGap(1, 1, 1)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(comboDiscipline, javax.swing.GroupLayout.PREFERRED_SIZE, 161, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(comboSchoolAttended, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(comboLevelOfEducation, 0, 163, Short.MAX_VALUE))))
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(comboYearObtained, javax.swing.GroupLayout.Alignment.LEADING, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(comboGrade, javax.swing.GroupLayout.Alignment.LEADING, 0, 161, Short.MAX_VALUE)))
.addGap(26, 26, 26)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 287, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel2Layout.createSequentialGroup()
.addComponent(jFormattedTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 49, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jLabel23)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jFormattedTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, 59, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(126, 126, 126)
.addComponent(jButton1)))
.addContainerGap(45, Short.MAX_VALUE))
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGap(20, 20, 20)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel31, javax.swing.GroupLayout.PREFERRED_SIZE, 19, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(comboSchoolAttended, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(comboLevelOfEducation, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel7, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(comboDiscipline, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel8, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel14)
.addComponent(comboYearObtained, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(comboGrade, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel22)))
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 109, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(CGPA)
.addComponent(jFormattedTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel23)
.addComponent(jFormattedTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton1))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 18, Short.MAX_VALUE)
.addComponent(jButton2)
.addContainerGap())
);
jPanel3.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0), 2));
jLabel24.setText(" Level of Education");
jLabel25.setText("Position");
jLabel26.setText("Start Date");
jScrollPane2.setViewportView(listDisplayWorkExperience);
jLabel27.setText("End Date");
CGPA1.setText("Reason For Leaving");
jButton3.setText("Remove");
jButton3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton3ActionPerformed(evt);
}
});
jButton4.setText("Add");
jButton4.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton4ActionPerformed(evt);
}
});
comboReason.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Select a Reason", "Resigned", "Retired", "Retrenched", "Sacked", "Company Shut Down", "Others" }));
javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
jPanel3.setLayout(jPanel3Layout);
jPanel3Layout.setHorizontalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addGap(33, 33, 33)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel24)
.addComponent(jLabel27)
.addComponent(CGPA1)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(jLabel25, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel26, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
.addGap(26, 26, 26)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jButton4)
.addComponent(jXDatePicker3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(txtPlaceOfWork)
.addComponent(txtPositionAtWork)
.addComponent(jXDatePicker2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(comboReason, 0, 161, Short.MAX_VALUE))
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addGap(39, 39, 39)
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 287, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel3Layout.createSequentialGroup()
.addGap(147, 147, 147)
.addComponent(jButton3)))
.addContainerGap(52, Short.MAX_VALUE))
);
jPanel3Layout.setVerticalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addGap(37, 37, 37)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel24, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txtPlaceOfWork, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel25, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txtPositionAtWork, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel26)
.addComponent(jXDatePicker2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(13, 13, 13)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel27)
.addComponent(jXDatePicker3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(CGPA1)
.addComponent(comboReason, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 9, Short.MAX_VALUE)
.addComponent(jButton4))
.addGroup(jPanel3Layout.createSequentialGroup()
.addGap(32, 32, 32)
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 109, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jButton3)
.addGap(0, 0, Short.MAX_VALUE)))
.addContainerGap())
);
jLabel29.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
jLabel29.setText("Work Experience");
jLabel30.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
jLabel30.setText("Education");
radioNo.setText("No");
radioNo.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
radioNoActionPerformed(evt);
}
});
radioYes.setText("Yes");
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jLabel21)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(txtStaffID, javax.swing.GroupLayout.PREFERRED_SIZE, 75, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 62, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(txtFirstName, javax.swing.GroupLayout.PREFERRED_SIZE, 118, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(12, 12, 12)
.addComponent(jLabel2))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 82, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(comboMaritalStatus, javax.swing.GroupLayout.PREFERRED_SIZE, 132, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel5)))
.addGap(54, 54, 54)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(txtMiddleName, javax.swing.GroupLayout.PREFERRED_SIZE, 129, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 58, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(comboTribalGroup, javax.swing.GroupLayout.PREFERRED_SIZE, 143, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 58, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(comboLanguage, javax.swing.GroupLayout.PREFERRED_SIZE, 164, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txtLastName, javax.swing.GroupLayout.PREFERRED_SIZE, 128, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel29, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(0, 0, Short.MAX_VALUE)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(comboSex, javax.swing.GroupLayout.PREFERRED_SIZE, 163, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(5, 5, 5)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel17)
.addComponent(jLabel12, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel18)
.addComponent(jLabel16))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(comboNationality, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(comboStateOfOrigin, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(comboReligion, javax.swing.GroupLayout.PREFERRED_SIZE, 159, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txtPhoneNumber)
.addComponent(jXDatePicker1, javax.swing.GroupLayout.PREFERRED_SIZE, 162, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jLabel15)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel13)
.addComponent(txtAddress, javax.swing.GroupLayout.PREFERRED_SIZE, 216, javax.swing.GroupLayout.PREFERRED_SIZE)))))
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jLabel11, javax.swing.GroupLayout.PREFERRED_SIZE, 58, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(date_joined, javax.swing.GroupLayout.PREFERRED_SIZE, 163, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel19)
.addComponent(jLabel10, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(comboPosition, javax.swing.GroupLayout.PREFERRED_SIZE, 163, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel9)
.addComponent(jLabel20))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(comboSpecialAilment, javax.swing.GroupLayout.PREFERRED_SIZE, 163, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(radioNo)
.addGap(18, 18, 18)
.addComponent(radioYes)))))
.addContainerGap())))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel30, javax.swing.GroupLayout.PREFERRED_SIZE, 89, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(437, 437, 437)
.addComponent(buttonRegisterTeacher, javax.swing.GroupLayout.PREFERRED_SIZE, 133, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(jLabel3)
.addComponent(txtLastName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel13)
.addComponent(comboSex, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txtMiddleName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txtFirstName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel21, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(txtStaffID, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(comboLanguage, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel6)
.addComponent(comboTribalGroup, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(14, 14, 14))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(comboMaritalStatus, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel4))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)))
.addComponent(jLabel30, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(txtAddress, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel15))
.addGap(15, 15, 15)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel17)
.addComponent(txtPhoneNumber, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel12, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(comboReligion, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel18)
.addComponent(comboStateOfOrigin, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel16)
.addComponent(jXDatePicker1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel19)
.addComponent(comboNationality, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(comboPosition, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel10, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(date_joined, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel11, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(comboSpecialAilment, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel9, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(22, 22, 22)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel20)
.addComponent(radioNo)
.addComponent(radioYes))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(13, 13, 13)
.addComponent(jLabel29, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(33, 33, 33)))
.addComponent(buttonRegisterTeacher, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(28, 28, 28))
);
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(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void txtFirstNameActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtFirstNameActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_txtFirstNameActionPerformed
private void buttonRegisterTeacherActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonRegisterTeacherActionPerformed
// TODO add your handling code here:
// DB_OPS dbops = new DB_OPS();
//
// dbops.createConnection();
// String stmt = "insert into register_teacher (first_name, middle_name,last_name,marital_status, staff_id, active) values ('" + txtFirstName.getText()
// + "','" + txtMiddleName.getText() + "','" + txtLastName.getText() + "','" + comboMaritalStatus.getSelectedItem() + "','" + txtStaffID.getText() + "','" + "Y" + "')";
// dbops.in_data(stmt);
//
//
// if(dbops.error_msg.trim().length()==0)
// JOptionPane.showMessageDialog(this, " Teacher's Registration Details Successfuly Inserted");
// else
// JOptionPane.showMessageDialog(this, "Error Occured While Inserting Teacher's Registration Details " + " : " + dbops.error_msg);
if (txtStaffID.getText().trim().length() == 0)
{
JOptionPane.showMessageDialog(this, "Please Enter The Staff ID " );
return;
}
save_data();
}//GEN-LAST:event_buttonRegisterTeacherActionPerformed
private void comboNationalityActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_comboNationalityActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_comboNationalityActionPerformed
private void jXDatePicker1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jXDatePicker1ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jXDatePicker1ActionPerformed
private void save_education()
{
// if (!(jRadioCA.isSelected() || jRadioExam.isSelected()))
// {
// JOptionPane.showMessageDialog(this, " Please Select Continuous Assessment OR Exam");
// return;
// }
String stmt;
String value, present_status, absent_status;
// stmt = "insert into ca_exam (exam_date, academic_session_id, academic_term_id, class_id, student_id,subject_id, score, exam_type) values ";
stmt = "insert into teachers_education (staff_id, school_attended, level_of_education, discipline,year_obtained,grade_obtained,cgpa) values ";
value="";
for (int i = 0; i < listDisplayEducation.getModel().getSize(); i++)
{
// value += " ( '" + txtStaffID.getText() + "', " +
// " (select id from school_attended where name = '" + comboSchoolAttended.getSelectedItem() + "'), " +
// " (select id from level_of_education where name = '" + comboLevelOfEducation.getSelectedItem() + "'), " +
// " (select id from discipline where name = '" + comboDiscipline.getSelectedItem() + "'), '" + jXDatePicker2.getDate() + "'," +
// " (select id from grade_obtained where name = '" + comboGrade.getSelectedItem() + "'), '" +
// Double.parseDouble(jFormattedTextField1.getText()) + "/" + Double.parseDouble(jFormattedTextField2.getText()) + "'" +
// " ),";
String test = listDisplayEducation.getModel().getElementAt(i);
String[] itemsarray = test.split("!");
System.out.println(test.split("!")[0]);
// value += " ( '" + txtStaffID.getText() + "', " +
// " (select id from school_attended where name = '" + listDisplayEducation.getModel().getElementAt(i).split(":")[0] + "'), " +
// " (select id from level_of_education where name = '" + listDisplayEducation.getModel().getElementAt(i).split(":")[1] + "'), " +
// " (select id from discipline where name = '" + listDisplayEducation.getModel().getElementAt(i).split(":")[2] + "'), '" +
// listDisplayEducation.getModel().getElementAt(i).split(":")[3] + "'," +
// " (select id from grade_obtained where name = '" + listDisplayEducation.getModel().getElementAt(i).split(":")[4] + "'), '" +
// listDisplayEducation.getModel().getElementAt(i).split(":")[5] + "'" +
// " ),";
value += " ( '" + txtStaffID.getText() + "', " +
" (select id from school_attended where name = '" + itemsarray[0] + "'), " +
" (select id from level_of_education where name = '" + itemsarray[1] + "'), " +
" (select id from discipline where name = '" + itemsarray[2] + "'), '" +
itemsarray[3] + "'," +
" (select id from grade_obtained where name = '" + itemsarray[4] + "'), '" +
itemsarray[5] + "'" +
" ),";
}
stmt += value.trim().substring(0, value.trim().length()- 1);
// stmt += value;
System.out.println(stmt);
DB_OPS dbops = new DB_OPS();
dbops.createConnection();
// System.out.println(stmt); // Print the SQL statement for debugging purpose
dbops.in_data(stmt);
if(dbops.error_msg.trim().length()==0)
{
// JOptionPane.showMessageDialog(this, " Score Successfuly Recorded");
// Utility myutil = new Utility();
// String itemtoadd = comboLevelOfEducation.getSelectedItem() + " " + comboDiscipline.getSelectedItem() + " " + comboGrade.getSelectedItem() ;
// myutil.fill_list(itemtoadd, listDisplayEducation );
}
else
JOptionPane.showMessageDialog(this, "Error Occured While Recording Score " + dbops.error_msg);
dbops.close_conn();
}
private void save_work_experience()
{
// if (!(jRadioCA.isSelected() || jRadioExam.isSelected()))
// {
// JOptionPane.showMessageDialog(this, " Please Select Continuous Assessment OR Exam");
// return;
// }
String stmt;
String value, present_status, absent_status;
// stmt = "insert into ca_exam (exam_date, academic_session_id, academic_term_id, class_id, student_id,subject_id, score, exam_type) values ";
stmt = "insert into teachers_work_experience (staff_id, place_of_work, position, start_date ,end_date, leaving_reason ) values ";
value="";
for (int i = 0; i < listDisplayWorkExperience.getModel().getSize(); i++)
{
// value += " ( '" + txtStaffID.getText() + "', " +
// " (select id from school_attended where name = '" + comboSchoolAttended.getSelectedItem() + "'), " +
// " (select id from level_of_education where name = '" + comboLevelOfEducation.getSelectedItem() + "'), " +
// " (select id from discipline where name = '" + comboDiscipline.getSelectedItem() + "'), '" + jXDatePicker2.getDate() + "'," +
// " (select id from grade_obtained where name = '" + comboGrade.getSelectedItem() + "'), '" +
// Double.parseDouble(jFormattedTextField1.getText()) + "/" + Double.parseDouble(jFormattedTextField2.getText()) + "'" +
// " ),";
String test = listDisplayWorkExperience.getModel().getElementAt(i);
String[] itemsarray = test.split("!");
System.out.println(test.split("!")[0]);
// value += " ( '" + txtStaffID.getText() + "', " +
// " (select id from school_attended where name = '" + listDisplayEducation.getModel().getElementAt(i).split(":")[0] + "'), " +
// " (select id from level_of_education where name = '" + listDisplayEducation.getModel().getElementAt(i).split(":")[1] + "'), " +
// " (select id from discipline where name = '" + listDisplayEducation.getModel().getElementAt(i).split(":")[2] + "'), '" +
// listDisplayEducation.getModel().getElementAt(i).split(":")[3] + "'," +
// " (select id from grade_obtained where name = '" + listDisplayEducation.getModel().getElementAt(i).split(":")[4] + "'), '" +
// listDisplayEducation.getModel().getElementAt(i).split(":")[5] + "'" +
// " ),";
value += " ( '" + txtStaffID.getText() + "', '" +
itemsarray[0] + "', '" +
itemsarray[1] + "', '" +
itemsarray[2] + "', '" +
itemsarray[3] + "', '" +
itemsarray[4] + "' " +
" ),";
}
stmt += value.trim().substring(0, value.trim().length()- 1);
// stmt += value;
System.out.println(stmt);
DB_OPS dbops = new DB_OPS();
dbops.createConnection();
// System.out.println(stmt); // Print the SQL statement for debugging purpose
dbops.in_data(stmt);
if(dbops.error_msg.trim().length()==0)
{
// JOptionPane.showMessageDialog(this, " Score Successfuly Recorded");
// Utility myutil = new Utility();
// String itemtoadd = comboLevelOfEducation.getSelectedItem() + " " + comboDiscipline.getSelectedItem() + " " + comboGrade.getSelectedItem() ;
// myutil.fill_list(itemtoadd, listDisplayEducation );
}
else
JOptionPane.showMessageDialog(this, "Error Occured While Recording Score " + dbops.error_msg);
dbops.close_conn();
}
private void save_teachers_details()
{
DB_OPS dbops = new DB_OPS();
dbops.createConnection();
String stmt = "insert into register_teacher (first_name, middle_name,last_name,marital_status, staff_id,sex, tribal_group, active) values ('" + txtFirstName.getText()
+ "','" + txtMiddleName.getText() + "','" + txtLastName.getText() + "','" + comboMaritalStatus.getSelectedItem() + "','" + txtStaffID.getText() + "','"
+ comboSex.getSelectedItem() + "','" + comboTribalGroup.getSelectedItem() + "','" + "Y" + "')";
dbops.in_data(stmt);
if(dbops.error_msg.trim().length()==0)
JOptionPane.showMessageDialog(this, " Teacher's Registration Details Successfuly Inserted");
else
JOptionPane.showMessageDialog(this, "Error Occured While Inserting Teacher's Registration Details " + " : " + dbops.error_msg);
}
private void save_data()
{
// save_education();
save_work_experience();
}
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
// TODO add your handling code here:
// save_data();
// Utility myutil = new Utility();
String itemtoadd = comboSchoolAttended.getSelectedItem() + "!" + comboLevelOfEducation.getSelectedItem() + "!"
+ comboDiscipline.getSelectedItem() + "!" + comboYearObtained.getSelectedItem() + "!" + comboGrade.getSelectedItem() + "!"
+ Double.parseDouble(jFormattedTextField1.getText()) + "/" + Double.parseDouble(jFormattedTextField2.getText()) ;
listModel.addElement(itemtoadd);
listDisplayEducation.setModel(listModel);
// myutil.fill_list(itemtoadd, listDisplayEducation , listModel);
}//GEN-LAST:event_jButton2ActionPerformed
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
// TODO add your handling code here:
// System.out.println(listDisplayEducation.getSelectedIndex());
listModel.remove(listDisplayEducation.getSelectedIndex());
}//GEN-LAST:event_jButton1ActionPerformed
private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
// TODO add your handling code here:
System.out.println("Start Date : " +df.format(jXDatePicker2.getDate()));
System.out.println("End Date : " +df.format(jXDatePicker3.getDate()));
String itemtoadd = txtPlaceOfWork.getText().trim() + "!" + txtPositionAtWork.getText().trim()+ "!"
+ df.format(jXDatePicker2.getDate()) + "!" + df.format(jXDatePicker3.getDate()) + "!" + comboReason.getSelectedItem() ;
listModel2.addElement(itemtoadd);
listDisplayWorkExperience.setModel(listModel2);
}//GEN-LAST:event_jButton4ActionPerformed
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
// TODO add your handling code here:
listModel2.remove(listDisplayWorkExperience.getSelectedIndex());
}//GEN-LAST:event_jButton3ActionPerformed
private void radioNoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_radioNoActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_radioNoActionPerformed
private void comboTribalGroupActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_comboTribalGroupActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_comboTribalGroupActionPerformed
/**
* @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(RegisterTeachers.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(RegisterTeachers.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(RegisterTeachers.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(RegisterTeachers.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the dialog */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
RegisterTeachers dialog = new RegisterTeachers(new javax.swing.JFrame(), true);
dialog.addWindowListener(new java.awt.event.WindowAdapter() {
@Override
public void windowClosing(java.awt.event.WindowEvent e) {
System.exit(0);
}
});
dialog.setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JLabel CGPA;
private javax.swing.JLabel CGPA1;
private javax.swing.JButton buttonRegisterTeacher;
private javax.swing.JComboBox<String> comboDiscipline;
private javax.swing.JComboBox<String> comboGrade;
private javax.swing.JComboBox<String> comboLanguage;
private javax.swing.JComboBox<String> comboLevelOfEducation;
private javax.swing.JComboBox<String> comboMaritalStatus;
private javax.swing.JComboBox<String> comboNationality;
private javax.swing.JComboBox<String> comboPosition;
private javax.swing.JComboBox<String> comboReason;
private javax.swing.JComboBox<String> comboReligion;
private javax.swing.JComboBox<String> comboSchoolAttended;
private javax.swing.JComboBox<String> comboSex;
private javax.swing.JComboBox<String> comboSpecialAilment;
private javax.swing.JComboBox<String> comboStateOfOrigin;
private javax.swing.JComboBox<String> comboTribalGroup;
private javax.swing.JComboBox<String> comboYearObtained;
private org.jdesktop.swingx.JXDatePicker date_joined;
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton3;
private javax.swing.JButton jButton4;
private javax.swing.JFormattedTextField jFormattedTextField1;
private javax.swing.JFormattedTextField jFormattedTextField2;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel10;
private javax.swing.JLabel jLabel11;
private javax.swing.JLabel jLabel12;
private javax.swing.JLabel jLabel13;
private javax.swing.JLabel jLabel14;
private javax.swing.JLabel jLabel15;
private javax.swing.JLabel jLabel16;
private javax.swing.JLabel jLabel17;
private javax.swing.JLabel jLabel18;
private javax.swing.JLabel jLabel19;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel20;
private javax.swing.JLabel jLabel21;
private javax.swing.JLabel jLabel22;
private javax.swing.JLabel jLabel23;
private javax.swing.JLabel jLabel24;
private javax.swing.JLabel jLabel25;
private javax.swing.JLabel jLabel26;
private javax.swing.JLabel jLabel27;
private javax.swing.JLabel jLabel29;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel30;
private javax.swing.JLabel jLabel31;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel8;
private javax.swing.JLabel jLabel9;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanel3;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private org.jdesktop.swingx.JXDatePicker jXDatePicker1;
private org.jdesktop.swingx.JXDatePicker jXDatePicker2;
private org.jdesktop.swingx.JXDatePicker jXDatePicker3;
private javax.swing.JList<String> listDisplayEducation;
private javax.swing.JList<String> listDisplayWorkExperience;
private javax.swing.JRadioButton radioNo;
private javax.swing.JRadioButton radioYes;
private javax.swing.JTextField txtAddress;
private javax.swing.JTextField txtFirstName;
private javax.swing.JTextField txtLastName;
private javax.swing.JTextField txtMiddleName;
private javax.swing.JTextField txtPhoneNumber;
private javax.swing.JTextField txtPlaceOfWork;
private javax.swing.JTextField txtPositionAtWork;
private javax.swing.JTextField txtStaffID;
// End of variables declaration//GEN-END:variables
}
| UTF-8 | Java | 69,794 | java | RegisterTeachers.java | Java | [
{
"context": "import javax.swing.JOptionPane;\n\n/**\n *\n * @author sogobanjo\n */\npublic class RegisterTeachers extends javax.s",
"end": 473,
"score": 0.9983536601066589,
"start": 464,
"tag": "USERNAME",
"value": "sogobanjo"
}
]
| 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 Registration;
import MainApp.Utility;
import dbconnect.DB_OPS;
import java.sql.ResultSet;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import javax.swing.DefaultListModel;
import javax.swing.JOptionPane;
/**
*
* @author sogobanjo
*/
public class RegisterTeachers extends javax.swing.JDialog {
/**
* Creates new form RegisterTeachers
*/
DefaultListModel listModel = new DefaultListModel();
DefaultListModel listModel2 = new DefaultListModel();
DateFormat df = new SimpleDateFormat("dd-MM-yyyy");
public RegisterTeachers(java.awt.Frame parent, boolean modal) {
super(parent, modal);
initComponents();
SimpleDateFormat thedate;
comboYearObtained.removeAllItems();
comboYearObtained.addItem("Select a Year");
for (int i = 1930; i <= LocalDate.now().getYear(); i++)
{
comboYearObtained.addItem("" + i);
}
DB_OPS ops = new DB_OPS();
ops.createConnection();
// MARITAL STATUS DROP DOWN
String stmt ="select name from marital_status";
ResultSet Rset = ops.sel_data(stmt);
comboMaritalStatus.removeAllItems();
comboMaritalStatus.addItem("Select a Marital Status");
fill_list(comboMaritalStatus,Rset);
// SEX DROP DOWN
stmt ="select name from sex";
Rset = ops.sel_data(stmt);
comboSex.removeAllItems();
comboSex.addItem("Select a Gender");
fill_list(comboSex,Rset);
// RELIGION DROP DOWN
stmt ="select name from religion";
Rset = ops.sel_data(stmt);
comboReligion.removeAllItems();
comboReligion.addItem("Select a Religion");
fill_list(comboReligion,Rset);
// STATE OF ORIGIN DROP DOWN
stmt ="select name from state";
Rset = ops.sel_data(stmt);
comboStateOfOrigin.removeAllItems();
comboStateOfOrigin.addItem("Select a State");
fill_list(comboStateOfOrigin,Rset);
// COUNTRY DROP DOWN
stmt ="select name from country";
Rset = ops.sel_data(stmt);
comboNationality.removeAllItems();
comboNationality.addItem("Select a Country");
fill_list(comboNationality,Rset);
// TEACHERS POSITION DROP DOWN
stmt ="select name from teachers_position";
Rset = ops.sel_data(stmt);
comboPosition.removeAllItems();
comboPosition.addItem("Select a Position");
fill_list(comboPosition,Rset);
// SPECIAL AILMENT DROP DOWN
stmt ="select name from special_ailment";
Rset = ops.sel_data(stmt);
comboSpecialAilment.removeAllItems();
comboSpecialAilment.addItem("Select Ailment");
fill_list(comboSpecialAilment,Rset);
// Tribal Group DROP DOWN
stmt ="select name from tribal_group";
Rset = ops.sel_data(stmt);
comboTribalGroup.removeAllItems();
comboTribalGroup.addItem("Select a Tribal Group");
fill_list(comboTribalGroup,Rset);
// Language DROP DOWN
stmt ="select name from language";
Rset = ops.sel_data(stmt);
comboLanguage.removeAllItems();
comboLanguage.addItem("Select a Language");
fill_list(comboLanguage,Rset);
// Level of Education DROP DOWN
stmt ="select name from level_of_education";
Rset = ops.sel_data(stmt);
comboLevelOfEducation.removeAllItems();
comboLevelOfEducation.addItem("Select Level of education");
fill_list(comboLevelOfEducation,Rset);
// Discipline DROP DOWN
stmt ="select name from discipline";
Rset = ops.sel_data(stmt);
comboDiscipline.removeAllItems();
comboDiscipline.addItem("Select Discipline");
fill_list(comboDiscipline,Rset);
// Grade Obtained DROP DOWN
stmt ="select name from grade_obtained";
Rset = ops.sel_data(stmt);
comboGrade.removeAllItems();
comboGrade.addItem("Select Grade");
fill_list(comboGrade,Rset);
// School Attended DROP DOWN
stmt ="select name from school_attended";
Rset = ops.sel_data(stmt);
comboSchoolAttended.removeAllItems();
comboSchoolAttended.addItem("Select School Attended");
fill_list(comboSchoolAttended,Rset);
listDisplayEducation.setModel(listModel);
ops.close_conn();
}
private void fill_list(javax.swing.JComboBox JBox, ResultSet Rset)
{
try
{
while (Rset.next())
{
JBox.addItem(Rset.getString(1));
}
}
catch(Exception ex)
{
}
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
txtFirstName = new javax.swing.JTextField();
jLabel2 = new javax.swing.JLabel();
txtMiddleName = new javax.swing.JTextField();
jLabel3 = new javax.swing.JLabel();
txtLastName = new javax.swing.JTextField();
jLabel4 = new javax.swing.JLabel();
comboMaritalStatus = new javax.swing.JComboBox<>();
jLabel5 = new javax.swing.JLabel();
comboTribalGroup = new javax.swing.JComboBox<>();
jLabel6 = new javax.swing.JLabel();
comboLanguage = new javax.swing.JComboBox<>();
jLabel9 = new javax.swing.JLabel();
comboSpecialAilment = new javax.swing.JComboBox<>();
jLabel10 = new javax.swing.JLabel();
comboPosition = new javax.swing.JComboBox<>();
jLabel11 = new javax.swing.JLabel();
date_joined = new org.jdesktop.swingx.JXDatePicker();
jLabel12 = new javax.swing.JLabel();
comboReligion = new javax.swing.JComboBox<>();
buttonRegisterTeacher = new javax.swing.JButton();
jLabel13 = new javax.swing.JLabel();
comboSex = new javax.swing.JComboBox<>();
jLabel15 = new javax.swing.JLabel();
txtAddress = new javax.swing.JTextField();
jLabel16 = new javax.swing.JLabel();
jXDatePicker1 = new org.jdesktop.swingx.JXDatePicker();
jLabel17 = new javax.swing.JLabel();
jLabel18 = new javax.swing.JLabel();
comboStateOfOrigin = new javax.swing.JComboBox<>();
txtPhoneNumber = new javax.swing.JTextField();
jLabel19 = new javax.swing.JLabel();
comboNationality = new javax.swing.JComboBox<>();
jLabel20 = new javax.swing.JLabel();
jLabel21 = new javax.swing.JLabel();
txtStaffID = new javax.swing.JTextField();
jPanel2 = new javax.swing.JPanel();
comboLevelOfEducation = new javax.swing.JComboBox<>();
jLabel7 = new javax.swing.JLabel();
jLabel8 = new javax.swing.JLabel();
comboDiscipline = new javax.swing.JComboBox<>();
jLabel14 = new javax.swing.JLabel();
jScrollPane1 = new javax.swing.JScrollPane();
listDisplayEducation = new javax.swing.JList<>();
jLabel22 = new javax.swing.JLabel();
comboGrade = new javax.swing.JComboBox<>();
CGPA = new javax.swing.JLabel();
jFormattedTextField1 = new javax.swing.JFormattedTextField();
jLabel23 = new javax.swing.JLabel();
jFormattedTextField2 = new javax.swing.JFormattedTextField();
jButton1 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
jLabel31 = new javax.swing.JLabel();
comboSchoolAttended = new javax.swing.JComboBox<>();
comboYearObtained = new javax.swing.JComboBox<>();
jPanel3 = new javax.swing.JPanel();
jLabel24 = new javax.swing.JLabel();
jLabel25 = new javax.swing.JLabel();
jLabel26 = new javax.swing.JLabel();
jScrollPane2 = new javax.swing.JScrollPane();
listDisplayWorkExperience = new javax.swing.JList<>();
jLabel27 = new javax.swing.JLabel();
CGPA1 = new javax.swing.JLabel();
jButton3 = new javax.swing.JButton();
jButton4 = new javax.swing.JButton();
txtPlaceOfWork = new javax.swing.JTextField();
txtPositionAtWork = new javax.swing.JTextField();
jXDatePicker2 = new org.jdesktop.swingx.JXDatePicker();
jXDatePicker3 = new org.jdesktop.swingx.JXDatePicker();
comboReason = new javax.swing.JComboBox<>();
jLabel29 = new javax.swing.JLabel();
jLabel30 = new javax.swing.JLabel();
radioNo = new javax.swing.JRadioButton();
radioYes = new javax.swing.JRadioButton();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
jLabel1.setText("First Name");
txtFirstName.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtFirstNameActionPerformed(evt);
}
});
jLabel2.setText("Middle Name");
jLabel3.setText("Last Name");
jLabel4.setText("Marital Status");
comboMaritalStatus.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jLabel5.setText("Tribal Group");
comboTribalGroup.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
comboTribalGroup.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
comboTribalGroupActionPerformed(evt);
}
});
jLabel6.setText("Language");
comboLanguage.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jLabel9.setText("Special Ailment");
comboSpecialAilment.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jLabel10.setText("Position");
comboPosition.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jLabel11.setText("Date Joined");
jLabel12.setText("Religion");
comboReligion.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
buttonRegisterTeacher.setText("Register Teacher");
buttonRegisterTeacher.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
buttonRegisterTeacherActionPerformed(evt);
}
});
jLabel13.setText("Sex");
comboSex.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jLabel15.setText("Address");
jLabel16.setText("Date of Birth");
jXDatePicker1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jXDatePicker1ActionPerformed(evt);
}
});
jLabel17.setText("Phone No.");
jLabel18.setText("State of Origin");
comboStateOfOrigin.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jLabel19.setText("Nationality");
comboNationality.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
comboNationality.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
comboNationalityActionPerformed(evt);
}
});
jLabel20.setText("Disability");
jLabel21.setText("Staff ID");
jPanel2.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0), 2));
comboLevelOfEducation.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jLabel7.setText(" Level of Education");
jLabel8.setText("Discipline");
comboDiscipline.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jLabel14.setText("Year Obtained");
jScrollPane1.setViewportView(listDisplayEducation);
jLabel22.setText("Grade Obtained");
comboGrade.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
CGPA.setText("CGPA");
jFormattedTextField1.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.NumberFormatter(new java.text.DecimalFormat("#0.00"))));
jLabel23.setText("Out of");
jButton1.setText("Remove");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jButton2.setText("Add");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
jLabel31.setText("School Attended");
comboSchoolAttended.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
comboYearObtained.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGap(33, 33, 33)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jLabel7, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel8)
.addComponent(jLabel14)
.addComponent(jLabel22)
.addComponent(CGPA)
.addComponent(jLabel31, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGap(26, 26, 26)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jButton2)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGap(1, 1, 1)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(comboDiscipline, javax.swing.GroupLayout.PREFERRED_SIZE, 161, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(comboSchoolAttended, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(comboLevelOfEducation, 0, 163, Short.MAX_VALUE))))
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(comboYearObtained, javax.swing.GroupLayout.Alignment.LEADING, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(comboGrade, javax.swing.GroupLayout.Alignment.LEADING, 0, 161, Short.MAX_VALUE)))
.addGap(26, 26, 26)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 287, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel2Layout.createSequentialGroup()
.addComponent(jFormattedTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 49, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jLabel23)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jFormattedTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, 59, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(126, 126, 126)
.addComponent(jButton1)))
.addContainerGap(45, Short.MAX_VALUE))
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGap(20, 20, 20)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel31, javax.swing.GroupLayout.PREFERRED_SIZE, 19, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(comboSchoolAttended, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(comboLevelOfEducation, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel7, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(comboDiscipline, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel8, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel14)
.addComponent(comboYearObtained, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(comboGrade, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel22)))
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 109, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(CGPA)
.addComponent(jFormattedTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel23)
.addComponent(jFormattedTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton1))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 18, Short.MAX_VALUE)
.addComponent(jButton2)
.addContainerGap())
);
jPanel3.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0), 2));
jLabel24.setText(" Level of Education");
jLabel25.setText("Position");
jLabel26.setText("Start Date");
jScrollPane2.setViewportView(listDisplayWorkExperience);
jLabel27.setText("End Date");
CGPA1.setText("Reason For Leaving");
jButton3.setText("Remove");
jButton3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton3ActionPerformed(evt);
}
});
jButton4.setText("Add");
jButton4.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton4ActionPerformed(evt);
}
});
comboReason.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Select a Reason", "Resigned", "Retired", "Retrenched", "Sacked", "Company Shut Down", "Others" }));
javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
jPanel3.setLayout(jPanel3Layout);
jPanel3Layout.setHorizontalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addGap(33, 33, 33)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel24)
.addComponent(jLabel27)
.addComponent(CGPA1)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(jLabel25, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel26, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
.addGap(26, 26, 26)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jButton4)
.addComponent(jXDatePicker3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(txtPlaceOfWork)
.addComponent(txtPositionAtWork)
.addComponent(jXDatePicker2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(comboReason, 0, 161, Short.MAX_VALUE))
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addGap(39, 39, 39)
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 287, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel3Layout.createSequentialGroup()
.addGap(147, 147, 147)
.addComponent(jButton3)))
.addContainerGap(52, Short.MAX_VALUE))
);
jPanel3Layout.setVerticalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addGap(37, 37, 37)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel24, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txtPlaceOfWork, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel25, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txtPositionAtWork, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel26)
.addComponent(jXDatePicker2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(13, 13, 13)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel27)
.addComponent(jXDatePicker3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(CGPA1)
.addComponent(comboReason, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 9, Short.MAX_VALUE)
.addComponent(jButton4))
.addGroup(jPanel3Layout.createSequentialGroup()
.addGap(32, 32, 32)
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 109, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jButton3)
.addGap(0, 0, Short.MAX_VALUE)))
.addContainerGap())
);
jLabel29.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
jLabel29.setText("Work Experience");
jLabel30.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
jLabel30.setText("Education");
radioNo.setText("No");
radioNo.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
radioNoActionPerformed(evt);
}
});
radioYes.setText("Yes");
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jLabel21)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(txtStaffID, javax.swing.GroupLayout.PREFERRED_SIZE, 75, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 62, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(txtFirstName, javax.swing.GroupLayout.PREFERRED_SIZE, 118, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(12, 12, 12)
.addComponent(jLabel2))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 82, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(comboMaritalStatus, javax.swing.GroupLayout.PREFERRED_SIZE, 132, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel5)))
.addGap(54, 54, 54)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(txtMiddleName, javax.swing.GroupLayout.PREFERRED_SIZE, 129, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 58, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(comboTribalGroup, javax.swing.GroupLayout.PREFERRED_SIZE, 143, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 58, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(comboLanguage, javax.swing.GroupLayout.PREFERRED_SIZE, 164, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txtLastName, javax.swing.GroupLayout.PREFERRED_SIZE, 128, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel29, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(0, 0, Short.MAX_VALUE)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(comboSex, javax.swing.GroupLayout.PREFERRED_SIZE, 163, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(5, 5, 5)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel17)
.addComponent(jLabel12, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel18)
.addComponent(jLabel16))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(comboNationality, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(comboStateOfOrigin, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(comboReligion, javax.swing.GroupLayout.PREFERRED_SIZE, 159, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txtPhoneNumber)
.addComponent(jXDatePicker1, javax.swing.GroupLayout.PREFERRED_SIZE, 162, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jLabel15)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel13)
.addComponent(txtAddress, javax.swing.GroupLayout.PREFERRED_SIZE, 216, javax.swing.GroupLayout.PREFERRED_SIZE)))))
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jLabel11, javax.swing.GroupLayout.PREFERRED_SIZE, 58, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(date_joined, javax.swing.GroupLayout.PREFERRED_SIZE, 163, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel19)
.addComponent(jLabel10, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(comboPosition, javax.swing.GroupLayout.PREFERRED_SIZE, 163, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel9)
.addComponent(jLabel20))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(comboSpecialAilment, javax.swing.GroupLayout.PREFERRED_SIZE, 163, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(radioNo)
.addGap(18, 18, 18)
.addComponent(radioYes)))))
.addContainerGap())))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel30, javax.swing.GroupLayout.PREFERRED_SIZE, 89, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(437, 437, 437)
.addComponent(buttonRegisterTeacher, javax.swing.GroupLayout.PREFERRED_SIZE, 133, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(jLabel3)
.addComponent(txtLastName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel13)
.addComponent(comboSex, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txtMiddleName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txtFirstName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel21, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(txtStaffID, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(comboLanguage, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel6)
.addComponent(comboTribalGroup, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(14, 14, 14))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(comboMaritalStatus, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel4))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)))
.addComponent(jLabel30, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(txtAddress, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel15))
.addGap(15, 15, 15)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel17)
.addComponent(txtPhoneNumber, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel12, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(comboReligion, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel18)
.addComponent(comboStateOfOrigin, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel16)
.addComponent(jXDatePicker1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel19)
.addComponent(comboNationality, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(comboPosition, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel10, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(date_joined, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel11, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(comboSpecialAilment, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel9, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(22, 22, 22)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel20)
.addComponent(radioNo)
.addComponent(radioYes))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(13, 13, 13)
.addComponent(jLabel29, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(33, 33, 33)))
.addComponent(buttonRegisterTeacher, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(28, 28, 28))
);
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(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void txtFirstNameActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtFirstNameActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_txtFirstNameActionPerformed
private void buttonRegisterTeacherActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonRegisterTeacherActionPerformed
// TODO add your handling code here:
// DB_OPS dbops = new DB_OPS();
//
// dbops.createConnection();
// String stmt = "insert into register_teacher (first_name, middle_name,last_name,marital_status, staff_id, active) values ('" + txtFirstName.getText()
// + "','" + txtMiddleName.getText() + "','" + txtLastName.getText() + "','" + comboMaritalStatus.getSelectedItem() + "','" + txtStaffID.getText() + "','" + "Y" + "')";
// dbops.in_data(stmt);
//
//
// if(dbops.error_msg.trim().length()==0)
// JOptionPane.showMessageDialog(this, " Teacher's Registration Details Successfuly Inserted");
// else
// JOptionPane.showMessageDialog(this, "Error Occured While Inserting Teacher's Registration Details " + " : " + dbops.error_msg);
if (txtStaffID.getText().trim().length() == 0)
{
JOptionPane.showMessageDialog(this, "Please Enter The Staff ID " );
return;
}
save_data();
}//GEN-LAST:event_buttonRegisterTeacherActionPerformed
private void comboNationalityActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_comboNationalityActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_comboNationalityActionPerformed
private void jXDatePicker1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jXDatePicker1ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jXDatePicker1ActionPerformed
private void save_education()
{
// if (!(jRadioCA.isSelected() || jRadioExam.isSelected()))
// {
// JOptionPane.showMessageDialog(this, " Please Select Continuous Assessment OR Exam");
// return;
// }
String stmt;
String value, present_status, absent_status;
// stmt = "insert into ca_exam (exam_date, academic_session_id, academic_term_id, class_id, student_id,subject_id, score, exam_type) values ";
stmt = "insert into teachers_education (staff_id, school_attended, level_of_education, discipline,year_obtained,grade_obtained,cgpa) values ";
value="";
for (int i = 0; i < listDisplayEducation.getModel().getSize(); i++)
{
// value += " ( '" + txtStaffID.getText() + "', " +
// " (select id from school_attended where name = '" + comboSchoolAttended.getSelectedItem() + "'), " +
// " (select id from level_of_education where name = '" + comboLevelOfEducation.getSelectedItem() + "'), " +
// " (select id from discipline where name = '" + comboDiscipline.getSelectedItem() + "'), '" + jXDatePicker2.getDate() + "'," +
// " (select id from grade_obtained where name = '" + comboGrade.getSelectedItem() + "'), '" +
// Double.parseDouble(jFormattedTextField1.getText()) + "/" + Double.parseDouble(jFormattedTextField2.getText()) + "'" +
// " ),";
String test = listDisplayEducation.getModel().getElementAt(i);
String[] itemsarray = test.split("!");
System.out.println(test.split("!")[0]);
// value += " ( '" + txtStaffID.getText() + "', " +
// " (select id from school_attended where name = '" + listDisplayEducation.getModel().getElementAt(i).split(":")[0] + "'), " +
// " (select id from level_of_education where name = '" + listDisplayEducation.getModel().getElementAt(i).split(":")[1] + "'), " +
// " (select id from discipline where name = '" + listDisplayEducation.getModel().getElementAt(i).split(":")[2] + "'), '" +
// listDisplayEducation.getModel().getElementAt(i).split(":")[3] + "'," +
// " (select id from grade_obtained where name = '" + listDisplayEducation.getModel().getElementAt(i).split(":")[4] + "'), '" +
// listDisplayEducation.getModel().getElementAt(i).split(":")[5] + "'" +
// " ),";
value += " ( '" + txtStaffID.getText() + "', " +
" (select id from school_attended where name = '" + itemsarray[0] + "'), " +
" (select id from level_of_education where name = '" + itemsarray[1] + "'), " +
" (select id from discipline where name = '" + itemsarray[2] + "'), '" +
itemsarray[3] + "'," +
" (select id from grade_obtained where name = '" + itemsarray[4] + "'), '" +
itemsarray[5] + "'" +
" ),";
}
stmt += value.trim().substring(0, value.trim().length()- 1);
// stmt += value;
System.out.println(stmt);
DB_OPS dbops = new DB_OPS();
dbops.createConnection();
// System.out.println(stmt); // Print the SQL statement for debugging purpose
dbops.in_data(stmt);
if(dbops.error_msg.trim().length()==0)
{
// JOptionPane.showMessageDialog(this, " Score Successfuly Recorded");
// Utility myutil = new Utility();
// String itemtoadd = comboLevelOfEducation.getSelectedItem() + " " + comboDiscipline.getSelectedItem() + " " + comboGrade.getSelectedItem() ;
// myutil.fill_list(itemtoadd, listDisplayEducation );
}
else
JOptionPane.showMessageDialog(this, "Error Occured While Recording Score " + dbops.error_msg);
dbops.close_conn();
}
private void save_work_experience()
{
// if (!(jRadioCA.isSelected() || jRadioExam.isSelected()))
// {
// JOptionPane.showMessageDialog(this, " Please Select Continuous Assessment OR Exam");
// return;
// }
String stmt;
String value, present_status, absent_status;
// stmt = "insert into ca_exam (exam_date, academic_session_id, academic_term_id, class_id, student_id,subject_id, score, exam_type) values ";
stmt = "insert into teachers_work_experience (staff_id, place_of_work, position, start_date ,end_date, leaving_reason ) values ";
value="";
for (int i = 0; i < listDisplayWorkExperience.getModel().getSize(); i++)
{
// value += " ( '" + txtStaffID.getText() + "', " +
// " (select id from school_attended where name = '" + comboSchoolAttended.getSelectedItem() + "'), " +
// " (select id from level_of_education where name = '" + comboLevelOfEducation.getSelectedItem() + "'), " +
// " (select id from discipline where name = '" + comboDiscipline.getSelectedItem() + "'), '" + jXDatePicker2.getDate() + "'," +
// " (select id from grade_obtained where name = '" + comboGrade.getSelectedItem() + "'), '" +
// Double.parseDouble(jFormattedTextField1.getText()) + "/" + Double.parseDouble(jFormattedTextField2.getText()) + "'" +
// " ),";
String test = listDisplayWorkExperience.getModel().getElementAt(i);
String[] itemsarray = test.split("!");
System.out.println(test.split("!")[0]);
// value += " ( '" + txtStaffID.getText() + "', " +
// " (select id from school_attended where name = '" + listDisplayEducation.getModel().getElementAt(i).split(":")[0] + "'), " +
// " (select id from level_of_education where name = '" + listDisplayEducation.getModel().getElementAt(i).split(":")[1] + "'), " +
// " (select id from discipline where name = '" + listDisplayEducation.getModel().getElementAt(i).split(":")[2] + "'), '" +
// listDisplayEducation.getModel().getElementAt(i).split(":")[3] + "'," +
// " (select id from grade_obtained where name = '" + listDisplayEducation.getModel().getElementAt(i).split(":")[4] + "'), '" +
// listDisplayEducation.getModel().getElementAt(i).split(":")[5] + "'" +
// " ),";
value += " ( '" + txtStaffID.getText() + "', '" +
itemsarray[0] + "', '" +
itemsarray[1] + "', '" +
itemsarray[2] + "', '" +
itemsarray[3] + "', '" +
itemsarray[4] + "' " +
" ),";
}
stmt += value.trim().substring(0, value.trim().length()- 1);
// stmt += value;
System.out.println(stmt);
DB_OPS dbops = new DB_OPS();
dbops.createConnection();
// System.out.println(stmt); // Print the SQL statement for debugging purpose
dbops.in_data(stmt);
if(dbops.error_msg.trim().length()==0)
{
// JOptionPane.showMessageDialog(this, " Score Successfuly Recorded");
// Utility myutil = new Utility();
// String itemtoadd = comboLevelOfEducation.getSelectedItem() + " " + comboDiscipline.getSelectedItem() + " " + comboGrade.getSelectedItem() ;
// myutil.fill_list(itemtoadd, listDisplayEducation );
}
else
JOptionPane.showMessageDialog(this, "Error Occured While Recording Score " + dbops.error_msg);
dbops.close_conn();
}
private void save_teachers_details()
{
DB_OPS dbops = new DB_OPS();
dbops.createConnection();
String stmt = "insert into register_teacher (first_name, middle_name,last_name,marital_status, staff_id,sex, tribal_group, active) values ('" + txtFirstName.getText()
+ "','" + txtMiddleName.getText() + "','" + txtLastName.getText() + "','" + comboMaritalStatus.getSelectedItem() + "','" + txtStaffID.getText() + "','"
+ comboSex.getSelectedItem() + "','" + comboTribalGroup.getSelectedItem() + "','" + "Y" + "')";
dbops.in_data(stmt);
if(dbops.error_msg.trim().length()==0)
JOptionPane.showMessageDialog(this, " Teacher's Registration Details Successfuly Inserted");
else
JOptionPane.showMessageDialog(this, "Error Occured While Inserting Teacher's Registration Details " + " : " + dbops.error_msg);
}
private void save_data()
{
// save_education();
save_work_experience();
}
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
// TODO add your handling code here:
// save_data();
// Utility myutil = new Utility();
String itemtoadd = comboSchoolAttended.getSelectedItem() + "!" + comboLevelOfEducation.getSelectedItem() + "!"
+ comboDiscipline.getSelectedItem() + "!" + comboYearObtained.getSelectedItem() + "!" + comboGrade.getSelectedItem() + "!"
+ Double.parseDouble(jFormattedTextField1.getText()) + "/" + Double.parseDouble(jFormattedTextField2.getText()) ;
listModel.addElement(itemtoadd);
listDisplayEducation.setModel(listModel);
// myutil.fill_list(itemtoadd, listDisplayEducation , listModel);
}//GEN-LAST:event_jButton2ActionPerformed
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
// TODO add your handling code here:
// System.out.println(listDisplayEducation.getSelectedIndex());
listModel.remove(listDisplayEducation.getSelectedIndex());
}//GEN-LAST:event_jButton1ActionPerformed
private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
// TODO add your handling code here:
System.out.println("Start Date : " +df.format(jXDatePicker2.getDate()));
System.out.println("End Date : " +df.format(jXDatePicker3.getDate()));
String itemtoadd = txtPlaceOfWork.getText().trim() + "!" + txtPositionAtWork.getText().trim()+ "!"
+ df.format(jXDatePicker2.getDate()) + "!" + df.format(jXDatePicker3.getDate()) + "!" + comboReason.getSelectedItem() ;
listModel2.addElement(itemtoadd);
listDisplayWorkExperience.setModel(listModel2);
}//GEN-LAST:event_jButton4ActionPerformed
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
// TODO add your handling code here:
listModel2.remove(listDisplayWorkExperience.getSelectedIndex());
}//GEN-LAST:event_jButton3ActionPerformed
private void radioNoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_radioNoActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_radioNoActionPerformed
private void comboTribalGroupActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_comboTribalGroupActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_comboTribalGroupActionPerformed
/**
* @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(RegisterTeachers.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(RegisterTeachers.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(RegisterTeachers.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(RegisterTeachers.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the dialog */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
RegisterTeachers dialog = new RegisterTeachers(new javax.swing.JFrame(), true);
dialog.addWindowListener(new java.awt.event.WindowAdapter() {
@Override
public void windowClosing(java.awt.event.WindowEvent e) {
System.exit(0);
}
});
dialog.setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JLabel CGPA;
private javax.swing.JLabel CGPA1;
private javax.swing.JButton buttonRegisterTeacher;
private javax.swing.JComboBox<String> comboDiscipline;
private javax.swing.JComboBox<String> comboGrade;
private javax.swing.JComboBox<String> comboLanguage;
private javax.swing.JComboBox<String> comboLevelOfEducation;
private javax.swing.JComboBox<String> comboMaritalStatus;
private javax.swing.JComboBox<String> comboNationality;
private javax.swing.JComboBox<String> comboPosition;
private javax.swing.JComboBox<String> comboReason;
private javax.swing.JComboBox<String> comboReligion;
private javax.swing.JComboBox<String> comboSchoolAttended;
private javax.swing.JComboBox<String> comboSex;
private javax.swing.JComboBox<String> comboSpecialAilment;
private javax.swing.JComboBox<String> comboStateOfOrigin;
private javax.swing.JComboBox<String> comboTribalGroup;
private javax.swing.JComboBox<String> comboYearObtained;
private org.jdesktop.swingx.JXDatePicker date_joined;
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton3;
private javax.swing.JButton jButton4;
private javax.swing.JFormattedTextField jFormattedTextField1;
private javax.swing.JFormattedTextField jFormattedTextField2;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel10;
private javax.swing.JLabel jLabel11;
private javax.swing.JLabel jLabel12;
private javax.swing.JLabel jLabel13;
private javax.swing.JLabel jLabel14;
private javax.swing.JLabel jLabel15;
private javax.swing.JLabel jLabel16;
private javax.swing.JLabel jLabel17;
private javax.swing.JLabel jLabel18;
private javax.swing.JLabel jLabel19;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel20;
private javax.swing.JLabel jLabel21;
private javax.swing.JLabel jLabel22;
private javax.swing.JLabel jLabel23;
private javax.swing.JLabel jLabel24;
private javax.swing.JLabel jLabel25;
private javax.swing.JLabel jLabel26;
private javax.swing.JLabel jLabel27;
private javax.swing.JLabel jLabel29;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel30;
private javax.swing.JLabel jLabel31;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel8;
private javax.swing.JLabel jLabel9;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanel3;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private org.jdesktop.swingx.JXDatePicker jXDatePicker1;
private org.jdesktop.swingx.JXDatePicker jXDatePicker2;
private org.jdesktop.swingx.JXDatePicker jXDatePicker3;
private javax.swing.JList<String> listDisplayEducation;
private javax.swing.JList<String> listDisplayWorkExperience;
private javax.swing.JRadioButton radioNo;
private javax.swing.JRadioButton radioYes;
private javax.swing.JTextField txtAddress;
private javax.swing.JTextField txtFirstName;
private javax.swing.JTextField txtLastName;
private javax.swing.JTextField txtMiddleName;
private javax.swing.JTextField txtPhoneNumber;
private javax.swing.JTextField txtPlaceOfWork;
private javax.swing.JTextField txtPositionAtWork;
private javax.swing.JTextField txtStaffID;
// End of variables declaration//GEN-END:variables
}
| 69,794 | 0.619222 | 0.605611 | 1,178 | 58.247879 | 46.664352 | 188 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.877759 | false | false | 1 |
f73ba72d777d40eb94894362ed200af562da1a33 | 12,953,621,402,105 | f137bee782df03bf599061e842de01bd4896dcaa | /src/com/test/lrucache/Node.java | e0a12e19aacf63f33c48a8c50dc212c34d6c7c3e | []
| no_license | ashigup14/codeExamples | https://github.com/ashigup14/codeExamples | f0b32bbe5912c375ee08dfa0cae9e2947e8b5f37 | 123dde49a9026cede505fabf6a7c2913f8265449 | refs/heads/master | 2021-11-25T06:10:11.871000 | 2021-11-24T05:50:51 | 2021-11-24T05:50:51 | 232,254,715 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.test.lrucache;
public class Node {
private int key;
private int val;
private Node prev;
private Node next;
public Node(int key, int val) {
this.key = key;
this.val = val;
}
public Node() {
}
public Node getPrev() {
return prev;
}
public void setPrev(Node prev) {
this.prev = prev;
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
public void setKey(int key) {
this.key = key;
}
public void setVal(int val) {
this.val = val;
}
public int getKey() {
return key;
}
public int getVal() {
return val;
}
}
| UTF-8 | Java | 623 | java | Node.java | Java | []
| null | []
| package com.test.lrucache;
public class Node {
private int key;
private int val;
private Node prev;
private Node next;
public Node(int key, int val) {
this.key = key;
this.val = val;
}
public Node() {
}
public Node getPrev() {
return prev;
}
public void setPrev(Node prev) {
this.prev = prev;
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
public void setKey(int key) {
this.key = key;
}
public void setVal(int val) {
this.val = val;
}
public int getKey() {
return key;
}
public int getVal() {
return val;
}
}
| 623 | 0.617977 | 0.617977 | 53 | 10.754717 | 10.85219 | 33 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.245283 | false | false | 1 |
e327930abc1ad24bdb11c63dd19c3942add68282 | 20,435,454,464,430 | ac56e673300a2b22c80b89630df85f7af99e69fb | /src/br/unirio/projetodswgae/actions/ActionCommon.java | 01e5754db001c0164ac27b73111191fdab75f88a | []
| no_license | amandaguiar/projeto-dsw-gae | https://github.com/amandaguiar/projeto-dsw-gae | d78be88132bcb4f2ca63bd555d20029c3c97f64b | fba231264ca076cb940ca4e314a7d598ca960710 | refs/heads/master | 2020-06-03T20:34:56.450000 | 2013-08-05T19:36:57 | 2013-08-05T19:36:57 | 32,414,986 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package br.unirio.projetodswgae.actions;
import br.unirio.projetodswgae.dao.DAOFactory;
import br.unirio.projetodswgae.model.Componente;
import br.unirio.simplemvc.actions.Action;
import br.unirio.simplemvc.actions.ActionException;
import br.unirio.simplemvc.actions.authentication.DisableUserVerification;
import br.unirio.simplemvc.actions.qualifiers.Ajax;
import br.unirio.simplemvc.json.JSONArray;
public class ActionCommon extends Action
{
/**
* Ação que lista os componentes de um sistema
*/
@DisableUserVerification
@Ajax
public String listaComponentes() throws ActionException
{
String sistema = getParameter("sistema");
Iterable<Componente> componentes = DAOFactory.getComponenteDAO().getComponentesSistema(sistema);
JSONArray result = new JSONArray();
if (componentes != null)
{
for (Componente componente : componentes)
result.add(componente.getNome());
}
else
{
result.add(sistema);
}
return ajaxSuccess(result);
}
}
| ISO-8859-1 | Java | 1,017 | java | ActionCommon.java | Java | []
| null | []
| package br.unirio.projetodswgae.actions;
import br.unirio.projetodswgae.dao.DAOFactory;
import br.unirio.projetodswgae.model.Componente;
import br.unirio.simplemvc.actions.Action;
import br.unirio.simplemvc.actions.ActionException;
import br.unirio.simplemvc.actions.authentication.DisableUserVerification;
import br.unirio.simplemvc.actions.qualifiers.Ajax;
import br.unirio.simplemvc.json.JSONArray;
public class ActionCommon extends Action
{
/**
* Ação que lista os componentes de um sistema
*/
@DisableUserVerification
@Ajax
public String listaComponentes() throws ActionException
{
String sistema = getParameter("sistema");
Iterable<Componente> componentes = DAOFactory.getComponenteDAO().getComponentesSistema(sistema);
JSONArray result = new JSONArray();
if (componentes != null)
{
for (Componente componente : componentes)
result.add(componente.getNome());
}
else
{
result.add(sistema);
}
return ajaxSuccess(result);
}
}
| 1,017 | 0.743842 | 0.743842 | 38 | 24.710526 | 24.558104 | 98 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.421053 | false | false | 1 |
f78fb164b500eb0e2b527d2c76c330ae747bf388 | 11,123,965,349,571 | 26b9f19411b923f8a8e1ba40ac0a5b8fde390dff | /src/main/java/io/mbab/sda/jvm/Controller.java | 6bae366fa0ffc38948fda004bb62735ad7e227d5 | []
| no_license | mbabul/sda-jvm | https://github.com/mbabul/sda-jvm | 33b5d518b80cb87acdb6f8cd92731a25c77e0f7c | cdaceaca9725354558281ca3573d0e9acfa18d55 | refs/heads/master | 2020-06-19T10:54:37.551000 | 2019-07-13T05:56:27 | 2019-07-13T05:56:27 | 196,683,894 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package io.mbab.sda.jvm;
import org.springframework.http.HttpEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.stream.IntStream;
@RestController
@RequestMapping("/")
class Controller {
private DataRepository repo;
public Controller() {
this.repo = DataRepository.getInstance();
}
@GetMapping
HttpEntity<String> root() {
return ResponseEntity.ok(
"Operations:<br/>" +
"<br/><button onClick=\"location.href='/list'\"><b>LIST_ALL<b></button><br/>" +
"<br/><button onClick=\"location.href='/generate?size=' + document.getElementById('size').value\"><b>GENERATE<b></button> " +
"<input type=\"number\" id=\"size\" value=\"0\" min=\"0\"><br/>" +
"<br/><button onClick=\"location.href='/delete_all'\"><b>DELETE_ALL<b></button><br/>" +
"<br/><button onClick=\"location.href='/size'\"><b>SIZE<b></button>"
);
}
@GetMapping("/list")
HttpEntity<List<DataModel>> getAll() {
return ResponseEntity.ok(repo.getAll());
}
@GetMapping("/list/{id}")
HttpEntity<DataModel> get(@PathVariable int id) {
return repo.get(id)
.map(ResponseEntity::ok)
.orElse(ResponseEntity.notFound().build());
}
@GetMapping("/generate")
HttpEntity<String> generate(@RequestParam int size) {
int actualSize = repo.getAll().size();
IntStream.range(0, size)
.mapToObj(e -> new DataModel((e + actualSize), "x"))
.forEach(e -> repo.save(e));
return ResponseEntity.ok("Generated " + size + " DataModel objects");
}
@GetMapping("/delete_all")
HttpEntity<String> deleteAll() {
int size = repo.getAll().size();
repo.deleteAll();
return ResponseEntity.ok("Deleted all DataModel objects: " + size);
}
@GetMapping("/size")
HttpEntity<String> size(){
return ResponseEntity.ok("Actual size: " + repo.getAll().size());
}
}
| UTF-8 | Java | 2,171 | java | Controller.java | Java | []
| null | []
| package io.mbab.sda.jvm;
import org.springframework.http.HttpEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.stream.IntStream;
@RestController
@RequestMapping("/")
class Controller {
private DataRepository repo;
public Controller() {
this.repo = DataRepository.getInstance();
}
@GetMapping
HttpEntity<String> root() {
return ResponseEntity.ok(
"Operations:<br/>" +
"<br/><button onClick=\"location.href='/list'\"><b>LIST_ALL<b></button><br/>" +
"<br/><button onClick=\"location.href='/generate?size=' + document.getElementById('size').value\"><b>GENERATE<b></button> " +
"<input type=\"number\" id=\"size\" value=\"0\" min=\"0\"><br/>" +
"<br/><button onClick=\"location.href='/delete_all'\"><b>DELETE_ALL<b></button><br/>" +
"<br/><button onClick=\"location.href='/size'\"><b>SIZE<b></button>"
);
}
@GetMapping("/list")
HttpEntity<List<DataModel>> getAll() {
return ResponseEntity.ok(repo.getAll());
}
@GetMapping("/list/{id}")
HttpEntity<DataModel> get(@PathVariable int id) {
return repo.get(id)
.map(ResponseEntity::ok)
.orElse(ResponseEntity.notFound().build());
}
@GetMapping("/generate")
HttpEntity<String> generate(@RequestParam int size) {
int actualSize = repo.getAll().size();
IntStream.range(0, size)
.mapToObj(e -> new DataModel((e + actualSize), "x"))
.forEach(e -> repo.save(e));
return ResponseEntity.ok("Generated " + size + " DataModel objects");
}
@GetMapping("/delete_all")
HttpEntity<String> deleteAll() {
int size = repo.getAll().size();
repo.deleteAll();
return ResponseEntity.ok("Deleted all DataModel objects: " + size);
}
@GetMapping("/size")
HttpEntity<String> size(){
return ResponseEntity.ok("Actual size: " + repo.getAll().size());
}
}
| 2,171 | 0.578535 | 0.577153 | 65 | 32.400002 | 31.800726 | 160 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.338462 | false | false | 1 |
7ae3eb7cb08c18c441f2bbfb1c0d56b2000bf58d | 18,296,560,719,915 | 84d8cb81ab7187f2a1ff1c7cd2211c3f1c17a536 | /src/app/src/main/java/it/unive/dais/cevid/datadroid/template/MainActivity.java | e63216a401d016cf6d0cbc10f2cdd8e98903501f | []
| no_license | unive-ingsw2017/docteam | https://github.com/unive-ingsw2017/docteam | 25e074a8ed5b676ffd25dc0339fb810249f7090b | 2c50e346d771863a913900ca4138ba18c69a501f | refs/heads/master | 2021-09-06T16:53:23.134000 | 2018-02-08T18:47:15 | 2018-02-08T18:47:15 | 110,126,118 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package it.unive.dais.cevid.datadroid.template;
import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.IntentSender;
import android.content.pm.PackageManager;
import android.location.Location;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.Snackbar;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageButton;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity
{
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void openMap (View view){
startActivity(new Intent("android.intent.action.MapsActivity"));
}
public void openList1 (View view){
startActivity(new Intent("android.intent.action.ListActivityDOC"));
}
public void openList2 (View view){
startActivity(new Intent("android.intent.action.ListActivityDOCG"));
}
/**
public void onStart()
{
super.onStart();
Log.d(tag, "Evento onStart()");
}
public void onRestart()
{
super.onRestart();
Log.d(tag, "Evento onRestart()");
}
public void onResume()
{
super.onResume();
Log.d(tag, "Evento onResume()");
}
public void onPause()
{
super.onPause();
Log.d(tag, "Evento onPause()");
}
public void onStop()
{
super.onStop();
Log.d(tag, "Evento onStop()");
}
public void onDestroy()
{
super.onDestroy();
Log.d(tag, "Evento onDestroy()");
}
*/
} | UTF-8 | Java | 2,047 | java | MainActivity.java | Java | []
| null | []
| package it.unive.dais.cevid.datadroid.template;
import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.IntentSender;
import android.content.pm.PackageManager;
import android.location.Location;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.Snackbar;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageButton;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity
{
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void openMap (View view){
startActivity(new Intent("android.intent.action.MapsActivity"));
}
public void openList1 (View view){
startActivity(new Intent("android.intent.action.ListActivityDOC"));
}
public void openList2 (View view){
startActivity(new Intent("android.intent.action.ListActivityDOCG"));
}
/**
public void onStart()
{
super.onStart();
Log.d(tag, "Evento onStart()");
}
public void onRestart()
{
super.onRestart();
Log.d(tag, "Evento onRestart()");
}
public void onResume()
{
super.onResume();
Log.d(tag, "Evento onResume()");
}
public void onPause()
{
super.onPause();
Log.d(tag, "Evento onPause()");
}
public void onStop()
{
super.onStop();
Log.d(tag, "Evento onStop()");
}
public void onDestroy()
{
super.onDestroy();
Log.d(tag, "Evento onDestroy()");
}
*/
} | 2,047 | 0.680508 | 0.678554 | 83 | 23.674698 | 18.931143 | 76 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.554217 | false | false | 1 |
961576d62834981d054bd22fd46f2c047d888efc | 33,397,665,748,382 | 42e92aa222fcbb9cd4677ef79451178e9dd3866e | /src/main/java/sg/darren/springboot/efamily/controller/AnniversaryController.java | ec549f00af1ae4605eab47f8817c0fae9c2eaf71 | []
| no_license | xueyublue/efamily | https://github.com/xueyublue/efamily | 9577dd0a8b8e475dbc9fe99acca51b37e26e59f0 | cd0d2d8984a3ded3e36298ffd6e525dda123c486 | refs/heads/master | 2022-05-06T01:00:17.147000 | 2022-05-04T05:27:15 | 2022-05-04T05:27:15 | 105,210,382 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package sg.darren.springboot.efamily.controller;
import java.util.List;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import sg.darren.springboot.efamily.domain.dto.AnniversaryForm;
import sg.darren.springboot.efamily.domain.dto.App;
import sg.darren.springboot.efamily.domain.dto.Message;
import sg.darren.springboot.efamily.domain.enums.AnniversaryCategory;
import sg.darren.springboot.efamily.domain.enums.AppAction;
import sg.darren.springboot.efamily.domain.enums.DateType;
import sg.darren.springboot.efamily.domain.enums.RepeatInterval;
import sg.darren.springboot.efamily.service.intf.AnniversaryService;
@Controller
@RequestMapping("/anniversary")
@SessionAttributes("app")
public class AnniversaryController extends BaseController {
@Autowired
private AnniversaryService anniversaryService;
@Autowired
private App app;
@ModelAttribute
public App initAppModel() {
app.setCurrentPage(MenuId.Anniversaries);
return app;
}
@GetMapping("/list")
public String showList(Model model) {
List<AnniversaryForm> anniversaries = anniversaryService.findAll();
model.addAttribute("anniversaries", anniversaries);
// do not reset message attribute if it was set at redirect
if(model.getAttribute("message") == null) {
model.addAttribute("message", new Message("message.user.info.data-found", new Object[] { anniversaries.size() }));
}
return Template.ANNIVERSARY_VIEW_NAME;
}
@GetMapping("/add")
public String showAddForm(Model model) {
app.setAction(AppAction.ADD);
AnniversaryForm anniversary = new AnniversaryForm();
anniversary.setDateType(DateType.SOLAR);
anniversary.setCategory(AnniversaryCategory.BIRTH);
anniversary.setRepeatInterval(RepeatInterval.YEAR);
model.addAttribute("anniversary", anniversary);
return Template.ANNIVERSARY_FORM_VIEW_NAME;
}
@PostMapping("/add")
public String processAddForm(
@ModelAttribute("anniversary") @Valid AnniversaryForm anniversary,
BindingResult bindingResult,
RedirectAttributes redirectAttributes,
Model model) {
// DTO validations
if(bindingResult.hasErrors()) {
return Template.USER_FORM_VIEW_NAME;
}
// Check if Name has been registered
if(anniversaryService.findByName(anniversary.getName()) != null) {
bindingResult.addError(new FieldError("anniversary", "name", "不存在!"));
model.addAttribute("anniversary", model.getAttribute("user"));
return Template.ANNIVERSARY_FORM_VIEW_NAME;
}
// persistence
if(anniversary.getRepeatInterval() == null) anniversary.setRepeatInterval(RepeatInterval.NONE);
anniversaryService.insert(anniversary);
// send redirect
redirectAttributes.addFlashAttribute("message", new Message("message.added"));
return redirect(Url.ANNIVERSARY_URL);
}
@GetMapping("/update/{id}")
public String showUpdateForm(@PathVariable(required = true) int id, Model model) {
app.setAction(AppAction.UPDATE);
AnniversaryForm anniversary = anniversaryService.findById(id);
model.addAttribute("anniversary", anniversary);
return Template.ANNIVERSARY_FORM_VIEW_NAME;
}
@PostMapping("/update/{id}")
public String processUpdateForm(
@ModelAttribute("anniversary") @Valid AnniversaryForm anniversary,
BindingResult bindingResult,
RedirectAttributes redirectAttributes,
Model model) {
// DTO validations
if(bindingResult.hasErrors()) {
return Template.ANNIVERSARY_FORM_VIEW_NAME;
}
// Check if user ID still exists
if(anniversaryService.findById(anniversary.getId()) == null) {
bindingResult.addError(new FieldError("anniversary", "name", "不存在!"));
model.addAttribute("anniversary", model.getAttribute("user"));
return Template.ANNIVERSARY_FORM_VIEW_NAME;
}
// persistence
anniversaryService.update(anniversary);
// send redirect
redirectAttributes.addFlashAttribute("message", new Message("message.updated"));
return redirect(Url.ANNIVERSARY_URL);
}
@GetMapping("/delete/{id}")
public String delete(
@PathVariable(required = true) int id,
RedirectAttributes redirectAttributes) {
anniversaryService.deleteById(id);
// send redirect
redirectAttributes.addFlashAttribute("message", new Message("message.deleted"));
return redirect(Url.ANNIVERSARY_URL);
}
} | UTF-8 | Java | 4,913 | java | AnniversaryController.java | Java | []
| null | []
| package sg.darren.springboot.efamily.controller;
import java.util.List;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import sg.darren.springboot.efamily.domain.dto.AnniversaryForm;
import sg.darren.springboot.efamily.domain.dto.App;
import sg.darren.springboot.efamily.domain.dto.Message;
import sg.darren.springboot.efamily.domain.enums.AnniversaryCategory;
import sg.darren.springboot.efamily.domain.enums.AppAction;
import sg.darren.springboot.efamily.domain.enums.DateType;
import sg.darren.springboot.efamily.domain.enums.RepeatInterval;
import sg.darren.springboot.efamily.service.intf.AnniversaryService;
@Controller
@RequestMapping("/anniversary")
@SessionAttributes("app")
public class AnniversaryController extends BaseController {
@Autowired
private AnniversaryService anniversaryService;
@Autowired
private App app;
@ModelAttribute
public App initAppModel() {
app.setCurrentPage(MenuId.Anniversaries);
return app;
}
@GetMapping("/list")
public String showList(Model model) {
List<AnniversaryForm> anniversaries = anniversaryService.findAll();
model.addAttribute("anniversaries", anniversaries);
// do not reset message attribute if it was set at redirect
if(model.getAttribute("message") == null) {
model.addAttribute("message", new Message("message.user.info.data-found", new Object[] { anniversaries.size() }));
}
return Template.ANNIVERSARY_VIEW_NAME;
}
@GetMapping("/add")
public String showAddForm(Model model) {
app.setAction(AppAction.ADD);
AnniversaryForm anniversary = new AnniversaryForm();
anniversary.setDateType(DateType.SOLAR);
anniversary.setCategory(AnniversaryCategory.BIRTH);
anniversary.setRepeatInterval(RepeatInterval.YEAR);
model.addAttribute("anniversary", anniversary);
return Template.ANNIVERSARY_FORM_VIEW_NAME;
}
@PostMapping("/add")
public String processAddForm(
@ModelAttribute("anniversary") @Valid AnniversaryForm anniversary,
BindingResult bindingResult,
RedirectAttributes redirectAttributes,
Model model) {
// DTO validations
if(bindingResult.hasErrors()) {
return Template.USER_FORM_VIEW_NAME;
}
// Check if Name has been registered
if(anniversaryService.findByName(anniversary.getName()) != null) {
bindingResult.addError(new FieldError("anniversary", "name", "不存在!"));
model.addAttribute("anniversary", model.getAttribute("user"));
return Template.ANNIVERSARY_FORM_VIEW_NAME;
}
// persistence
if(anniversary.getRepeatInterval() == null) anniversary.setRepeatInterval(RepeatInterval.NONE);
anniversaryService.insert(anniversary);
// send redirect
redirectAttributes.addFlashAttribute("message", new Message("message.added"));
return redirect(Url.ANNIVERSARY_URL);
}
@GetMapping("/update/{id}")
public String showUpdateForm(@PathVariable(required = true) int id, Model model) {
app.setAction(AppAction.UPDATE);
AnniversaryForm anniversary = anniversaryService.findById(id);
model.addAttribute("anniversary", anniversary);
return Template.ANNIVERSARY_FORM_VIEW_NAME;
}
@PostMapping("/update/{id}")
public String processUpdateForm(
@ModelAttribute("anniversary") @Valid AnniversaryForm anniversary,
BindingResult bindingResult,
RedirectAttributes redirectAttributes,
Model model) {
// DTO validations
if(bindingResult.hasErrors()) {
return Template.ANNIVERSARY_FORM_VIEW_NAME;
}
// Check if user ID still exists
if(anniversaryService.findById(anniversary.getId()) == null) {
bindingResult.addError(new FieldError("anniversary", "name", "不存在!"));
model.addAttribute("anniversary", model.getAttribute("user"));
return Template.ANNIVERSARY_FORM_VIEW_NAME;
}
// persistence
anniversaryService.update(anniversary);
// send redirect
redirectAttributes.addFlashAttribute("message", new Message("message.updated"));
return redirect(Url.ANNIVERSARY_URL);
}
@GetMapping("/delete/{id}")
public String delete(
@PathVariable(required = true) int id,
RedirectAttributes redirectAttributes) {
anniversaryService.deleteById(id);
// send redirect
redirectAttributes.addFlashAttribute("message", new Message("message.deleted"));
return redirect(Url.ANNIVERSARY_URL);
}
} | 4,913 | 0.779048 | 0.779048 | 138 | 34.492752 | 25.708862 | 117 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.007246 | false | false | 1 |
710bc8a13ccd4f5ec60edd513c16386fd14e09b4 | 17,557,826,362,809 | 00d08f725b03eadb940b5d7f03dc95b4bb1e4a2a | /GraduationProject/src/main/java/wbu/finalp/service/impl/LoginServiceImpl.java | 5c9df32c76b5479d3159440955573f1ee79461bd | []
| no_license | Xyunnnn/graduationProject | https://github.com/Xyunnnn/graduationProject | 7a6cb3d4d4ff68566d7e8c8720a11fdf0ff5b797 | 48d527824954bf70a5787a3646bc6ed893ad5fc0 | refs/heads/master | 2020-05-18T17:09:22.929000 | 2019-05-03T09:51:29 | 2019-05-03T09:51:29 | 184,546,802 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package wbu.finalp.service.impl;
import java.util.List;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Property;
import wbu.finalp.annotation.MyFieldAnno;
import wbu.finalp.bean.Admin;
import wbu.finalp.bean.FinalBean;
import wbu.finalp.bean.Student;
import wbu.finalp.bean.Teacher;
import wbu.finalp.dao.UniversalCRUD;
import wbu.finalp.data.Constant;
import wbu.finalp.service.LoginService;
public class LoginServiceImpl implements LoginService{
@MyFieldAnno(name = "universalCRUDExtend")
private UniversalCRUD universalDao;
//Login
@Override
public Object login(DetachedCriteria dCriteria) {
List<Object> objects = universalDao.singleTableQuery(dCriteria);
if(objects.size() > 0){
return objects.get(0);
}
return null;
}
//第一次登录
@Override
public Object firstLogin(String uname, String pwd, String role) {
DetachedCriteria dCriteria = null;
if(Constant.ROLE_STUDENT.equals(role)){
dCriteria = DetachedCriteria.forClass(Student.class);
}else{
dCriteria = DetachedCriteria.forClass(Teacher.class);
}
dCriteria.add(Property.forName("num").eq(uname));
dCriteria.add(Property.forName("pwd").eq(pwd));
List<Object> users = universalDao.singleTableQuery(dCriteria);
if(users.size() > 0){
return users.get(0);
}
return null;
}
}
| UTF-8 | Java | 1,322 | java | LoginServiceImpl.java | Java | []
| null | []
| package wbu.finalp.service.impl;
import java.util.List;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Property;
import wbu.finalp.annotation.MyFieldAnno;
import wbu.finalp.bean.Admin;
import wbu.finalp.bean.FinalBean;
import wbu.finalp.bean.Student;
import wbu.finalp.bean.Teacher;
import wbu.finalp.dao.UniversalCRUD;
import wbu.finalp.data.Constant;
import wbu.finalp.service.LoginService;
public class LoginServiceImpl implements LoginService{
@MyFieldAnno(name = "universalCRUDExtend")
private UniversalCRUD universalDao;
//Login
@Override
public Object login(DetachedCriteria dCriteria) {
List<Object> objects = universalDao.singleTableQuery(dCriteria);
if(objects.size() > 0){
return objects.get(0);
}
return null;
}
//第一次登录
@Override
public Object firstLogin(String uname, String pwd, String role) {
DetachedCriteria dCriteria = null;
if(Constant.ROLE_STUDENT.equals(role)){
dCriteria = DetachedCriteria.forClass(Student.class);
}else{
dCriteria = DetachedCriteria.forClass(Teacher.class);
}
dCriteria.add(Property.forName("num").eq(uname));
dCriteria.add(Property.forName("pwd").eq(pwd));
List<Object> users = universalDao.singleTableQuery(dCriteria);
if(users.size() > 0){
return users.get(0);
}
return null;
}
}
| 1,322 | 0.762195 | 0.759146 | 48 | 26.333334 | 20.538919 | 66 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.583333 | false | false | 1 |
736ac818ee83d9bab002fb7d7f7a23623cf93e84 | 23,124,103,956,996 | 555bd99b8b61dc59f936710ce9232f210b1e8763 | /src/main/java/com/fabricaReact/controller/DetalleOCController.java | 6e41393e350f43f654eb8b9642e48dadd980448a | []
| no_license | gmuryan/fabricaReact | https://github.com/gmuryan/fabricaReact | 4d6a05d88d6fdbd9eac46ea5e60856956ea64a73 | 5e0187396f5eb70b04abdb47b90cc710a1cf3006 | refs/heads/master | 2020-04-23T12:27:34.918000 | 2019-03-15T22:50:16 | 2019-03-15T22:50:16 | 171,169,054 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.fabricaReact.controller;
import com.fabricaReact.model.DetalleOC;
import com.fabricaReact.service.DetalleOCService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Collection;
import java.util.Optional;
@RestController
@RequestMapping("/api")
public class DetalleOCController {
private final Logger log = LoggerFactory.getLogger(DetalleOCController.class);
private DetalleOCService detalleOCService;
public DetalleOCController (DetalleOCService detalleOCService){
this.detalleOCService = detalleOCService;
}
@GetMapping("/detallesOC")
Collection<DetalleOC> detalleOCs() {
return detalleOCService.findAll();
}
@GetMapping("/detallesOC/{id}")
Collection<DetalleOC> detalleOCxId(@PathVariable Long id) {
return detalleOCService.findAllById(id);
}
@GetMapping("/detalleOC/{id}")
ResponseEntity<?> getDetalleOC(@PathVariable Long id) {
Optional<DetalleOC> detalleOC = detalleOCService.findById(id);
return detalleOC.map(response -> ResponseEntity.ok().body(response))
.orElse(new ResponseEntity<>(HttpStatus.NOT_FOUND));
}
@PostMapping("/detalleOC")
ResponseEntity<DetalleOC> createDetalleOC(@Valid @RequestBody DetalleOC detalleOC) throws URISyntaxException {
log.info("Request to create a detalleOC: {}", detalleOC);
DetalleOC result = detalleOCService.save(detalleOC);
return ResponseEntity.created(new URI("/api/detalleOC" + result.getIdDetalleOC())).body(result);
}
@PutMapping("/detalleOC")
ResponseEntity<DetalleOC> updateDetalleOC(@Valid @RequestBody DetalleOC detalleOC){
log.info("Request to update detalleOC: {}", detalleOC);
DetalleOC result = detalleOCService.save(detalleOC);
return ResponseEntity.ok().body(result);
}
@DeleteMapping("/detalleOC/{id}")
public ResponseEntity<?> deleteDetalleOC (@PathVariable Long id){
log.info("Request to delete detalleOC: {}", id);
detalleOCService.deleteById(id);
return ResponseEntity.ok().build();
}
}
| UTF-8 | Java | 2,348 | java | DetalleOCController.java | Java | []
| null | []
| package com.fabricaReact.controller;
import com.fabricaReact.model.DetalleOC;
import com.fabricaReact.service.DetalleOCService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Collection;
import java.util.Optional;
@RestController
@RequestMapping("/api")
public class DetalleOCController {
private final Logger log = LoggerFactory.getLogger(DetalleOCController.class);
private DetalleOCService detalleOCService;
public DetalleOCController (DetalleOCService detalleOCService){
this.detalleOCService = detalleOCService;
}
@GetMapping("/detallesOC")
Collection<DetalleOC> detalleOCs() {
return detalleOCService.findAll();
}
@GetMapping("/detallesOC/{id}")
Collection<DetalleOC> detalleOCxId(@PathVariable Long id) {
return detalleOCService.findAllById(id);
}
@GetMapping("/detalleOC/{id}")
ResponseEntity<?> getDetalleOC(@PathVariable Long id) {
Optional<DetalleOC> detalleOC = detalleOCService.findById(id);
return detalleOC.map(response -> ResponseEntity.ok().body(response))
.orElse(new ResponseEntity<>(HttpStatus.NOT_FOUND));
}
@PostMapping("/detalleOC")
ResponseEntity<DetalleOC> createDetalleOC(@Valid @RequestBody DetalleOC detalleOC) throws URISyntaxException {
log.info("Request to create a detalleOC: {}", detalleOC);
DetalleOC result = detalleOCService.save(detalleOC);
return ResponseEntity.created(new URI("/api/detalleOC" + result.getIdDetalleOC())).body(result);
}
@PutMapping("/detalleOC")
ResponseEntity<DetalleOC> updateDetalleOC(@Valid @RequestBody DetalleOC detalleOC){
log.info("Request to update detalleOC: {}", detalleOC);
DetalleOC result = detalleOCService.save(detalleOC);
return ResponseEntity.ok().body(result);
}
@DeleteMapping("/detalleOC/{id}")
public ResponseEntity<?> deleteDetalleOC (@PathVariable Long id){
log.info("Request to delete detalleOC: {}", id);
detalleOCService.deleteById(id);
return ResponseEntity.ok().build();
}
}
| 2,348 | 0.724872 | 0.72402 | 68 | 33.529411 | 28.14901 | 114 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.470588 | false | false | 1 |
93d88d84e3378199c188df6acb27358ebd643a2f | 34,316,788,704,637 | d9e38ec2441c9ebb30b32f6f426df0abd40784db | /src/main/java/programs/MissingAlphabets.java | b40ef29aed355b4892e8db84ea47724b865eae8b | []
| no_license | RajeshGanessan/CodingProblems | https://github.com/RajeshGanessan/CodingProblems | 1974515425c1a9ac855882dba62b91faf0b112cd | 7e96706b28f871a2ceab2048afc424d38cb5376b | refs/heads/master | 2023-06-27T01:17:01.280000 | 2021-07-07T10:40:23 | 2021-07-07T10:40:23 | 283,268,265 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package programs;
import java.util.*;
public class MissingAlphabets {
public static void main(String[] args) {
System.out.println("Finding missing alphabets");
String alphabets[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".split("");
System.out.println(alphabets.length);
Scanner sc = new Scanner(System.in);
String inputText = sc.nextLine();
sc.close();
inputText = inputText.replaceAll(" ","");
String[] inputString = inputText.split("");
HashSet<String> s1 = new HashSet<>(Arrays.asList(alphabets));
HashSet<String> s2 = new HashSet<>(Arrays.asList(inputString));
s1.removeAll(s2);
System.out.println(s1);
}
}
| UTF-8 | Java | 743 | java | MissingAlphabets.java | Java | []
| null | []
| package programs;
import java.util.*;
public class MissingAlphabets {
public static void main(String[] args) {
System.out.println("Finding missing alphabets");
String alphabets[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".split("");
System.out.println(alphabets.length);
Scanner sc = new Scanner(System.in);
String inputText = sc.nextLine();
sc.close();
inputText = inputText.replaceAll(" ","");
String[] inputString = inputText.split("");
HashSet<String> s1 = new HashSet<>(Arrays.asList(alphabets));
HashSet<String> s2 = new HashSet<>(Arrays.asList(inputString));
s1.removeAll(s2);
System.out.println(s1);
}
}
| 743 | 0.633917 | 0.627187 | 30 | 23.766666 | 26.515007 | 94 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 1 |
8ac2dfe260f818b185043b28496d370f11296bab | 17,343,077,999,761 | 90c04355348c3cd2c6504df4303a588c8f69d2bd | /src/main/java/concurrente/Barrier.java | 88c7337a8780a08ec34a5d0c9ad8998224e1ca15 | []
| no_license | danwyryunq/tp_concurrente | https://github.com/danwyryunq/tp_concurrente | cda4f92cd1b28893fd14ba366dc3dbe481d17f93 | 04dc7a4ca14decc2822221028adf75c2ff33f754 | refs/heads/master | 2021-01-20T19:06:42.861000 | 2016-06-17T03:41:03 | 2016-06-17T03:41:03 | 60,537,374 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package concurrente;
public class Barrier
{
int numThreads ;
private int pendingForReset = 0 ;
private int resets = 0;
public Barrier(int ts)
{
numThreads = pendingForReset = ts;
}
synchronized public void waitForIt()
{
--pendingForReset;
if (pendingForReset > 0 )
{
int currentTanda = resets;
do {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
} while (currentTanda == resets);
} else {
resets++;
pendingForReset = numThreads;
notifyAll();
}
}
}
| UTF-8 | Java | 726 | java | Barrier.java | Java | []
| null | []
| package concurrente;
public class Barrier
{
int numThreads ;
private int pendingForReset = 0 ;
private int resets = 0;
public Barrier(int ts)
{
numThreads = pendingForReset = ts;
}
synchronized public void waitForIt()
{
--pendingForReset;
if (pendingForReset > 0 )
{
int currentTanda = resets;
do {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
} while (currentTanda == resets);
} else {
resets++;
pendingForReset = numThreads;
notifyAll();
}
}
}
| 726 | 0.46832 | 0.464187 | 38 | 18.105263 | 15.572901 | 50 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.342105 | false | false | 1 |
dd7450d8f21330c51f9718c804679163735ae246 | 17,085,379,965,770 | 0f90d6227e090e6f269c44783a5e60ef3fb70b67 | /components/org.wso2.carbon.streaming.integrator.core/src/main/java/org/wso2/carbon/streaming/integrator/core/ha/RecordTableData.java | ec0de585f32caa19e42a193cbd3d9b2093fec9aa | [
"Apache-2.0"
]
| permissive | wso2/carbon-analytics | https://github.com/wso2/carbon-analytics | 723e89ed061164f1755fbe90dfda32176a75a51e | 03f4e6231633fd24112f3cede4597627df3661e8 | refs/heads/master | 2023-08-27T01:25:28.862000 | 2023-05-05T03:59:10 | 2023-05-05T03:59:10 | 16,543,113 | 63 | 301 | Apache-2.0 | false | 2023-05-05T03:59:12 | 2014-02-05T11:40:58 | 2023-03-23T05:48:45 | 2023-05-05T03:59:11 | 122,461 | 29 | 194 | 38 | JavaScript | false | false | /*
* Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wso2.carbon.streaming.integrator.core.ha;
import io.siddhi.core.table.record.RecordTableHandlerCallback;
import io.siddhi.core.util.collection.operator.CompiledCondition;
import io.siddhi.core.util.collection.operator.CompiledExpression;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* Object that holds information required for add, delete, update and updateOrAdd record table events.
*/
public class RecordTableData {
private RecordTableHandlerCallback recordTableHandlerCallback;
private CompiledCondition compiledCondition;
private List<Object[]> records;
private List<Map<String, Object>> conditionParameterMaps;
private LinkedHashMap<String, CompiledExpression> setMap;
private List<Map<String, Object>> setParameterMaps;
private long timestamp;
private EventType eventType;
/**
* Constructor for Add operation
*/
RecordTableData(long timestamp, EventType eventType, RecordTableHandlerCallback recordTableHandlerCallback,
List<Object[]> records) {
this.timestamp = timestamp;
this.eventType = eventType;
this.recordTableHandlerCallback = recordTableHandlerCallback;
this.records = records;
}
/**
* Constructor for Delete operation
*/
RecordTableData(long timestamp, EventType eventType, RecordTableHandlerCallback recordTableHandlerCallback,
CompiledCondition compiledCondition, List<Map<String, Object>> conditionParameterMaps) {
this.timestamp = timestamp;
this.eventType = eventType;
this.recordTableHandlerCallback = recordTableHandlerCallback;
this.compiledCondition = compiledCondition;
this.conditionParameterMaps = conditionParameterMaps;
}
/**
* Constructor for Update operation
*/
RecordTableData(long timestamp, EventType eventType, RecordTableHandlerCallback recordTableHandlerCallback,
CompiledCondition compiledCondition, List<Map<String, Object>> conditionParameterMaps,
LinkedHashMap<String, CompiledExpression> setMap, List<Map<String, Object>> setParameterMaps) {
this.timestamp = timestamp;
this.eventType = eventType;
this.recordTableHandlerCallback = recordTableHandlerCallback;
this.compiledCondition = compiledCondition;
this.conditionParameterMaps = conditionParameterMaps;
this.setMap = setMap;
this.setParameterMaps = setParameterMaps;
}
/**
* Constructor for UpdateOrAdd operation
*/
RecordTableData(long timestamp, EventType eventType, RecordTableHandlerCallback recordTableHandlerCallback,
CompiledCondition compiledCondition, List<Object[]> records,
List<Map<String, Object>> conditionParameterMaps, LinkedHashMap<String, CompiledExpression> setMap,
List<Map<String, Object>> setParameterMaps) {
this.timestamp = timestamp;
this.eventType = eventType;
this.recordTableHandlerCallback = recordTableHandlerCallback;
this.compiledCondition = compiledCondition;
this.records = records;
this.conditionParameterMaps = conditionParameterMaps;
this.setMap = setMap;
this.setParameterMaps = setParameterMaps;
}
RecordTableHandlerCallback getRecordTableHandlerCallback() {
return recordTableHandlerCallback;
}
CompiledCondition getCompiledCondition() {
return compiledCondition;
}
List<Object[]> getRecords() {
return records;
}
List<Map<String, Object>> getConditionParameterMaps() {
return conditionParameterMaps;
}
LinkedHashMap<String, CompiledExpression> getSetMap() {
return setMap;
}
List<Map<String, Object>> getSetParameterMaps() {
return setParameterMaps;
}
public long getTimestamp() {
return timestamp;
}
public EventType getEventType() {
return eventType;
}
public enum EventType {
ADD,
DELETE,
UPDATE,
UPDATE_OR_ADD
}
} | UTF-8 | Java | 4,783 | java | RecordTableData.java | Java | []
| null | []
| /*
* Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wso2.carbon.streaming.integrator.core.ha;
import io.siddhi.core.table.record.RecordTableHandlerCallback;
import io.siddhi.core.util.collection.operator.CompiledCondition;
import io.siddhi.core.util.collection.operator.CompiledExpression;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* Object that holds information required for add, delete, update and updateOrAdd record table events.
*/
public class RecordTableData {
private RecordTableHandlerCallback recordTableHandlerCallback;
private CompiledCondition compiledCondition;
private List<Object[]> records;
private List<Map<String, Object>> conditionParameterMaps;
private LinkedHashMap<String, CompiledExpression> setMap;
private List<Map<String, Object>> setParameterMaps;
private long timestamp;
private EventType eventType;
/**
* Constructor for Add operation
*/
RecordTableData(long timestamp, EventType eventType, RecordTableHandlerCallback recordTableHandlerCallback,
List<Object[]> records) {
this.timestamp = timestamp;
this.eventType = eventType;
this.recordTableHandlerCallback = recordTableHandlerCallback;
this.records = records;
}
/**
* Constructor for Delete operation
*/
RecordTableData(long timestamp, EventType eventType, RecordTableHandlerCallback recordTableHandlerCallback,
CompiledCondition compiledCondition, List<Map<String, Object>> conditionParameterMaps) {
this.timestamp = timestamp;
this.eventType = eventType;
this.recordTableHandlerCallback = recordTableHandlerCallback;
this.compiledCondition = compiledCondition;
this.conditionParameterMaps = conditionParameterMaps;
}
/**
* Constructor for Update operation
*/
RecordTableData(long timestamp, EventType eventType, RecordTableHandlerCallback recordTableHandlerCallback,
CompiledCondition compiledCondition, List<Map<String, Object>> conditionParameterMaps,
LinkedHashMap<String, CompiledExpression> setMap, List<Map<String, Object>> setParameterMaps) {
this.timestamp = timestamp;
this.eventType = eventType;
this.recordTableHandlerCallback = recordTableHandlerCallback;
this.compiledCondition = compiledCondition;
this.conditionParameterMaps = conditionParameterMaps;
this.setMap = setMap;
this.setParameterMaps = setParameterMaps;
}
/**
* Constructor for UpdateOrAdd operation
*/
RecordTableData(long timestamp, EventType eventType, RecordTableHandlerCallback recordTableHandlerCallback,
CompiledCondition compiledCondition, List<Object[]> records,
List<Map<String, Object>> conditionParameterMaps, LinkedHashMap<String, CompiledExpression> setMap,
List<Map<String, Object>> setParameterMaps) {
this.timestamp = timestamp;
this.eventType = eventType;
this.recordTableHandlerCallback = recordTableHandlerCallback;
this.compiledCondition = compiledCondition;
this.records = records;
this.conditionParameterMaps = conditionParameterMaps;
this.setMap = setMap;
this.setParameterMaps = setParameterMaps;
}
RecordTableHandlerCallback getRecordTableHandlerCallback() {
return recordTableHandlerCallback;
}
CompiledCondition getCompiledCondition() {
return compiledCondition;
}
List<Object[]> getRecords() {
return records;
}
List<Map<String, Object>> getConditionParameterMaps() {
return conditionParameterMaps;
}
LinkedHashMap<String, CompiledExpression> getSetMap() {
return setMap;
}
List<Map<String, Object>> getSetParameterMaps() {
return setParameterMaps;
}
public long getTimestamp() {
return timestamp;
}
public EventType getEventType() {
return eventType;
}
public enum EventType {
ADD,
DELETE,
UPDATE,
UPDATE_OR_ADD
}
} | 4,783 | 0.706669 | 0.70437 | 134 | 34.701492 | 31.24865 | 119 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.679105 | false | false | 1 |
64deecd95c1ae18b8622ef9f6c325668484a5e5b | 19,086,834,708,482 | a77adc13d87006ee497aa2c5fb79f0f047ac9f36 | /ViaExitos/src/Upc/Sistemas/Controller/CSalario.java | cc2bcca829ed0c6ec15c73290baba5361eea6da7 | []
| no_license | Lchavarria94/ProyectosUNI | https://github.com/Lchavarria94/ProyectosUNI | c926ce8450f7caff1e7d27ad7cb4297b8c2c7aff | f631c7a1c74ec704af7b4ec0318e5e91eb3e7202 | refs/heads/master | 2021-01-09T20:15:02.506000 | 2016-08-06T09:36:56 | 2016-08-06T09:36:56 | 65,075,424 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package Upc.Sistemas.Controller;
import Upc.Sistemas.Entity.ESalario;
import Upc.Sistemas.Model.MSalario;
public class CSalario {
//Variable de instancia
MSalario model;
//Constructor
public CSalario() {
model = new MSalario();
}
//Metodo del negocio
public void CalculaSalario(ESalario x){
model.ProcesarDatos(x);
}
}
| UTF-8 | Java | 403 | java | CSalario.java | Java | []
| null | []
| package Upc.Sistemas.Controller;
import Upc.Sistemas.Entity.ESalario;
import Upc.Sistemas.Model.MSalario;
public class CSalario {
//Variable de instancia
MSalario model;
//Constructor
public CSalario() {
model = new MSalario();
}
//Metodo del negocio
public void CalculaSalario(ESalario x){
model.ProcesarDatos(x);
}
}
| 403 | 0.617866 | 0.617866 | 20 | 18.15 | 13.842958 | 43 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.3 | false | false | 1 |
8e7c819b76771acf3e94a30b44f16c170d9ddb3e | 19,086,834,709,233 | 82e23802d8a77b5610ba3a99302d20fafa0d3305 | /src/com/turkey/LD29/Images/StandAloneImage.java | 0ae429e75f2ef2c3b6f674997cc152848531b21a | []
| no_license | TheTurkeyDev/LudumDare29 | https://github.com/TheTurkeyDev/LudumDare29 | a194c9206de37c464bd34bb27de657c992fa304d | 62bcddf6584f37d7bf04455a3bc1c300332bd7d2 | refs/heads/master | 2021-05-27T07:30:53.459000 | 2014-07-12T02:18:41 | 2014-07-12T02:18:41 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.turkey.LD29.Images;
public class StandAloneImage
{
private Image image;
private int x = 0, y = 0;
private boolean isVisible = true;
public StandAloneImage(Image i, int ix, int iy)
{
image = i;
x = ix;
y= iy;
}
public void hide()
{
isVisible = false;
}
public void show()
{
isVisible = true;
}
public boolean isVisible()
{
return isVisible;
}
public Image getImage()
{
return image;
}
public int getX()
{
return x;
}
public int getY()
{
return y;
}
}
| UTF-8 | Java | 521 | java | StandAloneImage.java | Java | []
| null | []
| package com.turkey.LD29.Images;
public class StandAloneImage
{
private Image image;
private int x = 0, y = 0;
private boolean isVisible = true;
public StandAloneImage(Image i, int ix, int iy)
{
image = i;
x = ix;
y= iy;
}
public void hide()
{
isVisible = false;
}
public void show()
{
isVisible = true;
}
public boolean isVisible()
{
return isVisible;
}
public Image getImage()
{
return image;
}
public int getX()
{
return x;
}
public int getY()
{
return y;
}
}
| 521 | 0.616123 | 0.608445 | 46 | 10.326087 | 11.455119 | 48 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.434783 | false | false | 1 |
4278d70ea39687f81ad1468b7a8f55e74f1eb028 | 893,353,247,248 | e4aac331edc788efafee5a196709f02080e802df | /1º Bim/Exercícios/Lista1_Java/exec17/NumeroComplexo.java | 28cc1b70672ecc3ab0ed8d8cd4f9c4a2e25ef426 | []
| no_license | jgazal/Programacao1 | https://github.com/jgazal/Programacao1 | f2baa313f6b2c32f562a36ba7bc581036b33658a | ce0bf9aa3ca5b9370bd7ca48c4c2178a8a7135a7 | refs/heads/master | 2020-03-22T07:56:30.017000 | 2018-07-04T14:50:09 | 2018-07-04T14:50:09 | 139,734,189 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | public class NumeroComplexo{
private double parteReal;
private double parteImaginaria;
private double i = Math.sqrt(-1);
public NumeroComplexo(double pParteReal, double pParteImaginaria){
this.setParteReal(pParteReal);
this.setParteImaginaria(pParteImaginaria);
}
public double getParteReal(){
return this.parteReal;
}
public void setParteReal(double pParteReal){
this.parteReal = pParteReal;
}
public double getParteImaginaria(){
return this.parteImaginaria;
}
public void setParteImaginaria(double pParteImaginaria){
this.parteImaginaria = pParteImaginaria;
}
public String numComplexo(){
return "Forma do Número Complexo: Z1 = " + parteReal + " + " + parteImaginaria + "*i(" +
+ parteReal + " + " + parteImaginaria + "i)";
}
public String obterNumero(){
return parteReal + " + " + parteImaginaria + "i";
}
public boolean verificaIgualdade(double nc1a, double nc1b, double nc2c, double nc2d){
if(nc1a == nc2c && nc1b == nc2d){
return true;
}
else{
return false;
}
}
public String adicaoNumeroComplexo(double nc1a, double nc1b, double nc2c, double nc2d){
double somaReal = nc1a + nc2c;
double somaImaginario = nc1b + nc2d;
return somaReal + " + " + somaImaginario + "i";
}
public String subtracaoNumeroComplexo(double nc1a, double nc1b, double nc2c, double nc2d){
double subtraiReal = nc1a - nc2c;
double subtraiImaginario = nc1b - nc2d;
return subtraiReal + " + " + subtraiImaginario + "i";
}
public String multiplicacaoNumeroComplexo(double nc1a, double nc1b, double nc2c, double nc2d){
double multiplicaReal = nc1a * nc2c;
double multiplicaImaginario = nc1b * nc2d;
double mult1 = multiplicaReal - multiplicaImaginario;
double multiplicaRealImag1 = nc1a * nc2d;
double multiplicaRealImag2 = nc1b * nc2c;
double mult2 = multiplicaRealImag1 + multiplicaRealImag2;
return mult1 + " + " + mult2 + "i";
}
public String divisaoNumeroComplexo(double nc1a, double nc1b, double nc2c, double nc2d){
double multiplicaReal = nc1a * nc2c;
double multiplicaImaginario = nc1b * nc2d;
double mult1 = multiplicaReal + multiplicaImaginario;
double div1 = mult1/(Math.pow(nc2c, 2) + Math.pow(nc2c, 2));
double multiplicaRealImag1 = nc1b * nc2c;
double multiplicaRealImag2 = nc1a * nc2d;
double mult2 = multiplicaRealImag1 - multiplicaRealImag2;
double div2 = mult2/(Math.pow(nc2c, 2) + Math.pow(nc2c, 2));
return div1 + " + " + div2 + "i";
}
}
| UTF-8 | Java | 2,550 | java | NumeroComplexo.java | Java | []
| null | []
| public class NumeroComplexo{
private double parteReal;
private double parteImaginaria;
private double i = Math.sqrt(-1);
public NumeroComplexo(double pParteReal, double pParteImaginaria){
this.setParteReal(pParteReal);
this.setParteImaginaria(pParteImaginaria);
}
public double getParteReal(){
return this.parteReal;
}
public void setParteReal(double pParteReal){
this.parteReal = pParteReal;
}
public double getParteImaginaria(){
return this.parteImaginaria;
}
public void setParteImaginaria(double pParteImaginaria){
this.parteImaginaria = pParteImaginaria;
}
public String numComplexo(){
return "Forma do Número Complexo: Z1 = " + parteReal + " + " + parteImaginaria + "*i(" +
+ parteReal + " + " + parteImaginaria + "i)";
}
public String obterNumero(){
return parteReal + " + " + parteImaginaria + "i";
}
public boolean verificaIgualdade(double nc1a, double nc1b, double nc2c, double nc2d){
if(nc1a == nc2c && nc1b == nc2d){
return true;
}
else{
return false;
}
}
public String adicaoNumeroComplexo(double nc1a, double nc1b, double nc2c, double nc2d){
double somaReal = nc1a + nc2c;
double somaImaginario = nc1b + nc2d;
return somaReal + " + " + somaImaginario + "i";
}
public String subtracaoNumeroComplexo(double nc1a, double nc1b, double nc2c, double nc2d){
double subtraiReal = nc1a - nc2c;
double subtraiImaginario = nc1b - nc2d;
return subtraiReal + " + " + subtraiImaginario + "i";
}
public String multiplicacaoNumeroComplexo(double nc1a, double nc1b, double nc2c, double nc2d){
double multiplicaReal = nc1a * nc2c;
double multiplicaImaginario = nc1b * nc2d;
double mult1 = multiplicaReal - multiplicaImaginario;
double multiplicaRealImag1 = nc1a * nc2d;
double multiplicaRealImag2 = nc1b * nc2c;
double mult2 = multiplicaRealImag1 + multiplicaRealImag2;
return mult1 + " + " + mult2 + "i";
}
public String divisaoNumeroComplexo(double nc1a, double nc1b, double nc2c, double nc2d){
double multiplicaReal = nc1a * nc2c;
double multiplicaImaginario = nc1b * nc2d;
double mult1 = multiplicaReal + multiplicaImaginario;
double div1 = mult1/(Math.pow(nc2c, 2) + Math.pow(nc2c, 2));
double multiplicaRealImag1 = nc1b * nc2c;
double multiplicaRealImag2 = nc1a * nc2d;
double mult2 = multiplicaRealImag1 - multiplicaRealImag2;
double div2 = mult2/(Math.pow(nc2c, 2) + Math.pow(nc2c, 2));
return div1 + " + " + div2 + "i";
}
}
| 2,550 | 0.688898 | 0.658297 | 80 | 30.862499 | 27.25103 | 96 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.6875 | false | false | 1 |
48176ce6becb6c01a9efac0a45d312cb7c87d661 | 22,522,808,537,051 | cb24009bbdeeab7f98ee8f4baa562f2d2765690e | /workflow-center/src/main/java/com/workflow/process/center/service/impl/MinioFileServiceImpl.java | ec8fedd099b48f8460b9b0e921e812e404e0df07 | []
| no_license | donald2150/workflow | https://github.com/donald2150/workflow | 7f3e00469f42a33bd3b4efa8ffb7304bd2de0d1f | d1503d71de7e1bc29f6257a04f474569cff2c65c | refs/heads/main | 2023-07-30T10:44:05.633000 | 2021-09-13T05:29:11 | 2021-09-13T05:29:11 | 405,864,879 | 1 | 0 | null | true | 2021-09-13T06:54:26 | 2021-09-13T06:54:25 | 2021-09-13T05:29:37 | 2021-09-13T05:29:35 | 1,921 | 0 | 0 | 0 | null | false | false | package com.workflow.process.center.service.impl;
import com.workflow.process.center.config.file.minio.MinioConfig;
import com.workflow.process.center.exception.BizException;
import com.workflow.process.center.service.FileService;
import com.workflow.process.center.utils.file.FileUploadUtils;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
/**
* @Author: 土豆仙
* @Date: 2021/7/19 17:36
* @Description: Minio 文件存储
*/
@Service
public class MinioFileServiceImpl implements FileService {
@Autowired
private MinioConfig minioConfig;
@Autowired
private MinioClient client;
@Override
public String uploadFile(MultipartFile file) throws Exception {
if (file ==null){
throw new BizException("上传文件不能为空!");
}
String fileName = FileUploadUtils.extractFilename(file);
PutObjectArgs args = PutObjectArgs.builder()
.bucket(minioConfig.getBucketName())
.object(fileName)
.stream(file.getInputStream(), file.getSize(), -1)
.contentType(file.getContentType())
.build();
client.putObject(args);
return minioConfig.getUrl() + "/" + minioConfig.getBucketName() + "/" + fileName;
}
}
| UTF-8 | Java | 1,453 | java | MinioFileServiceImpl.java | Java | [
{
"context": "rk.web.multipart.MultipartFile;\n\n/**\n* @Author: 土豆仙\n* @Date: 2021/7/19 17:36\n* @Description: Min",
"end": 542,
"score": 0.9602762460708618,
"start": 539,
"tag": "USERNAME",
"value": "土豆仙"
}
]
| null | []
| package com.workflow.process.center.service.impl;
import com.workflow.process.center.config.file.minio.MinioConfig;
import com.workflow.process.center.exception.BizException;
import com.workflow.process.center.service.FileService;
import com.workflow.process.center.utils.file.FileUploadUtils;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
/**
* @Author: 土豆仙
* @Date: 2021/7/19 17:36
* @Description: Minio 文件存储
*/
@Service
public class MinioFileServiceImpl implements FileService {
@Autowired
private MinioConfig minioConfig;
@Autowired
private MinioClient client;
@Override
public String uploadFile(MultipartFile file) throws Exception {
if (file ==null){
throw new BizException("上传文件不能为空!");
}
String fileName = FileUploadUtils.extractFilename(file);
PutObjectArgs args = PutObjectArgs.builder()
.bucket(minioConfig.getBucketName())
.object(fileName)
.stream(file.getInputStream(), file.getSize(), -1)
.contentType(file.getContentType())
.build();
client.putObject(args);
return minioConfig.getUrl() + "/" + minioConfig.getBucketName() + "/" + fileName;
}
}
| 1,453 | 0.698804 | 0.690359 | 42 | 32.833332 | 24.388636 | 89 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.452381 | false | false | 1 |
ebed5843174c7c6ea1c44fa346b945cfc4d8407f | 17,411,797,467,054 | 92a1cfcf2815bf9ac90b16068e65886a8d989a09 | /src/main/java/uk/co/autotrader/randomchallenges/lambdaskata/OddNumberRemover.java | 71a1d0744cc3a7722fe95b7262efa52d434971e9 | []
| no_license | Fraser-Chapman/Code-Katas | https://github.com/Fraser-Chapman/Code-Katas | e18b45e8f61ed5449790fd502afb7098e6128361 | 775f0b4be552794681fbbaf7ab4efdc72b6742e1 | refs/heads/master | 2020-04-07T19:59:51.516000 | 2019-01-19T01:57:17 | 2019-01-19T01:57:17 | 158,671,091 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package uk.co.autotrader.randomchallenges.lambdaskata;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
class OddNumberRemover {
List<Integer> removeOddNumbers(int... numbers) {
return IntStream.of(numbers)
.filter(number -> (number % 2 == 0))
.boxed()
.collect(Collectors.toList());
}
} | UTF-8 | Java | 395 | java | OddNumberRemover.java | Java | []
| null | []
| package uk.co.autotrader.randomchallenges.lambdaskata;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
class OddNumberRemover {
List<Integer> removeOddNumbers(int... numbers) {
return IntStream.of(numbers)
.filter(number -> (number % 2 == 0))
.boxed()
.collect(Collectors.toList());
}
} | 395 | 0.64557 | 0.640506 | 15 | 25.4 | 19.646204 | 54 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.333333 | false | false | 1 |
0faa602d63666a8b8b1c1925546214e023b70e2f | 17,411,797,462,940 | 92397c76c3a30cab34c50ec975a2251d19e2428f | /src/main/java/com/basketbandit/core/controllers/GenericMessageController.java | 277bc8774097d4704bc18eef31fac6a62eda0c39 | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
]
| permissive | Galaxiosaurus/BasketBandit-Java | https://github.com/Galaxiosaurus/BasketBandit-Java | d55c9664c62a3591088b62efdb2e16a6ec9979a4 | f4d0acbd324c5bebf1c3ac57bb3d8a79342fe6fe | refs/heads/master | 2018-09-08T13:58:58.913000 | 2018-09-03T16:10:57 | 2018-09-03T16:10:57 | 131,979,618 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.basketbandit.core.controllers;
import com.basketbandit.core.Configuration;
import com.basketbandit.core.database.DatabaseConnection;
import com.basketbandit.core.database.DatabaseFunctions;
import com.basketbandit.core.modules.Command;
import com.basketbandit.core.modules.audio.ModuleAudio;
import com.basketbandit.core.modules.audio.commands.CommandPlay;
import com.basketbandit.core.modules.logging.ModuleLogging;
import com.basketbandit.core.utils.Utils;
import net.dv8tion.jda.core.entities.User;
import net.dv8tion.jda.core.events.message.GenericMessageEvent;
import net.dv8tion.jda.core.events.message.MessageReceivedEvent;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
public class GenericMessageController {
public GenericMessageController(GenericMessageEvent e) {
if(e instanceof MessageReceivedEvent) {
messageReceivedEvent((MessageReceivedEvent)e);
}
}
private void messageReceivedEvent(MessageReceivedEvent e) {
try {
// Used to help calculate execution time of functions.
long startExecutionNano = System.nanoTime();
// Help command (Private Message) throws null pointer for serverLong (Obviously.)
String serverLong = e.getGuild().getId();
String msgRawLower = e.getMessage().getContentRaw().toLowerCase();
User user = e.getAuthor();
String prefix = new DatabaseFunctions().getServerPrefix(serverLong);
if(prefix == null || prefix.equals("") || msgRawLower.startsWith(Configuration.GLOBAL_PREFIX)) {
prefix = Configuration.GLOBAL_PREFIX;
}
if(user.isBot()
|| msgRawLower.equals(prefix)
|| msgRawLower.startsWith(prefix + prefix)
|| msgRawLower.equals(Configuration.GLOBAL_PREFIX)
|| msgRawLower.startsWith(Configuration.GLOBAL_PREFIX + Configuration.GLOBAL_PREFIX)) {
return;
}
if(msgRawLower.startsWith(prefix) || msgRawLower.startsWith(Configuration.GLOBAL_PREFIX)) {
processMessage(e, startExecutionNano, prefix);
return;
}
if(msgRawLower.matches("^[0-9]{1,2}$") || msgRawLower.equals("cancel")) {
processMessage(e, startExecutionNano);
}
} catch(NullPointerException ex) {
// Do nothing, null pointers happen.
} catch(Exception ex) {
ex.printStackTrace();
}
}
/**
* Deals with commands that start with a prefix.
* @param e MessageReceivedEvent
* @param startExecutionNano long
* @param prefix String
*/
private void processMessage(MessageReceivedEvent e, long startExecutionNano, String prefix) {
String[] input = e.getMessage().getContentRaw().substring(prefix.length()).split("\\s+", 2);
String inputPrefix = e.getMessage().getContentRaw().substring(0,prefix.length());
String serverLong = e.getGuild().getId();
try {
long executionTime = 0;
Class<?> clazz;
Constructor<?> constructor = null;
String moduleDbName = "";
String channelId = e.getTextChannel().getId();
boolean executed = false;
boolean bound = false;
StringBuilder boundChannels = new StringBuilder();
// Iterate through the command list, if the input matches the effective name (includes invocation)
// find the module class that beStrings to the command itself and create a new instance of that
// constructor (which takes a MessageReceivedEvent) with the parameter of a MessageReceivedEvent.
// Also return the command's module to check
for(Command c : Utils.commandList) {
if((inputPrefix + input[0]).equals(c.getGlobalName()) || (inputPrefix + input[0]).equals(prefix + c.getCommandName())) {
String commandModule = c.getCommandModule();
moduleDbName = Utils.extractModuleName(commandModule, false, true);
clazz = Class.forName(commandModule);
constructor = clazz.getConstructor(MessageReceivedEvent.class, String[].class);
// Remove the input message.
e.getMessage().delete().queue();
break;
}
}
Connection connection = new DatabaseConnection().getConnection();
ResultSet rs = new DatabaseFunctions().getBindingsExclusionsChannel(connection, serverLong, moduleDbName);
// While it has next, if excluded is true, if the module name and channel Id match, apologise and break.
// If excluded is false (implying that bounded is true) and the module name and channel Id do not match,
// apologise again and break, else execute and set executed to true!
// If the loop finishes and boolean executed is still false, execute!
while(rs.next()) {
if(rs.getBoolean(5)) {
if(rs.getString(3).toLowerCase().equals(moduleDbName) && rs.getString(2).equals(channelId)) {
Utils.sendMessage(e, "Sorry " + e.getAuthor().getAsMention() + ", that command is excluded from this channel.");
break;
}
} else {
if(rs.getString(3).toLowerCase().equals(moduleDbName) && rs.getString(2).equals(channelId)) {
if(constructor != null) {
constructor.newInstance(e, input);
executed = true;
break;
}
}
boundChannels.append(e.getGuild().getTextChannelById(rs.getString(2)).getName()).append(", ");
bound = true;
}
}
connection.close();
if(bound && !executed) {
boundChannels = Utils.removeLastOccurrence(boundChannels, ", ");
Utils.sendMessage(e, "Sorry " + e.getAuthor().getAsMention() + ", the " + input[0] + " command is bound to " + boundChannels.toString());
}
if(constructor != null && !executed && !bound) {
constructor.newInstance(e, input);
executed = true;
}
// Print the command and execution time into the console.
if(executed) {
executionTime = (System.nanoTime() - startExecutionNano)/1000000;
System.out.println("[" + Thread.currentThread().getName() + "] " + Instant.now().truncatedTo(ChronoUnit.SECONDS) + " - " + e.getGuild().getName() + " - " + input[0] + " (" + executionTime + "ms)");
}
if(executed && new DatabaseFunctions().checkModuleSettings("moduleLogging", serverLong)) {
new ModuleLogging(e, executionTime, null);
}
} catch (InvocationTargetException ex) {
ex.getCause();
} catch (Exception ex) {
ex.printStackTrace();
}
}
/**
* Deals with non-prefixed commands that are a number between 1-10.
* @param e MessageReceivedEvent
* @param startExecutionNano long
*/
private void processMessage(MessageReceivedEvent e, long startExecutionNano) {
try {
if(ModuleAudio.searchUsers.containsKey(e.getAuthor().getIdLong())) {
String[] input = e.getMessage().getContentRaw().toLowerCase().split("\\s+", 2);
String serverLong = e.getGuild().getId();
// Search function check if regex matches. Used in conjunction with the search input.
if(input[0].matches("^[0-9]{1,2}$") || input[0].equals("cancel")) {
if(!input[0].equals("cancel")) {
new CommandPlay(e, ModuleAudio.searchUsers.get(e.getAuthor().getIdLong()).get(Integer.parseInt(input[0]) - 1).getId().getVideoId());
ModuleAudio.searchUsers.remove(e.getAuthor().getIdLong());
} else if(input[0].equals("cancel")) {
ModuleAudio.searchUsers.remove(e.getAuthor().getIdLong());
Utils.sendMessage(e, "[" + e.getAuthor().getAsMention() + "] Search cancelled.");
}
}
// Remove the input message, but only if searchUsers contains the key.
e.getMessage().delete().queue();
if(new DatabaseFunctions().checkModuleSettings("moduleLogging", serverLong)) {
long executionTime = (System.nanoTime() - startExecutionNano)/1000000;
System.out.println("[" + Thread.currentThread().getName() + "] " + Instant.now().truncatedTo(ChronoUnit.SECONDS) + " - " + e.getGuild().getName() + " - " + input[0] + " (" + executionTime + "ms)");
new ModuleLogging(e, executionTime, null);
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
| UTF-8 | Java | 9,367 | java | GenericMessageController.java | Java | []
| null | []
| package com.basketbandit.core.controllers;
import com.basketbandit.core.Configuration;
import com.basketbandit.core.database.DatabaseConnection;
import com.basketbandit.core.database.DatabaseFunctions;
import com.basketbandit.core.modules.Command;
import com.basketbandit.core.modules.audio.ModuleAudio;
import com.basketbandit.core.modules.audio.commands.CommandPlay;
import com.basketbandit.core.modules.logging.ModuleLogging;
import com.basketbandit.core.utils.Utils;
import net.dv8tion.jda.core.entities.User;
import net.dv8tion.jda.core.events.message.GenericMessageEvent;
import net.dv8tion.jda.core.events.message.MessageReceivedEvent;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
public class GenericMessageController {
public GenericMessageController(GenericMessageEvent e) {
if(e instanceof MessageReceivedEvent) {
messageReceivedEvent((MessageReceivedEvent)e);
}
}
private void messageReceivedEvent(MessageReceivedEvent e) {
try {
// Used to help calculate execution time of functions.
long startExecutionNano = System.nanoTime();
// Help command (Private Message) throws null pointer for serverLong (Obviously.)
String serverLong = e.getGuild().getId();
String msgRawLower = e.getMessage().getContentRaw().toLowerCase();
User user = e.getAuthor();
String prefix = new DatabaseFunctions().getServerPrefix(serverLong);
if(prefix == null || prefix.equals("") || msgRawLower.startsWith(Configuration.GLOBAL_PREFIX)) {
prefix = Configuration.GLOBAL_PREFIX;
}
if(user.isBot()
|| msgRawLower.equals(prefix)
|| msgRawLower.startsWith(prefix + prefix)
|| msgRawLower.equals(Configuration.GLOBAL_PREFIX)
|| msgRawLower.startsWith(Configuration.GLOBAL_PREFIX + Configuration.GLOBAL_PREFIX)) {
return;
}
if(msgRawLower.startsWith(prefix) || msgRawLower.startsWith(Configuration.GLOBAL_PREFIX)) {
processMessage(e, startExecutionNano, prefix);
return;
}
if(msgRawLower.matches("^[0-9]{1,2}$") || msgRawLower.equals("cancel")) {
processMessage(e, startExecutionNano);
}
} catch(NullPointerException ex) {
// Do nothing, null pointers happen.
} catch(Exception ex) {
ex.printStackTrace();
}
}
/**
* Deals with commands that start with a prefix.
* @param e MessageReceivedEvent
* @param startExecutionNano long
* @param prefix String
*/
private void processMessage(MessageReceivedEvent e, long startExecutionNano, String prefix) {
String[] input = e.getMessage().getContentRaw().substring(prefix.length()).split("\\s+", 2);
String inputPrefix = e.getMessage().getContentRaw().substring(0,prefix.length());
String serverLong = e.getGuild().getId();
try {
long executionTime = 0;
Class<?> clazz;
Constructor<?> constructor = null;
String moduleDbName = "";
String channelId = e.getTextChannel().getId();
boolean executed = false;
boolean bound = false;
StringBuilder boundChannels = new StringBuilder();
// Iterate through the command list, if the input matches the effective name (includes invocation)
// find the module class that beStrings to the command itself and create a new instance of that
// constructor (which takes a MessageReceivedEvent) with the parameter of a MessageReceivedEvent.
// Also return the command's module to check
for(Command c : Utils.commandList) {
if((inputPrefix + input[0]).equals(c.getGlobalName()) || (inputPrefix + input[0]).equals(prefix + c.getCommandName())) {
String commandModule = c.getCommandModule();
moduleDbName = Utils.extractModuleName(commandModule, false, true);
clazz = Class.forName(commandModule);
constructor = clazz.getConstructor(MessageReceivedEvent.class, String[].class);
// Remove the input message.
e.getMessage().delete().queue();
break;
}
}
Connection connection = new DatabaseConnection().getConnection();
ResultSet rs = new DatabaseFunctions().getBindingsExclusionsChannel(connection, serverLong, moduleDbName);
// While it has next, if excluded is true, if the module name and channel Id match, apologise and break.
// If excluded is false (implying that bounded is true) and the module name and channel Id do not match,
// apologise again and break, else execute and set executed to true!
// If the loop finishes and boolean executed is still false, execute!
while(rs.next()) {
if(rs.getBoolean(5)) {
if(rs.getString(3).toLowerCase().equals(moduleDbName) && rs.getString(2).equals(channelId)) {
Utils.sendMessage(e, "Sorry " + e.getAuthor().getAsMention() + ", that command is excluded from this channel.");
break;
}
} else {
if(rs.getString(3).toLowerCase().equals(moduleDbName) && rs.getString(2).equals(channelId)) {
if(constructor != null) {
constructor.newInstance(e, input);
executed = true;
break;
}
}
boundChannels.append(e.getGuild().getTextChannelById(rs.getString(2)).getName()).append(", ");
bound = true;
}
}
connection.close();
if(bound && !executed) {
boundChannels = Utils.removeLastOccurrence(boundChannels, ", ");
Utils.sendMessage(e, "Sorry " + e.getAuthor().getAsMention() + ", the " + input[0] + " command is bound to " + boundChannels.toString());
}
if(constructor != null && !executed && !bound) {
constructor.newInstance(e, input);
executed = true;
}
// Print the command and execution time into the console.
if(executed) {
executionTime = (System.nanoTime() - startExecutionNano)/1000000;
System.out.println("[" + Thread.currentThread().getName() + "] " + Instant.now().truncatedTo(ChronoUnit.SECONDS) + " - " + e.getGuild().getName() + " - " + input[0] + " (" + executionTime + "ms)");
}
if(executed && new DatabaseFunctions().checkModuleSettings("moduleLogging", serverLong)) {
new ModuleLogging(e, executionTime, null);
}
} catch (InvocationTargetException ex) {
ex.getCause();
} catch (Exception ex) {
ex.printStackTrace();
}
}
/**
* Deals with non-prefixed commands that are a number between 1-10.
* @param e MessageReceivedEvent
* @param startExecutionNano long
*/
private void processMessage(MessageReceivedEvent e, long startExecutionNano) {
try {
if(ModuleAudio.searchUsers.containsKey(e.getAuthor().getIdLong())) {
String[] input = e.getMessage().getContentRaw().toLowerCase().split("\\s+", 2);
String serverLong = e.getGuild().getId();
// Search function check if regex matches. Used in conjunction with the search input.
if(input[0].matches("^[0-9]{1,2}$") || input[0].equals("cancel")) {
if(!input[0].equals("cancel")) {
new CommandPlay(e, ModuleAudio.searchUsers.get(e.getAuthor().getIdLong()).get(Integer.parseInt(input[0]) - 1).getId().getVideoId());
ModuleAudio.searchUsers.remove(e.getAuthor().getIdLong());
} else if(input[0].equals("cancel")) {
ModuleAudio.searchUsers.remove(e.getAuthor().getIdLong());
Utils.sendMessage(e, "[" + e.getAuthor().getAsMention() + "] Search cancelled.");
}
}
// Remove the input message, but only if searchUsers contains the key.
e.getMessage().delete().queue();
if(new DatabaseFunctions().checkModuleSettings("moduleLogging", serverLong)) {
long executionTime = (System.nanoTime() - startExecutionNano)/1000000;
System.out.println("[" + Thread.currentThread().getName() + "] " + Instant.now().truncatedTo(ChronoUnit.SECONDS) + " - " + e.getGuild().getName() + " - " + input[0] + " (" + executionTime + "ms)");
new ModuleLogging(e, executionTime, null);
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
| 9,367 | 0.588022 | 0.582791 | 200 | 45.834999 | 39.778862 | 217 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.695 | false | false | 1 |
6743c10c7c9b3d6cb92aeb1eef7a2577620fbeb3 | 14,139,032,391,770 | 5f9d266cfd06f72c36a85fb9ad340749a781a2e3 | /app/src/main/java/com/softrasol/ternaksukses/Fragments/AllShopFragment.java | 16d9844c9435514f2dd4c6e35321d3a18870b82f | []
| no_license | ahmedkhan4u/SobatTernak | https://github.com/ahmedkhan4u/SobatTernak | b3126bcbc0155f112136220f1cdfcb6890e056ea | 2c6c235aad7296c7f8247cb79602de7606be4dcd | refs/heads/master | 2022-11-05T13:42:58.577000 | 2020-06-07T18:31:02 | 2020-06-07T18:31:02 | 260,358,805 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.softrasol.ternaksukses.Fragments;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.softrasol.ternaksukses.Adapters.ShopCategoryAdapter;
import com.softrasol.ternaksukses.Adapters.ShopNewProductAdapter;
import com.softrasol.ternaksukses.Models.ShopCategoryModel;
import com.softrasol.ternaksukses.Models.ShopNewProductModel;
import com.softrasol.ternaksukses.R;
import java.util.ArrayList;
import java.util.List;
/**
* A simple {@link Fragment} subclass.
*/
public class AllShopFragment extends Fragment {
public AllShopFragment() {
// Required empty public constructor
}
private View mView;
private RecyclerView mRecyclerViewAllCategory, mRecyclerViewNewProducts;
private List<ShopCategoryModel> shopCategoryList;
private List<ShopNewProductModel> newProductList;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
mView = inflater.inflate(R.layout.fragment_all_shop, container, false);
widgetsInflation();
shopAllCategoriesRecyclerViewImplementation();
shopAllCategoriesnewProductsRecyclerView();
return mView;
}
private void shopAllCategoriesnewProductsRecyclerView() {
newProductList = new ArrayList<>();
mRecyclerViewNewProducts.setLayoutManager
(new GridLayoutManager(getContext(),2));
newProductList.add(new ShopNewProductModel(R.drawable.img_itemprice1,
"Product","Rp,145","New Town Ship"));
newProductList.add(new ShopNewProductModel(R.drawable.img_itemprice2,
"Product", "Rp,175","Bilter Town"));
newProductList.add(new ShopNewProductModel(R.drawable.img_itemprice1,
"Product","Rp,145","New Town Ship"));
newProductList.add(new ShopNewProductModel(R.drawable.img_itemprice2,
"Product", "Rp,175","Bilter Town"));
newProductList.add(new ShopNewProductModel(R.drawable.img_itemprice1,
"Product","Rp,145","New Town Ship"));
newProductList.add(new ShopNewProductModel(R.drawable.img_itemprice2,
"Product", "Rp,175","Bilter Town"));
ShopNewProductAdapter adapter = new ShopNewProductAdapter(getContext(), newProductList);
mRecyclerViewNewProducts.setAdapter(adapter);
}
private void shopAllCategoriesRecyclerViewImplementation() {
shopCategoryList = new ArrayList<>();
mRecyclerViewAllCategory.setLayoutManager(new LinearLayoutManager(getContext() , RecyclerView.HORIZONTAL,false));
shopCategoryList.add(new ShopCategoryModel(R.drawable.pakan,"Pakan"));
shopCategoryList.add(new ShopCategoryModel(R.drawable.hewan,"Hewan"));
shopCategoryList.add(new ShopCategoryModel(R.drawable.mesin,"Mesin"));
shopCategoryList.add(new ShopCategoryModel(R.drawable.jasa,"Jasa"));
shopCategoryList.add(new ShopCategoryModel(R.drawable.lain_lain,"Lain Lain"));
shopCategoryList.add(new ShopCategoryModel(R.drawable.obat,"Obat"));
ShopCategoryAdapter adapter = new ShopCategoryAdapter(getContext(), shopCategoryList);
mRecyclerViewAllCategory.setAdapter(adapter);
}
private void widgetsInflation() {
mRecyclerViewAllCategory = mView.findViewById(R.id.recyclerview_shop_all_categories);
mRecyclerViewNewProducts = mView.findViewById(R.id.recyclerview_shop_new_products);
}
}
| UTF-8 | Java | 3,814 | java | AllShopFragment.java | Java | []
| null | []
| package com.softrasol.ternaksukses.Fragments;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.softrasol.ternaksukses.Adapters.ShopCategoryAdapter;
import com.softrasol.ternaksukses.Adapters.ShopNewProductAdapter;
import com.softrasol.ternaksukses.Models.ShopCategoryModel;
import com.softrasol.ternaksukses.Models.ShopNewProductModel;
import com.softrasol.ternaksukses.R;
import java.util.ArrayList;
import java.util.List;
/**
* A simple {@link Fragment} subclass.
*/
public class AllShopFragment extends Fragment {
public AllShopFragment() {
// Required empty public constructor
}
private View mView;
private RecyclerView mRecyclerViewAllCategory, mRecyclerViewNewProducts;
private List<ShopCategoryModel> shopCategoryList;
private List<ShopNewProductModel> newProductList;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
mView = inflater.inflate(R.layout.fragment_all_shop, container, false);
widgetsInflation();
shopAllCategoriesRecyclerViewImplementation();
shopAllCategoriesnewProductsRecyclerView();
return mView;
}
private void shopAllCategoriesnewProductsRecyclerView() {
newProductList = new ArrayList<>();
mRecyclerViewNewProducts.setLayoutManager
(new GridLayoutManager(getContext(),2));
newProductList.add(new ShopNewProductModel(R.drawable.img_itemprice1,
"Product","Rp,145","New Town Ship"));
newProductList.add(new ShopNewProductModel(R.drawable.img_itemprice2,
"Product", "Rp,175","Bilter Town"));
newProductList.add(new ShopNewProductModel(R.drawable.img_itemprice1,
"Product","Rp,145","New Town Ship"));
newProductList.add(new ShopNewProductModel(R.drawable.img_itemprice2,
"Product", "Rp,175","Bilter Town"));
newProductList.add(new ShopNewProductModel(R.drawable.img_itemprice1,
"Product","Rp,145","New Town Ship"));
newProductList.add(new ShopNewProductModel(R.drawable.img_itemprice2,
"Product", "Rp,175","Bilter Town"));
ShopNewProductAdapter adapter = new ShopNewProductAdapter(getContext(), newProductList);
mRecyclerViewNewProducts.setAdapter(adapter);
}
private void shopAllCategoriesRecyclerViewImplementation() {
shopCategoryList = new ArrayList<>();
mRecyclerViewAllCategory.setLayoutManager(new LinearLayoutManager(getContext() , RecyclerView.HORIZONTAL,false));
shopCategoryList.add(new ShopCategoryModel(R.drawable.pakan,"Pakan"));
shopCategoryList.add(new ShopCategoryModel(R.drawable.hewan,"Hewan"));
shopCategoryList.add(new ShopCategoryModel(R.drawable.mesin,"Mesin"));
shopCategoryList.add(new ShopCategoryModel(R.drawable.jasa,"Jasa"));
shopCategoryList.add(new ShopCategoryModel(R.drawable.lain_lain,"Lain Lain"));
shopCategoryList.add(new ShopCategoryModel(R.drawable.obat,"Obat"));
ShopCategoryAdapter adapter = new ShopCategoryAdapter(getContext(), shopCategoryList);
mRecyclerViewAllCategory.setAdapter(adapter);
}
private void widgetsInflation() {
mRecyclerViewAllCategory = mView.findViewById(R.id.recyclerview_shop_all_categories);
mRecyclerViewNewProducts = mView.findViewById(R.id.recyclerview_shop_new_products);
}
}
| 3,814 | 0.727845 | 0.72129 | 100 | 37.139999 | 31.780819 | 121 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.87 | false | false | 1 |
1c605bbc789589e6ba278437c1f2c39b2d217fa6 | 14,139,032,390,282 | 2f4a058ab684068be5af77fea0bf07665b675ac0 | /utils/com/facebook/analytics/DefaultHoneyAnalyticsPeriodicReporter$1.java | e0680f4ff74964e5a9ab7b547447d4e91beffc18 | []
| no_license | cengizgoren/facebook_apk_crack | https://github.com/cengizgoren/facebook_apk_crack | ee812a57c746df3c28fb1f9263ae77190f08d8d2 | a112d30542b9f0bfcf17de0b3a09c6e6cfe1273b | refs/heads/master | 2021-05-26T14:44:04.092000 | 2013-01-16T08:39:00 | 2013-01-16T08:39:00 | 8,321,708 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.facebook.analytics;
import com.facebook.orca.ops.OrcaServiceOperation;
import com.facebook.orca.ops.OrcaServiceOperation.OnCompletedListener;
import com.facebook.orca.ops.ServiceException;
import com.facebook.orca.server.OperationResult;
class DefaultHoneyAnalyticsPeriodicReporter$1 extends OrcaServiceOperation.OnCompletedListener
{
DefaultHoneyAnalyticsPeriodicReporter$1(DefaultHoneyAnalyticsPeriodicReporter paramDefaultHoneyAnalyticsPeriodicReporter, OrcaServiceOperation paramOrcaServiceOperation)
{
}
public void a(ServiceException paramServiceException)
{
this.a.d();
}
public void a(OperationResult paramOperationResult)
{
this.a.d();
}
}
/* Location: /data1/software/apk2java/dex2jar-0.0.9.12/secondary-1.dex_dex2jar.jar
* Qualified Name: com.facebook.analytics.DefaultHoneyAnalyticsPeriodicReporter.1
* JD-Core Version: 0.6.2
*/ | UTF-8 | Java | 903 | java | DefaultHoneyAnalyticsPeriodicReporter$1.java | Java | []
| null | []
| package com.facebook.analytics;
import com.facebook.orca.ops.OrcaServiceOperation;
import com.facebook.orca.ops.OrcaServiceOperation.OnCompletedListener;
import com.facebook.orca.ops.ServiceException;
import com.facebook.orca.server.OperationResult;
class DefaultHoneyAnalyticsPeriodicReporter$1 extends OrcaServiceOperation.OnCompletedListener
{
DefaultHoneyAnalyticsPeriodicReporter$1(DefaultHoneyAnalyticsPeriodicReporter paramDefaultHoneyAnalyticsPeriodicReporter, OrcaServiceOperation paramOrcaServiceOperation)
{
}
public void a(ServiceException paramServiceException)
{
this.a.d();
}
public void a(OperationResult paramOperationResult)
{
this.a.d();
}
}
/* Location: /data1/software/apk2java/dex2jar-0.0.9.12/secondary-1.dex_dex2jar.jar
* Qualified Name: com.facebook.analytics.DefaultHoneyAnalyticsPeriodicReporter.1
* JD-Core Version: 0.6.2
*/ | 903 | 0.801772 | 0.784053 | 28 | 31.285715 | 40.652584 | 171 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.285714 | false | false | 1 |
66a9c5c26f8246e4cce4f05e6b6aa85d7e3abf48 | 25,074,019,139,385 | ad4264b17364b3205887d910d1419f881c296c33 | /src/test/java/com/mrprez/gencross/capharnaum/test/StandardCapharnaumPersonnageTest.java | 8078ee46d2a7fe93a02bf18106bcfa6a00e74bb0 | []
| no_license | gencross-plugins/capharnaum | https://github.com/gencross-plugins/capharnaum | 39fdad23ac956c9e3235fa6b0fc16f7b73e97ed5 | a02204b10886a0c149d92b0f4727862ce0932cb9 | refs/heads/master | 2016-09-05T21:21:02.056000 | 2014-09-29T23:03:24 | 2014-09-29T23:03:24 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.mrprez.gencross.capharnaum.test;
import com.mrprez.gencross.test.StandardPersonnageTest;
public class StandardCapharnaumPersonnageTest extends StandardPersonnageTest {
public StandardCapharnaumPersonnageTest() {
super("Capharnaum");
}
}
| UTF-8 | Java | 258 | java | StandardCapharnaumPersonnageTest.java | Java | []
| null | []
| package com.mrprez.gencross.capharnaum.test;
import com.mrprez.gencross.test.StandardPersonnageTest;
public class StandardCapharnaumPersonnageTest extends StandardPersonnageTest {
public StandardCapharnaumPersonnageTest() {
super("Capharnaum");
}
}
| 258 | 0.821705 | 0.821705 | 12 | 20.5 | 26.5 | 78 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.583333 | false | false | 1 |
add4f0a0dc9d640332b8067b8efd53617029c967 | 26,182,120,693,500 | 6b1b01618f03ea588b6dcff03195e3c16f1b7715 | /app/src/main/java/com/mandriklab/Debtor/View/AddOperationActivity.java | 919f8046769b2b28320b1b488cefe0d5c60daa4d | []
| no_license | ZefDev/Debtor | https://github.com/ZefDev/Debtor | 6ea460500d43279a0c4af47001c903afb06a093f | 24040803a30905bda5d5891468161fe0f9652e79 | refs/heads/master | 2020-06-21T11:04:31.766000 | 2019-08-04T18:38:03 | 2019-08-04T18:38:03 | 197,430,595 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.mandriklab.Debtor.View;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import com.mandriklab.Debtor.Model.DebtorsModel;
import com.mandriklab.Debtor.Model.Entity.Debtors;
import com.mandriklab.Debtor.Model.Entity.Operation;
import com.mandriklab.Debtor.Model.OperationModel;
import com.mandriklab.Debtor.Presenter.AddOperationPresenter;
import com.mandriklab.Debtor.Presenter.MainPresenter;
import com.mandriklab.Debtor.R;
import java.util.ArrayList;
public class AddOperationActivity extends AppCompatActivity {
AddOperationPresenter presenter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_debitor);
Toolbar tn = (Toolbar) findViewById(R.id.toolbar2);
setSupportActionBar(tn);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle("");
DebtorsModel debtorsModel = new DebtorsModel(this);
OperationModel operationModel = new OperationModel(this);
presenter = new AddOperationPresenter(operationModel,debtorsModel);
presenter.attachView(this);
presenter.viewIsReady();
}
public void showListDebitor(ArrayList<Debtors> list){
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
| UTF-8 | Java | 1,847 | java | AddOperationActivity.java | Java | []
| null | []
| package com.mandriklab.Debtor.View;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import com.mandriklab.Debtor.Model.DebtorsModel;
import com.mandriklab.Debtor.Model.Entity.Debtors;
import com.mandriklab.Debtor.Model.Entity.Operation;
import com.mandriklab.Debtor.Model.OperationModel;
import com.mandriklab.Debtor.Presenter.AddOperationPresenter;
import com.mandriklab.Debtor.Presenter.MainPresenter;
import com.mandriklab.Debtor.R;
import java.util.ArrayList;
public class AddOperationActivity extends AppCompatActivity {
AddOperationPresenter presenter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_debitor);
Toolbar tn = (Toolbar) findViewById(R.id.toolbar2);
setSupportActionBar(tn);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle("");
DebtorsModel debtorsModel = new DebtorsModel(this);
OperationModel operationModel = new OperationModel(this);
presenter = new AddOperationPresenter(operationModel,debtorsModel);
presenter.attachView(this);
presenter.viewIsReady();
}
public void showListDebitor(ArrayList<Debtors> list){
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
| 1,847 | 0.716838 | 0.715214 | 57 | 31.403509 | 22.263857 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.578947 | false | false | 1 |
a8357cdbe4076ab56f79cf63106a48fe01d2ff03 | 24,034,637,056,900 | 9d483059a0fe9e354be2159dfdf4efe6105fbd10 | /boot-thymeleaf-mybatis/src/main/java/cn/tycoding/mapper/UserRoleMapper.java | d04fa91e0339326d1c7bed033824ca583387f1b9 | []
| no_license | xuesongjaybluce/spring-learn | https://github.com/xuesongjaybluce/spring-learn | c136415fec786d71fd8d13bfe527ab249c73fdbc | 1a3f2c9b8eddd5b047e67208c52683a36d7d1230 | refs/heads/master | 2020-05-02T02:31:23.947000 | 2019-03-23T11:04:37 | 2019-03-23T11:04:37 | 177,706,232 | 1 | 0 | null | true | 2019-03-26T03:13:38 | 2019-03-26T03:13:37 | 2019-03-24T06:52:14 | 2019-03-23T11:04:50 | 11,835 | 0 | 0 | 0 | null | false | null | package cn.tycoding.mapper;
import cn.tycoding.entity.UserRole;
import cn.tycoding.utils.MyMapper;
public interface UserRoleMapper extends MyMapper<UserRole> {
} | UTF-8 | Java | 163 | java | UserRoleMapper.java | Java | []
| null | []
| package cn.tycoding.mapper;
import cn.tycoding.entity.UserRole;
import cn.tycoding.utils.MyMapper;
public interface UserRoleMapper extends MyMapper<UserRole> {
} | 163 | 0.822086 | 0.822086 | 7 | 22.428572 | 21.34651 | 60 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.428571 | false | false | 1 |
cf6cbeb27b671c9baddf3b410272c70366bdaa11 | 12,730,283,129,663 | a24d01dc1235066dc0e5ebac58d9fa171476bce2 | /src/main/java/org/spring/security/controller/SpringController.java | b4c6b2bcff6673dba30836b49f792aa46983b49a | []
| no_license | VladislavCheese/SpringSecurity-udemy | https://github.com/VladislavCheese/SpringSecurity-udemy | 4482968931a7eee708dad82266b1193a437afea6 | 38fca33e95a677bfc97d3dc6b7c2112aa7f3876f | refs/heads/master | 2023-03-29T00:11:18.220000 | 2021-04-01T23:23:46 | 2021-04-01T23:23:46 | 353,024,992 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.spring.security.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class SpringController {
@GetMapping("/")
public String getInfoForAllPeople(){
return "/info";
}
@GetMapping("/manager_info")
public String getInfoOnlyForManagers(){
return "/manager_view";
}
@GetMapping("/owner_info")
public String getInfoOnlyForOwners(){
return "/owner_view";
}
}
| UTF-8 | Java | 513 | java | SpringController.java | Java | []
| null | []
| package org.spring.security.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class SpringController {
@GetMapping("/")
public String getInfoForAllPeople(){
return "/info";
}
@GetMapping("/manager_info")
public String getInfoOnlyForManagers(){
return "/manager_view";
}
@GetMapping("/owner_info")
public String getInfoOnlyForOwners(){
return "/owner_view";
}
}
| 513 | 0.692008 | 0.692008 | 20 | 24.65 | 17.430649 | 58 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.3 | false | false | 1 |
3fb35ac58ae35a842091fd01817ff26038c37d5b | 19,146,964,211,037 | 9ffaa23ca80d47ee8095d6a74b0f2a4f5210ac85 | /src/test/java/com/timo/springcore/StringUtilsTest.java | a86e5bb672835e379f117285de0f2477c8730744 | []
| no_license | qinlinsen/sprintTest2 | https://github.com/qinlinsen/sprintTest2 | cc6c6f18f2b0d3b38fb32300ecf85ba481c64c02 | ae69cdda392c9e67bb7452fc9883bfebe8e96a0f | refs/heads/master | 2020-03-29T15:27:57.144000 | 2018-09-25T11:26:12 | 2018-09-25T11:26:12 | 150,064,526 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.timo.springcore;
import org.apache.commons.lang3.ObjectUtils;
import org.junit.Test;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.util.WebUtils;
import java.util.*;
/**
* @author qinlinsen
* @since 2019-09-24 中秋节
*/
public class StringUtilsTest {
private static final String String_DEMO_EXAMPLE_WITH_COMMA = "1,2,3,4,5";
@Test
public void testCommaListsToString(){
String[] stringArray = StringUtils.commaDelimitedListToStringArray(String_DEMO_EXAMPLE_WITH_COMMA);
System.out.println(stringArray.length);
//iterator stringArray:
for(String str:stringArray){
System.out.println(str);
}
}
@Test
public void test2(){
/* ArrayList<Integer> list = new ArrayList<>();
for(int i=0;i<6;i++){
list.add(i);
}
String str = org.apache.commons.lang3.StringUtils.join(list, "#");
System.out.println(str);*/
Integer min = ObjectUtils.min(1, 2, 3);
Integer max = ObjectUtils.max(1, 2, 3);
System.out.println(max
);
System.out.println(min);
}
}
| UTF-8 | Java | 1,074 | java | StringUtilsTest.java | Java | [
{
"context": "til.WebUtils;\n\nimport java.util.*;\n\n/**\n * @author qinlinsen\n * @since 2019-09-24 中秋节\n */\npublic class StringU",
"end": 282,
"score": 0.9994081854820251,
"start": 273,
"tag": "USERNAME",
"value": "qinlinsen"
}
]
| null | []
| package com.timo.springcore;
import org.apache.commons.lang3.ObjectUtils;
import org.junit.Test;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.util.WebUtils;
import java.util.*;
/**
* @author qinlinsen
* @since 2019-09-24 中秋节
*/
public class StringUtilsTest {
private static final String String_DEMO_EXAMPLE_WITH_COMMA = "1,2,3,4,5";
@Test
public void testCommaListsToString(){
String[] stringArray = StringUtils.commaDelimitedListToStringArray(String_DEMO_EXAMPLE_WITH_COMMA);
System.out.println(stringArray.length);
//iterator stringArray:
for(String str:stringArray){
System.out.println(str);
}
}
@Test
public void test2(){
/* ArrayList<Integer> list = new ArrayList<>();
for(int i=0;i<6;i++){
list.add(i);
}
String str = org.apache.commons.lang3.StringUtils.join(list, "#");
System.out.println(str);*/
Integer min = ObjectUtils.min(1, 2, 3);
Integer max = ObjectUtils.max(1, 2, 3);
System.out.println(max
);
System.out.println(min);
}
}
| 1,074 | 0.720974 | 0.698502 | 41 | 25.024391 | 22.389553 | 101 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.780488 | false | false | 1 |
bedbb012daec681e2bbc691c7969b3b1ea7f0c5a | 28,106,266,031,355 | 3b147ff5cc719ccd5c918ae2583aa2d98372a70a | /Example/adapter/src/main/java/com/google/ads/mediation/sample/adapter/SampleMediationRewardedAdEventForwarder.java | a0ffc9c80a1e342e5590ee9571d13933cd5cac53 | [
"Apache-2.0"
]
| permissive | googleads/googleads-mobile-android-mediation | https://github.com/googleads/googleads-mobile-android-mediation | 8a240f200297d17524b001132a8bbdb977dad6f2 | 3ea0d573f6cd9203ae21171be853c1a91e1dcb6c | refs/heads/main | 2023-09-05T19:22:18.217000 | 2023-08-30T21:38:43 | 2023-08-30T21:39:18 | 41,122,795 | 250 | 255 | Apache-2.0 | false | 2023-09-14T07:18:27 | 2015-08-20T23:05:45 | 2023-09-03T17:21:26 | 2023-09-14T07:18:27 | 8,098 | 223 | 209 | 70 | Java | false | false | package com.google.ads.mediation.sample.adapter;
import android.app.Activity;
import android.content.Context;
import com.google.ads.mediation.sample.sdk.SampleAdRequest;
import com.google.ads.mediation.sample.sdk.SampleErrorCode;
import com.google.ads.mediation.sample.sdk.SampleRewardedAd;
import com.google.ads.mediation.sample.sdk.SampleRewardedAdListener;
import com.google.android.gms.ads.mediation.MediationAdLoadCallback;
import com.google.android.gms.ads.mediation.MediationRewardedAd;
import com.google.android.gms.ads.mediation.MediationRewardedAdCallback;
import com.google.android.gms.ads.mediation.MediationRewardedAdConfiguration;
import com.google.android.gms.ads.rewarded.RewardItem;
public class SampleMediationRewardedAdEventForwarder extends SampleRewardedAdListener
implements MediationRewardedAd {
/**
* Represents a {@link SampleRewardedAd}.
*/
private SampleRewardedAd sampleRewardedAd;
/*
* Configurations used to load SampleRewardedAd.
*/
private final MediationRewardedAdConfiguration mediationRewardedAdConfiguration;
/**
* A {@link MediationAdLoadCallback} that handles any callback when a Sample rewarded ad finishes
* loading.
*/
private final MediationAdLoadCallback<MediationRewardedAd, MediationRewardedAdCallback> mediationAdLoadCallBack;
/**
* Used to forward rewarded video ad events to AdMob.
*/
private MediationRewardedAdCallback rewardedAdCallback;
public SampleMediationRewardedAdEventForwarder(
MediationRewardedAdConfiguration adConfiguration,
MediationAdLoadCallback<MediationRewardedAd, MediationRewardedAdCallback>
adLoadCallback
) {
this.mediationRewardedAdConfiguration = adConfiguration;
this.mediationAdLoadCallBack = adLoadCallback;
}
public void load() {
String adUnitID = mediationRewardedAdConfiguration.getServerParameters().getString("ad_unit");
SampleAdRequest request = new SampleAdRequest();
sampleRewardedAd = new SampleRewardedAd(adUnitID);
sampleRewardedAd.loadAd(request);
}
@Override
public void onRewardedAdLoaded() {
rewardedAdCallback = mediationAdLoadCallBack.onSuccess(this);
}
@Override
public void showAd(Context context) {
if (!(context instanceof Activity)) {
rewardedAdCallback.onAdFailedToShow(
"An activity context is required to show Sample rewarded ad.");
return;
}
Activity activity = (Activity) context;
if (!sampleRewardedAd.isAdAvailable()) {
rewardedAdCallback.onAdFailedToShow("No ads to show.");
return;
}
sampleRewardedAd.showAd(activity);
}
@Override
public void onRewardedAdFailedToLoad(SampleErrorCode error) {
mediationAdLoadCallBack.onFailure(error.toString());
}
@Override
public void onAdRewarded(final String rewardType, final int amount) {
RewardItem rewardItem =
new RewardItem() {
@Override
public String getType() {
return rewardType;
}
@Override
public int getAmount() {
return amount;
}
};
rewardedAdCallback.onUserEarnedReward(rewardItem);
}
@Override
public void onAdClicked() {
rewardedAdCallback.reportAdClicked();
}
@Override
public void onAdFullScreen() {
rewardedAdCallback.onAdOpened();
rewardedAdCallback.onVideoStart();
rewardedAdCallback.reportAdImpression();
}
@Override
public void onAdClosed() {
rewardedAdCallback.onAdClosed();
}
@Override
public void onAdCompleted() {
rewardedAdCallback.onVideoComplete();
}
}
| UTF-8 | Java | 3,596 | java | SampleMediationRewardedAdEventForwarder.java | Java | []
| null | []
| package com.google.ads.mediation.sample.adapter;
import android.app.Activity;
import android.content.Context;
import com.google.ads.mediation.sample.sdk.SampleAdRequest;
import com.google.ads.mediation.sample.sdk.SampleErrorCode;
import com.google.ads.mediation.sample.sdk.SampleRewardedAd;
import com.google.ads.mediation.sample.sdk.SampleRewardedAdListener;
import com.google.android.gms.ads.mediation.MediationAdLoadCallback;
import com.google.android.gms.ads.mediation.MediationRewardedAd;
import com.google.android.gms.ads.mediation.MediationRewardedAdCallback;
import com.google.android.gms.ads.mediation.MediationRewardedAdConfiguration;
import com.google.android.gms.ads.rewarded.RewardItem;
public class SampleMediationRewardedAdEventForwarder extends SampleRewardedAdListener
implements MediationRewardedAd {
/**
* Represents a {@link SampleRewardedAd}.
*/
private SampleRewardedAd sampleRewardedAd;
/*
* Configurations used to load SampleRewardedAd.
*/
private final MediationRewardedAdConfiguration mediationRewardedAdConfiguration;
/**
* A {@link MediationAdLoadCallback} that handles any callback when a Sample rewarded ad finishes
* loading.
*/
private final MediationAdLoadCallback<MediationRewardedAd, MediationRewardedAdCallback> mediationAdLoadCallBack;
/**
* Used to forward rewarded video ad events to AdMob.
*/
private MediationRewardedAdCallback rewardedAdCallback;
public SampleMediationRewardedAdEventForwarder(
MediationRewardedAdConfiguration adConfiguration,
MediationAdLoadCallback<MediationRewardedAd, MediationRewardedAdCallback>
adLoadCallback
) {
this.mediationRewardedAdConfiguration = adConfiguration;
this.mediationAdLoadCallBack = adLoadCallback;
}
public void load() {
String adUnitID = mediationRewardedAdConfiguration.getServerParameters().getString("ad_unit");
SampleAdRequest request = new SampleAdRequest();
sampleRewardedAd = new SampleRewardedAd(adUnitID);
sampleRewardedAd.loadAd(request);
}
@Override
public void onRewardedAdLoaded() {
rewardedAdCallback = mediationAdLoadCallBack.onSuccess(this);
}
@Override
public void showAd(Context context) {
if (!(context instanceof Activity)) {
rewardedAdCallback.onAdFailedToShow(
"An activity context is required to show Sample rewarded ad.");
return;
}
Activity activity = (Activity) context;
if (!sampleRewardedAd.isAdAvailable()) {
rewardedAdCallback.onAdFailedToShow("No ads to show.");
return;
}
sampleRewardedAd.showAd(activity);
}
@Override
public void onRewardedAdFailedToLoad(SampleErrorCode error) {
mediationAdLoadCallBack.onFailure(error.toString());
}
@Override
public void onAdRewarded(final String rewardType, final int amount) {
RewardItem rewardItem =
new RewardItem() {
@Override
public String getType() {
return rewardType;
}
@Override
public int getAmount() {
return amount;
}
};
rewardedAdCallback.onUserEarnedReward(rewardItem);
}
@Override
public void onAdClicked() {
rewardedAdCallback.reportAdClicked();
}
@Override
public void onAdFullScreen() {
rewardedAdCallback.onAdOpened();
rewardedAdCallback.onVideoStart();
rewardedAdCallback.reportAdImpression();
}
@Override
public void onAdClosed() {
rewardedAdCallback.onAdClosed();
}
@Override
public void onAdCompleted() {
rewardedAdCallback.onVideoComplete();
}
}
| 3,596 | 0.745273 | 0.745273 | 121 | 28.719007 | 27.156792 | 114 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.363636 | false | false | 1 |
0af8ff11a32d5323a80ba5894ea5947abee28228 | 30,081,950,976,915 | b7cec8cc625de4b8baa480b02d0d7e5fd32c74c5 | /src/main/java/com/taxis99/zendesk/config/ZendeskConfigModule.java | c3d4a47971753cb12cf965320375c21fcf32aef3 | [
"MIT"
]
| permissive | rsabro/zendesk | https://github.com/rsabro/zendesk | 422f46fec346ba5489538de7c8552450e17820b6 | 6b0520221954f0c5788d1eaf1a4e82511cc73257 | refs/heads/main | 2023-04-29T05:23:30.947000 | 2021-05-28T12:57:02 | 2021-05-28T12:57:02 | 371,699,945 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.taxis99.zendesk.config;
import com.google.inject.AbstractModule;
import com.google.inject.name.Names;
public class ZendeskConfigModule extends AbstractModule {
@Override protected void configure() {
bind(ZendeskConfig.class)
.annotatedWith(Names.named("Authorized"))
.to(ZendeskConfigFromProperties.class);
}
}
| UTF-8 | Java | 347 | java | ZendeskConfigModule.java | Java | [
{
"context": "package com.taxis99.zendesk.config;\n\nimport com.google.inject.Abstr",
"end": 17,
"score": 0.511362612247467,
"start": 13,
"tag": "USERNAME",
"value": "axis"
}
]
| null | []
| package com.taxis99.zendesk.config;
import com.google.inject.AbstractModule;
import com.google.inject.name.Names;
public class ZendeskConfigModule extends AbstractModule {
@Override protected void configure() {
bind(ZendeskConfig.class)
.annotatedWith(Names.named("Authorized"))
.to(ZendeskConfigFromProperties.class);
}
}
| 347 | 0.763689 | 0.757925 | 12 | 27.916666 | 20.180264 | 57 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.333333 | false | false | 1 |
88ba1f3647fa0f1223c1d0fd90ee6f6fbd0f7aa7 | 10,299,331,625,488 | c7588ba62a1378018981c5d31df97284ae03fe9e | /src/OOP/Lesson1/Triangle/PuzzleAboutTriangle_smplAlgor.java | 473eb65c861e8ff32e10cb505a5eccd38c362d77 | []
| no_license | skyllua/ProgKievUa | https://github.com/skyllua/ProgKievUa | 54df389d70d2233b354d643768807217091d6af5 | 6eecfc5bc05afcf3f84547281fb0e2a6a482ee2d | refs/heads/master | 2017-11-28T14:31:27.014000 | 2017-10-06T20:01:04 | 2017-10-06T20:01:04 | 59,322,891 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package OOP.Lesson1.Triangle;
import Kursach.IO.MyFile;
import com.sun.org.apache.xerces.internal.impl.xpath.regex.Match;
import java.io.IOException;
import java.util.Arrays;
import java.util.Scanner;
public class PuzzleAboutTriangle_smplAlgor {
public static void main(String[] args) throws IOException {
long start = System.currentTimeMillis();
MyFile file = new MyFile("triangle.txt");
int len = Methods.getLength(file.read());
int[][] arr = new int[len][];
for (int i = 0; i < arr.length; i++) {
arr[i] = new int[i+1];
}
Methods.fillArray(arr, file.read().substring(file.read().indexOf("\n")+1, file.read().length()));
Methods.printArray(arr);
System.out.println();
int[] max = new int[len];
int[] min = new int[len];
char[] maxMay = new char[len];
char[] minMay = new char[len];
int maxSum = 0;
int minSum = Methods.wayToSumMoney(arr, Methods.createNextWay(Methods.fillArray(new char[len], 'D'), 0));
long startFindStep = System.currentTimeMillis();
long n = 536_870_912;
int s = 42_397;
Methods.printComputationTime(n, s, len, 'n');
char[] way = new char[len];
Arrays.fill(way, 'D');
for (int c = 0; c < Math.pow(2, len - 1); c++) {
int sum = Methods.wayToSumMoney(arr, way);
if (sum > maxSum) {
maxSum = sum;
maxMay = Arrays.copyOf(way, maxMay.length);
} else if (sum < minSum) {
minSum = sum;
minMay = Arrays.copyOf(way, minMay.length);
}
way = Methods.createNextWay(way);
}
long finish = System.currentTimeMillis();
Methods.printResults(arr, maxSum, maxMay, minSum, minMay, start, startFindStep, finish);
}
}
| UTF-8 | Java | 1,884 | java | PuzzleAboutTriangle_smplAlgor.java | Java | []
| null | []
| package OOP.Lesson1.Triangle;
import Kursach.IO.MyFile;
import com.sun.org.apache.xerces.internal.impl.xpath.regex.Match;
import java.io.IOException;
import java.util.Arrays;
import java.util.Scanner;
public class PuzzleAboutTriangle_smplAlgor {
public static void main(String[] args) throws IOException {
long start = System.currentTimeMillis();
MyFile file = new MyFile("triangle.txt");
int len = Methods.getLength(file.read());
int[][] arr = new int[len][];
for (int i = 0; i < arr.length; i++) {
arr[i] = new int[i+1];
}
Methods.fillArray(arr, file.read().substring(file.read().indexOf("\n")+1, file.read().length()));
Methods.printArray(arr);
System.out.println();
int[] max = new int[len];
int[] min = new int[len];
char[] maxMay = new char[len];
char[] minMay = new char[len];
int maxSum = 0;
int minSum = Methods.wayToSumMoney(arr, Methods.createNextWay(Methods.fillArray(new char[len], 'D'), 0));
long startFindStep = System.currentTimeMillis();
long n = 536_870_912;
int s = 42_397;
Methods.printComputationTime(n, s, len, 'n');
char[] way = new char[len];
Arrays.fill(way, 'D');
for (int c = 0; c < Math.pow(2, len - 1); c++) {
int sum = Methods.wayToSumMoney(arr, way);
if (sum > maxSum) {
maxSum = sum;
maxMay = Arrays.copyOf(way, maxMay.length);
} else if (sum < minSum) {
minSum = sum;
minMay = Arrays.copyOf(way, minMay.length);
}
way = Methods.createNextWay(way);
}
long finish = System.currentTimeMillis();
Methods.printResults(arr, maxSum, maxMay, minSum, minMay, start, startFindStep, finish);
}
}
| 1,884 | 0.568471 | 0.556263 | 63 | 28.904762 | 26.702187 | 113 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.920635 | false | false | 1 |
fdd49cf3fecce6b4968d3b57ed49d966cb54b147 | 1,855,425,919,999 | 89f117fb08afcd3b9375273ab53f94106150cc09 | /src/ir_course/DocumentCollectionParser.java | 3386c5eabafbb8bbc335fbf7fb4bd4ba7007a926 | [
"MIT"
]
| permissive | myrjola/informationretrievalgroupproject | https://github.com/myrjola/informationretrievalgroupproject | 6e718681fa0beb5c1b8db5536d73bed81b501e4a | 9b1951826860d16d6ea1b3ba00e9cc6b6321389d | refs/heads/master | 2020-04-29T07:34:45.851000 | 2014-04-14T10:25:31 | 2014-04-14T10:25:31 | 17,588,873 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* Parser for a document collection
* Created on 2012-01-04
* Modified on 2012-04-19
* Jouni Tuominen <jouni.tuominen@aalto.fi>
* Matias Frosterus <matias.frosterus@aalto.fi>
*/
package ir_course;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class DocumentCollectionParser extends DefaultHandler {
private List<DocumentInCollection> docs;
private boolean item;
private boolean title;
private boolean abstractText;
private boolean searchTaskNumber;
private boolean query;
private boolean relevance;
private String currentText;
private DocumentInCollection currentDoc;
public DocumentCollectionParser() {
this.docs = new LinkedList<DocumentInCollection>();
this.item = false;
this.title = false;
this.abstractText = false;
this.searchTaskNumber = false;
this.query = false;
this.relevance = false;
}
// parses the document collection in the given URI
public void parse(String uri) {
try {
SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
parser.parse(uri, this);
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
// returns the documents of the collection as a list
public List<DocumentInCollection> getDocuments() {
return this.docs;
}
// methods for the SAX parser below
public void startElement(String uri, String localName, String qName, Attributes attributes) {
this.currentText = "";
if (qName.equals("item")) {
this.item = true;
this.currentDoc = new DocumentInCollection();
}
else if (qName.equals("title"))
this.title = true;
else if (qName.equals("abstract"))
this.abstractText = true;
else if (qName.equals("search_task_number"))
this.searchTaskNumber = true;
else if (qName.equals("query"))
this.query = true;
else if (qName.equals("relevance"))
this.relevance = true;
}
public void endElement(String uri, String localName, String qName) {
this.currentText = this.currentText.trim();
if (qName.equals("item")) {
this.item = false;
if (this.currentDoc.getTitle() != null)
// if (this.currentDoc.getSearchTaskNumber() == 4) {
docs.add(this.currentDoc);
// }
}
else if (qName.equals("title")) {
this.currentDoc.setTitle(this.currentText);
this.title = false;
}
else if (qName.equals("abstract")) {
this.currentDoc.setAbstractText(this.currentText);
this.abstractText = false;
}
else if (qName.equals("search_task_number")) {
this.currentDoc.setSearchTaskNumber(Integer.valueOf(this.currentText));
this.searchTaskNumber = false;
}
else if (qName.equals("query")) {
this.currentDoc.setQuery(this.currentText);
this.query = false;
}
else if (qName.equals("relevance")) {
if (Integer.valueOf(this.currentText) == 1)
this.currentDoc.setRelevant(true);
this.relevance = false;
}
}
public void characters(char[] ch, int start, int length) {
String text = "";
for (int i=0; i<length; i++)
text += ch[start+i];
this.currentText += text;
}
} | UTF-8 | Java | 3,378 | java | DocumentCollectionParser.java | Java | [
{
"context": "Created on 2012-01-04\n * Modified on 2012-04-19\n * Jouni Tuominen <jouni.tuominen@aalto.fi>\n * Matias Frosterus <ma",
"end": 107,
"score": 0.9998869895935059,
"start": 93,
"tag": "NAME",
"value": "Jouni Tuominen"
},
{
"context": "1-04\n * Modified on 2012-04-19\n * Jouni Tuominen <jouni.tuominen@aalto.fi>\n * Matias Frosterus <matias.frosterus@aalto.fi>\n",
"end": 132,
"score": 0.9999361634254456,
"start": 109,
"tag": "EMAIL",
"value": "jouni.tuominen@aalto.fi"
},
{
"context": "-19\n * Jouni Tuominen <jouni.tuominen@aalto.fi>\n * Matias Frosterus <matias.frosterus@aalto.fi>\n */\npackage ir_course",
"end": 153,
"score": 0.999884843826294,
"start": 137,
"tag": "NAME",
"value": "Matias Frosterus"
},
{
"context": "en <jouni.tuominen@aalto.fi>\n * Matias Frosterus <matias.frosterus@aalto.fi>\n */\npackage ir_course;\n\nimport java.io.IOExcepti",
"end": 180,
"score": 0.9999346137046814,
"start": 155,
"tag": "EMAIL",
"value": "matias.frosterus@aalto.fi"
}
]
| null | []
| /*
* Parser for a document collection
* Created on 2012-01-04
* Modified on 2012-04-19
* <NAME> <<EMAIL>>
* <NAME> <<EMAIL>>
*/
package ir_course;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class DocumentCollectionParser extends DefaultHandler {
private List<DocumentInCollection> docs;
private boolean item;
private boolean title;
private boolean abstractText;
private boolean searchTaskNumber;
private boolean query;
private boolean relevance;
private String currentText;
private DocumentInCollection currentDoc;
public DocumentCollectionParser() {
this.docs = new LinkedList<DocumentInCollection>();
this.item = false;
this.title = false;
this.abstractText = false;
this.searchTaskNumber = false;
this.query = false;
this.relevance = false;
}
// parses the document collection in the given URI
public void parse(String uri) {
try {
SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
parser.parse(uri, this);
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
// returns the documents of the collection as a list
public List<DocumentInCollection> getDocuments() {
return this.docs;
}
// methods for the SAX parser below
public void startElement(String uri, String localName, String qName, Attributes attributes) {
this.currentText = "";
if (qName.equals("item")) {
this.item = true;
this.currentDoc = new DocumentInCollection();
}
else if (qName.equals("title"))
this.title = true;
else if (qName.equals("abstract"))
this.abstractText = true;
else if (qName.equals("search_task_number"))
this.searchTaskNumber = true;
else if (qName.equals("query"))
this.query = true;
else if (qName.equals("relevance"))
this.relevance = true;
}
public void endElement(String uri, String localName, String qName) {
this.currentText = this.currentText.trim();
if (qName.equals("item")) {
this.item = false;
if (this.currentDoc.getTitle() != null)
// if (this.currentDoc.getSearchTaskNumber() == 4) {
docs.add(this.currentDoc);
// }
}
else if (qName.equals("title")) {
this.currentDoc.setTitle(this.currentText);
this.title = false;
}
else if (qName.equals("abstract")) {
this.currentDoc.setAbstractText(this.currentText);
this.abstractText = false;
}
else if (qName.equals("search_task_number")) {
this.currentDoc.setSearchTaskNumber(Integer.valueOf(this.currentText));
this.searchTaskNumber = false;
}
else if (qName.equals("query")) {
this.currentDoc.setQuery(this.currentText);
this.query = false;
}
else if (qName.equals("relevance")) {
if (Integer.valueOf(this.currentText) == 1)
this.currentDoc.setRelevant(true);
this.relevance = false;
}
}
public void characters(char[] ch, int start, int length) {
String text = "";
for (int i=0; i<length; i++)
text += ch[start+i];
this.currentText += text;
}
} | 3,326 | 0.709888 | 0.704263 | 126 | 25.817461 | 19.192591 | 94 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.134921 | false | false | 1 |
18496561643343216bb31f133bcb11f3d7a1fca3 | 26,706,106,703,802 | 2bc1d2fcff865ed2d5eea1ee0a163611aa36da06 | /chapter3/ForLoop.java | 60bd9d5261f7d792dc75a18e8aac9f7f198de205 | []
| no_license | fir2017/BeginJava7 | https://github.com/fir2017/BeginJava7 | 3ed30d4700d1cd47b80f101f2ffc4240f3881a02 | f3b4cbb8c3323970942d2e3e82fb1652f08670bf | refs/heads/master | 2020-12-03T00:21:24.059000 | 2014-09-19T09:48:37 | 2014-09-19T09:48:37 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | public class ForLoop {
public static void main(String[] args){
long lSum = 0;
for (int i=0;i<100;i++) {
lSum += i;
}
System.out.println("Sum of 1 to 100:" + lSum);
}
}
| UTF-8 | Java | 195 | java | ForLoop.java | Java | []
| null | []
| public class ForLoop {
public static void main(String[] args){
long lSum = 0;
for (int i=0;i<100;i++) {
lSum += i;
}
System.out.println("Sum of 1 to 100:" + lSum);
}
}
| 195 | 0.54359 | 0.497436 | 9 | 20.666666 | 16.020821 | 50 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.555556 | false | false | 1 |
000a7775c22ae8b57bb586da1d86def22aa39200 | 4,131,758,590,401 | e254b063e477d978e76de050b28060c9e05e9830 | /forum/src/main/java/com/piu/security/exception/VerificationCodeException.java | 9f2c6759d9ff8c396be386750be1421119776eb1 | []
| no_license | qq851156575/BBS | https://github.com/qq851156575/BBS | 4f14bbead5b35ad4fbae5f1095ec1e54af55898b | cd1c92ab380a2a832a94d79bc71424ef49e0dc32 | refs/heads/master | 2020-04-01T20:42:38.792000 | 2019-04-06T10:11:04 | 2019-04-06T10:11:19 | 153,617,045 | 3 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.piu.security.exception;
import org.springframework.security.core.AuthenticationException;
public class VerificationCodeException extends AuthenticationException{
public VerificationCodeException(String msg) {
super(msg);
}
}
| UTF-8 | Java | 245 | java | VerificationCodeException.java | Java | []
| null | []
| package com.piu.security.exception;
import org.springframework.security.core.AuthenticationException;
public class VerificationCodeException extends AuthenticationException{
public VerificationCodeException(String msg) {
super(msg);
}
}
| 245 | 0.828571 | 0.828571 | 11 | 21.272728 | 26.792439 | 71 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.636364 | false | false | 1 |
29ba00684c6f91af7367f45cb58dcd77a2cb12cc | 8,040,178,832,211 | b659193516cf632bdd9a24ca74da2249d29ff90a | /cerchio/src/cerchio/Cerchio.java | abe43e26d4ea1f5b960a7b079ecf9a20dcec577f | []
| no_license | P923/IT4_14-15Java | https://github.com/P923/IT4_14-15Java | 9c9a7c1536189b55713d00e43a931aa26a1bafaf | 635a42ceb43997d6900e9353c01abeab3b466196 | refs/heads/master | 2017-12-29T22:20:19.154000 | 2016-10-10T15:34:16 | 2016-10-10T15:34:16 | 69,966,197 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package cerchio;
public class Cerchio {
private float raggio;
Cerchio(){ //metodo costruttore
raggio=0;
}
Cerchio(float raggio){ //metodo costruttore 2
if(this.raggio>=0)
this.raggio = raggio;
}
public float getRaggio() {
return raggio;
}
public void setRaggio(float raggio) {
if(this.raggio>=0)
this.raggio = raggio;
}
public float getArea(){
float area;
area=raggio*raggio*(float)Math.PI;
return area;
}
public float getCirconferenza(){
float circonferenza;
circonferenza=raggio*2*(float)Math.PI;
return circonferenza;
}
}
| UTF-8 | Java | 597 | java | Cerchio.java | Java | []
| null | []
| package cerchio;
public class Cerchio {
private float raggio;
Cerchio(){ //metodo costruttore
raggio=0;
}
Cerchio(float raggio){ //metodo costruttore 2
if(this.raggio>=0)
this.raggio = raggio;
}
public float getRaggio() {
return raggio;
}
public void setRaggio(float raggio) {
if(this.raggio>=0)
this.raggio = raggio;
}
public float getArea(){
float area;
area=raggio*raggio*(float)Math.PI;
return area;
}
public float getCirconferenza(){
float circonferenza;
circonferenza=raggio*2*(float)Math.PI;
return circonferenza;
}
}
| 597 | 0.663317 | 0.654941 | 41 | 13.560976 | 14.055723 | 48 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.463415 | false | false | 1 |
e380daea2c1f06ef94f68dd6e142383c88caec54 | 8,040,178,835,580 | b0f178bbe061d11aa6f88d9a440f200d55fb370e | /cdb-core/src/main/java/com/excilys/cdb/model/UserRole.java | a93aa8ab42f9e2e008574f2105e1e7590929900b | [
"Apache-2.0"
]
| permissive | PoissonSoluble/computer-database | https://github.com/PoissonSoluble/computer-database | aaf522fbe1a37b75549c79d22b82672c12f697cb | 990303ad2ebf122999c0eff524eb58d2855ffef2 | refs/heads/master | 2021-04-01T10:25:44.455000 | 2018-05-24T09:18:22 | 2018-05-24T09:18:22 | 124,563,251 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.excilys.cdb.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "user_role")
public class UserRole {
public enum Role {
USER(new UserRole(2L, "ROLE_USER")), ADMIN(new UserRole(1L, "ROLE_ADMIN"));
private UserRole role;
private Role(UserRole pRole) {
role = pRole;
}
public UserRole getRole() {
return role;
}
}
@Id
@Column(name = "ur_id", unique = true, nullable = false)
private Long id;
@Column(name = "ur_label", unique = true, nullable = false)
private String label;
public UserRole() {
}
public UserRole(Long pId, String pLabel) {
id = pId;
label = pLabel;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
UserRole other = (UserRole) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
if (label == null) {
if (other.label != null)
return false;
} else if (!label.equals(other.label))
return false;
return true;
}
public Long getId() {
return id;
}
public String getLabel() {
return label;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result + ((label == null) ? 0 : label.hashCode());
return result;
}
public void setId(Long pId) {
id = pId;
}
public void setLabel(String pLabel) {
label = pLabel;
}
@Override
public String toString() {
return id + ":" + label;
}
}
| UTF-8 | Java | 2,042 | java | UserRole.java | Java | []
| null | []
| package com.excilys.cdb.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "user_role")
public class UserRole {
public enum Role {
USER(new UserRole(2L, "ROLE_USER")), ADMIN(new UserRole(1L, "ROLE_ADMIN"));
private UserRole role;
private Role(UserRole pRole) {
role = pRole;
}
public UserRole getRole() {
return role;
}
}
@Id
@Column(name = "ur_id", unique = true, nullable = false)
private Long id;
@Column(name = "ur_label", unique = true, nullable = false)
private String label;
public UserRole() {
}
public UserRole(Long pId, String pLabel) {
id = pId;
label = pLabel;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
UserRole other = (UserRole) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
if (label == null) {
if (other.label != null)
return false;
} else if (!label.equals(other.label))
return false;
return true;
}
public Long getId() {
return id;
}
public String getLabel() {
return label;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result + ((label == null) ? 0 : label.hashCode());
return result;
}
public void setId(Long pId) {
id = pId;
}
public void setLabel(String pLabel) {
label = pLabel;
}
@Override
public String toString() {
return id + ":" + label;
}
}
| 2,042 | 0.526934 | 0.523506 | 91 | 21.43956 | 17.753012 | 83 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.43956 | false | false | 1 |
b0a08bb1fc23a87043ba47277554d3d01cba8d19 | 2,765,958,945,340 | 4412775fb0dfb600059508a3673bc12d4bdeb7b1 | /src/main/java/com/talentactor/service/mapper/TelevisionMapper.java | 4665b47bd13caef718cd710c1e9f03cead5cb436 | []
| no_license | BulkSecurityGeneratorProject/talentactor | https://github.com/BulkSecurityGeneratorProject/talentactor | 4a5f06a957b9a615cdfd1738b91d4393cafb7d2e | 1cada340909a919549e11ef541260260b8981f1f | refs/heads/master | 2022-12-16T14:57:55.226000 | 2018-09-11T21:45:22 | 2018-09-11T21:45:22 | 296,649,000 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.talentactor.service.mapper;
import com.talentactor.domain.*;
import com.talentactor.service.dto.TelevisionDTO;
import org.mapstruct.*;
/**
* Mapper for the entity Television and its DTO TelevisionDTO.
*/
@Mapper(componentModel = "spring", uses = {ProfileMapper.class})
public interface TelevisionMapper extends EntityMapper<TelevisionDTO, Television> {
@Mapping(source = "profile.id", target = "profileId")
TelevisionDTO toDto(Television television);
@Mapping(source = "profileId", target = "profile")
Television toEntity(TelevisionDTO televisionDTO);
default Television fromId(Long id) {
if (id == null) {
return null;
}
Television television = new Television();
television.setId(id);
return television;
}
}
| UTF-8 | Java | 805 | java | TelevisionMapper.java | Java | []
| null | []
| package com.talentactor.service.mapper;
import com.talentactor.domain.*;
import com.talentactor.service.dto.TelevisionDTO;
import org.mapstruct.*;
/**
* Mapper for the entity Television and its DTO TelevisionDTO.
*/
@Mapper(componentModel = "spring", uses = {ProfileMapper.class})
public interface TelevisionMapper extends EntityMapper<TelevisionDTO, Television> {
@Mapping(source = "profile.id", target = "profileId")
TelevisionDTO toDto(Television television);
@Mapping(source = "profileId", target = "profile")
Television toEntity(TelevisionDTO televisionDTO);
default Television fromId(Long id) {
if (id == null) {
return null;
}
Television television = new Television();
television.setId(id);
return television;
}
}
| 805 | 0.69441 | 0.69441 | 28 | 27.75 | 24.472469 | 83 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 1 |
2901137bc20fbee0c14cdaff8c8a55ae35fbfe95 | 584,115,553,793 | 3adbe95f2dd61035cd05658a4047269339e05093 | /mod. 1/loop.java | 316922afde7c8a1b667504f2706b846fd9921db3 | []
| no_license | dersonNS/Studying-Java | https://github.com/dersonNS/Studying-Java | 338803f589c83717de1ff3e9de4b3154fab573e3 | 53495eec1166de3eb70ec1dc434ac87940b9636d | refs/heads/master | 2021-01-04T05:39:27.987000 | 2020-02-14T15:20:16 | 2020-02-14T15:20:16 | 240,412,487 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | public class loop {
public static void main(String[] args) {
boolean cont = false;
/*
//WHILE
if (cont == true) {
while (contador <= 10) {
System.out.println("Utilizando o while, contador esta em: " + contador);
contador++;
}
}
// FOR
else {
for (int i = 1; i <= 10; i++) {
System.out.println("Utilizando o for, Contador esta em: " + i);
}
}*/
int contador = 0;
do {
System.out.println(contador);
contador++;
} while (contador <= 3);
}
}
| UTF-8 | Java | 697 | java | loop.java | Java | []
| null | []
| public class loop {
public static void main(String[] args) {
boolean cont = false;
/*
//WHILE
if (cont == true) {
while (contador <= 10) {
System.out.println("Utilizando o while, contador esta em: " + contador);
contador++;
}
}
// FOR
else {
for (int i = 1; i <= 10; i++) {
System.out.println("Utilizando o for, Contador esta em: " + i);
}
}*/
int contador = 0;
do {
System.out.println(contador);
contador++;
} while (contador <= 3);
}
}
| 697 | 0.397418 | 0.387374 | 26 | 24.26923 | 21.230526 | 88 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.461538 | false | false | 1 |
260698c0d550f52ab3f1f356d8e6de1fb11a60c1 | 4,629,974,754,108 | cbaea3d4095228b4a953f4161c34bc54e4a51ec3 | /src/utils/Calc.java | aa4d28d61d826e1df3662da7b5858fef16a80214 | [
"MIT"
]
| permissive | Chiyozel/MarianneMods | https://github.com/Chiyozel/MarianneMods | 0cf84f6dad8f016ce80bc37bb282f08208620633 | 68787f0c9a6aef3d1803edf310c96e6c4fa1c342 | refs/heads/master | 2020-12-24T06:44:53.042000 | 2017-04-23T19:05:04 | 2017-04-23T19:05:04 | 57,134,737 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package utils;
/**
*
* @author Gezochan
*/
public class Calc {
/**
* This class will be used someday ayyyyyyyyyyy
*/
}
| UTF-8 | Java | 152 | java | Calc.java | Java | [
{
"context": "package utils;\r\n\r\n/**\r\n *\r\n * @author Gezochan\r\n */\r\npublic class Calc {\r\n\r\n /**\r\n * This",
"end": 46,
"score": 0.9841379523277283,
"start": 38,
"tag": "USERNAME",
"value": "Gezochan"
}
]
| null | []
| package utils;
/**
*
* @author Gezochan
*/
public class Calc {
/**
* This class will be used someday ayyyyyyyyyyy
*/
}
| 152 | 0.519737 | 0.519737 | 13 | 9.692307 | 13.640351 | 51 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.076923 | false | false | 1 |
4c753d628272061abf8a73250a1142b89bc2e968 | 23,897,198,041,376 | 0356afce1e236cd758c8ed24e29239b3636690ae | /app/src/main/java/instal/trackingtest/MainActivity.java | b3bbf1967b46a03d9730e39c43d2657a766bc0be | []
| no_license | GaruGaru/Tracking-Test | https://github.com/GaruGaru/Tracking-Test | e508736917f41d48d23a783ec55cf274dbecfe05 | 917a529e606b0af7e991eb90628d3d9f1dd754a6 | refs/heads/master | 2016-09-21T05:09:08.514000 | 2016-09-08T14:09:18 | 2016-09-08T14:09:18 | 67,688,803 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package instal.trackingtest;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.TextView;
import com.adform.adformtrackingsdk.AdformTrackingSdk;
public class MainActivity extends AppCompatActivity {
private static final int TRACKING_ID = 677074;
public static final String TAG = "TrackingTest";
private TextView trackingStatus;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.trackingStatus = (TextView) findViewById(R.id.tracking_status);
log("Starting...");
AdformTrackingSdk.startTracking(this, TRACKING_ID);
log("Started tracking -> " + TRACKING_ID);
}
@Override
protected void onResume() {
super.onResume();
AdformTrackingSdk.onResume(this);
log("onResume() tracking -> " + TRACKING_ID);
}
@Override
protected void onPause() {
log("onPause() tracking -> " + TRACKING_ID);
AdformTrackingSdk.onPause();
super.onPause();
}
private void log(String message) {
if (this.trackingStatus != null) {
this.trackingStatus.append("\n" + message);
}
Log.d(TAG, message);
}
}
| UTF-8 | Java | 1,334 | java | MainActivity.java | Java | []
| null | []
| package instal.trackingtest;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.TextView;
import com.adform.adformtrackingsdk.AdformTrackingSdk;
public class MainActivity extends AppCompatActivity {
private static final int TRACKING_ID = 677074;
public static final String TAG = "TrackingTest";
private TextView trackingStatus;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.trackingStatus = (TextView) findViewById(R.id.tracking_status);
log("Starting...");
AdformTrackingSdk.startTracking(this, TRACKING_ID);
log("Started tracking -> " + TRACKING_ID);
}
@Override
protected void onResume() {
super.onResume();
AdformTrackingSdk.onResume(this);
log("onResume() tracking -> " + TRACKING_ID);
}
@Override
protected void onPause() {
log("onPause() tracking -> " + TRACKING_ID);
AdformTrackingSdk.onPause();
super.onPause();
}
private void log(String message) {
if (this.trackingStatus != null) {
this.trackingStatus.append("\n" + message);
}
Log.d(TAG, message);
}
}
| 1,334 | 0.658921 | 0.653673 | 51 | 25.156862 | 21.754759 | 76 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.490196 | false | false | 1 |
8268c0ec5d73f4913ccdda9a0707ab60ac5fbb9b | 2,576,980,430,269 | 793388cd523e9020ac93b274687b44f44189ef4a | /CoParticipacaoCore/src/main/java/br/com/spread/qualicorp/wso2/coparticipacao/dao/impl/RegraDaoImpl.java | 34323e8245850ebd17824459ca788d37c5060322 | []
| no_license | eapereira/coparticipacao | https://github.com/eapereira/coparticipacao | d88c5beb8cda05ba152b7dd9398bfec0a2be6690 | a115fc4d0966d3c38cc8b95aaacc633214d53355 | refs/heads/master | 2020-03-22T16:49:53.425000 | 2019-02-11T15:27:05 | 2019-02-11T15:27:05 | 138,096,491 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package br.com.spread.qualicorp.wso2.coparticipacao.dao.impl;
import java.util.List;
import javax.persistence.Query;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Repository;
import br.com.spread.qualicorp.wso2.coparticipacao.dao.DaoException;
import br.com.spread.qualicorp.wso2.coparticipacao.dao.RegraDao;
import br.com.spread.qualicorp.wso2.coparticipacao.domain.entity.RegraEntity;
/**
*
* @author <a href="edson.apereira@spread.com.br">Edson Alves Pereira</a>
*
*/
@Repository
public class RegraDaoImpl extends AbstractDaoImpl<RegraEntity> implements RegraDao {
private static final Logger LOGGER = LogManager.getLogger(RegraDaoImpl.class);
public RegraDaoImpl() throws DaoException {
super();
}
public List<RegraEntity> listByArquivoInputId(Long id) throws DaoException {
List<RegraEntity> regraEntities;
Query query;
try {
LOGGER.info("BEGIN");
query = createQuery("listByArquivoInputId");
query.setParameter("arquivoInputId", id);
regraEntities = query.getResultList();
LOGGER.info("END");
return regraEntities;
} catch (Exception e) {
LOGGER.error(e.getMessage(), e);
throw new DaoException(e.getMessage(), e);
}
}
public List<RegraEntity> listByArquivoInputSheetId(Long arquivoInputSheetId) throws DaoException {
List<RegraEntity> regraEntities;
Query query;
try {
LOGGER.info("BEGIN");
query = createQuery("listByArquivoInputSheetId");
query.setParameter("arquivoInputSheetId", arquivoInputSheetId);
regraEntities = query.getResultList();
LOGGER.info("END");
return regraEntities;
} catch (Exception e) {
LOGGER.error(e.getMessage(), e);
throw new DaoException(e.getMessage(), e);
}
}
}
| UTF-8 | Java | 1,840 | java | RegraDaoImpl.java | Java | [
{
"context": "ity.RegraEntity;\r\n\r\n/**\r\n * \r\n * @author <a href=\"edson.apereira@spread.com.br\">Edson Alves Pereira</a>\r\n *\r\n */\r\n@Repository\r\np",
"end": 540,
"score": 0.9999232292175293,
"start": 512,
"tag": "EMAIL",
"value": "edson.apereira@spread.com.br"
},
{
"context": " * @author <a href=\"edson.apereira@spread.com.br\">Edson Alves Pereira</a>\r\n *\r\n */\r\n@Repository\r\npublic class RegraDaoI",
"end": 561,
"score": 0.999884307384491,
"start": 542,
"tag": "NAME",
"value": "Edson Alves Pereira"
}
]
| null | []
| package br.com.spread.qualicorp.wso2.coparticipacao.dao.impl;
import java.util.List;
import javax.persistence.Query;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Repository;
import br.com.spread.qualicorp.wso2.coparticipacao.dao.DaoException;
import br.com.spread.qualicorp.wso2.coparticipacao.dao.RegraDao;
import br.com.spread.qualicorp.wso2.coparticipacao.domain.entity.RegraEntity;
/**
*
* @author <a href="<EMAIL>"><NAME></a>
*
*/
@Repository
public class RegraDaoImpl extends AbstractDaoImpl<RegraEntity> implements RegraDao {
private static final Logger LOGGER = LogManager.getLogger(RegraDaoImpl.class);
public RegraDaoImpl() throws DaoException {
super();
}
public List<RegraEntity> listByArquivoInputId(Long id) throws DaoException {
List<RegraEntity> regraEntities;
Query query;
try {
LOGGER.info("BEGIN");
query = createQuery("listByArquivoInputId");
query.setParameter("arquivoInputId", id);
regraEntities = query.getResultList();
LOGGER.info("END");
return regraEntities;
} catch (Exception e) {
LOGGER.error(e.getMessage(), e);
throw new DaoException(e.getMessage(), e);
}
}
public List<RegraEntity> listByArquivoInputSheetId(Long arquivoInputSheetId) throws DaoException {
List<RegraEntity> regraEntities;
Query query;
try {
LOGGER.info("BEGIN");
query = createQuery("listByArquivoInputSheetId");
query.setParameter("arquivoInputSheetId", arquivoInputSheetId);
regraEntities = query.getResultList();
LOGGER.info("END");
return regraEntities;
} catch (Exception e) {
LOGGER.error(e.getMessage(), e);
throw new DaoException(e.getMessage(), e);
}
}
}
| 1,806 | 0.72337 | 0.720109 | 67 | 25.462687 | 26.517427 | 99 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.701493 | false | false | 1 |
d3fe88050fecb10bfd80dd4feb34b620c8d2cfd2 | 12,515,534,754,554 | 47fef491b9c71d13e76bcb2d16362c7ae03c6553 | /examples/BetterProgrammer/src/com/betterprogrammer1/BetterProgrammerTask3.java | b65b28c40fcbe22c8f1e18c7f4bacbebe66db7da | []
| no_license | djimenezc/djimenez-utilities | https://github.com/djimenezc/djimenez-utilities | 5f85f4b23167a7be15e91073ec7ccced8faf4f7a | ea50e122ba450f3369f011804d222fec6e93af90 | refs/heads/master | 2021-03-12T21:56:08.839000 | 2012-07-17T22:46:34 | 2012-07-17T22:46:34 | 33,079,350 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.betterprogrammer1;
import java.util.ArrayList;
import java.util.List;
public class BetterProgrammerTask3 {
// Please do not change this interface
public static interface Node {
List<Node> getChildren();
int getValue();
}
public static class NodeImpl implements Node {
private int value;
private final List<Node> childrens;
public NodeImpl(final int i, final List<Node> childrens) {
this.value = i;
this.childrens = childrens;
}
public int addChildren(final Node node) {
childrens.add(node);
return 1;
}
@Override
public List<Node> getChildren() {
return childrens;
}
@Override
public int getValue() {
return value;
}
public void setValue(final int value) {
this.value = value;
}
}
private static Node buildNodeList() {
final Node node1 = new NodeImpl(10, new ArrayList<Node>());
final Node node2 = new NodeImpl(10, new ArrayList<Node>());
final Node node3 = new NodeImpl(10, new ArrayList<Node>());
final Node node4 = new NodeImpl(10, new ArrayList<Node>());
final List<Node> nodeList2 = new ArrayList<Node>();
nodeList2.add(node4);
final Node node5 = new NodeImpl(10, nodeList2);
final List<Node> nodeList = new ArrayList<Node>();
nodeList.add(node1);
nodeList.add(node2);
nodeList.add(node3);
nodeList.add(node5);
final Node nodeRoot = new NodeImpl(10, nodeList);
return nodeRoot;
}
public static double getAverage(final Node root) {
/*
* Please implement this method to return the average of all node values (Node.getValue()) in
* the tree.
*/
double result = 0;
int totalSumValues = root.getValue();
int numNodes = 0;
double averageChildren = 0;
for (final Node node : root.getChildren()) {
numNodes++;
if ((node.getChildren() != null) && (node.getChildren().size() != 0)) {
averageChildren = getAverage(node);
}
else {
totalSumValues += node.getValue();
}
}
result = ((totalSumValues / numNodes) + averageChildren) / 2;
return result;
}
/**
* @param argv
*/
public static void main(final String argv[]) {
final Node nodeRoot = buildNodeList();
final double result = getAverage(nodeRoot);
final double expectResult = 10;
if (result == expectResult) {
System.out.println("The average value is: " + result);
}
else {
System.out.println("Error, result expected: " + expectResult + ", result calculated: "
+ result);
}
}
}
| UTF-8 | Java | 2,607 | java | BetterProgrammerTask3.java | Java | []
| null | []
| package com.betterprogrammer1;
import java.util.ArrayList;
import java.util.List;
public class BetterProgrammerTask3 {
// Please do not change this interface
public static interface Node {
List<Node> getChildren();
int getValue();
}
public static class NodeImpl implements Node {
private int value;
private final List<Node> childrens;
public NodeImpl(final int i, final List<Node> childrens) {
this.value = i;
this.childrens = childrens;
}
public int addChildren(final Node node) {
childrens.add(node);
return 1;
}
@Override
public List<Node> getChildren() {
return childrens;
}
@Override
public int getValue() {
return value;
}
public void setValue(final int value) {
this.value = value;
}
}
private static Node buildNodeList() {
final Node node1 = new NodeImpl(10, new ArrayList<Node>());
final Node node2 = new NodeImpl(10, new ArrayList<Node>());
final Node node3 = new NodeImpl(10, new ArrayList<Node>());
final Node node4 = new NodeImpl(10, new ArrayList<Node>());
final List<Node> nodeList2 = new ArrayList<Node>();
nodeList2.add(node4);
final Node node5 = new NodeImpl(10, nodeList2);
final List<Node> nodeList = new ArrayList<Node>();
nodeList.add(node1);
nodeList.add(node2);
nodeList.add(node3);
nodeList.add(node5);
final Node nodeRoot = new NodeImpl(10, nodeList);
return nodeRoot;
}
public static double getAverage(final Node root) {
/*
* Please implement this method to return the average of all node values (Node.getValue()) in
* the tree.
*/
double result = 0;
int totalSumValues = root.getValue();
int numNodes = 0;
double averageChildren = 0;
for (final Node node : root.getChildren()) {
numNodes++;
if ((node.getChildren() != null) && (node.getChildren().size() != 0)) {
averageChildren = getAverage(node);
}
else {
totalSumValues += node.getValue();
}
}
result = ((totalSumValues / numNodes) + averageChildren) / 2;
return result;
}
/**
* @param argv
*/
public static void main(final String argv[]) {
final Node nodeRoot = buildNodeList();
final double result = getAverage(nodeRoot);
final double expectResult = 10;
if (result == expectResult) {
System.out.println("The average value is: " + result);
}
else {
System.out.println("Error, result expected: " + expectResult + ", result calculated: "
+ result);
}
}
}
| 2,607 | 0.626391 | 0.612965 | 120 | 20.725 | 22.501097 | 97 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.425 | false | false | 1 |
c6ca9e36e7fd266d5665444ba47b513ff544ff4d | 12,515,534,754,317 | 136deafbbeabb2f20ee2c4cfda98bea916df5226 | /src/main/java/coffeemachine/models/ingredients/Ingredient.java | 872f8f182977b1347899c6762e76a9b807344468 | []
| no_license | sonalibansal/coffeemachine | https://github.com/sonalibansal/coffeemachine | 3a908a9dd17cb211212cf2e7d64d054366d27511 | 719f15452cb43654b30de81cc8b1a4e7b54e6b78 | refs/heads/master | 2022-12-08T22:43:37.821000 | 2020-08-16T15:03:39 | 2020-08-16T15:03:39 | 287,959,658 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package coffeemachine.models.ingredients;
import static coffeemachine.enums.IngredientType.GREEN_TEA_MIXTURE_TEXT;
import coffeemachine.enums.CapacityUnit;
import coffeemachine.enums.IngredientType;
import coffeemachine.models.Quantity;
import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.EXISTING_PROPERTY, property = "type")
@JsonSubTypes({
@JsonSubTypes.Type(value = HotWaterIngredient.class, name = IngredientType.HOT_WATER_TEXT),
@JsonSubTypes.Type(value = HotMilkIngredient.class, name = IngredientType.HOT_MILK_TEXT),
@JsonSubTypes.Type(value = GingerSyrupIngredient.class, name = IngredientType.GINGER_SYRUP_TEXT),
@JsonSubTypes.Type(value = SugarSyrupIngredient.class, name = IngredientType.SUGAR_SYRUP_TEXT),
@JsonSubTypes.Type(value = TeaLeavesPowderIngredient.class, name = IngredientType.TEA_LEAVES_POWDER_TEXT),
@JsonSubTypes.Type(value = CoffeeBeansPowderIngredient.class, name = IngredientType.COFFEE_BEANS_POWDER_TEXT),
@JsonSubTypes.Type(value = GreenTeaMixtureIngredient.class, name = GREEN_TEA_MIXTURE_TEXT)
})
public abstract class Ingredient {
private IngredientType type;
private String name;
private Quantity quantity;
private Integer maxCapacity;
private CapacityUnit capacityUnit;
Ingredient(IngredientType type, CapacityUnit capacityUnit) {
this.type = type;
this.capacityUnit = capacityUnit;
}
}
| UTF-8 | Java | 1,685 | java | Ingredient.java | Java | []
| null | []
| package coffeemachine.models.ingredients;
import static coffeemachine.enums.IngredientType.GREEN_TEA_MIXTURE_TEXT;
import coffeemachine.enums.CapacityUnit;
import coffeemachine.enums.IngredientType;
import coffeemachine.models.Quantity;
import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.EXISTING_PROPERTY, property = "type")
@JsonSubTypes({
@JsonSubTypes.Type(value = HotWaterIngredient.class, name = IngredientType.HOT_WATER_TEXT),
@JsonSubTypes.Type(value = HotMilkIngredient.class, name = IngredientType.HOT_MILK_TEXT),
@JsonSubTypes.Type(value = GingerSyrupIngredient.class, name = IngredientType.GINGER_SYRUP_TEXT),
@JsonSubTypes.Type(value = SugarSyrupIngredient.class, name = IngredientType.SUGAR_SYRUP_TEXT),
@JsonSubTypes.Type(value = TeaLeavesPowderIngredient.class, name = IngredientType.TEA_LEAVES_POWDER_TEXT),
@JsonSubTypes.Type(value = CoffeeBeansPowderIngredient.class, name = IngredientType.COFFEE_BEANS_POWDER_TEXT),
@JsonSubTypes.Type(value = GreenTeaMixtureIngredient.class, name = GREEN_TEA_MIXTURE_TEXT)
})
public abstract class Ingredient {
private IngredientType type;
private String name;
private Quantity quantity;
private Integer maxCapacity;
private CapacityUnit capacityUnit;
Ingredient(IngredientType type, CapacityUnit capacityUnit) {
this.type = type;
this.capacityUnit = capacityUnit;
}
}
| 1,685 | 0.776855 | 0.776855 | 39 | 42.205128 | 36.55146 | 118 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.846154 | false | false | 1 |
1bc49d711d891c78bc19934e1c66cfc64ac296f9 | 8,976,481,715,146 | 58da4d90e1784a8287b704ad052b7f1980b2df05 | /StudentProjects/JBotMiguel/src/controllers/EvolvableMissionController.java | eac56c47b18d6c5b9e0860b1ed0db1fa2e4da747 | []
| no_license | JustinoCaparica/JBotSim-Com | https://github.com/JustinoCaparica/JBotSim-Com | 2af93960a48352142daf7598ee472ac0cf1e8db2 | d4dbd03eab7ab091e424b00422bfe68d144d3e62 | refs/heads/master | 2020-05-22T01:13:40.873000 | 2017-07-14T14:24:04 | 2017-07-14T14:24:04 | 59,682,806 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package controllers;
import environments.MaritimeMissionEnvironment;
import evolutionaryrobotics.neuralnetworks.NeuralNetworkController;
import sensors.IntruderSensor;
import sensors.ParameterSensor;
import sensors.RobotPositionSensor;
import sensors.WaypointSensor;
import simulation.Simulator;
import simulation.robot.DifferentialDriveRobot;
import simulation.robot.Robot;
import simulation.util.Arguments;
public class EvolvableMissionController extends PreprogrammedArbitrator implements FixedLenghtGenomeEvolvableController {
private enum State {
GO_TO_AREA,PATROL
}
private enum Controllers {
WAYPOINT,PATROL
}
private State currentState = State.GO_TO_AREA;
private String destination;
private String base;
private WaypointSensor waypointSensor;
private MaritimeMissionEnvironment env;
private Simulator simulator;
private RobotPositionSensor rps;
private DifferentialDriveRobot r;
public EvolvableMissionController(Simulator simulator, Robot robot,
Arguments args) {
super(simulator, robot, args);
destination = args.getArgumentAsString("destination");
this.simulator = simulator;
rps = (RobotPositionSensor) robot.getSensorByType(RobotPositionSensor.class);
r = (DifferentialDriveRobot)robot;
}
@Override
public void controlStep(double time) {
if(env == null) {
env = (MaritimeMissionEnvironment)simulator.getEnvironment();
waypointSensor = (WaypointSensor)robot.getSensorByType(WaypointSensor.class);
}
int subController = 0;
switch(currentState) {
case GO_TO_AREA:
waypointSensor.setDestination(destination);
subController = Controllers.WAYPOINT.ordinal();
if(waypointSensor.getSensorReading(0) > 0) {
currentState = State.PATROL;
}
break;
case PATROL:
subController = Controllers.PATROL.ordinal();
break;
}
chooseSubController(subController,time);
}
@Override
public void setNNWeights(double[] weights) {
((NeuralNetworkController)subControllers.get(0)).setNNWeights(weights);
}
@Override
public int getGenomeLength() {
return ((NeuralNetworkController)subControllers.get(0)).getGenomeLength();
}
@Override
public double[] getNNWeights() {
return ((NeuralNetworkController)subControllers.get(0)).getNNWeights();
}
@Override
public int getNumberOfInputs() {
return 0;
}
@Override
public int getNumberOfOutputs() {
return 0;
}
} | UTF-8 | Java | 2,385 | java | EvolvableMissionController.java | Java | []
| null | []
| package controllers;
import environments.MaritimeMissionEnvironment;
import evolutionaryrobotics.neuralnetworks.NeuralNetworkController;
import sensors.IntruderSensor;
import sensors.ParameterSensor;
import sensors.RobotPositionSensor;
import sensors.WaypointSensor;
import simulation.Simulator;
import simulation.robot.DifferentialDriveRobot;
import simulation.robot.Robot;
import simulation.util.Arguments;
public class EvolvableMissionController extends PreprogrammedArbitrator implements FixedLenghtGenomeEvolvableController {
private enum State {
GO_TO_AREA,PATROL
}
private enum Controllers {
WAYPOINT,PATROL
}
private State currentState = State.GO_TO_AREA;
private String destination;
private String base;
private WaypointSensor waypointSensor;
private MaritimeMissionEnvironment env;
private Simulator simulator;
private RobotPositionSensor rps;
private DifferentialDriveRobot r;
public EvolvableMissionController(Simulator simulator, Robot robot,
Arguments args) {
super(simulator, robot, args);
destination = args.getArgumentAsString("destination");
this.simulator = simulator;
rps = (RobotPositionSensor) robot.getSensorByType(RobotPositionSensor.class);
r = (DifferentialDriveRobot)robot;
}
@Override
public void controlStep(double time) {
if(env == null) {
env = (MaritimeMissionEnvironment)simulator.getEnvironment();
waypointSensor = (WaypointSensor)robot.getSensorByType(WaypointSensor.class);
}
int subController = 0;
switch(currentState) {
case GO_TO_AREA:
waypointSensor.setDestination(destination);
subController = Controllers.WAYPOINT.ordinal();
if(waypointSensor.getSensorReading(0) > 0) {
currentState = State.PATROL;
}
break;
case PATROL:
subController = Controllers.PATROL.ordinal();
break;
}
chooseSubController(subController,time);
}
@Override
public void setNNWeights(double[] weights) {
((NeuralNetworkController)subControllers.get(0)).setNNWeights(weights);
}
@Override
public int getGenomeLength() {
return ((NeuralNetworkController)subControllers.get(0)).getGenomeLength();
}
@Override
public double[] getNNWeights() {
return ((NeuralNetworkController)subControllers.get(0)).getNNWeights();
}
@Override
public int getNumberOfInputs() {
return 0;
}
@Override
public int getNumberOfOutputs() {
return 0;
}
} | 2,385 | 0.773166 | 0.769811 | 91 | 25.21978 | 23.963251 | 121 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.967033 | false | false | 1 |
989cb7dcec51116576a63425068ea06fcf426be9 | 7,610,682,069,757 | ad8a71590fa8e3cf66d5e4af1716e5ca8b8b1654 | /serviceManager/src/com/fahai/cc/service/settingTemplet/entity/SettingTemplet.java | 5463d8758b94dfdb252e2dd6aba0841794f35e73 | []
| no_license | SalenLiang/hanwen | https://github.com/SalenLiang/hanwen | f1b7082a8d2f27013b5952a958eee8b4ad54cc1d | cd0e717f37229fb2b446b35bbba85749db1988bf | refs/heads/master | 2020-04-06T13:10:44.939000 | 2018-11-14T08:45:30 | 2018-11-14T08:45:30 | 157,487,460 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.fahai.cc.service.settingTemplet.entity;
import java.io.Serializable;
import java.util.Date;
public class SettingTemplet implements Serializable {
/**
*
*/
private static final long serialVersionUID = 2864997442654894085L;
private Integer logId;
private Integer templetId;
private String templetName;
private Integer status;
private String description;
private Date createDate;
private Date lastModifyDate;
private Integer actionUserId;
private String actionType;
public String getActionType() {
return actionType;
}
public void setActionType(String actionType) {
this.actionType = actionType;
}
public Integer getLogId() {
return logId;
}
public void setLogId(Integer logId) {
this.logId = logId;
}
public Integer getTempletId() {
return templetId;
}
public void setTempletId(Integer templetId) {
this.templetId = templetId;
}
public String getTempletName() {
return templetName;
}
public void setTempletName(String templetName) {
this.templetName = templetName;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Date getCreateDate() {
return createDate;
}
public void setCreateDate(Date createDate) {
this.createDate = createDate;
}
public Date getLastModifyDate() {
return lastModifyDate;
}
public void setLastModifyDate(Date lastModifyDate) {
this.lastModifyDate = lastModifyDate;
}
public Integer getActionUserId() {
return actionUserId;
}
public void setActionUserId(Integer actionUserId) {
this.actionUserId = actionUserId;
}
@Override
public String toString() {
return "SettingTemplet [templetId=" + templetId + ", templetName=" + templetName + ", status=" + status
+ ", description=" + description + ", createDate=" + createDate + ", lastModifyDate=" + lastModifyDate
+ ", actionUserId=" + actionUserId + "]";
}
}
| UTF-8 | Java | 2,083 | java | SettingTemplet.java | Java | []
| null | []
| package com.fahai.cc.service.settingTemplet.entity;
import java.io.Serializable;
import java.util.Date;
public class SettingTemplet implements Serializable {
/**
*
*/
private static final long serialVersionUID = 2864997442654894085L;
private Integer logId;
private Integer templetId;
private String templetName;
private Integer status;
private String description;
private Date createDate;
private Date lastModifyDate;
private Integer actionUserId;
private String actionType;
public String getActionType() {
return actionType;
}
public void setActionType(String actionType) {
this.actionType = actionType;
}
public Integer getLogId() {
return logId;
}
public void setLogId(Integer logId) {
this.logId = logId;
}
public Integer getTempletId() {
return templetId;
}
public void setTempletId(Integer templetId) {
this.templetId = templetId;
}
public String getTempletName() {
return templetName;
}
public void setTempletName(String templetName) {
this.templetName = templetName;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Date getCreateDate() {
return createDate;
}
public void setCreateDate(Date createDate) {
this.createDate = createDate;
}
public Date getLastModifyDate() {
return lastModifyDate;
}
public void setLastModifyDate(Date lastModifyDate) {
this.lastModifyDate = lastModifyDate;
}
public Integer getActionUserId() {
return actionUserId;
}
public void setActionUserId(Integer actionUserId) {
this.actionUserId = actionUserId;
}
@Override
public String toString() {
return "SettingTemplet [templetId=" + templetId + ", templetName=" + templetName + ", status=" + status
+ ", description=" + description + ", createDate=" + createDate + ", lastModifyDate=" + lastModifyDate
+ ", actionUserId=" + actionUserId + "]";
}
}
| 2,083 | 0.726836 | 0.717715 | 110 | 17.936363 | 21.020889 | 106 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.318182 | false | false | 1 |
1f39dc415922f47a79018c23fff5e6c8e5e89472 | 23,029,614,642,529 | 517172b4c2fe194188c4ddb40f1d2ee95220c4ef | /aop-spring-boot-starter/src/main/java/rebue/sbs/aop/SubErrAopConfig.java | 73205a882a7a71ff17e05a152d7ae972edf874c8 | []
| no_license | rebue/sbs | https://github.com/rebue/sbs | 5ff317e78578b63a9f986d3336e703a9ad7af597 | 73539d9dd0f73d6b26e1fde9f71324ff39cd2fb8 | refs/heads/master | 2022-03-13T07:17:12.636000 | 2021-11-16T09:47:43 | 2021-11-16T09:47:43 | 124,846,830 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package rebue.sbs.aop;
import java.sql.DataTruncation;
import java.sql.SQLIntegrityConstraintViolationException;
import javax.validation.ConstraintViolationException;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.dao.DuplicateKeyException;
import lombok.extern.slf4j.Slf4j;
import rebue.robotech.dic.ResultDic;
import rebue.robotech.ro.Ro;
import rebue.wheel.api.exception.RuntimeExceptionX;
/**
* SUB层异常拦截
*/
@Slf4j
@Aspect
@Configuration(proxyBeanMethods = false)
@Order(4)
public class SubErrAopConfig {
@Around("execution(public * *..sub..*Sub.*(..))")
public Object around(final ProceedingJoinPoint joinPoint) throws Throwable {
try {
return joinPoint.proceed();
} catch (final DuplicateKeyException e) {
log.error("AOP拦截到关键字重复的异常", e);
final String message = e.getCause().getMessage();
final int start = message.indexOf("'");
final int end = message.indexOf("'", start + 1) + 1;
return new Ro<>(ResultDic.WARN, message.substring(start, end) + "已存在");
} catch (final NumberFormatException e) {
log.error("AOP拦截到字符串转数值的异常", e);
final String[] errs = e.getMessage().split("\"");
return new Ro<>(ResultDic.PARAM_ERROR, "参数错误: \"" + errs[1] + "\"不是数值类型");
} catch (final IllegalArgumentException e) {
log.error("AOP拦截到参数错误的异常", e);
if (StringUtils.isBlank(e.getMessage())) {
return new Ro<>(ResultDic.PARAM_ERROR, "参数错误");
}
else {
return new Ro<>(ResultDic.PARAM_ERROR, "参数错误: " + e.getMessage());
}
} catch (final ConstraintViolationException e) {
log.error("AOP拦截到违反数据库约束的异常", e);
final String[] errs = e.getMessage().split(",");
final StringBuilder sb = new StringBuilder();
for (final String err : errs) {
sb.append(err.split(":")[1].trim() + ",");
}
return new Ro<>(ResultDic.PARAM_ERROR, sb.deleteCharAt(sb.length() - 1).toString());
} catch (final DataIntegrityViolationException e) {
log.error("AOP拦截到违反数据库完整性的异常", e);
final Throwable cause = e.getCause();
if (cause instanceof SQLIntegrityConstraintViolationException) {
return new Ro<>(ResultDic.WARN, "此操作违反了该字段作为外键、主键或唯一键的约束", cause.getMessage());
}
else if (cause instanceof DataTruncation) {
return new Ro<>(ResultDic.WARN, "此操作违反了该字段最大长度的约束", cause.getMessage());
}
else {
return new Ro<>(ResultDic.WARN, "此操作违反了数据库完整性的约束", cause.getMessage());
}
} catch (final NullPointerException e) {
log.error("AOP拦截到空指针异常", e);
if (StringUtils.isBlank(e.getMessage())) {
return new Ro<>(ResultDic.FAIL, "服务器出现空指针异常", null, "500", null);
}
else {
return new Ro<>(ResultDic.FAIL, "服务器出现空指针异常", e.getMessage(), "500", null);
}
} catch (final RuntimeExceptionX e) {
log.warn("AOP拦截到自定义的运行时异常", e);
return new Ro<>(ResultDic.WARN, e.getMessage());
} catch (final RuntimeException e) {
log.error("AOP拦截到运行时异常", e);
if (StringUtils.isBlank(e.getMessage())) {
return new Ro<>(ResultDic.FAIL, "服务器出现运行时异常", null, "500", null);
}
else {
return new Ro<>(ResultDic.FAIL, "服务器出现运行时异常", e.getMessage(), "500", null);
}
} catch (final Throwable e) {
log.error("AOP拦截到未能识别的异常", e);
return new Ro<>(ResultDic.FAIL, "服务器出现未定义的异常,请联系管理员", e.getMessage(), "500", null);
}
}
}
| UTF-8 | Java | 4,608 | java | SubErrAopConfig.java | Java | []
| null | []
| package rebue.sbs.aop;
import java.sql.DataTruncation;
import java.sql.SQLIntegrityConstraintViolationException;
import javax.validation.ConstraintViolationException;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.dao.DuplicateKeyException;
import lombok.extern.slf4j.Slf4j;
import rebue.robotech.dic.ResultDic;
import rebue.robotech.ro.Ro;
import rebue.wheel.api.exception.RuntimeExceptionX;
/**
* SUB层异常拦截
*/
@Slf4j
@Aspect
@Configuration(proxyBeanMethods = false)
@Order(4)
public class SubErrAopConfig {
@Around("execution(public * *..sub..*Sub.*(..))")
public Object around(final ProceedingJoinPoint joinPoint) throws Throwable {
try {
return joinPoint.proceed();
} catch (final DuplicateKeyException e) {
log.error("AOP拦截到关键字重复的异常", e);
final String message = e.getCause().getMessage();
final int start = message.indexOf("'");
final int end = message.indexOf("'", start + 1) + 1;
return new Ro<>(ResultDic.WARN, message.substring(start, end) + "已存在");
} catch (final NumberFormatException e) {
log.error("AOP拦截到字符串转数值的异常", e);
final String[] errs = e.getMessage().split("\"");
return new Ro<>(ResultDic.PARAM_ERROR, "参数错误: \"" + errs[1] + "\"不是数值类型");
} catch (final IllegalArgumentException e) {
log.error("AOP拦截到参数错误的异常", e);
if (StringUtils.isBlank(e.getMessage())) {
return new Ro<>(ResultDic.PARAM_ERROR, "参数错误");
}
else {
return new Ro<>(ResultDic.PARAM_ERROR, "参数错误: " + e.getMessage());
}
} catch (final ConstraintViolationException e) {
log.error("AOP拦截到违反数据库约束的异常", e);
final String[] errs = e.getMessage().split(",");
final StringBuilder sb = new StringBuilder();
for (final String err : errs) {
sb.append(err.split(":")[1].trim() + ",");
}
return new Ro<>(ResultDic.PARAM_ERROR, sb.deleteCharAt(sb.length() - 1).toString());
} catch (final DataIntegrityViolationException e) {
log.error("AOP拦截到违反数据库完整性的异常", e);
final Throwable cause = e.getCause();
if (cause instanceof SQLIntegrityConstraintViolationException) {
return new Ro<>(ResultDic.WARN, "此操作违反了该字段作为外键、主键或唯一键的约束", cause.getMessage());
}
else if (cause instanceof DataTruncation) {
return new Ro<>(ResultDic.WARN, "此操作违反了该字段最大长度的约束", cause.getMessage());
}
else {
return new Ro<>(ResultDic.WARN, "此操作违反了数据库完整性的约束", cause.getMessage());
}
} catch (final NullPointerException e) {
log.error("AOP拦截到空指针异常", e);
if (StringUtils.isBlank(e.getMessage())) {
return new Ro<>(ResultDic.FAIL, "服务器出现空指针异常", null, "500", null);
}
else {
return new Ro<>(ResultDic.FAIL, "服务器出现空指针异常", e.getMessage(), "500", null);
}
} catch (final RuntimeExceptionX e) {
log.warn("AOP拦截到自定义的运行时异常", e);
return new Ro<>(ResultDic.WARN, e.getMessage());
} catch (final RuntimeException e) {
log.error("AOP拦截到运行时异常", e);
if (StringUtils.isBlank(e.getMessage())) {
return new Ro<>(ResultDic.FAIL, "服务器出现运行时异常", null, "500", null);
}
else {
return new Ro<>(ResultDic.FAIL, "服务器出现运行时异常", e.getMessage(), "500", null);
}
} catch (final Throwable e) {
log.error("AOP拦截到未能识别的异常", e);
return new Ro<>(ResultDic.FAIL, "服务器出现未定义的异常,请联系管理员", e.getMessage(), "500", null);
}
}
}
| 4,608 | 0.599371 | 0.593327 | 98 | 41.204082 | 27.00263 | 96 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.94898 | false | false | 1 |
fe58281ceab38153587a1d1e107b549929c31f78 | 8,684,423,929,276 | af23e3c7b66a7a695c126dfa945e50c11f763b21 | /service/src/test/java/com/epam/esm/service/validator/PageValidatorTest.java | 41eca84d78288fc409a88e6e2f57c64fd988c764 | []
| no_license | TimurRadko/rest-basics | https://github.com/TimurRadko/rest-basics | da78e05c32bed24a6feb1f0a514853907e2909a9 | 6df04678376d4b82fc2488da25d6e79c38ed67e4 | refs/heads/master | 2023-06-11T16:42:37.861000 | 2021-06-21T08:35:03 | 2021-06-21T08:35:03 | 350,985,608 | 1 | 0 | null | false | 2021-06-21T08:35:04 | 2021-03-24T07:29:35 | 2021-06-20T14:47:31 | 2021-06-21T08:35:03 | 969 | 0 | 0 | 0 | Java | false | false | package com.epam.esm.service.validator;
import com.epam.esm.service.dto.PageDto;
import com.epam.esm.service.locale.LocaleTranslator;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.when;
@ExtendWith(MockitoExtension.class)
class PageValidatorTest {
@Mock private LocaleTranslator localeTranslator;
@InjectMocks private PageValidator pageValidator;
private static final String NULL_PAGE_MESSAGE = "The page mustn't be null";
private static final String NULL_SIZE_MESSAGE = "The size mustn't be null";
private static final String NULL_PAGE_AND_SIZE_MESSAGE =
"The page mustn't be null\nThe size mustn't be null";
private static final String LESS_THAN_ZERO_PAGE_MESSAGE = "The page must be more than 0";
private static final String LESS_THAN_ZERO_SIZE_MESSAGE = "The size must be more than 0";
private PageDto pageDto;
@BeforeEach
void setUp() {
pageDto = new PageDto(1, 1);
pageValidator = new PageValidator(localeTranslator);
}
@Test
void testsValid_shouldReturnCorrectErrorMessage_whenPageIsNull() {
// given
pageDto.setPage(null);
// when
when(localeTranslator.toLocale(any())).thenReturn(NULL_PAGE_MESSAGE);
boolean actualIsValid = pageValidator.isValid(pageDto);
String actualErrorMessage = pageValidator.getErrorMessage();
// then
assertFalse(actualIsValid);
assertEquals(NULL_PAGE_MESSAGE, actualErrorMessage);
}
@Test
void testsValid_shouldReturnCorrectErrorMessage_whenSizeIsNull() {
// given
pageDto.setSize(null);
// when
when(localeTranslator.toLocale(any())).thenReturn(NULL_SIZE_MESSAGE);
boolean actualIsValid = pageValidator.isValid(pageDto);
String actualErrorMessage = pageValidator.getErrorMessage();
// then
assertFalse(actualIsValid);
assertEquals(NULL_SIZE_MESSAGE, actualErrorMessage);
}
@Test
void testsValid_shouldReturnCorrectErrorMessage_whenPageAndSizeIsNull() {
// given
pageDto.setPage(null);
pageDto.setSize(null);
// when
when(localeTranslator.toLocale("exception.message.pageNotNull")).thenReturn(NULL_PAGE_MESSAGE);
when(localeTranslator.toLocale("exception.message.sizeNotNull")).thenReturn(NULL_SIZE_MESSAGE);
boolean actualIsValid = pageValidator.isValid(pageDto);
String actualErrorMessage = pageValidator.getErrorMessage();
// then
assertFalse(actualIsValid);
assertEquals(NULL_PAGE_AND_SIZE_MESSAGE, actualErrorMessage);
}
@Test
void testsValid_shouldReturnCorrectErrorMessage_whenPageIsLessThanZero() {
// given
pageDto.setPage(-1);
// when
when(localeTranslator.toLocale(any())).thenReturn(LESS_THAN_ZERO_PAGE_MESSAGE);
boolean actualIsValid = pageValidator.isValid(pageDto);
String actualErrorMessage = pageValidator.getErrorMessage();
// then
assertFalse(actualIsValid);
assertEquals(LESS_THAN_ZERO_PAGE_MESSAGE, actualErrorMessage);
}
@Test
void testsValid_shouldReturnCorrectErrorMessage_whenSizeIsLessThanZero() {
// given
pageDto.setSize(-1);
// when
when(localeTranslator.toLocale(any())).thenReturn(LESS_THAN_ZERO_SIZE_MESSAGE);
boolean actualIsValid = pageValidator.isValid(pageDto);
String actualErrorMessage = pageValidator.getErrorMessage();
// then
assertFalse(actualIsValid);
assertEquals(LESS_THAN_ZERO_SIZE_MESSAGE, actualErrorMessage);
}
}
| UTF-8 | Java | 3,751 | java | PageValidatorTest.java | Java | []
| null | []
| package com.epam.esm.service.validator;
import com.epam.esm.service.dto.PageDto;
import com.epam.esm.service.locale.LocaleTranslator;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.when;
@ExtendWith(MockitoExtension.class)
class PageValidatorTest {
@Mock private LocaleTranslator localeTranslator;
@InjectMocks private PageValidator pageValidator;
private static final String NULL_PAGE_MESSAGE = "The page mustn't be null";
private static final String NULL_SIZE_MESSAGE = "The size mustn't be null";
private static final String NULL_PAGE_AND_SIZE_MESSAGE =
"The page mustn't be null\nThe size mustn't be null";
private static final String LESS_THAN_ZERO_PAGE_MESSAGE = "The page must be more than 0";
private static final String LESS_THAN_ZERO_SIZE_MESSAGE = "The size must be more than 0";
private PageDto pageDto;
@BeforeEach
void setUp() {
pageDto = new PageDto(1, 1);
pageValidator = new PageValidator(localeTranslator);
}
@Test
void testsValid_shouldReturnCorrectErrorMessage_whenPageIsNull() {
// given
pageDto.setPage(null);
// when
when(localeTranslator.toLocale(any())).thenReturn(NULL_PAGE_MESSAGE);
boolean actualIsValid = pageValidator.isValid(pageDto);
String actualErrorMessage = pageValidator.getErrorMessage();
// then
assertFalse(actualIsValid);
assertEquals(NULL_PAGE_MESSAGE, actualErrorMessage);
}
@Test
void testsValid_shouldReturnCorrectErrorMessage_whenSizeIsNull() {
// given
pageDto.setSize(null);
// when
when(localeTranslator.toLocale(any())).thenReturn(NULL_SIZE_MESSAGE);
boolean actualIsValid = pageValidator.isValid(pageDto);
String actualErrorMessage = pageValidator.getErrorMessage();
// then
assertFalse(actualIsValid);
assertEquals(NULL_SIZE_MESSAGE, actualErrorMessage);
}
@Test
void testsValid_shouldReturnCorrectErrorMessage_whenPageAndSizeIsNull() {
// given
pageDto.setPage(null);
pageDto.setSize(null);
// when
when(localeTranslator.toLocale("exception.message.pageNotNull")).thenReturn(NULL_PAGE_MESSAGE);
when(localeTranslator.toLocale("exception.message.sizeNotNull")).thenReturn(NULL_SIZE_MESSAGE);
boolean actualIsValid = pageValidator.isValid(pageDto);
String actualErrorMessage = pageValidator.getErrorMessage();
// then
assertFalse(actualIsValid);
assertEquals(NULL_PAGE_AND_SIZE_MESSAGE, actualErrorMessage);
}
@Test
void testsValid_shouldReturnCorrectErrorMessage_whenPageIsLessThanZero() {
// given
pageDto.setPage(-1);
// when
when(localeTranslator.toLocale(any())).thenReturn(LESS_THAN_ZERO_PAGE_MESSAGE);
boolean actualIsValid = pageValidator.isValid(pageDto);
String actualErrorMessage = pageValidator.getErrorMessage();
// then
assertFalse(actualIsValid);
assertEquals(LESS_THAN_ZERO_PAGE_MESSAGE, actualErrorMessage);
}
@Test
void testsValid_shouldReturnCorrectErrorMessage_whenSizeIsLessThanZero() {
// given
pageDto.setSize(-1);
// when
when(localeTranslator.toLocale(any())).thenReturn(LESS_THAN_ZERO_SIZE_MESSAGE);
boolean actualIsValid = pageValidator.isValid(pageDto);
String actualErrorMessage = pageValidator.getErrorMessage();
// then
assertFalse(actualIsValid);
assertEquals(LESS_THAN_ZERO_SIZE_MESSAGE, actualErrorMessage);
}
}
| 3,751 | 0.755798 | 0.754199 | 101 | 36.138615 | 28.134764 | 99 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.60396 | false | false | 1 |
f648d97017216ce928f65a5045b463d5dbfbf54a | 37,323,265,812,924 | c5c89c175e160cb9255d793cfdbe2911f1eb5553 | /team-calendar/src/main/java/intec/sli/iwstudy/teamcalendar/infrastructure/mybatis/EventRepository.java | cb49736bfb2b440d47b28b15ac8723ccf60ae362 | [
"GPL-1.0-or-later",
"GPL-3.0-only",
"MIT"
]
| permissive | yukung/playground | https://github.com/yukung/playground | f63553df03aa36243245b2ed3b98bafe4c328708 | 983f1b536207b92b7d7650f0002c1c340df301dd | refs/heads/master | 2021-01-20T20:35:50.069000 | 2017-12-23T00:17:06 | 2017-12-23T00:17:06 | 59,887,934 | 0 | 0 | MIT | false | 2017-12-23T00:17:07 | 2016-05-28T09:49:43 | 2016-06-02T04:37:08 | 2017-12-23T00:17:06 | 8,451 | 0 | 0 | 0 | JavaScript | false | null | /*
* Copyright (C) 2014 Yusuke Ikeda <yukung.i@gmail.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package intec.sli.iwstudy.teamcalendar.infrastructure.mybatis;
import intec.sli.iwstudy.teamcalendar.domain.model.Event;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
/**
* Event エンティティへの操作を行う Repository の MyBatis 実装です。
*
* @author yukung
*
*/
@Repository
public class EventRepository extends RepositoryMyBatisImpl<Integer, Event> {
@Autowired
private EventMapper eventMapper;
/**
* 全ての Event エンティティを取得します。
*
* @return Event Entity の List
*/
public List<Event> findAll() {
return eventMapper.findAll();
}
@Override
public Event find(Class<Event> entityClass, Integer id) {
return eventMapper.findById(id);
}
/**
* 全ての Event エンティティの数を取得します。
*
* @return 全ての Event Entity の数
*/
public int countAll() {
return eventMapper.countAll();
}
@Override
public Event persist(Event event) {
if (event == null) {
throw new IllegalArgumentException();
} else if (event.getText() == null && event.getFrom() == null && event.getTo() == null) {
throw new IllegalArgumentException();
}
int count = 0;
if (event.getId() == null) {
count = eventMapper.insert(event);
} else {
count = eventMapper.update(event);
}
if (count == 0) {
return null;
}
return event;
}
@Override
public void remove(Event event) {
if (event == null || event.getId() == null) {
throw new IllegalArgumentException();
}
eventMapper.delete(event);
}
}
| UTF-8 | Java | 2,331 | java | EventRepository.java | Java | [
{
"context": "/*\n * Copyright (C) 2014 Yusuke Ikeda <yukung.i@gmail.com>\n *\n * This program is free s",
"end": 37,
"score": 0.999875545501709,
"start": 25,
"tag": "NAME",
"value": "Yusuke Ikeda"
},
{
"context": "/*\n * Copyright (C) 2014 Yusuke Ikeda <yukung.i@gmail.com>\n *\n * This program is free software: you can red",
"end": 57,
"score": 0.9999287128448486,
"start": 39,
"tag": "EMAIL",
"value": "yukung.i@gmail.com"
},
{
"context": "ィへの操作を行う Repository の MyBatis 実装です。\n * \n * @author yukung\n *\n */\n@Repository\npublic class EventRepository e",
"end": 1048,
"score": 0.8209589123725891,
"start": 1042,
"tag": "USERNAME",
"value": "yukung"
}
]
| null | []
| /*
* Copyright (C) 2014 <NAME> <<EMAIL>>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package intec.sli.iwstudy.teamcalendar.infrastructure.mybatis;
import intec.sli.iwstudy.teamcalendar.domain.model.Event;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
/**
* Event エンティティへの操作を行う Repository の MyBatis 実装です。
*
* @author yukung
*
*/
@Repository
public class EventRepository extends RepositoryMyBatisImpl<Integer, Event> {
@Autowired
private EventMapper eventMapper;
/**
* 全ての Event エンティティを取得します。
*
* @return Event Entity の List
*/
public List<Event> findAll() {
return eventMapper.findAll();
}
@Override
public Event find(Class<Event> entityClass, Integer id) {
return eventMapper.findById(id);
}
/**
* 全ての Event エンティティの数を取得します。
*
* @return 全ての Event Entity の数
*/
public int countAll() {
return eventMapper.countAll();
}
@Override
public Event persist(Event event) {
if (event == null) {
throw new IllegalArgumentException();
} else if (event.getText() == null && event.getFrom() == null && event.getTo() == null) {
throw new IllegalArgumentException();
}
int count = 0;
if (event.getId() == null) {
count = eventMapper.insert(event);
} else {
count = eventMapper.update(event);
}
if (count == 0) {
return null;
}
return event;
}
@Override
public void remove(Event event) {
if (event == null || event.getId() == null) {
throw new IllegalArgumentException();
}
eventMapper.delete(event);
}
}
| 2,314 | 0.702666 | 0.699503 | 88 | 24.147728 | 24.317755 | 91 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.238636 | false | false | 4 |
369b871c1cbfb0920b9fd4ed723d66e542e29da9 | 35,656,818,508,716 | d79c33e43be9b8edf33b507c6213963319e5b54c | /src/java/lec05/SprinterDAO.java | d7cca8879473daf00e81f7db3de03b14b4020770 | []
| no_license | cist-b213-t-kato/ISD | https://github.com/cist-b213-t-kato/ISD | d362ddf0c74aab4e124189eb19ea79fba2b4452d | d0d9bf4a016268d5b0d2b0c38839cfdada5c3ea4 | refs/heads/master | 2021-01-10T13:41:43.038000 | 2016-01-20T16:12:18 | 2016-01-20T16:12:18 | 48,285,255 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package lec05;
import lec04.DBSetting;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import lec01.Sprinter;
public class SprinterDAO {
public SprinterDAO() throws ClassNotFoundException {
// Webアプリケーション(Tomcat)でDBを動作させるアプリケーションでは、ドライバのロードが必要
Class.forName("org.apache.derby.jdbc.ClientDriver");
}
public static void main(String[] args) throws SQLException{
try {
SprinterDAO dao = new SprinterDAO();
Sprinter sprinter = new Sprinter(1,"1","1",1);
// dao.insertSprinter(sprinter);
// dao.deleteSprinter(2);
dao.updateSprinter(sprinter);
List<Sprinter> sprinters = dao.selectSprinters();
sprinters.stream().forEach(System.out::println);
} catch (ClassNotFoundException ex) {
Logger.getLogger(SprinterDAO.class.getName()).log(Level.SEVERE, null, ex);
}
}
// データベースのsprinterテーブルにSprinterオブジェクトのレコードをinsertする
public int insertSprinter(Sprinter insertObject) throws SQLException {
String sql = "insert into sprinter"
+ " values ("
+ insertObject.getZeichen() + ","
+ "'" + insertObject.getFamilyName() + "'" + ","
+ "'" + insertObject.getGivenName() + "'" + ","
+ insertObject.getBestTime()
+ ")";
int returning = 0;
try(Connection conn = DriverManager.getConnection(DBSetting.URL, DBSetting.USER, DBSetting.PASS)){
try(Statement stmt = conn.createStatement()) {
returning = stmt.executeUpdate(sql);
}
}
System.out.println("追加行数:"+returning);
return returning;
}
// データベースのsprinterテーブルから全レコードをSprinterオブジェクトのListで取得する
public List<Sprinter> selectSprinters() throws SQLException {
String sql = "select * from sprinter order by zeichen asc";
List<Sprinter> sprinters = new ArrayList<>();
try(Connection conn
= DriverManager.getConnection(DBSetting.URL, DBSetting.USER, DBSetting.PASS)){
try(Statement stmt = conn.createStatement()){
ResultSet results = stmt.executeQuery(sql);
while(results.next()){
sprinters.add(new Sprinter(
results.getInt("zeichen"),
results.getString("familyname"),
results.getString("givenname"),
results.getInt("besttime"))
);
}
}
}
return sprinters;
}
// データベースのsprinterテーブルから、ゼッケン番号のレコードを削除する
public int deleteSprinter(int deleteZeichen) throws SQLException {
String sql = "delete from sprinter where zeichen = "+ deleteZeichen +"";
int returning = 0;
try(Connection conn = DriverManager.getConnection(DBSetting.URL, DBSetting.USER, DBSetting.PASS)){
try(Statement stmt = conn.createStatement()) {
returning = stmt.executeUpdate(sql);
}
}
System.out.println("削除行数:"+returning);
return 0;
}
// データベースのsprinterテーブルで、ゼッケン番号を元にレコードの属性を更新する
public int updateSprinter(Sprinter updateObject) throws SQLException {
String sql = String.format(
"update sprinter set "
+ "ZEICHEN = %d,"
+ "FAMILYNAME = '%s',"
+ "GIVENNAME = '%s',"
+ "BESTTIME = %d "
+ "where zeichen = %s",
updateObject.getZeichen(),
updateObject.getFamilyName(),
updateObject.getGivenName(),
updateObject.getBestTime(),
updateObject.getZeichen()
);
int returning = 0;
try(Connection conn = DriverManager.getConnection(DBSetting.URL, DBSetting.USER, DBSetting.PASS)){
try(Statement stmt = conn.createStatement()) {
returning = stmt.executeUpdate(sql);
}
}
System.out.println("変更行数:"+returning);
return 0;
}
}
| UTF-8 | Java | 4,784 | java | SprinterDAO.java | Java | []
| null | []
| package lec05;
import lec04.DBSetting;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import lec01.Sprinter;
public class SprinterDAO {
public SprinterDAO() throws ClassNotFoundException {
// Webアプリケーション(Tomcat)でDBを動作させるアプリケーションでは、ドライバのロードが必要
Class.forName("org.apache.derby.jdbc.ClientDriver");
}
public static void main(String[] args) throws SQLException{
try {
SprinterDAO dao = new SprinterDAO();
Sprinter sprinter = new Sprinter(1,"1","1",1);
// dao.insertSprinter(sprinter);
// dao.deleteSprinter(2);
dao.updateSprinter(sprinter);
List<Sprinter> sprinters = dao.selectSprinters();
sprinters.stream().forEach(System.out::println);
} catch (ClassNotFoundException ex) {
Logger.getLogger(SprinterDAO.class.getName()).log(Level.SEVERE, null, ex);
}
}
// データベースのsprinterテーブルにSprinterオブジェクトのレコードをinsertする
public int insertSprinter(Sprinter insertObject) throws SQLException {
String sql = "insert into sprinter"
+ " values ("
+ insertObject.getZeichen() + ","
+ "'" + insertObject.getFamilyName() + "'" + ","
+ "'" + insertObject.getGivenName() + "'" + ","
+ insertObject.getBestTime()
+ ")";
int returning = 0;
try(Connection conn = DriverManager.getConnection(DBSetting.URL, DBSetting.USER, DBSetting.PASS)){
try(Statement stmt = conn.createStatement()) {
returning = stmt.executeUpdate(sql);
}
}
System.out.println("追加行数:"+returning);
return returning;
}
// データベースのsprinterテーブルから全レコードをSprinterオブジェクトのListで取得する
public List<Sprinter> selectSprinters() throws SQLException {
String sql = "select * from sprinter order by zeichen asc";
List<Sprinter> sprinters = new ArrayList<>();
try(Connection conn
= DriverManager.getConnection(DBSetting.URL, DBSetting.USER, DBSetting.PASS)){
try(Statement stmt = conn.createStatement()){
ResultSet results = stmt.executeQuery(sql);
while(results.next()){
sprinters.add(new Sprinter(
results.getInt("zeichen"),
results.getString("familyname"),
results.getString("givenname"),
results.getInt("besttime"))
);
}
}
}
return sprinters;
}
// データベースのsprinterテーブルから、ゼッケン番号のレコードを削除する
public int deleteSprinter(int deleteZeichen) throws SQLException {
String sql = "delete from sprinter where zeichen = "+ deleteZeichen +"";
int returning = 0;
try(Connection conn = DriverManager.getConnection(DBSetting.URL, DBSetting.USER, DBSetting.PASS)){
try(Statement stmt = conn.createStatement()) {
returning = stmt.executeUpdate(sql);
}
}
System.out.println("削除行数:"+returning);
return 0;
}
// データベースのsprinterテーブルで、ゼッケン番号を元にレコードの属性を更新する
public int updateSprinter(Sprinter updateObject) throws SQLException {
String sql = String.format(
"update sprinter set "
+ "ZEICHEN = %d,"
+ "FAMILYNAME = '%s',"
+ "GIVENNAME = '%s',"
+ "BESTTIME = %d "
+ "where zeichen = %s",
updateObject.getZeichen(),
updateObject.getFamilyName(),
updateObject.getGivenName(),
updateObject.getBestTime(),
updateObject.getZeichen()
);
int returning = 0;
try(Connection conn = DriverManager.getConnection(DBSetting.URL, DBSetting.USER, DBSetting.PASS)){
try(Statement stmt = conn.createStatement()) {
returning = stmt.executeUpdate(sql);
}
}
System.out.println("変更行数:"+returning);
return 0;
}
}
| 4,784 | 0.566667 | 0.563063 | 122 | 35.393444 | 25.239689 | 106 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.557377 | false | false | 4 |
4827f6e6d9e55a609fd9950961741fc216533b77 | 27,874,337,809,257 | 4efd04835eda5a73953e389781b9c23bed5c0a9e | /trunk/src/lff/jtxt2pdf/FontOption.java | f8db9c4ac0b06a7f76dc5744b306bc6fd9beeef0 | []
| no_license | BackupTheBerlios/jtxt2pdf-svn | https://github.com/BackupTheBerlios/jtxt2pdf-svn | 3a08f21c0540f0c3aca571d6035a6063606d7dd4 | 66d782b8a64ce721018fd1f1fb2601c89d9bc998 | refs/heads/master | 2021-03-12T20:07:29.143000 | 2009-12-30T07:26:57 | 2009-12-30T07:26:57 | 40,824,389 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package lff.jtxt2pdf;
public class FontOption {
private boolean isBold = false;
private String font = null;
private int style;
private int size;
public FontOption() {
font = "C:/windows/fonts/arial.ttf";
size = 10;
style = 0;
}
}
| UTF-8 | Java | 270 | java | FontOption.java | Java | []
| null | []
| package lff.jtxt2pdf;
public class FontOption {
private boolean isBold = false;
private String font = null;
private int style;
private int size;
public FontOption() {
font = "C:/windows/fonts/arial.ttf";
size = 10;
style = 0;
}
}
| 270 | 0.618519 | 0.603704 | 18 | 13 | 12.34234 | 38 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.333333 | false | false | 4 |
a2c14e63af0d772d0c79ba40bbd908cf9b9a39ac | 28,887,950,036,114 | ec7cdb58fa20e255c23bc855738d842ee573858f | /java/defpackage/ac$1.java | 2f3e5c0b1e43996cd63c9668ccafae959d8c9c9b | []
| no_license | BeCandid/JaDX | https://github.com/BeCandid/JaDX | 591e0abee58764b0f58d1883de9324bf43b52c56 | 9a3fa0e7c14a35bc528d0b019f850b190a054c3f | refs/heads/master | 2021-01-13T11:23:00.068000 | 2016-12-24T10:39:48 | 2016-12-24T10:39:48 | 77,222,067 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package defpackage;
/* compiled from: ValueAnimatorCompatImplEclairMr1 */
class ac$1 implements Runnable {
final /* synthetic */ ac a;
ac$1(ac acVar) {
this.a = acVar;
}
public void run() {
this.a.h();
}
}
| UTF-8 | Java | 245 | java | ac$1.java | Java | []
| null | []
| package defpackage;
/* compiled from: ValueAnimatorCompatImplEclairMr1 */
class ac$1 implements Runnable {
final /* synthetic */ ac a;
ac$1(ac acVar) {
this.a = acVar;
}
public void run() {
this.a.h();
}
}
| 245 | 0.583673 | 0.571429 | 14 | 16.5 | 15.150436 | 53 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.285714 | false | false | 4 |
d1d725eefcd9c838a23c713d123bbf4627448597 | 23,502,061,049,205 | f9701a5e0221031639224bb3314d5b23f9305790 | /src/smple/sample/DisplayState.java | 49144c28f89a2d36bd39ba26ab888ba986ced7e8 | []
| no_license | kamilo116/image_poll_displayer | https://github.com/kamilo116/image_poll_displayer | 5fe1f9e8a3e72a86c3ea4a352c7acc75987060ea | a2e9d937b4ce00e0af503b6694c3061b3be682c2 | refs/heads/master | 2020-03-12T18:00:18.450000 | 2018-09-04T21:44:47 | 2018-09-04T21:44:47 | 130,750,802 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package sample;
interface DisplayState{
void switchImage(DisplayImagePoll imagePollApp);
String getState();
}
| UTF-8 | Java | 119 | java | DisplayState.java | Java | []
| null | []
| package sample;
interface DisplayState{
void switchImage(DisplayImagePoll imagePollApp);
String getState();
}
| 119 | 0.764706 | 0.764706 | 6 | 18.833334 | 17.391729 | 52 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 4 |
a8fdf1f0622e8818c84e9d50aebfc91aa9349056 | 13,228,499,335,951 | b956bbe5c78c3de89a09d061a9899caf4f462fc7 | /gh/WEB-INF/classes/EditProfile1.java | 7d9da03ac5d7e328a95d38712edf9f3501090d77 | []
| no_license | swekeerthi/HotelManagement | https://github.com/swekeerthi/HotelManagement | 8b4683e93237efce078c83579e59261464b9fb3c | 470df248e7145c7e080cf9f4663f39bde0e57a1b | refs/heads/master | 2021-01-19T05:58:12.467000 | 2016-08-13T02:18:50 | 2016-08-13T02:18:50 | 65,594,629 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class EditProfile1 extends HttpServlet
{
public void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
{
String UserID=(String)req.getSession().getAttribute("UserID");
com.eResorts.EditProfileBean1 bean=new com.eResorts.EditProfileBean1 ();
String FirstName=req.getParameter("FirstName");
String LastName=req.getParameter("LastName");
String Age=req.getParameter("Age");
String EmailAddress=req.getParameter("EmailAddress");
String Address=req.getParameter("Address");
String ContactNumber=req.getParameter("ContactNumber");
String Occupation=req.getParameter("Occupation");
int flag=bean.edit(UserID,FirstName,LastName,Age,EmailAddress,Address,ContactNumber,Occupation);
System.out.println("it is servlet edituserprofile1 servlet");
req.getSession().setAttribute("flag", new Integer(flag));
getServletContext().getRequestDispatcher("/EditUserProfile1.jsp").forward(req,resp);
}// service()
}// class
| UTF-8 | Java | 1,042 | java | EditProfile1.java | Java | []
| null | []
| import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class EditProfile1 extends HttpServlet
{
public void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
{
String UserID=(String)req.getSession().getAttribute("UserID");
com.eResorts.EditProfileBean1 bean=new com.eResorts.EditProfileBean1 ();
String FirstName=req.getParameter("FirstName");
String LastName=req.getParameter("LastName");
String Age=req.getParameter("Age");
String EmailAddress=req.getParameter("EmailAddress");
String Address=req.getParameter("Address");
String ContactNumber=req.getParameter("ContactNumber");
String Occupation=req.getParameter("Occupation");
int flag=bean.edit(UserID,FirstName,LastName,Age,EmailAddress,Address,ContactNumber,Occupation);
System.out.println("it is servlet edituserprofile1 servlet");
req.getSession().setAttribute("flag", new Integer(flag));
getServletContext().getRequestDispatcher("/EditUserProfile1.jsp").forward(req,resp);
}// service()
}// class
| 1,042 | 0.792706 | 0.787908 | 25 | 40.599998 | 30.303795 | 106 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.24 | false | false | 4 |
11f405ca0c8f434e0e50ab750ef80c4198475c59 | 5,995,774,411,399 | 34063e13af7e0ca4fc022dbc2ef54778b7e3afec | /src/main/java/com/example/jdbcpoc/CircuitBreakerHystrixEventNotifier.java | 651c01b260abdd3df773928649348c551cd797b6 | []
| no_license | MathewsTito/jdbcpoc | https://github.com/MathewsTito/jdbcpoc | 1e229fdaf5ce372d077541a2dd03c0155ec3bde2 | 36ffd81cae8e5d3c1534db6fcc4e6049a7b56a78 | refs/heads/master | 2020-03-28T20:25:09.007000 | 2018-11-15T05:31:43 | 2018-11-15T05:31:43 | 149,068,100 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.jdbcpoc;
import com.netflix.hystrix.HystrixCommandKey;
import com.netflix.hystrix.HystrixEventType;
import com.netflix.hystrix.strategy.eventnotifier.HystrixEventNotifier;
public class CircuitBreakerHystrixEventNotifier extends HystrixEventNotifier{
public void markEvent(HystrixEventType eventType, HystrixCommandKey key) {
System.out.println("**WARNING** Hystrix Event Occured "+ eventType.toString());
}
}
| UTF-8 | Java | 449 | java | CircuitBreakerHystrixEventNotifier.java | Java | []
| null | []
| package com.example.jdbcpoc;
import com.netflix.hystrix.HystrixCommandKey;
import com.netflix.hystrix.HystrixEventType;
import com.netflix.hystrix.strategy.eventnotifier.HystrixEventNotifier;
public class CircuitBreakerHystrixEventNotifier extends HystrixEventNotifier{
public void markEvent(HystrixEventType eventType, HystrixCommandKey key) {
System.out.println("**WARNING** Hystrix Event Occured "+ eventType.toString());
}
}
| 449 | 0.806236 | 0.806236 | 13 | 33.53846 | 33.708286 | 87 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.461538 | false | false | 4 |
152507108c8aca5649eb17abe6f059570f5b5b86 | 31,439,160,669,352 | 1daa675860ff13a544c6bd74851ae5d6f8ba47fa | /Android/Work/part2.component/ad23-05.CustomListView/st3checkablelistview/src/main/java/com/example/checkablelistview/AdapterPerson.java | ce4c52f44a01796a250d356d5029d336c5ee305a | []
| no_license | kaevin1004/java-- | https://github.com/kaevin1004/java-- | 6d90a7613402e8e839a7c0dfa4f6b43681dde12e | 2de34eaf445b7d0946430bcc31d38be8fd5598dd | refs/heads/master | 2021-09-12T11:16:44.211000 | 2018-01-26T09:08:41 | 2018-01-26T09:08:41 | 103,893,846 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.checkablelistview;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import java.util.List;
/**
* Created by Administrator on 2018-01-05.
*/
public class AdapterPerson extends ArrayAdapter<ModelPerson> {
private final Context context;
public AdapterPerson(@NonNull Context context, int resource, @NonNull List<ModelPerson> objects) {
super(context, resource, objects);
this.context = context;
}
@NonNull
@Override
public View getView(final int position, @Nullable View convertView, @NonNull ViewGroup parent) {
ViewPerson view = null;
if( convertView == null ){
view = new ViewPerson( context );
}
else {
view = (ViewPerson) convertView;
view.setOnCheckedChangedListener(new ViewPerson.OnCheckedChangedListener() {
@Override
public void onCheckedChanged(ViewPerson checkableView, ModelPerson person) {
ModelPerson person1 = getItem(position);
person1 = person;
}
});
}
// ViewPerson 인스턴스에 값 설정
view.setPerson( getItem(position) );
return view;
}
/*
// 인터페이스 정의
public static interface OnCheckedChangedListener {
void onCheckedChanged(AdapterPerson adapter, ViewPerson checkableView, ModelPerson person);
}
// 인터페이스 리스너 선언
private OnCheckedChangedListener adapterListener;
public void setOnCheckedChangedListener( OnCheckedChangedListener listener ) {
this.adapterListener = listener;
}
@Override
public void onCheckedChanged(ViewPerson checkableView, ModelPerson person) {
if( adapterListener != null) {
adapterListener.onCheckedChanged(this, checkableView, person);
}
}*/
}
| UTF-8 | Java | 2,051 | java | AdapterPerson.java | Java | [
{
"context": "dapter;\n\nimport java.util.List;\n\n/**\n * Created by Administrator on 2018-01-05.\n */\n\npublic class AdapterPerson ex",
"end": 308,
"score": 0.7431544065475464,
"start": 295,
"tag": "USERNAME",
"value": "Administrator"
}
]
| null | []
| package com.example.checkablelistview;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import java.util.List;
/**
* Created by Administrator on 2018-01-05.
*/
public class AdapterPerson extends ArrayAdapter<ModelPerson> {
private final Context context;
public AdapterPerson(@NonNull Context context, int resource, @NonNull List<ModelPerson> objects) {
super(context, resource, objects);
this.context = context;
}
@NonNull
@Override
public View getView(final int position, @Nullable View convertView, @NonNull ViewGroup parent) {
ViewPerson view = null;
if( convertView == null ){
view = new ViewPerson( context );
}
else {
view = (ViewPerson) convertView;
view.setOnCheckedChangedListener(new ViewPerson.OnCheckedChangedListener() {
@Override
public void onCheckedChanged(ViewPerson checkableView, ModelPerson person) {
ModelPerson person1 = getItem(position);
person1 = person;
}
});
}
// ViewPerson 인스턴스에 값 설정
view.setPerson( getItem(position) );
return view;
}
/*
// 인터페이스 정의
public static interface OnCheckedChangedListener {
void onCheckedChanged(AdapterPerson adapter, ViewPerson checkableView, ModelPerson person);
}
// 인터페이스 리스너 선언
private OnCheckedChangedListener adapterListener;
public void setOnCheckedChangedListener( OnCheckedChangedListener listener ) {
this.adapterListener = listener;
}
@Override
public void onCheckedChanged(ViewPerson checkableView, ModelPerson person) {
if( adapterListener != null) {
adapterListener.onCheckedChanged(this, checkableView, person);
}
}*/
}
| 2,051 | 0.663168 | 0.658171 | 68 | 28.42647 | 28.411015 | 102 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.514706 | false | false | 4 |
7057f89a0e98e88c142c507bc80e2dd3ffb26d74 | 19,018,115,188,380 | 758af9145139807fec155e1ebae1edef4bff06a8 | /project-aop/src/main/java/com/pers/guofucheng/aop/constant/OperationType.java | 1f992b0bff62ec5d3115f39b22bfd85bf0dadcb0 | []
| no_license | Guofucheng0822/spring-boot-demo | https://github.com/Guofucheng0822/spring-boot-demo | 1a8a9ece7fdf2a7bad1146e01542ec0ad1fe2de9 | d745add490e44a40138d28189ed59b6610e3f5bf | refs/heads/master | 2022-12-25T00:24:13.872000 | 2021-10-28T10:09:40 | 2021-10-28T10:09:40 | 229,427,076 | 2 | 0 | null | false | 2022-12-16T05:12:21 | 2019-12-21T12:52:38 | 2021-10-28T10:10:26 | 2022-12-16T05:12:18 | 244 | 1 | 0 | 12 | Java | false | false | package com.pers.guofucheng.aop.constant;
/**
* @author guofucheng
*/
public enum OperationType {
INSERT(1,"新增"),
DELETE(2,"删除"),
SELECT(3,"查询"),
UPDATE(4,"修改");
private Integer index;
private String name;
OperationType(Integer index, String name) {
this.index = index;
this.name = name;
}
public Integer getIndex() {
return index;
}
public void setIndex(Integer index) {
this.index = index;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
| UTF-8 | Java | 629 | java | OperationType.java | Java | [
{
"context": " com.pers.guofucheng.aop.constant;\n\n/**\n * @author guofucheng\n */\n\npublic enum OperationType {\n INSERT(1,\"新增",
"end": 68,
"score": 0.9978556036949158,
"start": 58,
"tag": "USERNAME",
"value": "guofucheng"
}
]
| null | []
| package com.pers.guofucheng.aop.constant;
/**
* @author guofucheng
*/
public enum OperationType {
INSERT(1,"新增"),
DELETE(2,"删除"),
SELECT(3,"查询"),
UPDATE(4,"修改");
private Integer index;
private String name;
OperationType(Integer index, String name) {
this.index = index;
this.name = name;
}
public Integer getIndex() {
return index;
}
public void setIndex(Integer index) {
this.index = index;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
| 629 | 0.572594 | 0.566069 | 35 | 16.514286 | 13.970114 | 47 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.514286 | false | false | 4 |
e425dc236f91f38de6717eccc6092d3e89623de3 | 24,223,615,595,523 | 2f7a5ccc6ef9900ac4c5d84ed9b1dd374cef9ca3 | /SwitchExample.java | 0c97a07dcc3fdf060dbe0ec65f4c6563f079ea7a | []
| no_license | Squirrelbear/CP1Extras | https://github.com/Squirrelbear/CP1Extras | eefaace6ec94aed8d0a30cb248aba5e4afc80d33 | 516972a1ed7575f8606b4475bcd00b5ed9db1e1a | refs/heads/main | 2023-08-26T03:17:17.087000 | 2021-11-04T05:39:57 | 2021-11-04T05:39:57 | 349,670,001 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package Examples;
import java.util.Scanner;
public class SwitchExample {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter some text: ");
String input = scan.nextLine();
// switch based on the last character's value
char lastChar = input.charAt(input.length()-1);
switch(lastChar) {
case 'y':
System.out.println("Why so serious?");
break;
case 'b':
System.out.println("Be happy!");
break;
case '1':
case '2':
System.out.println("12121212");
break;
default:
System.out.println(lastChar + " was not important.");
break;
}
}
}
| UTF-8 | Java | 832 | java | SwitchExample.java | Java | []
| null | []
| package Examples;
import java.util.Scanner;
public class SwitchExample {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter some text: ");
String input = scan.nextLine();
// switch based on the last character's value
char lastChar = input.charAt(input.length()-1);
switch(lastChar) {
case 'y':
System.out.println("Why so serious?");
break;
case 'b':
System.out.println("Be happy!");
break;
case '1':
case '2':
System.out.println("12121212");
break;
default:
System.out.println(lastChar + " was not important.");
break;
}
}
}
| 832 | 0.497596 | 0.484375 | 28 | 28.714285 | 18.134138 | 69 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 4 |
0a592138a719379edbe974de24343b821366a62c | 541,165,895,708 | 886992e3e7c7bc9d6dea63562730e27df9f92642 | /odoo-android-framework/app/src/main/java/com/cuuuurzel/odoo/base/addons/product/ProductProduct.java | d2a636a4505e4ab5fced35e8e2c2a8741da66eed | []
| no_license | curzel-it/odoo-android-framework | https://github.com/curzel-it/odoo-android-framework | 1a0c5d4843c41c34302d600d8a9059daf9cb157a | a2f3eae293a7f774e69ad02d006d24ddd72d7ca1 | refs/heads/master | 2021-01-15T10:05:30.777000 | 2015-05-16T23:13:53 | 2015-05-16T23:13:53 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.odoo.base.addons.product;
import android.content.Context;
import android.net.Uri;
import com.odoo.core.orm.OModel;
import com.odoo.core.orm.fields.OColumn;
import com.odoo.core.orm.fields.types.OBlob;
import com.odoo.core.orm.fields.types.OBoolean;
import com.odoo.core.orm.fields.types.OFloat;
import com.odoo.core.orm.fields.types.OInteger;
import com.odoo.core.orm.fields.types.OVarchar;
import com.odoo.core.support.OUser;
/**
* Created by Cuuuurzel on 16/05/15.
*/
public class ProductProduct extends OModel {
public static final String AUTHORITY = "com.odoo.core.provider.content.sync.product_product";
//OColumn uom_id = new OColumn( "uom id", ProductUom.class, OColumn.RelationType.ManyToOne);
//OColumn categ_id = new OColumn("categ id", ProductCategory.class, OColumn.RelationType.ManyToOne);
OColumn default_code = new OColumn( "DefaultCode", OVarchar.class ).setRequired();
OColumn description = new OColumn( "Description", OVarchar.class ).setRequired();
OColumn ean13 = new OColumn( "EAN13", OVarchar.class ).setRequired();
OColumn list_price = new OColumn( "list price", OFloat.class ).setRequired();
OColumn name = new OColumn( "Name", OVarchar.class ).setRequired();
OColumn qty_available = new OColumn( "qty available", OFloat.class ).setRequired();
OColumn sale_ok = new OColumn( "sale ok", OBoolean.class ).setRequired();;
OColumn code = new OColumn( "code", OVarchar.class ).setRequired();
OColumn image = new OColumn( "Image", OBlob.class );
OColumn categ_id = new OColumn( "categ_id", ProductCategory.class, OColumn.RelationType.ManyToOne );
Context mContext;
OUser mUser;
public ProductProduct(Context context, OUser user) {
super(context, "product.product", user);
setHasMailChatter(false);
this.mContext = context;
this.mUser = user;
}
@Override
public Uri uri() {
return buildURI(AUTHORITY);
}
}
| UTF-8 | Java | 2,071 | java | ProductProduct.java | Java | [
{
"context": "rt com.odoo.core.support.OUser;\n\n/**\n * Created by Cuuuurzel on 16/05/15.\n */\npublic class ProductProduct exte",
"end": 469,
"score": 0.9979454874992371,
"start": 460,
"tag": "USERNAME",
"value": "Cuuuurzel"
}
]
| null | []
| package com.odoo.base.addons.product;
import android.content.Context;
import android.net.Uri;
import com.odoo.core.orm.OModel;
import com.odoo.core.orm.fields.OColumn;
import com.odoo.core.orm.fields.types.OBlob;
import com.odoo.core.orm.fields.types.OBoolean;
import com.odoo.core.orm.fields.types.OFloat;
import com.odoo.core.orm.fields.types.OInteger;
import com.odoo.core.orm.fields.types.OVarchar;
import com.odoo.core.support.OUser;
/**
* Created by Cuuuurzel on 16/05/15.
*/
public class ProductProduct extends OModel {
public static final String AUTHORITY = "com.odoo.core.provider.content.sync.product_product";
//OColumn uom_id = new OColumn( "uom id", ProductUom.class, OColumn.RelationType.ManyToOne);
//OColumn categ_id = new OColumn("categ id", ProductCategory.class, OColumn.RelationType.ManyToOne);
OColumn default_code = new OColumn( "DefaultCode", OVarchar.class ).setRequired();
OColumn description = new OColumn( "Description", OVarchar.class ).setRequired();
OColumn ean13 = new OColumn( "EAN13", OVarchar.class ).setRequired();
OColumn list_price = new OColumn( "list price", OFloat.class ).setRequired();
OColumn name = new OColumn( "Name", OVarchar.class ).setRequired();
OColumn qty_available = new OColumn( "qty available", OFloat.class ).setRequired();
OColumn sale_ok = new OColumn( "sale ok", OBoolean.class ).setRequired();;
OColumn code = new OColumn( "code", OVarchar.class ).setRequired();
OColumn image = new OColumn( "Image", OBlob.class );
OColumn categ_id = new OColumn( "categ_id", ProductCategory.class, OColumn.RelationType.ManyToOne );
Context mContext;
OUser mUser;
public ProductProduct(Context context, OUser user) {
super(context, "product.product", user);
setHasMailChatter(false);
this.mContext = context;
this.mUser = user;
}
@Override
public Uri uri() {
return buildURI(AUTHORITY);
}
}
| 2,071 | 0.67745 | 0.672622 | 50 | 40.400002 | 34.64275 | 104 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1 | false | false | 4 |
62028366281542919bb396d2f18bb795835e8da0 | 541,165,897,367 | 16af6a50604f269d9a851de74035c43867d58d7d | /Arduinobluetoothcontroller_v1.3_apkpure.com_source_from_JADX/android/support/design/widget/af.java | f7ef03aafd03bf7a6f6e0f78a6032b6d28b3d1c4 | []
| no_license | Siva6261/prescription-system-with-firebird-5 | https://github.com/Siva6261/prescription-system-with-firebird-5 | 3c63079d6a726628390ace4366481cbb4fe7094b | 8db690548809c65d3893922c5653acadb726c106 | refs/heads/master | 2020-03-22T13:15:41.392000 | 2018-07-07T15:43:10 | 2018-07-07T15:43:10 | 140,094,787 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package android.support.design.widget;
import android.view.ViewTreeObserver.OnPreDrawListener;
class af implements OnPreDrawListener {
final /* synthetic */ CoordinatorLayout f322a;
af(CoordinatorLayout coordinatorLayout) {
this.f322a = coordinatorLayout;
}
public boolean onPreDraw() {
this.f322a.m413a(false);
return true;
}
}
| UTF-8 | Java | 377 | java | af.java | Java | []
| null | []
| package android.support.design.widget;
import android.view.ViewTreeObserver.OnPreDrawListener;
class af implements OnPreDrawListener {
final /* synthetic */ CoordinatorLayout f322a;
af(CoordinatorLayout coordinatorLayout) {
this.f322a = coordinatorLayout;
}
public boolean onPreDraw() {
this.f322a.m413a(false);
return true;
}
}
| 377 | 0.70557 | 0.67374 | 16 | 22.5625 | 19.984272 | 55 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.375 | false | false | 4 |
7b603404e59f5edd972d325a08e8e4e18d8b3012 | 21,414,706,991,555 | 4ce8d5eadec1c3287bd091ea3741b079ae782850 | /firstproject/src/main/java/com/store/manager/Train.java | 69422981e11329a8ffebeccbdac3196248b296c2 | []
| no_license | ilyass-hisoka/firstproject | https://github.com/ilyass-hisoka/firstproject | 6efa83f5fec3e9beefa82d4c32688aa9fba23997 | 0760590bdcf7132520c59850fa4616271f1e3cdc | refs/heads/master | 2023-03-14T06:41:55.627000 | 2021-03-05T08:13:50 | 2021-03-05T08:13:50 | 343,776,045 | 0 | 0 | null | false | 2021-03-05T08:13:50 | 2021-03-02T13:01:20 | 2021-03-03T21:22:44 | 2021-03-05T08:13:50 | 33 | 0 | 0 | 0 | Java | false | false | package com.store.manager;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
public class Train {
private List<Wagon> wagons ;
public Train(String hpp) {
wagons = WagonsFactory.createWagons(hpp);
}
public String print() {
String result = wagons.stream().map(a -> a.getNameWagon()).collect(Collectors.joining("::"));
return result.toString();
}
public void detachEnd() {
wagons.remove(wagons.size() - 1);
}
public void detachHead() {
wagons.remove(0);
}
public boolean fill() {
Optional<Wagon> wagon = wagons.stream().filter((a) -> a.getNameWagon().equals("|____|")).findFirst();
wagon.ifPresent(a -> a.setNameWagon("|^^^^|"));
return wagon.isPresent();
}
}
| UTF-8 | Java | 803 | java | Train.java | Java | []
| null | []
| package com.store.manager;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
public class Train {
private List<Wagon> wagons ;
public Train(String hpp) {
wagons = WagonsFactory.createWagons(hpp);
}
public String print() {
String result = wagons.stream().map(a -> a.getNameWagon()).collect(Collectors.joining("::"));
return result.toString();
}
public void detachEnd() {
wagons.remove(wagons.size() - 1);
}
public void detachHead() {
wagons.remove(0);
}
public boolean fill() {
Optional<Wagon> wagon = wagons.stream().filter((a) -> a.getNameWagon().equals("|____|")).findFirst();
wagon.ifPresent(a -> a.setNameWagon("|^^^^|"));
return wagon.isPresent();
}
}
| 803 | 0.611457 | 0.608966 | 35 | 21.885714 | 25.069927 | 106 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.885714 | false | false | 4 |
4e95fbc013ae3040d0d72389146e2b3de6213a39 | 31,112,743,141,940 | fc9ecdc9455ec35d47654277dda70753309e43d2 | /src/main/java/cn/music/controller/TypeController.java | 416ddb59150e7236552bbea3d6b2ea90fb7e8029 | []
| no_license | yanyijia666/musicEverydaydb | https://github.com/yanyijia666/musicEverydaydb | 696b685e347613c5d588fd8eb31518eb30d3ed90 | 1275ef27823cbd896b452367207281b4da2ec438 | refs/heads/master | 2020-05-17T21:52:37.627000 | 2019-05-13T03:22:58 | 2019-05-13T03:22:58 | 183,981,416 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package cn.music.controller;
import org.springframework.stereotype.Controller;
@Controller
public class TypeController {
}
| UTF-8 | Java | 125 | java | TypeController.java | Java | []
| null | []
| package cn.music.controller;
import org.springframework.stereotype.Controller;
@Controller
public class TypeController {
}
| 125 | 0.824 | 0.824 | 7 | 16.857143 | 17.561554 | 49 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.285714 | false | false | 4 |
6bb9be5ac13d41230035f26de687173076e0c087 | 17,051,020,223,964 | 584532cf6fdee9e4d7428d1cdb2b1d1243b55b01 | /price-service/src/main/java/org/sse/priceservice/model/UserPreferStyle.java | 8c4ce0160047e5581c2345021124c8f1cdd8edac | []
| no_license | Abingcbc/ChiSha | https://github.com/Abingcbc/ChiSha | 5962a0e5bb0c8074038563c5c111b2ce44d936ba | 63acc03592ae9687cefe188b7c401d1cf164f7e4 | refs/heads/master | 2023-01-07T21:47:07.043000 | 2019-12-31T11:53:44 | 2019-12-31T11:53:44 | 226,328,343 | 2 | 1 | null | false | 2023-01-05T03:57:24 | 2019-12-06T12:44:58 | 2020-10-24T14:14:29 | 2023-01-05T03:57:24 | 62,908 | 2 | 0 | 25 | Java | false | false | package org.sse.priceservice.model;
import lombok.Data;
/**
* @author HPY
*/
@Data
public class UserPreferStyle {
private long userId;
private long styleId;
public long getUserId() {
return userId;
}
public void setUserId(long userId) {
this.userId = userId;
}
public long getStyleId() {
return styleId;
}
public void setStyleId(long styleId) {
this.styleId = styleId;
}
}
| UTF-8 | Java | 421 | java | UserPreferStyle.java | Java | [
{
"context": "ervice.model;\n\nimport lombok.Data;\n\n/**\n * @author HPY\n */\n@Data\npublic class UserPreferStyle {\n\n priva",
"end": 76,
"score": 0.999531626701355,
"start": 73,
"tag": "USERNAME",
"value": "HPY"
}
]
| null | []
| package org.sse.priceservice.model;
import lombok.Data;
/**
* @author HPY
*/
@Data
public class UserPreferStyle {
private long userId;
private long styleId;
public long getUserId() {
return userId;
}
public void setUserId(long userId) {
this.userId = userId;
}
public long getStyleId() {
return styleId;
}
public void setStyleId(long styleId) {
this.styleId = styleId;
}
}
| 421 | 0.660333 | 0.660333 | 32 | 12.15625 | 13.278529 | 40 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.25 | false | false | 4 |
3f5b39f9e652be175521bd78f315f03598a63fb7 | 33,105,607,918,839 | 11400d10b41a54715a6223f93b301808fa9ff6c5 | /src/projectmine/SignUpForPatientModel.java | 0262adf1f98c7ae9fe9a07d8a3b0dd6d3c3e79f8 | []
| no_license | Shoaib2020Obaidi/MyJavaFxTeleMediCareProject | https://github.com/Shoaib2020Obaidi/MyJavaFxTeleMediCareProject | f10cc6a3d6393d8fb7f5c15716d3a294c1c1411d | 0852db3365c7790455c4e3f92003cf78e778354a | refs/heads/master | 2022-04-25T10:22:21.256000 | 2020-04-26T03:47:39 | 2020-04-26T03:47:39 | 258,869,025 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package projectmine;
import com.mysql.cj.conf.StringProperty;
import javafx.beans.property.SimpleStringProperty;
public class SignUpForPatientModel {
private SimpleStringProperty fullName;
private SimpleStringProperty NID;
private SimpleStringProperty age;
private SimpleStringProperty disease;
private SimpleStringProperty joiningDate;
private SimpleStringProperty joiningTime;
private SimpleStringProperty address;
private SimpleStringProperty mobileNo;
private SimpleStringProperty bloodType;
private SimpleStringProperty roomNo;
private SimpleStringProperty dischargingDate;
private SimpleStringProperty dischargingTime;
public SignUpForPatientModel(){
this.fullName = new SimpleStringProperty();
this.NID = new SimpleStringProperty();
this.age = new SimpleStringProperty();
this.age = new SimpleStringProperty();
this.disease = new SimpleStringProperty();
this.joiningDate = new SimpleStringProperty();
this.joiningTime = new SimpleStringProperty();
this.address = new SimpleStringProperty();
this.mobileNo = new SimpleStringProperty();
this.bloodType = new SimpleStringProperty();
this.roomNo = new SimpleStringProperty();
this.dischargingDate = new SimpleStringProperty();
this.dischargingTime = new SimpleStringProperty();
}
public String getFullName(){
return fullName.get();
}
public void setFullName(String fullName){
this.fullName.set(fullName);
}
}
| UTF-8 | Java | 1,589 | java | SignUpForPatientModel.java | Java | []
| null | []
| package projectmine;
import com.mysql.cj.conf.StringProperty;
import javafx.beans.property.SimpleStringProperty;
public class SignUpForPatientModel {
private SimpleStringProperty fullName;
private SimpleStringProperty NID;
private SimpleStringProperty age;
private SimpleStringProperty disease;
private SimpleStringProperty joiningDate;
private SimpleStringProperty joiningTime;
private SimpleStringProperty address;
private SimpleStringProperty mobileNo;
private SimpleStringProperty bloodType;
private SimpleStringProperty roomNo;
private SimpleStringProperty dischargingDate;
private SimpleStringProperty dischargingTime;
public SignUpForPatientModel(){
this.fullName = new SimpleStringProperty();
this.NID = new SimpleStringProperty();
this.age = new SimpleStringProperty();
this.age = new SimpleStringProperty();
this.disease = new SimpleStringProperty();
this.joiningDate = new SimpleStringProperty();
this.joiningTime = new SimpleStringProperty();
this.address = new SimpleStringProperty();
this.mobileNo = new SimpleStringProperty();
this.bloodType = new SimpleStringProperty();
this.roomNo = new SimpleStringProperty();
this.dischargingDate = new SimpleStringProperty();
this.dischargingTime = new SimpleStringProperty();
}
public String getFullName(){
return fullName.get();
}
public void setFullName(String fullName){
this.fullName.set(fullName);
}
}
| 1,589 | 0.716174 | 0.716174 | 45 | 34.311111 | 18.670027 | 58 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.666667 | false | false | 4 |
1170964e5be57a0eb3eac37dc04a8306ec53feb6 | 33,105,607,917,909 | b1f4d5073878a1d2e35d43495b909e0e4e5465f8 | /app/src/main/java/com/phjethva/login/signup/sqlite/database/activity/ActivityAdmin.java | 88e42d0912b8fc092b9e3277253364b0fcacc780 | []
| no_license | phjethva/LoginSignUpSqliteDatabase | https://github.com/phjethva/LoginSignUpSqliteDatabase | 2097e8ce2d89dc354de61378242202336a36ce92 | 6650cd17319433e67d40ee4df0aea7474dc526c4 | refs/heads/master | 2021-01-21T14:44:11.325000 | 2017-05-21T13:00:14 | 2017-05-21T13:00:14 | 91,824,469 | 1 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**
* Created by "Pratik Jethva"
* Owned by "PJET APPS"
* https://pjetapps.blogspot.in/
*/
package com.phjethva.login.signup.sqlite.database.activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Toast;
import com.phjethva.login.signup.sqlite.database.R;
import com.phjethva.login.signup.sqlite.database.adapter.AdapterUser;
import com.phjethva.login.signup.sqlite.database.helper.DBHelper;
import com.phjethva.login.signup.sqlite.database.models.User;
import com.phjethva.login.signup.sqlite.database.widget.MyButton;
import com.phjethva.login.signup.sqlite.database.widget.MyTextView;
import java.util.ArrayList;
import java.util.List;
public class ActivityAdmin extends ActivityBase implements View.OnClickListener {
private Toolbar toolbar;
private MyTextView tvTB;
private MyButton btOut, btExt;
private DBHelper dbHelper;
private RecyclerView rvAdm;
private ArrayList<User> arrayUser;
private AdapterUser adapterUser;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_admin);
setUpView();
dbHelper = new DBHelper(this);
tvTB.setText(R.string.adm);
btOut.setOnClickListener(this);
btExt.setOnClickListener(this);
rvAdm.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getApplicationContext());
rvAdm.setLayoutManager(layoutManager);
arrayUser = new ArrayList<>();
adapterUser = new AdapterUser(arrayUser);
final List<User> users = dbHelper.getAllUser();
for (User un : users) {
String strLog = "Id: " + un.getId() + ", "
+ "Username : " + un.getUn() + ", "
+ "Email Id : " + un.getEi() + ", "
+ "Password : " + un.getPw();
Log.d("strLog", strLog);
arrayUser.add(un);
}
rvAdm.setAdapter(adapterUser);
rvAdm.addOnItemTouchListener(new RecyclerView.OnItemTouchListener() {
GestureDetector gestureDetector = new GestureDetector(getApplicationContext(), new GestureDetector.SimpleOnGestureListener(){
@Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
});
@Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
View child = rv.findChildViewUnder(e.getX(), e.getY());
if(child != null && gestureDetector.onTouchEvent(e)) {
int position = rv.getChildAdapterPosition(child);
Toast.makeText(getApplicationContext(), ""
+"Id: "+arrayUser.get(position).getId()+"\n"
+"Username: "+arrayUser.get(position).getUn()+"\n"
+"Email Id: "+arrayUser.get(position).getEi()+"\n"
+"Password: "+arrayUser.get(position).getPw(), Toast.LENGTH_SHORT).show();
}
return false;
}
@Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
}
@Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
});
}
private void setUpView() {
toolbar = (Toolbar) findViewById(R.id.toolbar);
tvTB = (MyTextView) toolbar.findViewById(R.id.tv_tb_ttl);
rvAdm = (RecyclerView) findViewById(R.id.rv_adm);
btOut = (MyButton) findViewById(R.id.bt_out);
btExt = (MyButton) findViewById(R.id.bt_ext);
rvAdm = (RecyclerView) findViewById(R.id.rv_adm);
}
@Override
public void onClick(View v) {
int id = v.getId();
switch (id) {
case R.id.bt_out:
Intent iLog = new Intent(getApplicationContext(), ActivityLogin.class);
startActivity(iLog);
finish();
break;
case R.id.bt_ext:
finish();
break;
}
}
} | UTF-8 | Java | 4,484 | java | ActivityAdmin.java | Java | [
{
"context": "/**\n * Created by \"Pratik Jethva\"\n * Owned by \"PJET APPS\"\n * https://pjetapps.blog",
"end": 32,
"score": 0.9998860359191895,
"start": 19,
"tag": "NAME",
"value": "Pratik Jethva"
}
]
| null | []
| /**
* Created by "<NAME>"
* Owned by "PJET APPS"
* https://pjetapps.blogspot.in/
*/
package com.phjethva.login.signup.sqlite.database.activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Toast;
import com.phjethva.login.signup.sqlite.database.R;
import com.phjethva.login.signup.sqlite.database.adapter.AdapterUser;
import com.phjethva.login.signup.sqlite.database.helper.DBHelper;
import com.phjethva.login.signup.sqlite.database.models.User;
import com.phjethva.login.signup.sqlite.database.widget.MyButton;
import com.phjethva.login.signup.sqlite.database.widget.MyTextView;
import java.util.ArrayList;
import java.util.List;
public class ActivityAdmin extends ActivityBase implements View.OnClickListener {
private Toolbar toolbar;
private MyTextView tvTB;
private MyButton btOut, btExt;
private DBHelper dbHelper;
private RecyclerView rvAdm;
private ArrayList<User> arrayUser;
private AdapterUser adapterUser;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_admin);
setUpView();
dbHelper = new DBHelper(this);
tvTB.setText(R.string.adm);
btOut.setOnClickListener(this);
btExt.setOnClickListener(this);
rvAdm.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getApplicationContext());
rvAdm.setLayoutManager(layoutManager);
arrayUser = new ArrayList<>();
adapterUser = new AdapterUser(arrayUser);
final List<User> users = dbHelper.getAllUser();
for (User un : users) {
String strLog = "Id: " + un.getId() + ", "
+ "Username : " + un.getUn() + ", "
+ "Email Id : " + un.getEi() + ", "
+ "Password : " + un.getPw();
Log.d("strLog", strLog);
arrayUser.add(un);
}
rvAdm.setAdapter(adapterUser);
rvAdm.addOnItemTouchListener(new RecyclerView.OnItemTouchListener() {
GestureDetector gestureDetector = new GestureDetector(getApplicationContext(), new GestureDetector.SimpleOnGestureListener(){
@Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
});
@Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
View child = rv.findChildViewUnder(e.getX(), e.getY());
if(child != null && gestureDetector.onTouchEvent(e)) {
int position = rv.getChildAdapterPosition(child);
Toast.makeText(getApplicationContext(), ""
+"Id: "+arrayUser.get(position).getId()+"\n"
+"Username: "+arrayUser.get(position).getUn()+"\n"
+"Email Id: "+arrayUser.get(position).getEi()+"\n"
+"Password: "+arrayUser.get(position).getPw(), Toast.LENGTH_SHORT).show();
}
return false;
}
@Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
}
@Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
});
}
private void setUpView() {
toolbar = (Toolbar) findViewById(R.id.toolbar);
tvTB = (MyTextView) toolbar.findViewById(R.id.tv_tb_ttl);
rvAdm = (RecyclerView) findViewById(R.id.rv_adm);
btOut = (MyButton) findViewById(R.id.bt_out);
btExt = (MyButton) findViewById(R.id.bt_ext);
rvAdm = (RecyclerView) findViewById(R.id.rv_adm);
}
@Override
public void onClick(View v) {
int id = v.getId();
switch (id) {
case R.id.bt_out:
Intent iLog = new Intent(getApplicationContext(), ActivityLogin.class);
startActivity(iLog);
finish();
break;
case R.id.bt_ext:
finish();
break;
}
}
} | 4,477 | 0.614184 | 0.613515 | 121 | 36.066116 | 26.517338 | 137 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.619835 | false | false | 4 |
8c7bb50d7ce35f5db8800f2604e9d6499930f175 | 30,666,066,561,532 | 457087c82d1e7c59ca1091b1f73748926db96553 | /src/main/java/com/hotel/service/impl/LoginServiceImpl.java | 041364cbe6f0c357d78dd7738702af109107c621 | []
| no_license | LittleLory/Hotel | https://github.com/LittleLory/Hotel | f20e5887ced7e8857695cea9e18d2142ab926122 | 4ef1e8cd346a69080ccd9c8234ddd8076a894ada | refs/heads/master | 2021-01-10T16:52:29.290000 | 2015-10-09T14:55:02 | 2015-10-09T14:55:02 | 43,962,397 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.hotel.service.impl;
import com.hotel.dao.ICityDao;
import com.hotel.dao.IMemberDao;
import com.hotel.dao.IProvinceDao;
import com.hotel.dao.impl.CityDaoImpl;
import com.hotel.dao.impl.MemberDaoImpl;
import com.hotel.dao.impl.ProvinceDaoImpl;
import com.hotel.model.City;
import com.hotel.model.Member;
import com.hotel.model.Province;
import com.hotel.service.ILoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class LoginServiceImpl implements ILoginService
{
@Autowired
private ICityDao cityDao;
@Autowired
private IProvinceDao provinceDao;
@Autowired
private IMemberDao loginDao;
@Override
public Member check(String account, String pwd) throws Exception
{
// TODO Auto-generated method stub
Member member = null;
if(account != null && pwd != null)
{
try
{
member = loginDao.check(account, pwd);
Province province = provinceDao.getProvinceById(member.getProvince().getProvinceId());
City city = cityDao.getCityById(member.getCity().getCityId());
member.setCity(city);
member.setProvince(province);
}
catch (Exception e)
{
throw e;
}finally
{
loginDao.closeResource();
}
}
return member;
}
}
| UTF-8 | Java | 1,308 | java | LoginServiceImpl.java | Java | []
| null | []
| package com.hotel.service.impl;
import com.hotel.dao.ICityDao;
import com.hotel.dao.IMemberDao;
import com.hotel.dao.IProvinceDao;
import com.hotel.dao.impl.CityDaoImpl;
import com.hotel.dao.impl.MemberDaoImpl;
import com.hotel.dao.impl.ProvinceDaoImpl;
import com.hotel.model.City;
import com.hotel.model.Member;
import com.hotel.model.Province;
import com.hotel.service.ILoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class LoginServiceImpl implements ILoginService
{
@Autowired
private ICityDao cityDao;
@Autowired
private IProvinceDao provinceDao;
@Autowired
private IMemberDao loginDao;
@Override
public Member check(String account, String pwd) throws Exception
{
// TODO Auto-generated method stub
Member member = null;
if(account != null && pwd != null)
{
try
{
member = loginDao.check(account, pwd);
Province province = provinceDao.getProvinceById(member.getProvince().getProvinceId());
City city = cityDao.getCityById(member.getCity().getCityId());
member.setCity(city);
member.setProvince(province);
}
catch (Exception e)
{
throw e;
}finally
{
loginDao.closeResource();
}
}
return member;
}
}
| 1,308 | 0.730122 | 0.730122 | 52 | 24.153847 | 20.183186 | 91 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.019231 | false | false | 4 |
de03a20d8610af2c2095108a4d4d756f3c4c55e3 | 31,293,131,751,437 | 48e1024651152be8dba04f84cf51d7da9cf9f5a2 | /src/console/Main.java | 281821dc89d7c61367f6d7e8365aec5983c94eff | []
| no_license | SaltyTuna/Tri-Again | https://github.com/SaltyTuna/Tri-Again | c4ca065bab65be8bd4ccebb330196a11f8b8c970 | 69ccd78f007f4ca8f9ba9ed2aa363d4faf29cbec | refs/heads/master | 2021-04-30T08:36:28.508000 | 2018-02-13T12:25:56 | 2018-02-13T12:25:56 | 121,379,870 | 2 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package console;
import java.awt.Graphics;
import java.awt.image.BufferStrategy;
import graphics.Display;
import states.MenuState;
import states.States;
public class Main implements Runnable {
// graphics
private Display display;
private BufferStrategy bs;
private Graphics g;
private int height, width;
// input
private KeyManager keyManager;
// other
private boolean running = false; // wird auf true gesetzt wenn das Spiel läuft
public static Main theGame; // vereinfacht das bearbeiten von Variablen
private Thread thread;
public Main(int width, int height) {
theGame = this;
keyManager = new KeyManager();
this.width = width;
this.height = height;
}
public void start() {
running = true;
thread = new Thread(this);
display = new Display(width, height);
display.getFrame().addKeyListener(keyManager);
States.setStates(new MenuState());
thread.start();
}
public void render() {
bs = display.getCanvas().getBufferStrategy();
if (bs == null) {
display.getCanvas().createBufferStrategy(2);
return;
}
g = bs.getDrawGraphics();
States.getState().render(g);
g.dispose();
bs.show();
}
public void tick() {
keyManager.tick();
States.getState().tick();
}
@Override
public void run() {
int fps = 60;
double timePerTick = 1000000000 / fps;
double delta = 0;
long now;
long lastTime = System.nanoTime();
while (running) {
now = System.nanoTime();
delta += (now - lastTime) / timePerTick;
lastTime = now;
if (delta >= 1) {
tick();
render();
delta--;
}
}
// wenn das Spiel verloren oder ein Exitbutton aktiviert wurde
display.getFrame().setVisible(false);
display.getFrame().dispose();
}
// getter & setter
public int getHeight() {
return height;
}
public int getWidth() {
return width;
}
public KeyManager getKeyManager() {
return keyManager;
}
public Display getDisplay() {
return display;
}
public Thread getThread() {
return thread;
}
public void setRunning(boolean y) {
running = y;
}
}
| ISO-8859-1 | Java | 2,049 | java | Main.java | Java | []
| null | []
| package console;
import java.awt.Graphics;
import java.awt.image.BufferStrategy;
import graphics.Display;
import states.MenuState;
import states.States;
public class Main implements Runnable {
// graphics
private Display display;
private BufferStrategy bs;
private Graphics g;
private int height, width;
// input
private KeyManager keyManager;
// other
private boolean running = false; // wird auf true gesetzt wenn das Spiel läuft
public static Main theGame; // vereinfacht das bearbeiten von Variablen
private Thread thread;
public Main(int width, int height) {
theGame = this;
keyManager = new KeyManager();
this.width = width;
this.height = height;
}
public void start() {
running = true;
thread = new Thread(this);
display = new Display(width, height);
display.getFrame().addKeyListener(keyManager);
States.setStates(new MenuState());
thread.start();
}
public void render() {
bs = display.getCanvas().getBufferStrategy();
if (bs == null) {
display.getCanvas().createBufferStrategy(2);
return;
}
g = bs.getDrawGraphics();
States.getState().render(g);
g.dispose();
bs.show();
}
public void tick() {
keyManager.tick();
States.getState().tick();
}
@Override
public void run() {
int fps = 60;
double timePerTick = 1000000000 / fps;
double delta = 0;
long now;
long lastTime = System.nanoTime();
while (running) {
now = System.nanoTime();
delta += (now - lastTime) / timePerTick;
lastTime = now;
if (delta >= 1) {
tick();
render();
delta--;
}
}
// wenn das Spiel verloren oder ein Exitbutton aktiviert wurde
display.getFrame().setVisible(false);
display.getFrame().dispose();
}
// getter & setter
public int getHeight() {
return height;
}
public int getWidth() {
return width;
}
public KeyManager getKeyManager() {
return keyManager;
}
public Display getDisplay() {
return display;
}
public Thread getThread() {
return thread;
}
public void setRunning(boolean y) {
running = y;
}
}
| 2,049 | 0.675781 | 0.668457 | 117 | 16.504274 | 16.298824 | 79 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.649573 | false | false | 4 |
e8d78e6f0fad5e1eebd1a4abedf3e47e20c54c9b | 29,661,044,183,050 | 3e909d759fa6fb4694447064a80dfb185a77d907 | /busineService_budian/src/com/xmniao/service/sellerOrder/SellerOrderServiceImpl.java | 253c33b466cb80d66066c4c29b90dbddbe408aba | []
| no_license | liveqmock/seeyouagain | https://github.com/liveqmock/seeyouagain | 9703616f59ae0b9cd2e641d135170c84c18a257c | fae0cb3471f07520878e51358cfa5ea88e1d659c | refs/heads/master | 2020-04-04T14:47:00.192000 | 2017-11-14T12:47:31 | 2017-11-14T12:47:31 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.xmniao.service.sellerOrder;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.thrift.TException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.alibaba.fastjson.JSONObject;
import com.xmniao.common.PreciseComputeUtil;
import com.xmniao.dao.coupon.RedPacketRecordDao;
import com.xmniao.dao.sellerOrder.ActivityKillOrderDao;
import com.xmniao.dao.sellerOrder.SellerOrderDao;
import com.xmniao.domain.coupon.RedPacketRecord;
import com.xmniao.domain.order.XmnWalletBean;
import com.xmniao.service.common.CommonServiceImpl;
import com.xmniao.service.order.OrderServiceImpl;
import com.xmniao.service.order.SellerActivityServiceImpl;
import com.xmniao.thrift.busine.common.FailureException;
import com.xmniao.thrift.busine.common.ResponseData;
import com.xmniao.thrift.busine.sellerOrder.SellerOrderService;
@Service("sellerOrderServiceImpl")
public class SellerOrderServiceImpl implements SellerOrderService.Iface {
// 初始化日志类
private final Logger log = Logger.getLogger(SellerOrderServiceImpl.class);
@Autowired
private SellerOrderDao sellerOrderDao;
@Autowired
private RedPacketRecordDao redPacketRecordDao;
@Autowired
private ActivityKillOrderDao activityKillOrderDao;
@Autowired
private SellerActivityServiceImpl sellerActivityService;
@Autowired
private CommonServiceImpl commonServiceImpl;
@Autowired
private OrderServiceImpl orderService;
/**
* 更新红包支付订单
*/
@Override
public Map<String, String> modifyRedPacketOrder(Map<String, String> paraMap)
throws FailureException, TException {
log.info("更新红包支付订单modifyRedPacketOrder:" + paraMap);
Map<String, String> resultMap = new HashMap<>();
try {
// 验证参数
if (!verifyParam(paraMap)) {
log.error("更新红包支付订单,验证参数失败");
throw new FailureException(1, "传入参数有误");
}
String orderNo = paraMap.get("order_no");// 订单id
resultMap.put("order_no", orderNo);
// 获取订单信息
Map<String, Object> redPacket = sellerOrderDao
.getRedPacket(orderNo);
if (redPacket == null) {
log.error("未查询到订单:" + orderNo);
throw new FailureException(1, "未查询到该订单");
}
Long version = (Long) redPacket.get("version");// 版本号
// 支付状态 1:未支付 2:已支付 3:取消支付 4:支付失败
int status = Integer.valueOf(paraMap.get("status"));
int orderStatus = (int) redPacket.get("status");// 订单支付状态
if (2 == orderStatus) {
log.info("订单" + orderNo + "已完成支付,请勿重复提交");
return resultMap;
} else if (status != 1 && status != 2 && status != 3 && status != 4) {
log.error("订单状态或支付状态有误" + status);
throw new FailureException(1, "订单状态或支付状态有误");
}
// 验证订单参数与数据库订单信息书否匹配
if (paraMap.get("sellerid").equals(redPacket.get("sellerid") + "")
&& paraMap.get("pay_type").equals(
redPacket.get("payType") + "")
&& paraMap.get("total_amount").equals(
redPacket.get("totalAmount").toString())
&& paraMap.get("balance").equals(
redPacket.get("balance").toString())
&& paraMap.get("commision").equals(
redPacket.get("commision").toString())
&& paraMap.get("zbalance").equals(
redPacket.get("zbalance").toString())
&& paraMap.get("integral").equals(
redPacket.get("integral").toString())
&& paraMap.get("amount").equals(
redPacket.get("amount").toString())
&& paraMap.get("profit").equals(
redPacket.get("profit").toString())) {
// 更新订单状态和支付状态
paraMap.put("version", version.toString());
Integer result = sellerOrderDao.updateRedPacketState(paraMap);
if (result != 1) {
log.error("更新红包支付订单失败");
throw new FailureException(1, "更新红包支付订单失败");
}
log.info("更新红包支付订单成功");
return resultMap;
} else {
log.error("传入订单参数与后台订单参数不匹配");
throw new FailureException(1, "传入订单参数与后台订单参数不匹配");
}
} catch (Exception e) {
log.error("更新红包支付订单失败", e);
throw new FailureException(1, "更新红包支付订单失败");
}
}
/**
* 更新领取红包记录状态
*/
@Override
public Map<String, String> modifyRedPacketRecord(Map<String, String> paraMap)
throws FailureException, TException {
log.info("更新领取红包记录状态modifyRedPacketRecord:" + paraMap);
Map<String, String> resultMap = new HashMap<String, String>();
resultMap.put("id", paraMap.get("id"));
if (StringUtils.isBlank(paraMap.get("id"))
|| StringUtils.isBlank(paraMap.get("status"))) {
log.error("传入参数有误:" + paraMap);
throw new FailureException(1, "传入参数有误");
}
try {
long id = Long.parseLong(paraMap.get("id"));
int status = Integer.parseInt(paraMap.get("status"));
RedPacketRecord record = new RedPacketRecord();
record.setId(id);
RedPacketRecord redPacketRecord = redPacketRecordDao
.getRedPacketRecord(record);
if (redPacketRecord == null) {
log.error("找不到对应红包【" + id + "】领取记录");
throw new FailureException(2, "找不到对应记录");
}
if (redPacketRecord.getStatus() == status) {
log.info("对应红包【" + id + "】领取记录已经到账");
return resultMap;
}
record.setStatus(status);
redPacketRecordDao.updateByPrimaryKeySelective(record);
} catch (Exception e) {
log.error("更新红包到帐状态异常", e);
throw new FailureException(3, "更新红包到账状态异常");
}
return resultMap;
}
/**
* 验证传入参数
*
* @param paraMap
*/
private boolean verifyParam(Map<String, String> paraMap) {
if (StringUtils.isBlank(paraMap.get("order_no"))
|| StringUtils.isBlank(paraMap.get("sellerid"))
|| StringUtils.isBlank(paraMap.get("status"))
|| StringUtils.isBlank(paraMap.get("pay_type"))
|| StringUtils.isBlank(paraMap.get("pay_id"))
|| StringUtils.isBlank(paraMap.get("total_amount"))
|| StringUtils.isBlank(paraMap.get("balance"))
|| StringUtils.isBlank(paraMap.get("commision"))
|| StringUtils.isBlank(paraMap.get("zbalance"))
|| StringUtils.isBlank(paraMap.get("integral"))
|| StringUtils.isBlank(paraMap.get("profit"))
|| StringUtils.isBlank(paraMap.get("amount"))
|| "null".equals(paraMap.get("order_no"))
|| "null".equals(paraMap.get("sellerid"))
|| "null".equals(paraMap.get("pay_type"))
|| "null".equals(paraMap.get("pay_id"))
|| "null".equals(paraMap.get("total_amount"))) {
return false;
} else {
return true;
}
}
/**
* 更新秒杀订单
*/
@Override
@Transactional(rollbackFor = { FailureException.class, Exception.class,
RuntimeException.class })
public Map<String, String> updateKillOrder(Map<String, String> paraMap)
throws FailureException, TException {
log.info("更新秒杀订单updateKillOrder:" + paraMap);
Map<String, String> resultMap = new HashMap<>();
try {
// 验证参数
if (StringUtils.isBlank(paraMap.get("uid"))
|| StringUtils.isBlank(paraMap.get("amount"))
|| StringUtils.isBlank(paraMap.get("number"))
|| StringUtils.isBlank(paraMap.get("status"))) {
log.error("传入参数部分为空");
throw new FailureException(1, "传入参数部分为空");
}
// 查询秒杀记录
Map<String, Object> activityRecord = activityKillOrderDao
.getActivityRecord(paraMap.get("number"));
if (activityRecord == null) {
log.error("未查询到秒杀记录:" + paraMap.get("number"));
throw new FailureException(1, "未查询到秒杀记录");
}
// 查询活动信息
/*
* Map<String, Object> activity = activityKillOrderDao
* .getActivity(activityRecord.get("activity_id") + ""); if
* (activity == null) { log.error("为查询到活动id为:" +
* activityRecord.get("activity_id") + "的秒杀活动"); throw new
* FailureException(1, "为查询到活动id为:" +
* activityRecord.get("activity_id") + "的秒杀活动"); }
*/
if ((int) activityRecord.get("pay_status") == 1) {
log.info("订单已支付成功,请勿重复提交");
return resultMap;
}
// 匹配传入参数与数据库参数
if (paraMap.get("uid").equals(activityRecord.get("uid").toString())
&& paraMap.get("amount").equals(
activityRecord.get("pay_amount").toString())) {
paraMap.put("version", activityRecord.get("version").toString());// 版本号,用于乐观锁控制
// 发放秒杀奖品
Object serialNo = sendCoupon(activityRecord);
// 更新订单状态
paraMap.put("payTime", formatDate());// 支付时间
paraMap.put("codeid",
serialNo == null ? null : serialNo.toString());// 赠品券序列码
BigDecimal ledgeramount = (BigDecimal) activityRecord.get("pay_amount");
BigDecimal selleramount = this.getKillOrderSellerLedgerAmount(
ledgeramount, (double) activityRecord.get("baseagio"));
paraMap.put("sellerAmount", selleramount.toString());
paraMap.put("isaccount", "0");
Integer result = activityKillOrderDao
.updateActivityRecordStatus(paraMap);
if (result != 1) {
log.error("更新秒杀订单失败");
throw new FailureException(1, "更新秒杀订单失败");
}
try{
if(paraMap.get("status").equals("1")){
//短信下发
orderService.sendSmsForSeller((int)activityRecord.get("sellerid"),paraMap.get("number"),selleramount.toString());
// 调用支付服务,给商户加钱
activityRecord.put("sellerAmount", selleramount.toString());
addMoney(activityRecord);
}
}catch(Exception e){
log.error("处理秒杀订单异常",e);
}
} else {
log.error("传入参数与数据库参数不匹配");
throw new FailureException(1, "传入参数与数据库参数不匹配");
}
log.info("更新秒杀订单状态成功");
return resultMap;
} catch (Exception e) {
log.error("更新秒杀订单失败", e);
throw new FailureException(1, "更新秒杀订单失败");
}
}
/**
* 发放秒杀奖品
*
* @param list
* @param activityRecord
* @throws FailureException
*/
private Object sendCoupon(Map<String, Object> activityRecord)
throws FailureException {
Map<String, Object> packageParam = null;
Map<String, Object> activityRelation = activityKillOrderDao
.getActivityRelaction(activityRecord.get("cid").toString());
if (activityRelation == null) {
log.error("为查询到奖品关联关系:" + activityRecord.get("cid"));
throw new FailureException(1, "为查询到奖品信息");
}
Map<String, Object> sellerCoupon = activityKillOrderDao
.getSellerCoupon(activityRelation.get("award_id").toString());
if (sellerCoupon != null) {
packageParam = packageParam(sellerCoupon, activityRecord);
activityKillOrderDao.insertUserCoupon(packageParam);
} else {
log.error("为查询到奖品信息cid:" + activityRecord.get("cid"));
throw new FailureException(1, "为查询到奖品信息");
}
return packageParam.get("serial_no");
}
/**
* 组装参数
*
* @param sellerCoupon
* @return
*/
private Map<String, Object> packageParam(Map<String, Object> sellerCoupon,
Map<String, Object> couponOrder) {
Map<String, Object> paraMap = new HashMap<>();
paraMap.put("cid", sellerCoupon.get("cid"));
if (sellerCoupon.get("coupon_type") != null
&& (Integer) sellerCoupon.get("coupon_type") == 4) {
String serialNo = sellerActivityService
.getRedisSerial((int) sellerCoupon.get("sellerid"));
if (StringUtils.isBlank(serialNo)) {
throw new RuntimeException("获取序列号出错");
}
paraMap.put("serial_no", ("3" + serialNo));
} else {
paraMap.put("serial_no", null);
}
paraMap.put("denomination", sellerCoupon.get("denomination"));
paraMap.put("get_way", 5);
paraMap.put("get_time", formatDate());
paraMap.put("uid", couponOrder.get("uid"));
paraMap.put("sellerid", sellerCoupon.get("sellerid"));
paraMap.put("use_status", 0);
paraMap.put("start_date", sellerCoupon.get("start_date"));
paraMap.put("end_date", sellerCoupon.get("end_date"));
paraMap.put("bid", couponOrder.get("number"));
paraMap.put("phone", couponOrder.get("phone"));
paraMap.put("activity_id", couponOrder.get("id"));
paraMap.put("activity_type", 3);
return paraMap;
}
private String formatDate() {
return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
}
/**
* 给商家加钱
*
* @param activity
* @param activityRecord
* @throws FailureException
* ,Exception
*/
private void addMoney(Map<String, Object> activityRecord)
throws FailureException, Exception {
// Map<String, String> paraMap = new HashMap<>();
// paraMap.put("uId", activityRecord.get("sellerid") + "");
// paraMap.put("userType", "2");
// paraMap.put("sellerAmount",activityRecord.get("sellerAmount").toString() + "");
// paraMap.put("orderId", activityRecord.get("number") + "_2");
// paraMap.put("remark", "秒杀活动");
// paraMap.put("rType", "22");
// int result = commonServiceImpl.modifyWalletBalance(paraMap);
// if (result != 0) {
// log.info("调用支付服务,给商家加钱失败");
// throw new FailureException(1, "调用支付服务,给商家加钱失败");
// }
XmnWalletBean xmnWallet = new XmnWalletBean();
xmnWallet.setuId(activityRecord.get("sellerid")+"");
xmnWallet.setUserType("2");
xmnWallet.setSellerAmount(activityRecord.get("sellerAmount").toString());
xmnWallet.setrType("22");
xmnWallet.setOrderId(activityRecord.get("number") + "_2");
xmnWallet.setRemark("秒杀活动");
xmnWallet.setOption("0");
xmnWallet.setReturnMode("2");
orderService.insertXmnWalletRedis(xmnWallet);
}
/**
* 更新面对面支付订单
*/
@Override
@Transactional
public Map<String, String> updateMicroOrder(Map<String, String> paraMap)
throws FailureException, TException {
log.info("updateMicroOrder:" + paraMap);
Map<String, String> resultMap = new HashMap<String, String>();
String orderNumber = paraMap.get("orderNumber");
resultMap.put("orderNumber", paraMap.get("orderNumber"));
try {
if (StringUtils.isBlank(orderNumber)
|| StringUtils.isBlank(paraMap.get("payType"))
|| StringUtils.isBlank(paraMap.get("authCode"))
|| StringUtils.isBlank(paraMap.get("totalAmount"))
|| StringUtils.isBlank(paraMap.get("payStatus"))
|| StringUtils.isBlank(paraMap.get("sellerid"))) {
throw new Exception("传入参数不齐");
}
Map<String, Object> orderMap = sellerOrderDao
.getMicroBill(orderNumber);
if (orderMap == null) {
throw new Exception("找不到该订单");
}
log.info("orderMap:" + orderMap);
if (orderMap.get("payStatus") != null
&& orderMap.get("payStatus").toString()
.equals(paraMap.get("payStatus"))) {
return resultMap;
}
if (orderMap.get("payStatus") != null
&& (Integer) orderMap.get("payStatus") == 1) {
throw new Exception("已支付订单不能被修改为其他状态");
}
if (!orderMap.get("totalAmount").toString()
.equals(paraMap.get("totalAmount"))) {
throw new Exception("订单金额错误");
}
// if(!orderMap.get("authCode").toString().equals(paraMap.get("authCode"))){
// throw new Exception("验证错误");
// }
BigDecimal ledgeramount = (BigDecimal) orderMap.get("totalAmount");
double ledgerratio = 1;
BigDecimal selleramount = getMicroOrderSellerLedgerAmount(
ledgeramount, ledgerratio);
Map<String, Object> uMap = new HashMap<String, Object>();
uMap.put("orderNumber", orderNumber);
uMap.put("payStatus", paraMap.get("payStatus"));
uMap.put("authCode", paraMap.get("authCode"));
uMap.put("sellerAmount", selleramount);
uMap.put("isaccount", 0);
sellerOrderDao.updateMicroBill(uMap);
// Map<String, String> walletMap = new HashMap<String, String>();
// walletMap.put("uId", orderMap.get("sellerid") + "");
// walletMap.put("userType", "2");
// walletMap.put("sellerAmount", selleramount + "");
// walletMap.put("orderId", orderNumber + "_2");
// walletMap.put("remark", "面对面扫码支付");
// walletMap.put("rType", "22");
// if (paraMap.get("payStatus").equals("1")) {
// commonServiceImpl.modifyWalletBalance(walletMap);
// }
try{
if (paraMap.get("payStatus").equals("1")) {
//短信下发
orderService.sendSmsForSeller((int)orderMap.get("sellerid"),paraMap.get("orderNumber"),selleramount.toString());
XmnWalletBean xmnWallet = new XmnWalletBean();
xmnWallet.setuId(orderMap.get("sellerid")+"");
xmnWallet.setUserType("2");
xmnWallet.setSellerAmount(selleramount + "");
xmnWallet.setrType("22");
xmnWallet.setOrderId(orderNumber + "_2");
xmnWallet.setRemark("面对面扫码支付");
xmnWallet.setOption("0");
xmnWallet.setReturnMode("3");
orderService.insertXmnWalletRedis(xmnWallet);
}
}catch(Exception sube){
log.error("",sube);
}
} catch (Exception e) {
log.error("更新异常", e);
throw new FailureException(101, e.getMessage());
}
return resultMap;
}
public ResponseData getKillOrderLedgerInfo(String bid) {
ResponseData responseData = new ResponseData();
try {
Map<String, Object> billBean = activityKillOrderDao
.getActivityRecord(bid);
if (billBean == null) {
responseData.setMsg("订单不存在");
responseData.setState(1);
return responseData;
}
if (billBean.get("pay_status") == null
|| (Integer) billBean.get("pay_status") != 1) {
responseData.setMsg("订单尚未支付");
responseData.setState(1);
return responseData;
}
if (billBean.get("baseagio") == null) {
responseData.setMsg("订单未写入分账比例");
responseData.setState(1);
return responseData;
}
Map<String, String> resultMap = new HashMap<String, String>();
resultMap.put("bid", String.valueOf(billBean.get("number")));
resultMap.put("paytype", String.valueOf(billBean.get("pay_type")));
resultMap.put("money",
String.valueOf(billBean.get("sec_kill_amount")));
resultMap.put("payamount",
String.valueOf(billBean.get("pay_amount")));
resultMap.put("wamount", String.valueOf("0"));
resultMap
.put("samount", String.valueOf(billBean.get("pay_amount")));
resultMap.put("preferential", String.valueOf(((BigDecimal) billBean
.get("sec_kill_amount")).subtract((BigDecimal) billBean
.get("pay_amount"))));
resultMap.put("zinteger", String.valueOf("0"));
resultMap.put("liveCoin", String.valueOf(0));
resultMap.put("liveCoinRatio", String.valueOf(0));
resultMap.put("codeid", String.valueOf(billBean.get("codeid")));
BigDecimal ledgeramount = (BigDecimal) billBean.get("pay_amount");
BigDecimal selleramount = this.getKillOrderSellerLedgerAmount(
ledgeramount, (double) billBean.get("baseagio"));
resultMap.put("ledgerratio",
String.valueOf(billBean.get("baseagio")));
resultMap.put("ledgeramount", String.valueOf(ledgeramount));
resultMap.put("selleramount", String.valueOf(selleramount));
resultMap.put("expectedselleramount", resultMap.get("selleramount"));
resultMap.put("sellercommision", String.valueOf(0));
resultMap.put("jointamount", String.valueOf(0));
resultMap.put("xmeramount", String.valueOf(0));
resultMap.put("txmeramount", String.valueOf(0));
resultMap.put("pxmeramount", String.valueOf(0));
resultMap.put("platformamount",
String.valueOf(ledgeramount.subtract(selleramount)));
responseData.setState(0);
responseData.setMsg("查询成功");
responseData.setResultMap(resultMap);
} catch (Exception e) {
log.error("查询异常", e);
responseData.setState(2);
responseData.setMsg("查询异常");
}
return responseData;
}
public ResponseData getMicroOrderLedgerInfo(String bid) {
ResponseData responseData = new ResponseData();
try {
Map<String, Object> billBean = sellerOrderDao.getMicroBill(bid);
if (billBean == null) {
responseData.setMsg("订单不存在");
responseData.setState(1);
return responseData;
}
if (billBean.get("payStatus") == null
|| (Integer) billBean.get("payStatus") != 1) {
responseData.setMsg("订单尚未支付");
responseData.setState(1);
return responseData;
}
Map<String, String> resultMap = new HashMap<String, String>();
resultMap.put("bid", String.valueOf(bid));
resultMap.put("paytype", String.valueOf(billBean.get("payType")));
resultMap.put("money", String.valueOf(billBean.get("totalAmount")));
resultMap.put("payamount",
String.valueOf(billBean.get("totalAmount")));
resultMap.put("wamount", String.valueOf(0));
resultMap.put("samount",
String.valueOf(billBean.get("totalAmount")));
resultMap.put("preferential", String.valueOf(0));
resultMap.put("zinteger", String.valueOf(0));
resultMap.put("liveCoin", String.valueOf(0));
resultMap.put("liveCoinRatio", String.valueOf(0));
resultMap.put("codeid", String.valueOf(""));
double ledgerRatio = 1;
BigDecimal ledgeramount = (BigDecimal) billBean.get("totalAmount");
BigDecimal selleramount = ledgeramount.multiply(
new BigDecimal(Double.toString(ledgerRatio))).setScale(2,
RoundingMode.FLOOR);
if (selleramount.compareTo(BigDecimal.ZERO) <= 0
&& ledgeramount.compareTo(BigDecimal.ZERO) > 0) {
selleramount = new BigDecimal("0.01");
}
resultMap.put("ledgerratio", String.valueOf(ledgerRatio));
resultMap.put("ledgeramount", String.valueOf(ledgeramount));
resultMap.put("selleramount", String.valueOf(selleramount));
resultMap.put("expectedselleramount", resultMap.get("selleramount"));
resultMap.put("sellercommision", String.valueOf(0));
resultMap.put("jointamount", String.valueOf(0));
resultMap.put("xmeramount", String.valueOf(0));
resultMap.put("txmeramount", String.valueOf(0));
resultMap.put("pxmeramount", String.valueOf(0));
resultMap.put("platformamount",
String.valueOf(ledgeramount.subtract(selleramount)));
responseData.setState(0);
responseData.setMsg("查询成功");
responseData.setResultMap(resultMap);
} catch (Exception e) {
log.error("查询异常", e);
responseData.setState(2);
responseData.setMsg("查询异常");
}
return responseData;
}
public BigDecimal getKillOrderSellerLedgerAmount(BigDecimal ledgeramount,
double ledgerRatio) {
BigDecimal selleramount = ledgeramount.multiply(
new BigDecimal(Double.toString(ledgerRatio))).setScale(2,
RoundingMode.FLOOR);
if (selleramount.compareTo(BigDecimal.ZERO) <= 0
&& ledgeramount.compareTo(BigDecimal.ZERO) > 0) {
selleramount = new BigDecimal("0.01");
}
return selleramount;
}
public BigDecimal getMicroOrderSellerLedgerAmount(BigDecimal ledgeramount,
double ledgerRatio) {
BigDecimal selleramount = ledgeramount.multiply(
new BigDecimal(Double.toString(ledgerRatio))).setScale(2,
RoundingMode.FLOOR);
if (selleramount.compareTo(BigDecimal.ZERO) <= 0
&& ledgeramount.compareTo(BigDecimal.ZERO) > 0) {
selleramount = new BigDecimal("0.01");
}
return selleramount;
}
/**
* 更新网红订单
*/
@Override
@Transactional(rollbackFor={FailureException.class,Exception.class,RuntimeException.class})
public Map<String, String> updateCelebrityOrder(Map<String, String> paraMap)
throws FailureException, TException {
log.info("更新网红订单updateCelebrityOrder:" + paraMap);
Map<String,String> resultMap = new HashMap<>();
try {
/**
* 验证参数
*/
if (StringUtils.isBlank(paraMap.get("orderNo"))
|| StringUtils.isBlank(paraMap.get("sellerid"))
|| StringUtils.isBlank(paraMap.get("payType"))
|| StringUtils.isBlank(paraMap.get("price"))
|| StringUtils.isBlank(paraMap.get("payStatus"))){
log.error("传入参数有误"+paraMap);
throw new FailureException(1,"传入参数部分为空");
}
if("1".equals(paraMap.get("payStatus"))){
log.error("订单状态不能为1"+paraMap);
throw new FailureException(1,"订单状态不能为1");
}
resultMap.put("orderNo",paraMap.get("orderNo"));
Map<String, Object> celebrityOrder = sellerOrderDao.getCelebrityOrder(paraMap);
if(celebrityOrder==null){
log.error("未查询到订单号为:"+paraMap.get("orderNo")+"的订单");
throw new FailureException(1,"为查询到订单号为:"+paraMap.get("orderNo")+"的订单");
}
//匹配数据库参数
if(!paraMap.get("sellerid").equals(celebrityOrder.get("seller_id").toString()) ||
!paraMap.get("price").equals(celebrityOrder.get("price").toString())){
log.error("匹配数据库参数失败,传参有误"+paraMap);
throw new FailureException(1,"匹配数据库参数失败");
}
if(paraMap.get("payStatus").equals(celebrityOrder.get("pay_status").toString())){
log.info("订单号为:"+paraMap.get("orderNo")+"的订单已修改状态成功,请勿重复提交");
return resultMap;
}
paraMap.put("payTime",formatDate());
paraMap.put("lock",celebrityOrder.get("version_lock").toString());
//更新订单状态
Integer result = sellerOrderDao.updateCelebrityOrder(paraMap);
if (result !=1) {
log.error("更新网红订单失败");
throw new FailureException(1,"更新网红订单失败");
}
log.info("更新网红订单成功");
return resultMap;
} catch (Exception e) {
log.error("更新网红订单失败",e);
throw new FailureException(1,"更新网红订单失败");
}
}
/**
* 更新金额到账状态
*/
@Override
public Map<String, String> modifyReceiptStatus(Map<String, String> paraMap)
throws FailureException, TException {
log.info("modifyReceiptStatus:"+paraMap);
if(StringUtils.isNotBlank(paraMap.get("type"))
&& StringUtils.isNotBlank(paraMap.get("id"))
&& StringUtils.isNotBlank(paraMap.get("status"))){
if(paraMap.get("type").equals("1")){
return this.modifyRedPacketRecord(paraMap);
}else if(paraMap.get("type").equals("2")){
return this.modifyKillOrderRecord(paraMap);
}else if(paraMap.get("type").equals("3")){
return this.modifyMicroRecord(paraMap);
}
}
throw new FailureException(1, "传入参数错误!");
}
/**
* 更新商家面对面订单分账记录状态
*/
public Map<String, String> modifyMicroRecord(Map<String, String> paraMap)
throws FailureException, TException {
log.info("更新面对面订单分账状态modifyMicroRecord:" + paraMap);
Map<String, String> resultMap = new HashMap<String, String>();
resultMap.put("id", paraMap.get("id"));
if (StringUtils.isBlank(paraMap.get("id"))
|| StringUtils.isBlank(paraMap.get("status"))) {
log.error("传入参数有误:" + paraMap);
throw new FailureException(1, "传入参数有误");
}
try {
String orderNumber = paraMap.get("id");
int status = Integer.parseInt(paraMap.get("status"));
Map<String,Object> microMap = sellerOrderDao
.getMicroBill(orderNumber);
if (microMap == null) {
log.error("找不到对应面对面订单【" + orderNumber + "】记录");
throw new FailureException(2, "找不到对应记录");
}
if (microMap.get("isaccount")!=null && microMap.get("isaccount").toString().equals("1")) {
log.info("对应面对面订单【" + orderNumber + "】分账已经到账");
return resultMap;
}
Map<String,Object> uMap = new HashMap<String,Object>();
uMap.put("orderNumber", orderNumber);
uMap.put("isaccount", status);
sellerOrderDao.updateMicroBill(uMap);
} catch (Exception e) {
log.error("更新面对面订单分账状态异常", e);
throw new FailureException(3, "更新面对面订单分账状态异常");
}
return resultMap;
}
/**
* 更新秒杀分账记录状态
*/
public Map<String, String> modifyKillOrderRecord(Map<String, String> paraMap)
throws FailureException, TException {
log.info("更新秒杀订单分账状态modifyKillOrderRecord:" + paraMap);
Map<String, String> resultMap = new HashMap<String, String>();
resultMap.put("id", paraMap.get("id"));
if (StringUtils.isBlank(paraMap.get("id"))
|| StringUtils.isBlank(paraMap.get("status"))) {
log.error("传入参数有误:" + paraMap);
throw new FailureException(1, "传入参数有误");
}
try {
String number = paraMap.get("id");
int status = Integer.parseInt(paraMap.get("status"));
Map<String,Object> record = activityKillOrderDao.getActivityRecord(number);
if (record == null) {
log.error("找不到秒杀订单【" + number + "】记录");
throw new FailureException(2, "找不到对应记录");
}
if (record.get("isaccount")!=null && record.get("isaccount").toString().equals("1")) {
log.info("对应订单【" + number + "】记录分账已经到账");
return resultMap;
}
Map<String,String> uMap = new HashMap<String,String>();
uMap.put("number", number);
uMap.put("isaccount", status+"");
uMap.put("version", record.get("version").toString());
activityKillOrderDao.updateActivityRecordStatus(uMap);
} catch (Exception e) {
log.error("更新秒杀订单分账到账状态异常", e);
throw new FailureException(3, "更新秒杀订单分账到账状态异常");
}
return resultMap;
}
}
| UTF-8 | Java | 29,930 | java | SellerOrderServiceImpl.java | Java | []
| null | []
| package com.xmniao.service.sellerOrder;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.thrift.TException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.alibaba.fastjson.JSONObject;
import com.xmniao.common.PreciseComputeUtil;
import com.xmniao.dao.coupon.RedPacketRecordDao;
import com.xmniao.dao.sellerOrder.ActivityKillOrderDao;
import com.xmniao.dao.sellerOrder.SellerOrderDao;
import com.xmniao.domain.coupon.RedPacketRecord;
import com.xmniao.domain.order.XmnWalletBean;
import com.xmniao.service.common.CommonServiceImpl;
import com.xmniao.service.order.OrderServiceImpl;
import com.xmniao.service.order.SellerActivityServiceImpl;
import com.xmniao.thrift.busine.common.FailureException;
import com.xmniao.thrift.busine.common.ResponseData;
import com.xmniao.thrift.busine.sellerOrder.SellerOrderService;
@Service("sellerOrderServiceImpl")
public class SellerOrderServiceImpl implements SellerOrderService.Iface {
// 初始化日志类
private final Logger log = Logger.getLogger(SellerOrderServiceImpl.class);
@Autowired
private SellerOrderDao sellerOrderDao;
@Autowired
private RedPacketRecordDao redPacketRecordDao;
@Autowired
private ActivityKillOrderDao activityKillOrderDao;
@Autowired
private SellerActivityServiceImpl sellerActivityService;
@Autowired
private CommonServiceImpl commonServiceImpl;
@Autowired
private OrderServiceImpl orderService;
/**
* 更新红包支付订单
*/
@Override
public Map<String, String> modifyRedPacketOrder(Map<String, String> paraMap)
throws FailureException, TException {
log.info("更新红包支付订单modifyRedPacketOrder:" + paraMap);
Map<String, String> resultMap = new HashMap<>();
try {
// 验证参数
if (!verifyParam(paraMap)) {
log.error("更新红包支付订单,验证参数失败");
throw new FailureException(1, "传入参数有误");
}
String orderNo = paraMap.get("order_no");// 订单id
resultMap.put("order_no", orderNo);
// 获取订单信息
Map<String, Object> redPacket = sellerOrderDao
.getRedPacket(orderNo);
if (redPacket == null) {
log.error("未查询到订单:" + orderNo);
throw new FailureException(1, "未查询到该订单");
}
Long version = (Long) redPacket.get("version");// 版本号
// 支付状态 1:未支付 2:已支付 3:取消支付 4:支付失败
int status = Integer.valueOf(paraMap.get("status"));
int orderStatus = (int) redPacket.get("status");// 订单支付状态
if (2 == orderStatus) {
log.info("订单" + orderNo + "已完成支付,请勿重复提交");
return resultMap;
} else if (status != 1 && status != 2 && status != 3 && status != 4) {
log.error("订单状态或支付状态有误" + status);
throw new FailureException(1, "订单状态或支付状态有误");
}
// 验证订单参数与数据库订单信息书否匹配
if (paraMap.get("sellerid").equals(redPacket.get("sellerid") + "")
&& paraMap.get("pay_type").equals(
redPacket.get("payType") + "")
&& paraMap.get("total_amount").equals(
redPacket.get("totalAmount").toString())
&& paraMap.get("balance").equals(
redPacket.get("balance").toString())
&& paraMap.get("commision").equals(
redPacket.get("commision").toString())
&& paraMap.get("zbalance").equals(
redPacket.get("zbalance").toString())
&& paraMap.get("integral").equals(
redPacket.get("integral").toString())
&& paraMap.get("amount").equals(
redPacket.get("amount").toString())
&& paraMap.get("profit").equals(
redPacket.get("profit").toString())) {
// 更新订单状态和支付状态
paraMap.put("version", version.toString());
Integer result = sellerOrderDao.updateRedPacketState(paraMap);
if (result != 1) {
log.error("更新红包支付订单失败");
throw new FailureException(1, "更新红包支付订单失败");
}
log.info("更新红包支付订单成功");
return resultMap;
} else {
log.error("传入订单参数与后台订单参数不匹配");
throw new FailureException(1, "传入订单参数与后台订单参数不匹配");
}
} catch (Exception e) {
log.error("更新红包支付订单失败", e);
throw new FailureException(1, "更新红包支付订单失败");
}
}
/**
* 更新领取红包记录状态
*/
@Override
public Map<String, String> modifyRedPacketRecord(Map<String, String> paraMap)
throws FailureException, TException {
log.info("更新领取红包记录状态modifyRedPacketRecord:" + paraMap);
Map<String, String> resultMap = new HashMap<String, String>();
resultMap.put("id", paraMap.get("id"));
if (StringUtils.isBlank(paraMap.get("id"))
|| StringUtils.isBlank(paraMap.get("status"))) {
log.error("传入参数有误:" + paraMap);
throw new FailureException(1, "传入参数有误");
}
try {
long id = Long.parseLong(paraMap.get("id"));
int status = Integer.parseInt(paraMap.get("status"));
RedPacketRecord record = new RedPacketRecord();
record.setId(id);
RedPacketRecord redPacketRecord = redPacketRecordDao
.getRedPacketRecord(record);
if (redPacketRecord == null) {
log.error("找不到对应红包【" + id + "】领取记录");
throw new FailureException(2, "找不到对应记录");
}
if (redPacketRecord.getStatus() == status) {
log.info("对应红包【" + id + "】领取记录已经到账");
return resultMap;
}
record.setStatus(status);
redPacketRecordDao.updateByPrimaryKeySelective(record);
} catch (Exception e) {
log.error("更新红包到帐状态异常", e);
throw new FailureException(3, "更新红包到账状态异常");
}
return resultMap;
}
/**
* 验证传入参数
*
* @param paraMap
*/
private boolean verifyParam(Map<String, String> paraMap) {
if (StringUtils.isBlank(paraMap.get("order_no"))
|| StringUtils.isBlank(paraMap.get("sellerid"))
|| StringUtils.isBlank(paraMap.get("status"))
|| StringUtils.isBlank(paraMap.get("pay_type"))
|| StringUtils.isBlank(paraMap.get("pay_id"))
|| StringUtils.isBlank(paraMap.get("total_amount"))
|| StringUtils.isBlank(paraMap.get("balance"))
|| StringUtils.isBlank(paraMap.get("commision"))
|| StringUtils.isBlank(paraMap.get("zbalance"))
|| StringUtils.isBlank(paraMap.get("integral"))
|| StringUtils.isBlank(paraMap.get("profit"))
|| StringUtils.isBlank(paraMap.get("amount"))
|| "null".equals(paraMap.get("order_no"))
|| "null".equals(paraMap.get("sellerid"))
|| "null".equals(paraMap.get("pay_type"))
|| "null".equals(paraMap.get("pay_id"))
|| "null".equals(paraMap.get("total_amount"))) {
return false;
} else {
return true;
}
}
/**
* 更新秒杀订单
*/
@Override
@Transactional(rollbackFor = { FailureException.class, Exception.class,
RuntimeException.class })
public Map<String, String> updateKillOrder(Map<String, String> paraMap)
throws FailureException, TException {
log.info("更新秒杀订单updateKillOrder:" + paraMap);
Map<String, String> resultMap = new HashMap<>();
try {
// 验证参数
if (StringUtils.isBlank(paraMap.get("uid"))
|| StringUtils.isBlank(paraMap.get("amount"))
|| StringUtils.isBlank(paraMap.get("number"))
|| StringUtils.isBlank(paraMap.get("status"))) {
log.error("传入参数部分为空");
throw new FailureException(1, "传入参数部分为空");
}
// 查询秒杀记录
Map<String, Object> activityRecord = activityKillOrderDao
.getActivityRecord(paraMap.get("number"));
if (activityRecord == null) {
log.error("未查询到秒杀记录:" + paraMap.get("number"));
throw new FailureException(1, "未查询到秒杀记录");
}
// 查询活动信息
/*
* Map<String, Object> activity = activityKillOrderDao
* .getActivity(activityRecord.get("activity_id") + ""); if
* (activity == null) { log.error("为查询到活动id为:" +
* activityRecord.get("activity_id") + "的秒杀活动"); throw new
* FailureException(1, "为查询到活动id为:" +
* activityRecord.get("activity_id") + "的秒杀活动"); }
*/
if ((int) activityRecord.get("pay_status") == 1) {
log.info("订单已支付成功,请勿重复提交");
return resultMap;
}
// 匹配传入参数与数据库参数
if (paraMap.get("uid").equals(activityRecord.get("uid").toString())
&& paraMap.get("amount").equals(
activityRecord.get("pay_amount").toString())) {
paraMap.put("version", activityRecord.get("version").toString());// 版本号,用于乐观锁控制
// 发放秒杀奖品
Object serialNo = sendCoupon(activityRecord);
// 更新订单状态
paraMap.put("payTime", formatDate());// 支付时间
paraMap.put("codeid",
serialNo == null ? null : serialNo.toString());// 赠品券序列码
BigDecimal ledgeramount = (BigDecimal) activityRecord.get("pay_amount");
BigDecimal selleramount = this.getKillOrderSellerLedgerAmount(
ledgeramount, (double) activityRecord.get("baseagio"));
paraMap.put("sellerAmount", selleramount.toString());
paraMap.put("isaccount", "0");
Integer result = activityKillOrderDao
.updateActivityRecordStatus(paraMap);
if (result != 1) {
log.error("更新秒杀订单失败");
throw new FailureException(1, "更新秒杀订单失败");
}
try{
if(paraMap.get("status").equals("1")){
//短信下发
orderService.sendSmsForSeller((int)activityRecord.get("sellerid"),paraMap.get("number"),selleramount.toString());
// 调用支付服务,给商户加钱
activityRecord.put("sellerAmount", selleramount.toString());
addMoney(activityRecord);
}
}catch(Exception e){
log.error("处理秒杀订单异常",e);
}
} else {
log.error("传入参数与数据库参数不匹配");
throw new FailureException(1, "传入参数与数据库参数不匹配");
}
log.info("更新秒杀订单状态成功");
return resultMap;
} catch (Exception e) {
log.error("更新秒杀订单失败", e);
throw new FailureException(1, "更新秒杀订单失败");
}
}
/**
* 发放秒杀奖品
*
* @param list
* @param activityRecord
* @throws FailureException
*/
private Object sendCoupon(Map<String, Object> activityRecord)
throws FailureException {
Map<String, Object> packageParam = null;
Map<String, Object> activityRelation = activityKillOrderDao
.getActivityRelaction(activityRecord.get("cid").toString());
if (activityRelation == null) {
log.error("为查询到奖品关联关系:" + activityRecord.get("cid"));
throw new FailureException(1, "为查询到奖品信息");
}
Map<String, Object> sellerCoupon = activityKillOrderDao
.getSellerCoupon(activityRelation.get("award_id").toString());
if (sellerCoupon != null) {
packageParam = packageParam(sellerCoupon, activityRecord);
activityKillOrderDao.insertUserCoupon(packageParam);
} else {
log.error("为查询到奖品信息cid:" + activityRecord.get("cid"));
throw new FailureException(1, "为查询到奖品信息");
}
return packageParam.get("serial_no");
}
/**
* 组装参数
*
* @param sellerCoupon
* @return
*/
private Map<String, Object> packageParam(Map<String, Object> sellerCoupon,
Map<String, Object> couponOrder) {
Map<String, Object> paraMap = new HashMap<>();
paraMap.put("cid", sellerCoupon.get("cid"));
if (sellerCoupon.get("coupon_type") != null
&& (Integer) sellerCoupon.get("coupon_type") == 4) {
String serialNo = sellerActivityService
.getRedisSerial((int) sellerCoupon.get("sellerid"));
if (StringUtils.isBlank(serialNo)) {
throw new RuntimeException("获取序列号出错");
}
paraMap.put("serial_no", ("3" + serialNo));
} else {
paraMap.put("serial_no", null);
}
paraMap.put("denomination", sellerCoupon.get("denomination"));
paraMap.put("get_way", 5);
paraMap.put("get_time", formatDate());
paraMap.put("uid", couponOrder.get("uid"));
paraMap.put("sellerid", sellerCoupon.get("sellerid"));
paraMap.put("use_status", 0);
paraMap.put("start_date", sellerCoupon.get("start_date"));
paraMap.put("end_date", sellerCoupon.get("end_date"));
paraMap.put("bid", couponOrder.get("number"));
paraMap.put("phone", couponOrder.get("phone"));
paraMap.put("activity_id", couponOrder.get("id"));
paraMap.put("activity_type", 3);
return paraMap;
}
private String formatDate() {
return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
}
/**
* 给商家加钱
*
* @param activity
* @param activityRecord
* @throws FailureException
* ,Exception
*/
private void addMoney(Map<String, Object> activityRecord)
throws FailureException, Exception {
// Map<String, String> paraMap = new HashMap<>();
// paraMap.put("uId", activityRecord.get("sellerid") + "");
// paraMap.put("userType", "2");
// paraMap.put("sellerAmount",activityRecord.get("sellerAmount").toString() + "");
// paraMap.put("orderId", activityRecord.get("number") + "_2");
// paraMap.put("remark", "秒杀活动");
// paraMap.put("rType", "22");
// int result = commonServiceImpl.modifyWalletBalance(paraMap);
// if (result != 0) {
// log.info("调用支付服务,给商家加钱失败");
// throw new FailureException(1, "调用支付服务,给商家加钱失败");
// }
XmnWalletBean xmnWallet = new XmnWalletBean();
xmnWallet.setuId(activityRecord.get("sellerid")+"");
xmnWallet.setUserType("2");
xmnWallet.setSellerAmount(activityRecord.get("sellerAmount").toString());
xmnWallet.setrType("22");
xmnWallet.setOrderId(activityRecord.get("number") + "_2");
xmnWallet.setRemark("秒杀活动");
xmnWallet.setOption("0");
xmnWallet.setReturnMode("2");
orderService.insertXmnWalletRedis(xmnWallet);
}
/**
* 更新面对面支付订单
*/
@Override
@Transactional
public Map<String, String> updateMicroOrder(Map<String, String> paraMap)
throws FailureException, TException {
log.info("updateMicroOrder:" + paraMap);
Map<String, String> resultMap = new HashMap<String, String>();
String orderNumber = paraMap.get("orderNumber");
resultMap.put("orderNumber", paraMap.get("orderNumber"));
try {
if (StringUtils.isBlank(orderNumber)
|| StringUtils.isBlank(paraMap.get("payType"))
|| StringUtils.isBlank(paraMap.get("authCode"))
|| StringUtils.isBlank(paraMap.get("totalAmount"))
|| StringUtils.isBlank(paraMap.get("payStatus"))
|| StringUtils.isBlank(paraMap.get("sellerid"))) {
throw new Exception("传入参数不齐");
}
Map<String, Object> orderMap = sellerOrderDao
.getMicroBill(orderNumber);
if (orderMap == null) {
throw new Exception("找不到该订单");
}
log.info("orderMap:" + orderMap);
if (orderMap.get("payStatus") != null
&& orderMap.get("payStatus").toString()
.equals(paraMap.get("payStatus"))) {
return resultMap;
}
if (orderMap.get("payStatus") != null
&& (Integer) orderMap.get("payStatus") == 1) {
throw new Exception("已支付订单不能被修改为其他状态");
}
if (!orderMap.get("totalAmount").toString()
.equals(paraMap.get("totalAmount"))) {
throw new Exception("订单金额错误");
}
// if(!orderMap.get("authCode").toString().equals(paraMap.get("authCode"))){
// throw new Exception("验证错误");
// }
BigDecimal ledgeramount = (BigDecimal) orderMap.get("totalAmount");
double ledgerratio = 1;
BigDecimal selleramount = getMicroOrderSellerLedgerAmount(
ledgeramount, ledgerratio);
Map<String, Object> uMap = new HashMap<String, Object>();
uMap.put("orderNumber", orderNumber);
uMap.put("payStatus", paraMap.get("payStatus"));
uMap.put("authCode", paraMap.get("authCode"));
uMap.put("sellerAmount", selleramount);
uMap.put("isaccount", 0);
sellerOrderDao.updateMicroBill(uMap);
// Map<String, String> walletMap = new HashMap<String, String>();
// walletMap.put("uId", orderMap.get("sellerid") + "");
// walletMap.put("userType", "2");
// walletMap.put("sellerAmount", selleramount + "");
// walletMap.put("orderId", orderNumber + "_2");
// walletMap.put("remark", "面对面扫码支付");
// walletMap.put("rType", "22");
// if (paraMap.get("payStatus").equals("1")) {
// commonServiceImpl.modifyWalletBalance(walletMap);
// }
try{
if (paraMap.get("payStatus").equals("1")) {
//短信下发
orderService.sendSmsForSeller((int)orderMap.get("sellerid"),paraMap.get("orderNumber"),selleramount.toString());
XmnWalletBean xmnWallet = new XmnWalletBean();
xmnWallet.setuId(orderMap.get("sellerid")+"");
xmnWallet.setUserType("2");
xmnWallet.setSellerAmount(selleramount + "");
xmnWallet.setrType("22");
xmnWallet.setOrderId(orderNumber + "_2");
xmnWallet.setRemark("面对面扫码支付");
xmnWallet.setOption("0");
xmnWallet.setReturnMode("3");
orderService.insertXmnWalletRedis(xmnWallet);
}
}catch(Exception sube){
log.error("",sube);
}
} catch (Exception e) {
log.error("更新异常", e);
throw new FailureException(101, e.getMessage());
}
return resultMap;
}
public ResponseData getKillOrderLedgerInfo(String bid) {
ResponseData responseData = new ResponseData();
try {
Map<String, Object> billBean = activityKillOrderDao
.getActivityRecord(bid);
if (billBean == null) {
responseData.setMsg("订单不存在");
responseData.setState(1);
return responseData;
}
if (billBean.get("pay_status") == null
|| (Integer) billBean.get("pay_status") != 1) {
responseData.setMsg("订单尚未支付");
responseData.setState(1);
return responseData;
}
if (billBean.get("baseagio") == null) {
responseData.setMsg("订单未写入分账比例");
responseData.setState(1);
return responseData;
}
Map<String, String> resultMap = new HashMap<String, String>();
resultMap.put("bid", String.valueOf(billBean.get("number")));
resultMap.put("paytype", String.valueOf(billBean.get("pay_type")));
resultMap.put("money",
String.valueOf(billBean.get("sec_kill_amount")));
resultMap.put("payamount",
String.valueOf(billBean.get("pay_amount")));
resultMap.put("wamount", String.valueOf("0"));
resultMap
.put("samount", String.valueOf(billBean.get("pay_amount")));
resultMap.put("preferential", String.valueOf(((BigDecimal) billBean
.get("sec_kill_amount")).subtract((BigDecimal) billBean
.get("pay_amount"))));
resultMap.put("zinteger", String.valueOf("0"));
resultMap.put("liveCoin", String.valueOf(0));
resultMap.put("liveCoinRatio", String.valueOf(0));
resultMap.put("codeid", String.valueOf(billBean.get("codeid")));
BigDecimal ledgeramount = (BigDecimal) billBean.get("pay_amount");
BigDecimal selleramount = this.getKillOrderSellerLedgerAmount(
ledgeramount, (double) billBean.get("baseagio"));
resultMap.put("ledgerratio",
String.valueOf(billBean.get("baseagio")));
resultMap.put("ledgeramount", String.valueOf(ledgeramount));
resultMap.put("selleramount", String.valueOf(selleramount));
resultMap.put("expectedselleramount", resultMap.get("selleramount"));
resultMap.put("sellercommision", String.valueOf(0));
resultMap.put("jointamount", String.valueOf(0));
resultMap.put("xmeramount", String.valueOf(0));
resultMap.put("txmeramount", String.valueOf(0));
resultMap.put("pxmeramount", String.valueOf(0));
resultMap.put("platformamount",
String.valueOf(ledgeramount.subtract(selleramount)));
responseData.setState(0);
responseData.setMsg("查询成功");
responseData.setResultMap(resultMap);
} catch (Exception e) {
log.error("查询异常", e);
responseData.setState(2);
responseData.setMsg("查询异常");
}
return responseData;
}
public ResponseData getMicroOrderLedgerInfo(String bid) {
ResponseData responseData = new ResponseData();
try {
Map<String, Object> billBean = sellerOrderDao.getMicroBill(bid);
if (billBean == null) {
responseData.setMsg("订单不存在");
responseData.setState(1);
return responseData;
}
if (billBean.get("payStatus") == null
|| (Integer) billBean.get("payStatus") != 1) {
responseData.setMsg("订单尚未支付");
responseData.setState(1);
return responseData;
}
Map<String, String> resultMap = new HashMap<String, String>();
resultMap.put("bid", String.valueOf(bid));
resultMap.put("paytype", String.valueOf(billBean.get("payType")));
resultMap.put("money", String.valueOf(billBean.get("totalAmount")));
resultMap.put("payamount",
String.valueOf(billBean.get("totalAmount")));
resultMap.put("wamount", String.valueOf(0));
resultMap.put("samount",
String.valueOf(billBean.get("totalAmount")));
resultMap.put("preferential", String.valueOf(0));
resultMap.put("zinteger", String.valueOf(0));
resultMap.put("liveCoin", String.valueOf(0));
resultMap.put("liveCoinRatio", String.valueOf(0));
resultMap.put("codeid", String.valueOf(""));
double ledgerRatio = 1;
BigDecimal ledgeramount = (BigDecimal) billBean.get("totalAmount");
BigDecimal selleramount = ledgeramount.multiply(
new BigDecimal(Double.toString(ledgerRatio))).setScale(2,
RoundingMode.FLOOR);
if (selleramount.compareTo(BigDecimal.ZERO) <= 0
&& ledgeramount.compareTo(BigDecimal.ZERO) > 0) {
selleramount = new BigDecimal("0.01");
}
resultMap.put("ledgerratio", String.valueOf(ledgerRatio));
resultMap.put("ledgeramount", String.valueOf(ledgeramount));
resultMap.put("selleramount", String.valueOf(selleramount));
resultMap.put("expectedselleramount", resultMap.get("selleramount"));
resultMap.put("sellercommision", String.valueOf(0));
resultMap.put("jointamount", String.valueOf(0));
resultMap.put("xmeramount", String.valueOf(0));
resultMap.put("txmeramount", String.valueOf(0));
resultMap.put("pxmeramount", String.valueOf(0));
resultMap.put("platformamount",
String.valueOf(ledgeramount.subtract(selleramount)));
responseData.setState(0);
responseData.setMsg("查询成功");
responseData.setResultMap(resultMap);
} catch (Exception e) {
log.error("查询异常", e);
responseData.setState(2);
responseData.setMsg("查询异常");
}
return responseData;
}
public BigDecimal getKillOrderSellerLedgerAmount(BigDecimal ledgeramount,
double ledgerRatio) {
BigDecimal selleramount = ledgeramount.multiply(
new BigDecimal(Double.toString(ledgerRatio))).setScale(2,
RoundingMode.FLOOR);
if (selleramount.compareTo(BigDecimal.ZERO) <= 0
&& ledgeramount.compareTo(BigDecimal.ZERO) > 0) {
selleramount = new BigDecimal("0.01");
}
return selleramount;
}
public BigDecimal getMicroOrderSellerLedgerAmount(BigDecimal ledgeramount,
double ledgerRatio) {
BigDecimal selleramount = ledgeramount.multiply(
new BigDecimal(Double.toString(ledgerRatio))).setScale(2,
RoundingMode.FLOOR);
if (selleramount.compareTo(BigDecimal.ZERO) <= 0
&& ledgeramount.compareTo(BigDecimal.ZERO) > 0) {
selleramount = new BigDecimal("0.01");
}
return selleramount;
}
/**
* 更新网红订单
*/
@Override
@Transactional(rollbackFor={FailureException.class,Exception.class,RuntimeException.class})
public Map<String, String> updateCelebrityOrder(Map<String, String> paraMap)
throws FailureException, TException {
log.info("更新网红订单updateCelebrityOrder:" + paraMap);
Map<String,String> resultMap = new HashMap<>();
try {
/**
* 验证参数
*/
if (StringUtils.isBlank(paraMap.get("orderNo"))
|| StringUtils.isBlank(paraMap.get("sellerid"))
|| StringUtils.isBlank(paraMap.get("payType"))
|| StringUtils.isBlank(paraMap.get("price"))
|| StringUtils.isBlank(paraMap.get("payStatus"))){
log.error("传入参数有误"+paraMap);
throw new FailureException(1,"传入参数部分为空");
}
if("1".equals(paraMap.get("payStatus"))){
log.error("订单状态不能为1"+paraMap);
throw new FailureException(1,"订单状态不能为1");
}
resultMap.put("orderNo",paraMap.get("orderNo"));
Map<String, Object> celebrityOrder = sellerOrderDao.getCelebrityOrder(paraMap);
if(celebrityOrder==null){
log.error("未查询到订单号为:"+paraMap.get("orderNo")+"的订单");
throw new FailureException(1,"为查询到订单号为:"+paraMap.get("orderNo")+"的订单");
}
//匹配数据库参数
if(!paraMap.get("sellerid").equals(celebrityOrder.get("seller_id").toString()) ||
!paraMap.get("price").equals(celebrityOrder.get("price").toString())){
log.error("匹配数据库参数失败,传参有误"+paraMap);
throw new FailureException(1,"匹配数据库参数失败");
}
if(paraMap.get("payStatus").equals(celebrityOrder.get("pay_status").toString())){
log.info("订单号为:"+paraMap.get("orderNo")+"的订单已修改状态成功,请勿重复提交");
return resultMap;
}
paraMap.put("payTime",formatDate());
paraMap.put("lock",celebrityOrder.get("version_lock").toString());
//更新订单状态
Integer result = sellerOrderDao.updateCelebrityOrder(paraMap);
if (result !=1) {
log.error("更新网红订单失败");
throw new FailureException(1,"更新网红订单失败");
}
log.info("更新网红订单成功");
return resultMap;
} catch (Exception e) {
log.error("更新网红订单失败",e);
throw new FailureException(1,"更新网红订单失败");
}
}
/**
* 更新金额到账状态
*/
@Override
public Map<String, String> modifyReceiptStatus(Map<String, String> paraMap)
throws FailureException, TException {
log.info("modifyReceiptStatus:"+paraMap);
if(StringUtils.isNotBlank(paraMap.get("type"))
&& StringUtils.isNotBlank(paraMap.get("id"))
&& StringUtils.isNotBlank(paraMap.get("status"))){
if(paraMap.get("type").equals("1")){
return this.modifyRedPacketRecord(paraMap);
}else if(paraMap.get("type").equals("2")){
return this.modifyKillOrderRecord(paraMap);
}else if(paraMap.get("type").equals("3")){
return this.modifyMicroRecord(paraMap);
}
}
throw new FailureException(1, "传入参数错误!");
}
/**
* 更新商家面对面订单分账记录状态
*/
public Map<String, String> modifyMicroRecord(Map<String, String> paraMap)
throws FailureException, TException {
log.info("更新面对面订单分账状态modifyMicroRecord:" + paraMap);
Map<String, String> resultMap = new HashMap<String, String>();
resultMap.put("id", paraMap.get("id"));
if (StringUtils.isBlank(paraMap.get("id"))
|| StringUtils.isBlank(paraMap.get("status"))) {
log.error("传入参数有误:" + paraMap);
throw new FailureException(1, "传入参数有误");
}
try {
String orderNumber = paraMap.get("id");
int status = Integer.parseInt(paraMap.get("status"));
Map<String,Object> microMap = sellerOrderDao
.getMicroBill(orderNumber);
if (microMap == null) {
log.error("找不到对应面对面订单【" + orderNumber + "】记录");
throw new FailureException(2, "找不到对应记录");
}
if (microMap.get("isaccount")!=null && microMap.get("isaccount").toString().equals("1")) {
log.info("对应面对面订单【" + orderNumber + "】分账已经到账");
return resultMap;
}
Map<String,Object> uMap = new HashMap<String,Object>();
uMap.put("orderNumber", orderNumber);
uMap.put("isaccount", status);
sellerOrderDao.updateMicroBill(uMap);
} catch (Exception e) {
log.error("更新面对面订单分账状态异常", e);
throw new FailureException(3, "更新面对面订单分账状态异常");
}
return resultMap;
}
/**
* 更新秒杀分账记录状态
*/
public Map<String, String> modifyKillOrderRecord(Map<String, String> paraMap)
throws FailureException, TException {
log.info("更新秒杀订单分账状态modifyKillOrderRecord:" + paraMap);
Map<String, String> resultMap = new HashMap<String, String>();
resultMap.put("id", paraMap.get("id"));
if (StringUtils.isBlank(paraMap.get("id"))
|| StringUtils.isBlank(paraMap.get("status"))) {
log.error("传入参数有误:" + paraMap);
throw new FailureException(1, "传入参数有误");
}
try {
String number = paraMap.get("id");
int status = Integer.parseInt(paraMap.get("status"));
Map<String,Object> record = activityKillOrderDao.getActivityRecord(number);
if (record == null) {
log.error("找不到秒杀订单【" + number + "】记录");
throw new FailureException(2, "找不到对应记录");
}
if (record.get("isaccount")!=null && record.get("isaccount").toString().equals("1")) {
log.info("对应订单【" + number + "】记录分账已经到账");
return resultMap;
}
Map<String,String> uMap = new HashMap<String,String>();
uMap.put("number", number);
uMap.put("isaccount", status+"");
uMap.put("version", record.get("version").toString());
activityKillOrderDao.updateActivityRecordStatus(uMap);
} catch (Exception e) {
log.error("更新秒杀订单分账到账状态异常", e);
throw new FailureException(3, "更新秒杀订单分账到账状态异常");
}
return resultMap;
}
}
| 29,930 | 0.681545 | 0.676545 | 808 | 33.160892 | 22.874147 | 132 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.455446 | false | false | 4 |
610cbb5ce842a212579d8df9663da88d37740974 | 29,661,044,180,587 | 274d67c5518bf1c91a874d27dccc0fa9d874ed19 | /src/main/java/cn/tedu/store/controller/AddressController.java | 46982c6ca9ab42dea69098207d084fae9bee8b9e | []
| no_license | haima1992/TeduStore | https://github.com/haima1992/TeduStore | 6492609429a32d4ca82c3fb24391df0df9e2d72c | 22a49a50e5d1934dc1bab2b4e4dda5caad5d5354 | refs/heads/master | 2022-12-21T11:48:01.706000 | 2020-05-16T13:58:45 | 2020-05-16T13:58:45 | 175,402,718 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package cn.tedu.store.controller;
import cn.tedu.store.entity.Address;
import cn.tedu.store.entity.Area;
import cn.tedu.store.entity.City;
import cn.tedu.store.entity.Province;
import cn.tedu.store.service.IAddressService;
import cn.tedu.store.service.IAreaService;
import cn.tedu.store.service.ICityService;
import cn.tedu.store.service.IProvinceService;
import cn.tedu.store.service.ex.ServiceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import javax.servlet.http.HttpSession;
import java.util.List;
@Controller
@RequestMapping("/address")
public class AddressController extends BaseController {
@Autowired
private IProvinceService provinceService;
@Autowired
private ICityService cityService;
@Autowired
private IAreaService areaService;
@Autowired
private IAddressService addressService;
@RequestMapping("/list.do")
public String showList(
String action,
Integer id,
ModelMap modelMap, HttpSession session) {
// 判断此次显示列表页时,表单的操作类型
String actionUrl;
String actionTitle;
if (!"edit".equals(action)) {
action = "addnew";
actionUrl = "addnew.do";
actionTitle = "增加";
} else {
action = "edit";
actionUrl = "edit.do";
actionTitle = "修改";
// 如果此次是修改操作,需要读取对应的数据
Address address =
addressService.getAddressById(id);
// 获取修改的地址对应的市列表和区列表
// 并转发到JSP页面
List<City> cities = cityService
.getCityListByProvinceCode(
address.getRecvProvince());
List<Area> areas = areaService
.getAreaListByCityCode(
address.getRecvCity());
// 封装所修改的收货地址数据
modelMap.addAttribute("address", address);
// 封装市列表
modelMap.addAttribute("cities", cities);
// 封装区列表
modelMap.addAttribute("areas", areas);
}
// 获取省的列表
List<Province> provinces
= provinceService.getProvinceList();
// 获取当前登录的用户的uid
Integer uid = getUidFromSession(session);
// 获取收货地址列表
List<Address> addresses =
addressService.getAddressListByUid(uid);
// 封装页面操作类型的名称
modelMap.addAttribute("actionTitle", actionTitle);
// 封装当前页面表单的操作类型和提交位置
modelMap.addAttribute("action", action);
modelMap.addAttribute("actionUrl", actionUrl);
// 封装省的列表,以准备转发
modelMap.addAttribute("provinces", provinces);
// 封装收货地址列表,以准备转发
modelMap.addAttribute("addresses", addresses);
// 执行转发
return "address";
}
@RequestMapping("/addnew.do")
public String handleAddnew(Address address,
HttpSession session) {
// 此次省略N多数据有效性的判断
// 封装uid
Integer uid = getUidFromSession(session);
address.setUid(uid);
// 执行增加
addressService.addnew(address);
// 完成,重定向
return "redirect:list.do";
}
@RequestMapping("/delete.do")
public String handleDelete(
Integer id, HttpSession session) {
// 获取uid
Integer uid = getUidFromSession(session);
// 执行删除
addressService.deleteAddressById(id, uid);
// 重定向到列表页
return "redirect:list.do";
}
@RequestMapping("/set_default.do")
public String handleSetDefault(
@RequestParam("id") Integer id,
HttpSession session,
ModelMap modelMap) {
// 获取uid
Integer uid = getUidFromSession(session);
// 执行
try {
addressService.setDefault(id, uid);
return "redirect:list.do";
} catch (ServiceException e) {
// 封装e.getMessage()
modelMap.addAttribute("err-msg", e.getMessage());
// 转发到专门的错误页面
return "error";
}
}
@RequestMapping(value="/edit.do",
method=RequestMethod.POST)
public String handleEdit(
Address address,
HttpSession session) {
// 获取username
String username =
session.getAttribute("username").toString();
// 获取uid
Integer uid = getUidFromSession(session);
// 向Address对象中封装数据
address.setUid(uid);
try {
// 执行修改
addressService.update(username, address);
// 返回:重定向
return "redirect:list.do";
} catch (ServiceException e) {
// 转发到专门提示错误的页面
return "error";
}
}
}
| UTF-8 | Java | 4,610 | java | AddressController.java | Java | []
| null | []
| package cn.tedu.store.controller;
import cn.tedu.store.entity.Address;
import cn.tedu.store.entity.Area;
import cn.tedu.store.entity.City;
import cn.tedu.store.entity.Province;
import cn.tedu.store.service.IAddressService;
import cn.tedu.store.service.IAreaService;
import cn.tedu.store.service.ICityService;
import cn.tedu.store.service.IProvinceService;
import cn.tedu.store.service.ex.ServiceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import javax.servlet.http.HttpSession;
import java.util.List;
@Controller
@RequestMapping("/address")
public class AddressController extends BaseController {
@Autowired
private IProvinceService provinceService;
@Autowired
private ICityService cityService;
@Autowired
private IAreaService areaService;
@Autowired
private IAddressService addressService;
@RequestMapping("/list.do")
public String showList(
String action,
Integer id,
ModelMap modelMap, HttpSession session) {
// 判断此次显示列表页时,表单的操作类型
String actionUrl;
String actionTitle;
if (!"edit".equals(action)) {
action = "addnew";
actionUrl = "addnew.do";
actionTitle = "增加";
} else {
action = "edit";
actionUrl = "edit.do";
actionTitle = "修改";
// 如果此次是修改操作,需要读取对应的数据
Address address =
addressService.getAddressById(id);
// 获取修改的地址对应的市列表和区列表
// 并转发到JSP页面
List<City> cities = cityService
.getCityListByProvinceCode(
address.getRecvProvince());
List<Area> areas = areaService
.getAreaListByCityCode(
address.getRecvCity());
// 封装所修改的收货地址数据
modelMap.addAttribute("address", address);
// 封装市列表
modelMap.addAttribute("cities", cities);
// 封装区列表
modelMap.addAttribute("areas", areas);
}
// 获取省的列表
List<Province> provinces
= provinceService.getProvinceList();
// 获取当前登录的用户的uid
Integer uid = getUidFromSession(session);
// 获取收货地址列表
List<Address> addresses =
addressService.getAddressListByUid(uid);
// 封装页面操作类型的名称
modelMap.addAttribute("actionTitle", actionTitle);
// 封装当前页面表单的操作类型和提交位置
modelMap.addAttribute("action", action);
modelMap.addAttribute("actionUrl", actionUrl);
// 封装省的列表,以准备转发
modelMap.addAttribute("provinces", provinces);
// 封装收货地址列表,以准备转发
modelMap.addAttribute("addresses", addresses);
// 执行转发
return "address";
}
@RequestMapping("/addnew.do")
public String handleAddnew(Address address,
HttpSession session) {
// 此次省略N多数据有效性的判断
// 封装uid
Integer uid = getUidFromSession(session);
address.setUid(uid);
// 执行增加
addressService.addnew(address);
// 完成,重定向
return "redirect:list.do";
}
@RequestMapping("/delete.do")
public String handleDelete(
Integer id, HttpSession session) {
// 获取uid
Integer uid = getUidFromSession(session);
// 执行删除
addressService.deleteAddressById(id, uid);
// 重定向到列表页
return "redirect:list.do";
}
@RequestMapping("/set_default.do")
public String handleSetDefault(
@RequestParam("id") Integer id,
HttpSession session,
ModelMap modelMap) {
// 获取uid
Integer uid = getUidFromSession(session);
// 执行
try {
addressService.setDefault(id, uid);
return "redirect:list.do";
} catch (ServiceException e) {
// 封装e.getMessage()
modelMap.addAttribute("err-msg", e.getMessage());
// 转发到专门的错误页面
return "error";
}
}
@RequestMapping(value="/edit.do",
method=RequestMethod.POST)
public String handleEdit(
Address address,
HttpSession session) {
// 获取username
String username =
session.getAttribute("username").toString();
// 获取uid
Integer uid = getUidFromSession(session);
// 向Address对象中封装数据
address.setUid(uid);
try {
// 执行修改
addressService.update(username, address);
// 返回:重定向
return "redirect:list.do";
} catch (ServiceException e) {
// 转发到专门提示错误的页面
return "error";
}
}
}
| 4,610 | 0.724365 | 0.724365 | 160 | 24.6 | 15.71512 | 62 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.3625 | false | false | 4 |
12f92f0271a5c311828d4f8fe782a846d6431608 | 19,920,058,346,660 | d57fd5cfc4174f79c6da331de959a42be1cd4c66 | /PBO2-10117072-Latihan39-NilaiTerbesarDanTerkecil/src/pbo2/pkg10117072/latihan39/nilaiterbesardanterkecil/PBO210117072Latihan39NilaiTerbesarDanTerkecil.java | 8efbeb6234c1b6f1ff1c5e41571c2184a4a7987e | []
| no_license | MRiswandaH22/MRiswandaH | https://github.com/MRiswandaH22/MRiswandaH | 0fecabf305f19ec90be95c32ef305f3420348b1f | 99a898caed4a36d57860c06354e3137eff65017d | refs/heads/master | 2020-03-29T11:54:36.610000 | 2018-10-22T07:25:43 | 2018-10-22T07:25:43 | 149,876,347 | 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 pbo2.pkg10117072.latihan39.nilaiterbesardanterkecil;
import java.util.Scanner;
/**
*
* NAMA : Muhammad Riswanda Hasan
* KELAS : PBO2
* NIM : 10117072
* Deskripsi Program : Program ini berisi program untuk menampilkan sebuah
* nilai nilai terbesar dan terkecil dari beberapa data
* contonya data nilai mahasiswa
*/
public class PBO210117072Latihan39NilaiTerbesarDanTerkecil {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
petugas ptgs = new petugas();
Nilai dafNilai = new Nilai();
Scanner scn = new Scanner(System.in);
System.out.println("=====Program Nilai Terbesar dan Terkecil Nilai=====");
ptgs.inputPetugas();
dafNilai.inputJumlahMhs();
// input nilai mhs
for (int i=0; i<dafNilai.jumlahMhs; i++) {
System.out.print("Masukkan Nilai Mahasiswa ke-" + (i + 1) + " = ");
dafNilai.nilaiMhs[i] = scn.nextInt();
dafNilai.hitungNilaiTerbesar(i);
dafNilai.hitungNilaiTerkecil(i);
}
dafNilai.hasilNilaiMhs();
System.out.println("\nNilai Terbesar adalah "+dafNilai.nBesar);
System.out.println("Nilai Terkecil adalah "+dafNilai.nKecil);
System.out.print("\nPetugas : "+ptgs.namaPetugas+"\n");
}
}
| UTF-8 | Java | 1,621 | java | PBO210117072Latihan39NilaiTerbesarDanTerkecil.java | Java | [
{
"context": "va.util.Scanner;\n\n/**\n *\n * NAMA : Muhammad Riswanda Hasan\n * KELAS : PBO2\n * NIM ",
"end": 330,
"score": 0.9998764395713806,
"start": 307,
"tag": "NAME",
"value": "Muhammad Riswanda Hasan"
}
]
| 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 pbo2.pkg10117072.latihan39.nilaiterbesardanterkecil;
import java.util.Scanner;
/**
*
* NAMA : <NAME>
* KELAS : PBO2
* NIM : 10117072
* Deskripsi Program : Program ini berisi program untuk menampilkan sebuah
* nilai nilai terbesar dan terkecil dari beberapa data
* contonya data nilai mahasiswa
*/
public class PBO210117072Latihan39NilaiTerbesarDanTerkecil {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
petugas ptgs = new petugas();
Nilai dafNilai = new Nilai();
Scanner scn = new Scanner(System.in);
System.out.println("=====Program Nilai Terbesar dan Terkecil Nilai=====");
ptgs.inputPetugas();
dafNilai.inputJumlahMhs();
// input nilai mhs
for (int i=0; i<dafNilai.jumlahMhs; i++) {
System.out.print("Masukkan Nilai Mahasiswa ke-" + (i + 1) + " = ");
dafNilai.nilaiMhs[i] = scn.nextInt();
dafNilai.hitungNilaiTerbesar(i);
dafNilai.hitungNilaiTerkecil(i);
}
dafNilai.hasilNilaiMhs();
System.out.println("\nNilai Terbesar adalah "+dafNilai.nBesar);
System.out.println("Nilai Terkecil adalah "+dafNilai.nKecil);
System.out.print("\nPetugas : "+ptgs.namaPetugas+"\n");
}
}
| 1,604 | 0.610117 | 0.589759 | 49 | 32.081635 | 27.12694 | 82 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.428571 | false | false | 4 |
8e27fa03f247849a46ffa121d021ee8da03cb0e4 | 1,236,950,636,538 | c8e662db2494e4092b9316cf8ee6cb73bfac39e7 | /src/step4/tools/AgeValidator.java | ee28f9045ffe76acb5afa590e06a7da76fbc1480 | []
| no_license | scarlettfres/TP-JSF-WebAppCustomscaaa | https://github.com/scarlettfres/TP-JSF-WebAppCustomscaaa | 36a62205b9a27f46ca4bc1232f7069d8e1e2f144 | 762032b56d267d4ecfa2aedbcba8f5067a75b47f | refs/heads/master | 2020-04-09T16:28:19.711000 | 2014-12-04T21:38:02 | 2014-12-04T21:38:02 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package step4.tools;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.FacesValidator;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;
@FacesValidator(value = "AgeValidator")
public class AgeValidator implements Validator
{
@Override
public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException
{
int name =(int)value;
if(name>100)
{
System.out.println("Validator Age: false");
throw new ValidatorException(new FacesMessage("'"+value+"' is not a correct age "));
}
else
{
System.out.println("Validator Age: true");
}
}
}
| UTF-8 | Java | 871 | java | AgeValidator.java | Java | []
| null | []
| package step4.tools;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.FacesValidator;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;
@FacesValidator(value = "AgeValidator")
public class AgeValidator implements Validator
{
@Override
public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException
{
int name =(int)value;
if(name>100)
{
System.out.println("Validator Age: false");
throw new ValidatorException(new FacesMessage("'"+value+"' is not a correct age "));
}
else
{
System.out.println("Validator Age: true");
}
}
}
| 871 | 0.71527 | 0.710677 | 33 | 25.363636 | 26.259565 | 107 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.969697 | false | false | 4 |
499c178865cebb850291bd4323e7d83b593b71e6 | 26,310,969,685,006 | 0112a30993da3f5c2e83bdf07f6a1917a077e40f | /src/com/fodrive/android/BleEventAdapter/service/gatt/SampleGattAttributes.java | 6cbffd852e78b8ebe45dfa87fa08df51f8ba2afa | [
"Apache-2.0"
]
| permissive | bufferhayes/fodrive | https://github.com/bufferhayes/fodrive | 2891b69f094c4c88f4af91439d9f3b18c7857eeb | 86ffd74e304484de2da4505323c7aad8c7ae67be | refs/heads/master | 2021-01-22T20:19:10.113000 | 2015-09-28T09:27:25 | 2015-09-28T09:27:25 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.fodrive.android.BleEventAdapter.service.gatt;
public class SampleGattAttributes
{
public static final String CLIENT_CHARACTERISTIC_CONFIG = "00002902-0000-1000-8000-00805f9b34fb";
public static final String SERVICE_UUID = "0000ffff-0000-1000-8000-00805f9b34fb";
public static final String CHAR_WRITE_UUID = "0000ff01-0000-1000-8000-00805f9b34fb";
// public static final String CHAR_NOTIFY_UUID = "0000ff01-0000-1000-8000-00805f9b34fb";
public static final String CHAR_NOTIFY_UUID = "0000ff02-0000-1000-8000-00805f9b34fb";
}
| UTF-8 | Java | 569 | java | SampleGattAttributes.java | Java | []
| null | []
| package com.fodrive.android.BleEventAdapter.service.gatt;
public class SampleGattAttributes
{
public static final String CLIENT_CHARACTERISTIC_CONFIG = "00002902-0000-1000-8000-00805f9b34fb";
public static final String SERVICE_UUID = "0000ffff-0000-1000-8000-00805f9b34fb";
public static final String CHAR_WRITE_UUID = "0000ff01-0000-1000-8000-00805f9b34fb";
// public static final String CHAR_NOTIFY_UUID = "0000ff01-0000-1000-8000-00805f9b34fb";
public static final String CHAR_NOTIFY_UUID = "0000ff02-0000-1000-8000-00805f9b34fb";
}
| 569 | 0.762742 | 0.534271 | 10 | 55.900002 | 41.229721 | 104 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.7 | false | false | 4 |
545f9645ee97dcc8cc26a5070efb9620d508ae19 | 773,094,147,890 | 67bface5e1caec5399cd8ae7ff7f577519e52f0c | /src/main/java/com/techspirit/casein/repository/api/profile/PhotoRepository.java | 8594ac8752052c2a7a028e631555b700009ce5e0 | []
| no_license | jegensomme/hr-online | https://github.com/jegensomme/hr-online | e0bd576eaf7ce4adcd267222c5ab321659c1cf39 | 000d7e897b3931274ceed4c1217e0cef46dba7f7 | refs/heads/master | 2023-04-15T07:44:48.322000 | 2021-04-22T09:55:26 | 2021-04-22T09:55:26 | 352,625,497 | 3 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.techspirit.casein.repository.api.profile;
import com.techspirit.casein.model.profile.Photo;
import com.techspirit.casein.repository.api.DependentRepository;
public interface PhotoRepository extends DependentRepository<Photo> {
}
| UTF-8 | Java | 243 | java | PhotoRepository.java | Java | []
| null | []
| package com.techspirit.casein.repository.api.profile;
import com.techspirit.casein.model.profile.Photo;
import com.techspirit.casein.repository.api.DependentRepository;
public interface PhotoRepository extends DependentRepository<Photo> {
}
| 243 | 0.847737 | 0.847737 | 7 | 33.714287 | 29.547609 | 69 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.428571 | false | false | 4 |
ba180adbae1f4543e611ebf06f5734f65734e47b | 23,562,190,617,694 | 75bd1ebbeca683573a16ee179a40fa7194c720bd | /MinHeap_PQ.java | 62fe6de96e5ad4df9107b57e003e0841c6e40eb4 | []
| no_license | MeheroonTondra/fewJavaWorks | https://github.com/MeheroonTondra/fewJavaWorks | 3bb38dad6498b4ae6045a9ab46e192e5bcde5774 | 1f3d067e6599199afcbec16eb8a070ceab8002da | refs/heads/master | 2021-07-07T11:15:20.257000 | 2017-09-30T14:36:54 | 2017-09-30T14:36:54 | 105,375,250 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.util.PriorityQueue;
public class MinHeap_PQ {
PriorityQueue<Integer> pq;
private int size;
private int count;
//constructor
public MinHeap_PQ() {
pq = new PriorityQueue<Integer>();
size = 0;
count = 0;
}
//method for adding new values in priority queue
public void insert(int[] x) {
for (int i = 0; i < x.length; i++) {
pq.offer(x[i]);
size = size + 1;
count = count + 1;
}
}
//to get the counter
public int QueCount() {
return count;
}
public int peek() {
return pq.peek();
}
public int extractMin() {
return pq.poll();
}
//size of the queue
public int getSize() {
return pq.size();
}
public void setSize(int s) {
size = s;
}
//removing minimum value from the queue
public void removeMin(int [] arrA) {
int v = arrA[1];
arrA[1] = arrA[getSize() - 1];
size--;
}
public void print() {
System.out.println(pq);
}
//main method for implementation
public static void main(String[] args) {
int[] arrA = { 1, 6, 2, 9, 4, 3, 8 };
MinHeap_PQ i = new MinHeap_PQ();
i.insert(arrA);
i.print();
System.out.println("Min Element in the Priority Queue: "
+ i.extractMin());
System.out.println("Min Element in the Priority Queue: "
+ i.extractMin());
System.out.println("Min Element in the Priority Queue: "
+ i.extractMin());
System.out.println("Priority Queue Size: " + i.getSize());
}
} | UTF-8 | Java | 1,467 | java | MinHeap_PQ.java | Java | []
| null | []
| import java.util.PriorityQueue;
public class MinHeap_PQ {
PriorityQueue<Integer> pq;
private int size;
private int count;
//constructor
public MinHeap_PQ() {
pq = new PriorityQueue<Integer>();
size = 0;
count = 0;
}
//method for adding new values in priority queue
public void insert(int[] x) {
for (int i = 0; i < x.length; i++) {
pq.offer(x[i]);
size = size + 1;
count = count + 1;
}
}
//to get the counter
public int QueCount() {
return count;
}
public int peek() {
return pq.peek();
}
public int extractMin() {
return pq.poll();
}
//size of the queue
public int getSize() {
return pq.size();
}
public void setSize(int s) {
size = s;
}
//removing minimum value from the queue
public void removeMin(int [] arrA) {
int v = arrA[1];
arrA[1] = arrA[getSize() - 1];
size--;
}
public void print() {
System.out.println(pq);
}
//main method for implementation
public static void main(String[] args) {
int[] arrA = { 1, 6, 2, 9, 4, 3, 8 };
MinHeap_PQ i = new MinHeap_PQ();
i.insert(arrA);
i.print();
System.out.println("Min Element in the Priority Queue: "
+ i.extractMin());
System.out.println("Min Element in the Priority Queue: "
+ i.extractMin());
System.out.println("Min Element in the Priority Queue: "
+ i.extractMin());
System.out.println("Priority Queue Size: " + i.getSize());
}
} | 1,467 | 0.592365 | 0.58214 | 65 | 20.6 | 15.832585 | 60 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.953846 | false | false | 4 |
e51ea6c3668787724e0b223b8d1438fc90e711aa | 19,275,813,256,845 | b15f1acf02df28f8c19f74ba14e9a277c51ef858 | /android_application/app/src/main/java/co/edu/eafit/jquiro12/settingup/Welcome.java | 6b9e763f7f169797565ceba23c12269f016ffa7e | []
| no_license | JuanGQCadavid/Nebulon | https://github.com/JuanGQCadavid/Nebulon | 530d32f07138cf4e6a74062e080aadb2f04354d5 | 34cfb8f21f66e547dfa6c00563f7e9ffd4501d1c | refs/heads/master | 2020-03-30T18:09:17.616000 | 2018-12-06T19:12:24 | 2018-12-06T19:12:24 | 151,486,255 | 0 | 0 | null | false | 2018-11-07T13:42:31 | 2018-10-03T22:03:16 | 2018-11-07T13:41:28 | 2018-11-07T13:42:31 | 651 | 0 | 0 | 0 | C++ | false | null | package co.edu.eafit.jquiro12.settingup;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.Serializable;
public class Welcome extends AppCompatActivity {
public static final String EXTRA_MESSAGE = "co.edu.eafit.jquiro12.settingup.MESSAGE";
private final int STANDAR_PORT = 5555;
Button send_button;
EditText user_text;
EditText password_text;
Switch rememberme_switch;
Data program_data;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_welcome);
send_button = (Button) findViewById(R.id.button);
user_text = (EditText) findViewById(R.id.editText);
password_text = (EditText) findViewById(R.id.editText2);
rememberme_switch = (Switch) findViewById(R.id.switch_sesion);
program_data = new Data();
program_data.setPort(STANDAR_PORT);
}
public void sendMessage(View view) {
Intent intent = new Intent(this, HomePage.class);
intent.putExtra("global_data", program_data);
startActivity(intent);
}
public void senddatatoserver(View v) {
String email, password;
boolean rememberme;
//function in the activity that corresponds to the layout button
email = user_text.getText().toString();
password = user_text.getText().toString();
rememberme = rememberme_switch.isActivated();
JSONObject post_dict = new JSONObject();
try {
post_dict.put("e-mail", email);
post_dict.put("password", password);
} catch (JSONException e) {
e.printStackTrace();
}
if (post_dict.length() > 0) {
new SendJsonDataToServer().execute(String.valueOf(post_dict));
}
}
public void wrongCredentials(){
//Toast().show();
TextView textView = findViewById(R.id.textView5);
textView.setVisibility(View.VISIBLE);
}
}
| UTF-8 | Java | 2,310 | java | Welcome.java | Java | []
| null | []
| package co.edu.eafit.jquiro12.settingup;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.Serializable;
public class Welcome extends AppCompatActivity {
public static final String EXTRA_MESSAGE = "co.edu.eafit.jquiro12.settingup.MESSAGE";
private final int STANDAR_PORT = 5555;
Button send_button;
EditText user_text;
EditText password_text;
Switch rememberme_switch;
Data program_data;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_welcome);
send_button = (Button) findViewById(R.id.button);
user_text = (EditText) findViewById(R.id.editText);
password_text = (EditText) findViewById(R.id.editText2);
rememberme_switch = (Switch) findViewById(R.id.switch_sesion);
program_data = new Data();
program_data.setPort(STANDAR_PORT);
}
public void sendMessage(View view) {
Intent intent = new Intent(this, HomePage.class);
intent.putExtra("global_data", program_data);
startActivity(intent);
}
public void senddatatoserver(View v) {
String email, password;
boolean rememberme;
//function in the activity that corresponds to the layout button
email = user_text.getText().toString();
password = user_text.getText().toString();
rememberme = rememberme_switch.isActivated();
JSONObject post_dict = new JSONObject();
try {
post_dict.put("e-mail", email);
post_dict.put("password", password);
} catch (JSONException e) {
e.printStackTrace();
}
if (post_dict.length() > 0) {
new SendJsonDataToServer().execute(String.valueOf(post_dict));
}
}
public void wrongCredentials(){
//Toast().show();
TextView textView = findViewById(R.id.textView5);
textView.setVisibility(View.VISIBLE);
}
}
| 2,310 | 0.666667 | 0.661472 | 84 | 26.5 | 22.67078 | 89 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.583333 | false | false | 4 |
5b4ddba1e2fb5bd4e8264adfeb0d3c7b9c34a196 | 10,316,511,484,780 | 983a68ad24f9a45bb93c0fec84e5b45398ec809d | /src/main/java/com/example/App.java | dbb9a461653774eb7681c26b90be7fe74c1005a9 | []
| no_license | vojislavStanojevikj/hibernatetuts | https://github.com/vojislavStanojevikj/hibernatetuts | c771be29d15fd699953140e993a01fb473265c26 | df5096c1c42f326c3595dd72ab844b60529b2631 | refs/heads/master | 2020-05-31T07:48:16.289000 | 2019-06-05T14:06:02 | 2019-06-05T14:06:02 | 190,173,544 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example;
import com.example.dao.IUserDAO;
import com.example.dao.UserDAO;
import com.example.inheritance.join.FourWheelerJT;
import com.example.inheritance.join.TwoWheelerJT;
import com.example.inheritance.join.WheelerJT;
import com.example.inheritance.tablePerClass.FourWheelerTPC;
import com.example.inheritance.tablePerClass.TwoWheelerTPC;
import com.example.inheritance.tablePerClass.WheelerTPC;
import com.example.model.*;
import com.example.inheritance.singleTable.FourWheeler;
import com.example.inheritance.singleTable.TwoWheeler;
import com.example.inheritance.singleTable.Wheeler;
import com.example.util.BuilderHelper;
import com.example.util.HibernateUtils;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.query.Query;
import java.util.Date;
import java.util.List;
import java.util.Random;
public final class App {
public static void main(String[] args) {
// testUsers();
// testUsersWithVehicle();
// testWheelers();
testReadUsers();
}
private static void testUsers() {
IUserDAO userDAO = new UserDAO();
User user = new UserWithAddress();
user.setUsername(String.format("user%d", new Random().nextInt(Integer.MAX_VALUE)));
user.setDescription(String.format("%s description", user.getUsername()));
user.setCreated(new Date());
((UserWithAddress)user).setHomeAddress(Address.buildTestAddress());
((UserWithAddress)user).setWorkAddress(Address.buildTestAddress());
userDAO.saveUser(user);
UserWithAddress userWithAddress = userDAO.getUser(Long.valueOf(1L), UserWithAddress.class);
System.out.println(userWithAddress);
user = new UserWithCollectionAddress();
user.setUsername(String.format("user%d", new Random().nextInt(Integer.MAX_VALUE)));
user.setDescription(String.format("%s description", user.getUsername()));
user.setCreated(new Date());
((UserWithCollectionAddress)user).getAddresses().add(Address.buildTestAddress());
((UserWithCollectionAddress)user).getAddresses().add(Address.buildTestAddress());
userDAO.saveUser(user);
UserWithCollectionAddress userWithCollectionAddress = userDAO.getUser(Long.valueOf(2), UserWithCollectionAddress.class);
System.out.println(userWithCollectionAddress);
}
private static void testUsersWithVehicle() {
Transaction transaction = null;
try(Session session = HibernateUtils.getSessionFactory().openSession()) {
transaction = session.beginTransaction();
// UserWithVehicleOneToOne userWithVehicleOneToOne = BuilderHelper.buildUser(UserWithVehicleOneToOne.class);
// userWithVehicleOneToOne.setVehicle(BuilderHelper.buildTestVehicle());
//
// session.save(userWithVehicleOneToOne);
// session.save(userWithVehicleOneToOne.getVehicle());
//
//
// UserWithVehiclesOneToMany userWithVehiclesOneToMany = BuilderHelper.buildUser(UserWithVehiclesOneToMany.class);
// userWithVehiclesOneToMany.getVehicles().add(BuilderHelper.buildTestVehicle());
// userWithVehiclesOneToMany.getVehicles().add(BuilderHelper.buildTestVehicle());
// session.save(userWithVehiclesOneToMany);
// userWithVehiclesOneToMany.getVehicles().forEach(vehicle -> vehicle.setUserWithVehiclesOneToMany(userWithVehiclesOneToMany));
// userWithVehiclesOneToMany.getVehicles().forEach(session::save);
//
//
// UserWithVehicles2OneToMany userWithVehicles2OneToMany = BuilderHelper.buildUser(UserWithVehicles2OneToMany.class);
// userWithVehicles2OneToMany.getVehicle2s().add(BuilderHelper.buildTestVehicle2());
// userWithVehicles2OneToMany.getVehicle2s().add(BuilderHelper.buildTestVehicle2());
// session.save(userWithVehicles2OneToMany);
// userWithVehicles2OneToMany.getVehicle2s().forEach(vehicle -> vehicle.setUserWithVehicles2OneToMany(userWithVehicles2OneToMany));
// userWithVehicles2OneToMany.getVehicle2s().forEach(session::save);
UserWithVehiclesManyToMany userWithVehiclesManyToMany = BuilderHelper.buildUser(UserWithVehiclesManyToMany.class);
userWithVehiclesManyToMany.getVehicle3s().add(BuilderHelper.buildTestVehicle3());
userWithVehiclesManyToMany.getVehicle3s().add(BuilderHelper.buildTestVehicle3());
userWithVehiclesManyToMany.getVehicle3s().forEach(vehicle3 -> vehicle3.getUsers().add(userWithVehiclesManyToMany));
UserWithVehiclesManyToMany userWithVehiclesManyToMany2 = BuilderHelper.buildUser(UserWithVehiclesManyToMany.class);
userWithVehiclesManyToMany2.getVehicle3s().add(BuilderHelper.buildTestVehicle3());
userWithVehiclesManyToMany2.getVehicle3s().add(userWithVehiclesManyToMany.getVehicle3s().stream().findFirst().get());
userWithVehiclesManyToMany2.getVehicle3s().forEach(vehicle3 -> vehicle3.getUsers().add(userWithVehiclesManyToMany2));
session.persist(userWithVehiclesManyToMany);
session.persist(userWithVehiclesManyToMany2);
transaction.commit();
} catch (Exception e) {
if (null != transaction) {
transaction.rollback();
}
}
}
private static void testWheelers() {
Transaction transaction = null;
try(Session session = HibernateUtils.getSessionFactory().openSession()) {
transaction = session.beginTransaction();
Wheeler wheeler = BuilderHelper.buildWheeler(Wheeler.class);
TwoWheeler twoWheeler = BuilderHelper.buildWheeler(TwoWheeler.class);
twoWheeler.setSteeringHandle("Bike");
FourWheeler fourWheeler = BuilderHelper.buildWheeler(FourWheeler.class);
fourWheeler.setSteeringWheel("Car");
session.save(wheeler);
session.save(twoWheeler);
session.save(fourWheeler);
WheelerTPC wheelerTPC = BuilderHelper.buildWheelerTPC(WheelerTPC.class);
TwoWheelerTPC twoWheelerTPC = BuilderHelper.buildWheelerTPC(TwoWheelerTPC.class);
twoWheelerTPC.setSteeringHandle("Bike");
FourWheelerTPC fourWheelerTPC = BuilderHelper.buildWheelerTPC(FourWheelerTPC.class);
fourWheelerTPC.setSteeringWheel("Car");
session.save(wheelerTPC);
session.save(twoWheelerTPC);
session.save(fourWheelerTPC);
WheelerJT wheelerJT = BuilderHelper.buildWheelerJT(WheelerJT.class);
TwoWheelerJT twoWheelerJT = BuilderHelper.buildWheelerJT(TwoWheelerJT.class);
twoWheelerJT.setSteeringHandle("Bike");
FourWheelerJT fourWheelerJT = BuilderHelper.buildWheelerJT(FourWheelerJT.class);
fourWheelerJT.setSteeringWheel("Car");
session.save(wheelerJT);
session.save(twoWheelerJT);
session.save(fourWheelerJT);
transaction.commit();
} catch (Exception e) {
if (null != transaction) {
transaction.rollback();
}
}
}
private static void testReadUsers() {
Transaction transaction = null;
try(Session session = HibernateUtils.getSessionFactory().openSession()) {
transaction = session.beginTransaction();
for (int i = 0; i< 10; i++) {
UserDetails userDetails = BuilderHelper.buildUser(UserDetails.class);
userDetails.setName(String.format("User%d", i));
session.save(userDetails);
}
transaction.commit();
} catch (Exception e) {
if (null != transaction) {
transaction.rollback();
}
}
try(Session session = HibernateUtils.getSessionFactory().openSession()) {
transaction = session.beginTransaction();
Query query = session.getNamedQuery("UserDetails.byId");
query.setParameter("id", Long.valueOf(5));
System.out.println(((UserDetails)query.uniqueResult()).getName());
query = session.getNamedNativeQuery("UserDetails.byName");
query.setParameter("name", "User3");
System.out.println(((UserDetails)query.uniqueResult()).getName());
transaction.commit();
} catch (Exception e) {
if (null != transaction) {
transaction.rollback();
}
}
}
} | UTF-8 | Java | 8,589 | java | App.java | Java | [
{
"context": "ddress();\n user.setUsername(String.format(\"user%d\", new Random().nextInt(Integer.MAX_VALUE)));\n ",
"end": 1243,
"score": 0.9774975180625916,
"start": 1237,
"tag": "USERNAME",
"value": "user%d"
},
{
"context": "ddress();\n user.setUsername(String.format(\"user%d\", new Random().nextInt(Integer.MAX_VALUE)));\n ",
"end": 1834,
"score": 0.949508011341095,
"start": 1828,
"tag": "USERNAME",
"value": "user%d"
},
{
"context": "me\");\n query.setParameter(\"name\", \"User3\");\n System.out.println(((UserDetails)q",
"end": 8329,
"score": 0.901209831237793,
"start": 8328,
"tag": "USERNAME",
"value": "3"
}
]
| null | []
| package com.example;
import com.example.dao.IUserDAO;
import com.example.dao.UserDAO;
import com.example.inheritance.join.FourWheelerJT;
import com.example.inheritance.join.TwoWheelerJT;
import com.example.inheritance.join.WheelerJT;
import com.example.inheritance.tablePerClass.FourWheelerTPC;
import com.example.inheritance.tablePerClass.TwoWheelerTPC;
import com.example.inheritance.tablePerClass.WheelerTPC;
import com.example.model.*;
import com.example.inheritance.singleTable.FourWheeler;
import com.example.inheritance.singleTable.TwoWheeler;
import com.example.inheritance.singleTable.Wheeler;
import com.example.util.BuilderHelper;
import com.example.util.HibernateUtils;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.query.Query;
import java.util.Date;
import java.util.List;
import java.util.Random;
public final class App {
public static void main(String[] args) {
// testUsers();
// testUsersWithVehicle();
// testWheelers();
testReadUsers();
}
private static void testUsers() {
IUserDAO userDAO = new UserDAO();
User user = new UserWithAddress();
user.setUsername(String.format("user%d", new Random().nextInt(Integer.MAX_VALUE)));
user.setDescription(String.format("%s description", user.getUsername()));
user.setCreated(new Date());
((UserWithAddress)user).setHomeAddress(Address.buildTestAddress());
((UserWithAddress)user).setWorkAddress(Address.buildTestAddress());
userDAO.saveUser(user);
UserWithAddress userWithAddress = userDAO.getUser(Long.valueOf(1L), UserWithAddress.class);
System.out.println(userWithAddress);
user = new UserWithCollectionAddress();
user.setUsername(String.format("user%d", new Random().nextInt(Integer.MAX_VALUE)));
user.setDescription(String.format("%s description", user.getUsername()));
user.setCreated(new Date());
((UserWithCollectionAddress)user).getAddresses().add(Address.buildTestAddress());
((UserWithCollectionAddress)user).getAddresses().add(Address.buildTestAddress());
userDAO.saveUser(user);
UserWithCollectionAddress userWithCollectionAddress = userDAO.getUser(Long.valueOf(2), UserWithCollectionAddress.class);
System.out.println(userWithCollectionAddress);
}
private static void testUsersWithVehicle() {
Transaction transaction = null;
try(Session session = HibernateUtils.getSessionFactory().openSession()) {
transaction = session.beginTransaction();
// UserWithVehicleOneToOne userWithVehicleOneToOne = BuilderHelper.buildUser(UserWithVehicleOneToOne.class);
// userWithVehicleOneToOne.setVehicle(BuilderHelper.buildTestVehicle());
//
// session.save(userWithVehicleOneToOne);
// session.save(userWithVehicleOneToOne.getVehicle());
//
//
// UserWithVehiclesOneToMany userWithVehiclesOneToMany = BuilderHelper.buildUser(UserWithVehiclesOneToMany.class);
// userWithVehiclesOneToMany.getVehicles().add(BuilderHelper.buildTestVehicle());
// userWithVehiclesOneToMany.getVehicles().add(BuilderHelper.buildTestVehicle());
// session.save(userWithVehiclesOneToMany);
// userWithVehiclesOneToMany.getVehicles().forEach(vehicle -> vehicle.setUserWithVehiclesOneToMany(userWithVehiclesOneToMany));
// userWithVehiclesOneToMany.getVehicles().forEach(session::save);
//
//
// UserWithVehicles2OneToMany userWithVehicles2OneToMany = BuilderHelper.buildUser(UserWithVehicles2OneToMany.class);
// userWithVehicles2OneToMany.getVehicle2s().add(BuilderHelper.buildTestVehicle2());
// userWithVehicles2OneToMany.getVehicle2s().add(BuilderHelper.buildTestVehicle2());
// session.save(userWithVehicles2OneToMany);
// userWithVehicles2OneToMany.getVehicle2s().forEach(vehicle -> vehicle.setUserWithVehicles2OneToMany(userWithVehicles2OneToMany));
// userWithVehicles2OneToMany.getVehicle2s().forEach(session::save);
UserWithVehiclesManyToMany userWithVehiclesManyToMany = BuilderHelper.buildUser(UserWithVehiclesManyToMany.class);
userWithVehiclesManyToMany.getVehicle3s().add(BuilderHelper.buildTestVehicle3());
userWithVehiclesManyToMany.getVehicle3s().add(BuilderHelper.buildTestVehicle3());
userWithVehiclesManyToMany.getVehicle3s().forEach(vehicle3 -> vehicle3.getUsers().add(userWithVehiclesManyToMany));
UserWithVehiclesManyToMany userWithVehiclesManyToMany2 = BuilderHelper.buildUser(UserWithVehiclesManyToMany.class);
userWithVehiclesManyToMany2.getVehicle3s().add(BuilderHelper.buildTestVehicle3());
userWithVehiclesManyToMany2.getVehicle3s().add(userWithVehiclesManyToMany.getVehicle3s().stream().findFirst().get());
userWithVehiclesManyToMany2.getVehicle3s().forEach(vehicle3 -> vehicle3.getUsers().add(userWithVehiclesManyToMany2));
session.persist(userWithVehiclesManyToMany);
session.persist(userWithVehiclesManyToMany2);
transaction.commit();
} catch (Exception e) {
if (null != transaction) {
transaction.rollback();
}
}
}
private static void testWheelers() {
Transaction transaction = null;
try(Session session = HibernateUtils.getSessionFactory().openSession()) {
transaction = session.beginTransaction();
Wheeler wheeler = BuilderHelper.buildWheeler(Wheeler.class);
TwoWheeler twoWheeler = BuilderHelper.buildWheeler(TwoWheeler.class);
twoWheeler.setSteeringHandle("Bike");
FourWheeler fourWheeler = BuilderHelper.buildWheeler(FourWheeler.class);
fourWheeler.setSteeringWheel("Car");
session.save(wheeler);
session.save(twoWheeler);
session.save(fourWheeler);
WheelerTPC wheelerTPC = BuilderHelper.buildWheelerTPC(WheelerTPC.class);
TwoWheelerTPC twoWheelerTPC = BuilderHelper.buildWheelerTPC(TwoWheelerTPC.class);
twoWheelerTPC.setSteeringHandle("Bike");
FourWheelerTPC fourWheelerTPC = BuilderHelper.buildWheelerTPC(FourWheelerTPC.class);
fourWheelerTPC.setSteeringWheel("Car");
session.save(wheelerTPC);
session.save(twoWheelerTPC);
session.save(fourWheelerTPC);
WheelerJT wheelerJT = BuilderHelper.buildWheelerJT(WheelerJT.class);
TwoWheelerJT twoWheelerJT = BuilderHelper.buildWheelerJT(TwoWheelerJT.class);
twoWheelerJT.setSteeringHandle("Bike");
FourWheelerJT fourWheelerJT = BuilderHelper.buildWheelerJT(FourWheelerJT.class);
fourWheelerJT.setSteeringWheel("Car");
session.save(wheelerJT);
session.save(twoWheelerJT);
session.save(fourWheelerJT);
transaction.commit();
} catch (Exception e) {
if (null != transaction) {
transaction.rollback();
}
}
}
private static void testReadUsers() {
Transaction transaction = null;
try(Session session = HibernateUtils.getSessionFactory().openSession()) {
transaction = session.beginTransaction();
for (int i = 0; i< 10; i++) {
UserDetails userDetails = BuilderHelper.buildUser(UserDetails.class);
userDetails.setName(String.format("User%d", i));
session.save(userDetails);
}
transaction.commit();
} catch (Exception e) {
if (null != transaction) {
transaction.rollback();
}
}
try(Session session = HibernateUtils.getSessionFactory().openSession()) {
transaction = session.beginTransaction();
Query query = session.getNamedQuery("UserDetails.byId");
query.setParameter("id", Long.valueOf(5));
System.out.println(((UserDetails)query.uniqueResult()).getName());
query = session.getNamedNativeQuery("UserDetails.byName");
query.setParameter("name", "User3");
System.out.println(((UserDetails)query.uniqueResult()).getName());
transaction.commit();
} catch (Exception e) {
if (null != transaction) {
transaction.rollback();
}
}
}
} | 8,589 | 0.685062 | 0.680056 | 213 | 39.32864 | 36.518246 | 142 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.610329 | false | false | 4 |
0f5aa813d53efd2563b8ad9b8385c55307aee731 | 10,316,511,483,326 | 812ccdb730accd3010fa09b77006e8abd0ec31f2 | /src/main/java/com/somecompany/trading/Order.java | bb4bed6832e65e2716c240ad9e45fb8e9171b35a | []
| no_license | genericarati/Event-Handling-Spring-Boot | https://github.com/genericarati/Event-Handling-Spring-Boot | b26cbb9c10fd01a275b10edca8084a7e1bd16bc4 | 7cee0764e985878ad5ab3fa8a5f65ca479021f33 | refs/heads/master | 2021-05-01T13:03:38.218000 | 2018-03-04T23:46:36 | 2018-03-04T23:46:36 | 121,069,402 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.somecompany.trading;
public class Order {
public String ordernumber;
public String dealer;
public Order() {
}
public Order(String ordernumber, String dealer) {
this.ordernumber = ordernumber;
this.dealer = dealer;
}
@Override
public String toString() {
return "Order [ordernumber=" + ordernumber + ", dealer=" + dealer + "]";
}
}
| UTF-8 | Java | 362 | java | Order.java | Java | []
| null | []
| package com.somecompany.trading;
public class Order {
public String ordernumber;
public String dealer;
public Order() {
}
public Order(String ordernumber, String dealer) {
this.ordernumber = ordernumber;
this.dealer = dealer;
}
@Override
public String toString() {
return "Order [ordernumber=" + ordernumber + ", dealer=" + dealer + "]";
}
}
| 362 | 0.69337 | 0.69337 | 20 | 17.1 | 19.382725 | 74 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.15 | false | false | 4 |
27a22a10df002fa37109a92aa56f75b5aadb7ad5 | 29,910,152,283,192 | 9fa24f4ecd5f49b893f28eff93faad6dfb3a710f | /class/java/source-/class_02/src/day04/Ex01.java | 1fc0dfc1737a9e5930333e6e5156e7227f5d7355 | []
| no_license | mygusdnd3/Java_Practice | https://github.com/mygusdnd3/Java_Practice | 91c420790d2bdf960ec542ecf40be5d421ca2111 | e398221f771ef3634c46059a691409ae0f165572 | refs/heads/master | 2023-07-01T11:31:54.209000 | 2020-10-19T09:19:02 | 2020-10-19T09:19:02 | 280,029,898 | 0 | 0 | null | false | 2021-08-02T17:04:54 | 2020-07-16T02:15:19 | 2020-10-19T09:19:23 | 2021-08-02T17:04:52 | 315,465 | 0 | 0 | 1 | Java | false | false | package day04;
import java.util.*;
/*
* 랜덤하게 두자리 숫자를 발생 시키고
* 키보드로 두자리 숫자를 입력하면 발생된 숫자보다 입력한 숫자가 큰수인지 아닌지
* 판별해주는 프로그램을 작성하세요.
* 심화 ]
* 입력한 수와 차는 얼마인지
*/
import javax.swing.*;
public class Ex01 {
public static void main(String[] args) {
int rand = (int)(Math.random()*(99-10+1)+1);
System.out.println(rand);
String snum = JOptionPane.showInputDialog("비교하고 싶은 두자리 숫자를 입력하세요");
JOptionPane.showMessageDialog(null, "입력한 숫자 :" +snum);
int num = Integer.parseInt(snum);
Scanner sc = new Scanner(System.in);
System.out.print("숫자 입력 : ");
//int num = sc.nextInt();
String result = (rand >num )? //랜덤이 더 크냐?
(rand-num+"만큼 랜덤 숫자가 더 크다.")
:(num-rand)+"만큼 입력한 숫자가 더크다";//참
System.out.printf("입력한 숫자는 [%d]이며 랜덤 숫자는 [%d]이기 때문에 , %s", num, rand, result);
}
}
| UTF-8 | Java | 1,166 | java | Ex01.java | Java | []
| null | []
| package day04;
import java.util.*;
/*
* 랜덤하게 두자리 숫자를 발생 시키고
* 키보드로 두자리 숫자를 입력하면 발생된 숫자보다 입력한 숫자가 큰수인지 아닌지
* 판별해주는 프로그램을 작성하세요.
* 심화 ]
* 입력한 수와 차는 얼마인지
*/
import javax.swing.*;
public class Ex01 {
public static void main(String[] args) {
int rand = (int)(Math.random()*(99-10+1)+1);
System.out.println(rand);
String snum = JOptionPane.showInputDialog("비교하고 싶은 두자리 숫자를 입력하세요");
JOptionPane.showMessageDialog(null, "입력한 숫자 :" +snum);
int num = Integer.parseInt(snum);
Scanner sc = new Scanner(System.in);
System.out.print("숫자 입력 : ");
//int num = sc.nextInt();
String result = (rand >num )? //랜덤이 더 크냐?
(rand-num+"만큼 랜덤 숫자가 더 크다.")
:(num-rand)+"만큼 입력한 숫자가 더크다";//참
System.out.printf("입력한 숫자는 [%d]이며 랜덤 숫자는 [%d]이기 때문에 , %s", num, rand, result);
}
}
| 1,166 | 0.574885 | 0.563364 | 38 | 20.842106 | 21.305456 | 81 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.684211 | false | false | 4 |
59c88fea7e047ee1d6dbb5e576c841abc408575d | 16,054,587,787,335 | 65a7d5672c51fce125a56a1d94317ffb74b84afa | /first/src/main/java/com/cqjtu/service/IEmpService.java | 03a67749df258d77731e468e1cb885c137c6d3d1 | []
| no_license | Eddie-LiYM/shixun | https://github.com/Eddie-LiYM/shixun | 1df16b0dd9acf8b336b58d4aae06498b22b4cab1 | 8d6f0c753cf2e13774691722265a83bf2c2bef4c | refs/heads/master | 2023-08-11T09:22:33.110000 | 2019-12-25T15:54:23 | 2019-12-25T15:54:23 | 230,037,724 | 0 | 0 | null | false | 2023-07-23T01:14:26 | 2019-12-25T03:51:56 | 2019-12-25T15:54:51 | 2023-07-23T01:14:26 | 3,618 | 0 | 0 | 7 | Java | false | false | package com.cqjtu.service;
import java.util.ArrayList;
import com.cqjtu.pojo.Emp;
import com.cqjtu.pojo.Staff;
/**
* 接口
* @author HASEE
*
*/
public interface IEmpService {
/**
* 登录时查询是否存在此对象
* @param nickname
* @param password
* @return
*/
Emp findEmpByNicknameAndPassword(String nickname, String password);
/**
* 根据注册信息判断用户是否已经存在
* @param nickname
* @return
*/
int findEmpByNickname(String nickname);
/**
* 注册信息
* @param emp
*/
void registerEmp(Emp emp);
void addStaff(Staff staff);
ArrayList<Staff> findStaff();
}
| UTF-8 | Java | 635 | java | IEmpService.java | Java | [
{
"context": "\nimport com.cqjtu.pojo.Staff;\n/**\n * 接口\n * @author HASEE\n *\n */\n\npublic interface IEmpService {\n\n\t/**\n\t * ",
"end": 139,
"score": 0.9996616244316101,
"start": 134,
"tag": "USERNAME",
"value": "HASEE"
}
]
| null | []
| package com.cqjtu.service;
import java.util.ArrayList;
import com.cqjtu.pojo.Emp;
import com.cqjtu.pojo.Staff;
/**
* 接口
* @author HASEE
*
*/
public interface IEmpService {
/**
* 登录时查询是否存在此对象
* @param nickname
* @param password
* @return
*/
Emp findEmpByNicknameAndPassword(String nickname, String password);
/**
* 根据注册信息判断用户是否已经存在
* @param nickname
* @return
*/
int findEmpByNickname(String nickname);
/**
* 注册信息
* @param emp
*/
void registerEmp(Emp emp);
void addStaff(Staff staff);
ArrayList<Staff> findStaff();
}
| 635 | 0.666667 | 0.666667 | 44 | 11.886364 | 14.164963 | 68 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.727273 | false | false | 4 |
6d29048411ecfd6bc79b41ea0989f8caa6da8d9e | 16,054,587,787,704 | e749e11ab05556c519637b31ae9b22af2225320e | /downloads/battleships-client-source/battleships/scene/components/ship/Cruiser.java | 1270c38780f46d5837ea6121f84e6272239c46da | []
| no_license | Deahgib/Website | https://github.com/Deahgib/Website | 59be70d857d798d3c1e74184c441edd4407c740f | 9a8829e81115736fb4c8ab6cbc16e9657c1577f7 | refs/heads/master | 2020-04-17T20:01:37.981000 | 2019-06-11T21:49:35 | 2019-06-11T21:49:35 | 166,888,324 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package battleships.scene.components.ship;
import battleships.engine.TextureManager;
/**
*
* @author Louis Bennette
*/
public class Cruiser extends AbstractShip{
public Cruiser(double x, double y, double height){
super(x, y, 3*height, height);
this.size = 3;
this.name = "Cruiser";
this.setTexture(TextureManager.loadTexture("cruiser"));
}
public Cruiser(){
super();
this.size = 3;
this.name = "Cruiser";
}
}
| UTF-8 | Java | 491 | java | Cruiser.java | Java | [
{
"context": "tleships.engine.TextureManager;\n\n/**\n *\n * @author Louis Bennette\n */\npublic class Cruiser extends AbstractShip{\n ",
"end": 119,
"score": 0.9998733997344971,
"start": 105,
"tag": "NAME",
"value": "Louis Bennette"
}
]
| null | []
| package battleships.scene.components.ship;
import battleships.engine.TextureManager;
/**
*
* @author <NAME>
*/
public class Cruiser extends AbstractShip{
public Cruiser(double x, double y, double height){
super(x, y, 3*height, height);
this.size = 3;
this.name = "Cruiser";
this.setTexture(TextureManager.loadTexture("cruiser"));
}
public Cruiser(){
super();
this.size = 3;
this.name = "Cruiser";
}
}
| 483 | 0.613035 | 0.606925 | 22 | 21.318182 | 18.731079 | 63 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.636364 | false | false | 4 |
b132252fc752787c0b776d25989a1880972f4ad2 | 29,231,547,452,713 | fc430bf2e15d970b10956dfebb559b2bbe9e3868 | /TreeExample.java | 2bf43c81c8b32f81f829b807a5eca7544707ffb2 | []
| no_license | AaronStahley/CSC205 | https://github.com/AaronStahley/CSC205 | 6525d6be278ee48127e16113807585d8759f2962 | 71d28401c934d45e074de0462835a470d434f90d | refs/heads/master | 2021-01-19T10:26:07.239000 | 2015-05-01T00:00:57 | 2015-05-01T00:00:57 | 34,313,396 | 0 | 1 | null | false | 2015-04-28T01:27:48 | 2015-04-21T08:09:11 | 2015-04-28T00:10:48 | 2015-04-28T01:27:47 | 0 | 0 | 1 | 1 | Java | null | null | import java.util.Iterator;
import Project8.*;
public class TreeExample {
public static void main(String[] args) {
// A
// / \
// B E
// / \ /
// C D F
LinkedBinaryTree<String> c = new LinkedBinaryTree<String>("C");
LinkedBinaryTree<String> d = new LinkedBinaryTree<String>("D");
LinkedBinaryTree<String> f = new LinkedBinaryTree<String>("F");
LinkedBinaryTree<String> b = new LinkedBinaryTree<String>("B",c,d);
LinkedBinaryTree<String> e = new LinkedBinaryTree<String>("E",f,null);
LinkedBinaryTree<String> a = new LinkedBinaryTree<String>("A",b,e);
System.out.println("toString(): " + a);
System.out.println("getHeight() = " + a.getHeight());
System.out.println("size() = " + a.size());
System.out.println("getLeft() of A: " + a.getLeft().getRootElement());
System.out.println("getRight() of A: " + a.getRight().getRootElement());
if ( (a.contains("A")) && (a.contains("B")) && (a.contains("D")) && (a.contains("E")) && (a.contains("Z") == false)) {
System.out.println("contains() works!");
}
else
System.out.println("contains() does not work!");
System.out.println();
System.out.print ("Pre-order traversal: ");
Iterator<String> pre = a.iteratorPreOrder();
while (pre.hasNext()) {
System.out.print (pre.next());
}
System.out.println();
System.out.print ("In-order traversal: ");
Iterator<String> in = a.iteratorInOrder();
while (in.hasNext()) {
System.out.print (in.next());
}
System.out.println();
System.out.print ("Post-order traversal: ");
Iterator<String> post = a.iteratorPostOrder();
while (post.hasNext()) {
System.out.print (post.next());
}
System.out.println();
}
}
| UTF-8 | Java | 1,710 | java | TreeExample.java | Java | []
| null | []
| import java.util.Iterator;
import Project8.*;
public class TreeExample {
public static void main(String[] args) {
// A
// / \
// B E
// / \ /
// C D F
LinkedBinaryTree<String> c = new LinkedBinaryTree<String>("C");
LinkedBinaryTree<String> d = new LinkedBinaryTree<String>("D");
LinkedBinaryTree<String> f = new LinkedBinaryTree<String>("F");
LinkedBinaryTree<String> b = new LinkedBinaryTree<String>("B",c,d);
LinkedBinaryTree<String> e = new LinkedBinaryTree<String>("E",f,null);
LinkedBinaryTree<String> a = new LinkedBinaryTree<String>("A",b,e);
System.out.println("toString(): " + a);
System.out.println("getHeight() = " + a.getHeight());
System.out.println("size() = " + a.size());
System.out.println("getLeft() of A: " + a.getLeft().getRootElement());
System.out.println("getRight() of A: " + a.getRight().getRootElement());
if ( (a.contains("A")) && (a.contains("B")) && (a.contains("D")) && (a.contains("E")) && (a.contains("Z") == false)) {
System.out.println("contains() works!");
}
else
System.out.println("contains() does not work!");
System.out.println();
System.out.print ("Pre-order traversal: ");
Iterator<String> pre = a.iteratorPreOrder();
while (pre.hasNext()) {
System.out.print (pre.next());
}
System.out.println();
System.out.print ("In-order traversal: ");
Iterator<String> in = a.iteratorInOrder();
while (in.hasNext()) {
System.out.print (in.next());
}
System.out.println();
System.out.print ("Post-order traversal: ");
Iterator<String> post = a.iteratorPostOrder();
while (post.hasNext()) {
System.out.print (post.next());
}
System.out.println();
}
}
| 1,710 | 0.626901 | 0.626316 | 62 | 26.580645 | 26.56735 | 120 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.080645 | false | false | 4 |
d2c40a56cdb4d5528590235c9b27ca91b05deabf | 15,710,990,410,303 | 1114fe9fe280cfd4ae582983348c9ccfd16b1fdd | /src/main/java/util/security/JWTHelper.java | 097d34f0dea17538bf1c1706915c35484b9e0d15 | []
| no_license | zebybez/JEA | https://github.com/zebybez/JEA | ad1ea6401e38cf71676aa63f8768063b518db26b | 158c02fd21ad4eb091532c92f747cea56cfd637c | refs/heads/master | 2020-04-20T22:28:18.774000 | 2019-06-20T01:19:03 | 2019-06-20T01:19:03 | 169,140,704 | 0 | 1 | null | false | 2019-06-20T01:19:04 | 2019-02-04T20:03:23 | 2019-06-19T15:08:38 | 2019-06-20T01:19:04 | 223 | 0 | 1 | 0 | Java | false | false | package util.security;
import com.google.gson.Gson;
import io.jsonwebtoken.*;
import util.Constants;
import javax.crypto.spec.SecretKeySpec;
import javax.ejb.Stateless;
import javax.xml.bind.DatatypeConverter;
import java.security.Key;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
@Stateless
public class JWTHelper {
private static JWTHelper jwTokenHelper = null;
private Key signingKey;
Gson gson;
private JWTHelper() {
new Gson();
byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(Constants.SECRET_SIGNING_KEY_STRING);
signingKey = new SecretKeySpec(apiKeySecretBytes, Constants.SIGNATURE_ALGORITHM.getJcaName());
}
public static JWTHelper getInstance() {
if(jwTokenHelper == null)
jwTokenHelper = new JWTHelper();
return jwTokenHelper;
}
/***
* generates a jason web token with the parameters as payload.
* @param payload the account to put in the payload
* @return
*/
public String generatePrivateKey(Payload payload) {
Map<String, Object> claimsMap = new HashMap<>();
claimsMap.put("payload", payload);
//should not put json in payload, maybe change later
return Jwts
.builder()
.addClaims(claimsMap)
.setExpiration(calcExpirationDate())
.setIssuedAt(new Date(System.currentTimeMillis()))
.signWith(Constants.SIGNATURE_ALGORITHM, signingKey)
.compact();
}
/***
* gets the string from the JWT body, if valid.
* @param jwsString the JWS
* @return a payload associated with the account
* @throws ExpiredJwtException
* @throws MalformedJwtException
*/
public HashMap claimKey(String jwsString) throws ExpiredJwtException, MalformedJwtException {
Jwt jwt = Jwts.parser()
.setSigningKey(signingKey)
.parse(jwsString);
Claims claims = (Claims) jwt.getBody();
return (HashMap) claims.get("payload");
}
private Date calcExpirationDate() {
long currentTimeInMillis = System.currentTimeMillis();
long expMilliSeconds = TimeUnit.MINUTES.toMillis(Constants.EXPIRATION_LIMIT);
return new Date(currentTimeInMillis + expMilliSeconds);
}
}
| UTF-8 | Java | 2,383 | java | JWTHelper.java | Java | []
| null | []
| package util.security;
import com.google.gson.Gson;
import io.jsonwebtoken.*;
import util.Constants;
import javax.crypto.spec.SecretKeySpec;
import javax.ejb.Stateless;
import javax.xml.bind.DatatypeConverter;
import java.security.Key;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
@Stateless
public class JWTHelper {
private static JWTHelper jwTokenHelper = null;
private Key signingKey;
Gson gson;
private JWTHelper() {
new Gson();
byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(Constants.SECRET_SIGNING_KEY_STRING);
signingKey = new SecretKeySpec(apiKeySecretBytes, Constants.SIGNATURE_ALGORITHM.getJcaName());
}
public static JWTHelper getInstance() {
if(jwTokenHelper == null)
jwTokenHelper = new JWTHelper();
return jwTokenHelper;
}
/***
* generates a jason web token with the parameters as payload.
* @param payload the account to put in the payload
* @return
*/
public String generatePrivateKey(Payload payload) {
Map<String, Object> claimsMap = new HashMap<>();
claimsMap.put("payload", payload);
//should not put json in payload, maybe change later
return Jwts
.builder()
.addClaims(claimsMap)
.setExpiration(calcExpirationDate())
.setIssuedAt(new Date(System.currentTimeMillis()))
.signWith(Constants.SIGNATURE_ALGORITHM, signingKey)
.compact();
}
/***
* gets the string from the JWT body, if valid.
* @param jwsString the JWS
* @return a payload associated with the account
* @throws ExpiredJwtException
* @throws MalformedJwtException
*/
public HashMap claimKey(String jwsString) throws ExpiredJwtException, MalformedJwtException {
Jwt jwt = Jwts.parser()
.setSigningKey(signingKey)
.parse(jwsString);
Claims claims = (Claims) jwt.getBody();
return (HashMap) claims.get("payload");
}
private Date calcExpirationDate() {
long currentTimeInMillis = System.currentTimeMillis();
long expMilliSeconds = TimeUnit.MINUTES.toMillis(Constants.EXPIRATION_LIMIT);
return new Date(currentTimeInMillis + expMilliSeconds);
}
}
| 2,383 | 0.664708 | 0.663869 | 71 | 32.563381 | 25.093477 | 108 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.507042 | false | false | 4 |
f3071f4f5ea98e2a233ee96d5445a80050d05ae4 | 12,678,743,481,266 | 622a6feadae1d9a7cd8c761225c49d6b506087a8 | /TestFramework/src/main/java/com/medtronic/neuro/smplus/testfwk/telemetry/ctm/CtmCommand.java | 9a3774aa8039c0ff12e1fd90fbfefc4969d8ec6d | []
| no_license | NeuroOne/TestAutomationEnvironmentValidation_Zen | https://github.com/NeuroOne/TestAutomationEnvironmentValidation_Zen | e20bd4e4e0779a79c39e7deaac613462f4aa6459 | 16c087e6eba86f8415a1ea5f61c5cc7dec8190ba | refs/heads/master | 2019-03-20T09:20:39.318000 | 2018-03-05T12:08:52 | 2018-03-05T12:08:52 | 123,900,254 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* Copyright Medtronic, Inc. 2015
*
* MEDTRONIC CONFIDENTIAL: This document is the property of Medtronic,
* Inc.,and must be accounted for. Information herein is confidential. Do
* not reproduce it, reveal it to unauthorized persons, or send it outside
* Medtronic without proper authorization.
*/
package com.medtronic.neuro.smplus.testfwk.telemetry.ctm;
import com.medtronic.neuro.smplus.testfwk.telemetry.tela.TelACommand;
import java.util.Map;
/**
* Base CTM command class
*/
public class CtmCommand extends TelACommand {
public RawParameters ctmRawParameters;
/**
* Gets the telemetry command raw parameters.
* @return the map of command parameters.
*/
@Override
public Map<String, Object> getRawParameters() {
return ctmRawParameters.toMap();
}
public CtmCommand(String name, Long code, RawParameters rawParameters) {
super(name, code, rawParameters.toMap(), null);
ctmRawParameters = rawParameters;
}
}
| UTF-8 | Java | 995 | java | CtmCommand.java | Java | []
| null | []
| /*
* Copyright Medtronic, Inc. 2015
*
* MEDTRONIC CONFIDENTIAL: This document is the property of Medtronic,
* Inc.,and must be accounted for. Information herein is confidential. Do
* not reproduce it, reveal it to unauthorized persons, or send it outside
* Medtronic without proper authorization.
*/
package com.medtronic.neuro.smplus.testfwk.telemetry.ctm;
import com.medtronic.neuro.smplus.testfwk.telemetry.tela.TelACommand;
import java.util.Map;
/**
* Base CTM command class
*/
public class CtmCommand extends TelACommand {
public RawParameters ctmRawParameters;
/**
* Gets the telemetry command raw parameters.
* @return the map of command parameters.
*/
@Override
public Map<String, Object> getRawParameters() {
return ctmRawParameters.toMap();
}
public CtmCommand(String name, Long code, RawParameters rawParameters) {
super(name, code, rawParameters.toMap(), null);
ctmRawParameters = rawParameters;
}
}
| 995 | 0.717588 | 0.713568 | 36 | 26.638889 | 26.530018 | 76 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 4 |
2452e0f18b7aab35fb002fd01561da356e4d4a18 | 36,550,171,708,947 | 0ca167b9162892983682a6bf44d83dd0bf43a13c | /seleniumjava/src/test/java/DevToTests.java | 99abd52014ecda463e040fc5d45858e5f9eae29a | []
| no_license | Alexis-LG/TestingJavaExercises | https://github.com/Alexis-LG/TestingJavaExercises | 7cbfcbf217c00ae718382f9844f49bfa88bc1fe7 | 0f047cb48d1fb2c36aa9e2d8130e467ad7bd07d7 | refs/heads/master | 2020-03-11T12:25:31.319000 | 2019-09-17T15:22:09 | 2019-09-17T15:22:09 | 129,997,015 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import page.HomePage;
import page.PostPage;
import page.ProfilePage;
import page.SearchPage;
import utils.WebDriverUtils;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static org.testng.Assert.assertTrue;
public class DevToTests {
private WebDriver driver;
private HomePage homePage;
private SearchPage searchPage;
private PostPage postPage;
private ProfilePage profilePage;
@BeforeMethod
public void setUp() {
driver = new ChromeDriver();
homePage = new HomePage(driver);
searchPage = new SearchPage(driver);
postPage = new PostPage(driver);
profilePage = new ProfilePage(driver);
homePage.open();
}
@Test
public void canUserVisitHomePage() {
assertTrue(homePage.isVisible());
}
@Test
public void canUserSearchForPosts() {
homePage.searchFor("must have extensions");
searchPage.selectFirstResult();
assertTrue(postPage.isReadable());
}
@Test
public void canUserVisitSocialLinks() {
final List<String> expectedLinks = new ArrayList<>(Arrays.asList(
"https://twitter.com/thepracticaldev",
"https://github.com/thepracticaldev",
"https://www.instagram.com/thepracticaldev/",
"https://www.facebook.com/thepracticaldev",
"https://www.twitch.tv/thepracticaldev"
)
);
for (final WebElement link : homePage.getKeyLinks()) {
link.click();
WebDriverUtils.switchToNextTab(driver);
assertTrue(expectedLinks.contains(driver.getCurrentUrl()));
driver.close();
WebDriverUtils.switchToNextTab(driver);
}
}
@Test
public void canCheckAnotherUserProfile() {
homePage.searchFor("ben halpern");
searchPage.selectFirstResult();
assertTrue(profilePage.isVisible());
}
@AfterMethod
public void teardown() {
driver.quit();
}
}
| UTF-8 | Java | 2,368 | java | DevToTests.java | Java | [
{
"context": "ays.asList(\r\n \"https://twitter.com/thepracticaldev\",\r\n \"https://github.com/thepractic",
"end": 1499,
"score": 0.9995834827423096,
"start": 1484,
"tag": "USERNAME",
"value": "thepracticaldev"
},
{
"context": "acticaldev\",\r\n \"https://github.com/thepracticaldev\",\r\n \"https://www.instagram.com/the",
"end": 1554,
"score": 0.9995982050895691,
"start": 1539,
"tag": "USERNAME",
"value": "thepracticaldev"
},
{
"context": "dev\",\r\n \"https://www.instagram.com/thepracticaldev/\",\r\n \"https://www.facebook.com/the",
"end": 1616,
"score": 0.9995973110198975,
"start": 1601,
"tag": "USERNAME",
"value": "thepracticaldev"
},
{
"context": "dev/\",\r\n \"https://www.facebook.com/thepracticaldev\",\r\n \"https://www.twitch.tv/theprac",
"end": 1678,
"score": 0.9996095299720764,
"start": 1663,
"tag": "USERNAME",
"value": "thepracticaldev"
},
{
"context": "icaldev\",\r\n \"https://www.twitch.tv/thepracticaldev\"\r\n )\r\n );\r\n\r\n for (final Web",
"end": 1736,
"score": 0.9995519518852234,
"start": 1721,
"tag": "USERNAME",
"value": "thepracticaldev"
},
{
"context": "otherUserProfile() {\r\n homePage.searchFor(\"ben halpern\");\r\n searchPage.selectFirstResult();\r\n\r\n ",
"end": 2181,
"score": 0.9962066411972046,
"start": 2170,
"tag": "NAME",
"value": "ben halpern"
}
]
| null | []
| import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import page.HomePage;
import page.PostPage;
import page.ProfilePage;
import page.SearchPage;
import utils.WebDriverUtils;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static org.testng.Assert.assertTrue;
public class DevToTests {
private WebDriver driver;
private HomePage homePage;
private SearchPage searchPage;
private PostPage postPage;
private ProfilePage profilePage;
@BeforeMethod
public void setUp() {
driver = new ChromeDriver();
homePage = new HomePage(driver);
searchPage = new SearchPage(driver);
postPage = new PostPage(driver);
profilePage = new ProfilePage(driver);
homePage.open();
}
@Test
public void canUserVisitHomePage() {
assertTrue(homePage.isVisible());
}
@Test
public void canUserSearchForPosts() {
homePage.searchFor("must have extensions");
searchPage.selectFirstResult();
assertTrue(postPage.isReadable());
}
@Test
public void canUserVisitSocialLinks() {
final List<String> expectedLinks = new ArrayList<>(Arrays.asList(
"https://twitter.com/thepracticaldev",
"https://github.com/thepracticaldev",
"https://www.instagram.com/thepracticaldev/",
"https://www.facebook.com/thepracticaldev",
"https://www.twitch.tv/thepracticaldev"
)
);
for (final WebElement link : homePage.getKeyLinks()) {
link.click();
WebDriverUtils.switchToNextTab(driver);
assertTrue(expectedLinks.contains(driver.getCurrentUrl()));
driver.close();
WebDriverUtils.switchToNextTab(driver);
}
}
@Test
public void canCheckAnotherUserProfile() {
homePage.searchFor("<NAME>");
searchPage.selectFirstResult();
assertTrue(profilePage.isVisible());
}
@AfterMethod
public void teardown() {
driver.quit();
}
}
| 2,363 | 0.635135 | 0.635135 | 83 | 26.530121 | 19.825344 | 73 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.53012 | false | false | 4 |
d5cf8a60a055606eb5d685a78d1eb9140880fc78 | 38,766,374,850,201 | dc026c3bc2737d5e5816cd4035feff231a21eb1e | /src/main/java/org/citygml/ade/noise/walker/NoiseADEGMLFunctionWalker.java | 90e68004af71fe0870c60d0c3fcc859451828911 | [
"Apache-2.0"
]
| permissive | citygml4j/module-noise-ade | https://github.com/citygml4j/module-noise-ade | 5ac9447d1a5cbc1e4dbd09ba712c5fa5bcbf5969 | 997d2cd49acc485afef071033940aa73cc89ad9e | refs/heads/master | 2021-01-18T20:52:28.835000 | 2019-04-29T19:49:23 | 2019-04-29T19:49:23 | 86,996,160 | 6 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* noise-ade-citygml4j - Noise ADE module for citygml4j
* https://github.com/citygml4j/noise-ade-citygml4j
*
* noise-ade-citygml4j is part of the citygml4j project
*
* Copyright 2013-2019 Claus Nagel <claus.nagel@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.citygml.ade.noise.walker;
import org.citygml.ade.noise.model.NoiseCityFurnitureSegment;
import org.citygml.ade.noise.model.NoiseCityFurnitureSegmentPropertyElement;
import org.citygml.ade.noise.model.NoiseRailwaySegment;
import org.citygml.ade.noise.model.NoiseRailwaySegmentPropertyElement;
import org.citygml.ade.noise.model.NoiseRoadSegment;
import org.citygml.ade.noise.model.NoiseRoadSegmentPropertyElement;
import org.citygml.ade.noise.model.Train;
import org.citygml.ade.noise.model.TrainProperty;
import org.citygml4j.model.citygml.ade.binding.ADEWalker;
import org.citygml4j.model.citygml.core.AbstractCityObject;
import org.citygml4j.model.citygml.transportation.AbstractTransportationObject;
import org.citygml4j.model.gml.feature.AbstractFeature;
import org.citygml4j.model.gml.feature.FeatureProperty;
import org.citygml4j.util.walker.GMLFunctionWalker;
public class NoiseADEGMLFunctionWalker<T> implements ADEWalker<GMLFunctionWalker<T>> {
private GMLFunctionWalker<T> walker;
@Override
public void setParentWalker(GMLFunctionWalker<T> walker) {
this.walker = walker;
}
public T apply(NoiseCityFurnitureSegment noiseCityFurnitureSegment) {
T object = walker.apply((AbstractCityObject)noiseCityFurnitureSegment);
if (object != null)
return object;
if (noiseCityFurnitureSegment.isSetLod0BaseLine()) {
object = walker.apply(noiseCityFurnitureSegment.getLod0BaseLine());
if (object != null)
return object;
}
return null;
}
public T apply(NoiseRoadSegment noiseRoadSegment) {
T object = walker.apply((AbstractTransportationObject)noiseRoadSegment);
if (object != null)
return object;
if (noiseRoadSegment.isSetLod0BaseLine()) {
object = walker.apply(noiseRoadSegment.getLod0BaseLine());
if (object != null)
return object;
}
return null;
}
public T apply(NoiseRailwaySegment noiseRailwaySegment) {
T object = walker.apply((AbstractTransportationObject)noiseRailwaySegment);
if (object != null)
return object;
if (noiseRailwaySegment.isSetLod0BaseLine()) {
object = walker.apply(noiseRailwaySegment.getLod0BaseLine());
if (object != null)
return object;
}
if (noiseRailwaySegment.isSetUsedBy()) {
for (TrainProperty trainProperty : noiseRailwaySegment.getUsedBy()) {
object = walker.apply((FeatureProperty<?>)trainProperty);
if (object != null)
return object;
}
}
return null;
}
public T apply(Train train) {
return walker.apply((AbstractFeature)train);
}
public T apply(NoiseCityFurnitureSegmentPropertyElement noiseCityFurnitureSegmentPropertyElement) {
return walker.apply((FeatureProperty<?>)noiseCityFurnitureSegmentPropertyElement.getValue());
}
public T apply(NoiseRoadSegmentPropertyElement noiseRoadSegmentPropertyElement) {
return walker.apply((FeatureProperty<?>)noiseRoadSegmentPropertyElement.getValue());
}
public T apply(NoiseRailwaySegmentPropertyElement noiseRailwaySegmentPropertyElement) {
return walker.apply((FeatureProperty<?>)noiseRailwaySegmentPropertyElement.getValue());
}
}
| UTF-8 | Java | 3,869 | java | NoiseADEGMLFunctionWalker.java | Java | [
{
"context": "se ADE module for citygml4j\n * https://github.com/citygml4j/noise-ade-citygml4j\n *\n * noise-ade-citygml4j is ",
"end": 90,
"score": 0.9994125962257385,
"start": 81,
"tag": "USERNAME",
"value": "citygml4j"
},
{
"context": "of the citygml4j project\n *\n * Copyright 2013-2019 Claus Nagel <claus.nagel@gmail.com>\n *\n * Licensed under the ",
"end": 207,
"score": 0.9998807907104492,
"start": 196,
"tag": "NAME",
"value": "Claus Nagel"
},
{
"context": "4j project\n *\n * Copyright 2013-2019 Claus Nagel <claus.nagel@gmail.com>\n *\n * Licensed under the Apache License, Version",
"end": 230,
"score": 0.9999352693557739,
"start": 209,
"tag": "EMAIL",
"value": "claus.nagel@gmail.com"
}
]
| null | []
| /*
* noise-ade-citygml4j - Noise ADE module for citygml4j
* https://github.com/citygml4j/noise-ade-citygml4j
*
* noise-ade-citygml4j is part of the citygml4j project
*
* Copyright 2013-2019 <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.citygml.ade.noise.walker;
import org.citygml.ade.noise.model.NoiseCityFurnitureSegment;
import org.citygml.ade.noise.model.NoiseCityFurnitureSegmentPropertyElement;
import org.citygml.ade.noise.model.NoiseRailwaySegment;
import org.citygml.ade.noise.model.NoiseRailwaySegmentPropertyElement;
import org.citygml.ade.noise.model.NoiseRoadSegment;
import org.citygml.ade.noise.model.NoiseRoadSegmentPropertyElement;
import org.citygml.ade.noise.model.Train;
import org.citygml.ade.noise.model.TrainProperty;
import org.citygml4j.model.citygml.ade.binding.ADEWalker;
import org.citygml4j.model.citygml.core.AbstractCityObject;
import org.citygml4j.model.citygml.transportation.AbstractTransportationObject;
import org.citygml4j.model.gml.feature.AbstractFeature;
import org.citygml4j.model.gml.feature.FeatureProperty;
import org.citygml4j.util.walker.GMLFunctionWalker;
public class NoiseADEGMLFunctionWalker<T> implements ADEWalker<GMLFunctionWalker<T>> {
private GMLFunctionWalker<T> walker;
@Override
public void setParentWalker(GMLFunctionWalker<T> walker) {
this.walker = walker;
}
public T apply(NoiseCityFurnitureSegment noiseCityFurnitureSegment) {
T object = walker.apply((AbstractCityObject)noiseCityFurnitureSegment);
if (object != null)
return object;
if (noiseCityFurnitureSegment.isSetLod0BaseLine()) {
object = walker.apply(noiseCityFurnitureSegment.getLod0BaseLine());
if (object != null)
return object;
}
return null;
}
public T apply(NoiseRoadSegment noiseRoadSegment) {
T object = walker.apply((AbstractTransportationObject)noiseRoadSegment);
if (object != null)
return object;
if (noiseRoadSegment.isSetLod0BaseLine()) {
object = walker.apply(noiseRoadSegment.getLod0BaseLine());
if (object != null)
return object;
}
return null;
}
public T apply(NoiseRailwaySegment noiseRailwaySegment) {
T object = walker.apply((AbstractTransportationObject)noiseRailwaySegment);
if (object != null)
return object;
if (noiseRailwaySegment.isSetLod0BaseLine()) {
object = walker.apply(noiseRailwaySegment.getLod0BaseLine());
if (object != null)
return object;
}
if (noiseRailwaySegment.isSetUsedBy()) {
for (TrainProperty trainProperty : noiseRailwaySegment.getUsedBy()) {
object = walker.apply((FeatureProperty<?>)trainProperty);
if (object != null)
return object;
}
}
return null;
}
public T apply(Train train) {
return walker.apply((AbstractFeature)train);
}
public T apply(NoiseCityFurnitureSegmentPropertyElement noiseCityFurnitureSegmentPropertyElement) {
return walker.apply((FeatureProperty<?>)noiseCityFurnitureSegmentPropertyElement.getValue());
}
public T apply(NoiseRoadSegmentPropertyElement noiseRoadSegmentPropertyElement) {
return walker.apply((FeatureProperty<?>)noiseRoadSegmentPropertyElement.getValue());
}
public T apply(NoiseRailwaySegmentPropertyElement noiseRailwaySegmentPropertyElement) {
return walker.apply((FeatureProperty<?>)noiseRailwaySegmentPropertyElement.getValue());
}
}
| 3,850 | 0.776686 | 0.768933 | 112 | 33.544643 | 30.044279 | 100 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.598214 | false | false | 4 |
e406b40bcefeb15d9d087d0c33cd10b57205829a | 20,521,353,804,435 | 9437faf1ab1a7fef14153277e656b8fe68ccee8c | /src/main/java/enums/ReviewError.java | e8b374bea27e54a6050abed55b1f6a5657ec514f | []
| no_license | harryy27/Crejo-Assignment | https://github.com/harryy27/Crejo-Assignment | 6c95729f1e61ab0900204c554d415feb145f8096 | d03d1b1e7333d70b108f0396f9b296c7b8b3976b | refs/heads/master | 2023-02-26T20:24:05.345000 | 2021-02-07T13:20:04 | 2021-02-07T13:20:04 | 336,790,120 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package enums;
public enum ReviewError {
MOVIE_NOT_RELEASED("Movie yet to be released"),
REVIEW_ALREADY_EXISTS("Multiple reviews not allowed");
private final String message;
public String getMessage() {
return message;
}
ReviewError(String message) {
this.message = message;
}
}
| UTF-8 | Java | 328 | java | ReviewError.java | Java | []
| null | []
| package enums;
public enum ReviewError {
MOVIE_NOT_RELEASED("Movie yet to be released"),
REVIEW_ALREADY_EXISTS("Multiple reviews not allowed");
private final String message;
public String getMessage() {
return message;
}
ReviewError(String message) {
this.message = message;
}
}
| 328 | 0.655488 | 0.655488 | 17 | 18.294117 | 18.5338 | 58 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.352941 | false | false | 4 |
edd4f21b4fbec9d6abd8fc608a7c2aa4eea81384 | 8,658,654,114,693 | 7d3bcba5f129bc52d4514bb6ad7897b05c65fe31 | /protocol/src/main/java/com/github/guocay/hj212/core/ProtocolGenerator.java | 69c490032331154d1ebd3ffb943e25005e49bacc | [
"MIT"
]
| permissive | guo-kay/HJ212-Moniter | https://github.com/guo-kay/HJ212-Moniter | 6fe65456559dbc982298346ab5fee21b60bdc2ac | 5a1ac2a779e87761dc1f762de95d9c4a231e1583 | refs/heads/main | 2023-08-25T04:17:02.642000 | 2023-05-18T12:56:42 | 2023-05-18T12:56:42 | 410,814,141 | 4 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.github.guocay.hj212.core;
import com.github.guocay.hj212.exception.ProtocolFormatException;
import com.github.guocay.hj212.model.verify.PacketElement;
import com.github.guocay.hj212.segment.config.Configurator;
import com.github.guocay.hj212.segment.config.Configured;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.Closeable;
import java.io.IOException;
import java.io.Writer;
/**
* 协议生成者
* @author aCay
*/
public class ProtocolGenerator implements Configured<ProtocolGenerator>, Closeable {
private static final Logger LOGGER = LoggerFactory.getLogger(ProtocolGenerator.class);
public static char[] HEADER = new char[]{ '#','#' };
public static char[] FOOTER = new char[]{ '\r', '\n' };
protected Writer writer;
//not use
@SuppressWarnings("unused")
private int generatorFeature;
public ProtocolGenerator(Writer writer){
this.writer = writer;
}
/**
* 设置生成特性
* @param generatorFeature 生成特性
*/
public void setGeneratorFeature(int generatorFeature) {
this.generatorFeature = generatorFeature;
}
/**
* 写入 包头
* @see PacketElement#HEADER
* @return count always 2
* @throws IOException
*/
public int writeHeader() throws IOException {
writer.write(HEADER);
return 2;
}
/**
* 写入 数据段长度
* @see PacketElement#DATA_LEN
* @param len chars
* @return length always 4
* @throws IOException
* @throws ProtocolFormatException
*/
public int writeDataLen(char[] len) throws IOException, ProtocolFormatException {
VerifyUtil.verifyLen(len.length, 4, PacketElement.DATA_LEN);
writer.write(len);
return 4;
}
/**
* 写入 4字节Integer
* @param i integer
* @return length always 4
* @throws IOException
*/
public int writeHexInt32(int i) throws IOException {
char[] intChars = Integer.toHexString(i).toCharArray();
writer.write(intChars);
return intChars.length;
}
/**
* 读取 数据段
* @see PacketElement#DATA
* @param data data chars
* @return data length
* @throws IOException
*/
public int writeData(char[] data) throws IOException {
writer.write(data);
return data.length;
}
/**
* 写入 DATA_CRC 校验
* @see PacketElement#DATA_CRC
* @param crc crc chars
* @return length always 4
* @throws ProtocolFormatException
* @throws IOException
*/
public int writeCrc(char[] crc) throws IOException, ProtocolFormatException {
VerifyUtil.verifyLen(crc.length, 4, PacketElement.DATA_LEN);
writer.write(crc);
return crc.length;
}
/**
* 写入 数据段长度+CRC校验
* @see PacketElement#DATA_LEN
* @param data data chars
* @return data length with 8 chars(4 chars for data_len and 4 chars for data_crc)
* @throws ProtocolFormatException
* @throws IOException
*/
public int writeDataAndLenAndCrc(char[] data) throws IOException, ProtocolFormatException {
int dataLen = data.length;
char[] len = String.format("%04d", dataLen).toCharArray();
writer.write(len);
VerifyUtil.verifyLen(len.length, 4, PacketElement.DATA_CRC);
writer.write(data);
int crc = ProtocolParser.crc16Checkout(data,dataLen);
int crcLen = writeHexInt32(crc);
VerifyUtil.verifyLen(crcLen, 4, PacketElement.DATA_CRC);
return len.length + data.length + crcLen;
}
/**
* 写入 包尾
* @see PacketElement#FOOTER
* @return length always 2
* @throws IOException
*/
public int writeFooter() throws IOException {
writer.write(FOOTER);
return 2;
}
@Override
public void configured(Configurator<ProtocolGenerator> configurator) {
configurator.config(this);
}
@Override
public void close() {
try {
writer.close();
} catch (IOException e) {
LOGGER.error(e.getMessage(), e);
}
}
}
| UTF-8 | Java | 4,172 | java | ProtocolGenerator.java | Java | [
{
"context": "n;\nimport java.io.Writer;\n\n/**\n * 协议生成者\n * @author aCay\n */\npublic class ProtocolGenerator implements Con",
"end": 446,
"score": 0.9996197819709778,
"start": 442,
"tag": "USERNAME",
"value": "aCay"
}
]
| null | []
| package com.github.guocay.hj212.core;
import com.github.guocay.hj212.exception.ProtocolFormatException;
import com.github.guocay.hj212.model.verify.PacketElement;
import com.github.guocay.hj212.segment.config.Configurator;
import com.github.guocay.hj212.segment.config.Configured;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.Closeable;
import java.io.IOException;
import java.io.Writer;
/**
* 协议生成者
* @author aCay
*/
public class ProtocolGenerator implements Configured<ProtocolGenerator>, Closeable {
private static final Logger LOGGER = LoggerFactory.getLogger(ProtocolGenerator.class);
public static char[] HEADER = new char[]{ '#','#' };
public static char[] FOOTER = new char[]{ '\r', '\n' };
protected Writer writer;
//not use
@SuppressWarnings("unused")
private int generatorFeature;
public ProtocolGenerator(Writer writer){
this.writer = writer;
}
/**
* 设置生成特性
* @param generatorFeature 生成特性
*/
public void setGeneratorFeature(int generatorFeature) {
this.generatorFeature = generatorFeature;
}
/**
* 写入 包头
* @see PacketElement#HEADER
* @return count always 2
* @throws IOException
*/
public int writeHeader() throws IOException {
writer.write(HEADER);
return 2;
}
/**
* 写入 数据段长度
* @see PacketElement#DATA_LEN
* @param len chars
* @return length always 4
* @throws IOException
* @throws ProtocolFormatException
*/
public int writeDataLen(char[] len) throws IOException, ProtocolFormatException {
VerifyUtil.verifyLen(len.length, 4, PacketElement.DATA_LEN);
writer.write(len);
return 4;
}
/**
* 写入 4字节Integer
* @param i integer
* @return length always 4
* @throws IOException
*/
public int writeHexInt32(int i) throws IOException {
char[] intChars = Integer.toHexString(i).toCharArray();
writer.write(intChars);
return intChars.length;
}
/**
* 读取 数据段
* @see PacketElement#DATA
* @param data data chars
* @return data length
* @throws IOException
*/
public int writeData(char[] data) throws IOException {
writer.write(data);
return data.length;
}
/**
* 写入 DATA_CRC 校验
* @see PacketElement#DATA_CRC
* @param crc crc chars
* @return length always 4
* @throws ProtocolFormatException
* @throws IOException
*/
public int writeCrc(char[] crc) throws IOException, ProtocolFormatException {
VerifyUtil.verifyLen(crc.length, 4, PacketElement.DATA_LEN);
writer.write(crc);
return crc.length;
}
/**
* 写入 数据段长度+CRC校验
* @see PacketElement#DATA_LEN
* @param data data chars
* @return data length with 8 chars(4 chars for data_len and 4 chars for data_crc)
* @throws ProtocolFormatException
* @throws IOException
*/
public int writeDataAndLenAndCrc(char[] data) throws IOException, ProtocolFormatException {
int dataLen = data.length;
char[] len = String.format("%04d", dataLen).toCharArray();
writer.write(len);
VerifyUtil.verifyLen(len.length, 4, PacketElement.DATA_CRC);
writer.write(data);
int crc = ProtocolParser.crc16Checkout(data,dataLen);
int crcLen = writeHexInt32(crc);
VerifyUtil.verifyLen(crcLen, 4, PacketElement.DATA_CRC);
return len.length + data.length + crcLen;
}
/**
* 写入 包尾
* @see PacketElement#FOOTER
* @return length always 2
* @throws IOException
*/
public int writeFooter() throws IOException {
writer.write(FOOTER);
return 2;
}
@Override
public void configured(Configurator<ProtocolGenerator> configurator) {
configurator.config(this);
}
@Override
public void close() {
try {
writer.close();
} catch (IOException e) {
LOGGER.error(e.getMessage(), e);
}
}
}
| 4,172 | 0.635447 | 0.625369 | 153 | 25.588236 | 22.660187 | 95 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.405229 | false | false | 4 |
83771da5e4bf3119824fdf23d1e3a3ff624face5 | 14,078,902,840,680 | 39bd184c623c54c17a8b00a9cb21ff1dbaef5368 | /solr/core/src/java/org/apache/solr/search/similarities/DFRSimilarityFactory.java | 61b972f604b14a81fe0bfbd301fff3009e116f3b | [
"Apache-2.0",
"MIT",
"BSD-3-Clause",
"CDDL-1.0",
"CDDL-1.1",
"ANTLR-PD",
"LGPL-2.0-or-later",
"LicenseRef-scancode-unicode",
"CPL-1.0",
"GPL-2.0-only",
"Classpath-exception-2.0",
"CC-BY-SA-3.0",
"BSD-2-Clause",
"LicenseRef-scancode-other-copyleft",
"LicenseRef-scancode-proprietary-license",
"LicenseRef-scancode-unknown-license-reference",
"NAIST-2003"
]
| permissive | apache/solr | https://github.com/apache/solr | 08654d4786d74861ac0b9d0c09aefbadde5419c8 | 22ac9105ea0382215c8fe558fc55977dc98aa14c | refs/heads/main | 2023-08-31T03:50:24.041000 | 2023-08-30T20:08:03 | 2023-08-30T20:08:03 | 341,374,920 | 847 | 532 | Apache-2.0 | false | 2023-09-14T20:45:30 | 2021-02-23T00:12:42 | 2023-09-14T18:38:00 | 2023-09-14T20:45:30 | 474,161 | 832 | 525 | 202 | Java | false | false | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.solr.search.similarities;
import org.apache.lucene.search.similarities.AfterEffect;
import org.apache.lucene.search.similarities.AfterEffectB;
import org.apache.lucene.search.similarities.AfterEffectL;
import org.apache.lucene.search.similarities.BasicModel;
import org.apache.lucene.search.similarities.BasicModelG;
import org.apache.lucene.search.similarities.BasicModelIF;
import org.apache.lucene.search.similarities.BasicModelIn;
import org.apache.lucene.search.similarities.BasicModelIne;
import org.apache.lucene.search.similarities.DFRSimilarity;
import org.apache.lucene.search.similarities.Normalization;
import org.apache.lucene.search.similarities.Normalization.NoNormalization;
import org.apache.lucene.search.similarities.NormalizationH1;
import org.apache.lucene.search.similarities.NormalizationH2;
import org.apache.lucene.search.similarities.NormalizationH3;
import org.apache.lucene.search.similarities.NormalizationZ;
import org.apache.lucene.search.similarities.Similarity;
import org.apache.solr.common.params.SolrParams;
import org.apache.solr.schema.SimilarityFactory;
/**
* Factory for {@link DFRSimilarity}
*
* <p>You must specify the implementations for all three components of DFR (strings). In general the
* models are parameter-free, but two of the normalizations take floating point parameters (see
* below):
*
* <ol>
* <li>{@link BasicModel basicModel}: Basic model of information content:
* <ul>
* <li>{@link BasicModelG G}: Geometric approximation of Bose-Einstein
* <li>{@link BasicModelIn I(n)}: Inverse document frequency
* <li>{@link BasicModelIne I(ne)}: Inverse expected document frequency [mixture of Poisson
* and IDF]
* <li>{@link BasicModelIF I(F)}: Inverse term frequency [approximation of I(ne)]
* </ul>
* <li>{@link AfterEffect afterEffect}: First normalization of information gain:
* <ul>
* <li>{@link AfterEffectL L}: Laplace's law of succession
* <li>{@link AfterEffectB B}: Ratio of two Bernoulli processes
* </ul>
* <li>{@link Normalization normalization}: Second (length) normalization:
* <ul>
* <li>{@link NormalizationH1 H1}: Uniform distribution of term frequency
* <ul>
* <li>parameter c (float): hyper-parameter that controls the term frequency
* normalization with respect to the document length. The default is <code>1
* </code>
* </ul>
* <li>{@link NormalizationH2 H2}: term frequency density inversely related to length
* <ul>
* <li>parameter c (float): hyper-parameter that controls the term frequency
* normalization with respect to the document length. The default is <code>1
* </code>
* </ul>
* <li>{@link NormalizationH3 H3}: term frequency normalization provided by Dirichlet prior
* <ul>
* <li>parameter mu (float): smoothing parameter μ. The default is <code>800</code>
* </ul>
* <li>{@link NormalizationZ Z}: term frequency normalization provided by a Zipfian relation
* <ul>
* <li>parameter z (float): represents <code>A/(A+1)</code> where A measures the
* specificity of the language. The default is <code>0.3</code>
* </ul>
* <li>{@link NoNormalization none}: no second normalization
* </ul>
* </ol>
*
* <p>Optional settings:
*
* <ul>
* <li>discountOverlaps (bool): Sets {@link DFRSimilarity#setDiscountOverlaps(boolean)}
* </ul>
*
* @lucene.experimental
*/
public class DFRSimilarityFactory extends SimilarityFactory {
private boolean discountOverlaps;
private BasicModel basicModel;
private AfterEffect afterEffect;
private Normalization normalization;
@Override
public void init(SolrParams params) {
super.init(params);
discountOverlaps = params.getBool("discountOverlaps", true);
basicModel = parseBasicModel(params.get("basicModel"));
afterEffect = parseAfterEffect(params.get("afterEffect"));
normalization =
parseNormalization(
params.get("normalization"), params.get("c"), params.get("mu"), params.get("z"));
}
private BasicModel parseBasicModel(String expr) {
if ("G".equals(expr)) {
return new BasicModelG();
} else if ("I(F)".equals(expr)) {
return new BasicModelIF();
} else if ("I(n)".equals(expr)) {
return new BasicModelIn();
} else if ("I(ne)".equals(expr)) {
return new BasicModelIne();
} else {
throw new RuntimeException("Invalid basicModel: " + expr);
}
}
private AfterEffect parseAfterEffect(String expr) {
if ("B".equals(expr)) {
return new AfterEffectB();
} else if ("L".equals(expr)) {
return new AfterEffectL();
} else {
throw new RuntimeException("Invalid afterEffect: " + expr);
}
}
// also used by IBSimilarityFactory
static Normalization parseNormalization(String expr, String c, String mu, String z) {
if (mu != null && !"H3".equals(expr)) {
throw new RuntimeException("parameter mu only makes sense for normalization H3");
}
if (z != null && !"Z".equals(expr)) {
throw new RuntimeException("parameter z only makes sense for normalization Z");
}
if (c != null && !("H1".equals(expr) || "H2".equals(expr))) {
throw new RuntimeException("parameter c only makese sense for normalizations H1 and H2");
}
if ("H1".equals(expr)) {
return (c != null) ? new NormalizationH1(Float.parseFloat(c)) : new NormalizationH1();
} else if ("H2".equals(expr)) {
return (c != null) ? new NormalizationH2(Float.parseFloat(c)) : new NormalizationH2();
} else if ("H3".equals(expr)) {
return (mu != null) ? new NormalizationH3(Float.parseFloat(mu)) : new NormalizationH3();
} else if ("Z".equals(expr)) {
return (z != null) ? new NormalizationZ(Float.parseFloat(z)) : new NormalizationZ();
} else if ("none".equals(expr)) {
return new Normalization.NoNormalization();
} else {
throw new RuntimeException("Invalid normalization: " + expr);
}
}
@Override
public Similarity getSimilarity() {
DFRSimilarity sim = new DFRSimilarity(basicModel, afterEffect, normalization);
sim.setDiscountOverlaps(discountOverlaps);
return sim;
}
}
| UTF-8 | Java | 7,261 | java | DFRSimilarityFactory.java | Java | []
| null | []
| /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.solr.search.similarities;
import org.apache.lucene.search.similarities.AfterEffect;
import org.apache.lucene.search.similarities.AfterEffectB;
import org.apache.lucene.search.similarities.AfterEffectL;
import org.apache.lucene.search.similarities.BasicModel;
import org.apache.lucene.search.similarities.BasicModelG;
import org.apache.lucene.search.similarities.BasicModelIF;
import org.apache.lucene.search.similarities.BasicModelIn;
import org.apache.lucene.search.similarities.BasicModelIne;
import org.apache.lucene.search.similarities.DFRSimilarity;
import org.apache.lucene.search.similarities.Normalization;
import org.apache.lucene.search.similarities.Normalization.NoNormalization;
import org.apache.lucene.search.similarities.NormalizationH1;
import org.apache.lucene.search.similarities.NormalizationH2;
import org.apache.lucene.search.similarities.NormalizationH3;
import org.apache.lucene.search.similarities.NormalizationZ;
import org.apache.lucene.search.similarities.Similarity;
import org.apache.solr.common.params.SolrParams;
import org.apache.solr.schema.SimilarityFactory;
/**
* Factory for {@link DFRSimilarity}
*
* <p>You must specify the implementations for all three components of DFR (strings). In general the
* models are parameter-free, but two of the normalizations take floating point parameters (see
* below):
*
* <ol>
* <li>{@link BasicModel basicModel}: Basic model of information content:
* <ul>
* <li>{@link BasicModelG G}: Geometric approximation of Bose-Einstein
* <li>{@link BasicModelIn I(n)}: Inverse document frequency
* <li>{@link BasicModelIne I(ne)}: Inverse expected document frequency [mixture of Poisson
* and IDF]
* <li>{@link BasicModelIF I(F)}: Inverse term frequency [approximation of I(ne)]
* </ul>
* <li>{@link AfterEffect afterEffect}: First normalization of information gain:
* <ul>
* <li>{@link AfterEffectL L}: Laplace's law of succession
* <li>{@link AfterEffectB B}: Ratio of two Bernoulli processes
* </ul>
* <li>{@link Normalization normalization}: Second (length) normalization:
* <ul>
* <li>{@link NormalizationH1 H1}: Uniform distribution of term frequency
* <ul>
* <li>parameter c (float): hyper-parameter that controls the term frequency
* normalization with respect to the document length. The default is <code>1
* </code>
* </ul>
* <li>{@link NormalizationH2 H2}: term frequency density inversely related to length
* <ul>
* <li>parameter c (float): hyper-parameter that controls the term frequency
* normalization with respect to the document length. The default is <code>1
* </code>
* </ul>
* <li>{@link NormalizationH3 H3}: term frequency normalization provided by Dirichlet prior
* <ul>
* <li>parameter mu (float): smoothing parameter μ. The default is <code>800</code>
* </ul>
* <li>{@link NormalizationZ Z}: term frequency normalization provided by a Zipfian relation
* <ul>
* <li>parameter z (float): represents <code>A/(A+1)</code> where A measures the
* specificity of the language. The default is <code>0.3</code>
* </ul>
* <li>{@link NoNormalization none}: no second normalization
* </ul>
* </ol>
*
* <p>Optional settings:
*
* <ul>
* <li>discountOverlaps (bool): Sets {@link DFRSimilarity#setDiscountOverlaps(boolean)}
* </ul>
*
* @lucene.experimental
*/
public class DFRSimilarityFactory extends SimilarityFactory {
private boolean discountOverlaps;
private BasicModel basicModel;
private AfterEffect afterEffect;
private Normalization normalization;
@Override
public void init(SolrParams params) {
super.init(params);
discountOverlaps = params.getBool("discountOverlaps", true);
basicModel = parseBasicModel(params.get("basicModel"));
afterEffect = parseAfterEffect(params.get("afterEffect"));
normalization =
parseNormalization(
params.get("normalization"), params.get("c"), params.get("mu"), params.get("z"));
}
private BasicModel parseBasicModel(String expr) {
if ("G".equals(expr)) {
return new BasicModelG();
} else if ("I(F)".equals(expr)) {
return new BasicModelIF();
} else if ("I(n)".equals(expr)) {
return new BasicModelIn();
} else if ("I(ne)".equals(expr)) {
return new BasicModelIne();
} else {
throw new RuntimeException("Invalid basicModel: " + expr);
}
}
private AfterEffect parseAfterEffect(String expr) {
if ("B".equals(expr)) {
return new AfterEffectB();
} else if ("L".equals(expr)) {
return new AfterEffectL();
} else {
throw new RuntimeException("Invalid afterEffect: " + expr);
}
}
// also used by IBSimilarityFactory
static Normalization parseNormalization(String expr, String c, String mu, String z) {
if (mu != null && !"H3".equals(expr)) {
throw new RuntimeException("parameter mu only makes sense for normalization H3");
}
if (z != null && !"Z".equals(expr)) {
throw new RuntimeException("parameter z only makes sense for normalization Z");
}
if (c != null && !("H1".equals(expr) || "H2".equals(expr))) {
throw new RuntimeException("parameter c only makese sense for normalizations H1 and H2");
}
if ("H1".equals(expr)) {
return (c != null) ? new NormalizationH1(Float.parseFloat(c)) : new NormalizationH1();
} else if ("H2".equals(expr)) {
return (c != null) ? new NormalizationH2(Float.parseFloat(c)) : new NormalizationH2();
} else if ("H3".equals(expr)) {
return (mu != null) ? new NormalizationH3(Float.parseFloat(mu)) : new NormalizationH3();
} else if ("Z".equals(expr)) {
return (z != null) ? new NormalizationZ(Float.parseFloat(z)) : new NormalizationZ();
} else if ("none".equals(expr)) {
return new Normalization.NoNormalization();
} else {
throw new RuntimeException("Invalid normalization: " + expr);
}
}
@Override
public Similarity getSimilarity() {
DFRSimilarity sim = new DFRSimilarity(basicModel, afterEffect, normalization);
sim.setDiscountOverlaps(discountOverlaps);
return sim;
}
}
| 7,261 | 0.678419 | 0.673461 | 167 | 42.479042 | 31.135946 | 100 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.39521 | false | false | 4 |
5968f1499febd4868ab12dd9c07affa081792168 | 26,491,358,340,657 | 85896ac8f822b4671d0e6a6b94991c85d72580cc | /issue-analysis/src/main/java/com/alkaid/isa/flow/controller/AnalysisSequenceController.java | 20c959635556d38bc31214f739cace09d8461ff9 | []
| no_license | jiangbb868/alltest-spring-boot | https://github.com/jiangbb868/alltest-spring-boot | 89d303a3b1df5d27cd6f44c3a6885f6f4efaf25a | e9fbe7042ff1b6e7129c82d99e5f20277d832473 | refs/heads/master | 2022-01-17T23:46:25.783000 | 2021-02-21T05:07:39 | 2021-02-21T05:07:39 | 215,817,868 | 0 | 0 | null | false | 2022-01-21T23:49:07 | 2019-10-17T14:49:56 | 2021-02-21T05:09:08 | 2022-01-21T23:49:06 | 5,501 | 0 | 0 | 8 | Java | false | false | package com.alkaid.isa.flow.controller;
import com.alibaba.fastjson.JSONObject;
import com.alkaid.isa.flow.api.IAnalysisSequenceService;
import com.alkaid.isa.flow.pojo.AnalysisSequence;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RequestMapping("/isa/sequence")
@RestController
public class AnalysisSequenceController {
@Autowired
private IAnalysisSequenceService analysisSequenceService;
@GetMapping(value="/list")
public String list() throws Exception {
List<AnalysisSequence> AnalysisSequences = analysisSequenceService.list();
JSONObject result = new JSONObject();
result.put("rows", AnalysisSequences);
result.put("total", AnalysisSequences.size());
return result.toJSONString();
}
@PostMapping(value="/add")
public String add(@RequestBody AnalysisSequence analysisSequence) throws Exception {
analysisSequenceService.save(analysisSequence);
return "sucess";
}
@PostMapping(value="/update")
public String update(@RequestBody AnalysisSequence analysisSequence) throws Exception {
analysisSequenceService.saveOrUpdate(analysisSequence);
return "sucess";
}
@PostMapping(value="/delete")
public String delete(@RequestParam(value="id") long id) throws Exception {
analysisSequenceService.removeById(id);
return "sucess";
}
@GetMapping(value="/get")
public String get(@RequestParam(value="id") long id) throws Exception {
analysisSequenceService.getById(id);
return "sucess";
}
}
| UTF-8 | Java | 1,971 | java | AnalysisSequenceController.java | Java | []
| null | []
| package com.alkaid.isa.flow.controller;
import com.alibaba.fastjson.JSONObject;
import com.alkaid.isa.flow.api.IAnalysisSequenceService;
import com.alkaid.isa.flow.pojo.AnalysisSequence;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RequestMapping("/isa/sequence")
@RestController
public class AnalysisSequenceController {
@Autowired
private IAnalysisSequenceService analysisSequenceService;
@GetMapping(value="/list")
public String list() throws Exception {
List<AnalysisSequence> AnalysisSequences = analysisSequenceService.list();
JSONObject result = new JSONObject();
result.put("rows", AnalysisSequences);
result.put("total", AnalysisSequences.size());
return result.toJSONString();
}
@PostMapping(value="/add")
public String add(@RequestBody AnalysisSequence analysisSequence) throws Exception {
analysisSequenceService.save(analysisSequence);
return "sucess";
}
@PostMapping(value="/update")
public String update(@RequestBody AnalysisSequence analysisSequence) throws Exception {
analysisSequenceService.saveOrUpdate(analysisSequence);
return "sucess";
}
@PostMapping(value="/delete")
public String delete(@RequestParam(value="id") long id) throws Exception {
analysisSequenceService.removeById(id);
return "sucess";
}
@GetMapping(value="/get")
public String get(@RequestParam(value="id") long id) throws Exception {
analysisSequenceService.getById(id);
return "sucess";
}
}
| 1,971 | 0.746829 | 0.746829 | 55 | 34.836365 | 26.253147 | 91 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.509091 | false | false | 4 |
0f0de445219e4091424ffcc3c3a62455b44a999c | 10,634,339,062,952 | 0104a82db0572c7c887c9a235bc63055d25eb697 | /carpool/src/main/java/car/pool/member/domain/MemberCommand.java | 1d46165bd03b5b285c41c0bb999a8de2dc1cac12 | []
| no_license | sinmun501/carpool | https://github.com/sinmun501/carpool | d25cd134f4ef58cb416f12b9778bf50243f9ff80 | aa4e1d8531488e72d26bb3c17701598ea3f595e3 | refs/heads/master | 2021-01-01T19:05:02.170000 | 2019-03-03T18:56:20 | 2019-03-03T18:56:20 | 98,503,043 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package car.pool.member.domain;
import java.io.IOException;
import java.sql.Date;
import javax.validation.constraints.Size;
import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.NotEmpty;
import org.springframework.web.multipart.MultipartFile;
public class MemberCommand {
@NotEmpty
private String mem_id;
private int mem_auth; /* 0탈퇴회원, 1일반회원, 2관리자 */
private int mem_driver; /* 1일반회원, 2운전자회원 */
@Size(min=4,max=10)
private String mem_pw;
@NotEmpty
private String mem_name;
private String mem_gender;
private String mem_grade;
@NotEmpty
private String mem_phone;
@NotEmpty
private String mem_email;
private Date mem_date;
private MultipartFile upload;
private byte[] mem_image;
private String mem_filename;
//비밀번호 일치 여부 체크
public boolean isCheckedPasswd(String userPasswd){
if(mem_auth > 0 && mem_pw.equals(userPasswd)){
return true;
}
return false;
}
public void setUpload(MultipartFile upload) throws IOException {
this.upload = upload;
setMem_image(upload.getBytes());
setMem_filename(upload.getOriginalFilename());
}
public String getMem_id() {
return mem_id;
}
public void setMem_id(String mem_id) {
this.mem_id = mem_id;
}
public int getMem_auth() {
return mem_auth;
}
public void setMem_auth(int mem_auth) {
this.mem_auth = mem_auth;
}
public int getMem_driver() {
return mem_driver;
}
public void setMem_driver(int mem_driver) {
this.mem_driver = mem_driver;
}
public String getMem_pw() {
return mem_pw;
}
public void setMem_pw(String mem_pw) {
this.mem_pw = mem_pw;
}
public String getMem_name() {
return mem_name;
}
public void setMem_name(String mem_name) {
this.mem_name = mem_name;
}
public String getMem_gender() {
return mem_gender;
}
public void setMem_gender(String mem_gender) {
this.mem_gender = mem_gender;
}
public String getMem_grade() {
return mem_grade;
}
public void setMem_grade(String mem_grade) {
this.mem_grade = mem_grade;
}
public String getMem_phone() {
return mem_phone;
}
public void setMem_phone(String mem_phone) {
this.mem_phone = mem_phone;
}
public String getMem_email() {
return mem_email;
}
public void setMem_email(String mem_email) {
this.mem_email = mem_email;
}
public Date getMem_date() {
return mem_date;
}
public void setMem_date(Date mem_date) {
this.mem_date = mem_date;
}
public MultipartFile getUpload() {
return upload;
}
public byte[] getMem_image() {
return mem_image;
}
public void setMem_image(byte[] mem_image) {
this.mem_image = mem_image;
}
public String getMem_filename() {
return mem_filename;
}
public void setMem_filename(String mem_filename) {
this.mem_filename = mem_filename;
}
@Override
public String toString() {
return "MemberCommand [mem_id=" + mem_id + ", mem_auth=" + mem_auth + ", mem_driver=" + mem_driver + ", mem_pw="
+ mem_pw + ", mem_name=" + mem_name + ", mem_gender=" + mem_gender + ", mem_grade=" + mem_grade
+ ", mem_phone=" + mem_phone + ", mem_email=" + mem_email + ", mem_date=" + mem_date + ", upload="
+ upload + ", mem_filename=" + mem_filename + "]";
}
}
| UHC | Java | 3,367 | java | MemberCommand.java | Java | []
| null | []
| package car.pool.member.domain;
import java.io.IOException;
import java.sql.Date;
import javax.validation.constraints.Size;
import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.NotEmpty;
import org.springframework.web.multipart.MultipartFile;
public class MemberCommand {
@NotEmpty
private String mem_id;
private int mem_auth; /* 0탈퇴회원, 1일반회원, 2관리자 */
private int mem_driver; /* 1일반회원, 2운전자회원 */
@Size(min=4,max=10)
private String mem_pw;
@NotEmpty
private String mem_name;
private String mem_gender;
private String mem_grade;
@NotEmpty
private String mem_phone;
@NotEmpty
private String mem_email;
private Date mem_date;
private MultipartFile upload;
private byte[] mem_image;
private String mem_filename;
//비밀번호 일치 여부 체크
public boolean isCheckedPasswd(String userPasswd){
if(mem_auth > 0 && mem_pw.equals(userPasswd)){
return true;
}
return false;
}
public void setUpload(MultipartFile upload) throws IOException {
this.upload = upload;
setMem_image(upload.getBytes());
setMem_filename(upload.getOriginalFilename());
}
public String getMem_id() {
return mem_id;
}
public void setMem_id(String mem_id) {
this.mem_id = mem_id;
}
public int getMem_auth() {
return mem_auth;
}
public void setMem_auth(int mem_auth) {
this.mem_auth = mem_auth;
}
public int getMem_driver() {
return mem_driver;
}
public void setMem_driver(int mem_driver) {
this.mem_driver = mem_driver;
}
public String getMem_pw() {
return mem_pw;
}
public void setMem_pw(String mem_pw) {
this.mem_pw = mem_pw;
}
public String getMem_name() {
return mem_name;
}
public void setMem_name(String mem_name) {
this.mem_name = mem_name;
}
public String getMem_gender() {
return mem_gender;
}
public void setMem_gender(String mem_gender) {
this.mem_gender = mem_gender;
}
public String getMem_grade() {
return mem_grade;
}
public void setMem_grade(String mem_grade) {
this.mem_grade = mem_grade;
}
public String getMem_phone() {
return mem_phone;
}
public void setMem_phone(String mem_phone) {
this.mem_phone = mem_phone;
}
public String getMem_email() {
return mem_email;
}
public void setMem_email(String mem_email) {
this.mem_email = mem_email;
}
public Date getMem_date() {
return mem_date;
}
public void setMem_date(Date mem_date) {
this.mem_date = mem_date;
}
public MultipartFile getUpload() {
return upload;
}
public byte[] getMem_image() {
return mem_image;
}
public void setMem_image(byte[] mem_image) {
this.mem_image = mem_image;
}
public String getMem_filename() {
return mem_filename;
}
public void setMem_filename(String mem_filename) {
this.mem_filename = mem_filename;
}
@Override
public String toString() {
return "MemberCommand [mem_id=" + mem_id + ", mem_auth=" + mem_auth + ", mem_driver=" + mem_driver + ", mem_pw="
+ mem_pw + ", mem_name=" + mem_name + ", mem_gender=" + mem_gender + ", mem_grade=" + mem_grade
+ ", mem_phone=" + mem_phone + ", mem_email=" + mem_email + ", mem_date=" + mem_date + ", upload="
+ upload + ", mem_filename=" + mem_filename + "]";
}
}
| 3,367 | 0.654974 | 0.652253 | 139 | 21.791367 | 20.649691 | 114 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.669065 | false | false | 4 |
f2fe479370e75fb74176a58dcb713bf320166d37 | 29,978,871,775,691 | e921703f9a60c42f054ebd0a277a8630e30277ec | /EpitechMessengerApp/app/src/main/java/com/gautier_lefebvre/epitechmessengerapp/helper/RSAHelper.java | 68d190ff16d9d9188a4384762b857d7d2df65134 | []
| no_license | gerybaudry/android-retro-picture | https://github.com/gerybaudry/android-retro-picture | fa156b6636190c4629267531a78042b5ba38bfe6 | d8e5014307eecc46d6367d8c776c9cbbe5b91a8b | refs/heads/master | 2021-01-10T11:18:40.874000 | 2016-03-04T18:34:17 | 2016-03-04T18:34:17 | 51,207,432 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.gautier_lefebvre.epitechmessengerapp.helper;
import android.util.Base64;
import com.gautier_lefebvre.epitechmessengerapp.exception.RSAException;
import java.io.UnsupportedEncodingException;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.X509EncodedKeySpec;
import javax.crypto.Cipher;
public class RSAHelper {
private static final String algorithm = "RSA";
public static byte[] encrypt(byte[] message, PublicKey rsaPublicKey) throws RSAException {
try {
Cipher cipher = Cipher.getInstance(RSAHelper.algorithm);
cipher.init(Cipher.ENCRYPT_MODE, rsaPublicKey);
return cipher.doFinal(message);
} catch (Exception e) {
throw new RSAException();
}
}
public static PublicKey getKeyFromString(String keyStr) throws RSAException {
try {
byte[] keyBytes = Base64.decode(keyStr.getBytes("utf-8"), Base64.DEFAULT);
X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(RSAHelper.algorithm);
return keyFactory.generatePublic(spec);
} catch (UnsupportedEncodingException|NoSuchAlgorithmException|InvalidKeySpecException e) {
throw new RSAException();
}
}
}
| UTF-8 | Java | 1,434 | java | RSAHelper.java | Java | [
{
"context": "elper;\n\nimport android.util.Base64;\n\nimport com.gautier_lefebvre.epitechmessengerapp.exception.RSAExceptio",
"end": 106,
"score": 0.6328021883964539,
"start": 100,
"tag": "USERNAME",
"value": "utier_"
},
{
"context": "ort android.util.Base64;\n\nimport com.gautier_lefebvre.epitechmessengerapp.exception.RSAException;\n\nimpo",
"end": 114,
"score": 0.5798502564430237,
"start": 111,
"tag": "USERNAME",
"value": "vre"
}
]
| null | []
| package com.gautier_lefebvre.epitechmessengerapp.helper;
import android.util.Base64;
import com.gautier_lefebvre.epitechmessengerapp.exception.RSAException;
import java.io.UnsupportedEncodingException;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.X509EncodedKeySpec;
import javax.crypto.Cipher;
public class RSAHelper {
private static final String algorithm = "RSA";
public static byte[] encrypt(byte[] message, PublicKey rsaPublicKey) throws RSAException {
try {
Cipher cipher = Cipher.getInstance(RSAHelper.algorithm);
cipher.init(Cipher.ENCRYPT_MODE, rsaPublicKey);
return cipher.doFinal(message);
} catch (Exception e) {
throw new RSAException();
}
}
public static PublicKey getKeyFromString(String keyStr) throws RSAException {
try {
byte[] keyBytes = Base64.decode(keyStr.getBytes("utf-8"), Base64.DEFAULT);
X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(RSAHelper.algorithm);
return keyFactory.generatePublic(spec);
} catch (UnsupportedEncodingException|NoSuchAlgorithmException|InvalidKeySpecException e) {
throw new RSAException();
}
}
}
| 1,434 | 0.718968 | 0.70781 | 39 | 35.76923 | 29.619347 | 99 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.641026 | false | false | 4 |
b5579b1edcabac5af6bb28a8e61a4d3a448f22f0 | 34,067,680,619,061 | 28dd5238eb642a859ec37ec4303bf41a208a2c2a | /src/Week1/Min/MinArray.java | e6be2a25565845915005c52b7fb0ac51f8dcc2a6 | []
| no_license | linhqtri123/DN-C0919H1-LeHaManhLinh-Module2 | https://github.com/linhqtri123/DN-C0919H1-LeHaManhLinh-Module2 | dc39f1529b7cc6ec6bc58de15dbe1f8ab89625be | 728f9a08fc41276f1290c8918eb48d7d0520945d | refs/heads/master | 2022-12-22T05:52:06.954000 | 2020-03-15T13:41:58 | 2020-03-15T13:41:58 | 215,184,941 | 0 | 0 | null | false | 2022-12-16T10:31:53 | 2019-10-15T02:09:59 | 2020-03-15T13:42:19 | 2022-12-16T10:31:50 | 33,607 | 0 | 0 | 12 | Java | false | false | package Week1.Min;
import java.util.*;
public class MinArray {
private int size;
private int array[] = new int[30];
private Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
MinArray minarr = new MinArray();
minarr.inputArray();
minarr.outputArray();
minarr.minArray();
}
public void inputArray() {
System.out.print("Nhập vào số phần tử : ");
size = scanner.nextInt();
for (int i = 0; i < size; i++) {
System.out.print("Phần tử " + i + " :");
array[i] = scanner.nextInt();
}
System.out.println();
}
public void outputArray() {
System.out.print("Array :");
for (int i = 0; i < size; i++) {
System.out.print("\t" + array[i]);
}
System.out.println();
}
public void minArray(){
int min = array[0];
int index = 0;
for (int i = 0 ; i < size; i++){
if (min > array[i]){
min = array[i];
index = i;
}
}
System.out.println("Min Array : "+min+" Index : "+index);
}
}
| UTF-8 | Java | 1,185 | java | MinArray.java | Java | []
| null | []
| package Week1.Min;
import java.util.*;
public class MinArray {
private int size;
private int array[] = new int[30];
private Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
MinArray minarr = new MinArray();
minarr.inputArray();
minarr.outputArray();
minarr.minArray();
}
public void inputArray() {
System.out.print("Nhập vào số phần tử : ");
size = scanner.nextInt();
for (int i = 0; i < size; i++) {
System.out.print("Phần tử " + i + " :");
array[i] = scanner.nextInt();
}
System.out.println();
}
public void outputArray() {
System.out.print("Array :");
for (int i = 0; i < size; i++) {
System.out.print("\t" + array[i]);
}
System.out.println();
}
public void minArray(){
int min = array[0];
int index = 0;
for (int i = 0 ; i < size; i++){
if (min > array[i]){
min = array[i];
index = i;
}
}
System.out.println("Min Array : "+min+" Index : "+index);
}
}
| 1,185 | 0.487201 | 0.480375 | 43 | 26.255814 | 16.249641 | 65 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.651163 | false | false | 4 |
43e7c4a3423ab966365ee60bb24fb37f4485649d | 24,584,392,853,905 | d0bae62eb391b9b1f2952ca8bbd8f9cc23a79152 | /app/src/main/java/com/ysln/tykj/partybuildaapp/fragments/FragmentUpdate.java | c3f89743ca368fd0c227849b5a1f45f600697427 | [
"Apache-2.0"
]
| permissive | CeuiLiSA/partyBuildAAPP | https://github.com/CeuiLiSA/partyBuildAAPP | 665b90642ae87ae2b76abb6352c776e8dd0244a9 | 9ebe64aa9ef479808aa1ffbb7cacd38c7370dc98 | refs/heads/master | 2018-10-25T10:43:15.310000 | 2018-09-27T09:54:17 | 2018-09-27T09:54:17 | 144,655,905 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.ysln.tykj.partybuildaapp.fragments;
import android.app.Dialog;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;
import com.ysln.tykj.partybuildaapp.R;
import com.ysln.tykj.partybuildaapp.network.RetrofitUtil;
import com.ysln.tykj.partybuildaapp.utils.ApkDownloadTask;
import com.ysln.tykj.partybuildaapp.utils.FileUtils;
public class FragmentUpdate {
private Context mContext;
private Dialog mDialog;
public FragmentUpdate(Context context) {
mContext = context;
initDialoag();
}
private void initDialoag() {
mDialog = new Dialog(mContext);
mDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
mDialog.setCancelable(true);
}
public void showUpdateMessage(String url) {
LayoutInflater inflater = LayoutInflater.from(mContext);
View dialogView = inflater.inflate(R.layout.update_dialoag, null);
TextView textView = dialogView.findViewById(R.id.title_left);
TextView textView2 = dialogView.findViewById(R.id.title_right);
textView.setOnClickListener(v -> mDialog.dismiss());
textView2.setOnClickListener(v -> {
mDialog.dismiss();
new ApkDownloadTask(FileUtils.
generateBinaryImgFile("PartyBuild.apk", mContext), mContext).
execute(url.replace("\\", "/"));
});
mDialog.setContentView(dialogView);
WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
Window window = mDialog.getWindow();
lp.copyFrom(window.getAttributes());
lp.width = mContext.getResources().getDisplayMetrics().widthPixels * 4 / 5;
lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
mDialog.show();
window.setAttributes(lp);
}
}
| UTF-8 | Java | 1,925 | java | FragmentUpdate.java | Java | []
| null | []
| package com.ysln.tykj.partybuildaapp.fragments;
import android.app.Dialog;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;
import com.ysln.tykj.partybuildaapp.R;
import com.ysln.tykj.partybuildaapp.network.RetrofitUtil;
import com.ysln.tykj.partybuildaapp.utils.ApkDownloadTask;
import com.ysln.tykj.partybuildaapp.utils.FileUtils;
public class FragmentUpdate {
private Context mContext;
private Dialog mDialog;
public FragmentUpdate(Context context) {
mContext = context;
initDialoag();
}
private void initDialoag() {
mDialog = new Dialog(mContext);
mDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
mDialog.setCancelable(true);
}
public void showUpdateMessage(String url) {
LayoutInflater inflater = LayoutInflater.from(mContext);
View dialogView = inflater.inflate(R.layout.update_dialoag, null);
TextView textView = dialogView.findViewById(R.id.title_left);
TextView textView2 = dialogView.findViewById(R.id.title_right);
textView.setOnClickListener(v -> mDialog.dismiss());
textView2.setOnClickListener(v -> {
mDialog.dismiss();
new ApkDownloadTask(FileUtils.
generateBinaryImgFile("PartyBuild.apk", mContext), mContext).
execute(url.replace("\\", "/"));
});
mDialog.setContentView(dialogView);
WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
Window window = mDialog.getWindow();
lp.copyFrom(window.getAttributes());
lp.width = mContext.getResources().getDisplayMetrics().widthPixels * 4 / 5;
lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
mDialog.show();
window.setAttributes(lp);
}
}
| 1,925 | 0.694026 | 0.691948 | 53 | 35.301888 | 23.316191 | 83 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.735849 | false | false | 4 |
ae45a6960bfa27a1474e1a6954905b9f6a326252 | 33,414,845,627,782 | 75e7bb7ef80ac599d6d3e008f8a83f007de17a6f | /ViewController/src/com/bio/mobile/dashboard/CategoryNBV.java | 34f676b697fdc5367f87dc933d0c6294ae84ad08 | []
| no_license | MarsMobile/BioApplication | https://github.com/MarsMobile/BioApplication | 7245b7adbaacabffa26cb71581bafefb60d34e23 | 8bfc0a5bd69f052cc8f10f4d36322e05d1155ac1 | refs/heads/master | 2017-04-03T03:38:56.636000 | 2016-10-25T20:27:51 | 2016-10-25T20:27:51 | 45,015,763 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.bio.mobile.dashboard;
import java.math.BigDecimal;
import oracle.adfmf.java.beans.PropertyChangeListener;
import oracle.adfmf.java.beans.PropertyChangeSupport;
public class CategoryNBV {
String category;
BigDecimal netBookValue, depriciation;
private PropertyChangeSupport propertyChangeSupport = new PropertyChangeSupport(this);
public CategoryNBV(String category, BigDecimal netBookValue, BigDecimal depriciation) {
setCategory(category);
setNetBookValue(netBookValue);
setDepriciation(depriciation);
}
public void setDepriciation(BigDecimal depriciation) {
BigDecimal oldDepriciation = this.depriciation;
this.depriciation = depriciation;
propertyChangeSupport.firePropertyChange("depriciation", oldDepriciation, depriciation);
}
public BigDecimal getDepriciation() {
return depriciation;
}
public CategoryNBV() {
super();
}
public void setCategory(String category) {
String oldCategory = this.category;
this.category = category;
propertyChangeSupport.firePropertyChange("category", oldCategory, category);
}
public String getCategory() {
return category;
}
public void setNetBookValue(BigDecimal netBookValue) {
BigDecimal oldNetBookValue = this.netBookValue;
this.netBookValue = netBookValue;
propertyChangeSupport.firePropertyChange("netBookValue", oldNetBookValue, netBookValue);
}
public BigDecimal getNetBookValue() {
return netBookValue;
}
public void addPropertyChangeListener(PropertyChangeListener l) {
propertyChangeSupport.addPropertyChangeListener(l);
}
public void removePropertyChangeListener(PropertyChangeListener l) {
propertyChangeSupport.removePropertyChangeListener(l);
}
}
| UTF-8 | Java | 1,921 | java | CategoryNBV.java | Java | []
| null | []
| package com.bio.mobile.dashboard;
import java.math.BigDecimal;
import oracle.adfmf.java.beans.PropertyChangeListener;
import oracle.adfmf.java.beans.PropertyChangeSupport;
public class CategoryNBV {
String category;
BigDecimal netBookValue, depriciation;
private PropertyChangeSupport propertyChangeSupport = new PropertyChangeSupport(this);
public CategoryNBV(String category, BigDecimal netBookValue, BigDecimal depriciation) {
setCategory(category);
setNetBookValue(netBookValue);
setDepriciation(depriciation);
}
public void setDepriciation(BigDecimal depriciation) {
BigDecimal oldDepriciation = this.depriciation;
this.depriciation = depriciation;
propertyChangeSupport.firePropertyChange("depriciation", oldDepriciation, depriciation);
}
public BigDecimal getDepriciation() {
return depriciation;
}
public CategoryNBV() {
super();
}
public void setCategory(String category) {
String oldCategory = this.category;
this.category = category;
propertyChangeSupport.firePropertyChange("category", oldCategory, category);
}
public String getCategory() {
return category;
}
public void setNetBookValue(BigDecimal netBookValue) {
BigDecimal oldNetBookValue = this.netBookValue;
this.netBookValue = netBookValue;
propertyChangeSupport.firePropertyChange("netBookValue", oldNetBookValue, netBookValue);
}
public BigDecimal getNetBookValue() {
return netBookValue;
}
public void addPropertyChangeListener(PropertyChangeListener l) {
propertyChangeSupport.addPropertyChangeListener(l);
}
public void removePropertyChangeListener(PropertyChangeListener l) {
propertyChangeSupport.removePropertyChangeListener(l);
}
}
| 1,921 | 0.704321 | 0.704321 | 61 | 29.491804 | 28.423393 | 96 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.557377 | false | false | 4 |
e214409c90b00287d234a6a103313324a145dd8b | 24,653,112,345,290 | 1d8ac735db44f1ccd357e9bfd62ebf6f957e9b18 | /src/main/java/com/agatah/dogtalk/repository/LocationRepository.java | 752c1ca18bae231347db2a0d07838abe51980165 | []
| no_license | agatah/dogtalk | https://github.com/agatah/dogtalk | 6f0a4e50c883cb68e33448c18dbb630c8a051c7a | 30e26f0bd1f0f3556dc3f206c836609462b233cf | refs/heads/master | 2023-08-22T08:37:22.333000 | 2021-10-14T11:37:37 | 2021-10-14T11:37:37 | 394,538,414 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.agatah.dogtalk.repository;
import com.agatah.dogtalk.model.Location;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.Optional;
public interface LocationRepository extends JpaRepository<Location, Long> {
Optional<Location> findByCity(String city);
}
| UTF-8 | Java | 301 | java | LocationRepository.java | Java | []
| null | []
| package com.agatah.dogtalk.repository;
import com.agatah.dogtalk.model.Location;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.Optional;
public interface LocationRepository extends JpaRepository<Location, Long> {
Optional<Location> findByCity(String city);
}
| 301 | 0.813953 | 0.813953 | 12 | 24.083334 | 26.452658 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 4 |
80bd5084f7ca38ec030df5c2a3d54e05d688e7b2 | 30,958,124,281,561 | 128cfd27761a704ed73de1d02387baecfea73d02 | /Android Developer Fundamentals Course (V1)/ScoreKeeper/app/src/main/java/com/luispena/scorekeeper/MainActivity.java | 2fa7f0fcf9a662c1ba0437072ed4d05e84064fb5 | []
| no_license | poszy/AADPro | https://github.com/poszy/AADPro | 787489f2fdb848e41b50fe5835885b37ff36526b | 676f1caaf8dcae12d3bde8124fdca0868eb25455 | refs/heads/master | 2021-07-12T11:11:22.313000 | 2020-05-10T10:22:25 | 2020-05-10T10:22:25 | 128,854,099 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.luispena.scorekeeper;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.app.AppCompatDelegate;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
// Class Global Variables
int mScoreOne = 0;
int mScoreTwo = 0;
//Tag to be used as the key in OnSavedInstanceState
static final String STATE_SCORE_1 = "Team 1 Score";
static final String STATE_SCORE_2 = "Team 2 Score";
private TextView teamOne;
private TextView teamTwo;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// In android API 26 and above you no longer need to case (TextView)
// https://stackoverflow.com/questions/44902651/no-need-to-cast-the-result-of-findviewbyid
teamOne = (TextView) findViewById(R.id.score_one);
teamTwo = (TextView) findViewById(R.id.score_two);
if (savedInstanceState != null) {
mScoreOne = savedInstanceState.getInt(STATE_SCORE_1);
mScoreTwo = savedInstanceState.getInt(STATE_SCORE_2);
//Set the score text views
teamOne.setText(String.valueOf(mScoreOne));
teamTwo.setText(String.valueOf(mScoreTwo));
}
}
@Override
protected void onSaveInstanceState(Bundle outState) {
//Save the scores
outState.putInt(STATE_SCORE_1, mScoreOne);
outState.putInt(STATE_SCORE_2, mScoreOne);
super.onSaveInstanceState(outState);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu, menu);
// change the label of the menu based on the state of the app
int nightMode = AppCompatDelegate.getDefaultNightMode();
if(nightMode == AppCompatDelegate.MODE_NIGHT_YES){
menu.findItem(R.id.night_mode).setTitle(R.string.day_mode);
} //end if
else {
menu.findItem(R.id.night_mode).setTitle(R.string.night_mode);
} // end else
return true;
} // end onCreateOptionsMenu
@Override
public boolean onOptionsItemSelected(MenuItem item) {
//Check if the correct item was clicked
if(item.getItemId()==R.id.night_mode){
int nightMode = AppCompatDelegate.getDefaultNightMode();
if (nightMode == AppCompatDelegate.MODE_NIGHT_YES) {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
} // end second if
else{
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
} //end else
// this will recreate the activity when theme changes
recreate();
return true;
} // end first if
//Recreate the activity for the theme change to take effect
recreate();
return super.onOptionsItemSelected(item);
} // end onOptionsItemSelected
public void decreaseScore(View view) {
Toast.makeText(getApplicationContext(), "d score", Toast.LENGTH_SHORT).show();
// Get the id of the button that was clicked
int viewID = view.getId();
switch (viewID){
// if it was on Team 1
case R.id.decrease_one:
// decrease the score
Toast.makeText(getApplicationContext(), "Decreased Team 1 Score", Toast.LENGTH_SHORT).show();
mScoreOne--;
teamOne.setText(String.valueOf(mScoreOne));
break;
case R.id.decrease_two:
Toast.makeText(getApplicationContext(), "Decreased Team 2 Score", Toast.LENGTH_SHORT).show();
mScoreTwo--;
teamTwo.setText(String.valueOf(mScoreTwo));
break;
} // end switch
} // end decreaseScore
public void increaseScore(View view) {
Toast.makeText(getApplicationContext(), "i score", Toast.LENGTH_SHORT).show();
// Get the id of the button that was clicked
int viewID = view.getId();
switch (viewID){
// if it was on Team 1]
case R.id.increase_one:
Toast.makeText(getApplicationContext(), "Increased Team 1 Score", Toast.LENGTH_SHORT).show();
// increase the score and update TextView
mScoreOne++;
teamOne.setText(String.valueOf(mScoreOne));
break;
case R.id.increase_two:
Toast.makeText(getApplicationContext(), "Decreased Team 2 Score", Toast.LENGTH_SHORT).show();
mScoreTwo++;
teamTwo.setText(String.valueOf(mScoreTwo));
break;
} // end switch
}
}
| UTF-8 | Java | 4,972 | java | MainActivity.java | Java | [
{
"context": "\npackage com.luispena.scorekeeper;\n\nimport android.support.v7.app.AppC",
"end": 20,
"score": 0.5373243689537048,
"start": 17,
"tag": "USERNAME",
"value": "pen"
}
]
| null | []
|
package com.luispena.scorekeeper;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.app.AppCompatDelegate;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
// Class Global Variables
int mScoreOne = 0;
int mScoreTwo = 0;
//Tag to be used as the key in OnSavedInstanceState
static final String STATE_SCORE_1 = "Team 1 Score";
static final String STATE_SCORE_2 = "Team 2 Score";
private TextView teamOne;
private TextView teamTwo;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// In android API 26 and above you no longer need to case (TextView)
// https://stackoverflow.com/questions/44902651/no-need-to-cast-the-result-of-findviewbyid
teamOne = (TextView) findViewById(R.id.score_one);
teamTwo = (TextView) findViewById(R.id.score_two);
if (savedInstanceState != null) {
mScoreOne = savedInstanceState.getInt(STATE_SCORE_1);
mScoreTwo = savedInstanceState.getInt(STATE_SCORE_2);
//Set the score text views
teamOne.setText(String.valueOf(mScoreOne));
teamTwo.setText(String.valueOf(mScoreTwo));
}
}
@Override
protected void onSaveInstanceState(Bundle outState) {
//Save the scores
outState.putInt(STATE_SCORE_1, mScoreOne);
outState.putInt(STATE_SCORE_2, mScoreOne);
super.onSaveInstanceState(outState);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu, menu);
// change the label of the menu based on the state of the app
int nightMode = AppCompatDelegate.getDefaultNightMode();
if(nightMode == AppCompatDelegate.MODE_NIGHT_YES){
menu.findItem(R.id.night_mode).setTitle(R.string.day_mode);
} //end if
else {
menu.findItem(R.id.night_mode).setTitle(R.string.night_mode);
} // end else
return true;
} // end onCreateOptionsMenu
@Override
public boolean onOptionsItemSelected(MenuItem item) {
//Check if the correct item was clicked
if(item.getItemId()==R.id.night_mode){
int nightMode = AppCompatDelegate.getDefaultNightMode();
if (nightMode == AppCompatDelegate.MODE_NIGHT_YES) {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
} // end second if
else{
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
} //end else
// this will recreate the activity when theme changes
recreate();
return true;
} // end first if
//Recreate the activity for the theme change to take effect
recreate();
return super.onOptionsItemSelected(item);
} // end onOptionsItemSelected
public void decreaseScore(View view) {
Toast.makeText(getApplicationContext(), "d score", Toast.LENGTH_SHORT).show();
// Get the id of the button that was clicked
int viewID = view.getId();
switch (viewID){
// if it was on Team 1
case R.id.decrease_one:
// decrease the score
Toast.makeText(getApplicationContext(), "Decreased Team 1 Score", Toast.LENGTH_SHORT).show();
mScoreOne--;
teamOne.setText(String.valueOf(mScoreOne));
break;
case R.id.decrease_two:
Toast.makeText(getApplicationContext(), "Decreased Team 2 Score", Toast.LENGTH_SHORT).show();
mScoreTwo--;
teamTwo.setText(String.valueOf(mScoreTwo));
break;
} // end switch
} // end decreaseScore
public void increaseScore(View view) {
Toast.makeText(getApplicationContext(), "i score", Toast.LENGTH_SHORT).show();
// Get the id of the button that was clicked
int viewID = view.getId();
switch (viewID){
// if it was on Team 1]
case R.id.increase_one:
Toast.makeText(getApplicationContext(), "Increased Team 1 Score", Toast.LENGTH_SHORT).show();
// increase the score and update TextView
mScoreOne++;
teamOne.setText(String.valueOf(mScoreOne));
break;
case R.id.increase_two:
Toast.makeText(getApplicationContext(), "Decreased Team 2 Score", Toast.LENGTH_SHORT).show();
mScoreTwo++;
teamTwo.setText(String.valueOf(mScoreTwo));
break;
} // end switch
}
}
| 4,972 | 0.619067 | 0.613435 | 165 | 29.127274 | 28.090366 | 109 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.442424 | false | false | 4 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.