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
6542c8f34cbbbd9296541ce6f2d9be37f00f209f
38,689,065,420,860
8a58b3f6e6b9a430314db2b92f5a381f041453bf
/src/in/myecash/services/InternalUserServices.java
a819f2b8a7f995d8a20a0d9fdf2fe56687d85b87
[]
no_license
dreamykun/backend2
https://github.com/dreamykun/backend2
eaa262d1a5073fb6a6f713dac6dec0b4357841b4
cf48c1bea35158c71a12507b58c347621aa933bd
refs/heads/master
2021-01-11T00:21:07.187000
2016-10-11T00:46:48
2016-10-11T00:46:48
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package in.myecash.services; import com.backendless.Backendless; import com.backendless.BackendlessUser; import com.backendless.FilePermission; import com.backendless.exceptions.BackendlessException; import com.backendless.servercode.IBackendlessService; import com.backendless.servercode.InvocationContext; import in.myecash.common.CommonUtils; import in.myecash.messaging.SmsConstants; import in.myecash.messaging.SmsHelper; import in.myecash.utilities.BackendOps; import in.myecash.utilities.BackendUtils; import in.myecash.utilities.MyLogger; import java.util.Date; import in.myecash.common.database.*; import in.myecash.common.constants.*; import in.myecash.constants.*; import in.myecash.database.*; /** * Created by adgangwa on 12-08-2016. */ public class InternalUserServices implements IBackendlessService { private MyLogger mLogger = new MyLogger("services.AgentServicesNoLogin"); private String[] mEdr = new String[BackendConstants.BACKEND_EDR_MAX_FIELDS];; /* * Public methods: Backend REST APIs */ public String registerMerchant(Merchants merchant) { BackendUtils.initAll(); long startTime = System.currentTimeMillis(); mEdr[BackendConstants.EDR_START_TIME_IDX] = String.valueOf(startTime); mEdr[BackendConstants.EDR_API_NAME_IDX] = "registerMerchant"; mEdr[BackendConstants.EDR_API_PARAMS_IDX] = merchant.getAuto_id()+BackendConstants.BACKEND_EDR_SUB_DELIMETER+ merchant.getMobile_num()+BackendConstants.BACKEND_EDR_SUB_DELIMETER+ merchant.getName(); String merchantId = null; try { //mLogger.debug("In registerMerchant"); //mLogger.debug("registerMerchant: Before: "+ InvocationContext.asString()); //mLogger.debug("registerMerchant: Before: "+HeadersManager.getInstance().getHeaders().toString()); //mLogger.flush(); // Fetch agent InternalUser agent = (InternalUser) BackendUtils.fetchCurrentUser(InvocationContext.getUserId(), DbConstants.USER_TYPE_AGENT, mEdr, mLogger, false); // Fetch city Cities city = BackendOps.fetchCity(merchant.getAddress().getCity()); // get open merchant id batch String countryCode = city.getCountryCode(); String batchTableName = DbConstantsBackend.MERCHANT_ID_BATCH_TABLE_NAME+countryCode; String whereClause = "status = '"+DbConstantsBackend.BATCH_STATUS_OPEN +"'"; MerchantIdBatches batch = BackendOps.fetchMerchantIdBatch(batchTableName,whereClause); if(batch == null) { throw new BackendlessException(String.valueOf(ErrorCodes.MERCHANT_ID_RANGE_ERROR), "No open merchant id batch available: "+batchTableName+","+whereClause); } // get merchant counter value and use the same to generate merchant id Long merchantCnt = BackendOps.fetchCounterValue(DbConstantsBackend.MERCHANT_ID_COUNTER); mLogger.debug("Fetched merchant cnt: "+merchantCnt); // set merchant id merchantId = BackendUtils.generateMerchantId(batch, countryCode, merchantCnt); mLogger.debug("Generated merchant id: "+merchantId); merchant.setAuto_id(merchantId); merchant.setAdmin_status(DbConstants.USER_STATUS_ACTIVE); merchant.setStatus_reason(DbConstantsBackend.ENABLED_ACTIVE); merchant.setStatus_update_time(new Date()); merchant.setLastRenewDate(new Date()); //merchant.setAdmin_remarks("New registered merchant"); merchant.setMobile_num(merchant.getMobile_num()); merchant.setFirst_login_ok(false); merchant.setAgentId(agent.getId()); // set cashback and transaction table names //setCbAndTransTables(merchant, merchantCnt); merchant.setCashback_table(DbConstantsBackend.CASHBACK_TABLE_NAME + city.getCbTableCode()); BackendOps.describeTable(merchant.getCashback_table()); // just to check that the table exists merchant.setTxn_table(DbConstantsBackend.TRANSACTION_TABLE_NAME + city.getCbTableCode()); BackendOps.describeTable(merchant.getTxn_table()); // just to check that the table exists // generate and set password String pwd = BackendUtils.generateTempPassword(); mLogger.debug("Generated passwd: "+pwd); BackendlessUser user = new BackendlessUser(); user.setProperty("user_id", merchantId); user.setPassword(pwd); user.setProperty("user_type", DbConstants.USER_TYPE_MERCHANT); user.setProperty("merchant", merchant); user = BackendOps.registerUser(user); // register successfull - can write to edr now mEdr[BackendConstants.EDR_MCHNT_ID_IDX] = merchant.getAuto_id(); try { BackendOps.assignRole(merchantId, BackendConstants.ROLE_MERCHANT); } catch(Exception e) { mLogger.fatal("Failed to assign role to merchant user: "+merchantId+","+e.toString()); rollbackRegister(merchantId); throw e; } // create directories for 'txnCsv' and 'txnImage' files String fileDir = null; String filePath = null; try { fileDir = CommonUtils.getMerchantTxnDir(merchantId); filePath = fileDir + CommonConstants.FILE_PATH_SEPERATOR+BackendConstants.DUMMY_FILENAME; // saving dummy files to create parent directories Backendless.Files.saveFile(filePath, BackendConstants.DUMMY_DATA.getBytes("UTF-8"), true); // Give this merchant permissions for this directory FilePermission.READ.grantForUser( user.getObjectId(), fileDir); FilePermission.DELETE.grantForUser( user.getObjectId(), fileDir); FilePermission.WRITE.grantForUser( user.getObjectId(), fileDir); mLogger.debug("Saved dummy txn csv file: " + filePath); fileDir = CommonUtils.getTxnImgDir(merchantId); filePath = fileDir + CommonConstants.FILE_PATH_SEPERATOR+BackendConstants.DUMMY_FILENAME; Backendless.Files.saveFile(filePath, BackendConstants.DUMMY_DATA.getBytes("UTF-8"), true); // Give read access to this merchant to this directory FilePermission.WRITE.grantForUser( user.getObjectId(), fileDir); mLogger.debug("Saved dummy txn image file: " + filePath); } catch(Exception e) { mLogger.fatal("Failed to create merchant directories: "+merchantId+","+e.toString()); rollbackRegister(merchantId); throw new BackendlessException(String.valueOf(ErrorCodes.GENERAL_ERROR), e.toString()); } // send SMS with user id String smsText = String.format(SmsConstants.SMS_MERCHANT_ID_FIRST, merchantId); SmsHelper.sendSMS(smsText, merchant.getMobile_num(), mEdr, mLogger); // no exception - means function execution success mEdr[BackendConstants.EDR_RESULT_IDX] = BackendConstants.BACKEND_EDR_RESULT_OK; return merchantId; } catch(Exception e) { BackendUtils.handleException(e,false,mLogger,mEdr); if(merchantId!=null && !merchantId.isEmpty()) { BackendOps.decrementCounterValue(DbConstantsBackend.MERCHANT_ID_COUNTER); } throw e; } finally { BackendUtils.finalHandling(startTime,mLogger,mEdr); } } public void disableMerchant(String merchantId, String ticketNum, String reason, String remarks) { BackendUtils.initAll(); long startTime = System.currentTimeMillis(); mEdr[BackendConstants.EDR_START_TIME_IDX] = String.valueOf(startTime); mEdr[BackendConstants.EDR_API_NAME_IDX] = "disableMerchant"; mEdr[BackendConstants.EDR_API_PARAMS_IDX] = merchantId+BackendConstants.BACKEND_EDR_SUB_DELIMETER+ ticketNum+BackendConstants.BACKEND_EDR_SUB_DELIMETER+ reason; try { // Fetch customer care user InternalUser internalUser = (InternalUser) BackendUtils.fetchCurrentUser(InvocationContext.getUserId(), null, mEdr, mLogger, false); int userType = Integer.parseInt(mEdr[BackendConstants.EDR_USER_TYPE_IDX]); if( userType!=DbConstants.USER_TYPE_CC && userType!=DbConstants.USER_TYPE_CNT ) { throw new BackendlessException(String.valueOf(ErrorCodes.OPERATION_NOT_ALLOWED), "Operation not allowed to this user"); } // Fetch merchant Merchants merchant = BackendOps.getMerchant(merchantId, false, false); // Add merchant op first - then update status MerchantOps op = new MerchantOps(); op.setCreateTime(new Date()); op.setMerchant_id(merchant.getAuto_id()); op.setMobile_num(merchant.getMobile_num()); op.setOp_code(DbConstants.OP_DISABLE_ACC); op.setOp_status(DbConstantsBackend.USER_OP_STATUS_COMPLETE); op.setTicketNum(ticketNum); op.setReason(reason); op.setRemarks(remarks); op.setAgentId(internalUser.getId()); op.setInitiatedBy( (userType==DbConstants.USER_TYPE_CC)? DbConstantsBackend.USER_OP_INITBY_MCHNT : DbConstantsBackend.USER_OP_INITBY_ADMIN); if(userType==DbConstants.USER_TYPE_CC) { op.setInitiatedVia(DbConstantsBackend.USER_OP_INITVIA_CC); } op = BackendOps.saveMerchantOp(op); // Update status try { BackendUtils.setMerchantStatus(merchant, DbConstants.USER_STATUS_DISABLED, reason, mEdr, mLogger); /*merchant.setAdmin_status(DbConstants.USER_STATUS_DISABLED); merchant.setStatus_update_time(new Date()); merchant.setStatus_reason(reason); merchant = BackendOps.updateMerchant(merchant);*/ } catch(Exception e) { mLogger.error("disableMerchant: Exception while updating merchant status: "+merchantId); // Rollback - delete merchant op added try { BackendOps.deleteMerchantOp(op); } catch(Exception ex) { mLogger.fatal("disableMerchant: Failed to rollback: merchant op deletion failed: "+merchantId); // Rollback also failed mEdr[BackendConstants.EDR_SPECIAL_FLAG_IDX] = BackendConstants.BACKEND_EDR_MANUAL_CHECK; throw ex; } throw e; } // send SMS with user id String smsText = String.format(SmsConstants.SMS_ACCOUNT_DISABLE, BackendUtils.getHalfVisibleId(merchantId)); SmsHelper.sendSMS(smsText, merchant.getMobile_num(), mEdr, mLogger); // no exception - means function execution success mEdr[BackendConstants.EDR_RESULT_IDX] = BackendConstants.BACKEND_EDR_RESULT_OK; } catch(Exception e) { BackendUtils.handleException(e,false,mLogger,mEdr); throw e; } finally { BackendUtils.finalHandling(startTime,mLogger,mEdr); } } /* * Private helper methods */ /* private void setCbAndTransTables(Merchants merchant, long regCounter) { // decide on the cashback table using round robin int pool_size = BackendConstants.CASHBACK_TABLE_POOL_SIZE; int pool_start = BackendConstants.CASHBACK_TABLE_POOL_START; // use last 4 numeric digits for round-robin int table_suffix = pool_start + ((int)(regCounter % pool_size)); String cbTableName = DbConstantsBackend.CASHBACK_TABLE_NAME + String.valueOf(table_suffix); merchant.setCashback_table(cbTableName); mLogger.debug("Generated cashback table name:" + cbTableName); // use the same prefix for cashback and transaction tables // as there is 1-to-1 mapping in the table schema - transaction0 maps to cashback0 only String transTableName = DbConstantsBackend.TRANSACTION_TABLE_NAME + String.valueOf(table_suffix); merchant.setTxn_table(transTableName); mLogger.debug("Generated transaction table name:" + transTableName); }*/ // private void rollbackRegister(BackendlessUser user) { private void rollbackRegister(String mchntId) { // TODO: add as 'Major' alarm - user to be removed later manually // rollback to not-usable state mEdr[BackendConstants.EDR_SPECIAL_FLAG_IDX] = BackendConstants.BACKEND_EDR_MANUAL_CHECK; try { Merchants merchant = BackendOps.getMerchant(mchntId, false, false); BackendUtils.setMerchantStatus(merchant, DbConstants.USER_STATUS_REG_ERROR, DbConstantsBackend.REG_ERROR_REG_FAILED, mEdr, mLogger); /*merchant.setAdmin_status(DbConstants.USER_STATUS_REG_ERROR); merchant.setStatus_reason(DbConstantsBackend.REG_ERROR_REG_FAILED); BackendOps.updateMerchant(merchant);*/ } catch(Exception ex) { mLogger.fatal("registerMerchant: Merchant Rollback failed: "+ex.toString()); mLogger.error(BackendUtils.stackTraceStr(ex)); mEdr[BackendConstants.EDR_SPECIAL_FLAG_IDX] = BackendConstants.BACKEND_EDR_MANUAL_CHECK; throw ex; } } }
UTF-8
Java
13,798
java
InternalUserServices.java
Java
[ { "context": ";\nimport in.myecash.database.*;\n\n/**\n * Created by adgangwa on 12-08-2016.\n */\npublic class InternalUserServi", "end": 736, "score": 0.9997313022613525, "start": 728, "tag": "USERNAME", "value": "adgangwa" }, { "context": "er_id\", merchantId);\n user.setPassword(pwd);\n user.setProperty(\"user_type\", DbCon", "end": 4641, "score": 0.8648412227630615, "start": 4638, "tag": "PASSWORD", "value": "pwd" } ]
null
[]
package in.myecash.services; import com.backendless.Backendless; import com.backendless.BackendlessUser; import com.backendless.FilePermission; import com.backendless.exceptions.BackendlessException; import com.backendless.servercode.IBackendlessService; import com.backendless.servercode.InvocationContext; import in.myecash.common.CommonUtils; import in.myecash.messaging.SmsConstants; import in.myecash.messaging.SmsHelper; import in.myecash.utilities.BackendOps; import in.myecash.utilities.BackendUtils; import in.myecash.utilities.MyLogger; import java.util.Date; import in.myecash.common.database.*; import in.myecash.common.constants.*; import in.myecash.constants.*; import in.myecash.database.*; /** * Created by adgangwa on 12-08-2016. */ public class InternalUserServices implements IBackendlessService { private MyLogger mLogger = new MyLogger("services.AgentServicesNoLogin"); private String[] mEdr = new String[BackendConstants.BACKEND_EDR_MAX_FIELDS];; /* * Public methods: Backend REST APIs */ public String registerMerchant(Merchants merchant) { BackendUtils.initAll(); long startTime = System.currentTimeMillis(); mEdr[BackendConstants.EDR_START_TIME_IDX] = String.valueOf(startTime); mEdr[BackendConstants.EDR_API_NAME_IDX] = "registerMerchant"; mEdr[BackendConstants.EDR_API_PARAMS_IDX] = merchant.getAuto_id()+BackendConstants.BACKEND_EDR_SUB_DELIMETER+ merchant.getMobile_num()+BackendConstants.BACKEND_EDR_SUB_DELIMETER+ merchant.getName(); String merchantId = null; try { //mLogger.debug("In registerMerchant"); //mLogger.debug("registerMerchant: Before: "+ InvocationContext.asString()); //mLogger.debug("registerMerchant: Before: "+HeadersManager.getInstance().getHeaders().toString()); //mLogger.flush(); // Fetch agent InternalUser agent = (InternalUser) BackendUtils.fetchCurrentUser(InvocationContext.getUserId(), DbConstants.USER_TYPE_AGENT, mEdr, mLogger, false); // Fetch city Cities city = BackendOps.fetchCity(merchant.getAddress().getCity()); // get open merchant id batch String countryCode = city.getCountryCode(); String batchTableName = DbConstantsBackend.MERCHANT_ID_BATCH_TABLE_NAME+countryCode; String whereClause = "status = '"+DbConstantsBackend.BATCH_STATUS_OPEN +"'"; MerchantIdBatches batch = BackendOps.fetchMerchantIdBatch(batchTableName,whereClause); if(batch == null) { throw new BackendlessException(String.valueOf(ErrorCodes.MERCHANT_ID_RANGE_ERROR), "No open merchant id batch available: "+batchTableName+","+whereClause); } // get merchant counter value and use the same to generate merchant id Long merchantCnt = BackendOps.fetchCounterValue(DbConstantsBackend.MERCHANT_ID_COUNTER); mLogger.debug("Fetched merchant cnt: "+merchantCnt); // set merchant id merchantId = BackendUtils.generateMerchantId(batch, countryCode, merchantCnt); mLogger.debug("Generated merchant id: "+merchantId); merchant.setAuto_id(merchantId); merchant.setAdmin_status(DbConstants.USER_STATUS_ACTIVE); merchant.setStatus_reason(DbConstantsBackend.ENABLED_ACTIVE); merchant.setStatus_update_time(new Date()); merchant.setLastRenewDate(new Date()); //merchant.setAdmin_remarks("New registered merchant"); merchant.setMobile_num(merchant.getMobile_num()); merchant.setFirst_login_ok(false); merchant.setAgentId(agent.getId()); // set cashback and transaction table names //setCbAndTransTables(merchant, merchantCnt); merchant.setCashback_table(DbConstantsBackend.CASHBACK_TABLE_NAME + city.getCbTableCode()); BackendOps.describeTable(merchant.getCashback_table()); // just to check that the table exists merchant.setTxn_table(DbConstantsBackend.TRANSACTION_TABLE_NAME + city.getCbTableCode()); BackendOps.describeTable(merchant.getTxn_table()); // just to check that the table exists // generate and set password String pwd = BackendUtils.generateTempPassword(); mLogger.debug("Generated passwd: "+pwd); BackendlessUser user = new BackendlessUser(); user.setProperty("user_id", merchantId); user.setPassword(pwd); user.setProperty("user_type", DbConstants.USER_TYPE_MERCHANT); user.setProperty("merchant", merchant); user = BackendOps.registerUser(user); // register successfull - can write to edr now mEdr[BackendConstants.EDR_MCHNT_ID_IDX] = merchant.getAuto_id(); try { BackendOps.assignRole(merchantId, BackendConstants.ROLE_MERCHANT); } catch(Exception e) { mLogger.fatal("Failed to assign role to merchant user: "+merchantId+","+e.toString()); rollbackRegister(merchantId); throw e; } // create directories for 'txnCsv' and 'txnImage' files String fileDir = null; String filePath = null; try { fileDir = CommonUtils.getMerchantTxnDir(merchantId); filePath = fileDir + CommonConstants.FILE_PATH_SEPERATOR+BackendConstants.DUMMY_FILENAME; // saving dummy files to create parent directories Backendless.Files.saveFile(filePath, BackendConstants.DUMMY_DATA.getBytes("UTF-8"), true); // Give this merchant permissions for this directory FilePermission.READ.grantForUser( user.getObjectId(), fileDir); FilePermission.DELETE.grantForUser( user.getObjectId(), fileDir); FilePermission.WRITE.grantForUser( user.getObjectId(), fileDir); mLogger.debug("Saved dummy txn csv file: " + filePath); fileDir = CommonUtils.getTxnImgDir(merchantId); filePath = fileDir + CommonConstants.FILE_PATH_SEPERATOR+BackendConstants.DUMMY_FILENAME; Backendless.Files.saveFile(filePath, BackendConstants.DUMMY_DATA.getBytes("UTF-8"), true); // Give read access to this merchant to this directory FilePermission.WRITE.grantForUser( user.getObjectId(), fileDir); mLogger.debug("Saved dummy txn image file: " + filePath); } catch(Exception e) { mLogger.fatal("Failed to create merchant directories: "+merchantId+","+e.toString()); rollbackRegister(merchantId); throw new BackendlessException(String.valueOf(ErrorCodes.GENERAL_ERROR), e.toString()); } // send SMS with user id String smsText = String.format(SmsConstants.SMS_MERCHANT_ID_FIRST, merchantId); SmsHelper.sendSMS(smsText, merchant.getMobile_num(), mEdr, mLogger); // no exception - means function execution success mEdr[BackendConstants.EDR_RESULT_IDX] = BackendConstants.BACKEND_EDR_RESULT_OK; return merchantId; } catch(Exception e) { BackendUtils.handleException(e,false,mLogger,mEdr); if(merchantId!=null && !merchantId.isEmpty()) { BackendOps.decrementCounterValue(DbConstantsBackend.MERCHANT_ID_COUNTER); } throw e; } finally { BackendUtils.finalHandling(startTime,mLogger,mEdr); } } public void disableMerchant(String merchantId, String ticketNum, String reason, String remarks) { BackendUtils.initAll(); long startTime = System.currentTimeMillis(); mEdr[BackendConstants.EDR_START_TIME_IDX] = String.valueOf(startTime); mEdr[BackendConstants.EDR_API_NAME_IDX] = "disableMerchant"; mEdr[BackendConstants.EDR_API_PARAMS_IDX] = merchantId+BackendConstants.BACKEND_EDR_SUB_DELIMETER+ ticketNum+BackendConstants.BACKEND_EDR_SUB_DELIMETER+ reason; try { // Fetch customer care user InternalUser internalUser = (InternalUser) BackendUtils.fetchCurrentUser(InvocationContext.getUserId(), null, mEdr, mLogger, false); int userType = Integer.parseInt(mEdr[BackendConstants.EDR_USER_TYPE_IDX]); if( userType!=DbConstants.USER_TYPE_CC && userType!=DbConstants.USER_TYPE_CNT ) { throw new BackendlessException(String.valueOf(ErrorCodes.OPERATION_NOT_ALLOWED), "Operation not allowed to this user"); } // Fetch merchant Merchants merchant = BackendOps.getMerchant(merchantId, false, false); // Add merchant op first - then update status MerchantOps op = new MerchantOps(); op.setCreateTime(new Date()); op.setMerchant_id(merchant.getAuto_id()); op.setMobile_num(merchant.getMobile_num()); op.setOp_code(DbConstants.OP_DISABLE_ACC); op.setOp_status(DbConstantsBackend.USER_OP_STATUS_COMPLETE); op.setTicketNum(ticketNum); op.setReason(reason); op.setRemarks(remarks); op.setAgentId(internalUser.getId()); op.setInitiatedBy( (userType==DbConstants.USER_TYPE_CC)? DbConstantsBackend.USER_OP_INITBY_MCHNT : DbConstantsBackend.USER_OP_INITBY_ADMIN); if(userType==DbConstants.USER_TYPE_CC) { op.setInitiatedVia(DbConstantsBackend.USER_OP_INITVIA_CC); } op = BackendOps.saveMerchantOp(op); // Update status try { BackendUtils.setMerchantStatus(merchant, DbConstants.USER_STATUS_DISABLED, reason, mEdr, mLogger); /*merchant.setAdmin_status(DbConstants.USER_STATUS_DISABLED); merchant.setStatus_update_time(new Date()); merchant.setStatus_reason(reason); merchant = BackendOps.updateMerchant(merchant);*/ } catch(Exception e) { mLogger.error("disableMerchant: Exception while updating merchant status: "+merchantId); // Rollback - delete merchant op added try { BackendOps.deleteMerchantOp(op); } catch(Exception ex) { mLogger.fatal("disableMerchant: Failed to rollback: merchant op deletion failed: "+merchantId); // Rollback also failed mEdr[BackendConstants.EDR_SPECIAL_FLAG_IDX] = BackendConstants.BACKEND_EDR_MANUAL_CHECK; throw ex; } throw e; } // send SMS with user id String smsText = String.format(SmsConstants.SMS_ACCOUNT_DISABLE, BackendUtils.getHalfVisibleId(merchantId)); SmsHelper.sendSMS(smsText, merchant.getMobile_num(), mEdr, mLogger); // no exception - means function execution success mEdr[BackendConstants.EDR_RESULT_IDX] = BackendConstants.BACKEND_EDR_RESULT_OK; } catch(Exception e) { BackendUtils.handleException(e,false,mLogger,mEdr); throw e; } finally { BackendUtils.finalHandling(startTime,mLogger,mEdr); } } /* * Private helper methods */ /* private void setCbAndTransTables(Merchants merchant, long regCounter) { // decide on the cashback table using round robin int pool_size = BackendConstants.CASHBACK_TABLE_POOL_SIZE; int pool_start = BackendConstants.CASHBACK_TABLE_POOL_START; // use last 4 numeric digits for round-robin int table_suffix = pool_start + ((int)(regCounter % pool_size)); String cbTableName = DbConstantsBackend.CASHBACK_TABLE_NAME + String.valueOf(table_suffix); merchant.setCashback_table(cbTableName); mLogger.debug("Generated cashback table name:" + cbTableName); // use the same prefix for cashback and transaction tables // as there is 1-to-1 mapping in the table schema - transaction0 maps to cashback0 only String transTableName = DbConstantsBackend.TRANSACTION_TABLE_NAME + String.valueOf(table_suffix); merchant.setTxn_table(transTableName); mLogger.debug("Generated transaction table name:" + transTableName); }*/ // private void rollbackRegister(BackendlessUser user) { private void rollbackRegister(String mchntId) { // TODO: add as 'Major' alarm - user to be removed later manually // rollback to not-usable state mEdr[BackendConstants.EDR_SPECIAL_FLAG_IDX] = BackendConstants.BACKEND_EDR_MANUAL_CHECK; try { Merchants merchant = BackendOps.getMerchant(mchntId, false, false); BackendUtils.setMerchantStatus(merchant, DbConstants.USER_STATUS_REG_ERROR, DbConstantsBackend.REG_ERROR_REG_FAILED, mEdr, mLogger); /*merchant.setAdmin_status(DbConstants.USER_STATUS_REG_ERROR); merchant.setStatus_reason(DbConstantsBackend.REG_ERROR_REG_FAILED); BackendOps.updateMerchant(merchant);*/ } catch(Exception ex) { mLogger.fatal("registerMerchant: Merchant Rollback failed: "+ex.toString()); mLogger.error(BackendUtils.stackTraceStr(ex)); mEdr[BackendConstants.EDR_SPECIAL_FLAG_IDX] = BackendConstants.BACKEND_EDR_MANUAL_CHECK; throw ex; } } }
13,798
0.644514
0.643427
281
48.099644
33.760365
135
false
false
0
0
0
0
0
0
0.768683
false
false
10
21386822c41a5598f29be05ee7a63bf9fb6ae71a
1,898,375,611,504
f1999a6a883283403c7c91d0190a1c55cd7011ce
/src/main/java/com/zhangwenit/mybatis/spring/demo/Test.java
16f3f9ce1588c6d67145467c63c99e1551dce824
[]
no_license
gudanrenao/mybatis-spring-demo
https://github.com/gudanrenao/mybatis-spring-demo
3e770a4d90e567128fd897c9a31a6e8dd5b5584a
0aeb5088ed08af5bc209d59dfc77c69a10b63663
refs/heads/master
2020-05-16T03:23:05.806000
2019-04-22T09:04:32
2019-04-22T09:04:32
182,698,399
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.zhangwenit.mybatis.spring.demo; import com.zhangwenit.mybatis.spring.demo.mapper.PersonMapper; import com.zhangwenit.mybatis.spring.demo.model.Person; import com.zhangwenit.mybatis.spring.demo.service.PersonService; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.transaction.TransactionStatus; import org.springframework.transaction.support.DefaultTransactionDefinition; import org.springframework.transaction.support.TransactionTemplate; /** * @Description * @Author ZWen * @Date 2019/4/22 11:01 AM * @Version 1.0 **/ public class Test { public static void main(String[] args) { // selectById(); // transactionTemplate(); // transactionStatus(); selectUseSqlTemplate(); } private static ClassPathXmlApplicationContext applicationContext(){ ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("ApplicationContext.xml"); return applicationContext; } public static void transactionStatus() { ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("ApplicationContext.xml"); DataSourceTransactionManager transactionManager = applicationContext.getBean(DataSourceTransactionManager.class); TransactionStatus transactionStatus = transactionManager.getTransaction(new DefaultTransactionDefinition()); PersonMapper personMapper = applicationContext.getBean(PersonMapper.class); try { personMapper.updatePersonUseSet(new Person(1L, 2, "2transactionStatus")); if (true) { throw new RuntimeException("rollback test"); } } catch (Exception e) { transactionManager.rollback(transactionStatus); throw e; } transactionManager.commit(transactionStatus); } public static void transactionTemplate() { ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("ApplicationContext.xml"); DataSourceTransactionManager transactionManager = applicationContext.getBean(DataSourceTransactionManager.class); TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager); Object personMapper = applicationContext.getBean("personMapper"); PersonService personService = new PersonService((PersonMapper) personMapper); Object execute = transactionTemplate.execute(txStatus -> { return personService.getById(1L); }); System.out.println(execute); } public static void selectById() { ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("ApplicationContext.xml"); PersonService personService = applicationContext.getBean(PersonService.class); personService.getById(1L); } public static void selectUseSqlTemplate(){ PersonService personService = applicationContext().getBean(PersonService.class); personService.useSqlSessionTemplateExecuteSql(); } }
UTF-8
Java
3,172
java
Test.java
Java
[ { "context": "ansactionTemplate;\n\n/**\n * @Description\n * @Author ZWen\n * @Date 2019/4/22 11:01 AM\n * @Version 1.0\n **/\n", "end": 616, "score": 0.9038910865783691, "start": 612, "tag": "USERNAME", "value": "ZWen" } ]
null
[]
package com.zhangwenit.mybatis.spring.demo; import com.zhangwenit.mybatis.spring.demo.mapper.PersonMapper; import com.zhangwenit.mybatis.spring.demo.model.Person; import com.zhangwenit.mybatis.spring.demo.service.PersonService; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.transaction.TransactionStatus; import org.springframework.transaction.support.DefaultTransactionDefinition; import org.springframework.transaction.support.TransactionTemplate; /** * @Description * @Author ZWen * @Date 2019/4/22 11:01 AM * @Version 1.0 **/ public class Test { public static void main(String[] args) { // selectById(); // transactionTemplate(); // transactionStatus(); selectUseSqlTemplate(); } private static ClassPathXmlApplicationContext applicationContext(){ ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("ApplicationContext.xml"); return applicationContext; } public static void transactionStatus() { ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("ApplicationContext.xml"); DataSourceTransactionManager transactionManager = applicationContext.getBean(DataSourceTransactionManager.class); TransactionStatus transactionStatus = transactionManager.getTransaction(new DefaultTransactionDefinition()); PersonMapper personMapper = applicationContext.getBean(PersonMapper.class); try { personMapper.updatePersonUseSet(new Person(1L, 2, "2transactionStatus")); if (true) { throw new RuntimeException("rollback test"); } } catch (Exception e) { transactionManager.rollback(transactionStatus); throw e; } transactionManager.commit(transactionStatus); } public static void transactionTemplate() { ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("ApplicationContext.xml"); DataSourceTransactionManager transactionManager = applicationContext.getBean(DataSourceTransactionManager.class); TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager); Object personMapper = applicationContext.getBean("personMapper"); PersonService personService = new PersonService((PersonMapper) personMapper); Object execute = transactionTemplate.execute(txStatus -> { return personService.getById(1L); }); System.out.println(execute); } public static void selectById() { ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("ApplicationContext.xml"); PersonService personService = applicationContext.getBean(PersonService.class); personService.getById(1L); } public static void selectUseSqlTemplate(){ PersonService personService = applicationContext().getBean(PersonService.class); personService.useSqlSessionTemplateExecuteSql(); } }
3,172
0.748424
0.742749
71
43.69014
37.288593
121
false
false
0
0
0
0
0
0
0.549296
false
false
10
aeb9aff22f155768d2f59272fb58b0e4586bf8ca
38,886,633,931,750
649c79c92ee23148912a37917cf739f7d79d10a8
/app/src/main/java/me/lonny/deamon/ui/act/SelfActivity.java
872ef511cb9c603d86c9a2adc04067a58564c848
[]
no_license
lonnyzhang423/deamon
https://github.com/lonnyzhang423/deamon
151af37cead0c5bf64b56038af69ff8e7e9ae397
3917dc8bded0a8fe09807200ec988545a9529cad
refs/heads/master
2018-07-29T14:40:12.534000
2018-07-19T16:03:43
2018-07-19T16:03:43
132,624,751
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package me.lonny.deamon.ui.act; import android.os.Bundle; import android.support.annotation.Nullable; import me.lonny.deamon.R; import me.lonny.deamon.ui.base.BaseActivity; import me.lonny.deamon.ui.fragment.SelfFragment; import me.lonny.deamon.utils.FragmentUtils; /** * User profile * Created by lonny on 2018/5/28. */ public class SelfActivity extends BaseActivity { @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_container); if (savedInstanceState == null) { FragmentUtils.add(SelfFragment.newInstance(), this, R.id.fl_container, SelfFragment.TAG); } } }
UTF-8
Java
720
java
SelfActivity.java
Java
[ { "context": ".FragmentUtils;\n\n/**\n * User profile\n * Created by lonny on 2018/5/28.\n */\npublic class SelfActivity exten", "end": 308, "score": 0.9995436668395996, "start": 303, "tag": "USERNAME", "value": "lonny" } ]
null
[]
package me.lonny.deamon.ui.act; import android.os.Bundle; import android.support.annotation.Nullable; import me.lonny.deamon.R; import me.lonny.deamon.ui.base.BaseActivity; import me.lonny.deamon.ui.fragment.SelfFragment; import me.lonny.deamon.utils.FragmentUtils; /** * User profile * Created by lonny on 2018/5/28. */ public class SelfActivity extends BaseActivity { @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_container); if (savedInstanceState == null) { FragmentUtils.add(SelfFragment.newInstance(), this, R.id.fl_container, SelfFragment.TAG); } } }
720
0.723611
0.713889
28
24.714285
25.177736
101
false
false
0
0
0
0
0
0
0.464286
false
false
10
0752b4da7f5d4d072bf6f66d2e1cdbc183712142
37,254,546,352,452
731f3fd82e35d0a81539ffddf7a7f13d3c2a7b13
/BattleshipGame/Project Files(Intellij)/src/GridContent.java
610914288d90c978bf5dd772aa55de141b550d97
[]
no_license
thepickpocket/Networks_COS332
https://github.com/thepickpocket/Networks_COS332
a84d63c19061ac4d5d16613dc4869823cb4b12d5
a814dad63a690377fb1b368103dd238a832f315a
refs/heads/master
2016-08-04T14:47:07.505000
2015-05-25T19:57:50
2015-05-25T19:57:50
31,319,962
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.util.HashMap; /** * Vivian Venter (13238435) & Jason Evans (13032608) * COS 332 - Practical 9 * Battleship Game * Collaboration */ public class GridContent { private String[] ranking = new String[] {"Leutenant", "Commander", "Captain", "Admiral"}; private HashMap<Integer, Character> map_Indexes; private String tableBoatInfoContent = ""; private static BattleShip game = null; public GridContent(BattleShip battleShip) { System.out.println("GridContent Initialized"); game = battleShip; map_Indexes = new HashMap(); map_Indexes.put(0,'A'); map_Indexes.put(1,'B'); map_Indexes.put(2,'C'); map_Indexes.put(3,'D'); map_Indexes.put(4,'E'); map_Indexes.put(5,'F'); map_Indexes.put(6,'G'); map_Indexes.put(7,'H'); map_Indexes.put(8,'I'); map_Indexes.put(9,'J'); } public String constructGridContent(char[][] grid, int size) { String content; if (game.hasWon) content = getGameFileHeader() + getWinner() + getGameFileFooter(); else content = getGameFileHeader() + getGridContent(grid, size) + getStatsContent() + getTableBoatInfoContent() + getGameFileFooter(); game.hasWon = false; return content; } private String getGameFileHeader() { return "<!DOCTYPE html>\n" + "<html>\n" + "<head lang=\"en\">\n" + " <meta charset=\"UTF-8\">\n" + " <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n" + " <title>Battleship</title>\n" + "\n" + " <!--Stylesheets-->\n" + " <link rel=\"stylesheet\" href=\"Frameworks/Bootstrap/css/bootstrap.min.css\">\n" + " <link rel=\"stylesheet\" href=\"//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css\">\n" + "\n" + " <!--Javascript-->\n" + " <script src=\"Frameworks/jquery-1.11.3.min.js\"></script>\n" + " <script src=\"Frameworks/Bootstrap/js/bootstrap.min.js\"></script>\n" + " <script src=\"ShipInformation/animations.js\"></script>\n" + "\n" + "</head>\n" + "<body style=\"background-image: url('Images/WorldMap.jpg'); background-size: cover;\">\n" + "<nav class=\"navbar navbar-inverse\">\n" + " <div class=\"container-fluid\">\n" + " <div class=\"navbar-header\">\n" + " <a class=\"navbar-brand\" href=\"index.html\">\n" + " <img src=\"Images/BattleShipLogo.png\" class=\"img-rounded\" alt=\"Battleships\" width=\"145\">\n" + " </a>\n" + " </div>\n" + " <div>\n" + " <ul class=\"nav navbar-nav\">\n" + " <li class=\"active\"><a href=\"index.html\"><span class=\"glyphicon glyphicon-home\"></span> Home</a></li>\n" + " <li class=\"dropdown\"><a class=\"dropdown-toggle\" data-toggle=\"dropdown\" href=\"#\"><span class=\"glyphicon glyphicon-globe\"></span> Ship Information (Alpha)<span class=\"caret\"></span></a>\n" + " <ul class=\"dropdown-menu\">\n" + " <li><a href=\"ShipInformation/AircraftCarrier.html\">Aircraft Carrier</a></li>\n" + " <li><a href=\"ShipInformation/Battleship.html\">Battleship</a></li>\n" + " <li><a href=\"ShipInformation/Destroyer.html\">Destroyer</a></li>\n" + " <li><a href=\"ShipInformation/PatrolBoat.html\">Patrol Boat</a></li>\n" + " <li><a href=\"ShipInformation/Submarine.html\">Submarine</a></li>\n" + " </ul>\n" + " </li>\n" + " <li><a href=\"help.html\"><span class=\"glyphicon glyphicon-question-sign\"></span> Help</a></li>\n" + " <li><a href=\"about.html\"><span class=\"glyphicon glyphicon-info-sign\"></span> About Us</a></li>\n" + " </ul>\n" + " </div>\n" + " </div>\n" + "</nav>"; } private String getNotifications() { return "<div class=\"container-fluid text-center\" style=\"background-color: rgba(0,0,0,0.7)\">\n" + " <div id=\"notifications\">\n" + " <h2 style=\"color: white; text-shadow: 3px 1px 3px #09b6ff\"> Hi, "+game.getPlayerName()+"!</h2>\n" + game.GLOBAL_Notification+ " </div>\n" + "</div>\n"; } private String getGridContent(char[][] theGrid, int size) { String content = "<div class=\"container-fluid\">\n" + " <div class=\"row\">\n" + " <div class=\"col-md-8\" style=\"background-color: rgba(0,0,0,0.7); margin-top: 2.5%;\">\n" + " <table class=\"table\" style=\"color: white;\">\n" + " <thead>\n"; content += getColHeadings(size); content += " </thead>\n" + " <tbody>"; char colC; for (int i = 0; i < size; i++) { content += " <tr>\n"; content += " <td>" + i + "</td>\n"; if (size == 6) { for (int k = 0; k < size; k++) { colC = map_Indexes.get(k); if (theGrid[i][k] == '1') { content += " <td><button class=\"btn\" onclick=\"location.href = 'shoot=" + colC + i + "\"';\" formmethod=\"get\" id=\"" + colC + i + "\" disabled><i class=\"fa fa-ban fa-3x\"></i> </button></td>\n"; } else if (theGrid[i][k] == '2') { content += " <td><button class=\"btn\" onclick=\"location.href = 'shoot=" + colC + i + "';\" formmethod=\"get\" id=\"" + colC + i + "\" disabled><i class=\"fa fa-fire fa-3x\" style=\"color: red\"></i></button></td>\n"; } else { content += " <td><button class=\"btn\" onclick=\"location.href = 'shoot=" + colC + i + "';\" formmethod=\"get\" id=\"" + colC + i + "\"><i class=\"fa fa-map-marker fa-3x\" style=\"color: #269abc;\"></i></button></td>\n"; } } content += " </tr>\n"; } else if (size == 8){ for (int k = 0; k < size; k++) { colC = map_Indexes.get(k); if (theGrid[i][k] == '1') { content += " <td><button class=\"btn\" onclick=\"location.href = 'shoot=" + colC + i + "\"';\" formmethod=\"get\" id=\"" + colC + i + "\" disabled><i class=\"fa fa-ban fa-2x\"></i> </button></td>\n"; } else if (theGrid[i][k] == '2') { content += " <td><button class=\"btn\" onclick=\"location.href = 'shoot=" + colC + i + "';\" formmethod=\"get\" id=\"" + colC + i + "\" disabled><i class=\"fa fa-fire fa-2x\" style=\"color: red\"></i></button></td>\n"; } else { content += " <td><button class=\"btn\" onclick=\"location.href = 'shoot=" + colC + i + "';\" formmethod=\"get\" id=\"" + colC + i + "\"><i class=\"fa fa-map-marker fa-2x\" style=\"color: #269abc;\"></i></button></td>\n"; } } content += " </tr>\n"; } else{ for (int k = 0; k < size; k++) { colC = map_Indexes.get(k); if (theGrid[i][k] == '1') { content += " <td><button class=\"btn\" onclick=\"location.href = 'shoot=" + colC + i + "\"';\" formmethod=\"get\" id=\"" + colC + i + "\" disabled><i class=\"fa fa-ban\"></i> </button></td>\n"; } else if (theGrid[i][k] == '2') { content += " <td><button class=\"btn\" onclick=\"location.href = 'shoot=" + colC + i + "';\" formmethod=\"get\" id=\"" + colC + i + "\" disabled><i class=\"fa fa-fire\" style=\"color: red\"></i></button></td>\n"; } else { content += " <td><button class=\"btn\" onclick=\"location.href = 'shoot=" + colC + i + "';\" formmethod=\"get\" id=\"" + colC + i + "\"><i class=\"fa fa-map-marker\" style=\"color: #269abc;\"></i></button></td>\n"; } } content += " </tr>\n"; } } content += " </tbody>\n" + " </table>\n" + " </div>"; return content; } private String getColHeadings(int size) { String content = " <tr>\n" + " <th> </th>\n"; for (int p = 0; p < size; p++) { content += " <th>"+map_Indexes.get(p)+"</th>\n"; } content += " </tr>\n"; return content; } private String getStatsContent() { return "<div class=\"col-md-3 col-md-offset-1\" style=\"margin-top: 3%\">\n" + getNotifications() + "<div class=\"container-fluid\" style=\"background-color: rgba(0,0,0,0.7); margin-top: 7.5%;\">"+ " <h3 style=\"color: white\">Current Standings</h3>\n" + " <div class=\"container-fluid text-center\">\n" + " <p style=\"color: white;\" class=\"pull-left\"><b>Hits:</b></p><p id=\"Hits\" style=\"color: white;\" class=\"text-right\">"+game.getHits()+"</p>\n" + " <p style=\"color: white;\" class=\"pull-left\"><b>Miss:</b></p><p id=\"Miss\" style=\"color: white;\" class=\"text-right\">"+game.getMisses()+"</p>\n" + " <p style=\"color: white;\" class=\"pull-left\"><b>Total:</b></p><p id=\"Total\" style=\"color: white;\" class=\"text-right\">"+game.getTotalShots()+"</p>\n" + " <p style=\"color: white;\" class=\"pull-left\"><b>Accuracy:</b></p><p id=\"Accuracy\" style=\"color: white;\" class=\"text-right\">"+game.getAccuracy()+"</p>\n" + " </div>"; } private String getGameFileFooter() { return "</body>\n" + "</html>"; } public String getTableBoatInfoContent() { return tableBoatInfoContent; } public void setTableBoatInfoContent(String tableBoatInfoContent) { this.tableBoatInfoContent = tableBoatInfoContent; } public void setTableBoatInfoContent6() { String lineA = " <tr>\n"; String lineB = " <tr>\n"; String lineC = " <tr>\n"; setTableBoatInfoContent( "<div class=\"text-center\">"+ "<table class=\"table\" style=\"color: white;\">\n" + " <thead>\n" + " <tr>\n" + " <th>Boat Name</th>\n" + " <th>Length</th>\n" + " <th>Destroyed</th>\n" + " </tr>\n" + " </thead>\n" + " <tbody>\n" + lineA + " <td>Aircraft Carrier</td>\n" + " <td>5</td>\n" + " <td id=\"AircraftDestroyed\">" + game.getNumberofA() + " </td>\n" + " </tr>" + lineB + " <td>Battleship</td>\n" + " <td>2</td>\n" + " <td id=\"BattleshipDestroyed\">" + game.getNumberofB() + " </td>\n" + " </tr>" + lineC + " <td>Destroyer</td>\n" + " <td>6</td>\n" + " <td id=\"DestroyerDestroyed\">" + game.getNumberofC() + " </td>\n" + " </tr>" + " </tbody>\n" + " </table></div></div></div>"); game.counter++; } public void setTableBoatInfoContent8() { setTableBoatInfoContent( "<div class=\"text-center\">" + "<table class=\"table\" style=\"color: white;\">\n" + " <thead>\n" + " <tr>\n" + " <th>Boat Name</th>\n" + " <th>Length</th>\n" + " <th>Destroyed</th>\n" + " </tr>\n" + " </thead>\n" + " <tbody>\n" + " <tr>\n" + " <td>Aircraft Carrier</td>\n" + " <td>5</td>\n" + " <td id=\"AircraftDestroyed\">" + game.getNumberofA() + " </td>\n" + " </tr>" + " <tr>\n" + " <td>Battleship</td>\n" + " <td>2</td>\n" + " <td id=\"BattleshipDestroyed\">" + game.getNumberofB() + " </td>\n" + " </tr>" + " <tr>\n" + " <td>Destroyer</td>\n" + " <td>6</td>\n" + " <td id=\"DestroyerDestroyed\">" + game.getNumberofC() + " </td>\n" + " </tr>" + " <tr>\n" + " <td>Patrol Boat</td>\n" + " <td>7</td>\n" + " <td id=\"PatrolDestroyed\">" + game.getNumberofD() + " </td>\n" + " </tr>"+ " </tbody>\n" + " </table></div></div></div>"); } public void setTableBoatInfoContent10() { setTableBoatInfoContent( "<div class=\"text-center\">" + "<table class=\"table\" style=\"color: white;\">\n" + " <thead>\n" + " <tr>\n" + " <th>Boat Name</th>\n" + " <th>Length</th>\n" + " <th>Destroyed</th>\n" + " </tr>\n" + " </thead>\n" + " <tbody>\n" + " <tr>\n" + " <td>Aircraft Carrier</td>\n" + " <td>5</td>\n" + " <td id=\"AircraftDestroyed\">" + game.getNumberofA() + " </td>\n" + " </tr>" + " <tr>\n" + " <td>Battleship</td>\n" + " <td>2</td>\n" + " <td id=\"BattleshipDestroyed\">" + game.getNumberofB() + " </td>\n" + " </tr>" + " <tr>\n" + " <td>Destroyer</td>\n" + " <td>6</td>\n" + " <td id=\"DestroyerDestroyed\">" + game.getNumberofC() + " </td>\n" + " </tr>" + " <tr>\n" + " <td>Patrol Boat</td>\n" + " <td>7</td>\n" + " <td id=\"PatrolDestroyed\">" + game.getNumberofD() + " </td>\n" + " </tr>"+ " <tr>\n" + " <td>Submarine</td>\n" + " <td>9</td>\n" + " <td id=\"SubmarineDestroyed\">" + game.getNumberofE() + " </td>\n" + " </tr>\n" + " </tbody>\n" + " </table></div></div></div>"); } private String getWinner(){ String currentRanking = ""; if (game.getAccuracy() >= 80) currentRanking = ranking[3]; else if (game.getAccuracy() >= 60) currentRanking = ranking[2]; else if (game.getAccuracy() >= 40) currentRanking = ranking[1]; else currentRanking = ranking[0]; return "<div class=\"container-fluid\" id=\"Text\" hidden>" + " <div class=\"row\">" + " <div class=\"col-md-4\"></div>" + " <div class=\"col-md-4 text-center\" style=\"background-color: rgba(0,0,0, 0.7); margin-top: 12%;\">" + " <h1 style=\"color: white; text-shadow: 3px 1px 3px #09b6ff;\">Congratulations <br />"+ currentRanking + " " + game.getPlayerName() + "</h1>" + " <p style=\"color: white;\">You have overthrown the enemy and the sea is now yours. Go forth and attack more ships and make even more of the ocean yours. Keep on going like this and you will be noted in history as the best battleship " + currentRanking +".</p>" + " <i class=\"fa fa-ship fa-5x\" style=\"color:white;\"></i><br /><br />" + " <a href=\"index.html\"><button class='btn btn-default'>New Game</button></a>" + " </div>" + " <div class=\"col-md-4\"></div>" + "</div>"; } }
UTF-8
Java
20,327
java
GridContent.java
Java
[ { "context": "import java.util.HashMap;\n\n/**\n * Vivian Venter (13238435) & Jason Evans (13032608)\n * COS 332 - ", "end": 47, "score": 0.999839186668396, "start": 34, "tag": "NAME", "value": "Vivian Venter" }, { "context": "a.util.HashMap;\n\n/**\n * Vivian Venter (13238435) & Jason Evans (13032608)\n * COS 332 - Practical 9\n * Battleship", "end": 72, "score": 0.9998326301574707, "start": 61, "tag": "NAME", "value": "Jason Evans" }, { "context": " {\n\n private String[] ranking = new String[] {\"Leutenant\", \"Commander\", \"Captain\", \"Admiral\"};\n private", "end": 232, "score": 0.8801173567771912, "start": 223, "tag": "NAME", "value": "Leutenant" }, { "context": "te String[] ranking = new String[] {\"Leutenant\", \"Commander\", \"Captain\", \"Admiral\"};\n private HashMap<Inte", "end": 245, "score": 0.9772114753723145, "start": 236, "tag": "NAME", "value": "Commander" }, { "context": "anking = new String[] {\"Leutenant\", \"Commander\", \"Captain\", \"Admiral\"};\n private HashMap<Integer, Charac", "end": 256, "score": 0.632591724395752, "start": 249, "tag": "NAME", "value": "Captain" }, { "context": "String[] {\"Leutenant\", \"Commander\", \"Captain\", \"Admiral\"};\n private HashMap<Integer, Character> map_In", "end": 267, "score": 0.5817400217056274, "start": 262, "tag": "NAME", "value": "miral" } ]
null
[]
import java.util.HashMap; /** * <NAME> (13238435) & <NAME> (13032608) * COS 332 - Practical 9 * Battleship Game * Collaboration */ public class GridContent { private String[] ranking = new String[] {"Leutenant", "Commander", "Captain", "Admiral"}; private HashMap<Integer, Character> map_Indexes; private String tableBoatInfoContent = ""; private static BattleShip game = null; public GridContent(BattleShip battleShip) { System.out.println("GridContent Initialized"); game = battleShip; map_Indexes = new HashMap(); map_Indexes.put(0,'A'); map_Indexes.put(1,'B'); map_Indexes.put(2,'C'); map_Indexes.put(3,'D'); map_Indexes.put(4,'E'); map_Indexes.put(5,'F'); map_Indexes.put(6,'G'); map_Indexes.put(7,'H'); map_Indexes.put(8,'I'); map_Indexes.put(9,'J'); } public String constructGridContent(char[][] grid, int size) { String content; if (game.hasWon) content = getGameFileHeader() + getWinner() + getGameFileFooter(); else content = getGameFileHeader() + getGridContent(grid, size) + getStatsContent() + getTableBoatInfoContent() + getGameFileFooter(); game.hasWon = false; return content; } private String getGameFileHeader() { return "<!DOCTYPE html>\n" + "<html>\n" + "<head lang=\"en\">\n" + " <meta charset=\"UTF-8\">\n" + " <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n" + " <title>Battleship</title>\n" + "\n" + " <!--Stylesheets-->\n" + " <link rel=\"stylesheet\" href=\"Frameworks/Bootstrap/css/bootstrap.min.css\">\n" + " <link rel=\"stylesheet\" href=\"//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css\">\n" + "\n" + " <!--Javascript-->\n" + " <script src=\"Frameworks/jquery-1.11.3.min.js\"></script>\n" + " <script src=\"Frameworks/Bootstrap/js/bootstrap.min.js\"></script>\n" + " <script src=\"ShipInformation/animations.js\"></script>\n" + "\n" + "</head>\n" + "<body style=\"background-image: url('Images/WorldMap.jpg'); background-size: cover;\">\n" + "<nav class=\"navbar navbar-inverse\">\n" + " <div class=\"container-fluid\">\n" + " <div class=\"navbar-header\">\n" + " <a class=\"navbar-brand\" href=\"index.html\">\n" + " <img src=\"Images/BattleShipLogo.png\" class=\"img-rounded\" alt=\"Battleships\" width=\"145\">\n" + " </a>\n" + " </div>\n" + " <div>\n" + " <ul class=\"nav navbar-nav\">\n" + " <li class=\"active\"><a href=\"index.html\"><span class=\"glyphicon glyphicon-home\"></span> Home</a></li>\n" + " <li class=\"dropdown\"><a class=\"dropdown-toggle\" data-toggle=\"dropdown\" href=\"#\"><span class=\"glyphicon glyphicon-globe\"></span> Ship Information (Alpha)<span class=\"caret\"></span></a>\n" + " <ul class=\"dropdown-menu\">\n" + " <li><a href=\"ShipInformation/AircraftCarrier.html\">Aircraft Carrier</a></li>\n" + " <li><a href=\"ShipInformation/Battleship.html\">Battleship</a></li>\n" + " <li><a href=\"ShipInformation/Destroyer.html\">Destroyer</a></li>\n" + " <li><a href=\"ShipInformation/PatrolBoat.html\">Patrol Boat</a></li>\n" + " <li><a href=\"ShipInformation/Submarine.html\">Submarine</a></li>\n" + " </ul>\n" + " </li>\n" + " <li><a href=\"help.html\"><span class=\"glyphicon glyphicon-question-sign\"></span> Help</a></li>\n" + " <li><a href=\"about.html\"><span class=\"glyphicon glyphicon-info-sign\"></span> About Us</a></li>\n" + " </ul>\n" + " </div>\n" + " </div>\n" + "</nav>"; } private String getNotifications() { return "<div class=\"container-fluid text-center\" style=\"background-color: rgba(0,0,0,0.7)\">\n" + " <div id=\"notifications\">\n" + " <h2 style=\"color: white; text-shadow: 3px 1px 3px #09b6ff\"> Hi, "+game.getPlayerName()+"!</h2>\n" + game.GLOBAL_Notification+ " </div>\n" + "</div>\n"; } private String getGridContent(char[][] theGrid, int size) { String content = "<div class=\"container-fluid\">\n" + " <div class=\"row\">\n" + " <div class=\"col-md-8\" style=\"background-color: rgba(0,0,0,0.7); margin-top: 2.5%;\">\n" + " <table class=\"table\" style=\"color: white;\">\n" + " <thead>\n"; content += getColHeadings(size); content += " </thead>\n" + " <tbody>"; char colC; for (int i = 0; i < size; i++) { content += " <tr>\n"; content += " <td>" + i + "</td>\n"; if (size == 6) { for (int k = 0; k < size; k++) { colC = map_Indexes.get(k); if (theGrid[i][k] == '1') { content += " <td><button class=\"btn\" onclick=\"location.href = 'shoot=" + colC + i + "\"';\" formmethod=\"get\" id=\"" + colC + i + "\" disabled><i class=\"fa fa-ban fa-3x\"></i> </button></td>\n"; } else if (theGrid[i][k] == '2') { content += " <td><button class=\"btn\" onclick=\"location.href = 'shoot=" + colC + i + "';\" formmethod=\"get\" id=\"" + colC + i + "\" disabled><i class=\"fa fa-fire fa-3x\" style=\"color: red\"></i></button></td>\n"; } else { content += " <td><button class=\"btn\" onclick=\"location.href = 'shoot=" + colC + i + "';\" formmethod=\"get\" id=\"" + colC + i + "\"><i class=\"fa fa-map-marker fa-3x\" style=\"color: #269abc;\"></i></button></td>\n"; } } content += " </tr>\n"; } else if (size == 8){ for (int k = 0; k < size; k++) { colC = map_Indexes.get(k); if (theGrid[i][k] == '1') { content += " <td><button class=\"btn\" onclick=\"location.href = 'shoot=" + colC + i + "\"';\" formmethod=\"get\" id=\"" + colC + i + "\" disabled><i class=\"fa fa-ban fa-2x\"></i> </button></td>\n"; } else if (theGrid[i][k] == '2') { content += " <td><button class=\"btn\" onclick=\"location.href = 'shoot=" + colC + i + "';\" formmethod=\"get\" id=\"" + colC + i + "\" disabled><i class=\"fa fa-fire fa-2x\" style=\"color: red\"></i></button></td>\n"; } else { content += " <td><button class=\"btn\" onclick=\"location.href = 'shoot=" + colC + i + "';\" formmethod=\"get\" id=\"" + colC + i + "\"><i class=\"fa fa-map-marker fa-2x\" style=\"color: #269abc;\"></i></button></td>\n"; } } content += " </tr>\n"; } else{ for (int k = 0; k < size; k++) { colC = map_Indexes.get(k); if (theGrid[i][k] == '1') { content += " <td><button class=\"btn\" onclick=\"location.href = 'shoot=" + colC + i + "\"';\" formmethod=\"get\" id=\"" + colC + i + "\" disabled><i class=\"fa fa-ban\"></i> </button></td>\n"; } else if (theGrid[i][k] == '2') { content += " <td><button class=\"btn\" onclick=\"location.href = 'shoot=" + colC + i + "';\" formmethod=\"get\" id=\"" + colC + i + "\" disabled><i class=\"fa fa-fire\" style=\"color: red\"></i></button></td>\n"; } else { content += " <td><button class=\"btn\" onclick=\"location.href = 'shoot=" + colC + i + "';\" formmethod=\"get\" id=\"" + colC + i + "\"><i class=\"fa fa-map-marker\" style=\"color: #269abc;\"></i></button></td>\n"; } } content += " </tr>\n"; } } content += " </tbody>\n" + " </table>\n" + " </div>"; return content; } private String getColHeadings(int size) { String content = " <tr>\n" + " <th> </th>\n"; for (int p = 0; p < size; p++) { content += " <th>"+map_Indexes.get(p)+"</th>\n"; } content += " </tr>\n"; return content; } private String getStatsContent() { return "<div class=\"col-md-3 col-md-offset-1\" style=\"margin-top: 3%\">\n" + getNotifications() + "<div class=\"container-fluid\" style=\"background-color: rgba(0,0,0,0.7); margin-top: 7.5%;\">"+ " <h3 style=\"color: white\">Current Standings</h3>\n" + " <div class=\"container-fluid text-center\">\n" + " <p style=\"color: white;\" class=\"pull-left\"><b>Hits:</b></p><p id=\"Hits\" style=\"color: white;\" class=\"text-right\">"+game.getHits()+"</p>\n" + " <p style=\"color: white;\" class=\"pull-left\"><b>Miss:</b></p><p id=\"Miss\" style=\"color: white;\" class=\"text-right\">"+game.getMisses()+"</p>\n" + " <p style=\"color: white;\" class=\"pull-left\"><b>Total:</b></p><p id=\"Total\" style=\"color: white;\" class=\"text-right\">"+game.getTotalShots()+"</p>\n" + " <p style=\"color: white;\" class=\"pull-left\"><b>Accuracy:</b></p><p id=\"Accuracy\" style=\"color: white;\" class=\"text-right\">"+game.getAccuracy()+"</p>\n" + " </div>"; } private String getGameFileFooter() { return "</body>\n" + "</html>"; } public String getTableBoatInfoContent() { return tableBoatInfoContent; } public void setTableBoatInfoContent(String tableBoatInfoContent) { this.tableBoatInfoContent = tableBoatInfoContent; } public void setTableBoatInfoContent6() { String lineA = " <tr>\n"; String lineB = " <tr>\n"; String lineC = " <tr>\n"; setTableBoatInfoContent( "<div class=\"text-center\">"+ "<table class=\"table\" style=\"color: white;\">\n" + " <thead>\n" + " <tr>\n" + " <th>Boat Name</th>\n" + " <th>Length</th>\n" + " <th>Destroyed</th>\n" + " </tr>\n" + " </thead>\n" + " <tbody>\n" + lineA + " <td>Aircraft Carrier</td>\n" + " <td>5</td>\n" + " <td id=\"AircraftDestroyed\">" + game.getNumberofA() + " </td>\n" + " </tr>" + lineB + " <td>Battleship</td>\n" + " <td>2</td>\n" + " <td id=\"BattleshipDestroyed\">" + game.getNumberofB() + " </td>\n" + " </tr>" + lineC + " <td>Destroyer</td>\n" + " <td>6</td>\n" + " <td id=\"DestroyerDestroyed\">" + game.getNumberofC() + " </td>\n" + " </tr>" + " </tbody>\n" + " </table></div></div></div>"); game.counter++; } public void setTableBoatInfoContent8() { setTableBoatInfoContent( "<div class=\"text-center\">" + "<table class=\"table\" style=\"color: white;\">\n" + " <thead>\n" + " <tr>\n" + " <th>Boat Name</th>\n" + " <th>Length</th>\n" + " <th>Destroyed</th>\n" + " </tr>\n" + " </thead>\n" + " <tbody>\n" + " <tr>\n" + " <td>Aircraft Carrier</td>\n" + " <td>5</td>\n" + " <td id=\"AircraftDestroyed\">" + game.getNumberofA() + " </td>\n" + " </tr>" + " <tr>\n" + " <td>Battleship</td>\n" + " <td>2</td>\n" + " <td id=\"BattleshipDestroyed\">" + game.getNumberofB() + " </td>\n" + " </tr>" + " <tr>\n" + " <td>Destroyer</td>\n" + " <td>6</td>\n" + " <td id=\"DestroyerDestroyed\">" + game.getNumberofC() + " </td>\n" + " </tr>" + " <tr>\n" + " <td>Patrol Boat</td>\n" + " <td>7</td>\n" + " <td id=\"PatrolDestroyed\">" + game.getNumberofD() + " </td>\n" + " </tr>"+ " </tbody>\n" + " </table></div></div></div>"); } public void setTableBoatInfoContent10() { setTableBoatInfoContent( "<div class=\"text-center\">" + "<table class=\"table\" style=\"color: white;\">\n" + " <thead>\n" + " <tr>\n" + " <th>Boat Name</th>\n" + " <th>Length</th>\n" + " <th>Destroyed</th>\n" + " </tr>\n" + " </thead>\n" + " <tbody>\n" + " <tr>\n" + " <td>Aircraft Carrier</td>\n" + " <td>5</td>\n" + " <td id=\"AircraftDestroyed\">" + game.getNumberofA() + " </td>\n" + " </tr>" + " <tr>\n" + " <td>Battleship</td>\n" + " <td>2</td>\n" + " <td id=\"BattleshipDestroyed\">" + game.getNumberofB() + " </td>\n" + " </tr>" + " <tr>\n" + " <td>Destroyer</td>\n" + " <td>6</td>\n" + " <td id=\"DestroyerDestroyed\">" + game.getNumberofC() + " </td>\n" + " </tr>" + " <tr>\n" + " <td>Patrol Boat</td>\n" + " <td>7</td>\n" + " <td id=\"PatrolDestroyed\">" + game.getNumberofD() + " </td>\n" + " </tr>"+ " <tr>\n" + " <td>Submarine</td>\n" + " <td>9</td>\n" + " <td id=\"SubmarineDestroyed\">" + game.getNumberofE() + " </td>\n" + " </tr>\n" + " </tbody>\n" + " </table></div></div></div>"); } private String getWinner(){ String currentRanking = ""; if (game.getAccuracy() >= 80) currentRanking = ranking[3]; else if (game.getAccuracy() >= 60) currentRanking = ranking[2]; else if (game.getAccuracy() >= 40) currentRanking = ranking[1]; else currentRanking = ranking[0]; return "<div class=\"container-fluid\" id=\"Text\" hidden>" + " <div class=\"row\">" + " <div class=\"col-md-4\"></div>" + " <div class=\"col-md-4 text-center\" style=\"background-color: rgba(0,0,0, 0.7); margin-top: 12%;\">" + " <h1 style=\"color: white; text-shadow: 3px 1px 3px #09b6ff;\">Congratulations <br />"+ currentRanking + " " + game.getPlayerName() + "</h1>" + " <p style=\"color: white;\">You have overthrown the enemy and the sea is now yours. Go forth and attack more ships and make even more of the ocean yours. Keep on going like this and you will be noted in history as the best battleship " + currentRanking +".</p>" + " <i class=\"fa fa-ship fa-5x\" style=\"color:white;\"></i><br /><br />" + " <a href=\"index.html\"><button class='btn btn-default'>New Game</button></a>" + " </div>" + " <div class=\"col-md-4\"></div>" + "</div>"; } }
20,315
0.345845
0.338564
365
54.690411
48.003769
290
false
false
0
0
0
0
0
0
0.40274
false
false
10
ce6ac78f659a78c98019dc434aa6b6d3fb6f8d35
34,282,429,008,344
96cda4fb58977cdfb413b9703e97988a53295599
/Old Files/DC2 Files/GregorianMainController.java
04bf7486e62b0f33d6a0510526eb93f6aa8f0565
[]
no_license
alvinalvord/udc
https://github.com/alvinalvord/udc
1093517525b71b23a2f869c7d62a113a03d5ff4e
03cbb072d486c5e9de62918502a0adb459a75d42
refs/heads/master
2021-01-19T04:37:55.548000
2017-04-17T19:45:29
2017-04-17T19:45:29
87,382,237
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import javafx.stage.*; public class GregorianMainController extends MainController { private GregorianCalendarController gcc; public GregorianMainController (Stage stage) { super (stage); } protected void initControllers () { gcc = new GregorianCalendarController (this); } public void setScene (int n){ switch (n) { case 0: currentView = n; break; default: currentView = 0; } changeView (); } protected void changeView () { switch (currentView) { case 0: scene.setRoot (gcc.getView ()); break; default: scene.setRoot (gcc.getView ()); } } }
UTF-8
Java
625
java
GregorianMainController.java
Java
[]
null
[]
import javafx.stage.*; public class GregorianMainController extends MainController { private GregorianCalendarController gcc; public GregorianMainController (Stage stage) { super (stage); } protected void initControllers () { gcc = new GregorianCalendarController (this); } public void setScene (int n){ switch (n) { case 0: currentView = n; break; default: currentView = 0; } changeView (); } protected void changeView () { switch (currentView) { case 0: scene.setRoot (gcc.getView ()); break; default: scene.setRoot (gcc.getView ()); } } }
625
0.6464
0.6416
39
15.051282
15.921198
61
false
false
0
0
0
0
0
0
2.153846
false
false
10
2ffc9394cfc12c98a96c162a02f819f37e173ca1
38,895,223,875,460
5254d273a4e3ca67e7863b77277a32936e86e151
/framework/gwt/src/cc/alcina/framework/gwt/client/gwittir/widget/FileSelectorInfo.java
19dfe5d23903a537c2bc67a4a2a8f45af5879074
[]
no_license
google-code/alcina
https://github.com/google-code/alcina
2722ef4180a114efc5204a68919ad4437787d723
735d9308308ce0685f885d03aba6684c58ecb4cc
refs/heads/master
2016-09-09T22:56:12.142000
2015-03-14T13:11:23
2015-03-14T13:11:23
32,212,473
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package cc.alcina.framework.gwt.client.gwittir.widget; import java.io.Serializable; import cc.alcina.framework.common.client.csobjects.BaseSourcesPropertyChangeEvents; public class FileSelectorInfo extends BaseSourcesPropertyChangeEvents implements Serializable { private String fileName; private byte[] bytes; public String getFileName() { return this.fileName; } public void setFileName(String fileName) { String old_fileName = this.fileName; this.fileName = fileName; propertyChangeSupport().firePropertyChange("fileName", old_fileName, fileName); } public byte[] getBytes() { return this.bytes; } public void setBytes(byte[] bytes) { byte[] old_bytes = this.bytes; this.bytes = bytes; propertyChangeSupport().firePropertyChange("bytes", old_bytes, bytes); } }
UTF-8
Java
802
java
FileSelectorInfo.java
Java
[]
null
[]
package cc.alcina.framework.gwt.client.gwittir.widget; import java.io.Serializable; import cc.alcina.framework.common.client.csobjects.BaseSourcesPropertyChangeEvents; public class FileSelectorInfo extends BaseSourcesPropertyChangeEvents implements Serializable { private String fileName; private byte[] bytes; public String getFileName() { return this.fileName; } public void setFileName(String fileName) { String old_fileName = this.fileName; this.fileName = fileName; propertyChangeSupport().firePropertyChange("fileName", old_fileName, fileName); } public byte[] getBytes() { return this.bytes; } public void setBytes(byte[] bytes) { byte[] old_bytes = this.bytes; this.bytes = bytes; propertyChangeSupport().firePropertyChange("bytes", old_bytes, bytes); } }
802
0.763092
0.763092
32
24.0625
26.16407
95
false
false
0
0
0
0
0
0
1.46875
false
false
10
b00ab7d9bd56e749090f275487627ca47f207f87
35,476,429,911,968
a056dbeef44e0fb5dd71a7be1e6fb83a5467ea6c
/src/main/java/sample/Game.java
c27b906ee2be2cca848723ca7e7e08577c5c2c4f
[]
no_license
gemcfadyen/Apprenticeship-JavaFXSpike
https://github.com/gemcfadyen/Apprenticeship-JavaFXSpike
f47ad3fa7c0edd40bfd678a9e357623c94e0914c
6af799a0bf8a1e3562c50da105c29e7e0fc7487a
refs/heads/master
2021-01-10T11:15:14.926000
2015-11-23T17:52:02
2015-11-23T17:52:02
46,655,542
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package sample; public class Game { private int playerIndex = 0; private int numberOfTurns = 0; public int currentPlayersIndex() { int originalPlayerIndex = playerIndex; if(playerIndex == 0) { playerIndex = 1; } else { playerIndex = 0; } return originalPlayerIndex; } public void updateAt(String cellIndex, String symbol) { numberOfTurns++; System.out.println("Game received message from Gui"); System.out.println("Symbol " + symbol + " placed at index " + cellIndex); } public String getStatus() { if(numberOfTurns == 3) { return "GAME OVER"; } return "Continue...Please select your next move"; } }
UTF-8
Java
760
java
Game.java
Java
[]
null
[]
package sample; public class Game { private int playerIndex = 0; private int numberOfTurns = 0; public int currentPlayersIndex() { int originalPlayerIndex = playerIndex; if(playerIndex == 0) { playerIndex = 1; } else { playerIndex = 0; } return originalPlayerIndex; } public void updateAt(String cellIndex, String symbol) { numberOfTurns++; System.out.println("Game received message from Gui"); System.out.println("Symbol " + symbol + " placed at index " + cellIndex); } public String getStatus() { if(numberOfTurns == 3) { return "GAME OVER"; } return "Continue...Please select your next move"; } }
760
0.580263
0.572368
29
25.206896
20.861414
81
false
false
0
0
0
0
0
0
0.448276
false
false
10
0c858463af8fac5809265489bd3c46acf4c0645d
38,732,015,096,497
4dbede13455829560d55580cee491460aa8371f1
/src/ImageRecoTests/Runner.java
782e2a7cef46ecd574b137568d9b4e6dae60c7df
[]
no_license
Eeshwar-Krishnan/CvTesting
https://github.com/Eeshwar-Krishnan/CvTesting
eca3f7ef52c3ceae950bddb409a19e9c4e74ed04
f1f7215fb28f17dbf7ac83df99130b649f1331f8
refs/heads/main
2023-03-10T01:56:29.539000
2021-02-27T13:38:57
2021-02-27T13:38:57
342,864,866
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ImageRecoTests; import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Image; import java.awt.image.*; import java.io.*; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import javax.imageio.ImageIO; import org.opencv.calib3d.Calib3d; import org.opencv.core.*; import org.opencv.features2d.*; import org.opencv.highgui.HighGui; import org.opencv.imgproc.Imgproc; public class Runner { public static void main(String[] args) throws IOException { System.loadLibrary(Core.NATIVE_LIBRARY_NAME); BufferedImage navTarget = ImageIO.read(new File("res/NavTargets/redtowergoaltarget.jpg")); Mat navMat = bufferedImageToMat(navTarget); BufferedImage fullImage = ImageIO.read(new File("res/RealTests/Test6.jpg")); Mat fullMat = bufferedImageToMat(fullImage); Imgproc.resize(navMat, navMat, new Size(navTarget.getWidth()/5, navTarget.getHeight()/5)); Imgproc.cvtColor(navMat, navMat, Imgproc.COLOR_BGR2GRAY); Imgproc.cvtColor(fullMat, fullMat, Imgproc.COLOR_BGR2GRAY); System.out.println(navMat.cols() + ", " + navMat.rows()); System.out.println(fullMat.cols() + ", " + fullMat.rows()); MatOfKeyPoint navKeypoints = new MatOfKeyPoint(); Mat navDescriptors = new Mat(); BRISK featureDetector = BRISK.create(20); featureDetector.detectAndCompute(navMat, navMat, navKeypoints, navDescriptors); MatOfKeyPoint fullKeypoints = new MatOfKeyPoint(); Mat fullDescriptors = new Mat(); featureDetector.detectAndCompute(fullMat, fullMat, fullKeypoints, fullDescriptors); ArrayList<KeyPoint> keyPoints = new ArrayList<>(); keyPoints.addAll(navKeypoints.toList()); Mat out2 = new Mat(); Features2d.drawKeypoints(fullMat, fullKeypoints, out2); Image i2 = HighGui.toBufferedImage(out2); File f2 = new File("res/ImageReco/outKeypoints.png"); f2.createNewFile(); ImageIO.write(toBufferedImage(i2), "PNG", f2); Mat out3 = new Mat(); Features2d.drawKeypoints(navMat, navKeypoints, out3); Image i3 = HighGui.toBufferedImage(out3); File f3 = new File("res/ImageReco/outNavKeypoints.png"); f2.createNewFile(); ImageIO.write(toBufferedImage(i3), "PNG", f3); System.out.println("Found Keypoints"); //MatOfDMatch matches = new MatOfDMatch(); List<MatOfDMatch> matches = new ArrayList<>(); BFMatcher matcher = BFMatcher.create(); //matcher.match(navDescriptors, fullDescriptors, matches); matcher.knnMatch(navDescriptors, fullDescriptors, matches, 2); ArrayList<DMatch> arr = new ArrayList<>(); for(MatOfDMatch mD : matches) { if(mD.toArray()[0].distance < (0.8 * mD.toArray()[1].distance)) { arr.add(mD.toArray()[0]); } //arr.add(mD.toArray()[0]); //arr.add(mD.toArray()[1]); } List<DMatch> betterMatches = new ArrayList<>(); KeyPoint[] arr1 = navKeypoints.toArray(); KeyPoint[] arr2 = fullKeypoints.toArray(); MatOfPoint2f pts1Mat = new MatOfPoint2f(); MatOfPoint2f pts2Mat = new MatOfPoint2f(); for(int i = 0; i < arr.size(); i ++) { pts1Mat.push_back(new MatOfPoint2f(arr1[arr.get(i).queryIdx].pt)); pts2Mat.push_back(new MatOfPoint2f(arr2[arr.get(i).trainIdx].pt)); } Mat mask = new Mat(); Calib3d.findHomography(pts1Mat, pts2Mat, Calib3d.RANSAC, 15, mask); for(int i = (arr.size()-1); i >= 0; i --) { if(mask.get(i, 0)[0] != 0.0) { betterMatches.add(arr.get(i)); } } System.out.println(betterMatches.size()); System.out.println(arr.size()); if(betterMatches.size() > 5) { arr.clear(); arr.addAll(betterMatches); } Collections.sort(arr, new Comparator<DMatch>() { @Override public int compare(DMatch o1, DMatch o2) { return (int)(o1.distance - o2.distance); } }); MatOfDMatch match2 = new MatOfDMatch(arr.subList(0, (int)(arr.size())).toArray(new DMatch[10])); //System.out.println(navKeypoints.cols() + ", " + navKeypoints.rows() + " | " + fullKeypoints.cols() + ", " + fullKeypoints.rows()); //System.out.println(navKeypoints.dump()); Mat out = new Mat(); Features2d.drawMatches(navMat, navKeypoints, fullMat, fullKeypoints, match2, out); Image i = HighGui.toBufferedImage(out); File f = new File("res/ImageReco/outMatches.png"); f.createNewFile(); ImageIO.write(toBufferedImage(i), "PNG", f); BufferedImage buffOut = fullImage; Graphics g = buffOut.getGraphics(); g.setColor(Color.black); for(DMatch match : arr.subList(0, arr.size())) { KeyPoint kp = fullKeypoints.toArray()[match.trainIdx]; g.fillRect((int)kp.pt.x, (int)kp.pt.y, 10, 10); } ImageIO.write(buffOut, "PNG", new File("res/ImageReco/outTestImg.png")); } public static Mat bufferedImageToMat(BufferedImage bi) { Mat mat = new Mat(bi.getHeight(), bi.getWidth(), CvType.CV_8UC3); byte[] data = ((DataBufferByte) bi.getRaster().getDataBuffer()).getData(); mat.put(0, 0, data); return mat; } public static BufferedImage toBufferedImage(Image img) { if (img instanceof BufferedImage) { return (BufferedImage) img; } // Create a buffered image with transparency BufferedImage bimage = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_ARGB); // Draw the image on to the buffered image Graphics2D bGr = bimage.createGraphics(); bGr.drawImage(img, 0, 0, null); bGr.dispose(); // Return the buffered image return bimage; } }
UTF-8
Java
5,452
java
Runner.java
Java
[]
null
[]
package ImageRecoTests; import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Image; import java.awt.image.*; import java.io.*; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import javax.imageio.ImageIO; import org.opencv.calib3d.Calib3d; import org.opencv.core.*; import org.opencv.features2d.*; import org.opencv.highgui.HighGui; import org.opencv.imgproc.Imgproc; public class Runner { public static void main(String[] args) throws IOException { System.loadLibrary(Core.NATIVE_LIBRARY_NAME); BufferedImage navTarget = ImageIO.read(new File("res/NavTargets/redtowergoaltarget.jpg")); Mat navMat = bufferedImageToMat(navTarget); BufferedImage fullImage = ImageIO.read(new File("res/RealTests/Test6.jpg")); Mat fullMat = bufferedImageToMat(fullImage); Imgproc.resize(navMat, navMat, new Size(navTarget.getWidth()/5, navTarget.getHeight()/5)); Imgproc.cvtColor(navMat, navMat, Imgproc.COLOR_BGR2GRAY); Imgproc.cvtColor(fullMat, fullMat, Imgproc.COLOR_BGR2GRAY); System.out.println(navMat.cols() + ", " + navMat.rows()); System.out.println(fullMat.cols() + ", " + fullMat.rows()); MatOfKeyPoint navKeypoints = new MatOfKeyPoint(); Mat navDescriptors = new Mat(); BRISK featureDetector = BRISK.create(20); featureDetector.detectAndCompute(navMat, navMat, navKeypoints, navDescriptors); MatOfKeyPoint fullKeypoints = new MatOfKeyPoint(); Mat fullDescriptors = new Mat(); featureDetector.detectAndCompute(fullMat, fullMat, fullKeypoints, fullDescriptors); ArrayList<KeyPoint> keyPoints = new ArrayList<>(); keyPoints.addAll(navKeypoints.toList()); Mat out2 = new Mat(); Features2d.drawKeypoints(fullMat, fullKeypoints, out2); Image i2 = HighGui.toBufferedImage(out2); File f2 = new File("res/ImageReco/outKeypoints.png"); f2.createNewFile(); ImageIO.write(toBufferedImage(i2), "PNG", f2); Mat out3 = new Mat(); Features2d.drawKeypoints(navMat, navKeypoints, out3); Image i3 = HighGui.toBufferedImage(out3); File f3 = new File("res/ImageReco/outNavKeypoints.png"); f2.createNewFile(); ImageIO.write(toBufferedImage(i3), "PNG", f3); System.out.println("Found Keypoints"); //MatOfDMatch matches = new MatOfDMatch(); List<MatOfDMatch> matches = new ArrayList<>(); BFMatcher matcher = BFMatcher.create(); //matcher.match(navDescriptors, fullDescriptors, matches); matcher.knnMatch(navDescriptors, fullDescriptors, matches, 2); ArrayList<DMatch> arr = new ArrayList<>(); for(MatOfDMatch mD : matches) { if(mD.toArray()[0].distance < (0.8 * mD.toArray()[1].distance)) { arr.add(mD.toArray()[0]); } //arr.add(mD.toArray()[0]); //arr.add(mD.toArray()[1]); } List<DMatch> betterMatches = new ArrayList<>(); KeyPoint[] arr1 = navKeypoints.toArray(); KeyPoint[] arr2 = fullKeypoints.toArray(); MatOfPoint2f pts1Mat = new MatOfPoint2f(); MatOfPoint2f pts2Mat = new MatOfPoint2f(); for(int i = 0; i < arr.size(); i ++) { pts1Mat.push_back(new MatOfPoint2f(arr1[arr.get(i).queryIdx].pt)); pts2Mat.push_back(new MatOfPoint2f(arr2[arr.get(i).trainIdx].pt)); } Mat mask = new Mat(); Calib3d.findHomography(pts1Mat, pts2Mat, Calib3d.RANSAC, 15, mask); for(int i = (arr.size()-1); i >= 0; i --) { if(mask.get(i, 0)[0] != 0.0) { betterMatches.add(arr.get(i)); } } System.out.println(betterMatches.size()); System.out.println(arr.size()); if(betterMatches.size() > 5) { arr.clear(); arr.addAll(betterMatches); } Collections.sort(arr, new Comparator<DMatch>() { @Override public int compare(DMatch o1, DMatch o2) { return (int)(o1.distance - o2.distance); } }); MatOfDMatch match2 = new MatOfDMatch(arr.subList(0, (int)(arr.size())).toArray(new DMatch[10])); //System.out.println(navKeypoints.cols() + ", " + navKeypoints.rows() + " | " + fullKeypoints.cols() + ", " + fullKeypoints.rows()); //System.out.println(navKeypoints.dump()); Mat out = new Mat(); Features2d.drawMatches(navMat, navKeypoints, fullMat, fullKeypoints, match2, out); Image i = HighGui.toBufferedImage(out); File f = new File("res/ImageReco/outMatches.png"); f.createNewFile(); ImageIO.write(toBufferedImage(i), "PNG", f); BufferedImage buffOut = fullImage; Graphics g = buffOut.getGraphics(); g.setColor(Color.black); for(DMatch match : arr.subList(0, arr.size())) { KeyPoint kp = fullKeypoints.toArray()[match.trainIdx]; g.fillRect((int)kp.pt.x, (int)kp.pt.y, 10, 10); } ImageIO.write(buffOut, "PNG", new File("res/ImageReco/outTestImg.png")); } public static Mat bufferedImageToMat(BufferedImage bi) { Mat mat = new Mat(bi.getHeight(), bi.getWidth(), CvType.CV_8UC3); byte[] data = ((DataBufferByte) bi.getRaster().getDataBuffer()).getData(); mat.put(0, 0, data); return mat; } public static BufferedImage toBufferedImage(Image img) { if (img instanceof BufferedImage) { return (BufferedImage) img; } // Create a buffered image with transparency BufferedImage bimage = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_ARGB); // Draw the image on to the buffered image Graphics2D bGr = bimage.createGraphics(); bGr.drawImage(img, 0, 0, null); bGr.dispose(); // Return the buffered image return bimage; } }
5,452
0.694241
0.678283
164
32.243904
26.301517
134
false
false
0
0
0
0
0
0
2.664634
false
false
10
8dd542761569d176718125646a5a82f702fd14fa
33,552,284,581,590
d8129bfe8f842bedc02026f482bbc7fe26b9862a
/NowSaleAndroidApp/app/src/main/java/com/chapchapbrothers/nowsale/LoadingAnimationFragment.java
8f9391fa03cef79c801e2042ed83a84c397c4849
[]
no_license
skawk5678/NowSale
https://github.com/skawk5678/NowSale
bf7a25d2547fb731a8e9e54f2ffb8531bebf6672
c782dc021810068cea918878c06ccc862b0188bb
refs/heads/master
2020-03-26T01:42:01.157000
2019-01-20T14:01:54
2019-01-20T14:01:54
144,378,361
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.chapchapbrothers.nowsale; import android.app.Fragment; /** * Created by TedPark on 2017. 3. 18.. */ public class LoadingAnimationFragment extends Fragment { public void progressON() { LoadingAnimationApplication.getInstance().progressON(getActivity(), null); } public void progressON(String message) { LoadingAnimationApplication.getInstance().progressON(getActivity(), message); } public void progressOFF() { LoadingAnimationApplication.getInstance().progressOFF(); } }
UTF-8
Java
541
java
LoadingAnimationFragment.java
Java
[ { "context": ";\n\nimport android.app.Fragment;\n\n/**\n * Created by TedPark on 2017. 3. 18..\n */\n\npublic class LoadingAnimati", "end": 94, "score": 0.8808342218399048, "start": 87, "tag": "NAME", "value": "TedPark" } ]
null
[]
package com.chapchapbrothers.nowsale; import android.app.Fragment; /** * Created by TedPark on 2017. 3. 18.. */ public class LoadingAnimationFragment extends Fragment { public void progressON() { LoadingAnimationApplication.getInstance().progressON(getActivity(), null); } public void progressON(String message) { LoadingAnimationApplication.getInstance().progressON(getActivity(), message); } public void progressOFF() { LoadingAnimationApplication.getInstance().progressOFF(); } }
541
0.709797
0.696858
24
21.541666
27.027731
85
false
false
0
0
0
0
0
0
0.291667
false
false
10
03a6ff2d9b3ca2a23cbd8ae89fd68b6c69b9c3a6
38,285,338,500,869
162f2cbd6ac5dd9b09004002ed714cef5b46d46c
/IT18151152/Beta04b/src/SoftwarePackage.java
42ae47637f6716c424873639f4b68e2c3898d171
[]
no_license
SLIIT-HCI/markMe
https://github.com/SLIIT-HCI/markMe
57ab469a4c35b3b2c3b9d93f8f9bc6165e2afb66
16d6fd94078db44e47281e04ad7ba6ff30b63dc7
refs/heads/master
2022-10-27T01:20:52.989000
2020-06-16T02:14:29
2020-06-16T02:14:29
265,216,503
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
public class SoftwarePackage { private String name; public SoftwarePackage(String name) { super(); this.name = name; } public void Open(){ System.out.println("software package is open"); } public void Close(){ System.out.println("software package is close"); } }
UTF-8
Java
287
java
SoftwarePackage.java
Java
[]
null
[]
public class SoftwarePackage { private String name; public SoftwarePackage(String name) { super(); this.name = name; } public void Open(){ System.out.println("software package is open"); } public void Close(){ System.out.println("software package is close"); } }
287
0.679443
0.679443
18
14.888889
16.689613
50
false
false
0
0
0
0
0
0
1.277778
false
false
10
21d140c8f78e7cf0919b940724b4553c8a7269e5
38,354,057,977,504
fbdd95f9dcf4da14714569c74c12c21db5e0e294
/user-coupon/user-service-api/src/main/java/com/xdclass/userserviceapi/service/IUserService.java
c58444a5477488d51750db2b1e5d963decb4410c
[]
no_license
blench/xdclass-demo
https://github.com/blench/xdclass-demo
13eb7b794e8ff712343d4400a9330bd9eaf2afd4
1d471ad21bd9386f63cb7c3bf6668430791f0315
refs/heads/main
2023-01-19T19:42:36.182000
2020-11-30T09:17:49
2020-11-30T09:17:49
317,091,758
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.xdclass.userserviceapi.service; import com.xdclass.userserviceapi.vo.UserVO; /** * @author William * @version 1.0 * @description: TODO * @date 2020/11/28 20:21 */ public interface IUserService { UserVO getUserById(Integer id); }
UTF-8
Java
254
java
IUserService.java
Java
[ { "context": ".xdclass.userserviceapi.vo.UserVO;\n\n/**\n * @author William\n * @version 1.0\n * @description: TODO\n * @date 20", "end": 113, "score": 0.9902253150939941, "start": 106, "tag": "NAME", "value": "William" } ]
null
[]
package com.xdclass.userserviceapi.service; import com.xdclass.userserviceapi.vo.UserVO; /** * @author William * @version 1.0 * @description: TODO * @date 2020/11/28 20:21 */ public interface IUserService { UserVO getUserById(Integer id); }
254
0.716535
0.661417
15
15.933333
15.910025
44
false
false
0
0
0
0
0
0
0.2
false
false
10
286d6779bbd45b68ac6697c3603429d0a249c1bf
39,273,180,978,114
ec57a2d53f7cbaeafa93f27d816930fd509639e2
/Runescape 530 Client/source/Class133.java
9c5d512d9db11522a857d12e32753c028e923397
[]
no_license
rockseller2/runescape-server-csharp
https://github.com/rockseller2/runescape-server-csharp
4464a97c3fbd083fbb06a83bbb957c34a5c1b7a6
fae8dfb7f44474ed3b1528cecc0560530ca7c5cd
refs/heads/master
2021-01-01T16:50:34.062000
2013-12-26T09:14:09
2013-12-26T09:14:09
33,208,230
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.awt.event.FocusEvent; import java.awt.event.FocusListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; public class Class133 implements MouseListener, MouseMotionListener, FocusListener { public static RSString aRSString_2446 = Class134.method1914(" from your friend list first)3", (byte) 95); public static int anInt2447; public static int anInt2448; public static Class9 aClass9_2449; public static int anInt2450; public static int anInt2451; public static int anInt2452; public static int anInt2453; public static int anInt2454; public static RSString aRSString_2455 = aRSString_2446; public static Class136 aClass136_2456 = new Class136(50); public static int anInt2457; public static int anInt2458; public static int anInt2459; public static int anInt2460; public static int anInt2461; public static void method1906(int arg0) { aClass136_2456 = null; aRSString_2446 = null; aRSString_2455 = null; aClass9_2449 = null; if (arg0 >= -11) aRSString_2455 = null; } public void focusGained(FocusEvent arg0) { anInt2461++; } public static Class119_Sub1 method1907(int arg0) { anInt2458++; Class119_Sub1 class119_sub1 = new Class119_Sub1(Class3.anInt119, Class80.anInt1628, Class67_Sub23.anIntArray3201[0], Class67_Sub6.anIntArray2870[0], Class55_Sub3.anIntArray2810[0], Class67_Sub5_Sub4.anIntArray4510[arg0], Class67_Sub1_Sub35.aByteArrayArray4357[0], Class73.anIntArray1462); Class67_Sub5_Sub11.method937(false); return class119_sub1; } public static Class64 method1908(int arg0, int arg1) { anInt2451++; Class64 class64 = (Class64) Class67_Sub1_Sub7.aClass136_3908 .method1924((long) arg0, false); if (class64 != null) return class64; byte[] is = Class86.aClass9_1762.method138(-809612665, Class43.method381(arg0, 127), Class67_Sub1_Sub16_Sub1 .method693(arg0, 23614)); class64 = new Class64(); class64.anInt1205 = arg0; if (is != null) class64.method572(new Stream(is), (byte) -28); class64.method577((byte) 46); int i = 25 / ((arg1 - 48) / 38); Class67_Sub1_Sub7.aClass136_3908.method1926((long) arg0, class64, (byte) -71); return class64; } public synchronized void mouseExited(MouseEvent arg0) { anInt2453++; if (Class6.aClass133_154 != null) { Class67_Sub1_Sub12.anInt4014 = 0; Class67_Sub1_Sub25.anInt4218 = -1; Class52.anInt1048 = -1; } } public void mouseClicked(MouseEvent arg0) { if (arg0.isPopupTrigger()) arg0.consume(); anInt2454++; } public synchronized void focusLost(FocusEvent arg0) { if (Class6.aClass133_154 != null) Class87.anInt1813 = 0; anInt2448++; } public synchronized void mouseEntered(MouseEvent arg0) { if (Class6.aClass133_154 != null) { Class67_Sub1_Sub12.anInt4014 = 0; Class67_Sub1_Sub25.anInt4218 = arg0.getX(); Class52.anInt1048 = arg0.getY(); } anInt2450++; } public synchronized void mouseMoved(MouseEvent arg0) { if (Class6.aClass133_154 != null) { Class67_Sub1_Sub12.anInt4014 = 0; Class67_Sub1_Sub25.anInt4218 = arg0.getX(); Class52.anInt1048 = arg0.getY(); } anInt2447++; } public synchronized void mouseDragged(MouseEvent arg0) { anInt2460++; if (Class6.aClass133_154 != null) { Class67_Sub1_Sub12.anInt4014 = 0; Class67_Sub1_Sub25.anInt4218 = arg0.getX(); Class52.anInt1048 = arg0.getY(); } } public static void method1909(int arg0, int arg1, int arg2, int arg3, int arg4, int arg5, int arg6, int arg7, int arg8, int arg9, int arg10, int arg11, int arg12, int arg13, int arg14, int arg15, int arg16, int arg17, int arg18, int arg19) { if (arg3 == 0) { Class84 class84 = new Class84(arg10, arg11, arg12, arg13, -1, arg18, false); for (int i = arg0; i >= 0; i--) { if (Class76.aClass67_Sub24ArrayArrayArray1578[i][arg1][arg2] == null) Class76.aClass67_Sub24ArrayArrayArray1578[i][arg1][arg2] = new Class67_Sub24(i, arg1, arg2); } Class76.aClass67_Sub24ArrayArrayArray1578[arg0][arg1][arg2] .aClass84_3227 = class84; } else if (arg3 == 1) { Class84 class84 = new Class84(arg14, arg15, arg16, arg17, arg5, arg19, arg6 == arg7 && arg6 == arg8 && arg6 == arg9); for (int i = arg0; i >= 0; i--) { if (Class76.aClass67_Sub24ArrayArrayArray1578[i][arg1][arg2] == null) Class76.aClass67_Sub24ArrayArrayArray1578[i][arg1][arg2] = new Class67_Sub24(i, arg1, arg2); } Class76.aClass67_Sub24ArrayArrayArray1578[arg0][arg1][arg2] .aClass84_3227 = class84; } else { Class71 class71 = new Class71(arg3, arg4, arg5, arg1, arg2, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19); for (int i = arg0; i >= 0; i--) { if (Class76.aClass67_Sub24ArrayArrayArray1578[i][arg1][arg2] == null) Class76.aClass67_Sub24ArrayArrayArray1578[i][arg1][arg2] = new Class67_Sub24(i, arg1, arg2); } Class76.aClass67_Sub24ArrayArrayArray1578[arg0][arg1][arg2] .aClass71_3219 = class71; } } public synchronized void mousePressed(MouseEvent arg0) { anInt2452++; if (Class6.aClass133_154 != null) { Class67_Sub1_Sub12.anInt4014 = 0; Class67_Sub1_Sub12.anInt4006 = arg0.getX(); Class14.anInt447 = arg0.getY(); Class125.aLong2342 = Class39.method337(19644); if (!arg0.isMetaDown()) { Class131_Sub7.anInt3768 = 1; Class87.anInt1813 = 1; } else { Class131_Sub7.anInt3768 = 2; Class87.anInt1813 = 2; } int i = arg0.getModifiers(); } if (arg0.isPopupTrigger()) arg0.consume(); } public synchronized void mouseReleased(MouseEvent arg0) { anInt2457++; if (Class6.aClass133_154 != null) { Class67_Sub1_Sub12.anInt4014 = 0; Class87.anInt1813 = 0; int i = arg0.getModifiers(); } if (arg0.isPopupTrigger()) arg0.consume(); } }
UTF-8
Java
6,345
java
Class133.java
Java
[]
null
[]
import java.awt.event.FocusEvent; import java.awt.event.FocusListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; public class Class133 implements MouseListener, MouseMotionListener, FocusListener { public static RSString aRSString_2446 = Class134.method1914(" from your friend list first)3", (byte) 95); public static int anInt2447; public static int anInt2448; public static Class9 aClass9_2449; public static int anInt2450; public static int anInt2451; public static int anInt2452; public static int anInt2453; public static int anInt2454; public static RSString aRSString_2455 = aRSString_2446; public static Class136 aClass136_2456 = new Class136(50); public static int anInt2457; public static int anInt2458; public static int anInt2459; public static int anInt2460; public static int anInt2461; public static void method1906(int arg0) { aClass136_2456 = null; aRSString_2446 = null; aRSString_2455 = null; aClass9_2449 = null; if (arg0 >= -11) aRSString_2455 = null; } public void focusGained(FocusEvent arg0) { anInt2461++; } public static Class119_Sub1 method1907(int arg0) { anInt2458++; Class119_Sub1 class119_sub1 = new Class119_Sub1(Class3.anInt119, Class80.anInt1628, Class67_Sub23.anIntArray3201[0], Class67_Sub6.anIntArray2870[0], Class55_Sub3.anIntArray2810[0], Class67_Sub5_Sub4.anIntArray4510[arg0], Class67_Sub1_Sub35.aByteArrayArray4357[0], Class73.anIntArray1462); Class67_Sub5_Sub11.method937(false); return class119_sub1; } public static Class64 method1908(int arg0, int arg1) { anInt2451++; Class64 class64 = (Class64) Class67_Sub1_Sub7.aClass136_3908 .method1924((long) arg0, false); if (class64 != null) return class64; byte[] is = Class86.aClass9_1762.method138(-809612665, Class43.method381(arg0, 127), Class67_Sub1_Sub16_Sub1 .method693(arg0, 23614)); class64 = new Class64(); class64.anInt1205 = arg0; if (is != null) class64.method572(new Stream(is), (byte) -28); class64.method577((byte) 46); int i = 25 / ((arg1 - 48) / 38); Class67_Sub1_Sub7.aClass136_3908.method1926((long) arg0, class64, (byte) -71); return class64; } public synchronized void mouseExited(MouseEvent arg0) { anInt2453++; if (Class6.aClass133_154 != null) { Class67_Sub1_Sub12.anInt4014 = 0; Class67_Sub1_Sub25.anInt4218 = -1; Class52.anInt1048 = -1; } } public void mouseClicked(MouseEvent arg0) { if (arg0.isPopupTrigger()) arg0.consume(); anInt2454++; } public synchronized void focusLost(FocusEvent arg0) { if (Class6.aClass133_154 != null) Class87.anInt1813 = 0; anInt2448++; } public synchronized void mouseEntered(MouseEvent arg0) { if (Class6.aClass133_154 != null) { Class67_Sub1_Sub12.anInt4014 = 0; Class67_Sub1_Sub25.anInt4218 = arg0.getX(); Class52.anInt1048 = arg0.getY(); } anInt2450++; } public synchronized void mouseMoved(MouseEvent arg0) { if (Class6.aClass133_154 != null) { Class67_Sub1_Sub12.anInt4014 = 0; Class67_Sub1_Sub25.anInt4218 = arg0.getX(); Class52.anInt1048 = arg0.getY(); } anInt2447++; } public synchronized void mouseDragged(MouseEvent arg0) { anInt2460++; if (Class6.aClass133_154 != null) { Class67_Sub1_Sub12.anInt4014 = 0; Class67_Sub1_Sub25.anInt4218 = arg0.getX(); Class52.anInt1048 = arg0.getY(); } } public static void method1909(int arg0, int arg1, int arg2, int arg3, int arg4, int arg5, int arg6, int arg7, int arg8, int arg9, int arg10, int arg11, int arg12, int arg13, int arg14, int arg15, int arg16, int arg17, int arg18, int arg19) { if (arg3 == 0) { Class84 class84 = new Class84(arg10, arg11, arg12, arg13, -1, arg18, false); for (int i = arg0; i >= 0; i--) { if (Class76.aClass67_Sub24ArrayArrayArray1578[i][arg1][arg2] == null) Class76.aClass67_Sub24ArrayArrayArray1578[i][arg1][arg2] = new Class67_Sub24(i, arg1, arg2); } Class76.aClass67_Sub24ArrayArrayArray1578[arg0][arg1][arg2] .aClass84_3227 = class84; } else if (arg3 == 1) { Class84 class84 = new Class84(arg14, arg15, arg16, arg17, arg5, arg19, arg6 == arg7 && arg6 == arg8 && arg6 == arg9); for (int i = arg0; i >= 0; i--) { if (Class76.aClass67_Sub24ArrayArrayArray1578[i][arg1][arg2] == null) Class76.aClass67_Sub24ArrayArrayArray1578[i][arg1][arg2] = new Class67_Sub24(i, arg1, arg2); } Class76.aClass67_Sub24ArrayArrayArray1578[arg0][arg1][arg2] .aClass84_3227 = class84; } else { Class71 class71 = new Class71(arg3, arg4, arg5, arg1, arg2, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19); for (int i = arg0; i >= 0; i--) { if (Class76.aClass67_Sub24ArrayArrayArray1578[i][arg1][arg2] == null) Class76.aClass67_Sub24ArrayArrayArray1578[i][arg1][arg2] = new Class67_Sub24(i, arg1, arg2); } Class76.aClass67_Sub24ArrayArrayArray1578[arg0][arg1][arg2] .aClass71_3219 = class71; } } public synchronized void mousePressed(MouseEvent arg0) { anInt2452++; if (Class6.aClass133_154 != null) { Class67_Sub1_Sub12.anInt4014 = 0; Class67_Sub1_Sub12.anInt4006 = arg0.getX(); Class14.anInt447 = arg0.getY(); Class125.aLong2342 = Class39.method337(19644); if (!arg0.isMetaDown()) { Class131_Sub7.anInt3768 = 1; Class87.anInt1813 = 1; } else { Class131_Sub7.anInt3768 = 2; Class87.anInt1813 = 2; } int i = arg0.getModifiers(); } if (arg0.isPopupTrigger()) arg0.consume(); } public synchronized void mouseReleased(MouseEvent arg0) { anInt2457++; if (Class6.aClass133_154 != null) { Class67_Sub1_Sub12.anInt4014 = 0; Class87.anInt1813 = 0; int i = arg0.getModifiers(); } if (arg0.isPopupTrigger()) arg0.consume(); } }
6,345
0.641135
0.492987
202
29.410891
19.092907
73
false
false
0
0
0
0
0
0
1.930693
false
false
10
0b624db6b5f520a84dca65d0ce329b75ec56830d
39,273,180,977,569
70e90853cc165a5ef162fc5e1fab28a1177ba892
/app/src/main/java/lu/eminozandac/ondamondclinet/OnDamondClient.java
739eb1b4ac6ef8505a5879445bb5717b7ccb50d9
[]
no_license
wenjinge0424/Client_Damond
https://github.com/wenjinge0424/Client_Damond
0c92b47488d0bfbd4ffd0247098c0bbd0dc9b6cf
83d7b5474bb9a04cfceba58ac6557819a147cc7e
refs/heads/master
2023-04-15T06:15:48.790000
2021-04-20T08:30:51
2021-04-20T08:30:51
359,737,580
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package lu.eminozandac.ondamondclinet; import android.content.Context; import android.content.SharedPreferences; import android.preference.PreferenceManager; import androidx.multidex.MultiDex; import androidx.multidex.MultiDexApplication; import com.parse.Parse; import com.parse.ParseACL; public class OnDamondClient extends MultiDexApplication { public static Context mContext; @Override protected void attachBaseContext(Context context) { super.attachBaseContext(context); MultiDex.install(this); } @SuppressWarnings("deprecation") @Override public void onCreate() { // TODO Auto-generated method stub super.onCreate(); mContext = getApplicationContext(); // initialize SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(mContext); // AppPreference.initialize(pref); /* * initialize parse */ // Initialize Crash Reporting. // ParseCrashReporting.enable(this); // Enable Local Datastore. Parse.enableLocalDatastore(this); // Add your initialization code here Parse.initialize(new Parse.Configuration.Builder(this) .applicationId("maquetee_app_01") .clientKey("master_maquetee_0123") .server("http://3.137.103.177:1337/parse") .build()); ParseACL defaultACL = new ParseACL(); defaultACL.setPublicReadAccess(true); defaultACL.setPublicWriteAccess(true); ParseACL.setDefaultACL(defaultACL, true); Parse.setLogLevel(Parse.LOG_LEVEL_DEBUG); initImageLoader(mContext); // new MyImageLoader(); // MyImageLoader.init(); } public static Context getContext() { return mContext; } private void initImageLoader(Context context) { // ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context) // .memoryCacheExtraOptions(480, 800) // default = device screen dimensions // .diskCacheExtraOptions(480, 800, null) // .threadPoolSize(3) // default // .threadPriority(Thread.NORM_PRIORITY - 2) // default // .tasksProcessingOrder(QueueProcessingType.FIFO) // default // .denyCacheImageMultipleSizesInMemory() // .memoryCache(new LruMemoryCache(10 * 1024 * 1024)) // .memoryCacheSize(10 * 1024 * 1024) // .memoryCacheSizePercentage(13) // default // .diskCacheSize(50 * 1024 * 1024) // .diskCacheFileCount(100) // .diskCacheFileNameGenerator(new HashCodeFileNameGenerator()) // default // .imageDownloader(new BaseImageDownloader(context)) // default // .defaultDisplayImageOptions(DisplayImageOptions.createSimple()) // default // .writeDebugLogs() // .build(); // ImageLoader.getInstance().init(config); } }
UTF-8
Java
2,572
java
OnDamondClient.java
Java
[ { "context": ".applicationId(\"maquetee_app_01\")\n\t\t\t\t.clientKey(\"master_maquetee_0123\")\n\t\t\t\t.server(\"http://3.137.103.177:1337/parse\")\n", "end": 1160, "score": 0.9995549321174622, "start": 1140, "tag": "KEY", "value": "master_maquetee_0123" }, { "context": "ntKey(\"master_maquetee_0123\")\n\t\t\t\t.server(\"http://3.137.103.177:1337/parse\")\n\t\t\t\t.build());\n\t\tParseACL defaultACL", "end": 1196, "score": 0.9993621110916138, "start": 1183, "tag": "IP_ADDRESS", "value": "3.137.103.177" } ]
null
[]
package lu.eminozandac.ondamondclinet; import android.content.Context; import android.content.SharedPreferences; import android.preference.PreferenceManager; import androidx.multidex.MultiDex; import androidx.multidex.MultiDexApplication; import com.parse.Parse; import com.parse.ParseACL; public class OnDamondClient extends MultiDexApplication { public static Context mContext; @Override protected void attachBaseContext(Context context) { super.attachBaseContext(context); MultiDex.install(this); } @SuppressWarnings("deprecation") @Override public void onCreate() { // TODO Auto-generated method stub super.onCreate(); mContext = getApplicationContext(); // initialize SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(mContext); // AppPreference.initialize(pref); /* * initialize parse */ // Initialize Crash Reporting. // ParseCrashReporting.enable(this); // Enable Local Datastore. Parse.enableLocalDatastore(this); // Add your initialization code here Parse.initialize(new Parse.Configuration.Builder(this) .applicationId("maquetee_app_01") .clientKey("master_maquetee_0123") .server("http://172.16.31.10:1337/parse") .build()); ParseACL defaultACL = new ParseACL(); defaultACL.setPublicReadAccess(true); defaultACL.setPublicWriteAccess(true); ParseACL.setDefaultACL(defaultACL, true); Parse.setLogLevel(Parse.LOG_LEVEL_DEBUG); initImageLoader(mContext); // new MyImageLoader(); // MyImageLoader.init(); } public static Context getContext() { return mContext; } private void initImageLoader(Context context) { // ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context) // .memoryCacheExtraOptions(480, 800) // default = device screen dimensions // .diskCacheExtraOptions(480, 800, null) // .threadPoolSize(3) // default // .threadPriority(Thread.NORM_PRIORITY - 2) // default // .tasksProcessingOrder(QueueProcessingType.FIFO) // default // .denyCacheImageMultipleSizesInMemory() // .memoryCache(new LruMemoryCache(10 * 1024 * 1024)) // .memoryCacheSize(10 * 1024 * 1024) // .memoryCacheSizePercentage(13) // default // .diskCacheSize(50 * 1024 * 1024) // .diskCacheFileCount(100) // .diskCacheFileNameGenerator(new HashCodeFileNameGenerator()) // default // .imageDownloader(new BaseImageDownloader(context)) // default // .defaultDisplayImageOptions(DisplayImageOptions.createSimple()) // default // .writeDebugLogs() // .build(); // ImageLoader.getInstance().init(config); } }
2,571
0.746112
0.719285
81
30.765432
21.946777
83
false
false
0
0
0
0
0
0
2.234568
false
false
10
e6f2d243d128bd0ef0460ce272fac0baf2177f26
36,000,415,919,205
cbbc4ca3268dd0640e8aabdc61e65695ea2f68c4
/app/src/main/java/com/thecyberian/cms_system/CustomerDetails.java
0c07ca2b38a3e161d2253275946fe22127abfa18
[ "Apache-2.0" ]
permissive
TheCyberian/CMS-Android
https://github.com/TheCyberian/CMS-Android
565c681a2c751f232ecde1e25a6f4aad48463544
b0c359db5570bd8b4996b5aa5ad86553f857378b
refs/heads/master
2023-06-03T02:42:26.424000
2023-05-22T10:00:39
2023-05-22T10:00:39
217,129,259
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.thecyberian.cms_system; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import org.json.JSONArray; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; public class CustomerDetails extends AppCompatActivity { TextView nameTextView; TextView addressTextView; TextView contactTextView; ListView orderList; ArrayAdapter orderListAdapter; String baseEndPoint = "http://10.0.2.2:5000/getCustomerOrder/"; ArrayList<String[]> orderData; public void createOrder(View view) { Intent intent = new Intent(CustomerDetails.this, AddOrderActivity.class); intent.putExtra("name", nameTextView.getText().toString()); intent.putExtra("address", addressTextView.getText().toString()); intent.putExtra("phone", contactTextView.getText().toString()); startActivity(intent); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_customer_details); GetDataFromApi task = new GetDataFromApi(); String custId = getIntent().getStringExtra("custId"); String name = getIntent().getStringExtra("name"); String address = getIntent().getStringExtra("address"); String phone = getIntent().getStringExtra("phone"); Log.i("CustID from Intent", custId); Log.i("name from Intent", name); Log.i("address from Intent", address); Log.i("phone from Intent", phone); nameTextView = findViewById(R.id.nameTextView); addressTextView = findViewById(R.id.addressTextView); contactTextView = findViewById(R.id.contactTextView); orderList = findViewById(R.id.custOrdersListView); nameTextView.setText("Name : \n\t" + name); addressTextView.setText("Address : \n" + address); contactTextView.setText("Phone : \n" + phone); task.execute(baseEndPoint + custId); orderList.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { Intent intent = new Intent(CustomerDetails.this, OrderDetailsActivity.class); intent.putExtra("orderIdEditText", orderData.get(i)[0]); intent.putExtra("itemNameEditText", orderData.get(i)[1]); intent.putExtra("weight", orderData.get(i)[2]); intent.putExtra("amountPaid", orderData.get(i)[3]); intent.putExtra("totalAmount", orderData.get(i)[4]); intent.putExtra("FROM_ACTIVITY", "CustomerDetails"); startActivity(intent); } }); } public class GetDataFromApi extends AsyncTask<String, Void, String> { @Override protected String doInBackground(String... urls) { String result = ""; URL url; HttpURLConnection urlConnection = null; try { url = new URL(urls[0]); urlConnection = (HttpURLConnection) url.openConnection(); InputStream in = urlConnection.getInputStream(); InputStreamReader reader = new InputStreamReader(in); int data = reader.read(); while (data != -1) { char current = (char) data; result += current; data = reader.read(); } return result; } catch (Exception e) { e.printStackTrace(); return null; } } @Override protected void onPostExecute(String s) { super.onPostExecute(s); try { JSONArray jsonArray = new JSONArray(s); ArrayList<String> data = new ArrayList<>(); orderData = new ArrayList<>(); for (int i = 0; i < jsonArray.length(); i++) { JSONArray subArray = jsonArray.getJSONArray(i); data.add(i, subArray.get(1).toString()); String[] order = new String[5]; order[0] = subArray.get(0).toString(); order[1] = subArray.get(1).toString(); order[2] = subArray.get(2).toString(); order[3] = subArray.get(3).toString(); order[4] = subArray.get(4).toString(); Log.i("Order 0", String.valueOf(order[0])); Log.i("Order 1", String.valueOf(order[1])); Log.i("Order 2", String.valueOf(order[2])); Log.i("Order 3", String.valueOf(order[3])); Log.i("Order 4", String.valueOf(order[4])); orderData.add(i, order); } orderListAdapter = new ArrayAdapter(CustomerDetails.this, android.R.layout.simple_list_item_1, data); orderList.setAdapter(orderListAdapter); } catch (Exception e) { e.printStackTrace(); } } } }
UTF-8
Java
5,542
java
CustomerDetails.java
Java
[ { "context": "derListAdapter;\n String baseEndPoint = \"http://10.0.2.2:5000/getCustomerOrder/\";\n\n ArrayList<String[]>", "end": 811, "score": 0.9995795488357544, "start": 803, "tag": "IP_ADDRESS", "value": "10.0.2.2" } ]
null
[]
package com.thecyberian.cms_system; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import org.json.JSONArray; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; public class CustomerDetails extends AppCompatActivity { TextView nameTextView; TextView addressTextView; TextView contactTextView; ListView orderList; ArrayAdapter orderListAdapter; String baseEndPoint = "http://10.0.2.2:5000/getCustomerOrder/"; ArrayList<String[]> orderData; public void createOrder(View view) { Intent intent = new Intent(CustomerDetails.this, AddOrderActivity.class); intent.putExtra("name", nameTextView.getText().toString()); intent.putExtra("address", addressTextView.getText().toString()); intent.putExtra("phone", contactTextView.getText().toString()); startActivity(intent); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_customer_details); GetDataFromApi task = new GetDataFromApi(); String custId = getIntent().getStringExtra("custId"); String name = getIntent().getStringExtra("name"); String address = getIntent().getStringExtra("address"); String phone = getIntent().getStringExtra("phone"); Log.i("CustID from Intent", custId); Log.i("name from Intent", name); Log.i("address from Intent", address); Log.i("phone from Intent", phone); nameTextView = findViewById(R.id.nameTextView); addressTextView = findViewById(R.id.addressTextView); contactTextView = findViewById(R.id.contactTextView); orderList = findViewById(R.id.custOrdersListView); nameTextView.setText("Name : \n\t" + name); addressTextView.setText("Address : \n" + address); contactTextView.setText("Phone : \n" + phone); task.execute(baseEndPoint + custId); orderList.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { Intent intent = new Intent(CustomerDetails.this, OrderDetailsActivity.class); intent.putExtra("orderIdEditText", orderData.get(i)[0]); intent.putExtra("itemNameEditText", orderData.get(i)[1]); intent.putExtra("weight", orderData.get(i)[2]); intent.putExtra("amountPaid", orderData.get(i)[3]); intent.putExtra("totalAmount", orderData.get(i)[4]); intent.putExtra("FROM_ACTIVITY", "CustomerDetails"); startActivity(intent); } }); } public class GetDataFromApi extends AsyncTask<String, Void, String> { @Override protected String doInBackground(String... urls) { String result = ""; URL url; HttpURLConnection urlConnection = null; try { url = new URL(urls[0]); urlConnection = (HttpURLConnection) url.openConnection(); InputStream in = urlConnection.getInputStream(); InputStreamReader reader = new InputStreamReader(in); int data = reader.read(); while (data != -1) { char current = (char) data; result += current; data = reader.read(); } return result; } catch (Exception e) { e.printStackTrace(); return null; } } @Override protected void onPostExecute(String s) { super.onPostExecute(s); try { JSONArray jsonArray = new JSONArray(s); ArrayList<String> data = new ArrayList<>(); orderData = new ArrayList<>(); for (int i = 0; i < jsonArray.length(); i++) { JSONArray subArray = jsonArray.getJSONArray(i); data.add(i, subArray.get(1).toString()); String[] order = new String[5]; order[0] = subArray.get(0).toString(); order[1] = subArray.get(1).toString(); order[2] = subArray.get(2).toString(); order[3] = subArray.get(3).toString(); order[4] = subArray.get(4).toString(); Log.i("Order 0", String.valueOf(order[0])); Log.i("Order 1", String.valueOf(order[1])); Log.i("Order 2", String.valueOf(order[2])); Log.i("Order 3", String.valueOf(order[3])); Log.i("Order 4", String.valueOf(order[4])); orderData.add(i, order); } orderListAdapter = new ArrayAdapter(CustomerDetails.this, android.R.layout.simple_list_item_1, data); orderList.setAdapter(orderListAdapter); } catch (Exception e) { e.printStackTrace(); } } } }
5,542
0.588596
0.581379
161
33.422359
26.474091
117
false
false
0
0
0
0
0
0
0.770186
false
false
10
500e0c21101525bbd1181beb355c0d5569f1726a
35,313,221,161,331
5dc5e4f19cb96c99b65f16ee100088bf7f404af4
/src/main/java/com/thepoptartcrpr/culinary/handlers/ConfigHandler.java
bc579c21a643b8800c1e2309c063d8950049ec98
[]
no_license
ThePoptartCrpr/Culinary
https://github.com/ThePoptartCrpr/Culinary
fc90b77d62e6aa892458e4fdd7d092529c344310
6610642b6b77b2dcea469379e0be7fc197ce9c43
refs/heads/master
2020-03-20T20:08:16.549000
2018-06-26T19:26:42
2018-06-26T19:26:42
137,671,912
10
2
null
false
2018-06-17T22:07:20
2018-06-17T17:08:34
2018-06-17T21:27:57
2018-06-17T22:07:20
72
0
2
0
Java
false
null
package com.thepoptartcrpr.culinary.handlers; import com.thepoptartcrpr.culinary.Culinary; import net.minecraftforge.common.config.Config; import net.minecraftforge.common.config.Config.Comment; import net.minecraftforge.common.config.Config.Type; import net.minecraftforge.common.config.ConfigManager; import net.minecraftforge.fml.client.event.ConfigChangedEvent; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; public class ConfigHandler { @SubscribeEvent public void onConfigChangedEvent(ConfigChangedEvent.OnConfigChangedEvent event) { if (event.getModID().equals(Culinary.Reference.MODID)) ConfigManager.sync(Culinary.Reference.MODID, Config.Type.INSTANCE); } @Config(modid = Culinary.Reference.MODID, type = Type.INSTANCE, name = Culinary.Reference.NAME) public static class CONFIG { @Comment("When enabled, all animals will drop bones on death") public static boolean shouldDropBones = true; @Comment("When enabled, logs harvested with a saw tool will automatically drop planks. You might want to disable this if you have, for instance, modified the plank recipe") public static boolean shouldSawLogs = true; @Comment("When shouldSawLogs is enabled, this modifies how many planks are dropped when a log is sawed, maximum of 4") public static int planksToSaw = 4; } }
UTF-8
Java
1,388
java
ConfigHandler.java
Java
[]
null
[]
package com.thepoptartcrpr.culinary.handlers; import com.thepoptartcrpr.culinary.Culinary; import net.minecraftforge.common.config.Config; import net.minecraftforge.common.config.Config.Comment; import net.minecraftforge.common.config.Config.Type; import net.minecraftforge.common.config.ConfigManager; import net.minecraftforge.fml.client.event.ConfigChangedEvent; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; public class ConfigHandler { @SubscribeEvent public void onConfigChangedEvent(ConfigChangedEvent.OnConfigChangedEvent event) { if (event.getModID().equals(Culinary.Reference.MODID)) ConfigManager.sync(Culinary.Reference.MODID, Config.Type.INSTANCE); } @Config(modid = Culinary.Reference.MODID, type = Type.INSTANCE, name = Culinary.Reference.NAME) public static class CONFIG { @Comment("When enabled, all animals will drop bones on death") public static boolean shouldDropBones = true; @Comment("When enabled, logs harvested with a saw tool will automatically drop planks. You might want to disable this if you have, for instance, modified the plank recipe") public static boolean shouldSawLogs = true; @Comment("When shouldSawLogs is enabled, this modifies how many planks are dropped when a log is sawed, maximum of 4") public static int planksToSaw = 4; } }
1,388
0.764409
0.762968
28
48.57143
44.031994
180
false
false
0
0
0
0
0
0
0.75
false
false
10
061533f55638b323953b30cc3d8c66406dcaa7ed
38,697,655,362,876
11c6da5632f40c4f697606f3e1b7ce9e64c1d4de
/week-11/day-3/Extension/test/ExtensionTest.java
8012067e3c29c4203d28a2d96e9ae0771cb9a2d2
[]
no_license
green-fox-academy/ZetenyiEmese
https://github.com/green-fox-academy/ZetenyiEmese
37546b7627e5d64f95cfd3d16c787a54844d3956
ca523b132dba58170eec31e8afd17f924d17f21e
refs/heads/master
2020-03-31T17:04:08.179000
2019-05-08T19:20:14
2019-05-08T19:20:14
152,404,237
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
import org.junit.Test; import java.util.Arrays; import static org.junit.Assert.*; public class ExtensionTest { private Extension extension = new Extension(); @Test public void testAdd_2and3is5() { assertEquals(5, extension.add(2, 3)); } @Test public void testAdd_1and4is5() { assertEquals(5, extension.add(1, 4)); } @Test public void testAdd_3and4is7() { assertEquals(7, extension.add(3, 4)); } @Test public void testMaxOfThree_first() { assertEquals(5, extension.maxOfThree(5, 4, 3)); } @Test public void testMaxOfThree_second() { assertEquals(5, extension.maxOfThree(3, 5, 4)); } @Test public void testMaxOfThree_third() { assertEquals(5, extension.maxOfThree(3, 4, 5)); } @Test public void testMaxOfThree_With_Zeros() { assertEquals(0, extension.maxOfThree(0, 0, 0)); } @Test public void testMedian_one() { assertEquals(5, extension.median(Arrays.asList(5))); } @Test public void testMedian_two() { assertEquals(7, extension.median(Arrays.asList(7, 8))); } @Test public void testMedian_four() { assertEquals(2, extension.median(Arrays.asList(1,2,3,4))); } @Test public void testMedian_five() { assertEquals(3, extension.median(Arrays.asList(1,2,3,4,5))); } @Test public void testMedian_empty() { assertEquals(0, extension.median(Arrays.asList())); } @Test public void testMedian_null() { assertEquals(0, extension.median(null)); } @Test public void testIsVowel_a() { assertTrue(extension.isVowel('a')); } @Test public void testIsVowel_u() { assertTrue(extension.isVowel('u')); } @Test public void testTranslate_bemutatkozik() { assertEquals("bevemuvutavatkovozivik", extension.translate("bemutatkozik")); } @Test public void testTranslate_lagopus() { assertEquals("lavagovopuvus", extension.translate("lagopus")); } @Test public void testTranslate_alma() { assertEquals("avalmava", extension.translate("alma")); } @Test public void testTranslate_akar() { assertEquals("avakavar", extension.translate("akar")); } @Test public void testTranslate_a() { assertEquals("ava", extension.translate("a")); } @Test public void testTranslate_aa() { assertEquals("avaava", extension.translate("aa")); } @Test public void testTranslate_aaaa() { assertEquals("avaavaavaava", extension.translate("aaaa")); } @Test public void testTranslate_Empty() { assertEquals("", extension.translate("")); } @Test public void testTranslate_Null() { assertEquals("", extension.translate(null)); } }
UTF-8
Java
2,887
java
ExtensionTest.java
Java
[]
null
[]
import org.junit.Test; import java.util.Arrays; import static org.junit.Assert.*; public class ExtensionTest { private Extension extension = new Extension(); @Test public void testAdd_2and3is5() { assertEquals(5, extension.add(2, 3)); } @Test public void testAdd_1and4is5() { assertEquals(5, extension.add(1, 4)); } @Test public void testAdd_3and4is7() { assertEquals(7, extension.add(3, 4)); } @Test public void testMaxOfThree_first() { assertEquals(5, extension.maxOfThree(5, 4, 3)); } @Test public void testMaxOfThree_second() { assertEquals(5, extension.maxOfThree(3, 5, 4)); } @Test public void testMaxOfThree_third() { assertEquals(5, extension.maxOfThree(3, 4, 5)); } @Test public void testMaxOfThree_With_Zeros() { assertEquals(0, extension.maxOfThree(0, 0, 0)); } @Test public void testMedian_one() { assertEquals(5, extension.median(Arrays.asList(5))); } @Test public void testMedian_two() { assertEquals(7, extension.median(Arrays.asList(7, 8))); } @Test public void testMedian_four() { assertEquals(2, extension.median(Arrays.asList(1,2,3,4))); } @Test public void testMedian_five() { assertEquals(3, extension.median(Arrays.asList(1,2,3,4,5))); } @Test public void testMedian_empty() { assertEquals(0, extension.median(Arrays.asList())); } @Test public void testMedian_null() { assertEquals(0, extension.median(null)); } @Test public void testIsVowel_a() { assertTrue(extension.isVowel('a')); } @Test public void testIsVowel_u() { assertTrue(extension.isVowel('u')); } @Test public void testTranslate_bemutatkozik() { assertEquals("bevemuvutavatkovozivik", extension.translate("bemutatkozik")); } @Test public void testTranslate_lagopus() { assertEquals("lavagovopuvus", extension.translate("lagopus")); } @Test public void testTranslate_alma() { assertEquals("avalmava", extension.translate("alma")); } @Test public void testTranslate_akar() { assertEquals("avakavar", extension.translate("akar")); } @Test public void testTranslate_a() { assertEquals("ava", extension.translate("a")); } @Test public void testTranslate_aa() { assertEquals("avaava", extension.translate("aa")); } @Test public void testTranslate_aaaa() { assertEquals("avaavaavaava", extension.translate("aaaa")); } @Test public void testTranslate_Empty() { assertEquals("", extension.translate("")); } @Test public void testTranslate_Null() { assertEquals("", extension.translate(null)); } }
2,887
0.607205
0.589193
131
21.038168
22.048664
84
false
false
0
0
0
0
0
0
0.526718
false
false
10
5192ae9429d25aa3ce383b55ba30de96cbd7eb7c
38,697,655,364,294
79450b181f708c8a69d897fb9ac29bf8206756a9
/app/src/main/java/kim/gaeun/bookworm/model/BookSummary.java
6413d1ba52f063dd3b0a1859295e4ff56a3c8dc1
[]
no_license
wonderemily12/bookworm
https://github.com/wonderemily12/bookworm
dcced879deb8d35deb4ef1cd15f24c59cbf49937
7415668cf9303b46ea4f2e05c8b2591596a1c17a
refs/heads/master
2020-03-24T13:42:41.832000
2018-08-05T14:33:06
2018-08-05T14:33:06
142,749,790
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package kim.gaeun.bookworm.model; public class BookSummary { private String title; private String author; private String thumbnailUrl; private float rating; public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public String getThumbnailUrl() { return thumbnailUrl; } public void setThumbnailUrl(String thumbnailUrl) { this.thumbnailUrl = thumbnailUrl; } public float getRating() { return rating; } public void setRating(float rating) { this.rating = rating; } }
UTF-8
Java
772
java
BookSummary.java
Java
[]
null
[]
package kim.gaeun.bookworm.model; public class BookSummary { private String title; private String author; private String thumbnailUrl; private float rating; public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public String getThumbnailUrl() { return thumbnailUrl; } public void setThumbnailUrl(String thumbnailUrl) { this.thumbnailUrl = thumbnailUrl; } public float getRating() { return rating; } public void setRating(float rating) { this.rating = rating; } }
772
0.619171
0.619171
40
18.299999
15.729272
54
false
false
0
0
0
0
0
0
0.325
false
false
10
cbebccd761a52032ffbfac9d4b5ebba99646ef41
36,464,272,387,796
5a67c4cf544b4238f0c685ebd7bf4fa438ed32a9
/15-puzzle/src/pkg15puzzle/FuncComparator.java
54ec8d4df943fa24814f0bf39ce28a2e3d35b7fe
[]
no_license
TasfiaZahin/Artifical-Intelligence-Assignments
https://github.com/TasfiaZahin/Artifical-Intelligence-Assignments
d8c0d1d541e3e5bb2bb5fbbb7ca8b3707fe3b46d
68d82b2c16882c4c4068501e6b41099078b7f7ee
refs/heads/master
2022-11-28T21:54:08.330000
2020-08-03T05:44:26
2020-08-03T05:44:26
284,677,016
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 pkg15puzzle; import java.util.Comparator; import java.util.HashMap; /** * * @author acer */ public class FuncComparator implements Comparator<Board>{ HashMap<Board, Integer> costSoFar; int mode; public FuncComparator(HashMap<Board, Integer> costSoFar, int mode) { this.costSoFar = costSoFar; this.mode = mode; } @Override public int compare(Board b1, Board b2) { int b1value = 0; int b2value = 0; if(mode == 1) { b1value = (int) b1.h1(); b2value = (int) b2.h1(); } else if(mode == 2) { b1value = (int) b1.h2(); b2value = (int) b2.h2(); } else if(mode == 3) { b1value = (int) b1.h3(); b2value = (int) b2.h3(); } else if(mode == 4) { b1value = (int) b1.h4(); b2value = (int) b2.h4(); } else if(mode == 5) { b1value = (int) b1.h5(); b2value = (int) b2.h5(); } int f1 = (int) (costSoFar.get(b1) + b1value); System.out.println("printing t in comparefunc\n"); b1.show(); System.out.println(f1); System.out.println("end printing t\n"); int f2 = (int) (costSoFar.get(b2) + b2value); System.out.println("printing t1 in comparefunc\n"); b2.show(); System.out.println(f2); System.out.println("end printing t1\n"); //System.out.println("comparing\n"); if(f1 < f2) { return -1; } return 1; } }
UTF-8
Java
1,867
java
FuncComparator.java
Java
[ { "context": "ator;\nimport java.util.HashMap;\n\n/**\n *\n * @author acer\n */\npublic class FuncComparator implements Compar", "end": 285, "score": 0.999550461769104, "start": 281, "tag": "USERNAME", "value": "acer" } ]
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 pkg15puzzle; import java.util.Comparator; import java.util.HashMap; /** * * @author acer */ public class FuncComparator implements Comparator<Board>{ HashMap<Board, Integer> costSoFar; int mode; public FuncComparator(HashMap<Board, Integer> costSoFar, int mode) { this.costSoFar = costSoFar; this.mode = mode; } @Override public int compare(Board b1, Board b2) { int b1value = 0; int b2value = 0; if(mode == 1) { b1value = (int) b1.h1(); b2value = (int) b2.h1(); } else if(mode == 2) { b1value = (int) b1.h2(); b2value = (int) b2.h2(); } else if(mode == 3) { b1value = (int) b1.h3(); b2value = (int) b2.h3(); } else if(mode == 4) { b1value = (int) b1.h4(); b2value = (int) b2.h4(); } else if(mode == 5) { b1value = (int) b1.h5(); b2value = (int) b2.h5(); } int f1 = (int) (costSoFar.get(b1) + b1value); System.out.println("printing t in comparefunc\n"); b1.show(); System.out.println(f1); System.out.println("end printing t\n"); int f2 = (int) (costSoFar.get(b2) + b2value); System.out.println("printing t1 in comparefunc\n"); b2.show(); System.out.println(f2); System.out.println("end printing t1\n"); //System.out.println("comparing\n"); if(f1 < f2) { return -1; } return 1; } }
1,867
0.495447
0.463846
78
22.935898
18.599241
79
false
false
0
0
0
0
0
0
0.5
false
false
10
c066e689f907013b89fcb821b9979b3ce40ba6ac
39,041,252,741,234
ca1030b99a8a84f73c1064228f91f2b0db088aa8
/src/main/java/com/ll/autotransaction/controller/security/CookieWebTokenValueResolver.java
b607f883104bac6cef6454ef8b4498818f8af33e
[]
no_license
923035434/autoTransaction
https://github.com/923035434/autoTransaction
dfecad07e257933db167af4677b1a9eec6e4b823
c5984f8b75ba45a272a383adc7d267bd14d7991d
refs/heads/main
2023-06-11T08:49:19.701000
2021-06-29T06:53:26
2021-06-29T06:53:26
360,383,974
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.ll.autotransaction.controller.security; import lombok.Getter; import lombok.Setter; import org.springframework.util.Assert; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @Getter @Setter public class CookieWebTokenValueResolver implements WebTokenValueResolver { private String name; private String domain; private int maxAge = 1440; private Boolean useSecureCookie; public CookieWebTokenValueResolver(String name, String domain, int maxAge) { Assert.hasText(name, "Cookie name is empty"); Assert.isTrue(maxAge > 0, "Cookie maxAge invalid"); this.name = name; this.domain = domain; this.maxAge = maxAge; } @Override public String getWebTokenValue(HttpServletRequest request) { Cookie[] cookies = request.getCookies(); if ((cookies == null) || (cookies.length == 0)) { return null; } for (Cookie cookie : cookies) { if (name.equals(cookie.getName())) { return cookie.getValue(); } } return null; } @Override public void setWebTokenValue(String tokenValue, HttpServletRequest request, HttpServletResponse response) { Cookie cookie = new Cookie(name, tokenValue); cookie.setPath(getCookiePath(request)); if (domain != null) { cookie.setDomain(domain); } cookie.setMaxAge(maxAge); if (maxAge < 1) { cookie.setVersion(1); } if (useSecureCookie == null) { cookie.setSecure(request.isSecure()); } else { cookie.setSecure(useSecureCookie); } cookie.setHttpOnly(true); response.addCookie(cookie); } @Override public void expireWebTokenValue(HttpServletRequest request, HttpServletResponse response) { Cookie cookie = new Cookie(name, null); cookie.setMaxAge(0); cookie.setPath(getCookiePath(request)); if (domain != null) { cookie.setDomain(domain); } response.addCookie(cookie); } private String getCookiePath(HttpServletRequest request) { // String contextPath = request.getContextPath(); // return contextPath.length() > 0 ? contextPath : "/"; return "/"; } public void setCookieDomain(String cookieDomain) { this.domain = cookieDomain; } public void setUseSecureCookie(Boolean useSecureCookie) { this.useSecureCookie = useSecureCookie; } public void setCookieName(String cookieName) { this.name = cookieName; } }
UTF-8
Java
2,738
java
CookieWebTokenValueResolver.java
Java
[]
null
[]
package com.ll.autotransaction.controller.security; import lombok.Getter; import lombok.Setter; import org.springframework.util.Assert; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @Getter @Setter public class CookieWebTokenValueResolver implements WebTokenValueResolver { private String name; private String domain; private int maxAge = 1440; private Boolean useSecureCookie; public CookieWebTokenValueResolver(String name, String domain, int maxAge) { Assert.hasText(name, "Cookie name is empty"); Assert.isTrue(maxAge > 0, "Cookie maxAge invalid"); this.name = name; this.domain = domain; this.maxAge = maxAge; } @Override public String getWebTokenValue(HttpServletRequest request) { Cookie[] cookies = request.getCookies(); if ((cookies == null) || (cookies.length == 0)) { return null; } for (Cookie cookie : cookies) { if (name.equals(cookie.getName())) { return cookie.getValue(); } } return null; } @Override public void setWebTokenValue(String tokenValue, HttpServletRequest request, HttpServletResponse response) { Cookie cookie = new Cookie(name, tokenValue); cookie.setPath(getCookiePath(request)); if (domain != null) { cookie.setDomain(domain); } cookie.setMaxAge(maxAge); if (maxAge < 1) { cookie.setVersion(1); } if (useSecureCookie == null) { cookie.setSecure(request.isSecure()); } else { cookie.setSecure(useSecureCookie); } cookie.setHttpOnly(true); response.addCookie(cookie); } @Override public void expireWebTokenValue(HttpServletRequest request, HttpServletResponse response) { Cookie cookie = new Cookie(name, null); cookie.setMaxAge(0); cookie.setPath(getCookiePath(request)); if (domain != null) { cookie.setDomain(domain); } response.addCookie(cookie); } private String getCookiePath(HttpServletRequest request) { // String contextPath = request.getContextPath(); // return contextPath.length() > 0 ? contextPath : "/"; return "/"; } public void setCookieDomain(String cookieDomain) { this.domain = cookieDomain; } public void setUseSecureCookie(Boolean useSecureCookie) { this.useSecureCookie = useSecureCookie; } public void setCookieName(String cookieName) { this.name = cookieName; } }
2,738
0.625639
0.621987
100
26.379999
23.199474
95
false
false
0
0
0
0
0
0
0.51
false
false
10
9b707b2b73605a2b277ab4a23999a33585ae386b
16,252,156,299,967
e6f3730f73fb2c921db853834d2e44b23f1b08a4
/src/main/java/fr/tatscher/combatminions/spells/SummonMiner.java
bc6b67ef23a23011d7c94e6a53d36b9a1495c46a
[]
no_license
TaTscher/Addon-Wizardry
https://github.com/TaTscher/Addon-Wizardry
02f02ddbb60c15126a4db250db0fc0a52b7b5241
4ea05f0f214148b81a3da976e6598242f323f98b
refs/heads/master
2022-12-26T10:40:02.863000
2020-09-28T21:55:56
2020-09-28T21:55:56
261,448,404
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package fr.tatscher.combatminions.spells; import electroblob.wizardry.spell.SpellMinion; import electroblob.wizardry.util.SpellModifiers; import fr.tatscher.combatminions.CombatMinions; import fr.tatscher.combatminions.entity.EntityVindicatorMiner; import net.minecraft.entity.EntityLivingBase; import net.minecraft.init.Items; import net.minecraft.inventory.EntityEquipmentSlot; import net.minecraft.item.ItemStack; import net.minecraft.util.math.BlockPos; public class SummonMiner extends SpellMinion<EntityVindicatorMiner> { public SummonMiner() { super(CombatMinions.MODID, "summon_miner", EntityVindicatorMiner::new); } @Override protected void addMinionExtras(EntityVindicatorMiner minion, BlockPos pos, EntityLivingBase caster, SpellModifiers modifiers, int alreadySpawned) { minion.setItemStackToSlot(EntityEquipmentSlot.MAINHAND, new ItemStack(Items.IRON_PICKAXE)); minion.setItemStackToSlot(EntityEquipmentSlot.OFFHAND, new ItemStack(Items.IRON_PICKAXE)); } }
UTF-8
Java
1,017
java
SummonMiner.java
Java
[]
null
[]
package fr.tatscher.combatminions.spells; import electroblob.wizardry.spell.SpellMinion; import electroblob.wizardry.util.SpellModifiers; import fr.tatscher.combatminions.CombatMinions; import fr.tatscher.combatminions.entity.EntityVindicatorMiner; import net.minecraft.entity.EntityLivingBase; import net.minecraft.init.Items; import net.minecraft.inventory.EntityEquipmentSlot; import net.minecraft.item.ItemStack; import net.minecraft.util.math.BlockPos; public class SummonMiner extends SpellMinion<EntityVindicatorMiner> { public SummonMiner() { super(CombatMinions.MODID, "summon_miner", EntityVindicatorMiner::new); } @Override protected void addMinionExtras(EntityVindicatorMiner minion, BlockPos pos, EntityLivingBase caster, SpellModifiers modifiers, int alreadySpawned) { minion.setItemStackToSlot(EntityEquipmentSlot.MAINHAND, new ItemStack(Items.IRON_PICKAXE)); minion.setItemStackToSlot(EntityEquipmentSlot.OFFHAND, new ItemStack(Items.IRON_PICKAXE)); } }
1,017
0.811209
0.811209
23
43.217392
37.210281
151
false
false
0
0
0
0
0
0
0.913043
false
false
10
adf338a0f5f5a84e46c8f92ed3145eda6e37d980
13,073,880,491,825
94151674eda09dbc740dcd5793ad749467a861ee
/ders5/EcommerceMembership/EcommerceMembership/src/EcommerceMembership/core/abstracts/LoginService.java
df17a21efe86eca2a84944ccaecbfc1f955cf3cd
[]
no_license
kongeee/kodlamaioJava
https://github.com/kongeee/kodlamaioJava
35699998a3e8e96d341bf6b5f720aa3e14844d30
af7973304947fd90ddb60767c41dcea499eb8406
refs/heads/master
2023-04-30T17:32:49.973000
2021-05-07T16:00:58
2021-05-07T16:00:58
363,739,144
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package EcommerceMembership.core.abstracts; import EcommerceMembership.entities.concretes.User; public interface LoginService { void loginToSystem(User user); }
UTF-8
Java
164
java
LoginService.java
Java
[]
null
[]
package EcommerceMembership.core.abstracts; import EcommerceMembership.entities.concretes.User; public interface LoginService { void loginToSystem(User user); }
164
0.835366
0.835366
7
22.428572
20.183849
51
false
false
0
0
0
0
0
0
0.571429
false
false
10
048d8877208d50f469e845b88db3ba46b4e747fd
2,508,260,950,166
b07e80c5fc4c6336adcf99d385ab7b88c84f2c39
/server/car-service-core/src/main/java/com/huhuo/carservicecore/cust/car/DaoCar.java
a0227b2d45a30d86432e8156c514c5032bc9b2e6
[]
no_license
Becker365/car-rental
https://github.com/Becker365/car-rental
a34ebe6cbaaf20ca7bdd46b1d89700967c6b69a0
a360c9eec844f9dcf95d52c5e73d8b1b2213b140
refs/heads/main
2023-04-10T06:12:56.023000
2020-12-26T14:43:40
2020-12-26T14:43:40
361,785,498
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.huhuo.carservicecore.cust.car; import org.springframework.stereotype.Repository; import com.huhuo.carservicecore.db.GenericBaseExtenseDao; @Repository("carservicecoreDaoCar") public class DaoCar extends GenericBaseExtenseDao<ModelCar> implements IDaoCar { @Override public String getTableName() { return "cust_car"; } @Override public Class<ModelCar> getModelClazz() { return ModelCar.class; } }
UTF-8
Java
424
java
DaoCar.java
Java
[]
null
[]
package com.huhuo.carservicecore.cust.car; import org.springframework.stereotype.Repository; import com.huhuo.carservicecore.db.GenericBaseExtenseDao; @Repository("carservicecoreDaoCar") public class DaoCar extends GenericBaseExtenseDao<ModelCar> implements IDaoCar { @Override public String getTableName() { return "cust_car"; } @Override public Class<ModelCar> getModelClazz() { return ModelCar.class; } }
424
0.790094
0.790094
20
20.200001
23.135687
80
false
false
0
0
0
0
0
0
0.75
false
false
10
5fe5a66c051e6e72e137b6d561e45d5ea110a50e
30,545,807,464,261
a773335d26fc35135dd9b3fa6a246428c9d4891d
/solution/src/test/java/br/com/geocab/tests/entity/PhotoAlbumTest.java
64cd6f351b96064e91a55cda37468dfcc65da3bf
[]
no_license
itaipubinacional/geocab
https://github.com/itaipubinacional/geocab
eaae7c5661afa3d6eb429265f1a7db6f3b35213a
fdfba83e44c83580c8ef32ca34e91d4c66118ee2
refs/heads/master
2021-03-16T05:04:52.808000
2018-02-28T13:37:05
2018-02-28T13:37:05
22,929,544
8
5
null
false
2018-01-16T10:24:27
2014-08-13T20:06:29
2016-10-24T16:59:53
2018-01-16T10:24:27
420,175
7
9
64
JavaScript
false
null
package br.com.geocab.tests.entity; import org.junit.Test; import com.vividsolutions.jts.util.Assert; import br.com.geocab.domain.entity.marker.Marker; import br.com.geocab.domain.entity.marker.MarkerAttribute; import br.com.geocab.domain.entity.marker.photo.Photo; import br.com.geocab.domain.entity.marker.photo.PhotoAlbum; /** * * @author emanuelvictor * */ public class PhotoAlbumTest { /*------------------------------------------------------------------- * ATTRIBUTES *-------------------------------------------------------------------*/ /*------------------------------------------------------------------- * TESTS *-------------------------------------------------------------------*/ @Test public void testGenerateIdentifierPhotoAlbumWithOutPhotoFolder() { Marker marker = new Marker(100L); MarkerAttribute markerAttribute = new MarkerAttribute(200L); markerAttribute.setMarker(marker); PhotoAlbum photoAlbum = new PhotoAlbum(300L); photoAlbum.setMarkerAttribute(markerAttribute); Assert.equals("/markers/100/albuns/300/photos", photoAlbum.getIdentifier()); } @Test public void testGetIdentifierPhoto() { Marker marker = new Marker(100L); MarkerAttribute attribute = new MarkerAttribute(200L); attribute.setMarker(marker); PhotoAlbum photoAlbum = new PhotoAlbum(300L); photoAlbum.setMarkerAttribute(attribute); Photo photo = new Photo(400L); photo.setPhotoAlbum(photoAlbum); Assert.equals("/markers/100/albuns/300/photos/400", photo.getIdentifier()); } }
UTF-8
Java
1,560
java
PhotoAlbumTest.java
Java
[ { "context": "ntity.marker.photo.PhotoAlbum;\n\n/**\n * \n * @author emanuelvictor\n *\n */\npublic class PhotoAlbumTest\n{\n\t/*---------", "end": 362, "score": 0.9988271594047546, "start": 349, "tag": "USERNAME", "value": "emanuelvictor" } ]
null
[]
package br.com.geocab.tests.entity; import org.junit.Test; import com.vividsolutions.jts.util.Assert; import br.com.geocab.domain.entity.marker.Marker; import br.com.geocab.domain.entity.marker.MarkerAttribute; import br.com.geocab.domain.entity.marker.photo.Photo; import br.com.geocab.domain.entity.marker.photo.PhotoAlbum; /** * * @author emanuelvictor * */ public class PhotoAlbumTest { /*------------------------------------------------------------------- * ATTRIBUTES *-------------------------------------------------------------------*/ /*------------------------------------------------------------------- * TESTS *-------------------------------------------------------------------*/ @Test public void testGenerateIdentifierPhotoAlbumWithOutPhotoFolder() { Marker marker = new Marker(100L); MarkerAttribute markerAttribute = new MarkerAttribute(200L); markerAttribute.setMarker(marker); PhotoAlbum photoAlbum = new PhotoAlbum(300L); photoAlbum.setMarkerAttribute(markerAttribute); Assert.equals("/markers/100/albuns/300/photos", photoAlbum.getIdentifier()); } @Test public void testGetIdentifierPhoto() { Marker marker = new Marker(100L); MarkerAttribute attribute = new MarkerAttribute(200L); attribute.setMarker(marker); PhotoAlbum photoAlbum = new PhotoAlbum(300L); photoAlbum.setMarkerAttribute(attribute); Photo photo = new Photo(400L); photo.setPhotoAlbum(photoAlbum); Assert.equals("/markers/100/albuns/300/photos/400", photo.getIdentifier()); } }
1,560
0.610256
0.587179
60
25
26.10364
78
false
false
0
0
0
0
0
0
1.366667
false
false
10
367ab6c600cb6ee5357d4ba012c46882169baca1
16,501,264,419,444
072a850d7bcd0d836b5f7e44b0149f8c7a174457
/src/main/java/com/spacex/concurrent/countdown/converter/ConvertTask.java
e7c546fb3fa80d87b0b8ddb6513adc791dc65d09
[]
no_license
wolfbang/spacex-flask
https://github.com/wolfbang/spacex-flask
70ef06864032909fc079352a84454280d9c8b75f
619631c99f5475ef57a07029baddb4233fe79968
refs/heads/master
2020-03-21T00:48:56.561000
2018-10-09T14:45:48
2018-10-09T14:45:48
137,911,133
0
0
null
false
2018-10-09T14:50:49
2018-06-19T15:31:51
2018-10-09T14:45:51
2018-10-09T14:50:55
114
0
0
1
Java
false
null
package com.spacex.concurrent.countdown.converter; import java.util.concurrent.Callable; import java.util.concurrent.CountDownLatch; public abstract class ConvertTask implements Callable<String> { private final CountDownLatch latch; private String value; public ConvertTask(CountDownLatch latch, String value) { this.latch = latch; this.value = value; } @Override public String call() { value = convert(value); latch.countDown(); return value; } protected abstract String convert(String value); }
UTF-8
Java
575
java
ConvertTask.java
Java
[]
null
[]
package com.spacex.concurrent.countdown.converter; import java.util.concurrent.Callable; import java.util.concurrent.CountDownLatch; public abstract class ConvertTask implements Callable<String> { private final CountDownLatch latch; private String value; public ConvertTask(CountDownLatch latch, String value) { this.latch = latch; this.value = value; } @Override public String call() { value = convert(value); latch.countDown(); return value; } protected abstract String convert(String value); }
575
0.693913
0.693913
24
22.958334
20.329533
63
false
false
0
0
0
0
0
0
0.5
false
false
10
b098af6d09fb438ac5634fb95df75a5038a8ce66
27,522,150,468,461
674ae17357796a2de81f7eb5446c8a338b3f7001
/parser/SQLtoXMLParser/src/constants/SortType.java
df540863eda3b175799711f5e2ceff0963b8bd54
[]
no_license
gellaho/thesis
https://github.com/gellaho/thesis
3ff770c38c9a9e8d4df426bd01d00f7027aa099a
90fa700d9b089fdf15d6a6f2f1eec97bb331f114
refs/heads/master
2019-04-29T17:43:23.227000
2015-08-28T00:52:07
2015-08-28T00:52:07
25,550,458
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * */ package constants; /** * @author Jamie Gordon * */ public enum SortType { ASC, DESC }
UTF-8
Java
115
java
SortType.java
Java
[ { "context": "*\r\n * \r\n */\r\npackage constants;\r\n\r\n/**\r\n * @author Jamie Gordon\r\n *\r\n */\r\npublic enum SortType {\r\n\tASC, DESC\r\n}\r\n", "end": 65, "score": 0.9998247623443604, "start": 53, "tag": "NAME", "value": "Jamie Gordon" } ]
null
[]
/** * */ package constants; /** * @author <NAME> * */ public enum SortType { ASC, DESC }
109
0.504348
0.504348
12
7.583333
8.149216
23
false
false
0
0
0
0
0
0
0.25
false
false
10
0d7e1a1a17d67f1fa898b5a5dd3e8846bcab623b
37,185,826,883,102
64bbf74f3eb6448aae6485c3ab80375f67f6071e
/addOns/exim/src/main/java/org/zaproxy/addon/exim/PopupMenuExportMessages.java
1473d10a0b3d69b026682497563e1b7c5068d20b
[ "Apache-2.0" ]
permissive
zaproxy/zap-extensions
https://github.com/zaproxy/zap-extensions
0ce06cd939b5c2b4183c0ccb399b625d1674667a
ed8f0469cd7ed4bfcafda99849736ab138942861
refs/heads/main
2023-08-25T05:10:57.321000
2023-08-24T13:50:37
2023-08-24T13:50:37
35,210,580
790
977
Apache-2.0
false
2023-09-14T18:48:40
2015-05-07T09:17:13
2023-09-10T12:39:24
2023-09-14T18:48:39
960,038
759
656
33
Java
false
false
/* * Zed Attack Proxy (ZAP) and its related class files. * * ZAP is an HTTP/HTTPS proxy for assessing web application security. * * Copyright 2022 The ZAP Development Team * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.zaproxy.addon.exim; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.List; import javax.swing.JFileChooser; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.parosproxy.paros.Constant; import org.parosproxy.paros.extension.history.ExtensionHistory; import org.parosproxy.paros.model.HistoryReference; import org.parosproxy.paros.network.HttpMessage; import org.zaproxy.zap.utils.Stats; import org.zaproxy.zap.view.widgets.WritableFileChooser; @SuppressWarnings("serial") public class PopupMenuExportMessages extends JMenuItem { private static final long serialVersionUID = 1L; private static final String NEWLINE = "\n"; private static final Logger LOGGER = LogManager.getLogger(PopupMenuExportMessages.class); private static final String STATS_EXPORT_MESSAGES = ExtensionExim.STATS_PREFIX + "export.messages"; private static final String STATS_EXPORT_MESSAGES_ERROR = ExtensionExim.STATS_PREFIX + "export.messages.error"; private ExtensionHistory extension; public PopupMenuExportMessages(ExtensionHistory extension, boolean responsesOnly) { if (responsesOnly) { setText(Constant.messages.getString("exim.menu.export.responses.popup")); } else { setText(Constant.messages.getString("exim.menu.export.messages.popup")); } this.extension = extension; this.addActionListener( e -> { List<HistoryReference> hrefs = extension.getSelectedHistoryReferences(); if (hrefs.isEmpty()) { extension .getView() .showWarningDialog( Constant.messages.getString( "exim.menu.export.messages.select.warning")); return; } File file = getOutputFile(); if (file == null) { return; } boolean append = true; if (file.exists()) { int rc = extension .getView() .showYesNoCancelDialog( Constant.messages.getString( "file.overwrite.warning")); if (rc == JOptionPane.CANCEL_OPTION) { return; } else if (rc == JOptionPane.YES_OPTION) { append = false; } } try (BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file, append)); ) { for (HistoryReference href : hrefs) { HttpMessage msg = null; msg = href.getHttpMessage(); exportHistory(msg, bos, responsesOnly); } } catch (Exception e1) { extension .getView() .showWarningDialog( Constant.messages.getString("file.save.error") + file.getAbsolutePath() + "."); LOGGER.warn(e1.getMessage(), e1); } }); } private void exportHistory(HttpMessage msg, BufferedOutputStream bos, boolean responsesOnly) { try { if (responsesOnly) { if (!msg.getResponseHeader().isEmpty()) { bos.write(NEWLINE.getBytes()); writeDelimiter(bos, String.valueOf(msg.getHistoryRef().getHistoryId())); bos.write(msg.getResponseBody().getBytes()); } } else { writeDelimiter(bos, String.valueOf(msg.getHistoryRef().getHistoryId())); bos.write(msg.getRequestHeader().toString().getBytes()); String body = msg.getRequestBody().toString(); bos.write(body.getBytes()); if (!body.endsWith(NEWLINE)) { bos.write(NEWLINE.getBytes()); } if (!msg.getResponseHeader().isEmpty()) { bos.write(msg.getResponseHeader().toString().getBytes()); body = msg.getResponseBody().toString(); bos.write(body.getBytes()); if (!body.endsWith(NEWLINE)) { bos.write(NEWLINE.getBytes()); } } } Stats.incCounter(STATS_EXPORT_MESSAGES); } catch (Exception e) { LOGGER.warn(e.getMessage(), e); Stats.incCounter(STATS_EXPORT_MESSAGES_ERROR); } } private void writeDelimiter(BufferedOutputStream bos, String id) throws IOException { bos.write("==== ".getBytes()); bos.write(id.getBytes()); bos.write(" ==========".getBytes()); bos.write(NEWLINE.getBytes()); } private File getOutputFile() { String filename = "untitled.txt"; JFileChooser chooser = new WritableFileChooser(extension.getModel().getOptionsParam().getUserDirectory()); if (filename.length() > 0) { chooser.setSelectedFile(new File(filename)); } File file = null; int rc = chooser.showSaveDialog(extension.getView().getMainFrame()); if (rc == JFileChooser.APPROVE_OPTION) { file = chooser.getSelectedFile(); if (file == null) { return file; } return file; } return file; } }
UTF-8
Java
6,953
java
PopupMenuExportMessages.java
Java
[]
null
[]
/* * Zed Attack Proxy (ZAP) and its related class files. * * ZAP is an HTTP/HTTPS proxy for assessing web application security. * * Copyright 2022 The ZAP Development Team * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.zaproxy.addon.exim; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.List; import javax.swing.JFileChooser; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.parosproxy.paros.Constant; import org.parosproxy.paros.extension.history.ExtensionHistory; import org.parosproxy.paros.model.HistoryReference; import org.parosproxy.paros.network.HttpMessage; import org.zaproxy.zap.utils.Stats; import org.zaproxy.zap.view.widgets.WritableFileChooser; @SuppressWarnings("serial") public class PopupMenuExportMessages extends JMenuItem { private static final long serialVersionUID = 1L; private static final String NEWLINE = "\n"; private static final Logger LOGGER = LogManager.getLogger(PopupMenuExportMessages.class); private static final String STATS_EXPORT_MESSAGES = ExtensionExim.STATS_PREFIX + "export.messages"; private static final String STATS_EXPORT_MESSAGES_ERROR = ExtensionExim.STATS_PREFIX + "export.messages.error"; private ExtensionHistory extension; public PopupMenuExportMessages(ExtensionHistory extension, boolean responsesOnly) { if (responsesOnly) { setText(Constant.messages.getString("exim.menu.export.responses.popup")); } else { setText(Constant.messages.getString("exim.menu.export.messages.popup")); } this.extension = extension; this.addActionListener( e -> { List<HistoryReference> hrefs = extension.getSelectedHistoryReferences(); if (hrefs.isEmpty()) { extension .getView() .showWarningDialog( Constant.messages.getString( "exim.menu.export.messages.select.warning")); return; } File file = getOutputFile(); if (file == null) { return; } boolean append = true; if (file.exists()) { int rc = extension .getView() .showYesNoCancelDialog( Constant.messages.getString( "file.overwrite.warning")); if (rc == JOptionPane.CANCEL_OPTION) { return; } else if (rc == JOptionPane.YES_OPTION) { append = false; } } try (BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file, append)); ) { for (HistoryReference href : hrefs) { HttpMessage msg = null; msg = href.getHttpMessage(); exportHistory(msg, bos, responsesOnly); } } catch (Exception e1) { extension .getView() .showWarningDialog( Constant.messages.getString("file.save.error") + file.getAbsolutePath() + "."); LOGGER.warn(e1.getMessage(), e1); } }); } private void exportHistory(HttpMessage msg, BufferedOutputStream bos, boolean responsesOnly) { try { if (responsesOnly) { if (!msg.getResponseHeader().isEmpty()) { bos.write(NEWLINE.getBytes()); writeDelimiter(bos, String.valueOf(msg.getHistoryRef().getHistoryId())); bos.write(msg.getResponseBody().getBytes()); } } else { writeDelimiter(bos, String.valueOf(msg.getHistoryRef().getHistoryId())); bos.write(msg.getRequestHeader().toString().getBytes()); String body = msg.getRequestBody().toString(); bos.write(body.getBytes()); if (!body.endsWith(NEWLINE)) { bos.write(NEWLINE.getBytes()); } if (!msg.getResponseHeader().isEmpty()) { bos.write(msg.getResponseHeader().toString().getBytes()); body = msg.getResponseBody().toString(); bos.write(body.getBytes()); if (!body.endsWith(NEWLINE)) { bos.write(NEWLINE.getBytes()); } } } Stats.incCounter(STATS_EXPORT_MESSAGES); } catch (Exception e) { LOGGER.warn(e.getMessage(), e); Stats.incCounter(STATS_EXPORT_MESSAGES_ERROR); } } private void writeDelimiter(BufferedOutputStream bos, String id) throws IOException { bos.write("==== ".getBytes()); bos.write(id.getBytes()); bos.write(" ==========".getBytes()); bos.write(NEWLINE.getBytes()); } private File getOutputFile() { String filename = "untitled.txt"; JFileChooser chooser = new WritableFileChooser(extension.getModel().getOptionsParam().getUserDirectory()); if (filename.length() > 0) { chooser.setSelectedFile(new File(filename)); } File file = null; int rc = chooser.showSaveDialog(extension.getView().getMainFrame()); if (rc == JFileChooser.APPROVE_OPTION) { file = chooser.getSelectedFile(); if (file == null) { return file; } return file; } return file; } }
6,953
0.532432
0.530275
178
38.061798
26.579573
99
false
false
0
0
0
0
0
0
0.483146
false
false
10
3431818700303b8634b588cd08acd49667308153
8,761,733,350,165
096573e96b775364ec0c212f7b2263c3af8d56b9
/src/main/java/com/mtg/examples/mongo/daos/UserDaoMongoImpl.java
0b945838712741ea5754572dad26aed2d649a5f6
[ "MIT" ]
permissive
ekovshilovsky/mongo_java
https://github.com/ekovshilovsky/mongo_java
0bd1c933d84a355256b1695a1c4077e580950103
4cbca3b5cbfab86dc8a9703a382824a0111d3247
refs/heads/master
2021-01-01T18:37:47.248000
2013-06-07T23:52:22
2013-06-07T23:52:22
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.mtg.examples.mongo.daos; import java.util.List; import org.bson.types.ObjectId; import org.springframework.beans.factory.annotation.Autowired; import com.mtg.examples.mongo.dto.User; import com.mtg.examples.mongo.repository.UserRepository; /** * */ public class UserDaoMongoImpl implements UserDao { @Autowired private UserRepository userRepository; @Override public User find(String userID) { return find(new ObjectId(userID)); } @Override public User find(ObjectId userID) { return userRepository.get(userID); } @Override public User save(User user) { userRepository.save(user); return user; } @Override public List<User> findAll() { return userRepository.findAll(); } }
UTF-8
Java
840
java
UserDaoMongoImpl.java
Java
[]
null
[]
package com.mtg.examples.mongo.daos; import java.util.List; import org.bson.types.ObjectId; import org.springframework.beans.factory.annotation.Autowired; import com.mtg.examples.mongo.dto.User; import com.mtg.examples.mongo.repository.UserRepository; /** * */ public class UserDaoMongoImpl implements UserDao { @Autowired private UserRepository userRepository; @Override public User find(String userID) { return find(new ObjectId(userID)); } @Override public User find(ObjectId userID) { return userRepository.get(userID); } @Override public User save(User user) { userRepository.save(user); return user; } @Override public List<User> findAll() { return userRepository.findAll(); } }
840
0.645238
0.645238
39
19.538462
18.833748
62
false
false
0
0
0
0
0
0
0.307692
false
false
10
2013e948afaf43c3b32634f735a50113926bb5b4
36,103,495,133,476
8bba5cad5a613188a0b628e8bf3612b0beeb5dfb
/0-Uygulamalar/oyuncak-fabrikasฤฑ/Arac.java
27200a87bc095b7782acb540ac902d12ac710a34
[]
no_license
subratcall/JAVA-PROGRAMMING-1
https://github.com/subratcall/JAVA-PROGRAMMING-1
1f250602cc3588452390ed5405ee54d2324e8ebb
ddefb9ca3fd1818aad1910ed6649a33ea7cfee32
refs/heads/main
2023-02-01T22:26:26.033000
2020-12-22T20:50:17
2020-12-22T20:50:17
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
public interface Arac { void hareketeGec(); void hizlan(int hiz); }
UTF-8
Java
82
java
Arac.java
Java
[]
null
[]
public interface Arac { void hareketeGec(); void hizlan(int hiz); }
82
0.609756
0.609756
6
11.333333
10.370899
23
false
false
0
0
0
0
0
0
1
false
false
10
faf181d55e1afbb98bf014616088e809bfc242f0
11,304,353,934,937
6f4abd6058ef11cc52d138c44f03a6e13529b53f
/app/src/main/java/com/emi/emireading/ui/setting/ProfessionalModeActivity.java
553ed13034b721caf0e7d9872f284e0480896033
[]
no_license
jenkinsZhou/EmiReading
https://github.com/jenkinsZhou/EmiReading
c82ca83bea61e67a8830b61d4a7e2d6df9521cea
2a45432c91096968eaba813a14ea4c5cbbddac58
refs/heads/master
2020-08-10T18:58:51.901000
2019-10-11T08:57:53
2019-10-11T08:57:53
214,401,054
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.emi.emireading.ui.setting; import android.content.Context; import android.view.View; import com.emi.emireading.R; import com.emi.emireading.core.BaseActivity; /** * @author :zhoujian * @description : ไธ“ไธšๆจกๅผ * @company :็ฟผ่ฟˆ็ง‘ๆŠ€ * @date 2018ๅนด06ๆœˆ08ๆ—ฅไธŠๅˆ 10:21 * @Email: 971613168@qq.com */ public class ProfessionalModeActivity extends BaseActivity implements View.OnClickListener { private Context mContext; @Override public void onClick(View view) { switch (view.getId()) { case R.id.mivDebug: openActivity(mContext, EmiDebugActivity.class); break; case R.id.mivReadMeterSetting: openActivity(mContext, ReadMeterSettingActivity.class); break; case R.id.mivExportSetting: openActivity(mContext, ExportSettingActivity.class); break; case R.id.mivOtherSetting: openActivity(mContext, OtherSettingActivity.class); break; default: break; } } @Override protected int getContentLayout() { return R.layout.activity_professional_mode; } @Override protected void initIntent() { mContext = this; } @Override protected void initUI() { findViewById(R.id.mivDebug).setOnClickListener(this); findViewById(R.id.mivReadMeterSetting).setOnClickListener(this); findViewById(R.id.mivExportSetting).setOnClickListener(this); findViewById(R.id.mivOtherSetting).setOnClickListener(this); } @Override protected void initData() { } }
UTF-8
Java
1,687
java
ProfessionalModeActivity.java
Java
[ { "context": "mi.emireading.core.BaseActivity;\n\n/**\n * @author :zhoujian\n * @description : ไธ“ไธšๆจกๅผ\n * @company :็ฟผ่ฟˆ็ง‘ๆŠ€\n * @date", "end": 198, "score": 0.9993801116943359, "start": 190, "tag": "USERNAME", "value": "zhoujian" }, { "context": "any :็ฟผ่ฟˆ็ง‘ๆŠ€\n * @date 2018ๅนด06ๆœˆ08ๆ—ฅไธŠๅˆ 10:21\n * @Email: 971613168@qq.com\n */\n\npublic class ProfessionalModeActivity extend", "end": 296, "score": 0.9998674392700195, "start": 280, "tag": "EMAIL", "value": "971613168@qq.com" } ]
null
[]
package com.emi.emireading.ui.setting; import android.content.Context; import android.view.View; import com.emi.emireading.R; import com.emi.emireading.core.BaseActivity; /** * @author :zhoujian * @description : ไธ“ไธšๆจกๅผ * @company :็ฟผ่ฟˆ็ง‘ๆŠ€ * @date 2018ๅนด06ๆœˆ08ๆ—ฅไธŠๅˆ 10:21 * @Email: <EMAIL> */ public class ProfessionalModeActivity extends BaseActivity implements View.OnClickListener { private Context mContext; @Override public void onClick(View view) { switch (view.getId()) { case R.id.mivDebug: openActivity(mContext, EmiDebugActivity.class); break; case R.id.mivReadMeterSetting: openActivity(mContext, ReadMeterSettingActivity.class); break; case R.id.mivExportSetting: openActivity(mContext, ExportSettingActivity.class); break; case R.id.mivOtherSetting: openActivity(mContext, OtherSettingActivity.class); break; default: break; } } @Override protected int getContentLayout() { return R.layout.activity_professional_mode; } @Override protected void initIntent() { mContext = this; } @Override protected void initUI() { findViewById(R.id.mivDebug).setOnClickListener(this); findViewById(R.id.mivReadMeterSetting).setOnClickListener(this); findViewById(R.id.mivExportSetting).setOnClickListener(this); findViewById(R.id.mivOtherSetting).setOnClickListener(this); } @Override protected void initData() { } }
1,678
0.632751
0.620108
62
25.790323
22.812092
92
false
false
0
0
0
0
0
0
0.403226
false
false
10
7820601c5d623db7a2f425eda30daecebcc58502
3,977,139,733,238
148a7c8731e887847188f99bf062514d7e1620bd
/src/bn/IOๆต่ฏปๅ†™_่ถ…็บง้‡่ฆ_ไปฅๅŽๅฐฑ่ฟ™็ง็”จๆณ•ไบ†/D_OutputStreamWriterๅญ—็ฌฆๆ•ฐ็ป„ๅฝขๅผ.java
5f591d55ff351c92e3f34c196c6a3b7af7ad0135
[ "Apache-2.0" ]
permissive
qingkediguo/-JavaSE-
https://github.com/qingkediguo/-JavaSE-
5659b624818e120c1c86ea7d09499aa1e12601d5
5cd7ec530c0dbebe5456bf057a81454ac969c339
refs/heads/master
2021-09-14T12:38:33.247000
2018-05-14T03:14:18
2018-05-14T03:14:18
111,383,763
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package bn.IOๆต่ฏปๅ†™_่ถ…็บง้‡่ฆ_ไปฅๅŽๅฐฑ่ฟ™็ง็”จๆณ•ไบ†; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; /* * OutputStreamWriter็š„ๆ–นๆณ•๏ผš * public void write(int c):ๅ†™ไธ€ไธชๅญ—็ฌฆ * public void write(char[] cbuf):ๅ†™ไธ€ไธชๅญ—็ฌฆๆ•ฐ็ป„ * public void write(char[] cbuf,int off,int len):ๅ†™ไธ€ไธชๅญ—็ฌฆๆ•ฐ็ป„็š„ไธ€้ƒจๅˆ† * public void write(String str):ๅ†™ไธ€ไธชๅญ—็ฌฆไธฒ * public void write(String str,int off,int len):ๅ†™ไธ€ไธชๅญ—็ฌฆไธฒ็š„ไธ€้ƒจๅˆ† * * ้ข่ฏ•้ข˜๏ผšclose()ๅ’Œflush()็š„ๅŒบๅˆซ? * A:close()ๅ…ณ้—ญๆตๅฏน่ฑก๏ผŒไฝ†ๆ˜ฏๅ…ˆๅˆทๆ–ฐไธ€ๆฌก็ผ“ๅ†ฒๅŒบใ€‚ๅ…ณ้—ญไน‹ๅŽ๏ผŒๆตๅฏน่ฑกไธๅฏไปฅ็ปง็ปญๅ†ไฝฟ็”จไบ†ใ€‚ * B:flush()ไป…ไป…ๅˆทๆ–ฐ็ผ“ๅ†ฒๅŒบ,ๅˆทๆ–ฐไน‹ๅŽ๏ผŒๆตๅฏน่ฑก่ฟ˜ๅฏไปฅ็ปง็ปญไฝฟ็”จใ€‚ */ public class D_OutputStreamWriterๅญ—็ฌฆๆ•ฐ็ป„ๅฝขๅผ { public static void main(String[] args) throws IOException { // ๅˆ›ๅปบๅฏน่ฑก OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream( "osw2.txt")); // ๅ†™ๆ•ฐๆฎ // public void write(int c):ๅ†™ไธ€ไธชๅญ—็ฌฆ // osw.write('a'); // osw.write(97); // ไธบไป€ไนˆๆ•ฐๆฎๆฒกๆœ‰่ฟ›ๅŽปๅ‘ข? // ๅŽŸๅ› ๆ˜ฏ๏ผšๅญ—็ฌฆ = 2ๅญ—่Š‚ // ๆ–‡ไปถไธญๆ•ฐๆฎๅญ˜ๅ‚จ็š„ๅŸบๆœฌๅ•ไฝๆ˜ฏๅญ—่Š‚ใ€‚ // void flush() // public void write(char[] cbuf):ๅ†™ไธ€ไธชๅญ—็ฌฆๆ•ฐ็ป„ // char[] chs = {'a','b','c','d','e'}; // osw.write(chs); // public void write(char[] cbuf,int off,int len):ๅ†™ไธ€ไธชๅญ—็ฌฆๆ•ฐ็ป„็š„ไธ€้ƒจๅˆ† // osw.write(chs,1,3); // public void write(String str):ๅ†™ไธ€ไธชๅญ—็ฌฆไธฒ // osw.write("ๆˆ‘็ˆฑๆž—้’้œž"); // public void write(String str,int off,int len):ๅ†™ไธ€ไธชๅญ—็ฌฆไธฒ็š„ไธ€้ƒจๅˆ† osw.write("ๆˆ‘็ˆฑๆž—้’้œž", 2, 3); // ๅˆทๆ–ฐ็ผ“ๅ†ฒๅŒบ osw.flush(); // osw.write("ๆˆ‘็ˆฑๆž—้’้œž", 2, 3); // ้‡Šๆ”พ่ต„ๆบ osw.close(); // java.io.IOException: Stream closed // osw.write("ๆˆ‘็ˆฑๆž—้’้œž", 2, 3); } }
UTF-8
Java
1,876
java
D_OutputStreamWriterๅญ—็ฌฆๆ•ฐ็ป„ๅฝขๅผ.java
Java
[ { "context": "ing str,int off,int len):ๅ†™ไธ€ไธชๅญ—็ฌฆไธฒ็š„ไธ€้ƒจๅˆ†\n\t\tosw.write(\"ๆˆ‘็ˆฑๆž—้’้œž\", 2, 3);\n\n\t\t// ๅˆทๆ–ฐ็ผ“ๅ†ฒๅŒบ\n\t\tosw.flush();\n\t\t// osw.writ", "end": 1228, "score": 0.578803300857544, "start": 1224, "tag": "NAME", "value": "็ˆฑๆž—้’้œž" }, { "context": "2, 3);\n\n\t\t// ๅˆทๆ–ฐ็ผ“ๅ†ฒๅŒบ\n\t\tosw.flush();\n\t\t// osw.write(\"ๆˆ‘็ˆฑๆž—้’้œž\", 2, 3);\n\n\t\t// ้‡Šๆ”พ่ต„ๆบ\n\t\tosw.close();\n\t\t// java.io.I", "end": 1286, "score": 0.8490723967552185, "start": 1281, "tag": "NAME", "value": "ๆˆ‘็ˆฑๆž—้’้œž" }, { "context": "va.io.IOException: Stream closed\n\t\t// osw.write(\"ๆˆ‘็ˆฑๆž—้’้œž\", 2, 3);\n\t}\n}\n", "end": 1383, "score": 0.8762291073799133, "start": 1379, "tag": "NAME", "value": "็ˆฑๆž—้’้œž" } ]
null
[]
package bn.IOๆต่ฏปๅ†™_่ถ…็บง้‡่ฆ_ไปฅๅŽๅฐฑ่ฟ™็ง็”จๆณ•ไบ†; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; /* * OutputStreamWriter็š„ๆ–นๆณ•๏ผš * public void write(int c):ๅ†™ไธ€ไธชๅญ—็ฌฆ * public void write(char[] cbuf):ๅ†™ไธ€ไธชๅญ—็ฌฆๆ•ฐ็ป„ * public void write(char[] cbuf,int off,int len):ๅ†™ไธ€ไธชๅญ—็ฌฆๆ•ฐ็ป„็š„ไธ€้ƒจๅˆ† * public void write(String str):ๅ†™ไธ€ไธชๅญ—็ฌฆไธฒ * public void write(String str,int off,int len):ๅ†™ไธ€ไธชๅญ—็ฌฆไธฒ็š„ไธ€้ƒจๅˆ† * * ้ข่ฏ•้ข˜๏ผšclose()ๅ’Œflush()็š„ๅŒบๅˆซ? * A:close()ๅ…ณ้—ญๆตๅฏน่ฑก๏ผŒไฝ†ๆ˜ฏๅ…ˆๅˆทๆ–ฐไธ€ๆฌก็ผ“ๅ†ฒๅŒบใ€‚ๅ…ณ้—ญไน‹ๅŽ๏ผŒๆตๅฏน่ฑกไธๅฏไปฅ็ปง็ปญๅ†ไฝฟ็”จไบ†ใ€‚ * B:flush()ไป…ไป…ๅˆทๆ–ฐ็ผ“ๅ†ฒๅŒบ,ๅˆทๆ–ฐไน‹ๅŽ๏ผŒๆตๅฏน่ฑก่ฟ˜ๅฏไปฅ็ปง็ปญไฝฟ็”จใ€‚ */ public class D_OutputStreamWriterๅญ—็ฌฆๆ•ฐ็ป„ๅฝขๅผ { public static void main(String[] args) throws IOException { // ๅˆ›ๅปบๅฏน่ฑก OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream( "osw2.txt")); // ๅ†™ๆ•ฐๆฎ // public void write(int c):ๅ†™ไธ€ไธชๅญ—็ฌฆ // osw.write('a'); // osw.write(97); // ไธบไป€ไนˆๆ•ฐๆฎๆฒกๆœ‰่ฟ›ๅŽปๅ‘ข? // ๅŽŸๅ› ๆ˜ฏ๏ผšๅญ—็ฌฆ = 2ๅญ—่Š‚ // ๆ–‡ไปถไธญๆ•ฐๆฎๅญ˜ๅ‚จ็š„ๅŸบๆœฌๅ•ไฝๆ˜ฏๅญ—่Š‚ใ€‚ // void flush() // public void write(char[] cbuf):ๅ†™ไธ€ไธชๅญ—็ฌฆๆ•ฐ็ป„ // char[] chs = {'a','b','c','d','e'}; // osw.write(chs); // public void write(char[] cbuf,int off,int len):ๅ†™ไธ€ไธชๅญ—็ฌฆๆ•ฐ็ป„็š„ไธ€้ƒจๅˆ† // osw.write(chs,1,3); // public void write(String str):ๅ†™ไธ€ไธชๅญ—็ฌฆไธฒ // osw.write("ๆˆ‘็ˆฑๆž—้’้œž"); // public void write(String str,int off,int len):ๅ†™ไธ€ไธชๅญ—็ฌฆไธฒ็š„ไธ€้ƒจๅˆ† osw.write("ๆˆ‘็ˆฑๆž—้’้œž", 2, 3); // ๅˆทๆ–ฐ็ผ“ๅ†ฒๅŒบ osw.flush(); // osw.write("ๆˆ‘็ˆฑๆž—้’้œž", 2, 3); // ้‡Šๆ”พ่ต„ๆบ osw.close(); // java.io.IOException: Stream closed // osw.write("ๆˆ‘็ˆฑๆž—้’้œž", 2, 3); } }
1,876
0.663805
0.655222
56
23.964285
19.387003
71
false
false
0
0
0
0
0
0
1.696429
false
false
10
adb31ba0244ea4c2e89d9be566b4477a089cfd78
6,270,652,269,108
e3e7c0d706351e7b75d86339696f25f144fe652b
/java_generics_and_collections/special-collections/src/main/java/com/efimchick/ifmo/collections/PairStringList.java
7b24eb0261c0d9839c306eb682b4ea3b48b0f4be
[]
no_license
HakJko/AutocodeEpam
https://github.com/HakJko/AutocodeEpam
22dcbd7b20a6d04785de3ab6fcfc21c9ff032ffd
9e3b9c8ffd57a3a30d2cd93ddd05bcae51dfe2af
refs/heads/main
2023-05-31T21:42:51.139000
2021-07-02T20:33:28
2021-07-02T20:33:28
363,626,646
1
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.efimchick.ifmo.collections; import java.util.*; class PairStringList implements List<String> { private final List<String> LIST = new ArrayList<>(); @Override public int size() { return LIST.size(); } @Override public Iterator<String> iterator() { return LIST.iterator(); } @Override public boolean add(final String str) { for (int i = 0; i < 2; i++) { LIST.add(str); } return true; } @Override public void add(int index, final String elem) { index = correctIndex(index); for (int i = 0; i < 2; i++) { LIST.add(index, elem); } } @Override public boolean remove(final Object obj) { for (int i = 0; i < 2; i++) { LIST.remove(obj); } return true; } @Override public String remove(final int index) { LIST.remove(index); return LIST.remove(getPairIndex(index)); } @Override public boolean addAll(final Collection<? extends String> collect) { for (String string : collect) { add(string); } return true; } @Override public boolean addAll(int index, final Collection<? extends String> collect) { index = correctIndex(index); for (String string : collect) { add(index, string); index = index + 2; } return true; } @Override public String get(final int index) { return LIST.get(index); } @Override public String set(final int index, final String elem) { LIST.set(index, elem); return LIST.set(getPairIndex(index), elem); } @Override public <T> T[] toArray(final T[] array) { return array; } @Override public void clear() { LIST.clear(); } @Override public boolean isEmpty() { return LIST.isEmpty(); } @Override public boolean contains(final Object obj) { return LIST.contains(obj); } @Override public Object[] toArray() { return LIST.toArray(); } @Override public boolean containsAll(final Collection<?> collect) { return LIST.containsAll(collect); } @Override public boolean removeAll(final Collection<?> collect) { throw new UnsupportedOperationException(); } @Override public boolean retainAll(final Collection<?> collect) { throw new UnsupportedOperationException(); } @Override public int indexOf(final Object obj) { throw new UnsupportedOperationException(); } @Override public int lastIndexOf(final Object obj) { throw new UnsupportedOperationException(); } @Override public ListIterator<String> listIterator() { throw new UnsupportedOperationException(); } @Override public ListIterator<String> listIterator(final int index) { throw new UnsupportedOperationException(); } @Override public List<String> subList(final int fromIndex, final int toIndex) { throw new UnsupportedOperationException(); } private int correctIndex(int index) { if (isOdd(index)) { return ++index; } else return index; } private int getPairIndex(int index) { if (isEven(index)) { return ++index; } else { return --index; } } private boolean isEven(final int num) { return (num ^ (num + 1)) == 1; } private boolean isOdd(final int num) { return !isEven(num); } }
UTF-8
Java
3,636
java
PairStringList.java
Java
[]
null
[]
package com.efimchick.ifmo.collections; import java.util.*; class PairStringList implements List<String> { private final List<String> LIST = new ArrayList<>(); @Override public int size() { return LIST.size(); } @Override public Iterator<String> iterator() { return LIST.iterator(); } @Override public boolean add(final String str) { for (int i = 0; i < 2; i++) { LIST.add(str); } return true; } @Override public void add(int index, final String elem) { index = correctIndex(index); for (int i = 0; i < 2; i++) { LIST.add(index, elem); } } @Override public boolean remove(final Object obj) { for (int i = 0; i < 2; i++) { LIST.remove(obj); } return true; } @Override public String remove(final int index) { LIST.remove(index); return LIST.remove(getPairIndex(index)); } @Override public boolean addAll(final Collection<? extends String> collect) { for (String string : collect) { add(string); } return true; } @Override public boolean addAll(int index, final Collection<? extends String> collect) { index = correctIndex(index); for (String string : collect) { add(index, string); index = index + 2; } return true; } @Override public String get(final int index) { return LIST.get(index); } @Override public String set(final int index, final String elem) { LIST.set(index, elem); return LIST.set(getPairIndex(index), elem); } @Override public <T> T[] toArray(final T[] array) { return array; } @Override public void clear() { LIST.clear(); } @Override public boolean isEmpty() { return LIST.isEmpty(); } @Override public boolean contains(final Object obj) { return LIST.contains(obj); } @Override public Object[] toArray() { return LIST.toArray(); } @Override public boolean containsAll(final Collection<?> collect) { return LIST.containsAll(collect); } @Override public boolean removeAll(final Collection<?> collect) { throw new UnsupportedOperationException(); } @Override public boolean retainAll(final Collection<?> collect) { throw new UnsupportedOperationException(); } @Override public int indexOf(final Object obj) { throw new UnsupportedOperationException(); } @Override public int lastIndexOf(final Object obj) { throw new UnsupportedOperationException(); } @Override public ListIterator<String> listIterator() { throw new UnsupportedOperationException(); } @Override public ListIterator<String> listIterator(final int index) { throw new UnsupportedOperationException(); } @Override public List<String> subList(final int fromIndex, final int toIndex) { throw new UnsupportedOperationException(); } private int correctIndex(int index) { if (isOdd(index)) { return ++index; } else return index; } private int getPairIndex(int index) { if (isEven(index)) { return ++index; } else { return --index; } } private boolean isEven(final int num) { return (num ^ (num + 1)) == 1; } private boolean isOdd(final int num) { return !isEven(num); } }
3,636
0.575082
0.572607
164
21.176828
19.310347
82
false
false
0
0
0
0
0
0
0.335366
false
false
10
2fda5a04397a0f493e2eda4ffbcc4e17c4e00d3d
17,016,660,452,759
00153ce86fcf0932c8b88cf0a1a330fa1e9cf6b5
/grant-server/src/main/java/ru/itis/grant/conversion/response/ApplicationToResponseApplicationDtoConverter.java
dd22b8600eaf685c9846cb91669115b3ba9f5bb1
[]
no_license
KarimovKamil/Grant-System
https://github.com/KarimovKamil/Grant-System
ccfc79a27297f86ea2a6443b3bafcac42451b765
ae35579f184c35cfa8558576a0da3707f0d156d6
refs/heads/master
2020-03-23T16:34:47.586000
2018-08-03T16:08:11
2018-08-03T16:08:11
141,818,295
1
0
null
false
2018-08-03T15:41:32
2018-07-21T14:02:53
2018-08-03T09:54:12
2018-08-03T15:41:32
148
0
0
0
Java
false
null
package ru.itis.grant.conversion.response; import ru.itis.grant.dto.response.ResponseApplicationDto; import ru.itis.grant.dto.response.ResponseElementValueDto; import ru.itis.grant.model.Application; import ru.itis.grant.model.ElementValue; import java.util.ArrayList; import java.util.List; public class ApplicationToResponseApplicationDtoConverter { private static volatile ApplicationToResponseApplicationDtoConverter instance; public static ApplicationToResponseApplicationDtoConverter getInstance() { ApplicationToResponseApplicationDtoConverter localInstance = instance; if (localInstance == null) { synchronized (ApplicationToResponseApplicationDtoConverter.class) { localInstance = instance; if (localInstance == null) { instance = localInstance = new ApplicationToResponseApplicationDtoConverter(); } } } return localInstance; } public ResponseApplicationDto convert(Application application) { List<ResponseElementValueDto> responseElementValueDtoList = new ArrayList<>(); for (ElementValue elementValue : application.getValueList()) { responseElementValueDtoList.add(ElementValueToResponseElementValueDtoConverter.getInstance() .convert(elementValue)); } return ResponseApplicationDto.builder() .id(application.getId()) .applicationDate(application.getApplicationDate()) .applicationName(application.getPattern().getApplicationName()) .status(application.getStatus()) .values(responseElementValueDtoList) .comment(application.getComment()) .build(); } }
UTF-8
Java
1,788
java
ApplicationToResponseApplicationDtoConverter.java
Java
[]
null
[]
package ru.itis.grant.conversion.response; import ru.itis.grant.dto.response.ResponseApplicationDto; import ru.itis.grant.dto.response.ResponseElementValueDto; import ru.itis.grant.model.Application; import ru.itis.grant.model.ElementValue; import java.util.ArrayList; import java.util.List; public class ApplicationToResponseApplicationDtoConverter { private static volatile ApplicationToResponseApplicationDtoConverter instance; public static ApplicationToResponseApplicationDtoConverter getInstance() { ApplicationToResponseApplicationDtoConverter localInstance = instance; if (localInstance == null) { synchronized (ApplicationToResponseApplicationDtoConverter.class) { localInstance = instance; if (localInstance == null) { instance = localInstance = new ApplicationToResponseApplicationDtoConverter(); } } } return localInstance; } public ResponseApplicationDto convert(Application application) { List<ResponseElementValueDto> responseElementValueDtoList = new ArrayList<>(); for (ElementValue elementValue : application.getValueList()) { responseElementValueDtoList.add(ElementValueToResponseElementValueDtoConverter.getInstance() .convert(elementValue)); } return ResponseApplicationDto.builder() .id(application.getId()) .applicationDate(application.getApplicationDate()) .applicationName(application.getPattern().getApplicationName()) .status(application.getStatus()) .values(responseElementValueDtoList) .comment(application.getComment()) .build(); } }
1,788
0.690157
0.690157
42
41.595238
29.63995
104
false
false
0
0
0
0
0
0
0.357143
false
false
10
8b9efbcc81330574d90379b77fad8246e4480351
3,942,779,998,509
da596c89572dbcf7f388bd4805e4b4765b5a2af1
/curso-java-basico1/src/pt/andre/variaveis/MediaNotas.java
59e4e91c5630beffbb1b078eb702e377a5f56134
[]
no_license
OliveiraRASO/java.classes
https://github.com/OliveiraRASO/java.classes
9070f3d19d526ed9c330d2e5f4294fa82297b313
81ad4ff0743550841dfd385aabe06707eb24cca9
refs/heads/master
2021-05-22T21:08:47.993000
2020-10-24T15:38:45
2020-10-24T15:38:45
253,096,672
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package pt.andre.variaveis; import java.util.Scanner; public class MediaNotas { public static void main(String[] args) { Scanner teclado = new Scanner(System.in); System.out.print("Digite a primeira nota: "); double nota1 = teclado.nextDouble(); System.out.print("Digite a segunda nota: "); double nota2 = teclado.nextDouble(); System.out.print("Digite a terceira nota: "); double nota3 = teclado.nextDouble(); System.out.print("Digite a quarta nota: "); double nota4 = teclado.nextDouble(); double media = (nota1+nota2+nota3+nota4)/4; System.out.print("A media das notas รฉ: " + media); } }
WINDOWS-1252
Java
640
java
MediaNotas.java
Java
[]
null
[]
package pt.andre.variaveis; import java.util.Scanner; public class MediaNotas { public static void main(String[] args) { Scanner teclado = new Scanner(System.in); System.out.print("Digite a primeira nota: "); double nota1 = teclado.nextDouble(); System.out.print("Digite a segunda nota: "); double nota2 = teclado.nextDouble(); System.out.print("Digite a terceira nota: "); double nota3 = teclado.nextDouble(); System.out.print("Digite a quarta nota: "); double nota4 = teclado.nextDouble(); double media = (nota1+nota2+nota3+nota4)/4; System.out.print("A media das notas รฉ: " + media); } }
640
0.679186
0.665102
27
22.666666
20.079472
52
false
false
0
0
0
0
0
0
1.888889
false
false
10
ba0cbee9599937cf9d4301e4ff59cf91b0948fbb
3,942,779,999,348
25b4a4202d7dce18419c3078c27c14da3c5e7d8a
/Mavsocial/src/test/java/TestCases/EnterpriseuserLogin.java
6d4170dbed6ff5a8a3254b39c0fa5f41d6d2d4f3
[]
no_license
harichandra599/MSframework
https://github.com/harichandra599/MSframework
94fc8c5e9b4ea4481211dc97846f9a03bd97e15b
0957dc4a5a497ba30dfb78e5362cb92f2ced725e
refs/heads/master
2021-12-24T00:33:47.072000
2020-06-18T15:15:50
2020-06-18T15:15:50
179,290,368
0
0
null
false
2021-12-14T20:51:33
2019-04-03T12:57:25
2020-06-18T15:17:53
2021-12-14T20:51:31
69,303
0
0
4
HTML
false
false
package TestCases; import java.io.IOException; import java.lang.reflect.Method; import org.apache.log4j.Logger; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import com.relevantcodes.extentreports.LogStatus; import BusinessFunctions.TestBase; import UiActions.Enterpriseuserobj; import jxl.read.biff.BiffException; public class EnterpriseuserLogin extends TestBase { Enterpriseuserobj ent; public static final Logger log=Logger.getLogger(EnterpriseuserLogin.class.getName()); @BeforeMethod public void openbrowser(Method result) throws Exception { test = extent.startTest(result.getName()); test.log(LogStatus.INFO, result.getName() + " test Started"); init(); wait_for_page_load(5000); } @Test public void executionoder() { } @AfterMethod public void browserclose() throws Exception { closeBrowser(); } }
UTF-8
Java
996
java
EnterpriseuserLogin.java
Java
[]
null
[]
package TestCases; import java.io.IOException; import java.lang.reflect.Method; import org.apache.log4j.Logger; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import com.relevantcodes.extentreports.LogStatus; import BusinessFunctions.TestBase; import UiActions.Enterpriseuserobj; import jxl.read.biff.BiffException; public class EnterpriseuserLogin extends TestBase { Enterpriseuserobj ent; public static final Logger log=Logger.getLogger(EnterpriseuserLogin.class.getName()); @BeforeMethod public void openbrowser(Method result) throws Exception { test = extent.startTest(result.getName()); test.log(LogStatus.INFO, result.getName() + " test Started"); init(); wait_for_page_load(5000); } @Test public void executionoder() { } @AfterMethod public void browserclose() throws Exception { closeBrowser(); } }
996
0.758032
0.753012
40
23.9
21.257704
88
false
false
0
0
0
0
0
0
1.2
false
false
10
845990228b8ed56bcf4275a9448a7439a7aec93e
12,799,002,561,740
1a0481d74f88038bdeb1e7df215ff122fd9fc366
/WorkingWithLegacy/trunk/src/main/java/com/amri/legacy/extract_override_factory_method/WorkflowEngine.java
381869ff46f01c085c289c0bb49743e294a812dd
[]
no_license
amri/WorkingWithLegacy
https://github.com/amri/WorkingWithLegacy
8b8e134d96a228a1e3df401bc982fc656089e9b2
f1d7a31c51c26570003bb38d989beb466ef804c6
refs/heads/master
2021-01-13T02:26:13.912000
2015-09-15T00:41:03
2015-09-15T00:41:03
31,571,013
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.amri.legacy.extract_override_factory_method; //MAIN public class WorkflowEngine { public WorkflowEngine() { this.tm = makeTransactionManager(); } public TransactionManager makeTransactionManager() { Reader reader = new ModelReader(AppConfig.getDryConfiguration()); return new TransactionManager(reader); } private TransactionManager tm; }
UTF-8
Java
383
java
WorkflowEngine.java
Java
[]
null
[]
package com.amri.legacy.extract_override_factory_method; //MAIN public class WorkflowEngine { public WorkflowEngine() { this.tm = makeTransactionManager(); } public TransactionManager makeTransactionManager() { Reader reader = new ModelReader(AppConfig.getDryConfiguration()); return new TransactionManager(reader); } private TransactionManager tm; }
383
0.744125
0.744125
16
21.9375
22.675617
67
false
false
0
0
0
0
0
0
1.0625
false
false
10
670317e1796345aab435e6f5f8adae027de39b80
13,125,420,095,037
bafd8df403148b17112241bea6e8e584d42b482c
/src/main/java/com/ruoyi/project/system/util/CutTimeUtil.java
d8731a7291376b467ccfb012752317c3cab2f226
[ "LicenseRef-scancode-mulanpsl-2.0-en", "MulanPSL-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
Vetch0710/hospital
https://github.com/Vetch0710/hospital
8262a35b9cf978c55378809c5c2fe4cb02df4c8e
15f3594a3e07a2d036a5b5c7f58be2e3a899216e
refs/heads/master
2023-04-12T13:34:51.074000
2021-04-27T06:30:24
2021-04-27T06:30:24
359,290,340
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.ruoyi.project.system.util; /** * @author Vetch * @Description * @create 2021-04-09-9:19 */ import com.ruoyi.framework.config.RuoYiConfig; import org.apache.poi.util.Units; import org.apache.poi.xwpf.usermodel.*; import java.io.*; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; /** * ๅˆ‡ๅ‰ฒๆ—ถ้—ดๅญ—็ฌฆไธฒ * * */ public class CutTimeUtil { /** * Description: ่Žทๅ–ๅœจๆŒ‡ๅฎšๆ—ถ้—ดๅ†…ไปฅๆŒ‡ๅฎšๅˆ†้’Ÿๆฎตๅˆ†ๅ‰ฒ็š„ๆ—ถ้—ด้›†ๅˆ * * @param time ๆŒ‡ๅฎšๆ—ถ้—ด * @param minItem ๆŒ‡ๅฎšๅˆ†้’Ÿๆฎต * @param disableTimes ไธๅŒ…ๅซ็š„ๆ—ถ้—ด * @Return: java.util.List<java.lang.String> * @Date: 2021/04/25 10:45 */ public static List<String> cutTime(String time, int minItem, List<String> disableTimes) { List<String> result = new ArrayList<>(); String[] minItems = getMin(minItem); Map<String, String> times = getTime(time); int startHour = Integer.parseInt(times.get("startHour")); int endHour = Integer.parseInt(times.get("endHour")); int startMin = Integer.parseInt(times.get("startMin")); String endTime = times.get("endTime"); for (int i = startHour; i <= endHour; i++) { for (int j = 0; j < minItems.length; j++) { String temp; if (i == startHour && j == 0) { temp = (startHour == 0 ? "00" : startHour) + ":" + (startMin == 0 ? "00" : startMin); j = startMin / minItem + 1; } else { temp = (i == 0 ? "00" : i) + ":" + minItems[j]; } if (disableTimes != null) { if (!disableTimes.contains(temp)) { result.add(temp); if (temp.equals(endTime)) { break; } } else { if (temp.equals(endTime)) { break; } } } else { result.add(temp); if (temp.equals(endTime)) { break; } } } } return result; } /** * Description: ่Žทๅ–ๆฏๅฐๆ—ถไธญๆŒ‡ๅฎšๅˆ†้’Ÿๆฎตๅˆ†ๅ‰ฒ็š„ๅˆ†้’Ÿ้›†ๅˆ * * @param item ๆŒ‡ๅฎšๅˆ†้’Ÿๆฎต * @Return: java.lang.String[] * @Date: 2021/04/25 10:46 */ public static String[] getMin(int item) { int num = 60 / item; String[] result = new String[num]; result[0] = "00"; for (int i = 1; i < num; i++) { result[i] = String.valueOf(item * i); } return result; } /** * Description: ๅˆ†ๅ‰ฒๆŒ‡ๅฎšๆ—ถ้—ด๏ผŒ่Žทๅ–ๆ—ถ้—ดไฟกๆฏ * * @param time ๆŒ‡ๅฎšๆ—ถ้—ด * @Return: java.util.Map<java.lang.String, java.lang.String> * @Date: 2021/04/25 10:47 */ public static Map<String, String> getTime(String time) { Map<String, String> result = new HashMap<>(); String regex = "[: -]"; String[] splitTime = time.split(regex); result.put("startTime", splitTime[0] + ":" + splitTime[1]); result.put("endTime", splitTime[2] + ":" + splitTime[3]); result.put("startHour", splitTime[0]); result.put("startMin", splitTime[1]); result.put("endHour", splitTime[2]); result.put("endMin", splitTime[3]); return result; } }
UTF-8
Java
3,614
java
CutTimeUtil.java
Java
[ { "context": "age com.ruoyi.project.system.util;\n\n/**\n * @author Vetch\n * @Description\n * @create 2021-04-09-9:19\n */\n\ni", "end": 60, "score": 0.9379855394363403, "start": 55, "tag": "USERNAME", "value": "Vetch" } ]
null
[]
package com.ruoyi.project.system.util; /** * @author Vetch * @Description * @create 2021-04-09-9:19 */ import com.ruoyi.framework.config.RuoYiConfig; import org.apache.poi.util.Units; import org.apache.poi.xwpf.usermodel.*; import java.io.*; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; /** * ๅˆ‡ๅ‰ฒๆ—ถ้—ดๅญ—็ฌฆไธฒ * * */ public class CutTimeUtil { /** * Description: ่Žทๅ–ๅœจๆŒ‡ๅฎšๆ—ถ้—ดๅ†…ไปฅๆŒ‡ๅฎšๅˆ†้’Ÿๆฎตๅˆ†ๅ‰ฒ็š„ๆ—ถ้—ด้›†ๅˆ * * @param time ๆŒ‡ๅฎšๆ—ถ้—ด * @param minItem ๆŒ‡ๅฎšๅˆ†้’Ÿๆฎต * @param disableTimes ไธๅŒ…ๅซ็š„ๆ—ถ้—ด * @Return: java.util.List<java.lang.String> * @Date: 2021/04/25 10:45 */ public static List<String> cutTime(String time, int minItem, List<String> disableTimes) { List<String> result = new ArrayList<>(); String[] minItems = getMin(minItem); Map<String, String> times = getTime(time); int startHour = Integer.parseInt(times.get("startHour")); int endHour = Integer.parseInt(times.get("endHour")); int startMin = Integer.parseInt(times.get("startMin")); String endTime = times.get("endTime"); for (int i = startHour; i <= endHour; i++) { for (int j = 0; j < minItems.length; j++) { String temp; if (i == startHour && j == 0) { temp = (startHour == 0 ? "00" : startHour) + ":" + (startMin == 0 ? "00" : startMin); j = startMin / minItem + 1; } else { temp = (i == 0 ? "00" : i) + ":" + minItems[j]; } if (disableTimes != null) { if (!disableTimes.contains(temp)) { result.add(temp); if (temp.equals(endTime)) { break; } } else { if (temp.equals(endTime)) { break; } } } else { result.add(temp); if (temp.equals(endTime)) { break; } } } } return result; } /** * Description: ่Žทๅ–ๆฏๅฐๆ—ถไธญๆŒ‡ๅฎšๅˆ†้’Ÿๆฎตๅˆ†ๅ‰ฒ็š„ๅˆ†้’Ÿ้›†ๅˆ * * @param item ๆŒ‡ๅฎšๅˆ†้’Ÿๆฎต * @Return: java.lang.String[] * @Date: 2021/04/25 10:46 */ public static String[] getMin(int item) { int num = 60 / item; String[] result = new String[num]; result[0] = "00"; for (int i = 1; i < num; i++) { result[i] = String.valueOf(item * i); } return result; } /** * Description: ๅˆ†ๅ‰ฒๆŒ‡ๅฎšๆ—ถ้—ด๏ผŒ่Žทๅ–ๆ—ถ้—ดไฟกๆฏ * * @param time ๆŒ‡ๅฎšๆ—ถ้—ด * @Return: java.util.Map<java.lang.String, java.lang.String> * @Date: 2021/04/25 10:47 */ public static Map<String, String> getTime(String time) { Map<String, String> result = new HashMap<>(); String regex = "[: -]"; String[] splitTime = time.split(regex); result.put("startTime", splitTime[0] + ":" + splitTime[1]); result.put("endTime", splitTime[2] + ":" + splitTime[3]); result.put("startHour", splitTime[0]); result.put("startMin", splitTime[1]); result.put("endHour", splitTime[2]); result.put("endMin", splitTime[3]); return result; } }
3,614
0.49797
0.476798
114
29.245613
21.135138
105
false
false
0
0
0
0
0
0
0.535088
false
false
10
c0a96c35bc73794d3d7e38e4b5ad6c929151c1d6
18,468,359,389,849
63df4e596534c9de15273d2e033920fde53183d8
/src/main/java/nl/quintor/studybits/business/OsirisParser.java
7565f2df92f438c3d4e2a1fd574ffe5370440a81
[]
no_license
TijnvandenBergh/StudyBitsParser
https://github.com/TijnvandenBergh/StudyBitsParser
02e4d21bf96ce2d3ecf338b7980f1f53c7de94f7
93efde64a6cf6c81c4c1a60a7191699af29835fc
refs/heads/master
2022-02-10T12:49:17.335000
2019-05-14T12:55:52
2019-05-14T12:55:52
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package nl.quintor.studybits.business; import lombok.NoArgsConstructor; import nl.quintor.studybits.entity.ExchangePosition; import nl.quintor.studybits.entity.Student; import nl.quintor.studybits.entity.Transcript; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.json.JSONObject; import java.io.IOException; @NoArgsConstructor public class OsirisParser extends Parser { protected static final Logger logger = LogManager.getLogger(); private static final String URL_PROGRESS = "https://my-json-server.typicode.com/tijn167/FakeJsonApi"; private static final String STUDENT_BY_ID_ENDPOINT = "/students/{id}"; ApiCallService apiCallService = new ApiCallService(); public OsirisParser(String name, String url) { super(name, url); } @Override public String callDataSource(int id, String url, String endpoint) { String data = apiCallService.callService(id, url, endpoint); logger.info(data); return data; } @Override public Student parseStudent(int id) { try { String jsonString = callDataSource(id, URL_PROGRESS, STUDENT_BY_ID_ENDPOINT); if (jsonString.contains("{")) { JSONObject jsonObject = new JSONObject(jsonString); String fullName = jsonObject.getString("name"); String firstName = splitFirstName(fullName); logger.info(firstName); logger.info(jsonObject.getJSONArray("inschrijvingen").toString()); Student student = new Student(); student.setFirstName(firstName); } } catch (NullPointerException e) { e.printStackTrace(); logger.info(e.getMessage()); } //Make student so app doesnt crash Student student = new Student(); return student; } @Override public Transcript parseTranscript() { return null; } @Override public ExchangePosition parseExchangePosition() { return null; } public String splitFirstName(String name) { int index = name.indexOf(' '); if (index > -1) { // Check if there is more than one word. return name.substring(0, index); // Extract first word. } else { return name; // Text is the first word itself. } } }
UTF-8
Java
2,397
java
OsirisParser.java
Java
[ { "context": "L_PROGRESS = \"https://my-json-server.typicode.com/tijn167/FakeJsonApi\";\n private static final String STU", "end": 580, "score": 0.7740879058837891, "start": 573, "tag": "USERNAME", "value": "tijn167" } ]
null
[]
package nl.quintor.studybits.business; import lombok.NoArgsConstructor; import nl.quintor.studybits.entity.ExchangePosition; import nl.quintor.studybits.entity.Student; import nl.quintor.studybits.entity.Transcript; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.json.JSONObject; import java.io.IOException; @NoArgsConstructor public class OsirisParser extends Parser { protected static final Logger logger = LogManager.getLogger(); private static final String URL_PROGRESS = "https://my-json-server.typicode.com/tijn167/FakeJsonApi"; private static final String STUDENT_BY_ID_ENDPOINT = "/students/{id}"; ApiCallService apiCallService = new ApiCallService(); public OsirisParser(String name, String url) { super(name, url); } @Override public String callDataSource(int id, String url, String endpoint) { String data = apiCallService.callService(id, url, endpoint); logger.info(data); return data; } @Override public Student parseStudent(int id) { try { String jsonString = callDataSource(id, URL_PROGRESS, STUDENT_BY_ID_ENDPOINT); if (jsonString.contains("{")) { JSONObject jsonObject = new JSONObject(jsonString); String fullName = jsonObject.getString("name"); String firstName = splitFirstName(fullName); logger.info(firstName); logger.info(jsonObject.getJSONArray("inschrijvingen").toString()); Student student = new Student(); student.setFirstName(firstName); } } catch (NullPointerException e) { e.printStackTrace(); logger.info(e.getMessage()); } //Make student so app doesnt crash Student student = new Student(); return student; } @Override public Transcript parseTranscript() { return null; } @Override public ExchangePosition parseExchangePosition() { return null; } public String splitFirstName(String name) { int index = name.indexOf(' '); if (index > -1) { // Check if there is more than one word. return name.substring(0, index); // Extract first word. } else { return name; // Text is the first word itself. } } }
2,397
0.64247
0.639549
75
30.959999
25.715593
105
false
false
0
0
0
0
0
0
0.573333
false
false
10
3fd057831706dce8c0e3f7bc6adffd2fc6f0bbc4
22,900,765,644,290
9143ad6914f9009548b0c571cf248342a35fe6f6
/src/main/java/ru/demoopencart/steps/BaseSteps.java
f223b924809d99d236aac7e060a0408cc4dfe24e
[]
no_license
supeedo/OTUS_JAVA_QA_Final_Project
https://github.com/supeedo/OTUS_JAVA_QA_Final_Project
b3ceb8efed03cfe1b8eeae36b6309a0bc0623051
ce3c0083aa7cf627e93068481aa6f1322fab9658
refs/heads/master
2022-12-06T07:26:06.831000
2020-08-25T05:29:35
2020-08-25T05:29:35
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ru.demoopencart.steps; import com.codeborne.selenide.SelenideElement; import io.qameta.allure.Step; import org.testng.Assert; import ru.demoopencart.pages.components.Header; import ru.demoopencart.pages.components.LeftColumn; import ru.demoopencart.pages.components.MainMenu; import static com.codeborne.selenide.Selenide.title; /** * ะšะปะฐัั ั ะฑะฐะทะพะฒั‹ะผะธ ัั‚ะตะฟะฐะผะธ, ะดะพัั‚ัƒะฟ ะบ ะฒะทะฐะธะผะพะดะตะนัั‚ะฒะธัŽ ั ะบะพั‚ะพั€ั‹ะผะธ ะธะผะตัŽ ะฒัะต ะพัั‚ะฐะปัŒะฝั‹ะต ะšะปะฐััั‹ ัั‚ะตะฟะพะฒ * , ะฝะฐัะปะตะดัƒะตะผั‹ะต ะพั‚ ะฑะฐะทะพะฒะพะณะพ. ะŸะพ ะปะพะณะธะบะต, ะฒ ะดะฐะฝะฝะพะผ ะบะปะฐััะต ะปะตะถะฐั‚ ะผะตั‚ะพะดั‹ ะพะฑั€ะฐั‰ะฐัŽั‰ะธะตัั ะบ ัะปะตะผะตะฝั‚ะฐะผ * ะดะพัั‚ัƒะฟะฝั‹ะต ะฝะฐ ะฒัะตั… ัั‚ั€ะฐะฝะธั†ะฐั… ัะฐะนั‚ะฐ. */ public class BaseSteps<P> { @Step("Check title with expected") public P checkTitle( String titleExpected ) { Assert.assertEquals(title(), titleExpected, "title not the same with expected"); return (P) this; } @Step public P useMainMenuByText( String textMenuButton ) { MainMenu menu = new MainMenu(); menu.getSectionMenuByText(textMenuButton).click(); return (P) this; } @Step public P useMainMenuWithSubbuttonByText( String textMenuButton, String textSubMenuButton ) { MainMenu menu = new MainMenu(); SelenideElement button = menu.getSectionMenuByText(textMenuButton); button.click(); SelenideElement subbutton = menu.getSubbuttonFromMainMenuByText(button, textSubMenuButton); if (subbutton.exists()) { subbutton.click(); } else { button.click(); subbutton.click(); } return (P) this; } @Step public P checkBusketText( String textBasket ) { Header header = new Header(); Assert.assertEquals(header.getBasket().getText(), textBasket, "text does not converge with expected"); return (P) this; } @Step public P sendTextInSearchField( String text ) { Header header = new Header(); header.getSearchField().sendKeys(text); header.getSearchField().pressEnter(); return (P) this; } @Step public P useLeftMenuByText( String textButton ) { LeftColumn column = new LeftColumn(); column.updateCollection(); column.getButtonCollection().get(textButton).click(); return (P) this; } }
UTF-8
Java
2,441
java
BaseSteps.java
Java
[]
null
[]
package ru.demoopencart.steps; import com.codeborne.selenide.SelenideElement; import io.qameta.allure.Step; import org.testng.Assert; import ru.demoopencart.pages.components.Header; import ru.demoopencart.pages.components.LeftColumn; import ru.demoopencart.pages.components.MainMenu; import static com.codeborne.selenide.Selenide.title; /** * ะšะปะฐัั ั ะฑะฐะทะพะฒั‹ะผะธ ัั‚ะตะฟะฐะผะธ, ะดะพัั‚ัƒะฟ ะบ ะฒะทะฐะธะผะพะดะตะนัั‚ะฒะธัŽ ั ะบะพั‚ะพั€ั‹ะผะธ ะธะผะตัŽ ะฒัะต ะพัั‚ะฐะปัŒะฝั‹ะต ะšะปะฐััั‹ ัั‚ะตะฟะพะฒ * , ะฝะฐัะปะตะดัƒะตะผั‹ะต ะพั‚ ะฑะฐะทะพะฒะพะณะพ. ะŸะพ ะปะพะณะธะบะต, ะฒ ะดะฐะฝะฝะพะผ ะบะปะฐััะต ะปะตะถะฐั‚ ะผะตั‚ะพะดั‹ ะพะฑั€ะฐั‰ะฐัŽั‰ะธะตัั ะบ ัะปะตะผะตะฝั‚ะฐะผ * ะดะพัั‚ัƒะฟะฝั‹ะต ะฝะฐ ะฒัะตั… ัั‚ั€ะฐะฝะธั†ะฐั… ัะฐะนั‚ะฐ. */ public class BaseSteps<P> { @Step("Check title with expected") public P checkTitle( String titleExpected ) { Assert.assertEquals(title(), titleExpected, "title not the same with expected"); return (P) this; } @Step public P useMainMenuByText( String textMenuButton ) { MainMenu menu = new MainMenu(); menu.getSectionMenuByText(textMenuButton).click(); return (P) this; } @Step public P useMainMenuWithSubbuttonByText( String textMenuButton, String textSubMenuButton ) { MainMenu menu = new MainMenu(); SelenideElement button = menu.getSectionMenuByText(textMenuButton); button.click(); SelenideElement subbutton = menu.getSubbuttonFromMainMenuByText(button, textSubMenuButton); if (subbutton.exists()) { subbutton.click(); } else { button.click(); subbutton.click(); } return (P) this; } @Step public P checkBusketText( String textBasket ) { Header header = new Header(); Assert.assertEquals(header.getBasket().getText(), textBasket, "text does not converge with expected"); return (P) this; } @Step public P sendTextInSearchField( String text ) { Header header = new Header(); header.getSearchField().sendKeys(text); header.getSearchField().pressEnter(); return (P) this; } @Step public P useLeftMenuByText( String textButton ) { LeftColumn column = new LeftColumn(); column.updateCollection(); column.getButtonCollection().get(textButton).click(); return (P) this; } }
2,441
0.673162
0.673162
72
30.361111
28.028412
110
false
false
0
0
0
0
0
0
0.569444
false
false
10
fc6c30b445fc6b7fe0a6d814f9328be970a6e3c6
27,135,603,395,248
9a43cb738a95e7200498b1183e0675b42e32175f
/src/main/java/duke/storage/Storage.java
5cc026305e8dcb7d133de3dcfc6d3c5f3bb9c620
[]
no_license
lyeyixian/ip
https://github.com/lyeyixian/ip
1eda43baf9ac585263272577bd7f90bd98cc5a21
69cf4f7b033f4eba31ad2571929108a2715b4eeb
refs/heads/master
2022-12-18T13:56:01.542000
2020-09-24T14:43:39
2020-09-24T14:43:39
287,902,426
0
0
null
true
2020-09-05T04:22:24
2020-08-16T08:17:04
2020-09-05T04:17:52
2020-09-05T04:22:23
1,467
0
0
0
Java
false
false
package duke.storage; import java.io.File; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Scanner; import duke.task.Deadline; import duke.task.Event; import duke.task.Task; import duke.task.ToDo; /** * Represents a storage for the data (TaskList) of Duke program. */ public class Storage { private String filePath; public Storage(String filePath) { this.filePath = filePath; } private void readFileAndUpdateList(Scanner sc, List<Task> list) { while (sc.hasNext()) { String[] data = sc.nextLine().split("/"); String taskType = data[0]; boolean status = data[1].equals("1"); String description = data[2]; String additional; switch (taskType) { case "t": list.add(new ToDo(description, status)); break; case "d": additional = data[3]; list.add(new Deadline(description, additional, status)); break; case "e": additional = data[3]; list.add(new Event(description, additional, status)); break; default: break; } } } /** * Return the list of tasks previously saved in the filepath specified. * * @return list of tasks */ public List<Task> load() { List<Task> list = new ArrayList<>(); try { File file = new File(this.filePath); if (file.exists()) { Scanner sc = new Scanner(file); readFileAndUpdateList(sc, list); } else { String[] path = filePath.split("/"); String[] dirPath = new String[path.length - 1]; for (int i = 0; i < path.length - 1; i++) { dirPath[i] = path[i]; } File dir = new File(String.join("/", dirPath)); dir.mkdir(); file.createNewFile(); } } catch (FileNotFoundException e) { System.out.println("File not exists" + e.getMessage()); } catch (IOException e) { System.out.println("Something went wrong " + e.getMessage()); } return list; } /** * Update the storage with the given list of tasks. * * @param list list of tasks */ public void update(List<Task> list) { try { FileWriter fw = new FileWriter(this.filePath); StringBuilder textToAdd = new StringBuilder(); for (Task t : list) { String data = t.getData(); textToAdd.append(data).append("\n"); } fw.write(textToAdd.toString()); fw.close(); } catch (IOException e) { System.out.println("Something went wrong" + e.getMessage()); } } }
UTF-8
Java
3,043
java
Storage.java
Java
[]
null
[]
package duke.storage; import java.io.File; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Scanner; import duke.task.Deadline; import duke.task.Event; import duke.task.Task; import duke.task.ToDo; /** * Represents a storage for the data (TaskList) of Duke program. */ public class Storage { private String filePath; public Storage(String filePath) { this.filePath = filePath; } private void readFileAndUpdateList(Scanner sc, List<Task> list) { while (sc.hasNext()) { String[] data = sc.nextLine().split("/"); String taskType = data[0]; boolean status = data[1].equals("1"); String description = data[2]; String additional; switch (taskType) { case "t": list.add(new ToDo(description, status)); break; case "d": additional = data[3]; list.add(new Deadline(description, additional, status)); break; case "e": additional = data[3]; list.add(new Event(description, additional, status)); break; default: break; } } } /** * Return the list of tasks previously saved in the filepath specified. * * @return list of tasks */ public List<Task> load() { List<Task> list = new ArrayList<>(); try { File file = new File(this.filePath); if (file.exists()) { Scanner sc = new Scanner(file); readFileAndUpdateList(sc, list); } else { String[] path = filePath.split("/"); String[] dirPath = new String[path.length - 1]; for (int i = 0; i < path.length - 1; i++) { dirPath[i] = path[i]; } File dir = new File(String.join("/", dirPath)); dir.mkdir(); file.createNewFile(); } } catch (FileNotFoundException e) { System.out.println("File not exists" + e.getMessage()); } catch (IOException e) { System.out.println("Something went wrong " + e.getMessage()); } return list; } /** * Update the storage with the given list of tasks. * * @param list list of tasks */ public void update(List<Task> list) { try { FileWriter fw = new FileWriter(this.filePath); StringBuilder textToAdd = new StringBuilder(); for (Task t : list) { String data = t.getData(); textToAdd.append(data).append("\n"); } fw.write(textToAdd.toString()); fw.close(); } catch (IOException e) { System.out.println("Something went wrong" + e.getMessage()); } } }
3,043
0.517581
0.514624
109
26.917431
21.166933
75
false
false
0
0
0
0
0
0
0.53211
false
false
10
4813de453225ee1b394122f465b1096b26888b93
23,347,442,261,209
8c420a6bc0402b1ad25e33262f74ef22af7fb56e
/app/src/main/java/example/com/mvpexample/Login2/SessionRun.java
4247d33dbbd451a86b434dff225bd11f403c321b
[]
no_license
chirag1210/MVPGetRequestWithRetrofit
https://github.com/chirag1210/MVPGetRequestWithRetrofit
38d00b62b327ad7d1b28634584a06ab5fd25a06c
14354c12f0a1d73495a79d22441f1e4fd25d3ae5
refs/heads/master
2021-08-30T11:11:40.159000
2017-12-17T01:48:37
2017-12-17T01:48:37
114,551,752
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package example.com.mvpexample.Login2; /** * Created by Win on 16-12-2017. */ import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; public class SessionRun { @SerializedName("id") @Expose private Integer id; @SerializedName("session_id") @Expose private Integer sessionId; @SerializedName("no_run") @Expose private Integer noRun; @SerializedName("yes_run") @Expose private Integer yesRun; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Integer getSessionId() { return sessionId; } public void setSessionId(Integer sessionId) { this.sessionId = sessionId; } public Integer getNoRun() { return noRun; } public void setNoRun(Integer noRun) { this.noRun = noRun; } public Integer getYesRun() { return yesRun; } public void setYesRun(Integer yesRun) { this.yesRun = yesRun; } }
UTF-8
Java
1,049
java
SessionRun.java
Java
[ { "context": " example.com.mvpexample.Login2;\n\n/**\n * Created by Win on 16-12-2017.\n */\n\nimport com.google.gson.annota", "end": 61, "score": 0.6487995386123657, "start": 58, "tag": "NAME", "value": "Win" } ]
null
[]
package example.com.mvpexample.Login2; /** * Created by Win on 16-12-2017. */ import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; public class SessionRun { @SerializedName("id") @Expose private Integer id; @SerializedName("session_id") @Expose private Integer sessionId; @SerializedName("no_run") @Expose private Integer noRun; @SerializedName("yes_run") @Expose private Integer yesRun; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Integer getSessionId() { return sessionId; } public void setSessionId(Integer sessionId) { this.sessionId = sessionId; } public Integer getNoRun() { return noRun; } public void setNoRun(Integer noRun) { this.noRun = noRun; } public Integer getYesRun() { return yesRun; } public void setYesRun(Integer yesRun) { this.yesRun = yesRun; } }
1,049
0.621544
0.612965
57
17.421053
15.280933
50
false
false
0
0
0
0
0
0
0.263158
false
false
10
ff7c24c5ba24515d515cc8c3c121145459b40508
2,826,088,500,368
20070e46ecc9a7cb032bf2866d053195e0124b4e
/chapter2-answer2/src/main/java/com/itedu/chapter2/answer2/abstractfactory/factory/ColorFactory.java
3c0b28ad211001f34dc78e34a69e4ed418027d1d
[]
no_license
yantingji/java-architecture-book
https://github.com/yantingji/java-architecture-book
ae226c449f3cc5f6f94ac01d9239f9eeb3e12f34
2ad35c139e363c1ecfd62ce99e2e1fc314ea4d03
refs/heads/master
2022-12-21T23:00:35.304000
2020-02-02T04:00:55
2020-02-02T04:00:55
168,796,933
3
3
null
false
2022-12-16T01:21:07
2019-02-02T05:13:26
2021-06-09T05:42:31
2022-12-16T01:21:03
109,443
1
3
107
Java
false
false
package com.itedu.chapter2.answer2.abstractfactory.factory; import com.itedu.chapter2.answer2.abstractfactory.AbstractFactory; import com.itedu.chapter2.answer2.abstractfactory.color.Blue; import com.itedu.chapter2.answer2.abstractfactory.color.Color; import com.itedu.chapter2.answer2.abstractfactory.color.Green; import com.itedu.chapter2.answer2.abstractfactory.shape.Shape; public class ColorFactory extends AbstractFactory { @Override public Shape getShape(String shapeType){ return null; } @Override public Color getColor(String color) { if(color == null){ return null; } if(color.equalsIgnoreCase("GREEN")){ return new Green(); } else if(color.equalsIgnoreCase("BLUE")){ return (Color) new Blue(); } return null; } }
UTF-8
Java
831
java
ColorFactory.java
Java
[]
null
[]
package com.itedu.chapter2.answer2.abstractfactory.factory; import com.itedu.chapter2.answer2.abstractfactory.AbstractFactory; import com.itedu.chapter2.answer2.abstractfactory.color.Blue; import com.itedu.chapter2.answer2.abstractfactory.color.Color; import com.itedu.chapter2.answer2.abstractfactory.color.Green; import com.itedu.chapter2.answer2.abstractfactory.shape.Shape; public class ColorFactory extends AbstractFactory { @Override public Shape getShape(String shapeType){ return null; } @Override public Color getColor(String color) { if(color == null){ return null; } if(color.equalsIgnoreCase("GREEN")){ return new Green(); } else if(color.equalsIgnoreCase("BLUE")){ return (Color) new Blue(); } return null; } }
831
0.701564
0.687124
29
27.655172
22.986166
66
false
false
0
0
0
0
0
0
0.37931
false
false
10
84c14d628e9f3f1705dc545b1a0d28316e9dc6c0
3,616,362,525,637
f7b6a3810e791fea3377c85066998fe30032969e
/src/tests/AdaBoostTest.java
9c459f0b4c0b24c69ae16f6b7e73132cb9a8a7c6
[]
no_license
misael86/ViolaJones-Java
https://github.com/misael86/ViolaJones-Java
d4bad13a4c299f29a8daca733fc70ebfaaed5f8c
03f55493f63acc7c189ff921e1ddb60b08aeaaf3
refs/heads/master
2020-08-06T16:37:15.860000
2014-06-06T05:37:38
2014-06-06T05:37:38
6,012,863
1
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package tests; import global.Methods; import global.Enumerators.DataSet; import models.AdaBoostRespons; import models.WeakClassifier; import org.junit.Assert; import org.junit.Test; import utilities.AdaBoost; import utilities.Data; import utilities.Feature; import utilities.Image; import utilities.Matrix; public class AdaBoostTest { @Test public void TestGetInitializedWeights() { int nrNeg = 5000; int nrPos = 3000; Matrix weights = AdaBoost.getInitializedWeights(nrPos, nrNeg); Assert.assertTrue(Math.abs(weights.getSum() - 1) < 0.0001); } @Test public void TestGetInitializedIsFaceList() { int nrNeg = 5000; int nrPos = 3000; Matrix isFaceList = AdaBoost.getInitializedIsFaceList(nrPos, nrNeg); Assert.assertTrue(isFaceList.getSum() == nrPos); } @Test public void TestLearnWeakClassifier() { int nrNeg = 4000; int nrPos = 2000; Feature ftype = Feature.getAllFeatures(19, 19)[12028]; Matrix weights = AdaBoost.getInitializedWeights(nrPos, nrNeg); Matrix isFaceList = AdaBoost.getInitializedIsFaceList(nrPos, nrNeg); String[] allFaceNeg = Data.getImageList(DataSet.nFace); String[] allFacePos = Data.getImageList(DataSet.pFace); String[] faceNeg = Data.getRandomImageList(allFaceNeg, nrNeg).learnImages; String[] facePos = Data.getRandomImageList(allFacePos, nrPos).learnImages; Matrix[] faceNegIntegrals = Image.getIntegralImages(Data.getNormalisedImageMatrixList(faceNeg, DataSet.nFace)); Matrix[] facePosIntegrals = Image.getIntegralImages(Data.getNormalisedImageMatrixList(facePos, DataSet.pFace)); Matrix featureValuesNeg = Feature.getFeatureValues(faceNegIntegrals, ftype); Matrix featureValuesPos = Feature.getFeatureValues(facePosIntegrals, ftype); Matrix featureValuesAll = new Matrix(nrPos + nrNeg, 1, Methods.concat(featureValuesPos.getData(), featureValuesNeg.getData())); WeakClassifier weakClassifier = AdaBoost.learnWeakClassifier(featureValuesAll, weights, isFaceList); double meanPos = featureValuesPos.getSum() / (double)nrPos; double meanNeg = featureValuesNeg.getSum() / (double)nrNeg; double meanTot = (meanPos + meanNeg) / 2.0; System.out.println(weakClassifier.threshold); Assert.assertTrue(weakClassifier.parity == 1); Assert.assertTrue(Math.abs(weakClassifier.threshold - meanTot) < 0.001); Assert.assertTrue(Math.abs(weakClassifier.threshold - (-3.6453)) < 0.001); } @Test public void TestExecuteAdaBoost() { int T = 3; double[] alphas = new double[] { 1.694004004780836, 1.188907795146310, 0.982307485873930 }; int featureSize = 19; Feature[] allFeatures = Feature.getAllFeatures(featureSize, featureSize); String[] negFaceList = Data.getImageList(DataSet.nFace); String[] posFaceList = Data.getImageList(DataSet.pFace); Matrix[] negImages = Data.getNormalisedImageMatrixList(negFaceList, DataSet.nFace); Matrix[] posImages = Data.getNormalisedImageMatrixList(posFaceList, DataSet.pFace); Matrix[] negIntegralImages = Image.getIntegralImages(negImages); Matrix[] posIntegralImages = Image.getIntegralImages(posImages); Matrix[] integralImages = Matrix.getJoinedLists(posIntegralImages, negIntegralImages); Matrix isFaceList = AdaBoost.getInitializedIsFaceList(posIntegralImages.length, negIntegralImages.length); //Matrix allFeatureValues = Feature.getAllFeatureValues(integral_images, allFeatures); AdaBoostRespons[] adaBoostResponses = AdaBoost.executeAdaBoost(integralImages, allFeatures, isFaceList, negIntegralImages.length, T); AdaBoost.computeROC1(adaBoostResponses, posImages, negImages); AdaBoost.computeROC2(adaBoostResponses, posImages, negImages); for (int i = 0; i < adaBoostResponses.length; i++) { Feature.saveFeaturePic(Feature.getFeature(adaBoostResponses[i].featureIndex.j, adaBoostResponses[i].featureIndex.featureType, featureSize, featureSize), featureSize, featureSize, "feature" + i); } double sumAlpha = 0; for (int i = 0; i < adaBoostResponses.length; i++) { sumAlpha += Math.abs(adaBoostResponses[i].alpha - alphas[i]); } double eps = 0.000001; Assert.assertTrue(sumAlpha < eps); } @Test public void TestApplyDetector() { Matrix image = Data.getImageMatrix("face00001.bmp", DataSet.pFace); image = image.getNormal(); image = Image.getIntegralImage(image); Matrix image2 = Data.getImageMatrix("B1_00001.bmp", DataSet.nFace); image2 = image2.getNormal(); image2 = Image.getIntegralImage(image2); AdaBoostRespons[] strongClassifier = AdaBoostRespons.loadAdaBoostResponsArray("strongClassifier"); double result = AdaBoost.ApplyDetector(strongClassifier, image); double result2 = AdaBoost.ApplyDetector(strongClassifier, image2); //double eps = 0.000001; Assert.assertTrue(result >= AdaBoost.loadThreshold(2).getValue(1)); Assert.assertTrue(result2 < AdaBoost.loadThreshold(2).getValue(1)); //Assert.assertTrue(Math.abs(result - 9.1409) < eps); } }
UTF-8
Java
5,378
java
AdaBoostTest.java
Java
[]
null
[]
package tests; import global.Methods; import global.Enumerators.DataSet; import models.AdaBoostRespons; import models.WeakClassifier; import org.junit.Assert; import org.junit.Test; import utilities.AdaBoost; import utilities.Data; import utilities.Feature; import utilities.Image; import utilities.Matrix; public class AdaBoostTest { @Test public void TestGetInitializedWeights() { int nrNeg = 5000; int nrPos = 3000; Matrix weights = AdaBoost.getInitializedWeights(nrPos, nrNeg); Assert.assertTrue(Math.abs(weights.getSum() - 1) < 0.0001); } @Test public void TestGetInitializedIsFaceList() { int nrNeg = 5000; int nrPos = 3000; Matrix isFaceList = AdaBoost.getInitializedIsFaceList(nrPos, nrNeg); Assert.assertTrue(isFaceList.getSum() == nrPos); } @Test public void TestLearnWeakClassifier() { int nrNeg = 4000; int nrPos = 2000; Feature ftype = Feature.getAllFeatures(19, 19)[12028]; Matrix weights = AdaBoost.getInitializedWeights(nrPos, nrNeg); Matrix isFaceList = AdaBoost.getInitializedIsFaceList(nrPos, nrNeg); String[] allFaceNeg = Data.getImageList(DataSet.nFace); String[] allFacePos = Data.getImageList(DataSet.pFace); String[] faceNeg = Data.getRandomImageList(allFaceNeg, nrNeg).learnImages; String[] facePos = Data.getRandomImageList(allFacePos, nrPos).learnImages; Matrix[] faceNegIntegrals = Image.getIntegralImages(Data.getNormalisedImageMatrixList(faceNeg, DataSet.nFace)); Matrix[] facePosIntegrals = Image.getIntegralImages(Data.getNormalisedImageMatrixList(facePos, DataSet.pFace)); Matrix featureValuesNeg = Feature.getFeatureValues(faceNegIntegrals, ftype); Matrix featureValuesPos = Feature.getFeatureValues(facePosIntegrals, ftype); Matrix featureValuesAll = new Matrix(nrPos + nrNeg, 1, Methods.concat(featureValuesPos.getData(), featureValuesNeg.getData())); WeakClassifier weakClassifier = AdaBoost.learnWeakClassifier(featureValuesAll, weights, isFaceList); double meanPos = featureValuesPos.getSum() / (double)nrPos; double meanNeg = featureValuesNeg.getSum() / (double)nrNeg; double meanTot = (meanPos + meanNeg) / 2.0; System.out.println(weakClassifier.threshold); Assert.assertTrue(weakClassifier.parity == 1); Assert.assertTrue(Math.abs(weakClassifier.threshold - meanTot) < 0.001); Assert.assertTrue(Math.abs(weakClassifier.threshold - (-3.6453)) < 0.001); } @Test public void TestExecuteAdaBoost() { int T = 3; double[] alphas = new double[] { 1.694004004780836, 1.188907795146310, 0.982307485873930 }; int featureSize = 19; Feature[] allFeatures = Feature.getAllFeatures(featureSize, featureSize); String[] negFaceList = Data.getImageList(DataSet.nFace); String[] posFaceList = Data.getImageList(DataSet.pFace); Matrix[] negImages = Data.getNormalisedImageMatrixList(negFaceList, DataSet.nFace); Matrix[] posImages = Data.getNormalisedImageMatrixList(posFaceList, DataSet.pFace); Matrix[] negIntegralImages = Image.getIntegralImages(negImages); Matrix[] posIntegralImages = Image.getIntegralImages(posImages); Matrix[] integralImages = Matrix.getJoinedLists(posIntegralImages, negIntegralImages); Matrix isFaceList = AdaBoost.getInitializedIsFaceList(posIntegralImages.length, negIntegralImages.length); //Matrix allFeatureValues = Feature.getAllFeatureValues(integral_images, allFeatures); AdaBoostRespons[] adaBoostResponses = AdaBoost.executeAdaBoost(integralImages, allFeatures, isFaceList, negIntegralImages.length, T); AdaBoost.computeROC1(adaBoostResponses, posImages, negImages); AdaBoost.computeROC2(adaBoostResponses, posImages, negImages); for (int i = 0; i < adaBoostResponses.length; i++) { Feature.saveFeaturePic(Feature.getFeature(adaBoostResponses[i].featureIndex.j, adaBoostResponses[i].featureIndex.featureType, featureSize, featureSize), featureSize, featureSize, "feature" + i); } double sumAlpha = 0; for (int i = 0; i < adaBoostResponses.length; i++) { sumAlpha += Math.abs(adaBoostResponses[i].alpha - alphas[i]); } double eps = 0.000001; Assert.assertTrue(sumAlpha < eps); } @Test public void TestApplyDetector() { Matrix image = Data.getImageMatrix("face00001.bmp", DataSet.pFace); image = image.getNormal(); image = Image.getIntegralImage(image); Matrix image2 = Data.getImageMatrix("B1_00001.bmp", DataSet.nFace); image2 = image2.getNormal(); image2 = Image.getIntegralImage(image2); AdaBoostRespons[] strongClassifier = AdaBoostRespons.loadAdaBoostResponsArray("strongClassifier"); double result = AdaBoost.ApplyDetector(strongClassifier, image); double result2 = AdaBoost.ApplyDetector(strongClassifier, image2); //double eps = 0.000001; Assert.assertTrue(result >= AdaBoost.loadThreshold(2).getValue(1)); Assert.assertTrue(result2 < AdaBoost.loadThreshold(2).getValue(1)); //Assert.assertTrue(Math.abs(result - 9.1409) < eps); } }
5,378
0.697843
0.669208
147
35.585033
37.712273
207
false
false
0
0
0
0
0
0
1.197279
false
false
10
14cbc0a2d17879b8d75c797331c115370a193057
38,989,713,137,961
b09d9742338e24a0789fff0c62a6766522adb175
/src/pages/CreateAccountPage.java
21dc31947c99b5c73e6a65abe1b7498ba4f8a1b0
[]
no_license
AndrewPopenko/MyGardenTest
https://github.com/AndrewPopenko/MyGardenTest
a7b4a666cb84925dbafa1d26b876601a417e9d6c
cced927a4d7168768a5dc3a2f9df80a346620178
refs/heads/master
2021-01-13T00:52:25.074000
2016-02-15T21:12:40
2016-02-15T21:12:40
51,757,881
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package pages; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; public class CreateAccountPage extends SuperPage { WebDriver driver; By textElement = By.xpath("//*[@id='noSlide']/h1"); public CreateAccountPage(WebDriver driver) { super(driver); if(!driver.getTitle().equals("Logowanie - GARDEN STORE") && driver.findElement(textElement).getText().equals("Stwรณrz konto")) printLog("Something went wrong it is not page with title - \"Logowanie - GARDEN STORE\" (Stwรณrz konto)"); else { printLog(OpenedPage(driver.getTitle() + " (Stwรณrz konto)") + "by link"); } this.driver = driver; } }
WINDOWS-1250
Java
670
java
CreateAccountPage.java
Java
[]
null
[]
package pages; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; public class CreateAccountPage extends SuperPage { WebDriver driver; By textElement = By.xpath("//*[@id='noSlide']/h1"); public CreateAccountPage(WebDriver driver) { super(driver); if(!driver.getTitle().equals("Logowanie - GARDEN STORE") && driver.findElement(textElement).getText().equals("Stwรณrz konto")) printLog("Something went wrong it is not page with title - \"Logowanie - GARDEN STORE\" (Stwรณrz konto)"); else { printLog(OpenedPage(driver.getTitle() + " (Stwรณrz konto)") + "by link"); } this.driver = driver; } }
670
0.671664
0.670165
24
25.791666
29.453323
108
false
false
0
0
0
0
0
0
1.625
false
false
10
43ff904493922489d3a0473b4d20bc792e1ac0c5
7,550,552,554,271
0a8ebbb1addf53c438fdfed4dfd4c3e4818b6b2a
/src/main/java/com/pocket/controllers/NutritionistController.java
da69a83976bdc11b2a97823ba4acf4cfdc83dbc6
[]
no_license
DanielaRednic/pocket-nutritionist
https://github.com/DanielaRednic/pocket-nutritionist
739a22bf4f034ec74513b80a277c6e3f73044b39
bb497b4391c2af5950467b198ecd62027708cc5d
refs/heads/master
2023-05-02T13:35:24.194000
2021-05-16T16:25:48
2021-05-16T16:25:48
353,073,613
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.pocket.controllers; import java.util.ResourceBundle; import com.pocket.model.User; import com.pocket.services.UserService; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.fxml.Initializable; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.cell.TextFieldTableCell; import javafx.scene.text.Font; import javafx.scene.text.FontPosture; import javafx.scene.text.FontWeight; import javafx.scene.text.Text; import javafx.stage.Stage; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.scene.control.TableColumn; import javafx.scene.control.TableView; import javafx.scene.control.cell.PropertyValueFactory; import javafx.scene.layout.VBox; import javafx.util.converter.IntegerStringConverter; import java.io.IOException; import java.util.List; import java.net.URL; public class NutritionistController { @FXML private TableView<User> table; @FXML private Button Close; @FXML private Button LoginScreen; @FXML private Text ClientName; @FXML private Button ViewClients; @FXML private TableColumn<User, Button> clientEdit; @FXML private TableColumn<User, Integer> clientCalories; @FXML private TableColumn<User, String> clientName; @FXML private TableColumn<User, String> clientEmail; @FXML private TableColumn<User, String> clientPhoneNumber; @FXML private TableColumn<User, String> clientHeight; @FXML private TableColumn<User, String> clientWeight; @FXML private TableColumn<User, String> clientAllergies; @FXML private TableColumn<User, String> clientDiet; @FXML private TableColumn<User, String> clientGender; private User user; Stage window; public void initialize(User user) { this.user = user; ClientName.setText(user.getFullName()); } public void handleClientsAction() throws IOException { Label label = new Label("File Data:"); Font font = Font.font("verdana", FontWeight.BOLD, FontPosture.REGULAR, 12); label.setFont(font); List<User> users = UserService.loadUsersFromFile2(); TableView<User> table = new TableView<User>(); table.setEditable(true); //Creating columns TableColumn <User, String> clientName = new TableColumn("Client"); clientName.setCellValueFactory(new PropertyValueFactory<>("FullName")); TableColumn <User, String> clientPhoneNumber = new TableColumn("Phone Number"); clientPhoneNumber.setCellValueFactory(new PropertyValueFactory<>("PhoneNumber")); TableColumn <User, String> clientEmail = new TableColumn("Email"); clientEmail.setCellValueFactory(new PropertyValueFactory<>("Email")); TableColumn <User, String> clientDiet = new TableColumn("Diet Type"); clientDiet.setCellValueFactory(new PropertyValueFactory<>("DietType")); TableColumn <User, String> clientGender = new TableColumn("Gender"); clientGender.setCellValueFactory(new PropertyValueFactory<>("Gender")); TableColumn <User, String> clientHeight = new TableColumn("Height"); clientHeight.setCellValueFactory(new PropertyValueFactory<>("Height")); TableColumn <User, String> clientWeight = new TableColumn("Weight"); clientWeight.setCellValueFactory(new PropertyValueFactory<>("Weight")); TableColumn <User, String> clientAllergies = new TableColumn("Allergies"); clientAllergies.setCellValueFactory(new PropertyValueFactory<>("Allergies")); TableColumn <User, Integer> clientCalories = new TableColumn("Calories Allowed"); clientCalories.setCellValueFactory(new PropertyValueFactory<>("calories")); clientCalories.setCellFactory(TextFieldTableCell.forTableColumn(new IntegerStringConverter())); clientCalories.setOnEditCommit(new EventHandler<TableColumn.CellEditEvent<User, Integer>>() { @Override public void handle(TableColumn.CellEditEvent<User, Integer> event) { User changes = event.getRowValue(); changes.setCalories(event.getNewValue()); UserService.persistUsers2(users); } }); table.getColumns().addAll(clientName,clientPhoneNumber,clientEmail,clientDiet,clientGender,clientHeight,clientWeight,clientAllergies,clientCalories); ObservableList<User> data = FXCollections.observableArrayList(); for (User it : users) { if (it.getRole().compareTo("Client") == 0) { data.add(it); } } table.setItems(data); window=new Stage(); VBox vbox= new VBox(); vbox.getChildren().addAll(table); Scene scene=new Scene(vbox); window.setTitle("Clients"); window.setScene(scene); window.show(); } @FXML public void handleClientsButton() throws IOException{ Stage stage; try{ handleClientsAction(); stage = (Stage) ViewClients.getScene().getWindow(); stage.show(); } catch(Exception e) { e.printStackTrace(); e.getCause(); } } @FXML public void handleCloseAction(ActionEvent event) { Stage stage; stage = (Stage) Close.getScene().getWindow(); stage.close(); } @FXML public void handleLoginScreenButton() { Stage stage; Parent root; try{ stage = (Stage) LoginScreen.getScene().getWindow(); root = FXMLLoader.load(getClass().getClassLoader().getResource("LoginLauncher.fxml")); Scene scene = new Scene(root); stage.setScene(scene); stage.show(); } catch(Exception e) { e.printStackTrace(); e.getCause(); } } }
UTF-8
Java
6,082
java
NutritionistController.java
Java
[]
null
[]
package com.pocket.controllers; import java.util.ResourceBundle; import com.pocket.model.User; import com.pocket.services.UserService; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.fxml.Initializable; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.cell.TextFieldTableCell; import javafx.scene.text.Font; import javafx.scene.text.FontPosture; import javafx.scene.text.FontWeight; import javafx.scene.text.Text; import javafx.stage.Stage; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.scene.control.TableColumn; import javafx.scene.control.TableView; import javafx.scene.control.cell.PropertyValueFactory; import javafx.scene.layout.VBox; import javafx.util.converter.IntegerStringConverter; import java.io.IOException; import java.util.List; import java.net.URL; public class NutritionistController { @FXML private TableView<User> table; @FXML private Button Close; @FXML private Button LoginScreen; @FXML private Text ClientName; @FXML private Button ViewClients; @FXML private TableColumn<User, Button> clientEdit; @FXML private TableColumn<User, Integer> clientCalories; @FXML private TableColumn<User, String> clientName; @FXML private TableColumn<User, String> clientEmail; @FXML private TableColumn<User, String> clientPhoneNumber; @FXML private TableColumn<User, String> clientHeight; @FXML private TableColumn<User, String> clientWeight; @FXML private TableColumn<User, String> clientAllergies; @FXML private TableColumn<User, String> clientDiet; @FXML private TableColumn<User, String> clientGender; private User user; Stage window; public void initialize(User user) { this.user = user; ClientName.setText(user.getFullName()); } public void handleClientsAction() throws IOException { Label label = new Label("File Data:"); Font font = Font.font("verdana", FontWeight.BOLD, FontPosture.REGULAR, 12); label.setFont(font); List<User> users = UserService.loadUsersFromFile2(); TableView<User> table = new TableView<User>(); table.setEditable(true); //Creating columns TableColumn <User, String> clientName = new TableColumn("Client"); clientName.setCellValueFactory(new PropertyValueFactory<>("FullName")); TableColumn <User, String> clientPhoneNumber = new TableColumn("Phone Number"); clientPhoneNumber.setCellValueFactory(new PropertyValueFactory<>("PhoneNumber")); TableColumn <User, String> clientEmail = new TableColumn("Email"); clientEmail.setCellValueFactory(new PropertyValueFactory<>("Email")); TableColumn <User, String> clientDiet = new TableColumn("Diet Type"); clientDiet.setCellValueFactory(new PropertyValueFactory<>("DietType")); TableColumn <User, String> clientGender = new TableColumn("Gender"); clientGender.setCellValueFactory(new PropertyValueFactory<>("Gender")); TableColumn <User, String> clientHeight = new TableColumn("Height"); clientHeight.setCellValueFactory(new PropertyValueFactory<>("Height")); TableColumn <User, String> clientWeight = new TableColumn("Weight"); clientWeight.setCellValueFactory(new PropertyValueFactory<>("Weight")); TableColumn <User, String> clientAllergies = new TableColumn("Allergies"); clientAllergies.setCellValueFactory(new PropertyValueFactory<>("Allergies")); TableColumn <User, Integer> clientCalories = new TableColumn("Calories Allowed"); clientCalories.setCellValueFactory(new PropertyValueFactory<>("calories")); clientCalories.setCellFactory(TextFieldTableCell.forTableColumn(new IntegerStringConverter())); clientCalories.setOnEditCommit(new EventHandler<TableColumn.CellEditEvent<User, Integer>>() { @Override public void handle(TableColumn.CellEditEvent<User, Integer> event) { User changes = event.getRowValue(); changes.setCalories(event.getNewValue()); UserService.persistUsers2(users); } }); table.getColumns().addAll(clientName,clientPhoneNumber,clientEmail,clientDiet,clientGender,clientHeight,clientWeight,clientAllergies,clientCalories); ObservableList<User> data = FXCollections.observableArrayList(); for (User it : users) { if (it.getRole().compareTo("Client") == 0) { data.add(it); } } table.setItems(data); window=new Stage(); VBox vbox= new VBox(); vbox.getChildren().addAll(table); Scene scene=new Scene(vbox); window.setTitle("Clients"); window.setScene(scene); window.show(); } @FXML public void handleClientsButton() throws IOException{ Stage stage; try{ handleClientsAction(); stage = (Stage) ViewClients.getScene().getWindow(); stage.show(); } catch(Exception e) { e.printStackTrace(); e.getCause(); } } @FXML public void handleCloseAction(ActionEvent event) { Stage stage; stage = (Stage) Close.getScene().getWindow(); stage.close(); } @FXML public void handleLoginScreenButton() { Stage stage; Parent root; try{ stage = (Stage) LoginScreen.getScene().getWindow(); root = FXMLLoader.load(getClass().getClassLoader().getResource("LoginLauncher.fxml")); Scene scene = new Scene(root); stage.setScene(scene); stage.show(); } catch(Exception e) { e.printStackTrace(); e.getCause(); } } }
6,082
0.673298
0.672476
193
30.507772
28.011677
157
false
false
0
0
0
0
0
0
0.715026
false
false
10
4b2d92f7416422a7102dba2ba06a0129442dc51f
36,344,013,289,112
eb0c0ade9beccd9c6d7b09240bdb6acc30006152
/src/main/java/ๅœบๆ™ฏ้ข˜/hashMapDemo.java
de84dc08fce887be970730f90cdd68e2634e6f45
[]
no_license
chenqian1998/javaProgram
https://github.com/chenqian1998/javaProgram
550405e3b16a921550268033b2f6e247a9fb9f03
24470fddaa11285de3dfb6e4fccfa8b16fbed87b
refs/heads/master
2023-01-08T08:24:31.053000
2020-05-22T11:09:23
2020-05-22T11:09:23
266,088,118
0
0
null
false
2020-10-13T22:12:37
2020-05-22T10:55:56
2020-05-22T11:09:51
2020-10-13T22:12:36
219
0
0
1
Java
false
false
package ๅœบๆ™ฏ้ข˜; public class hashMapDemo { // ๆ•ฐๆฎๆกถ node private String[] table; private int size; public hashMapDemo() { table = new String[16]; size = 16; } public void push(String key, String value) { int hash = key.hashCode() & (size - 1); } public static void main(String[] args) { } }
UTF-8
Java
366
java
hashMapDemo.java
Java
[]
null
[]
package ๅœบๆ™ฏ้ข˜; public class hashMapDemo { // ๆ•ฐๆฎๆกถ node private String[] table; private int size; public hashMapDemo() { table = new String[16]; size = 16; } public void push(String key, String value) { int hash = key.hashCode() & (size - 1); } public static void main(String[] args) { } }
366
0.556497
0.542373
23
14.391304
16.067085
48
false
false
0
0
0
0
0
0
0.304348
false
false
10
da13e378f760b4d55cfba6c6876e9c6ea5dc2a54
5,076,651,401,098
e227db90efcae12dd3886cdbdb901bb19bd8bea1
/src/main/java/com/syntel/vertx/StarterController.java
ee8319661b711fa55cadcf3bf241d35b8466ee94
[]
no_license
jayant-ingale/realtimedataHackthon
https://github.com/jayant-ingale/realtimedataHackthon
e5079328444ac3ac91598d2f06326adf6f695ad9
dd54caf7403f9ebafad812b585c0a99f877f9dac
refs/heads/master
2021-07-15T18:05:57.204000
2019-10-23T14:15:42
2019-10-23T14:15:42
217,066,864
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.syntel.vertx; import com.syntel.vertx.MyFirstVerticle; import io.vertx.core.AbstractVerticle; import io.vertx.core.DeploymentOptions; import io.vertx.core.Vertx; import io.vertx.core.VertxOptions; import io.vertx.core.json.JsonObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class StarterController extends AbstractVerticle { /** * * @param args */ public static void main(String[] args){ Logger logger = LoggerFactory.getLogger(StarterController.class); // VertxOptions vxOptions = new VertxOptions().setBlockedThreadCheckInterval(200000000); //.setblockedThreadCheckInterval(200000000); //Vertx myVertx = Vertx.vertx(vxOptions); final Vertx vertx = Vertx.vertx(); vertx.deployVerticle("com.syntel.vertx.VehicleVertx", new DeploymentOptions().setInstances(1)); // vertx.deployVerticle("com.syntel.vertx.VehicleVertx", new DeploymentOptions().setWorker(true)); //setInstances--Set the number of instances that should be deployed. // vertx.deployVerticle("com.syntel.vertx.heatsensor.HeatSensor", new DeploymentOptions().setInstances(4)); /* vertx.deployVerticle("com.syntel.vertx.heatsensor.HeatSensor", new DeploymentOptions().setConfig(new JsonObject() .put("http.port", 3000))); */ // vertx.deployVerticle("com.syntel.vertx.SensorData"); /*vertx.deployVerticle(new RealTimeCollectorVertx(), res -> { if (res.succeeded()) { logger.info("Deployment id is: " + res.result()); } else { logger.info("Deployment failed!"); } });*/ /*vertx.deployVerticle(new VehicleVertx(), res -> { if (res.succeeded()) { logger.info("Deployment[VehicleVertx] id is: " + res.result()); } else { logger.info("Deployment VehicleVertx failed!"); } });*/ // vertx.deployVerticle(new BlockEventLoop()); } }
UTF-8
Java
2,055
java
StarterController.java
Java
[]
null
[]
package com.syntel.vertx; import com.syntel.vertx.MyFirstVerticle; import io.vertx.core.AbstractVerticle; import io.vertx.core.DeploymentOptions; import io.vertx.core.Vertx; import io.vertx.core.VertxOptions; import io.vertx.core.json.JsonObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class StarterController extends AbstractVerticle { /** * * @param args */ public static void main(String[] args){ Logger logger = LoggerFactory.getLogger(StarterController.class); // VertxOptions vxOptions = new VertxOptions().setBlockedThreadCheckInterval(200000000); //.setblockedThreadCheckInterval(200000000); //Vertx myVertx = Vertx.vertx(vxOptions); final Vertx vertx = Vertx.vertx(); vertx.deployVerticle("com.syntel.vertx.VehicleVertx", new DeploymentOptions().setInstances(1)); // vertx.deployVerticle("com.syntel.vertx.VehicleVertx", new DeploymentOptions().setWorker(true)); //setInstances--Set the number of instances that should be deployed. // vertx.deployVerticle("com.syntel.vertx.heatsensor.HeatSensor", new DeploymentOptions().setInstances(4)); /* vertx.deployVerticle("com.syntel.vertx.heatsensor.HeatSensor", new DeploymentOptions().setConfig(new JsonObject() .put("http.port", 3000))); */ // vertx.deployVerticle("com.syntel.vertx.SensorData"); /*vertx.deployVerticle(new RealTimeCollectorVertx(), res -> { if (res.succeeded()) { logger.info("Deployment id is: " + res.result()); } else { logger.info("Deployment failed!"); } });*/ /*vertx.deployVerticle(new VehicleVertx(), res -> { if (res.succeeded()) { logger.info("Deployment[VehicleVertx] id is: " + res.result()); } else { logger.info("Deployment VehicleVertx failed!"); } });*/ // vertx.deployVerticle(new BlockEventLoop()); } }
2,055
0.639416
0.626764
58
34.431034
29.540218
113
false
false
0
0
0
0
0
0
0.862069
false
false
10
bd1bed68cd853dfc10fb221983fc04299d1b5269
5,755,256,233,903
edd9fd9e6a4362277d1d32a12e384a57d5c15eb7
/MicroService/spring-mvc/springmvc01/src/main/java/com/github/support/service/TaskService.java
e942e99f4ba9510876e7219178d887ded3748fc0
[]
no_license
sxc588/studio
https://github.com/sxc588/studio
ca6ae5dd7ea8d24ff32b98d03e18dd81cafadb92
5bb5bb5d8c672ac963cb63470d36acc4a8b48f62
refs/heads/master
2022-12-23T09:27:32.968000
2020-07-20T17:02:00
2020-07-20T17:02:00
71,612,687
0
2
null
false
2022-12-16T10:49:10
2016-10-22T02:51:04
2020-07-20T17:02:26
2022-12-16T10:49:08
75,120
0
1
560
JavaScript
false
false
package com.github.support.service; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.springframework.stereotype.Service; @Service public class TaskService { }
UTF-8
Java
208
java
TaskService.java
Java
[]
null
[]
package com.github.support.service; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.springframework.stereotype.Service; @Service public class TaskService { }
208
0.764423
0.764423
11
16.90909
15.180457
46
false
false
0
0
0
0
0
0
0.454545
false
false
10
fcfe496d88c71b16a4e877210c643a41f77f1192
9,809,705,336,949
ac3a7a8d120d4e281431329c8c9d388fcfb94342
/src/main/java/com/leetcode/algorithm/hard/expressionaddoperators/Solution.java
bf55f9abc66d7c828219b6cef274545e2601cc70
[ "MIT" ]
permissive
paulxi/LeetCodeJava
https://github.com/paulxi/LeetCodeJava
c69014c24cda48f80a25227b7ac09c6c5d6cfadc
10b4430629314c7cfedaae02c7dc4c2318ea6256
refs/heads/master
2021-04-03T08:03:16.305000
2021-03-02T06:20:24
2021-03-02T06:20:24
125,126,097
3
3
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.leetcode.algorithm.hard.expressionaddoperators; import java.util.ArrayList; import java.util.List; class Solution { public List<String> addOperators(String num, int target) { List<String> result = new ArrayList<>(); helper(num, target, 0, 0, 0, "", result); return result; } private void helper(String num, int target, int pos, long prev, long curr, String path, List<String> result) { if (pos == num.length()) { if (target == curr) { result.add(path); } return; } for (int len = 1; len + pos <= num.length(); len++) { String sub = num.substring(pos, len + pos); if (sub.startsWith("0") && len > 1) { break; } long n = Long.parseLong(sub); if (pos == 0) { helper(num, target, len, n, n, path + sub, result); } else { helper(num, target, pos + len, n, curr + n, path + "+" + sub, result); helper(num, target, pos + len, -n, curr - n, path + "-" + sub, result); helper(num, target, pos + len, n * prev, curr - prev + n * prev, path + "*" + sub, result); } } } }
UTF-8
Java
1,122
java
Solution.java
Java
[]
null
[]
package com.leetcode.algorithm.hard.expressionaddoperators; import java.util.ArrayList; import java.util.List; class Solution { public List<String> addOperators(String num, int target) { List<String> result = new ArrayList<>(); helper(num, target, 0, 0, 0, "", result); return result; } private void helper(String num, int target, int pos, long prev, long curr, String path, List<String> result) { if (pos == num.length()) { if (target == curr) { result.add(path); } return; } for (int len = 1; len + pos <= num.length(); len++) { String sub = num.substring(pos, len + pos); if (sub.startsWith("0") && len > 1) { break; } long n = Long.parseLong(sub); if (pos == 0) { helper(num, target, len, n, n, path + sub, result); } else { helper(num, target, pos + len, n, curr + n, path + "+" + sub, result); helper(num, target, pos + len, -n, curr - n, path + "-" + sub, result); helper(num, target, pos + len, n * prev, curr - prev + n * prev, path + "*" + sub, result); } } } }
1,122
0.55615
0.549911
38
28.526316
29.136463
112
false
false
0
0
0
0
0
0
1.447368
false
false
10
ade57fa2bfbf4408602589402da57a07699bb01a
8,134,668,085,540
b09bed3e30f2de9957a8db01a76b326611a02ee4
/src/org/snake/game/Game.java
471c6624461cd15d6810416715d6486b434f673e
[]
no_license
Faris-Mckay/Snake
https://github.com/Faris-Mckay/Snake
e53ede1e8192defbd15e2b394aeec5d7dcc8e285
011f33b3d51aa2a2dc57810b34d4a8b8cc8c9781
refs/heads/master
2020-05-26T23:01:07.848000
2012-10-14T15:54:02
2012-10-14T15:54:02
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.snake.game; import java.sql.Time; import org.snake.game.entity.Entity; import org.snake.task.UpdateableTask; import org.snake.game.entity.impl.Egg; import org.snake.game.entity.impl.Snake; import org.snake.util.Miscellaneous; /** * * @author Faris */ public class Game implements UpdateableTask { @Override public void update() { //ObjectAction.getCanvas().initComponents("Score: "+score); } public Game(){ gameStarted = true; startTime = new Time(System.currentTimeMillis()); Entity.createEntity(new Snake()); Entity.createEntity(new Egg()); } public static Game currentGame = null; /** * Creates a single instance of this class and makes sure only this instance is modified * @returns the instance */ public static Game getSingleton(){ if(currentGame == null){ currentGame = new Game(); } return currentGame; } /** * Stores the current score value */ public static short score = 0; /** * Usage to prevent null pointer exceptions */ public boolean gameStarted = false; /** * Stores time objects for time played */ private Time startTime = null, endTime = null; /** * Variables associated with stopping the game of snake */ public void endGame(){ endTime = new Time(System.currentTimeMillis()); Miscellaneous.log("You played for "+startTime.getTime() % endTime.getTime()); } /** * @return the score */ public short getScore() { return score; } /** * @param score the score to set */ public void setScore(short score) { this.score = score; } }
UTF-8
Java
1,798
java
Game.java
Java
[ { "context": "t org.snake.util.Miscellaneous;\n\n/**\n *\n * @author Faris\n */\npublic class Game implements UpdateableTask {", "end": 263, "score": 0.9991601705551147, "start": 258, "tag": "NAME", "value": "Faris" } ]
null
[]
package org.snake.game; import java.sql.Time; import org.snake.game.entity.Entity; import org.snake.task.UpdateableTask; import org.snake.game.entity.impl.Egg; import org.snake.game.entity.impl.Snake; import org.snake.util.Miscellaneous; /** * * @author Faris */ public class Game implements UpdateableTask { @Override public void update() { //ObjectAction.getCanvas().initComponents("Score: "+score); } public Game(){ gameStarted = true; startTime = new Time(System.currentTimeMillis()); Entity.createEntity(new Snake()); Entity.createEntity(new Egg()); } public static Game currentGame = null; /** * Creates a single instance of this class and makes sure only this instance is modified * @returns the instance */ public static Game getSingleton(){ if(currentGame == null){ currentGame = new Game(); } return currentGame; } /** * Stores the current score value */ public static short score = 0; /** * Usage to prevent null pointer exceptions */ public boolean gameStarted = false; /** * Stores time objects for time played */ private Time startTime = null, endTime = null; /** * Variables associated with stopping the game of snake */ public void endGame(){ endTime = new Time(System.currentTimeMillis()); Miscellaneous.log("You played for "+startTime.getTime() % endTime.getTime()); } /** * @return the score */ public short getScore() { return score; } /** * @param score the score to set */ public void setScore(short score) { this.score = score; } }
1,798
0.595106
0.594549
81
21.197531
20.686024
92
false
false
0
0
0
0
0
0
0.283951
false
false
10
fef27920c21a4cc62a01e4bd258e0ae892d74ecf
17,076,790,001,912
a7ade37f1260ff081dba122c1ac8c67081021645
/League/app/src/main/java/alex/league/api/API.java
5db87c4f6c17ac9511b154b1396bf2ec451f4b0c
[]
no_license
alexherrera33/023684_Herrera_Examenextra
https://github.com/alexherrera33/023684_Herrera_Examenextra
6ff806dbcfccb272cf54c293fc731243d0e79e31
b7ef77a1d16bd538cd0a6b52eb10777f0ea62487
refs/heads/master
2021-05-13T21:58:01.916000
2018-01-06T11:08:52
2018-01-06T11:08:52
116,476,764
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package alex.league.api; import android.app.ProgressDialog; import android.content.Context; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import android.os.AsyncTask; import android.widget.Toast; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.HashMap; import alex.league.Leagues; import alex.league.R; import alex.league.database.Db; import alex.league.utils.ApplicationContanst; import alex.league.utils.JSONfunctions; public class API { Db usdbh; SQLiteDatabase db; Context ctx; Leagues objleagues; ProgressDialog pDialog; JSONObject jsonobject; JSONArray jsonarray,teams,players; String league,id_team; public API(Context ctx) { this.ctx = ctx; usdbh = new Db(ctx, "LEAGUES", null, 1); db = usdbh.getWritableDatabase(); } public class get_leagues extends AsyncTask<Void, Void, Void> { @Override protected void onPreExecute() { super.onPreExecute(); pDialog = new ProgressDialog(ctx); pDialog.setTitle(ctx.getResources().getString(R.string.app_name)); pDialog.setMessage("Cargando Ligas"); pDialog.setIndeterminate(false); pDialog.setCancelable(false); pDialog.setIcon(R.mipmap.ic_launcher); pDialog.show(); } @Override protected Void doInBackground(Void... params) { objleagues = (Leagues) ctx; objleagues.leagues = new ArrayList<HashMap<String, String>>(); try { jsonarray = JSONfunctions.getJSONfromURL(ApplicationContanst.URL_API +"leagues"); System.out.println("valor "+jsonobject); if (jsonarray != null) { for (int i = 0; i < jsonarray.length(); i++) { jsonobject = jsonarray.getJSONObject(i); //insertamos en la base de datos sqlite league = jsonobject.getString("league"); if(db != null) { try { db.execSQL("insert into leagues(id_league,league,owner) values('"+ jsonobject.getString("id")+"','"+league+"','"+jsonobject.getString("owner")+"') "); }catch (SQLException e) { System.out.println("error no encontro"); } } league = jsonobject.getString("id"); //guardamos los teams teams = jsonobject.getJSONArray("teams"); for (int j = 0; j < teams.length(); j++) { jsonobject = teams.getJSONObject(j); if(db != null) { try { System.out.println("team "+jsonobject.getString("team")); System.out.println("owner "+jsonobject.getString("owner")); System.out.println("rank "+jsonobject.getString("rank")); System.out.println("id "+jsonobject.getString("id")); id_team = jsonobject.getString("id"); db.execSQL("insert into teams(team,owner,rank,id,id_league) values('"+jsonobject.getString("team")+"','"+jsonobject.getString("owner")+"',"+jsonobject.getString("rank")+",'"+jsonobject.getString("id")+"','"+league+"') "); System.out.println("jsonobject "+jsonobject); if(jsonobject.has("players")) { System.out.println("si existe"); players = jsonobject.getJSONArray("players"); if(players != null) { for (int h = 0; h < players.length(); h++) { jsonobject = players.getJSONObject(h); System.out.println("name "+jsonobject.getString("name")); System.out.println("position "+jsonobject.getString("position")); System.out.println("team "+jsonobject.getString("team")); System.out.println("id_team "+id_team); try { db.execSQL("insert into players(name,position,team,id_team) values('"+jsonobject.getString("name")+"','"+jsonobject.getString("position")+"','"+jsonobject.getString("team")+"','"+id_team+"')"); }catch (SQLException e) { System.out.print("fallo al insertar "+e.getMessage()); } } } } else { System.out.println("NO existe"); } }catch (SQLException e) { } } } } } }catch(JSONException e){ e.printStackTrace(); } return null; } @Override protected void onPostExecute(Void result) { super.onPostExecute(result); pDialog.dismiss(); if(jsonobject != null) { objleagues.get_leagues(); } else { Toast.makeText(ctx,"Error en la API",Toast.LENGTH_LONG).show(); } } } }
UTF-8
Java
6,597
java
API.java
Java
[]
null
[]
package alex.league.api; import android.app.ProgressDialog; import android.content.Context; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import android.os.AsyncTask; import android.widget.Toast; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.HashMap; import alex.league.Leagues; import alex.league.R; import alex.league.database.Db; import alex.league.utils.ApplicationContanst; import alex.league.utils.JSONfunctions; public class API { Db usdbh; SQLiteDatabase db; Context ctx; Leagues objleagues; ProgressDialog pDialog; JSONObject jsonobject; JSONArray jsonarray,teams,players; String league,id_team; public API(Context ctx) { this.ctx = ctx; usdbh = new Db(ctx, "LEAGUES", null, 1); db = usdbh.getWritableDatabase(); } public class get_leagues extends AsyncTask<Void, Void, Void> { @Override protected void onPreExecute() { super.onPreExecute(); pDialog = new ProgressDialog(ctx); pDialog.setTitle(ctx.getResources().getString(R.string.app_name)); pDialog.setMessage("Cargando Ligas"); pDialog.setIndeterminate(false); pDialog.setCancelable(false); pDialog.setIcon(R.mipmap.ic_launcher); pDialog.show(); } @Override protected Void doInBackground(Void... params) { objleagues = (Leagues) ctx; objleagues.leagues = new ArrayList<HashMap<String, String>>(); try { jsonarray = JSONfunctions.getJSONfromURL(ApplicationContanst.URL_API +"leagues"); System.out.println("valor "+jsonobject); if (jsonarray != null) { for (int i = 0; i < jsonarray.length(); i++) { jsonobject = jsonarray.getJSONObject(i); //insertamos en la base de datos sqlite league = jsonobject.getString("league"); if(db != null) { try { db.execSQL("insert into leagues(id_league,league,owner) values('"+ jsonobject.getString("id")+"','"+league+"','"+jsonobject.getString("owner")+"') "); }catch (SQLException e) { System.out.println("error no encontro"); } } league = jsonobject.getString("id"); //guardamos los teams teams = jsonobject.getJSONArray("teams"); for (int j = 0; j < teams.length(); j++) { jsonobject = teams.getJSONObject(j); if(db != null) { try { System.out.println("team "+jsonobject.getString("team")); System.out.println("owner "+jsonobject.getString("owner")); System.out.println("rank "+jsonobject.getString("rank")); System.out.println("id "+jsonobject.getString("id")); id_team = jsonobject.getString("id"); db.execSQL("insert into teams(team,owner,rank,id,id_league) values('"+jsonobject.getString("team")+"','"+jsonobject.getString("owner")+"',"+jsonobject.getString("rank")+",'"+jsonobject.getString("id")+"','"+league+"') "); System.out.println("jsonobject "+jsonobject); if(jsonobject.has("players")) { System.out.println("si existe"); players = jsonobject.getJSONArray("players"); if(players != null) { for (int h = 0; h < players.length(); h++) { jsonobject = players.getJSONObject(h); System.out.println("name "+jsonobject.getString("name")); System.out.println("position "+jsonobject.getString("position")); System.out.println("team "+jsonobject.getString("team")); System.out.println("id_team "+id_team); try { db.execSQL("insert into players(name,position,team,id_team) values('"+jsonobject.getString("name")+"','"+jsonobject.getString("position")+"','"+jsonobject.getString("team")+"','"+id_team+"')"); }catch (SQLException e) { System.out.print("fallo al insertar "+e.getMessage()); } } } } else { System.out.println("NO existe"); } }catch (SQLException e) { } } } } } }catch(JSONException e){ e.printStackTrace(); } return null; } @Override protected void onPostExecute(Void result) { super.onPostExecute(result); pDialog.dismiss(); if(jsonobject != null) { objleagues.get_leagues(); } else { Toast.makeText(ctx,"Error en la API",Toast.LENGTH_LONG).show(); } } } }
6,597
0.423071
0.422465
217
29.400921
36.330036
257
false
false
0
0
0
0
0
0
0.483871
false
false
10
83837c858701cf8cd2ec2da17cd4257193a3ec7e
14,620,068,711,091
91b8dd01981b6b70faf71e66e34cf61a006a55a8
/src/com/andrei1058/reporting/bungee/Main.java
86b76efa2813c162861b86314a12e6d5ebe59df3
[]
no_license
NycuRO/Reporting1058
https://github.com/NycuRO/Reporting1058
c898b6f573377ea6992011c5c8c7d039c6f6b596
58501cf02395f6880fa928c18456a100c6fce7a1
refs/heads/master
2020-02-29T21:52:52.267000
2017-05-04T16:18:41
2017-05-04T16:18:41
90,284,206
0
0
null
true
2017-05-04T16:16:49
2017-05-04T16:16:48
2017-01-07T12:26:31
2017-05-04T15:30:15
99
0
0
0
null
null
null
package com.andrei1058.reporting.bungee; import com.andrei1058.reporting.bungee.commands.*; import com.andrei1058.reporting.bungee.metrics.bStats; import com.andrei1058.reporting.bungee.misc.Listeners; import com.andrei1058.reporting.bungee.settings.Configuration; import net.md_5.bungee.api.plugin.Plugin; import net.md_5.bungee.api.plugin.PluginManager; import java.util.ArrayList; public class Main extends Plugin { public static Main plugin; public static boolean titles = true; public static boolean action = true; public static boolean mysql = false; public static int suspect = 5; public static long rep_cooldown = 20000; public static boolean motd = true; public static int r_p_p = 7; public static ArrayList<String> disabled_servers = new ArrayList<>(); @Override public void onEnable() { plugin = this; Configuration.setupConfig(); PluginManager pm = getProxy().getPluginManager(); pm.registerCommand(this, new Report()); pm.registerCommand(this, new ReportsList("reportslist")); pm.registerCommand(this, new ReportsList("reportlist")); pm.registerCommand(this, new ReportsList("reports")); pm.registerCommand(this, new ReportsList("rlist")); pm.registerCommand(this, new DelReport("delreport")); pm.registerCommand(this, new DelReport("rdel")); pm.registerCommand(this, new Reporting1058("reporting1058")); pm.registerCommand(this, new Reporting1058("reporting")); pm.registerCommand(this, new ReportInfo("reportinfo")); pm.registerCommand(this, new ReportInfo("rinfo")); pm.registerCommand(this, new CloseReport("closereport")); pm.registerCommand(this, new CloseReport("rclose")); pm.registerCommand(this, new ActiveReports("areports")); pm.registerCommand(this, new ActiveReports("activereports")); pm.registerCommand(this, new CloseReports()); pm.registerListener(this, new Listeners()); pm.registerCommand(this, new DelReports("delreports")); pm.registerCommand(this, new DelReports("rdelall")); pm.registerCommand(this, new MostReported("mostreported")); pm.registerCommand(this, new MostReported("mreported")); pm.registerCommand(this, new MostReported("rmost")); new bStats(this); } }
UTF-8
Java
2,363
java
Main.java
Java
[ { "context": "package com.andrei1058.reporting.bungee;\n\nimport com.andrei1058.reportin", "end": 22, "score": 0.968116283416748, "start": 12, "tag": "USERNAME", "value": "andrei1058" }, { "context": "kage com.andrei1058.reporting.bungee;\n\nimport com.andrei1058.reporting.bungee.commands.*;\nimport com.andrei105", "end": 63, "score": 0.9930596351623535, "start": 53, "tag": "USERNAME", "value": "andrei1058" }, { "context": "ndrei1058.reporting.bungee.commands.*;\nimport com.andrei1058.reporting.bungee.metrics.bStats;\nimport com.andre", "end": 114, "score": 0.937694787979126, "start": 104, "tag": "USERNAME", "value": "andrei1058" }, { "context": "58.reporting.bungee.metrics.bStats;\nimport com.andrei1058.reporting.bungee.misc.Listeners;\nimport com.andre", "end": 169, "score": 0.978352427482605, "start": 162, "tag": "USERNAME", "value": "rei1058" }, { "context": "i1058.reporting.bungee.misc.Listeners;\nimport com.andrei1058.reporting.bungee.settings.Configuration;\nimport n", "end": 224, "score": 0.9516913294792175, "start": 214, "tag": "USERNAME", "value": "andrei1058" } ]
null
[]
package com.andrei1058.reporting.bungee; import com.andrei1058.reporting.bungee.commands.*; import com.andrei1058.reporting.bungee.metrics.bStats; import com.andrei1058.reporting.bungee.misc.Listeners; import com.andrei1058.reporting.bungee.settings.Configuration; import net.md_5.bungee.api.plugin.Plugin; import net.md_5.bungee.api.plugin.PluginManager; import java.util.ArrayList; public class Main extends Plugin { public static Main plugin; public static boolean titles = true; public static boolean action = true; public static boolean mysql = false; public static int suspect = 5; public static long rep_cooldown = 20000; public static boolean motd = true; public static int r_p_p = 7; public static ArrayList<String> disabled_servers = new ArrayList<>(); @Override public void onEnable() { plugin = this; Configuration.setupConfig(); PluginManager pm = getProxy().getPluginManager(); pm.registerCommand(this, new Report()); pm.registerCommand(this, new ReportsList("reportslist")); pm.registerCommand(this, new ReportsList("reportlist")); pm.registerCommand(this, new ReportsList("reports")); pm.registerCommand(this, new ReportsList("rlist")); pm.registerCommand(this, new DelReport("delreport")); pm.registerCommand(this, new DelReport("rdel")); pm.registerCommand(this, new Reporting1058("reporting1058")); pm.registerCommand(this, new Reporting1058("reporting")); pm.registerCommand(this, new ReportInfo("reportinfo")); pm.registerCommand(this, new ReportInfo("rinfo")); pm.registerCommand(this, new CloseReport("closereport")); pm.registerCommand(this, new CloseReport("rclose")); pm.registerCommand(this, new ActiveReports("areports")); pm.registerCommand(this, new ActiveReports("activereports")); pm.registerCommand(this, new CloseReports()); pm.registerListener(this, new Listeners()); pm.registerCommand(this, new DelReports("delreports")); pm.registerCommand(this, new DelReports("rdelall")); pm.registerCommand(this, new MostReported("mostreported")); pm.registerCommand(this, new MostReported("mreported")); pm.registerCommand(this, new MostReported("rmost")); new bStats(this); } }
2,363
0.70165
0.6843
51
45.333332
20.200628
73
false
false
0
0
0
0
0
0
1.27451
false
false
10
e46f0bfe99408c62994f6f4b89a466619cc3779d
28,003,186,802,547
a6a19127b9720eadc0909161f70241c3f322f126
/olastic-core/src/main/java/com/hevelian/olastic/core/elastic/requests/creators/BucketsAggregationsRequestCreator.java
6e3edb97be91adb4c11b1ed2348661d6ee41d90e
[ "Apache-2.0" ]
permissive
RuslanDidyk/hevelian-olastic
https://github.com/RuslanDidyk/hevelian-olastic
e735efaa2fe035e2ab13745d48b5fa37959b3d38
505c374ddb5d563fc7cdc7daf3410217584fd69d
refs/heads/master
2020-12-24T07:47:37.609000
2017-05-08T11:47:20
2017-05-08T11:47:20
73,367,677
2
0
null
true
2016-11-10T09:39:57
2016-11-10T09:39:57
2016-10-07T05:29:16
2016-10-08T06:18:15
68
0
0
0
null
null
null
package com.hevelian.olastic.core.elastic.requests.creators; import static com.hevelian.olastic.core.elastic.utils.ElasticUtils.addKeywordIfNeeded; import static com.hevelian.olastic.core.utils.ApplyOptionUtils.getAggregations; import static com.hevelian.olastic.core.utils.ApplyOptionUtils.getGroupByItems; import static com.hevelian.olastic.core.utils.ProcessorUtils.throwNotImplemented; import static java.util.Collections.reverse; import static java.util.stream.Collectors.toMap; import static org.elasticsearch.search.aggregations.AggregationBuilders.terms; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Locale; import java.util.Map; import org.apache.olingo.commons.api.http.HttpStatusCode; import org.apache.olingo.server.api.ODataApplicationException; import org.apache.olingo.server.api.uri.UriInfo; import org.apache.olingo.server.api.uri.UriResource; import org.apache.olingo.server.api.uri.UriResourceKind; import org.apache.olingo.server.api.uri.queryoption.apply.GroupBy; import org.apache.olingo.server.api.uri.queryoption.apply.GroupByItem; import org.elasticsearch.search.aggregations.AggregationBuilder; import org.elasticsearch.search.aggregations.bucket.terms.Terms; import org.elasticsearch.search.aggregations.bucket.terms.Terms.Order; import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder; import com.hevelian.olastic.core.edm.ElasticEdmEntitySet; import com.hevelian.olastic.core.edm.ElasticEdmEntityType; import com.hevelian.olastic.core.edm.ElasticEdmProperty; import com.hevelian.olastic.core.elastic.builders.ESQueryBuilder; import com.hevelian.olastic.core.elastic.pagination.Pagination; import com.hevelian.olastic.core.elastic.pagination.Sort.Direction; import com.hevelian.olastic.core.elastic.queries.AggregateQuery; import com.hevelian.olastic.core.elastic.queries.Query; import com.hevelian.olastic.core.elastic.requests.AggregateRequest; import com.hevelian.olastic.core.elastic.requests.ESRequest; /** * Class responsible for creating {@link AggregateRequest} instance for buckets * aggregations with metrics. * * @author rdidyk */ public class BucketsAggregationsRequestCreator extends AbstractAggregationsRequestCreator { /** * Default constructor. */ public BucketsAggregationsRequestCreator() { super(); } /** * Constructor to initialize ES query builder. * * @param queryBuilder * ES query builder */ public BucketsAggregationsRequestCreator(ESQueryBuilder<?> queryBuilder) { super(queryBuilder); } @Override public AggregateRequest create(UriInfo uriInfo) throws ODataApplicationException { ESRequest baseRequestInfo = getBaseRequestInfo(uriInfo); Query baseQuery = baseRequestInfo.getQuery(); ElasticEdmEntitySet entitySet = baseRequestInfo.getEntitySet(); ElasticEdmEntityType entityType = entitySet.getEntityType(); List<GroupBy> groupByItems = getGroupByItems(uriInfo.getApplyOption()); if (groupByItems.size() > 1) { throwNotImplemented("Combining Transformations per Group is not supported."); } Pagination pagination = getPagination(uriInfo); List<AggregationBuilder> bucketsQueries = getBucketsQueries(groupByItems.get(0), entityType, pagination); AggregateQuery aggregateQuery = new AggregateQuery(baseQuery.getIndex(), baseQuery.getTypes(), baseQuery.getQueryBuilder(), bucketsQueries, Collections.emptyList()); return new AggregateRequest(aggregateQuery, entitySet, pagination, getCountAlias()); } /** * Get's buckets queries from {@link GroupBy} item in URL. * * @param groupBy * groupBy instance * @param entityType * entity type * @param pagination * pagination information * @return list of fields * @throws ODataApplicationException * if any error occurred */ protected List<AggregationBuilder> getBucketsQueries(GroupBy groupBy, ElasticEdmEntityType entityType, Pagination pagination) throws ODataApplicationException { int size = pagination.getSkip() + pagination.getTop(); Map<String, Boolean> orders = pagination.getOrderBy().stream().collect(toMap( order -> order.getProperty(), order -> order.getDirection() == Direction.ASC)); List<String> properties = getProperties(groupBy); reverse(properties); // Last because of reverse String lastProperty = properties.remove(0); String queryField = getQueryField(lastProperty, entityType); TermsAggregationBuilder groupByQuery = terms(lastProperty).field(queryField).size(size); getMetricsAggQueries(getAggregations(groupBy.getApplyOption())) .forEach(groupByQuery::subAggregation); List<Order> queryOrders = getQueryOrders(queryField, orders); if (!queryOrders.isEmpty()) { groupByQuery.order(queryOrders); } for (String property : properties) { queryField = getQueryField(property, entityType); groupByQuery = terms(property).field(queryField).size(size) .subAggregation(groupByQuery); Boolean termOrder = orders.remove(queryField); if (termOrder != null) { groupByQuery.order(Terms.Order.term(termOrder)); } } // Fields in $orderby are not same as $groupby fields! if (!orders.isEmpty()) { throw new ODataApplicationException( "Ordering only by fields in $groupby or $aggregation options is allowed.", HttpStatusCode.BAD_REQUEST.getStatusCode(), Locale.ROOT); } // For now only one 'groupby' is supported and returned in the list return Arrays.asList(groupByQuery); } /** * Get's properties from {@link #groupBy} for aggregation query. * * @param groupBy * groupBy instance * @return list of properties * @throws ODataApplicationException */ private static List<String> getProperties(GroupBy groupBy) throws ODataApplicationException { List<String> groupByProperties = new ArrayList<>(); for (GroupByItem item : groupBy.getGroupByItems()) { List<UriResource> path = item.getPath(); if (path.size() > 1) { throwNotImplemented("Grouping by navigation property is not supported yet."); } UriResource resource = path.get(0); if (resource.getKind() == UriResourceKind.primitiveProperty) { groupByProperties.add(resource.getSegmentValue()); } else { throwNotImplemented("Grouping by complex type is not supported yet."); } } return groupByProperties; } /** * Get's list of orders for first query, because it has metrics aggregations * and also can have count and term order. * * @param field * query field * @param ordersMap * orders map from URI * @return list of orders */ private List<Order> getQueryOrders(String field, Map<String, Boolean> ordersMap) { List<Order> orders = new ArrayList<>(); Boolean termOrder = ordersMap.remove(field); if (termOrder != null) { orders.add(Terms.Order.term(termOrder)); } Boolean countOrder = ordersMap.remove(getCountAlias()); if (countOrder != null) { orders.add(Terms.Order.count(countOrder)); } for (String alias : getMetricAliases()) { Boolean aliasOrder = ordersMap.remove(alias); if (aliasOrder != null) { orders.add(Terms.Order.aggregation(alias, aliasOrder)); } } return orders; } /** * Gets field for 'term' aggregation query by property from entity type. * * @param propertyName * property name * @param entityType * entity type * @return field for query */ private static String getQueryField(String propertyName, ElasticEdmEntityType entityType) { ElasticEdmProperty property = entityType.getEProperties().get(propertyName); return addKeywordIfNeeded(property.getEField(), property.getAnnotations()); } }
UTF-8
Java
8,571
java
BucketsAggregationsRequestCreator.java
Java
[ { "context": "ckets\n * aggregations with metrics.\n * \n * @author rdidyk\n */\npublic class BucketsAggregationsRequestCreato", "end": 2180, "score": 0.9995991587638855, "start": 2174, "tag": "USERNAME", "value": "rdidyk" } ]
null
[]
package com.hevelian.olastic.core.elastic.requests.creators; import static com.hevelian.olastic.core.elastic.utils.ElasticUtils.addKeywordIfNeeded; import static com.hevelian.olastic.core.utils.ApplyOptionUtils.getAggregations; import static com.hevelian.olastic.core.utils.ApplyOptionUtils.getGroupByItems; import static com.hevelian.olastic.core.utils.ProcessorUtils.throwNotImplemented; import static java.util.Collections.reverse; import static java.util.stream.Collectors.toMap; import static org.elasticsearch.search.aggregations.AggregationBuilders.terms; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Locale; import java.util.Map; import org.apache.olingo.commons.api.http.HttpStatusCode; import org.apache.olingo.server.api.ODataApplicationException; import org.apache.olingo.server.api.uri.UriInfo; import org.apache.olingo.server.api.uri.UriResource; import org.apache.olingo.server.api.uri.UriResourceKind; import org.apache.olingo.server.api.uri.queryoption.apply.GroupBy; import org.apache.olingo.server.api.uri.queryoption.apply.GroupByItem; import org.elasticsearch.search.aggregations.AggregationBuilder; import org.elasticsearch.search.aggregations.bucket.terms.Terms; import org.elasticsearch.search.aggregations.bucket.terms.Terms.Order; import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder; import com.hevelian.olastic.core.edm.ElasticEdmEntitySet; import com.hevelian.olastic.core.edm.ElasticEdmEntityType; import com.hevelian.olastic.core.edm.ElasticEdmProperty; import com.hevelian.olastic.core.elastic.builders.ESQueryBuilder; import com.hevelian.olastic.core.elastic.pagination.Pagination; import com.hevelian.olastic.core.elastic.pagination.Sort.Direction; import com.hevelian.olastic.core.elastic.queries.AggregateQuery; import com.hevelian.olastic.core.elastic.queries.Query; import com.hevelian.olastic.core.elastic.requests.AggregateRequest; import com.hevelian.olastic.core.elastic.requests.ESRequest; /** * Class responsible for creating {@link AggregateRequest} instance for buckets * aggregations with metrics. * * @author rdidyk */ public class BucketsAggregationsRequestCreator extends AbstractAggregationsRequestCreator { /** * Default constructor. */ public BucketsAggregationsRequestCreator() { super(); } /** * Constructor to initialize ES query builder. * * @param queryBuilder * ES query builder */ public BucketsAggregationsRequestCreator(ESQueryBuilder<?> queryBuilder) { super(queryBuilder); } @Override public AggregateRequest create(UriInfo uriInfo) throws ODataApplicationException { ESRequest baseRequestInfo = getBaseRequestInfo(uriInfo); Query baseQuery = baseRequestInfo.getQuery(); ElasticEdmEntitySet entitySet = baseRequestInfo.getEntitySet(); ElasticEdmEntityType entityType = entitySet.getEntityType(); List<GroupBy> groupByItems = getGroupByItems(uriInfo.getApplyOption()); if (groupByItems.size() > 1) { throwNotImplemented("Combining Transformations per Group is not supported."); } Pagination pagination = getPagination(uriInfo); List<AggregationBuilder> bucketsQueries = getBucketsQueries(groupByItems.get(0), entityType, pagination); AggregateQuery aggregateQuery = new AggregateQuery(baseQuery.getIndex(), baseQuery.getTypes(), baseQuery.getQueryBuilder(), bucketsQueries, Collections.emptyList()); return new AggregateRequest(aggregateQuery, entitySet, pagination, getCountAlias()); } /** * Get's buckets queries from {@link GroupBy} item in URL. * * @param groupBy * groupBy instance * @param entityType * entity type * @param pagination * pagination information * @return list of fields * @throws ODataApplicationException * if any error occurred */ protected List<AggregationBuilder> getBucketsQueries(GroupBy groupBy, ElasticEdmEntityType entityType, Pagination pagination) throws ODataApplicationException { int size = pagination.getSkip() + pagination.getTop(); Map<String, Boolean> orders = pagination.getOrderBy().stream().collect(toMap( order -> order.getProperty(), order -> order.getDirection() == Direction.ASC)); List<String> properties = getProperties(groupBy); reverse(properties); // Last because of reverse String lastProperty = properties.remove(0); String queryField = getQueryField(lastProperty, entityType); TermsAggregationBuilder groupByQuery = terms(lastProperty).field(queryField).size(size); getMetricsAggQueries(getAggregations(groupBy.getApplyOption())) .forEach(groupByQuery::subAggregation); List<Order> queryOrders = getQueryOrders(queryField, orders); if (!queryOrders.isEmpty()) { groupByQuery.order(queryOrders); } for (String property : properties) { queryField = getQueryField(property, entityType); groupByQuery = terms(property).field(queryField).size(size) .subAggregation(groupByQuery); Boolean termOrder = orders.remove(queryField); if (termOrder != null) { groupByQuery.order(Terms.Order.term(termOrder)); } } // Fields in $orderby are not same as $groupby fields! if (!orders.isEmpty()) { throw new ODataApplicationException( "Ordering only by fields in $groupby or $aggregation options is allowed.", HttpStatusCode.BAD_REQUEST.getStatusCode(), Locale.ROOT); } // For now only one 'groupby' is supported and returned in the list return Arrays.asList(groupByQuery); } /** * Get's properties from {@link #groupBy} for aggregation query. * * @param groupBy * groupBy instance * @return list of properties * @throws ODataApplicationException */ private static List<String> getProperties(GroupBy groupBy) throws ODataApplicationException { List<String> groupByProperties = new ArrayList<>(); for (GroupByItem item : groupBy.getGroupByItems()) { List<UriResource> path = item.getPath(); if (path.size() > 1) { throwNotImplemented("Grouping by navigation property is not supported yet."); } UriResource resource = path.get(0); if (resource.getKind() == UriResourceKind.primitiveProperty) { groupByProperties.add(resource.getSegmentValue()); } else { throwNotImplemented("Grouping by complex type is not supported yet."); } } return groupByProperties; } /** * Get's list of orders for first query, because it has metrics aggregations * and also can have count and term order. * * @param field * query field * @param ordersMap * orders map from URI * @return list of orders */ private List<Order> getQueryOrders(String field, Map<String, Boolean> ordersMap) { List<Order> orders = new ArrayList<>(); Boolean termOrder = ordersMap.remove(field); if (termOrder != null) { orders.add(Terms.Order.term(termOrder)); } Boolean countOrder = ordersMap.remove(getCountAlias()); if (countOrder != null) { orders.add(Terms.Order.count(countOrder)); } for (String alias : getMetricAliases()) { Boolean aliasOrder = ordersMap.remove(alias); if (aliasOrder != null) { orders.add(Terms.Order.aggregation(alias, aliasOrder)); } } return orders; } /** * Gets field for 'term' aggregation query by property from entity type. * * @param propertyName * property name * @param entityType * entity type * @return field for query */ private static String getQueryField(String propertyName, ElasticEdmEntityType entityType) { ElasticEdmProperty property = entityType.getEProperties().get(propertyName); return addKeywordIfNeeded(property.getEField(), property.getAnnotations()); } }
8,571
0.680201
0.679617
208
40.20673
28.906025
100
false
false
0
0
0
0
0
0
0.5
false
false
10
86c7b0a5cd3c7a797536d7c871cef24b1c3e5141
8,658,654,122,351
2c11b97a861edec4f09a985b6678d824d789c28b
/src/edu/ucuccs/pangasinandisastermap/CameraHolder.java
64f14896f0bc60813da5f5acc11111475f9e2dbf
[]
no_license
dondonalbay/Pangasinan-Mobile-Disaster
https://github.com/dondonalbay/Pangasinan-Mobile-Disaster
2100f3bd39b6d009b4b32e4b449bee5c63d49b1c
5243591ca44e337bbd6c65b972b425e02e345c2b
refs/heads/master
2021-01-13T01:28:54.404000
2020-02-11T10:01:05
2020-02-11T10:01:05
24,141,007
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package edu.ucuccs.pangasinandisastermap; import java.io.IOException; import android.content.Context; import android.hardware.Camera; import android.view.SurfaceHolder; import android.view.SurfaceView; public class CameraHolder extends SurfaceView implements SurfaceHolder.Callback { Camera cam; SurfaceHolder sfh; public CameraHolder(Context context, Camera camera) { super(context); // TODO Auto-generated constructor stub cam=camera; sfh=getHolder(); sfh.addCallback(this); } @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { // TODO Auto-generated method stub } @Override public void surfaceCreated(SurfaceHolder holder) { // TODO Auto-generated method stub try { cam.setPreviewDisplay(holder); cam.startPreview(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } @Override public void surfaceDestroyed(SurfaceHolder holder) { // TODO Auto-generated method stub cam.stopPreview(); } }
UTF-8
Java
1,053
java
CameraHolder.java
Java
[]
null
[]
package edu.ucuccs.pangasinandisastermap; import java.io.IOException; import android.content.Context; import android.hardware.Camera; import android.view.SurfaceHolder; import android.view.SurfaceView; public class CameraHolder extends SurfaceView implements SurfaceHolder.Callback { Camera cam; SurfaceHolder sfh; public CameraHolder(Context context, Camera camera) { super(context); // TODO Auto-generated constructor stub cam=camera; sfh=getHolder(); sfh.addCallback(this); } @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { // TODO Auto-generated method stub } @Override public void surfaceCreated(SurfaceHolder holder) { // TODO Auto-generated method stub try { cam.setPreviewDisplay(holder); cam.startPreview(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } @Override public void surfaceDestroyed(SurfaceHolder holder) { // TODO Auto-generated method stub cam.stopPreview(); } }
1,053
0.736942
0.736942
54
18.5
19.620237
81
false
false
0
0
0
0
0
0
1.574074
false
false
10
43776036c9428483a258028a3c35477ccd0d288b
15,547,781,616,344
d6fa90192bf88513659cf99d18b5e70780bfa005
/src/IsBalanced.java
bd3d6f9ee6944192e055aef01772aec0f92fa12e
[]
no_license
damonxue/algo
https://github.com/damonxue/algo
94748333f27f5530d63a23af85c0b4a5bf1da263
efa13e900d908e589357d613e3f5814ce2466b13
refs/heads/main
2023-08-29T00:23:11.817000
2021-10-20T06:43:16
2021-10-20T06:43:16
419,235,408
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
public class IsBalanced { public boolean isBalanced(TreeNode root) { if (root == null){ return true; } int value = Math.abs(treeHeight(root.left)-treeHeight(root.right)); boolean temp = true; if (value>1){ temp = false; } return temp&&(isBalanced(root.left))&&(isBalanced(root.right)); } public int treeHeight(TreeNode root){ if (root == null){ return 0; } int leftH = treeHeight(root.left); int rightH = treeHeight(root.right); return Math.max(leftH+1,rightH+1); } }
UTF-8
Java
620
java
IsBalanced.java
Java
[]
null
[]
public class IsBalanced { public boolean isBalanced(TreeNode root) { if (root == null){ return true; } int value = Math.abs(treeHeight(root.left)-treeHeight(root.right)); boolean temp = true; if (value>1){ temp = false; } return temp&&(isBalanced(root.left))&&(isBalanced(root.right)); } public int treeHeight(TreeNode root){ if (root == null){ return 0; } int leftH = treeHeight(root.left); int rightH = treeHeight(root.right); return Math.max(leftH+1,rightH+1); } }
620
0.540323
0.533871
22
27.181818
20.323824
75
false
false
0
0
0
0
0
0
0.454545
false
false
10
390089570ec796164500abeb8d01826ebf597ace
20,856,361,224,951
1d53e9d5972687a23b4b2807c209749c22338769
/driver/src/ru/aplix/mera/scales/LoadMessage.java
ed459fadf30d6695b03e91d25b693ce1f4ffc5ba
[]
no_license
widgetii/mera-scales-java-pure-driver
https://github.com/widgetii/mera-scales-java-pure-driver
cd5f0854cd11475a4e839f3c027adda159c3f47f
2f5ae4d17a348da87e2f4b554111d6429469333f
refs/heads/master
2021-05-14T23:27:10.765000
2013-11-14T10:49:13
2013-11-14T10:49:13
104,662,373
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ru.aplix.mera.scales; import ru.aplix.mera.scales.backend.WeightUpdate; /** * Weight load/unload event message. * * <p>This message is sent when the scales are loaded or unloaded with new * weight. This happens when the weight changes after significant amount * of time it was steady.</p> */ public class LoadMessage { private final WeightUpdate update; private final boolean loaded; LoadMessage(WeightUpdate update, boolean loaded) { this.update = update; this.loaded = loaded; } /** * The indicated weight. * * <p>Note that this value can not be relied upon. It may change in the * next moment, because of the scales fluctuations, when the weight is * dropped onto the scales.</p> * * @return weight in metric grams. */ public final int getWeight() { return this.update.getWeight(); } /** * Whether the weight is loaded or unloaded. * * @return <code>true</code> if the weight on the scales have been * increased, or <code>false</code> otherwise. */ public boolean isLoaded() { return this.loaded; } @Override public String toString() { if (this.update == null) { return super.toString(); } return "LoadMessage[" + getWeight() + (this.loaded ? "g loaded]" : "g unloaded]"); } }
UTF-8
Java
1,263
java
LoadMessage.java
Java
[]
null
[]
package ru.aplix.mera.scales; import ru.aplix.mera.scales.backend.WeightUpdate; /** * Weight load/unload event message. * * <p>This message is sent when the scales are loaded or unloaded with new * weight. This happens when the weight changes after significant amount * of time it was steady.</p> */ public class LoadMessage { private final WeightUpdate update; private final boolean loaded; LoadMessage(WeightUpdate update, boolean loaded) { this.update = update; this.loaded = loaded; } /** * The indicated weight. * * <p>Note that this value can not be relied upon. It may change in the * next moment, because of the scales fluctuations, when the weight is * dropped onto the scales.</p> * * @return weight in metric grams. */ public final int getWeight() { return this.update.getWeight(); } /** * Whether the weight is loaded or unloaded. * * @return <code>true</code> if the weight on the scales have been * increased, or <code>false</code> otherwise. */ public boolean isLoaded() { return this.loaded; } @Override public String toString() { if (this.update == null) { return super.toString(); } return "LoadMessage[" + getWeight() + (this.loaded ? "g loaded]" : "g unloaded]"); } }
1,263
0.684877
0.684877
55
21.963636
22.325659
74
false
false
0
0
0
0
0
0
1.109091
false
false
10
c6773521cb575e237f216fa46575dc3a5f36441a
10,960,756,587,433
2510d558f40675fc70443a149f3dd869ec95c177
/src/main/java/com/rest/army/dashboard/service/EmployeeService.java
5e1d89ce884796d22ed29a5a5aeaa10d8e0d3bf4
[]
no_license
Emi14/armyRestService
https://github.com/Emi14/armyRestService
9362cbac67be4ca85f2f8d6b2897f97888e952c8
294d351fb8fae55137f2fbcdb8383e02183c16c6
refs/heads/master
2021-09-10T02:35:38.704000
2018-03-20T18:42:16
2018-03-20T18:42:16
113,662,973
0
0
null
false
2018-03-20T18:42:17
2017-12-09T11:04:01
2018-01-27T21:08:19
2018-03-20T18:42:16
57
0
0
0
Java
false
null
package com.rest.army.dashboard.service; import com.rest.army.dashboard.mapper.Mapper; import com.rest.army.dashboard.model.Employee; import com.rest.army.dashboard.repository.IEmployeeRepository; import com.rest.army.dashboard.resource.EmployeeResource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.List; /** * Created by ionutmihailescu on 1/24/18. */ @Service public class EmployeeService { @Autowired private IEmployeeRepository employeeRepository; @Autowired private Mapper mapper; public List<EmployeeResource> findAll() { List<EmployeeResource> employeeResources = new ArrayList<>(); mapper.mapAsCollection(employeeRepository.findAll(), employeeResources, EmployeeResource.class); return employeeResources; } public EmployeeResource findById(Long employeeId) { EmployeeResource employeeResource = new EmployeeResource(); mapper.map(employeeRepository.findOne(employeeId), employeeResource); return employeeResource; } public EmployeeResource saveEmployeeResource(EmployeeResource employeeResource) { Employee employee = new Employee(); mapper.map(employeeResource, employee); employee = employeeRepository.saveAndFlush(employee); mapper.map(employee, employeeResource); return employeeResource; } }
UTF-8
Java
1,454
java
EmployeeService.java
Java
[ { "context": "rayList;\nimport java.util.List;\n\n/**\n * Created by ionutmihailescu on 1/24/18.\n */\n@Service\npublic class EmployeeSer", "end": 452, "score": 0.9994803071022034, "start": 437, "tag": "USERNAME", "value": "ionutmihailescu" } ]
null
[]
package com.rest.army.dashboard.service; import com.rest.army.dashboard.mapper.Mapper; import com.rest.army.dashboard.model.Employee; import com.rest.army.dashboard.repository.IEmployeeRepository; import com.rest.army.dashboard.resource.EmployeeResource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.List; /** * Created by ionutmihailescu on 1/24/18. */ @Service public class EmployeeService { @Autowired private IEmployeeRepository employeeRepository; @Autowired private Mapper mapper; public List<EmployeeResource> findAll() { List<EmployeeResource> employeeResources = new ArrayList<>(); mapper.mapAsCollection(employeeRepository.findAll(), employeeResources, EmployeeResource.class); return employeeResources; } public EmployeeResource findById(Long employeeId) { EmployeeResource employeeResource = new EmployeeResource(); mapper.map(employeeRepository.findOne(employeeId), employeeResource); return employeeResource; } public EmployeeResource saveEmployeeResource(EmployeeResource employeeResource) { Employee employee = new Employee(); mapper.map(employeeResource, employee); employee = employeeRepository.saveAndFlush(employee); mapper.map(employee, employeeResource); return employeeResource; } }
1,454
0.755846
0.752407
44
32.045456
27.230459
104
false
false
0
0
0
0
0
0
0.613636
false
false
10
9fdccdc1841f30c8f8db2ba197f69404c6aea6b6
10,960,756,586,645
0f6fd10864812567c2a9497c5087798055ec9285
/๊ฑฐ์Šค๋ฆ„๋ˆ/Sol.java
219c5d101309e2d72dc5606ec219731a1179c14d
[]
no_license
ysjune/coding-test
https://github.com/ysjune/coding-test
667a8f6866bf04f291f017d32e0b65ad7d3f5d0a
d90690e74bdf9fdf3551fd7a91fd6a955887918b
refs/heads/master
2023-08-01T15:09:54.432000
2023-07-08T07:06:01
2023-07-08T07:06:01
241,652,819
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ๊ฑฐ์Šค๋ฆ„๋ˆ; public class Sol { // n์›์„ ๊ฑฐ์Šฌ๋Ÿฌ์ฃผ๋Š” ๋ฐฉ๋ฒ• public static int solution(int n, int[] money) { int[] array = new int[n+1]; array[0] = 1; // 0์› ๋งŒ๋“œ๋Š” ๋ฐฉ๋ฒ• /** * 0 1 2 3 4 5 * 1 1 1 1 1 1 1 * 2 1 1 2 2 3 3 * 5 1 1 2 2 3 4 */ for (int i = 0; i < money.length; i++) { for (int j = money[i]; j <= n; j++) { int temp = j - money[i]; array[j] += array[j - money[i]]; array[j] %= 1000000007; } } return array[n]; } public static void main(String[] args) { int n = 5; int[] money = {1,2,5}; int solution = solution(n, money); System.out.println(solution); } }
UTF-8
Java
814
java
Sol.java
Java
[]
null
[]
package ๊ฑฐ์Šค๋ฆ„๋ˆ; public class Sol { // n์›์„ ๊ฑฐ์Šฌ๋Ÿฌ์ฃผ๋Š” ๋ฐฉ๋ฒ• public static int solution(int n, int[] money) { int[] array = new int[n+1]; array[0] = 1; // 0์› ๋งŒ๋“œ๋Š” ๋ฐฉ๋ฒ• /** * 0 1 2 3 4 5 * 1 1 1 1 1 1 1 * 2 1 1 2 2 3 3 * 5 1 1 2 2 3 4 */ for (int i = 0; i < money.length; i++) { for (int j = money[i]; j <= n; j++) { int temp = j - money[i]; array[j] += array[j - money[i]]; array[j] %= 1000000007; } } return array[n]; } public static void main(String[] args) { int n = 5; int[] money = {1,2,5}; int solution = solution(n, money); System.out.println(solution); } }
814
0.411082
0.351804
35
21.171429
16.984842
52
false
false
0
0
0
0
0
0
0.542857
false
false
10
70b865f1c345520b68478c130db96759af1b7bc4
21,174,188,818,393
bb55181ac07aa265e4a9f3638ebfa3d76091c8e2
/framework-common/src/main/java/com/zjdex/framework/holder/RequestHolder.java
ebda03323a6c985a597e6c775c83d9d28bf7f69b
[]
no_license
henuuDigPlayer/framework-parent
https://github.com/henuuDigPlayer/framework-parent
7c761db18861d147f1065f9276c485e9796b26fa
64c9848fe8ff1a5d43ebead6c4c974c9da8d9b8d
refs/heads/master
2021-06-03T14:54:08.241000
2019-02-20T09:38:38
2019-02-20T09:38:38
143,505,290
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.zjdex.framework.holder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.context.request.RequestAttributes; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import javax.servlet.http.HttpServletRequest; /** * @author lindj * @create 2018/9/25 * @desc ่Žทๅ–HttpServletRequest **/ public class RequestHolder { private static final Logger logger = LoggerFactory.getLogger(RequestHolder.class.getName()); /** * ่Žทๅ–HttpServletRequest * * @return HttpServletRequest */ public static HttpServletRequest getRequest() { RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes(); HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest(); return request; } /** * ่Žทๅ–token * * @return String */ public static String getToken() { return getHeader("token"); } /** * ่Žทๅ–่ฏทๆฑ‚ๅคดไฟกๆฏ * * @param key String * @return String */ public static String getHeader(String key) { return getRequest().getHeader(key); } }
UTF-8
Java
1,272
java
RequestHolder.java
Java
[ { "context": "x.servlet.http.HttpServletRequest;\n\n/**\n * @author lindj\n * @create 2018/9/25\n * @desc ่Žทๅ–HttpServletReques", "end": 370, "score": 0.9996294379234314, "start": 365, "tag": "USERNAME", "value": "lindj" } ]
null
[]
package com.zjdex.framework.holder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.context.request.RequestAttributes; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import javax.servlet.http.HttpServletRequest; /** * @author lindj * @create 2018/9/25 * @desc ่Žทๅ–HttpServletRequest **/ public class RequestHolder { private static final Logger logger = LoggerFactory.getLogger(RequestHolder.class.getName()); /** * ่Žทๅ–HttpServletRequest * * @return HttpServletRequest */ public static HttpServletRequest getRequest() { RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes(); HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest(); return request; } /** * ่Žทๅ–token * * @return String */ public static String getToken() { return getHeader("token"); } /** * ่Žทๅ–่ฏทๆฑ‚ๅคดไฟกๆฏ * * @param key String * @return String */ public static String getHeader(String key) { return getRequest().getHeader(key); } }
1,272
0.692616
0.685393
53
22.509434
25.948877
97
false
false
0
0
0
0
0
0
0.245283
false
false
10
f50828633c742b258382c41d29f50b79fa99725a
30,880,814,924,789
5200709a0b29dcf7886876d63416a8fd173937c1
/src/org/crazyit/auction/dao/AuctionUserDao.java
ef3f197b136e6b6b5786202901919aa77bcf7700
[]
no_license
Stainlesswang/Find
https://github.com/Stainlesswang/Find
2812a9083167f65d6a3fc24ceadfaf1d90429652
0997f22491d4afae9ab7e6d81ed923753d84ce40
refs/heads/master
2021-01-19T06:56:49.361000
2017-05-02T05:40:07
2017-05-02T05:40:07
87,511,663
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.crazyit.auction.dao; import java.util.List; import org.crazyit.common.dao.*; import org.crazyit.auction.domain.*; import org.crazyit.auction.business.*; public interface AuctionUserDao extends BaseDao<AuctionUser> { /** * ๆ นๆฎ็”จๆˆทๅ๏ผŒๅฏ†็ ๆŸฅๆ‰พ็”จๆˆท * @param username ๆŸฅ่ฏขๆ‰€้œ€็š„็”จๆˆทๅ * @param pass ๆŸฅ่ฏขๆ‰€้œ€็š„ๅฏ†็  * @return ๆŒ‡ๅฎš็”จๆˆทๅใ€ๅฏ†็ ๅฏนๅบ”็š„็”จๆˆท */ AuctionUser findUserByNameAndPass(String username , String pass); int RegisterUser(AuctionUser auctionUser); }
GB18030
Java
531
java
AuctionUserDao.java
Java
[]
null
[]
package org.crazyit.auction.dao; import java.util.List; import org.crazyit.common.dao.*; import org.crazyit.auction.domain.*; import org.crazyit.auction.business.*; public interface AuctionUserDao extends BaseDao<AuctionUser> { /** * ๆ นๆฎ็”จๆˆทๅ๏ผŒๅฏ†็ ๆŸฅๆ‰พ็”จๆˆท * @param username ๆŸฅ่ฏขๆ‰€้œ€็š„็”จๆˆทๅ * @param pass ๆŸฅ่ฏขๆ‰€้œ€็š„ๅฏ†็  * @return ๆŒ‡ๅฎš็”จๆˆทๅใ€ๅฏ†็ ๅฏนๅบ”็š„็”จๆˆท */ AuctionUser findUserByNameAndPass(String username , String pass); int RegisterUser(AuctionUser auctionUser); }
531
0.760532
0.760532
21
20.523809
20.070398
66
false
false
0
0
0
0
0
0
0.761905
false
false
10
f41f6924f8ecf972d8780b75e17da6afc0fad4c2
6,064,493,826,450
13c07fc7b43542f4b91c2697c282f398a28e4099
/tests-arquillian/src/test/java/org/jboss/weld/tests/beanManager/ProducesUtil.java
17f4871165a92f5f2711e67a720d908b1e8e9397
[ "Apache-2.0" ]
permissive
Mattlk13/core
https://github.com/Mattlk13/core
d889253fa1d1815ffbfea21dcc077616766eb3bb
6c369e15b89d25ce33151f5f5db91c57e916c68a
refs/heads/master
2023-08-18T03:11:48.024000
2020-03-28T12:23:48
2020-03-28T12:23:48
81,315,189
0
0
Apache-2.0
true
2023-05-01T20:35:07
2017-02-08T10:01:42
2020-03-28T12:58:53
2023-05-01T20:35:06
52,135
0
0
6
Java
false
false
package org.jboss.weld.tests.beanManager; import javax.enterprise.context.SessionScoped; import javax.enterprise.inject.Produces; import javax.inject.Named; public class ProducesUtil { @Produces @SessionScoped @Named("myBean") UserInfo getUserInfo() { return new UserInfo() { private static final long serialVersionUID = 1L; public String getUsername() { return "pmuir"; } }; } }
UTF-8
Java
473
java
ProducesUtil.java
Java
[ { "context": "ic String getUsername() {\n return \"pmuir\";\n }\n };\n }\n}\n", "end": 437, "score": 0.9996104836463928, "start": 432, "tag": "USERNAME", "value": "pmuir" } ]
null
[]
package org.jboss.weld.tests.beanManager; import javax.enterprise.context.SessionScoped; import javax.enterprise.inject.Produces; import javax.inject.Named; public class ProducesUtil { @Produces @SessionScoped @Named("myBean") UserInfo getUserInfo() { return new UserInfo() { private static final long serialVersionUID = 1L; public String getUsername() { return "pmuir"; } }; } }
473
0.630021
0.627907
22
20.5
17.492207
60
false
false
0
0
0
0
0
0
0.318182
false
false
10
eb388e40d3a7734eff27a280dcf471a0ae18dc48
22,385,369,551,142
39ef08f0f94073ca44487c5107bf928c7327a7ce
/app/src/main/java/com/example/dell/myapplication/EditTextOnSamePage.java
6b0b58c331eec84e83de33f7d461aa39a5f28770
[]
no_license
shreeja02/androiddemo
https://github.com/shreeja02/androiddemo
df91fb060226f0ab44456837d4b18857b18e916b
ec3ff6b698789449a1ae2f8e91a963085ff20e6b
refs/heads/master
2021-01-21T09:34:14.282000
2017-06-20T04:25:01
2017-06-20T04:25:01
91,656,896
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.dell.myapplication; import android.content.Context; import android.content.DialogInterface; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.View; import android.view.inputmethod.InputMethodManager; import android.widget.Button; import android.widget.EditText; public class EditTextOnSamePage extends AppCompatActivity { EditText ed; Button btn1; @Override public void onBackPressed() { super.onBackPressed(); ed= (EditText) findViewById(R.id.lblEditTextOnSamePage); btn1= (Button) findViewById(R.id.btnEditDemo); ed.setVisibility(View.INVISIBLE); btn1.setVisibility(View.INVISIBLE); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_edit_text_on_same_page); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); ed= (EditText) findViewById(R.id.lblEditTextOnSamePage); btn1= (Button) findViewById(R.id.btnEditDemo); FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG) .setAction("Action", null).show(); ed.setVisibility(view.VISIBLE); btn1.setVisibility(view.VISIBLE); ed.requestFocus(); InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,0); btn1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { final AlertDialog.Builder alert=new AlertDialog.Builder(EditTextOnSamePage.this); alert.setMessage(ed.getText()+""); alert.setCancelable(false); alert.setPositiveButton("yes", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }); alert.create().show(); } }); } }); } }
UTF-8
Java
2,751
java
EditTextOnSamePage.java
Java
[]
null
[]
package com.example.dell.myapplication; import android.content.Context; import android.content.DialogInterface; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.View; import android.view.inputmethod.InputMethodManager; import android.widget.Button; import android.widget.EditText; public class EditTextOnSamePage extends AppCompatActivity { EditText ed; Button btn1; @Override public void onBackPressed() { super.onBackPressed(); ed= (EditText) findViewById(R.id.lblEditTextOnSamePage); btn1= (Button) findViewById(R.id.btnEditDemo); ed.setVisibility(View.INVISIBLE); btn1.setVisibility(View.INVISIBLE); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_edit_text_on_same_page); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); ed= (EditText) findViewById(R.id.lblEditTextOnSamePage); btn1= (Button) findViewById(R.id.btnEditDemo); FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG) .setAction("Action", null).show(); ed.setVisibility(view.VISIBLE); btn1.setVisibility(view.VISIBLE); ed.requestFocus(); InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,0); btn1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { final AlertDialog.Builder alert=new AlertDialog.Builder(EditTextOnSamePage.this); alert.setMessage(ed.getText()+""); alert.setCancelable(false); alert.setPositiveButton("yes", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }); alert.create().show(); } }); } }); } }
2,751
0.624137
0.620502
71
37.746479
26.843164
109
false
false
0
0
0
0
0
0
0.647887
false
false
10
ecff7566db886ec6b83e392d2804f494ceebcdb0
24,446,953,908,647
fa9e57d27e056c2ceb630c5adcc16c453521bafc
/app/src/main/java/com/juztoss/rhythmo/audio/AdvancedMediaPlayer.java
49f69350cde5c1436d0faff7b3e06d075a50f566
[ "Apache-2.0" ]
permissive
tueksta/Rhythmo
https://github.com/tueksta/Rhythmo
2a7612ce4522932fef6cd38fdffc49fd2949660e
a82047c7b99a2067ea47c4d1b19a98bd72a5f5aa
refs/heads/master
2022-01-06T23:07:26.680000
2019-02-02T19:23:19
2019-02-02T20:15:17
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.juztoss.rhythmo.audio; import android.util.Log; /** * Created by JuzTosS on 5/22/2016. * A media player with ability to stretch audio duration. * Uses SuperpoweredSDK and OpenSLES. */ public class AdvancedMediaPlayer { private boolean DEBUG = false; private static int totalObjectsCreated = 0; public static String LIBRARY_NAME = "AdvancedMediaPlayer"; private final int mId; private OnEndListener mOnEndListener; private OnErrorListener mOnErrorListener; private OnPreparedListener mOnPreparedListener; public AdvancedMediaPlayer(int samplerate, int buffersize) { mId = ++totalObjectsCreated; init(samplerate, buffersize); } /** * Is called when playback of audiofile ends */ public void setOnEndListener(OnEndListener onEndListener) { mOnEndListener = onEndListener; } /** * Is called audio file is ready to play */ public void setOnPreparedListener(OnPreparedListener onPreparedListener) { mOnPreparedListener = onPreparedListener; } /** * Is called when any error is occured */ public void setOnErrorListener(OnErrorListener onErrorListener) { mOnErrorListener = onErrorListener; } private native void init(int samplerate, int buffersize); /** * Sets audio source for player, wait for the onPrepared event before call Play method. */ public native void setSource(String path); /** * Starts playback */ public native void play(); /** * Pauses playback */ public native void pause(); /** * Return duration of file in milliseconds */ public native int getDuration(); /** * Return current position in milliseconds */ public native int getPosition(); /** * Sets current position in milliseconds */ public native void setPosition(int offset); /** * Sets song original BPM, paired with setNewBPM(double) */ public native void setBPM(double bpm); /** * Sets song new BPM to play with. Depends on original BPM that set by setBPM(double) */ public native void setNewBPM(double bpm); /** * Free memory. Have to be called if player will never be used anymore. */ private native void releaseNative(); /** * Free memory and clear callbacks. Have to be called if player will never be used anymore. */ public void release() { releaseNative(); mOnEndListener = null; mOnErrorListener = null; mOnPreparedListener = null; } /** * Return id of player instance */ private int getIdJNI() { return mId; } /** * JNI callbacks */ private void onPrepared() { if(DEBUG) Log.d(AdvancedMediaPlayer.class.toString(), "onPreparedCalled"); if(mOnPreparedListener != null) mOnPreparedListener.onPrepared(); } private void onEnd() { if(DEBUG) Log.d(AdvancedMediaPlayer.class.toString(), "onEndCalled"); if(mOnEndListener != null) mOnEndListener.onEnd(); } private void onError() { if(DEBUG) Log.d(AdvancedMediaPlayer.class.toString(), "onErrorCalled"); if(mOnErrorListener != null) mOnErrorListener.onError(); } /** * Event listeners */ public interface OnEndListener { //BE CALLED FROM OTHER THREAD void onEnd(); } public interface OnPreparedListener { //BE CALLED FROM OTHER THREAD void onPrepared(); } public interface OnErrorListener { //BE CALLED FROM OTHER THREAD void onError(); } }
UTF-8
Java
3,751
java
AdvancedMediaPlayer.java
Java
[ { "context": "udio;\n\nimport android.util.Log;\n\n/**\n * Created by JuzTosS on 5/22/2016.\n * A media player with ability to s", "end": 87, "score": 0.9967448115348816, "start": 80, "tag": "USERNAME", "value": "JuzTosS" } ]
null
[]
package com.juztoss.rhythmo.audio; import android.util.Log; /** * Created by JuzTosS on 5/22/2016. * A media player with ability to stretch audio duration. * Uses SuperpoweredSDK and OpenSLES. */ public class AdvancedMediaPlayer { private boolean DEBUG = false; private static int totalObjectsCreated = 0; public static String LIBRARY_NAME = "AdvancedMediaPlayer"; private final int mId; private OnEndListener mOnEndListener; private OnErrorListener mOnErrorListener; private OnPreparedListener mOnPreparedListener; public AdvancedMediaPlayer(int samplerate, int buffersize) { mId = ++totalObjectsCreated; init(samplerate, buffersize); } /** * Is called when playback of audiofile ends */ public void setOnEndListener(OnEndListener onEndListener) { mOnEndListener = onEndListener; } /** * Is called audio file is ready to play */ public void setOnPreparedListener(OnPreparedListener onPreparedListener) { mOnPreparedListener = onPreparedListener; } /** * Is called when any error is occured */ public void setOnErrorListener(OnErrorListener onErrorListener) { mOnErrorListener = onErrorListener; } private native void init(int samplerate, int buffersize); /** * Sets audio source for player, wait for the onPrepared event before call Play method. */ public native void setSource(String path); /** * Starts playback */ public native void play(); /** * Pauses playback */ public native void pause(); /** * Return duration of file in milliseconds */ public native int getDuration(); /** * Return current position in milliseconds */ public native int getPosition(); /** * Sets current position in milliseconds */ public native void setPosition(int offset); /** * Sets song original BPM, paired with setNewBPM(double) */ public native void setBPM(double bpm); /** * Sets song new BPM to play with. Depends on original BPM that set by setBPM(double) */ public native void setNewBPM(double bpm); /** * Free memory. Have to be called if player will never be used anymore. */ private native void releaseNative(); /** * Free memory and clear callbacks. Have to be called if player will never be used anymore. */ public void release() { releaseNative(); mOnEndListener = null; mOnErrorListener = null; mOnPreparedListener = null; } /** * Return id of player instance */ private int getIdJNI() { return mId; } /** * JNI callbacks */ private void onPrepared() { if(DEBUG) Log.d(AdvancedMediaPlayer.class.toString(), "onPreparedCalled"); if(mOnPreparedListener != null) mOnPreparedListener.onPrepared(); } private void onEnd() { if(DEBUG) Log.d(AdvancedMediaPlayer.class.toString(), "onEndCalled"); if(mOnEndListener != null) mOnEndListener.onEnd(); } private void onError() { if(DEBUG) Log.d(AdvancedMediaPlayer.class.toString(), "onErrorCalled"); if(mOnErrorListener != null) mOnErrorListener.onError(); } /** * Event listeners */ public interface OnEndListener { //BE CALLED FROM OTHER THREAD void onEnd(); } public interface OnPreparedListener { //BE CALLED FROM OTHER THREAD void onPrepared(); } public interface OnErrorListener { //BE CALLED FROM OTHER THREAD void onError(); } }
3,751
0.6257
0.623567
163
22.01227
22.795164
95
false
false
0
0
0
0
0
0
0.282209
false
false
10
495980c72416844ebbb99b0f7c0533dc22eb2c38
26,216,480,429,769
d3ea628aff60f4e374b4a50936b4d9d834dd655f
/ueb18/src/main/java/ueb09/Main.java
f26465854ecd979643c6d77205763026bec7cb43
[]
no_license
Omega1001/HTW
https://github.com/Omega1001/HTW
8d122e3179065dc07684b8ae74edd17330dd6e4e
9c7b4693fc5289ba733150d3bf31987a8f640e48
refs/heads/pi17w
2021-06-06T08:30:26.385000
2019-07-01T11:15:26
2019-07-01T11:15:26
112,590,547
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ueb09; import java.util.function.BiPredicate; import java.util.function.Consumer; import java.util.function.Predicate; import utils.UpcastConsumerBuilder; import utils.UpcastPredicateBuilder; public class Main { public static void main(String[] args) { // private static final BiPredicate <Artikel, Artikel> // Unterkategorie = ???; was ist die Unterkategorie? // assuming Classname where default Artikels are smalest, because // they have no subcat. BiPredicate<Artikel, Artikel> subcat = (x, y) -> { int comp = x.getClass().getSimpleName().compareTo(y.getClass() .getSimpleName()); if (comp == 0) { return String.CASE_INSENSITIVE_ORDER.compare(x .getArtikelBezeichnung(), y .getArtikelBezeichnung()) < 0; } else { if (x.getClass().equals(Artikel.class)) { return true; } else { return comp > 0; } } }; BiPredicate<Artikel, Artikel> bestand = (x, y) -> x .getArtikelBestand() > y.getArtikelBestand(); BiPredicate<Artikel, Artikel> preis = (x, y) -> x.getPreis() > y .getPreis(); Consumer<Artikel> zehnProzent = a -> { ((Artikel) a).setPreis(((Artikel) a).getPreis() * 0.9); }; Consumer<Artikel> sonderangebot = a -> { ((Artikel) a).setArtikelBezeichnung("Sonderangebot " + ((Artikel) a).getArtikelBezeichnung()); }; Consumer<Artikel> zehnProzentSonderangebot = a -> { zehnProzent.andThen(sonderangebot).accept(a); }; Lager lager = buildLager(); System.out.println(lager.ausgebenBestandsListe()); System.out.println("Subcat"); System.out.println(lager.getSorted(subcat)); System.out.println("Bestand"); System.out.println(lager.getSorted(bestand)); System.out.println("Preis"); System.out.println(lager.getSorted(preis)); System.out.println(lager.ausgebenBestandsListe()); System.out.println("10 %"); lager.applyToArticles(zehnProzent); System.out.println(lager.ausgebenBestandsListe()); System.out.println("Sunderangebot"); lager.applyToArticles(sonderangebot); System.out.println(lager.ausgebenBestandsListe()); System.out.println("10 % + Sonderangebot"); lager.applyToArticles(zehnProzentSonderangebot); System.out.println(lager.ausgebenBestandsListe()); // ------Start // ueb18---------------------------------------------------------------------------------------------------- System.out.println("Start ueb18!"); System.out.println(lager.ausgebenBestandsListe()); System.out.println("Erhoehen Sie den Preis aller CDs um 10%"); Consumer<Artikel> plusZehnProzent = a -> a.setPreis(a.getPreis() * 1.1); Predicate<Artikel> cD = a -> a.getClass().isAssignableFrom(Cd.class); lager.applyToSomeArticles(plusZehnProzent, cD); System.out.println(lager.ausgebenBestandsListe()); System.out.println( "Reduzieren Sie den Preis aller Artikel, von denen nur noch zwei Exemplare im Bestand sind um 5%."); Predicate<Artikel> bestand2 = a -> a.getArtikelBestand() == 2; Consumer<Artikel> funfProzent = a -> a.setPreis(a.getPreis() * 0.95); lager.applyToSomeArticles(funfProzent, bestand2); System.out.println(lager.ausgebenBestandsListe()); System.out.println( "Reduzieren Sie alle Buecher eines gegebenen Autors um 5%."); Predicate<Artikel> buchAutorX = UpcastPredicateBuilder .upcastPredicate(a -> a.getAutor().equals("BuchAuthor2"), Buch.class); // Warum verschiedene Fehler hier und // darunter? lager.applyToSomeArticles(funfProzent, buchAutorX); System.out.println(lager.ausgebenBestandsListe()); System.out.println( "Erzeugen Sie einen Lambda-Ausdruck der die beiden Operationen i und iii kombiniert."); // Die Methode frisst zwei Argumente wie soll ich da EINEN validen // Ausdruck erzeugen... // andThen wuerde hier nicht funktionieren da ansonsten fuer alle // CDs UND Bucher der Preis um 10% erhoeht UND um 5% verringert // werden wuerde. Consumer< Artikel> pluszehnProzentFurCDsUndFunfProzentfurBuchervonAutorX = UpcastConsumerBuilder.upcastConsumer((cd) -> { plusZehnProzent.accept(cd); }, Cd.class); pluszehnProzentFurCDsUndFunfProzentfurBuchervonAutorX = pluszehnProzentFurCDsUndFunfProzentfurBuchervonAutorX .andThen(UpcastConsumerBuilder.upcastConsumer(( buch) -> { funfProzent.accept(buch); }, Buch.class)); Predicate<Artikel> cDsUndBucherMitAutorX = cD.or(buchAutorX); lager.applyToSomeArticles( pluszehnProzentFurCDsUndFunfProzentfurBuchervonAutorX, cDsUndBucherMitAutorX); System.out.println(lager.ausgebenBestandsListe()); System.out.println( "Fragen Sie eine Liste aller Buecher, sortiert nach Autor, ab."); Predicate<Artikel> buch = a -> a.getClass().getSimpleName().equals( "Buch"); BiPredicate<Artikel, Artikel> autor = (x, y) -> { int comp = x.getBeschreibung().compareTo(y.getBeschreibung()); if (comp == 0) { return String.CASE_INSENSITIVE_ORDER.compare(x .getArtikelBezeichnung(), y .getArtikelBezeichnung()) < 0; } else { if (x.getClass().equals(Artikel.class)) { return true; } else { return comp > 0; } } }; System.out.println(lager.getArticles(buch, autor)); } private static Lager buildLager() { Lager lager = new Lager(20); lager.lagereArtikel(new Artikel(1000, "Artikel", 20, 1.0)); lager.lagereArtikel(new Artikel(1100, "Artikel 2", 2, 1.0)); lager.lagereArtikel(new Buch(1001, "Buch", 15, 5.0, "BuchAuthor", "BuchTitel", "BuchVerlag")); lager.lagereArtikel(new Buch(1101, "Buch", 15, 5.0, "BuchAuthor2", "BuchTitel", "BuchVerlag")); lager.lagereArtikel(new Cd(1002, "CD", 10, 10.0, "CDIntepret", "CDTitel", 5)); lager.lagereArtikel(new Dvd(1003, "DVD", 5, 15.55, "DVDTitel", 120, 2010)); lager.lagereArtikel(new Dvd(1103, "DVD", 2, 15.55, "DVDTitel2", 120, 2010)); return lager; } }
UTF-8
Java
6,036
java
Main.java
Java
[ { "context": "r\r\n\t\t\t\t.upcastPredicate(a -> a.getAutor().equals(\"BuchAuthor2\"),\r\n\t\t\t\t\t\tBuch.class); // Warum verschiedene Fehl", "end": 3445, "score": 0.984372079372406, "start": 3434, "tag": "USERNAME", "value": "BuchAuthor2" } ]
null
[]
package ueb09; import java.util.function.BiPredicate; import java.util.function.Consumer; import java.util.function.Predicate; import utils.UpcastConsumerBuilder; import utils.UpcastPredicateBuilder; public class Main { public static void main(String[] args) { // private static final BiPredicate <Artikel, Artikel> // Unterkategorie = ???; was ist die Unterkategorie? // assuming Classname where default Artikels are smalest, because // they have no subcat. BiPredicate<Artikel, Artikel> subcat = (x, y) -> { int comp = x.getClass().getSimpleName().compareTo(y.getClass() .getSimpleName()); if (comp == 0) { return String.CASE_INSENSITIVE_ORDER.compare(x .getArtikelBezeichnung(), y .getArtikelBezeichnung()) < 0; } else { if (x.getClass().equals(Artikel.class)) { return true; } else { return comp > 0; } } }; BiPredicate<Artikel, Artikel> bestand = (x, y) -> x .getArtikelBestand() > y.getArtikelBestand(); BiPredicate<Artikel, Artikel> preis = (x, y) -> x.getPreis() > y .getPreis(); Consumer<Artikel> zehnProzent = a -> { ((Artikel) a).setPreis(((Artikel) a).getPreis() * 0.9); }; Consumer<Artikel> sonderangebot = a -> { ((Artikel) a).setArtikelBezeichnung("Sonderangebot " + ((Artikel) a).getArtikelBezeichnung()); }; Consumer<Artikel> zehnProzentSonderangebot = a -> { zehnProzent.andThen(sonderangebot).accept(a); }; Lager lager = buildLager(); System.out.println(lager.ausgebenBestandsListe()); System.out.println("Subcat"); System.out.println(lager.getSorted(subcat)); System.out.println("Bestand"); System.out.println(lager.getSorted(bestand)); System.out.println("Preis"); System.out.println(lager.getSorted(preis)); System.out.println(lager.ausgebenBestandsListe()); System.out.println("10 %"); lager.applyToArticles(zehnProzent); System.out.println(lager.ausgebenBestandsListe()); System.out.println("Sunderangebot"); lager.applyToArticles(sonderangebot); System.out.println(lager.ausgebenBestandsListe()); System.out.println("10 % + Sonderangebot"); lager.applyToArticles(zehnProzentSonderangebot); System.out.println(lager.ausgebenBestandsListe()); // ------Start // ueb18---------------------------------------------------------------------------------------------------- System.out.println("Start ueb18!"); System.out.println(lager.ausgebenBestandsListe()); System.out.println("Erhoehen Sie den Preis aller CDs um 10%"); Consumer<Artikel> plusZehnProzent = a -> a.setPreis(a.getPreis() * 1.1); Predicate<Artikel> cD = a -> a.getClass().isAssignableFrom(Cd.class); lager.applyToSomeArticles(plusZehnProzent, cD); System.out.println(lager.ausgebenBestandsListe()); System.out.println( "Reduzieren Sie den Preis aller Artikel, von denen nur noch zwei Exemplare im Bestand sind um 5%."); Predicate<Artikel> bestand2 = a -> a.getArtikelBestand() == 2; Consumer<Artikel> funfProzent = a -> a.setPreis(a.getPreis() * 0.95); lager.applyToSomeArticles(funfProzent, bestand2); System.out.println(lager.ausgebenBestandsListe()); System.out.println( "Reduzieren Sie alle Buecher eines gegebenen Autors um 5%."); Predicate<Artikel> buchAutorX = UpcastPredicateBuilder .upcastPredicate(a -> a.getAutor().equals("BuchAuthor2"), Buch.class); // Warum verschiedene Fehler hier und // darunter? lager.applyToSomeArticles(funfProzent, buchAutorX); System.out.println(lager.ausgebenBestandsListe()); System.out.println( "Erzeugen Sie einen Lambda-Ausdruck der die beiden Operationen i und iii kombiniert."); // Die Methode frisst zwei Argumente wie soll ich da EINEN validen // Ausdruck erzeugen... // andThen wuerde hier nicht funktionieren da ansonsten fuer alle // CDs UND Bucher der Preis um 10% erhoeht UND um 5% verringert // werden wuerde. Consumer< Artikel> pluszehnProzentFurCDsUndFunfProzentfurBuchervonAutorX = UpcastConsumerBuilder.upcastConsumer((cd) -> { plusZehnProzent.accept(cd); }, Cd.class); pluszehnProzentFurCDsUndFunfProzentfurBuchervonAutorX = pluszehnProzentFurCDsUndFunfProzentfurBuchervonAutorX .andThen(UpcastConsumerBuilder.upcastConsumer(( buch) -> { funfProzent.accept(buch); }, Buch.class)); Predicate<Artikel> cDsUndBucherMitAutorX = cD.or(buchAutorX); lager.applyToSomeArticles( pluszehnProzentFurCDsUndFunfProzentfurBuchervonAutorX, cDsUndBucherMitAutorX); System.out.println(lager.ausgebenBestandsListe()); System.out.println( "Fragen Sie eine Liste aller Buecher, sortiert nach Autor, ab."); Predicate<Artikel> buch = a -> a.getClass().getSimpleName().equals( "Buch"); BiPredicate<Artikel, Artikel> autor = (x, y) -> { int comp = x.getBeschreibung().compareTo(y.getBeschreibung()); if (comp == 0) { return String.CASE_INSENSITIVE_ORDER.compare(x .getArtikelBezeichnung(), y .getArtikelBezeichnung()) < 0; } else { if (x.getClass().equals(Artikel.class)) { return true; } else { return comp > 0; } } }; System.out.println(lager.getArticles(buch, autor)); } private static Lager buildLager() { Lager lager = new Lager(20); lager.lagereArtikel(new Artikel(1000, "Artikel", 20, 1.0)); lager.lagereArtikel(new Artikel(1100, "Artikel 2", 2, 1.0)); lager.lagereArtikel(new Buch(1001, "Buch", 15, 5.0, "BuchAuthor", "BuchTitel", "BuchVerlag")); lager.lagereArtikel(new Buch(1101, "Buch", 15, 5.0, "BuchAuthor2", "BuchTitel", "BuchVerlag")); lager.lagereArtikel(new Cd(1002, "CD", 10, 10.0, "CDIntepret", "CDTitel", 5)); lager.lagereArtikel(new Dvd(1003, "DVD", 5, 15.55, "DVDTitel", 120, 2010)); lager.lagereArtikel(new Dvd(1103, "DVD", 2, 15.55, "DVDTitel2", 120, 2010)); return lager; } }
6,036
0.66617
0.647614
172
33.093021
24.903828
110
false
false
0
0
0
0
0
0
3.226744
false
false
10
4ce1562f0a0ac3fd73a2560ad0b8136fdea650b3
16,887,811,428,552
b38df39d5fe44d36acaca9f11cb10f2a4da8b229
/property-web/cre-property-web/src/main/java/com/hd123/m3/cre/controller/property/material/subscribes/MaterialSubscribeProcessor.java
83cd125098ccdbcd9212fb7128bd0647bd4e9766
[]
no_license
jacobQin/cre
https://github.com/jacobQin/cre
6447ac1ee07105d4064699c5d62253a40c4cc56b
eebe3cedbabda2017fafe74edf4eed3a56045cb0
refs/heads/master
2021-03-21T23:51:57.670000
2017-09-27T08:48:50
2017-09-27T08:48:50
104,985,697
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * ็‰ˆๆƒๆ‰€ๆœ‰(C)๏ผŒไธŠๆตทๆตท้ผŽไฟกๆฏๅทฅ็จ‹่‚กไปฝๆœ‰้™ๅ…ฌๅธ๏ผŒ2017๏ผŒๆ‰€ๆœ‰ๆƒๅˆฉไฟ็•™ใ€‚ * * ้กน็›ฎๅ๏ผš cre-property-web * ๆ–‡ไปถๅ๏ผš MaterialSubscribeProcessor.java * ๆจกๅ—่ฏดๆ˜Ž๏ผš * ไฟฎๆ”นๅކๅฒ๏ผš * 2017ๅนด6ๆœˆ28ๆ—ฅ - qinzhicheng - ๅˆ›ๅปบใ€‚ */ package com.hd123.m3.cre.controller.property.material.subscribes; import java.math.BigDecimal; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.hd123.m3.commons.biz.query.FlecsQueryDefinition; import com.hd123.m3.commons.biz.util.JsonUtil; import com.hd123.m3.commons.util.impex.poi.WorkbookUtil; import com.hd123.m3.property.service.material.material.Material; import com.hd123.m3.property.service.material.material.MaterialService; import com.hd123.m3.property.service.material.material.Materials; import com.hd123.m3.property.service.material.subscribe.MaterialSubscribeDetail; import com.hd123.rumba.commons.biz.entity.UCN; /** * @author qzc * */ @Component public class MaterialSubscribeProcessor { private static final String COL_MATERIAL = "็‰ฉๆ–™"; private static final String COL_QRY = "ๆ•ฐ้‡"; private static final String COL_REMARK = "่ฏดๆ˜Ž"; private static final String BIZ_STATE = "using"; @Autowired private MaterialService materialService; public List<MaterialSubscribeDetail> importFile(String filePath, String storeUuid) throws Exception { List<MaterialSubscribeDetail> result = new ArrayList<MaterialSubscribeDetail>(); List<String> errors = new ArrayList<String>(); Set<String> dateInput = new HashSet<String>(); Workbook book = WorkbookUtil.getWorkbook(filePath); Sheet sheet = book.getSheetAt(0); Map<String,Material> materials = getMaterials(storeUuid); for (int rowIdx = 1; rowIdx <= sheet.getLastRowNum(); rowIdx++) { Row row = sheet.getRow(rowIdx); if (WorkbookUtil.isRowEmpty(row)) { continue; } try { BMaterialSubscribeDetail line = new BMaterialSubscribeDetail(); String code = WorkbookUtil.getStringCellValue(row, COL_MATERIAL); if(code != null && dateInput.contains(code)){ throw new Exception(line.getMaterial().getName() + "้‡ๅคๅฝ•ๅ…ฅ"); } if(materials == null || materials.containsKey(code) == false){ throw new Exception("่ฏฅ้กน็›ฎไธ‹็‰ฉๆ–™ไธๅญ˜ๅœจๆˆ–ไธๅœจไฝฟ็”จไธญ"); } Material material = materials.get(code); line.setMaterial(UCN.newInstance(material));//็‰ฉๆ–™ line.setMaterialInfo(material);//็‰ฉๆ–™่ฏฆๆƒ… line.setQty(WorkbookUtil.getBigDecimalCellValue(row, COL_QRY, false, BigDecimal.ZERO, false, WorkbookUtil.BIGDECIMAL_MAXVALUE_S3, true, 3)); //ๆ•ฐ้‡ line.setRemark(WorkbookUtil.getStringCellValue(row, COL_REMARK)); //่ฏดๆ˜Ž if (line.getRemark() != null && line.getRemark().length() > 256){ throw new Exception("่ฏดๆ˜Žๅญ—ๆฎต่ถ…่ฟ‡256ๅญ—็ฌฆ"); } dateInput.add(line.getMaterial().getCode()); result.add(line); } catch (Exception e) { errors.add("็ฌฌ" + rowIdx + "่กŒ๏ผš" + e.getMessage()); } } if (errors.isEmpty() == false) throw new Exception(JsonUtil.objectToJson(errors)); return result; } private Map<String,Material> getMaterials(String storeUuid){ Map<String,Material> materials = new HashMap<String,Material>(); FlecsQueryDefinition condition = new FlecsQueryDefinition(); condition.addFlecsCondition(Materials.FIELD_STORE, Materials.OPERATOR_EQUALS, storeUuid); condition.addFlecsCondition(Materials.FIELD_STATE, Materials.OPERATOR_EQUALS, BIZ_STATE); List<Material> materialList = materialService.query(condition).getRecords(); if(materialList.size() <= 0) return null; for(Material m: materialList){ materials.put(m.getCode(), m); } return materials; } }
UTF-8
Java
4,321
java
MaterialSubscribeProcessor.java
Java
[ { "context": "3.rumba.commons.biz.entity.UCN;\r\n\r\n/**\r\n * @author qzc\r\n *\r\n */\r\n@Component\r\npublic class MaterialSubscr", "end": 1202, "score": 0.999632716178894, "start": 1199, "tag": "USERNAME", "value": "qzc" } ]
null
[]
/** * ็‰ˆๆƒๆ‰€ๆœ‰(C)๏ผŒไธŠๆตทๆตท้ผŽไฟกๆฏๅทฅ็จ‹่‚กไปฝๆœ‰้™ๅ…ฌๅธ๏ผŒ2017๏ผŒๆ‰€ๆœ‰ๆƒๅˆฉไฟ็•™ใ€‚ * * ้กน็›ฎๅ๏ผš cre-property-web * ๆ–‡ไปถๅ๏ผš MaterialSubscribeProcessor.java * ๆจกๅ—่ฏดๆ˜Ž๏ผš * ไฟฎๆ”นๅކๅฒ๏ผš * 2017ๅนด6ๆœˆ28ๆ—ฅ - qinzhicheng - ๅˆ›ๅปบใ€‚ */ package com.hd123.m3.cre.controller.property.material.subscribes; import java.math.BigDecimal; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.hd123.m3.commons.biz.query.FlecsQueryDefinition; import com.hd123.m3.commons.biz.util.JsonUtil; import com.hd123.m3.commons.util.impex.poi.WorkbookUtil; import com.hd123.m3.property.service.material.material.Material; import com.hd123.m3.property.service.material.material.MaterialService; import com.hd123.m3.property.service.material.material.Materials; import com.hd123.m3.property.service.material.subscribe.MaterialSubscribeDetail; import com.hd123.rumba.commons.biz.entity.UCN; /** * @author qzc * */ @Component public class MaterialSubscribeProcessor { private static final String COL_MATERIAL = "็‰ฉๆ–™"; private static final String COL_QRY = "ๆ•ฐ้‡"; private static final String COL_REMARK = "่ฏดๆ˜Ž"; private static final String BIZ_STATE = "using"; @Autowired private MaterialService materialService; public List<MaterialSubscribeDetail> importFile(String filePath, String storeUuid) throws Exception { List<MaterialSubscribeDetail> result = new ArrayList<MaterialSubscribeDetail>(); List<String> errors = new ArrayList<String>(); Set<String> dateInput = new HashSet<String>(); Workbook book = WorkbookUtil.getWorkbook(filePath); Sheet sheet = book.getSheetAt(0); Map<String,Material> materials = getMaterials(storeUuid); for (int rowIdx = 1; rowIdx <= sheet.getLastRowNum(); rowIdx++) { Row row = sheet.getRow(rowIdx); if (WorkbookUtil.isRowEmpty(row)) { continue; } try { BMaterialSubscribeDetail line = new BMaterialSubscribeDetail(); String code = WorkbookUtil.getStringCellValue(row, COL_MATERIAL); if(code != null && dateInput.contains(code)){ throw new Exception(line.getMaterial().getName() + "้‡ๅคๅฝ•ๅ…ฅ"); } if(materials == null || materials.containsKey(code) == false){ throw new Exception("่ฏฅ้กน็›ฎไธ‹็‰ฉๆ–™ไธๅญ˜ๅœจๆˆ–ไธๅœจไฝฟ็”จไธญ"); } Material material = materials.get(code); line.setMaterial(UCN.newInstance(material));//็‰ฉๆ–™ line.setMaterialInfo(material);//็‰ฉๆ–™่ฏฆๆƒ… line.setQty(WorkbookUtil.getBigDecimalCellValue(row, COL_QRY, false, BigDecimal.ZERO, false, WorkbookUtil.BIGDECIMAL_MAXVALUE_S3, true, 3)); //ๆ•ฐ้‡ line.setRemark(WorkbookUtil.getStringCellValue(row, COL_REMARK)); //่ฏดๆ˜Ž if (line.getRemark() != null && line.getRemark().length() > 256){ throw new Exception("่ฏดๆ˜Žๅญ—ๆฎต่ถ…่ฟ‡256ๅญ—็ฌฆ"); } dateInput.add(line.getMaterial().getCode()); result.add(line); } catch (Exception e) { errors.add("็ฌฌ" + rowIdx + "่กŒ๏ผš" + e.getMessage()); } } if (errors.isEmpty() == false) throw new Exception(JsonUtil.objectToJson(errors)); return result; } private Map<String,Material> getMaterials(String storeUuid){ Map<String,Material> materials = new HashMap<String,Material>(); FlecsQueryDefinition condition = new FlecsQueryDefinition(); condition.addFlecsCondition(Materials.FIELD_STORE, Materials.OPERATOR_EQUALS, storeUuid); condition.addFlecsCondition(Materials.FIELD_STATE, Materials.OPERATOR_EQUALS, BIZ_STATE); List<Material> materialList = materialService.query(condition).getRecords(); if(materialList.size() <= 0) return null; for(Material m: materialList){ materials.put(m.getCode(), m); } return materials; } }
4,321
0.687515
0.673697
111
35.162163
27.375448
103
false
false
0
0
0
0
0
0
0.747748
false
false
10
d0baef9fe29cdc3866d45cc332bad915fad45693
12,395,275,626,639
66c0afc5d8a68fd23300a60dc8ec89093f9f48f2
/src/app/ApplicationQuery.java
bf8e008ed126ea099b76fe8dc582c3a2f3cfac4a
[]
no_license
emirPuskaITAkademija/BookPublisher
https://github.com/emirPuskaITAkademija/BookPublisher
a846fcf4a976864fe2b3d2ae602907bb1133d566
1e9594b3208806236cbf51ad5a123e2167cc1c5d
refs/heads/master
2022-11-11T02:49:46.037000
2020-06-27T08:11:34
2020-06-27T08:11:34
275,328,268
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package app; //PARAMETRIZOVANI Upiti -> import app.CloseableSession; import app.HibernateUtil; import app.model.Book; import java.util.List; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; public class ApplicationQuery { public static void main(String[] args) { SessionFactory sessionFactory = HibernateUtil.getSessionFactory(); try(CloseableSession closeableSession = new CloseableSession(sessionFactory.openSession())){ //parametrizovani sa like %% String parametar = "ostrvo"; Session session = closeableSession.getSession(); Query query = session.createQuery("from Book book where lower(book.title) like :input"); query.setParameter("input", "%"+parametar.toLowerCase()+"%"); List<Book> books = query.list(); books.forEach(System.out::println); }catch(Exception he){ throw new RuntimeException(he.getMessage()); } } }
UTF-8
Java
1,037
java
ApplicationQuery.java
Java
[]
null
[]
package app; //PARAMETRIZOVANI Upiti -> import app.CloseableSession; import app.HibernateUtil; import app.model.Book; import java.util.List; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; public class ApplicationQuery { public static void main(String[] args) { SessionFactory sessionFactory = HibernateUtil.getSessionFactory(); try(CloseableSession closeableSession = new CloseableSession(sessionFactory.openSession())){ //parametrizovani sa like %% String parametar = "ostrvo"; Session session = closeableSession.getSession(); Query query = session.createQuery("from Book book where lower(book.title) like :input"); query.setParameter("input", "%"+parametar.toLowerCase()+"%"); List<Book> books = query.list(); books.forEach(System.out::println); }catch(Exception he){ throw new RuntimeException(he.getMessage()); } } }
1,037
0.656702
0.656702
28
35.035713
27.042933
100
false
false
0
0
0
0
0
0
0.607143
false
false
10
d8575b43cb63f9cb95b523c024126cccd5180a55
18,090,402,321,710
51efbdb873776ada01b6ce61075678cc7feceac5
/Spring-Cloud-Service-1/src/main/java/com/cchuaspace/system/service/SysCommodityInfoDetailsService.java
b04d53105fb4f9d6e2a867b33d2fa907cd92d228
[]
no_license
vipcchua/Spring-Cloud
https://github.com/vipcchua/Spring-Cloud
87f443808546bbee98f202493590234eed05ddd7
c4c4e9b3987406d9769e6367ff88a734ee1ebd74
refs/heads/master
2021-01-12T00:19:34.927000
2017-05-24T06:24:38
2017-05-24T06:24:38
78,705,974
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.cchuaspace.system.service; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.TypeReference; import com.cchuaspace.currency.CchuaTool; import com.cchuaspace.mapper.CommodityInfoDetailsMapper; import com.cchuaspace.mapper.CommodityInfoMapper; import com.cchuaspace.mapper.SysCommodityPriceMapper; import com.cchuaspace.model.CommodityInfo; import com.cchuaspace.model.CommodityInfoDetails; import com.cchuaspace.model.SysCommodityPrice; import com.cchuaspace.pojo.CommodityInfoDetailsVo; import com.cchuaspace.pojo.CommodityInfoVo; import com.cchuaspace.pojo.PaginationVo; import org.apache.commons.beanutils.PropertyUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Service; import java.lang.reflect.InvocationTargetException; import java.util.HashMap; import java.util.List; /* * ****************<--*---Code information---*-->************** * * Author: Cchua * GitHub: https://github.com/vipcchua * Blog : weibo.com/vipcchua * * * ************************************************************/ @Service @Scope("prototype") public class SysCommodityInfoDetailsService { @Autowired private CommodityInfoMapper commodityInfoMapper; @Autowired private CommodityInfoDetailsMapper commodityInfoDetailsMapper; @Autowired private SysCommodityPriceMapper sysCommodityPriceMapper; @Autowired private PaginationVo paginationVo; @Autowired private CommodityInfoVo commodityInfoVo; @Autowired private CchuaTool cchuaTool; /* @Qualifier("PaginationVo") */ /* @Component */ public PaginationVo SelectByNumber(int commoditynumber) { CommodityInfo data = commodityInfoMapper.SelectCommodityByNumberObj(commoditynumber); List<CommodityInfoDetails> datas = commodityInfoDetailsMapper.SelectCByNumberObj(data.getCommodityNumber()); try { PropertyUtils.copyProperties(commodityInfoVo, data); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvocationTargetException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchMethodException e) { // TODO Auto-generated catch block e.printStackTrace(); } commodityInfoVo.setDataResultObj(datas); paginationVo.setDataResultObj(commodityInfoVo); return paginationVo; } public PaginationVo InsertInfo(String CommodityInfo) { CommodityInfoDetails json = JSONObject.parseObject(CommodityInfo, CommodityInfoDetails.class); json.setId(cchuaTool.uuid()); int tostate = commodityInfoDetailsMapper.insertSelective(json); if (tostate != 0) paginationVo.setSqlState("Success"); else paginationVo.setSqlState("Error"); return paginationVo; } public PaginationVo insertinfoprice(String commodityInfo) { try { HashMap<String, String> map = JSON.parseObject(commodityInfo, new TypeReference<HashMap<String, String>>() { }); CommodityInfoDetails json = JSONObject.parseObject(map.get("info"), CommodityInfoDetails.class); SysCommodityPrice price = JSONObject.parseObject(map.get("price"), SysCommodityPrice.class); if (json.getCommodityNumber() == 0 && price.getCommodityNumber() == 0) { paginationVo.setHtmlState("Error"); return paginationVo; } else { json.setId(cchuaTool.uuid()); price.setId(cchuaTool.uuid()); int tostate = commodityInfoDetailsMapper.insertSelective(json); int pricestate = sysCommodityPriceMapper.insertSelective(price); if (tostate != 0 && pricestate != 0) paginationVo.setHtmlState("Success"); else paginationVo.setHtmlState("Error"); return paginationVo; } } catch (Exception e) { paginationVo.setHtmlState("Error"); return paginationVo; } } public PaginationVo SelectAllByPage(String data) { CommodityInfoDetailsVo json = JSONObject.parseObject(data, CommodityInfoDetailsVo.class); List<CommodityInfoDetailsVo> sqldata = commodityInfoDetailsMapper.SelectAllByPage(json); for (int i = 0; i < sqldata.size(); i++) { try { List<CommodityInfo> commodityInfodata = commodityInfoMapper.SelectCommodityByNumber(sqldata.get(i).getCommodityNumber()); sqldata.get(i).setDataResultList(commodityInfodata); } catch (Exception e) { sqldata.get(i).setDataResultObj("Error"); } } paginationVo.setPaginalNumber(Math.ceil(sqldata.get(0).getDataTotal() / json.getPagerow())); paginationVo.setDataResultList(sqldata); return paginationVo; } public PaginationVo updateById(String CommodityInfo) { CommodityInfoDetails json = JSONObject.parseObject(CommodityInfo, CommodityInfoDetails.class); int tostate = commodityInfoDetailsMapper.updateByPrimaryKeySelective(json); if (tostate != 0) paginationVo.setSqlState("Success"); else paginationVo.setSqlState("Error"); return paginationVo; } }
UTF-8
Java
5,566
java
SysCommodityInfoDetailsService.java
Java
[ { "context": " information---*-->**************\n * \t\n *\t\tAuthor: Cchua\n *\t\tGitHub: https://github.com/vipcchua\n *\t\tBlog ", "end": 1042, "score": 0.8264694213867188, "start": 1037, "tag": "NAME", "value": "Cchua" }, { "context": "\n *\t\tAuthor: Cchua\n *\t\tGitHub: https://github.com/vipcchua\n *\t\tBlog : weibo.com/vipcchua\n * \n * \n * *******", "end": 1082, "score": 0.9996967911720276, "start": 1074, "tag": "USERNAME", "value": "vipcchua" } ]
null
[]
package com.cchuaspace.system.service; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.TypeReference; import com.cchuaspace.currency.CchuaTool; import com.cchuaspace.mapper.CommodityInfoDetailsMapper; import com.cchuaspace.mapper.CommodityInfoMapper; import com.cchuaspace.mapper.SysCommodityPriceMapper; import com.cchuaspace.model.CommodityInfo; import com.cchuaspace.model.CommodityInfoDetails; import com.cchuaspace.model.SysCommodityPrice; import com.cchuaspace.pojo.CommodityInfoDetailsVo; import com.cchuaspace.pojo.CommodityInfoVo; import com.cchuaspace.pojo.PaginationVo; import org.apache.commons.beanutils.PropertyUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Service; import java.lang.reflect.InvocationTargetException; import java.util.HashMap; import java.util.List; /* * ****************<--*---Code information---*-->************** * * Author: Cchua * GitHub: https://github.com/vipcchua * Blog : weibo.com/vipcchua * * * ************************************************************/ @Service @Scope("prototype") public class SysCommodityInfoDetailsService { @Autowired private CommodityInfoMapper commodityInfoMapper; @Autowired private CommodityInfoDetailsMapper commodityInfoDetailsMapper; @Autowired private SysCommodityPriceMapper sysCommodityPriceMapper; @Autowired private PaginationVo paginationVo; @Autowired private CommodityInfoVo commodityInfoVo; @Autowired private CchuaTool cchuaTool; /* @Qualifier("PaginationVo") */ /* @Component */ public PaginationVo SelectByNumber(int commoditynumber) { CommodityInfo data = commodityInfoMapper.SelectCommodityByNumberObj(commoditynumber); List<CommodityInfoDetails> datas = commodityInfoDetailsMapper.SelectCByNumberObj(data.getCommodityNumber()); try { PropertyUtils.copyProperties(commodityInfoVo, data); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvocationTargetException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchMethodException e) { // TODO Auto-generated catch block e.printStackTrace(); } commodityInfoVo.setDataResultObj(datas); paginationVo.setDataResultObj(commodityInfoVo); return paginationVo; } public PaginationVo InsertInfo(String CommodityInfo) { CommodityInfoDetails json = JSONObject.parseObject(CommodityInfo, CommodityInfoDetails.class); json.setId(cchuaTool.uuid()); int tostate = commodityInfoDetailsMapper.insertSelective(json); if (tostate != 0) paginationVo.setSqlState("Success"); else paginationVo.setSqlState("Error"); return paginationVo; } public PaginationVo insertinfoprice(String commodityInfo) { try { HashMap<String, String> map = JSON.parseObject(commodityInfo, new TypeReference<HashMap<String, String>>() { }); CommodityInfoDetails json = JSONObject.parseObject(map.get("info"), CommodityInfoDetails.class); SysCommodityPrice price = JSONObject.parseObject(map.get("price"), SysCommodityPrice.class); if (json.getCommodityNumber() == 0 && price.getCommodityNumber() == 0) { paginationVo.setHtmlState("Error"); return paginationVo; } else { json.setId(cchuaTool.uuid()); price.setId(cchuaTool.uuid()); int tostate = commodityInfoDetailsMapper.insertSelective(json); int pricestate = sysCommodityPriceMapper.insertSelective(price); if (tostate != 0 && pricestate != 0) paginationVo.setHtmlState("Success"); else paginationVo.setHtmlState("Error"); return paginationVo; } } catch (Exception e) { paginationVo.setHtmlState("Error"); return paginationVo; } } public PaginationVo SelectAllByPage(String data) { CommodityInfoDetailsVo json = JSONObject.parseObject(data, CommodityInfoDetailsVo.class); List<CommodityInfoDetailsVo> sqldata = commodityInfoDetailsMapper.SelectAllByPage(json); for (int i = 0; i < sqldata.size(); i++) { try { List<CommodityInfo> commodityInfodata = commodityInfoMapper.SelectCommodityByNumber(sqldata.get(i).getCommodityNumber()); sqldata.get(i).setDataResultList(commodityInfodata); } catch (Exception e) { sqldata.get(i).setDataResultObj("Error"); } } paginationVo.setPaginalNumber(Math.ceil(sqldata.get(0).getDataTotal() / json.getPagerow())); paginationVo.setDataResultList(sqldata); return paginationVo; } public PaginationVo updateById(String CommodityInfo) { CommodityInfoDetails json = JSONObject.parseObject(CommodityInfo, CommodityInfoDetails.class); int tostate = commodityInfoDetailsMapper.updateByPrimaryKeySelective(json); if (tostate != 0) paginationVo.setSqlState("Success"); else paginationVo.setSqlState("Error"); return paginationVo; } }
5,566
0.668882
0.667445
176
30.625
30.47999
137
false
false
0
0
0
0
0
0
0.5
false
false
10
a6278974765a8951827f2ceef13c72009ef737d9
4,999,341,996,751
5cf8888f01beee24b014c9e7525d68b0fa4325dc
/own/editor/src/main/java/strong_bridge/shape/Rectangle.java
b29d77b7b8833c7948cbecade0ff515640d79b6b
[ "Apache-2.0" ]
permissive
ljaljushkin/PatternPractise
https://github.com/ljaljushkin/PatternPractise
b5b5272c5e4896d636b72c4b7852773a1fc0d872
dfbe337f0da2428b37f6171a9522502c1e05e26f
refs/heads/master
2021-01-10T08:10:49.270000
2015-12-09T07:27:33
2015-12-09T07:27:33
46,216,082
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package strong_bridge.shape; import strong_bridge.drawer.IDrawer; public class Rectangle extends Shape { private int x, y, w, h; // x,t left down corner public Rectangle(IDrawer drawer) { super(drawer); } @Override public Shape clone(IDrawer drawer) throws CloneNotSupportedException { return new Rectangle(drawer); } public void initialize(int x, int y, int w, int h) { this.x = x; this.y = y; this.w = w; this.h = h; } @Override public void draw() { super.drawRectangle(x, y, w, h); } }
UTF-8
Java
596
java
Rectangle.java
Java
[]
null
[]
package strong_bridge.shape; import strong_bridge.drawer.IDrawer; public class Rectangle extends Shape { private int x, y, w, h; // x,t left down corner public Rectangle(IDrawer drawer) { super(drawer); } @Override public Shape clone(IDrawer drawer) throws CloneNotSupportedException { return new Rectangle(drawer); } public void initialize(int x, int y, int w, int h) { this.x = x; this.y = y; this.w = w; this.h = h; } @Override public void draw() { super.drawRectangle(x, y, w, h); } }
596
0.592282
0.592282
29
19.551723
19.482241
74
false
false
0
0
0
0
0
0
0.689655
false
false
10
6d338b7f760443a582eaa32b213e79bb128475bf
13,348,758,424,847
f2435b29845c36a35c03835f315e2ea565fcbe9d
/app/src/main/java/myapplication/com/tourbook/Share/AddAttractionActivity.java
89fbfad09f085334a610cfb7f330470042fde8f1
[]
no_license
elpl993/TourBook
https://github.com/elpl993/TourBook
e7348517d8f445696dcef16fef9808c4514ba097
811d430308377743d82924831dcaca5a5972d1ea
refs/heads/master
2020-08-27T23:26:29.687000
2019-10-25T08:26:50
2019-10-25T08:26:50
216,823,346
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package myapplication.com.tourbook.Share; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.NumberPicker; import android.widget.RatingBar; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.ittianyu.bottomnavigationviewex.BottomNavigationViewEx; import myapplication.com.tourbook.Models.Attraction; import myapplication.com.tourbook.Models.Trip; import myapplication.com.tourbook.R; import myapplication.com.tourbook.Utils.BottomNavigationViewHelper; import myapplication.com.tourbook.Utils.FirebaseMethods; import myapplication.com.tourbook.dialogs.AddAttractionDialog; import myapplication.com.tourbook.dialogs.CancelAttractionDialog; /** * Created by Lir Zeitouny on 30/08/2019. */ public class AddAttractionActivity extends AppCompatActivity implements AddAttractionDialog.OnGetUserChoice { private static final String TAG = "AddAttractionActivity"; private String name, place, dayOfTrip, numDays, cost, lodging, description, attrImage, currency; private float rate; private NumberPicker mCost; private EditText mName, mPlace, mDayOfTrip, mNumDays, mLodging, mDescription; private TextView mRateText; private RatingBar mRate; private Button btnAddNewAttraction, btnCancelAttraction; private Attraction currentAttraction; private Trip myTrip; private String mGetDialogChoice; private ImageView mImageViewAttraction; private Spinner mCurrency; //constants private static final int ACTIVITY_NUM = 2; private static final int VERIFY_PERMISSIONS_REQUESTS = 1; private Context mContext = AddAttractionActivity.this; private String Document_img1=""; //firebase private FirebaseAuth mAuth; private FirebaseAuth.AuthStateListener mAuthListener; private FirebaseMethods mFirebaseMethods; private FirebaseDatabase mFirebaseDatabase; private DatabaseReference myRef; private String userID; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); Log.d(TAG, "onCreate started."); setContentView(R.layout.activity_add_attraction); mFirebaseMethods = new FirebaseMethods(mContext); mFirebaseDatabase = FirebaseDatabase.getInstance(); myRef = mFirebaseDatabase.getReference(); mAuth = FirebaseAuth.getInstance(); userID = mAuth.getCurrentUser().getUid(); myTrip = (Trip) getIntent().getSerializableExtra("Trip"); NumberPicker np = (NumberPicker)findViewById(R.id.cost); np.setMinValue(0); np.setMaxValue(100); initWidgets(); // setupFirebaseAuth(); init(); setupBottomNavigationView(); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode == RESULT_OK && requestCode == 2 &&data !=null ) { Uri selectedImage = data.getData(); mImageViewAttraction.setImageURI(selectedImage); attrImage = selectedImage.toString(); } } private void init() { btnAddNewAttraction.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { name = mName.getText().toString(); place = mPlace.getText().toString(); dayOfTrip = mDayOfTrip.getText().toString(); numDays = mNumDays.getText().toString(); cost= String.valueOf(mCost.getValue()); lodging = mLodging.getText().toString(); rate= mRate.getRating(); description = mDescription.getText().toString(); currency = mCurrency.getSelectedItem().toString(); if (checkInputs(name, dayOfTrip, cost, String.valueOf(rate),currency)) { String key = myRef.child(getString(R.string.dbname_user_trips)).push().getKey(); currentAttraction = new Attraction(name, place, Integer.parseInt(dayOfTrip), Integer.parseInt(numDays), rate, Integer.parseInt(cost), lodging, description, key, myTrip.getTrip_Key(), userID,currency); currentAttraction.setImageUrl(attrImage); myTrip.getAttractions().put(key, currentAttraction); AddAttractionDialog dialogAdd = new AddAttractionDialog(); dialogAdd.show(getSupportFragmentManager(), getString(R.string.add_attraction_dialog)); dialogAdd.setCancelable(false); } } }); btnCancelAttraction.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (myTrip.getAttractions().size() == 0) { CancelAttractionDialog dialogCancel = new CancelAttractionDialog(); dialogCancel.show(getSupportFragmentManager(), getString(R.string.cancel_attraction_dialog)); dialogCancel.setCancelable(false); } } }); // Spinner spinner = (Spinner) findViewById(R.id.cost); // spinner.setOnItemSelectedListener((AdapterView.OnItemSelectedListener) this); mImageViewAttraction.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { selectImage(); } }); } private void clearDialog() { mName.setText(""); mPlace.setText(""); mDayOfTrip.setText(""); mNumDays.setText(""); //mCost.setText(""); mLodging.setText(""); mRate.setRating(0); mDescription.setText(""); mCurrency.setTag(""); } private boolean checkInputs(String name, String dayOfTrip, String cost, String rate, String currency) { Log.d(TAG, "checkInputs: checking inputs for null values. "); if (name.equals("") || dayOfTrip.equals("") || cost.equals("") || rate.equals("") ||currency.equals("Choose a currency")) { Toast.makeText(mContext, "Name, Day of trip, Cost, Rate and Currency are fields that must be filled out", Toast.LENGTH_SHORT).show(); return false; } return true; } /* * Initialize the activity widgets */ private void initWidgets() { Log.d(TAG, "initWidgets: Initalizing Widgets."); // mCountries = (EditText) findViewById(R.id.input_countries); // btnAddNewTrip = (Button) findViewById(R.id.btn_addtrip); mName = (EditText) findViewById(R.id.attraction_name); mRateText = (TextView) findViewById(R.id.rate_text); mRate = (RatingBar) findViewById(R.id.rate_1_5); mLodging = (EditText) findViewById(R.id.lodging); mDayOfTrip = (EditText) findViewById(R.id.day_of_trip); mCost = (NumberPicker) findViewById(R.id.cost); mCurrency = (Spinner) findViewById(R.id.currency); mDescription = (EditText) findViewById(R.id.description); mNumDays = (EditText) findViewById(R.id.num_of_days); mPlace = (EditText) findViewById(R.id.place); btnAddNewAttraction = (Button) findViewById(R.id.btnAddAttraction); btnCancelAttraction = (Button) findViewById(R.id.btnCancelAttraction); mImageViewAttraction=(ImageView)findViewById(R.id.imageViewAttraction); } private boolean isStringNull(String string) { Log.d(TAG, "isStringNull: checking if string is null"); if (string.equals("")) { return true; } else { return false; } } @Override public void sendChoice(String Choice) { Log.d(TAG, "After dialog "); clearDialog(); Log.d(TAG, "Got choice" + Choice); mGetDialogChoice = Choice; Log.d(TAG, "User Choice: " + mGetDialogChoice); if (mGetDialogChoice == "Yes") Log.d(TAG, "checkUserChoice: Choice" + mGetDialogChoice); else if (mGetDialogChoice == "No") { mFirebaseMethods.addNewTripToFireBase(myTrip); Intent intent = new Intent(AddAttractionActivity.this, ShowTripActivity.class); intent.putExtra("UserId", userID); startActivity(intent); Log.d(TAG, "checkUserChoice: Choice" + mGetDialogChoice); } } /** * BottomNavigationView setup */ private void setupBottomNavigationView() { Log.d(TAG, "setupBottomNavigationView: setting up BottomNavigationView"); BottomNavigationViewEx bottomNavigationViewEx = (BottomNavigationViewEx) findViewById(R.id.bottomNavViewBar); BottomNavigationViewHelper.setupBottomNavigationView(bottomNavigationViewEx); BottomNavigationViewHelper.enableNavigation(mContext, bottomNavigationViewEx); Menu menu = bottomNavigationViewEx.getMenu(); MenuItem menuItem = menu.getItem(ACTIVITY_NUM); menuItem.setChecked(true); } private void selectImage() { Intent intent = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI); startActivityForResult(intent, 2); } }
UTF-8
Java
9,863
java
AddAttractionActivity.java
Java
[ { "context": "dialogs.CancelAttractionDialog;\n\n/**\n * Created by Lir Zeitouny on 30/08/2019.\n */\n\npublic class AddAttractionAct", "end": 1258, "score": 0.999845027923584, "start": 1246, "tag": "NAME", "value": "Lir Zeitouny" } ]
null
[]
package myapplication.com.tourbook.Share; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.NumberPicker; import android.widget.RatingBar; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.ittianyu.bottomnavigationviewex.BottomNavigationViewEx; import myapplication.com.tourbook.Models.Attraction; import myapplication.com.tourbook.Models.Trip; import myapplication.com.tourbook.R; import myapplication.com.tourbook.Utils.BottomNavigationViewHelper; import myapplication.com.tourbook.Utils.FirebaseMethods; import myapplication.com.tourbook.dialogs.AddAttractionDialog; import myapplication.com.tourbook.dialogs.CancelAttractionDialog; /** * Created by <NAME> on 30/08/2019. */ public class AddAttractionActivity extends AppCompatActivity implements AddAttractionDialog.OnGetUserChoice { private static final String TAG = "AddAttractionActivity"; private String name, place, dayOfTrip, numDays, cost, lodging, description, attrImage, currency; private float rate; private NumberPicker mCost; private EditText mName, mPlace, mDayOfTrip, mNumDays, mLodging, mDescription; private TextView mRateText; private RatingBar mRate; private Button btnAddNewAttraction, btnCancelAttraction; private Attraction currentAttraction; private Trip myTrip; private String mGetDialogChoice; private ImageView mImageViewAttraction; private Spinner mCurrency; //constants private static final int ACTIVITY_NUM = 2; private static final int VERIFY_PERMISSIONS_REQUESTS = 1; private Context mContext = AddAttractionActivity.this; private String Document_img1=""; //firebase private FirebaseAuth mAuth; private FirebaseAuth.AuthStateListener mAuthListener; private FirebaseMethods mFirebaseMethods; private FirebaseDatabase mFirebaseDatabase; private DatabaseReference myRef; private String userID; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); Log.d(TAG, "onCreate started."); setContentView(R.layout.activity_add_attraction); mFirebaseMethods = new FirebaseMethods(mContext); mFirebaseDatabase = FirebaseDatabase.getInstance(); myRef = mFirebaseDatabase.getReference(); mAuth = FirebaseAuth.getInstance(); userID = mAuth.getCurrentUser().getUid(); myTrip = (Trip) getIntent().getSerializableExtra("Trip"); NumberPicker np = (NumberPicker)findViewById(R.id.cost); np.setMinValue(0); np.setMaxValue(100); initWidgets(); // setupFirebaseAuth(); init(); setupBottomNavigationView(); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode == RESULT_OK && requestCode == 2 &&data !=null ) { Uri selectedImage = data.getData(); mImageViewAttraction.setImageURI(selectedImage); attrImage = selectedImage.toString(); } } private void init() { btnAddNewAttraction.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { name = mName.getText().toString(); place = mPlace.getText().toString(); dayOfTrip = mDayOfTrip.getText().toString(); numDays = mNumDays.getText().toString(); cost= String.valueOf(mCost.getValue()); lodging = mLodging.getText().toString(); rate= mRate.getRating(); description = mDescription.getText().toString(); currency = mCurrency.getSelectedItem().toString(); if (checkInputs(name, dayOfTrip, cost, String.valueOf(rate),currency)) { String key = myRef.child(getString(R.string.dbname_user_trips)).push().getKey(); currentAttraction = new Attraction(name, place, Integer.parseInt(dayOfTrip), Integer.parseInt(numDays), rate, Integer.parseInt(cost), lodging, description, key, myTrip.getTrip_Key(), userID,currency); currentAttraction.setImageUrl(attrImage); myTrip.getAttractions().put(key, currentAttraction); AddAttractionDialog dialogAdd = new AddAttractionDialog(); dialogAdd.show(getSupportFragmentManager(), getString(R.string.add_attraction_dialog)); dialogAdd.setCancelable(false); } } }); btnCancelAttraction.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (myTrip.getAttractions().size() == 0) { CancelAttractionDialog dialogCancel = new CancelAttractionDialog(); dialogCancel.show(getSupportFragmentManager(), getString(R.string.cancel_attraction_dialog)); dialogCancel.setCancelable(false); } } }); // Spinner spinner = (Spinner) findViewById(R.id.cost); // spinner.setOnItemSelectedListener((AdapterView.OnItemSelectedListener) this); mImageViewAttraction.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { selectImage(); } }); } private void clearDialog() { mName.setText(""); mPlace.setText(""); mDayOfTrip.setText(""); mNumDays.setText(""); //mCost.setText(""); mLodging.setText(""); mRate.setRating(0); mDescription.setText(""); mCurrency.setTag(""); } private boolean checkInputs(String name, String dayOfTrip, String cost, String rate, String currency) { Log.d(TAG, "checkInputs: checking inputs for null values. "); if (name.equals("") || dayOfTrip.equals("") || cost.equals("") || rate.equals("") ||currency.equals("Choose a currency")) { Toast.makeText(mContext, "Name, Day of trip, Cost, Rate and Currency are fields that must be filled out", Toast.LENGTH_SHORT).show(); return false; } return true; } /* * Initialize the activity widgets */ private void initWidgets() { Log.d(TAG, "initWidgets: Initalizing Widgets."); // mCountries = (EditText) findViewById(R.id.input_countries); // btnAddNewTrip = (Button) findViewById(R.id.btn_addtrip); mName = (EditText) findViewById(R.id.attraction_name); mRateText = (TextView) findViewById(R.id.rate_text); mRate = (RatingBar) findViewById(R.id.rate_1_5); mLodging = (EditText) findViewById(R.id.lodging); mDayOfTrip = (EditText) findViewById(R.id.day_of_trip); mCost = (NumberPicker) findViewById(R.id.cost); mCurrency = (Spinner) findViewById(R.id.currency); mDescription = (EditText) findViewById(R.id.description); mNumDays = (EditText) findViewById(R.id.num_of_days); mPlace = (EditText) findViewById(R.id.place); btnAddNewAttraction = (Button) findViewById(R.id.btnAddAttraction); btnCancelAttraction = (Button) findViewById(R.id.btnCancelAttraction); mImageViewAttraction=(ImageView)findViewById(R.id.imageViewAttraction); } private boolean isStringNull(String string) { Log.d(TAG, "isStringNull: checking if string is null"); if (string.equals("")) { return true; } else { return false; } } @Override public void sendChoice(String Choice) { Log.d(TAG, "After dialog "); clearDialog(); Log.d(TAG, "Got choice" + Choice); mGetDialogChoice = Choice; Log.d(TAG, "User Choice: " + mGetDialogChoice); if (mGetDialogChoice == "Yes") Log.d(TAG, "checkUserChoice: Choice" + mGetDialogChoice); else if (mGetDialogChoice == "No") { mFirebaseMethods.addNewTripToFireBase(myTrip); Intent intent = new Intent(AddAttractionActivity.this, ShowTripActivity.class); intent.putExtra("UserId", userID); startActivity(intent); Log.d(TAG, "checkUserChoice: Choice" + mGetDialogChoice); } } /** * BottomNavigationView setup */ private void setupBottomNavigationView() { Log.d(TAG, "setupBottomNavigationView: setting up BottomNavigationView"); BottomNavigationViewEx bottomNavigationViewEx = (BottomNavigationViewEx) findViewById(R.id.bottomNavViewBar); BottomNavigationViewHelper.setupBottomNavigationView(bottomNavigationViewEx); BottomNavigationViewHelper.enableNavigation(mContext, bottomNavigationViewEx); Menu menu = bottomNavigationViewEx.getMenu(); MenuItem menuItem = menu.getItem(ACTIVITY_NUM); menuItem.setChecked(true); } private void selectImage() { Intent intent = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI); startActivityForResult(intent, 2); } }
9,857
0.662881
0.660651
254
37.830708
29.885721
145
false
false
0
0
0
0
0
0
0.858268
false
false
10
60d7b421058947943035f89f599d18d5a60acf19
20,521,353,778,437
16db62a2a5a1ead1b84f6b0ea26118a51a21479f
/src/uoc/tdp/pac4/st/common/ReportResult.java
1a0a76a4f5c5afa3bbce971459b85c095fbfec58
[]
no_license
SwingTeam/PAC4
https://github.com/SwingTeam/PAC4
f6d14c1cb5bf320337d5ce0819e034499ca90316
dbb9430fd720e1584c34fe5e9ebfab0e28e32ca6
refs/heads/master
2016-09-16T10:02:08.077000
2014-12-15T23:09:11
2014-12-15T23:09:11
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package uoc.tdp.pac4.st.common; import java.text.SimpleDateFormat; import java.util.List; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.table.DefaultTableCellRenderer; import javax.swing.table.TableColumn; import javax.swing.JPanel; import javax.swing.JButton; import java.awt.FlowLayout; import javax.swing.SwingConstants; import java.awt.BorderLayout; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import javax.swing.JLabel; import javax.swing.JSplitPane; import javax.swing.JTextPane; import java.awt.SystemColor; import uoc.tdp.pac4.st.common.dto.*; /*** * Classe base per a tots els formularis * que mostren el resultat dels informes * demanats. * * @author Swing Team - 2014 * * @param <T> */ public class ReportResult <T> extends STFrame { private static final long serialVersionUID = -597281336156358964L; private List<T> _reportLines = null; private ReportSelectorData _reportSelectorData = null; private STTable dataTable = null; private JScrollPane dataTableScrollPane = null; private JLabel lblStartDate = null; private JLabel lblEndDate = null; private JLabel lblEstablishment = null; private JLabel lblOrder = null; private JTextPane txtProducts = null; /*** * Constructor * * @param reportLines Llista de ReportLine * que contรฉ les lรญnies de l'informe * @param reportSelectorData Instร ncia de * ReportSelectorData que contรฉ la selecciรณ * de l'usuari. */ public ReportResult(List<T> reportLines, ReportSelectorData reportSelectorData) { super(null, null, false); this._reportLines = reportLines; this._reportSelectorData = reportSelectorData; setContentPane(contentPane); contentPane.setLayout(new BorderLayout(0, 0)); setBounds(100, 100, 934, 477); JPanel panelBottom = new JPanel(); contentPane.add(panelBottom, BorderLayout.SOUTH); panelBottom.setLayout(new FlowLayout(FlowLayout.RIGHT)); JButton btnClose = new JButton("BUTTON_CLOSE"); btnClose.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { dispose(); } }); btnClose.setHorizontalAlignment(SwingConstants.RIGHT); panelBottom.add(btnClose); this.dataTableScrollPane = new JScrollPane(); // splitPane.add(scrollPane, BorderLayout.SOUTH); JPanel pnlHeader = new JPanel(); pnlHeader.setLayout(null); JLabel lblDataDinici = new JLabel("LABEL_START_DATE_COLON"); lblDataDinici.setBounds(12, 5, 135, 15); pnlHeader.add(lblDataDinici); this.lblStartDate = new JLabel(""); lblStartDate.setBounds(152, 5, 119, 15); pnlHeader.add(lblStartDate); JLabel lblDataFinal = new JLabel("LABEL_END_DATE_COLON"); lblDataFinal.setBounds(12, 32, 135, 15); pnlHeader.add(lblDataFinal); this.lblEndDate = new JLabel(""); lblEndDate.setBounds(152, 32, 119, 15); pnlHeader.add(lblEndDate); JLabel lblLocal = new JLabel("LABEL_ESTAB_COLON"); lblLocal.setHorizontalAlignment(SwingConstants.RIGHT); lblLocal.setBounds(272, 5, 146, 15); pnlHeader.add(lblLocal); this.lblEstablishment = new JLabel(""); lblEstablishment.setBounds(424, 5, 360, 15); pnlHeader.add(lblEstablishment); JLabel lblOrderTitle = new JLabel("LABEL_ORDER_COLON"); lblOrderTitle.setHorizontalAlignment(SwingConstants.RIGHT); lblOrderTitle.setBounds(272, 32, 146, 15); pnlHeader.add(lblOrderTitle); this.lblOrder = new JLabel(""); lblOrder.setBounds(424, 32, 257, 15); pnlHeader.add(lblOrder); JLabel lblRecanvis = new JLabel("LABEL_PRODUCTS_COLON"); lblRecanvis.setBounds(12, 59, 135, 15); pnlHeader.add(lblRecanvis); JScrollPane scrollPane_1 = new JScrollPane(); scrollPane_1.setBounds(152, 59, 632, 58); pnlHeader.add(scrollPane_1); this.txtProducts = new JTextPane(); txtProducts.setBorder(null); txtProducts.setBackground(SystemColor.text); txtProducts.setEditable(false); scrollPane_1.setViewportView(txtProducts); JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, pnlHeader, this.dataTableScrollPane); splitPane.setDividerLocation(130); contentPane.add(splitPane, BorderLayout.CENTER); //Omplim la selecciรณ de l'usuari this.fillinSelectionData(); } /*** * Posa els valors de la instร ncia rebuda * a les etiquetes de capรงalera. * * @param reportSelectorData Instร ncia de * ReportSelectorData amb la selecciรณ que * ha fet l'usuari. */ private void fillinSelectionData(){ this.lblStartDate.setText(new SimpleDateFormat(Constants.LOCAL_DATE_FORMAT).format(this._reportSelectorData.getStartDate())); this.lblEndDate.setText(new SimpleDateFormat(Constants.LOCAL_DATE_FORMAT).format(this._reportSelectorData.getEndDate())); this.lblEstablishment.setText(this._reportSelectorData.getEstablishmentName()); this.lblOrder.setText(Managers.i18n.getTranslation(Constants.ENUM_PREFIX + this._reportSelectorData.getOrder().toUpperCase())); StringBuilder products = new StringBuilder(); for(STTreeNode node : this._reportSelectorData.getProducts()){ if (products.length() > 0) products.append(" - "); if (node.getNodeType() == Enums.NodeType.Root) products.append(Managers.i18n.getTranslation(TokenKeys.ALL_PRODUCTS)); else if (node.getNodeType() == Enums.NodeType.Group) products.append(Managers.i18n.getTranslation(TokenKeys.GROUP) + ": " + node.getDescription()); else if (node.getNodeType() == Enums.NodeType.Subgroup) products.append(Managers.i18n.getTranslation(TokenKeys.SUBGROUP) + ": " + node.getDescription()); else products.append(node.getIdAsString()); } this.txtProducts.setText(products.toString()); } /*** * Mรจtode que s'encarrega de crear la taula * a partir de las lรญnies de l'informe. * * @param reportLines Lista d'objecte ReportLineInterface * i que contenen la informaciรณ de l'informe. */ protected void showReport(String[] columnName, String[] columnField, int[] columnWidth, int[] columnAlign){ String[] columnTraslatedName = this.translateColumns(columnName); Object[][] dataList = new Object[0][columnTraslatedName.length]; if (this._reportLines != null && this._reportLines.size() > 0){ dataList = new Object[this._reportLines.size()][columnTraslatedName.length]; int i = 0; for (T item : this._reportLines) { for (int n = 0; n < columnTraslatedName.length; n++){ dataList[i][n] = ((ReportLine)item).getValue(columnField[n]); } i++; } } if (this.dataTable == null){ this.dataTable = new STTable(dataList, columnTraslatedName); this.dataTable.setFillsViewportHeight(true); this.dataTableScrollPane.setViewportView(this.dataTable); } STTableModel tableModel = new STTableModel(dataList, columnTraslatedName); this.dataTable.setModel(tableModel); tableModel.fireTableDataChanged(); //Amplada de les columnes i alineaciรณ this.dataTable.setAutoResizeMode(JTable.AUTO_RESIZE_LAST_COLUMN); TableColumn column = null; for (int j = 0; j < columnWidth.length; j++) { //Amplada column = this.dataTable.getColumnModel().getColumn(j); //El valor de l'amplada de les columnes //รฉs porcentual... per tant, hem de fer //la conversiรณ int formWidth = this.getWidth() - 50; int width = (int) (formWidth * columnWidth[j] / 100); column.setPreferredWidth(width); //Alineaciรณ DefaultTableCellRenderer renderer = new DefaultTableCellRenderer(); renderer.setHorizontalAlignment(columnAlign[j]); this.dataTable.getColumnModel().getColumn(j).setCellRenderer(renderer); } } /*** * Tradueix tots els tokens corresponents * als noms de columnes de l'informe. * * @return */ private String[] translateColumns(String[] columnName){ String[] result = columnName; for (int i = 0; i < result.length; i++){ result[i] = Managers.i18n.getTranslation(result[i]); } return result; } }
UTF-8
Java
8,069
java
ReportResult.java
Java
[ { "context": "resultat dels informes\n * demanats.\n * \n * @author Swing Team - 2014\n *\n * @param <T>\n */\npublic class ReportRe", "end": 745, "score": 0.9994446635246277, "start": 735, "tag": "NAME", "value": "Swing Team" } ]
null
[]
package uoc.tdp.pac4.st.common; import java.text.SimpleDateFormat; import java.util.List; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.table.DefaultTableCellRenderer; import javax.swing.table.TableColumn; import javax.swing.JPanel; import javax.swing.JButton; import java.awt.FlowLayout; import javax.swing.SwingConstants; import java.awt.BorderLayout; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import javax.swing.JLabel; import javax.swing.JSplitPane; import javax.swing.JTextPane; import java.awt.SystemColor; import uoc.tdp.pac4.st.common.dto.*; /*** * Classe base per a tots els formularis * que mostren el resultat dels informes * demanats. * * @author <NAME> - 2014 * * @param <T> */ public class ReportResult <T> extends STFrame { private static final long serialVersionUID = -597281336156358964L; private List<T> _reportLines = null; private ReportSelectorData _reportSelectorData = null; private STTable dataTable = null; private JScrollPane dataTableScrollPane = null; private JLabel lblStartDate = null; private JLabel lblEndDate = null; private JLabel lblEstablishment = null; private JLabel lblOrder = null; private JTextPane txtProducts = null; /*** * Constructor * * @param reportLines Llista de ReportLine * que contรฉ les lรญnies de l'informe * @param reportSelectorData Instร ncia de * ReportSelectorData que contรฉ la selecciรณ * de l'usuari. */ public ReportResult(List<T> reportLines, ReportSelectorData reportSelectorData) { super(null, null, false); this._reportLines = reportLines; this._reportSelectorData = reportSelectorData; setContentPane(contentPane); contentPane.setLayout(new BorderLayout(0, 0)); setBounds(100, 100, 934, 477); JPanel panelBottom = new JPanel(); contentPane.add(panelBottom, BorderLayout.SOUTH); panelBottom.setLayout(new FlowLayout(FlowLayout.RIGHT)); JButton btnClose = new JButton("BUTTON_CLOSE"); btnClose.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { dispose(); } }); btnClose.setHorizontalAlignment(SwingConstants.RIGHT); panelBottom.add(btnClose); this.dataTableScrollPane = new JScrollPane(); // splitPane.add(scrollPane, BorderLayout.SOUTH); JPanel pnlHeader = new JPanel(); pnlHeader.setLayout(null); JLabel lblDataDinici = new JLabel("LABEL_START_DATE_COLON"); lblDataDinici.setBounds(12, 5, 135, 15); pnlHeader.add(lblDataDinici); this.lblStartDate = new JLabel(""); lblStartDate.setBounds(152, 5, 119, 15); pnlHeader.add(lblStartDate); JLabel lblDataFinal = new JLabel("LABEL_END_DATE_COLON"); lblDataFinal.setBounds(12, 32, 135, 15); pnlHeader.add(lblDataFinal); this.lblEndDate = new JLabel(""); lblEndDate.setBounds(152, 32, 119, 15); pnlHeader.add(lblEndDate); JLabel lblLocal = new JLabel("LABEL_ESTAB_COLON"); lblLocal.setHorizontalAlignment(SwingConstants.RIGHT); lblLocal.setBounds(272, 5, 146, 15); pnlHeader.add(lblLocal); this.lblEstablishment = new JLabel(""); lblEstablishment.setBounds(424, 5, 360, 15); pnlHeader.add(lblEstablishment); JLabel lblOrderTitle = new JLabel("LABEL_ORDER_COLON"); lblOrderTitle.setHorizontalAlignment(SwingConstants.RIGHT); lblOrderTitle.setBounds(272, 32, 146, 15); pnlHeader.add(lblOrderTitle); this.lblOrder = new JLabel(""); lblOrder.setBounds(424, 32, 257, 15); pnlHeader.add(lblOrder); JLabel lblRecanvis = new JLabel("LABEL_PRODUCTS_COLON"); lblRecanvis.setBounds(12, 59, 135, 15); pnlHeader.add(lblRecanvis); JScrollPane scrollPane_1 = new JScrollPane(); scrollPane_1.setBounds(152, 59, 632, 58); pnlHeader.add(scrollPane_1); this.txtProducts = new JTextPane(); txtProducts.setBorder(null); txtProducts.setBackground(SystemColor.text); txtProducts.setEditable(false); scrollPane_1.setViewportView(txtProducts); JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, pnlHeader, this.dataTableScrollPane); splitPane.setDividerLocation(130); contentPane.add(splitPane, BorderLayout.CENTER); //Omplim la selecciรณ de l'usuari this.fillinSelectionData(); } /*** * Posa els valors de la instร ncia rebuda * a les etiquetes de capรงalera. * * @param reportSelectorData Instร ncia de * ReportSelectorData amb la selecciรณ que * ha fet l'usuari. */ private void fillinSelectionData(){ this.lblStartDate.setText(new SimpleDateFormat(Constants.LOCAL_DATE_FORMAT).format(this._reportSelectorData.getStartDate())); this.lblEndDate.setText(new SimpleDateFormat(Constants.LOCAL_DATE_FORMAT).format(this._reportSelectorData.getEndDate())); this.lblEstablishment.setText(this._reportSelectorData.getEstablishmentName()); this.lblOrder.setText(Managers.i18n.getTranslation(Constants.ENUM_PREFIX + this._reportSelectorData.getOrder().toUpperCase())); StringBuilder products = new StringBuilder(); for(STTreeNode node : this._reportSelectorData.getProducts()){ if (products.length() > 0) products.append(" - "); if (node.getNodeType() == Enums.NodeType.Root) products.append(Managers.i18n.getTranslation(TokenKeys.ALL_PRODUCTS)); else if (node.getNodeType() == Enums.NodeType.Group) products.append(Managers.i18n.getTranslation(TokenKeys.GROUP) + ": " + node.getDescription()); else if (node.getNodeType() == Enums.NodeType.Subgroup) products.append(Managers.i18n.getTranslation(TokenKeys.SUBGROUP) + ": " + node.getDescription()); else products.append(node.getIdAsString()); } this.txtProducts.setText(products.toString()); } /*** * Mรจtode que s'encarrega de crear la taula * a partir de las lรญnies de l'informe. * * @param reportLines Lista d'objecte ReportLineInterface * i que contenen la informaciรณ de l'informe. */ protected void showReport(String[] columnName, String[] columnField, int[] columnWidth, int[] columnAlign){ String[] columnTraslatedName = this.translateColumns(columnName); Object[][] dataList = new Object[0][columnTraslatedName.length]; if (this._reportLines != null && this._reportLines.size() > 0){ dataList = new Object[this._reportLines.size()][columnTraslatedName.length]; int i = 0; for (T item : this._reportLines) { for (int n = 0; n < columnTraslatedName.length; n++){ dataList[i][n] = ((ReportLine)item).getValue(columnField[n]); } i++; } } if (this.dataTable == null){ this.dataTable = new STTable(dataList, columnTraslatedName); this.dataTable.setFillsViewportHeight(true); this.dataTableScrollPane.setViewportView(this.dataTable); } STTableModel tableModel = new STTableModel(dataList, columnTraslatedName); this.dataTable.setModel(tableModel); tableModel.fireTableDataChanged(); //Amplada de les columnes i alineaciรณ this.dataTable.setAutoResizeMode(JTable.AUTO_RESIZE_LAST_COLUMN); TableColumn column = null; for (int j = 0; j < columnWidth.length; j++) { //Amplada column = this.dataTable.getColumnModel().getColumn(j); //El valor de l'amplada de les columnes //รฉs porcentual... per tant, hem de fer //la conversiรณ int formWidth = this.getWidth() - 50; int width = (int) (formWidth * columnWidth[j] / 100); column.setPreferredWidth(width); //Alineaciรณ DefaultTableCellRenderer renderer = new DefaultTableCellRenderer(); renderer.setHorizontalAlignment(columnAlign[j]); this.dataTable.getColumnModel().getColumn(j).setCellRenderer(renderer); } } /*** * Tradueix tots els tokens corresponents * als noms de columnes de l'informe. * * @return */ private String[] translateColumns(String[] columnName){ String[] result = columnName; for (int i = 0; i < result.length; i++){ result[i] = Managers.i18n.getTranslation(result[i]); } return result; } }
8,065
0.714481
0.69461
243
32.135803
25.850832
129
false
false
0
0
0
0
0
0
2.09465
false
false
10
468daa11d00830f5f3bc6ecd6ca603922df8f744
36,472,862,278,964
bb0e001f1e17b5a5398927e991e9cf476661fc65
/workshop/Assignment3.java
aef6f0a9d846e85c8500361f0afcfd9cff42f735
[]
no_license
rubenvroegindeweij/javaview
https://github.com/rubenvroegindeweij/javaview
8969219586813bc2c86ac5be0783c5bb0117062a
ddbca432c12056420ca6848bdf37ad3633e02596
refs/heads/master
2021-01-18T03:12:38.011000
2016-06-12T14:11:06
2016-06-12T14:11:06
58,365,927
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package workshop; import java.awt.Color; import java.util.Arrays; import java.util.Random; import jv.geom.PgElementSet; import jv.project.PgGeometry; import jv.vecmath.PdVector; import jv.vecmath.PiVector; import jvx.project.PjWorkshop; import jv.vecmath.PdMatrix; import jv.object.PsDebug; import jvx.numeric.PnSparseMatrix; import java.util.ArrayList; import dev6.numeric.PnMumpsSolver; import jvx.numeric.PnSparseMatrix; import jv.object.PsObject; import jvx.geom.PgVertexStar; public class Assignment3 extends PjWorkshop { PgElementSet m_geom; PgElementSet m_geomSave; PnSparseMatrix G; // Gradient Matrix PnSparseMatrix M; // Mass Matrix PnSparseMatrix Mv; PnSparseMatrix S; // Stiffness Matrix PnSparseMatrix L; // Laplacian Matrix double stepwidth; PdVector newVertices_x; PdVector newVertices_y; PdVector newVertices_z; PdVector xSolved; PdVector ySolved; PdVector zSolved; public Assignment3() { super("Assignment 3"); init(); } @Override public void setGeometry(PgGeometry geom) { super.setGeometry(geom); m_geom = (PgElementSet)super.m_geom; m_geomSave = (PgElementSet)super.m_geomSave; } public void init() { super.init(); } public void iterativeAveraging(double stepwidth) throws Exception { this.stepwidth = stepwidth; // make a copy of the original model, and store the vertices in an array PgElementSet clonedGeom = (PgElementSet) m_geom.clone(); PdVector[] newVertices = (PdVector[]) clonedGeom.getVertices(); // for each vertice, find its neighbours and store them in an array PiVector[] NeighbouringVertices = PgVertexStar.makeVertexNeighbours(m_geom); int numOfVertices = m_geom.getNumVertices(); for (int i = 0; i < numOfVertices; i++) { PdVector currentVertex = m_geom.getVertex(i); PdVector tempVertex = new PdVector(0d, 0d, 0d); int numOfNeighbours = NeighbouringVertices[i].getSize(); for (int j = 0; j < numOfNeighbours; j++) { PdVector oneNeighbour = m_geom.getVertex(NeighbouringVertices[i].getEntry(j)); tempVertex.add(oneNeighbour); } // compute the average coordinate of its neighbors tempVertex.multScalar(1d / (double)numOfNeighbours); // find the difference between the average coordiante and the original one tempVertex.sub(currentVertex); // multiply with stepwidth tempVertex.multScalar(stepwidth); // calculate the new coordinates newVertices[i].add(tempVertex); } // update the model with the new vertices m_geom.setVertices(newVertices); } public void explicitMCF(double stepwidth) throws Exception { calculateLaplacianMatrix(); this.stepwidth = stepwidth; int numOfVertices = m_geom.getNumVertices(); newVertices_x = new PdVector(numOfVertices); newVertices_y = new PdVector(numOfVertices); newVertices_z = new PdVector(numOfVertices); for (int i = 0; i < numOfVertices; i++) { newVertices_x.setEntry(i, m_geom.getVertex(i).getEntry(0)); newVertices_y.setEntry(i, m_geom.getVertex(i).getEntry(1)); newVertices_z.setEntry(i, m_geom.getVertex(i).getEntry(2)); } PdVector tempNewVertices_x = PnSparseMatrix.rightMultVector(L, newVertices_x, new PdVector()); tempNewVertices_x.multScalar(stepwidth); newVertices_x.sub(tempNewVertices_x); PdVector tempNewVertices_y = PnSparseMatrix.rightMultVector(L, newVertices_y, new PdVector()); tempNewVertices_y.multScalar(stepwidth); newVertices_y.sub(tempNewVertices_y); PdVector tempNewVertices_z = PnSparseMatrix.rightMultVector(L, newVertices_z, new PdVector()); tempNewVertices_z.multScalar(stepwidth); newVertices_z.sub(tempNewVertices_z); for (int i = 0; i < numOfVertices; i++) { m_geom.setVertex(i, newVertices_x.getEntry(i), newVertices_y.getEntry(i), newVertices_z.getEntry(i)); } } public void implicitMCF(double stepwidth) throws Exception { calculateMandS(); this.stepwidth = stepwidth; int numOfVertices = m_geom.getNumVertices(); // construct A = M + tau*S PnSparseMatrix A = new PnSparseMatrix(numOfVertices, numOfVertices); A.copy(S); A.multScalar(stepwidth); A.add(M); // construct three vectors containing coordinate system specific values from every vertex PdVector x = new PdVector(numOfVertices); PdVector y = new PdVector(numOfVertices); PdVector z = new PdVector(numOfVertices); for (int i = 0; i < numOfVertices; i++) { x.setEntry(i, m_geom.getVertex(i).getEntry(0)); y.setEntry(i, m_geom.getVertex(i).getEntry(1)); z.setEntry(i, m_geom.getVertex(i).getEntry(2)); } // B = Mx (x depending on the coordinate system) PdVector Bx = PnSparseMatrix.rightMultVector(M, x, new PdVector()); PdVector By = PnSparseMatrix.rightMultVector(M, y, new PdVector()); PdVector Bz = PnSparseMatrix.rightMultVector(M, z, new PdVector()); xSolved = new PdVector(numOfVertices); ySolved = new PdVector(numOfVertices); zSolved = new PdVector(numOfVertices); long factorization = PnMumpsSolver.factor(A, PnMumpsSolver.Type.UNSYMMETRIC); PnMumpsSolver.solve(factorization, xSolved, Bx); PnMumpsSolver.solve(factorization, ySolved, By); PnMumpsSolver.solve(factorization, zSolved, Bz); for (int i = 0; i < xSolved.getSize(); i++) { m_geom.setVertex(i, xSolved.getEntry(i), ySolved.getEntry(i), zSolved.getEntry(i)); } } public void calculateLaplacianMatrix() { calculateMandS(); PnSparseMatrix MInverse = new PnSparseMatrix(M.getNumRows(), M.getNumCols(), 1); //calculate M-inverse // N.B.: this method can only be used when M is a diagonal matrix for (int i = 0; i < M.getNumCols(); i++) { double newValue = (1.0 / M.getEntry(i, i)); MInverse.setEntry(i, i, newValue); } L = PnSparseMatrix.multMatrices(MInverse, S, new PnSparseMatrix()); } public void calculateMandS() { calculateGandMandMv(); PnSparseMatrix GTMv = PnSparseMatrix.multMatrices(G.transposeNew(), Mv, new PnSparseMatrix()); S = PnSparseMatrix.multMatrices(GTMv, G, new PnSparseMatrix()); } /* Fills the gradient matrix G (3m by n) by all the small gradient matrices, fills the mass matrix M (n by n), and also fills the Mv (3m by 3m) matrix with triangle areas on the diagonal. */ public void calculateGandMandMv() { PiVector[] elements = m_geom.getElements(); int numOfElements = m_geom.getNumElements(); int numOfVertices = m_geom.getNumVertices(); G = new PnSparseMatrix((numOfElements * 3), numOfVertices, 3); M = new PnSparseMatrix(numOfVertices, numOfVertices, 1); Mv = new PnSparseMatrix((numOfElements * 3), (numOfElements * 3), 1); for (int i = 0; i < elements.length; i++) { PdMatrix temp = calculateElementaryGAndFillMandMv(elements[i], i); for (int j = 0; j < 3; j++) { PdVector tempColumn = temp.getColumn(j); int startPos = (i * 3); double x = tempColumn.getEntry(0); double y = tempColumn.getEntry(1); double z = tempColumn.getEntry(2); int currentVertexIndex = elements[i].getEntry(j); G.addEntry(startPos, currentVertexIndex, x); G.addEntry(startPos + 1, currentVertexIndex, y); G.addEntry(startPos + 2, currentVertexIndex, z); } } } /* Computes for every triangle the small gradient matrix (3 by 3) and fills for every triangle the Mv. */ public PdMatrix calculateElementaryGAndFillMandMv(PiVector triangle, int currentTriangleIndex) { PdVector p1 = m_geom.getVertex(triangle.getEntry(0)); PdVector p2 = m_geom.getVertex(triangle.getEntry(1)); PdVector p3 = m_geom.getVertex(triangle.getEntry(2)); // http://math.stackexchange.com/questions/305642/how-to-find-surface-normal-of-a-triangle PdVector v = PdVector.subNew(p2, p1); PdVector w = PdVector.subNew(p3, p1); double nX = (v.getEntry(1) * w.getEntry(2) - v.getEntry(2) * w.getEntry(1)); double nY = (v.getEntry(2) * w.getEntry(0) - v.getEntry(0) * w.getEntry(2)); double nZ = (v.getEntry(0) * w.getEntry(1) - v.getEntry(1) * w.getEntry(0)); PdVector n = new PdVector(nX, nY, nZ); n.normalize(); PdVector e1 = PdVector.subNew(p3, p2); PdVector e2 = PdVector.subNew(p1, p3); PdVector e3 = PdVector.subNew(p2, p1); double area = PdVector.crossNew(v, w).length() / 2; // value to be returned to build G PdMatrix triangleGradientMatrix = new PdMatrix(3); triangleGradientMatrix.setColumn(0, PdVector.crossNew(n, e1)); triangleGradientMatrix.setColumn(1, PdVector.crossNew(n, e2)); triangleGradientMatrix.setColumn(2, PdVector.crossNew(n, e3)); triangleGradientMatrix.multScalar(1d / (2 * area)); // Build the mass matrix M. double inputM1 = (area / 3) + M.getEntry(triangle.getEntry(0), triangle.getEntry(0)); M.setEntry(triangle.getEntry(0), triangle.getEntry(0), inputM1); double inputM2 = (area / 3) + M.getEntry(triangle.getEntry(1), triangle.getEntry(1)); M.setEntry(triangle.getEntry(1), triangle.getEntry(1), inputM2); double inputM3 = (area / 3) + M.getEntry(triangle.getEntry(2), triangle.getEntry(2)); M.setEntry(triangle.getEntry(2), triangle.getEntry(2), inputM3); // Filles the Mv matrix with area values. int startMv = (currentTriangleIndex * 3); Mv.addEntry(startMv, startMv, area); Mv.addEntry(startMv + 1, startMv + 1, area); Mv.addEntry(startMv + 2, startMv + 2, area); return triangleGradientMatrix; } public void reset() { m_geom.setVertices(m_geomSave.getVertices()); } }
UTF-8
Java
9,248
java
Assignment3.java
Java
[]
null
[]
package workshop; import java.awt.Color; import java.util.Arrays; import java.util.Random; import jv.geom.PgElementSet; import jv.project.PgGeometry; import jv.vecmath.PdVector; import jv.vecmath.PiVector; import jvx.project.PjWorkshop; import jv.vecmath.PdMatrix; import jv.object.PsDebug; import jvx.numeric.PnSparseMatrix; import java.util.ArrayList; import dev6.numeric.PnMumpsSolver; import jvx.numeric.PnSparseMatrix; import jv.object.PsObject; import jvx.geom.PgVertexStar; public class Assignment3 extends PjWorkshop { PgElementSet m_geom; PgElementSet m_geomSave; PnSparseMatrix G; // Gradient Matrix PnSparseMatrix M; // Mass Matrix PnSparseMatrix Mv; PnSparseMatrix S; // Stiffness Matrix PnSparseMatrix L; // Laplacian Matrix double stepwidth; PdVector newVertices_x; PdVector newVertices_y; PdVector newVertices_z; PdVector xSolved; PdVector ySolved; PdVector zSolved; public Assignment3() { super("Assignment 3"); init(); } @Override public void setGeometry(PgGeometry geom) { super.setGeometry(geom); m_geom = (PgElementSet)super.m_geom; m_geomSave = (PgElementSet)super.m_geomSave; } public void init() { super.init(); } public void iterativeAveraging(double stepwidth) throws Exception { this.stepwidth = stepwidth; // make a copy of the original model, and store the vertices in an array PgElementSet clonedGeom = (PgElementSet) m_geom.clone(); PdVector[] newVertices = (PdVector[]) clonedGeom.getVertices(); // for each vertice, find its neighbours and store them in an array PiVector[] NeighbouringVertices = PgVertexStar.makeVertexNeighbours(m_geom); int numOfVertices = m_geom.getNumVertices(); for (int i = 0; i < numOfVertices; i++) { PdVector currentVertex = m_geom.getVertex(i); PdVector tempVertex = new PdVector(0d, 0d, 0d); int numOfNeighbours = NeighbouringVertices[i].getSize(); for (int j = 0; j < numOfNeighbours; j++) { PdVector oneNeighbour = m_geom.getVertex(NeighbouringVertices[i].getEntry(j)); tempVertex.add(oneNeighbour); } // compute the average coordinate of its neighbors tempVertex.multScalar(1d / (double)numOfNeighbours); // find the difference between the average coordiante and the original one tempVertex.sub(currentVertex); // multiply with stepwidth tempVertex.multScalar(stepwidth); // calculate the new coordinates newVertices[i].add(tempVertex); } // update the model with the new vertices m_geom.setVertices(newVertices); } public void explicitMCF(double stepwidth) throws Exception { calculateLaplacianMatrix(); this.stepwidth = stepwidth; int numOfVertices = m_geom.getNumVertices(); newVertices_x = new PdVector(numOfVertices); newVertices_y = new PdVector(numOfVertices); newVertices_z = new PdVector(numOfVertices); for (int i = 0; i < numOfVertices; i++) { newVertices_x.setEntry(i, m_geom.getVertex(i).getEntry(0)); newVertices_y.setEntry(i, m_geom.getVertex(i).getEntry(1)); newVertices_z.setEntry(i, m_geom.getVertex(i).getEntry(2)); } PdVector tempNewVertices_x = PnSparseMatrix.rightMultVector(L, newVertices_x, new PdVector()); tempNewVertices_x.multScalar(stepwidth); newVertices_x.sub(tempNewVertices_x); PdVector tempNewVertices_y = PnSparseMatrix.rightMultVector(L, newVertices_y, new PdVector()); tempNewVertices_y.multScalar(stepwidth); newVertices_y.sub(tempNewVertices_y); PdVector tempNewVertices_z = PnSparseMatrix.rightMultVector(L, newVertices_z, new PdVector()); tempNewVertices_z.multScalar(stepwidth); newVertices_z.sub(tempNewVertices_z); for (int i = 0; i < numOfVertices; i++) { m_geom.setVertex(i, newVertices_x.getEntry(i), newVertices_y.getEntry(i), newVertices_z.getEntry(i)); } } public void implicitMCF(double stepwidth) throws Exception { calculateMandS(); this.stepwidth = stepwidth; int numOfVertices = m_geom.getNumVertices(); // construct A = M + tau*S PnSparseMatrix A = new PnSparseMatrix(numOfVertices, numOfVertices); A.copy(S); A.multScalar(stepwidth); A.add(M); // construct three vectors containing coordinate system specific values from every vertex PdVector x = new PdVector(numOfVertices); PdVector y = new PdVector(numOfVertices); PdVector z = new PdVector(numOfVertices); for (int i = 0; i < numOfVertices; i++) { x.setEntry(i, m_geom.getVertex(i).getEntry(0)); y.setEntry(i, m_geom.getVertex(i).getEntry(1)); z.setEntry(i, m_geom.getVertex(i).getEntry(2)); } // B = Mx (x depending on the coordinate system) PdVector Bx = PnSparseMatrix.rightMultVector(M, x, new PdVector()); PdVector By = PnSparseMatrix.rightMultVector(M, y, new PdVector()); PdVector Bz = PnSparseMatrix.rightMultVector(M, z, new PdVector()); xSolved = new PdVector(numOfVertices); ySolved = new PdVector(numOfVertices); zSolved = new PdVector(numOfVertices); long factorization = PnMumpsSolver.factor(A, PnMumpsSolver.Type.UNSYMMETRIC); PnMumpsSolver.solve(factorization, xSolved, Bx); PnMumpsSolver.solve(factorization, ySolved, By); PnMumpsSolver.solve(factorization, zSolved, Bz); for (int i = 0; i < xSolved.getSize(); i++) { m_geom.setVertex(i, xSolved.getEntry(i), ySolved.getEntry(i), zSolved.getEntry(i)); } } public void calculateLaplacianMatrix() { calculateMandS(); PnSparseMatrix MInverse = new PnSparseMatrix(M.getNumRows(), M.getNumCols(), 1); //calculate M-inverse // N.B.: this method can only be used when M is a diagonal matrix for (int i = 0; i < M.getNumCols(); i++) { double newValue = (1.0 / M.getEntry(i, i)); MInverse.setEntry(i, i, newValue); } L = PnSparseMatrix.multMatrices(MInverse, S, new PnSparseMatrix()); } public void calculateMandS() { calculateGandMandMv(); PnSparseMatrix GTMv = PnSparseMatrix.multMatrices(G.transposeNew(), Mv, new PnSparseMatrix()); S = PnSparseMatrix.multMatrices(GTMv, G, new PnSparseMatrix()); } /* Fills the gradient matrix G (3m by n) by all the small gradient matrices, fills the mass matrix M (n by n), and also fills the Mv (3m by 3m) matrix with triangle areas on the diagonal. */ public void calculateGandMandMv() { PiVector[] elements = m_geom.getElements(); int numOfElements = m_geom.getNumElements(); int numOfVertices = m_geom.getNumVertices(); G = new PnSparseMatrix((numOfElements * 3), numOfVertices, 3); M = new PnSparseMatrix(numOfVertices, numOfVertices, 1); Mv = new PnSparseMatrix((numOfElements * 3), (numOfElements * 3), 1); for (int i = 0; i < elements.length; i++) { PdMatrix temp = calculateElementaryGAndFillMandMv(elements[i], i); for (int j = 0; j < 3; j++) { PdVector tempColumn = temp.getColumn(j); int startPos = (i * 3); double x = tempColumn.getEntry(0); double y = tempColumn.getEntry(1); double z = tempColumn.getEntry(2); int currentVertexIndex = elements[i].getEntry(j); G.addEntry(startPos, currentVertexIndex, x); G.addEntry(startPos + 1, currentVertexIndex, y); G.addEntry(startPos + 2, currentVertexIndex, z); } } } /* Computes for every triangle the small gradient matrix (3 by 3) and fills for every triangle the Mv. */ public PdMatrix calculateElementaryGAndFillMandMv(PiVector triangle, int currentTriangleIndex) { PdVector p1 = m_geom.getVertex(triangle.getEntry(0)); PdVector p2 = m_geom.getVertex(triangle.getEntry(1)); PdVector p3 = m_geom.getVertex(triangle.getEntry(2)); // http://math.stackexchange.com/questions/305642/how-to-find-surface-normal-of-a-triangle PdVector v = PdVector.subNew(p2, p1); PdVector w = PdVector.subNew(p3, p1); double nX = (v.getEntry(1) * w.getEntry(2) - v.getEntry(2) * w.getEntry(1)); double nY = (v.getEntry(2) * w.getEntry(0) - v.getEntry(0) * w.getEntry(2)); double nZ = (v.getEntry(0) * w.getEntry(1) - v.getEntry(1) * w.getEntry(0)); PdVector n = new PdVector(nX, nY, nZ); n.normalize(); PdVector e1 = PdVector.subNew(p3, p2); PdVector e2 = PdVector.subNew(p1, p3); PdVector e3 = PdVector.subNew(p2, p1); double area = PdVector.crossNew(v, w).length() / 2; // value to be returned to build G PdMatrix triangleGradientMatrix = new PdMatrix(3); triangleGradientMatrix.setColumn(0, PdVector.crossNew(n, e1)); triangleGradientMatrix.setColumn(1, PdVector.crossNew(n, e2)); triangleGradientMatrix.setColumn(2, PdVector.crossNew(n, e3)); triangleGradientMatrix.multScalar(1d / (2 * area)); // Build the mass matrix M. double inputM1 = (area / 3) + M.getEntry(triangle.getEntry(0), triangle.getEntry(0)); M.setEntry(triangle.getEntry(0), triangle.getEntry(0), inputM1); double inputM2 = (area / 3) + M.getEntry(triangle.getEntry(1), triangle.getEntry(1)); M.setEntry(triangle.getEntry(1), triangle.getEntry(1), inputM2); double inputM3 = (area / 3) + M.getEntry(triangle.getEntry(2), triangle.getEntry(2)); M.setEntry(triangle.getEntry(2), triangle.getEntry(2), inputM3); // Filles the Mv matrix with area values. int startMv = (currentTriangleIndex * 3); Mv.addEntry(startMv, startMv, area); Mv.addEntry(startMv + 1, startMv + 1, area); Mv.addEntry(startMv + 2, startMv + 2, area); return triangleGradientMatrix; } public void reset() { m_geom.setVertices(m_geomSave.getVertices()); } }
9,248
0.721886
0.709234
257
34.988327
26.360636
104
false
false
0
0
0
0
0
0
2.579767
false
false
10
e7b6c91cff115b65a408a277464fb504f09fa09c
36,515,811,954,417
9a11de2a95155cfa24213f7c79896d3444e9049c
/src/teste/EspecialidadeTeste.java
a6e1052e4a253d4800f64cc35ffda0f1ea542b3b
[ "MIT" ]
permissive
aldaypinheiro/maternidade-core
https://github.com/aldaypinheiro/maternidade-core
7df8fef551c6b50a59c4a73639cbfc01ae314dad
1b8e336b964b08dd0ff53869c1b1b1289c84567c
refs/heads/master
2020-05-18T10:03:22.937000
2015-05-09T14:19:53
2015-05-09T14:19:53
14,987,505
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package teste; import br.edu.fjn.maternidade.application.impl.EspecialidadeApplicationImpl; import br.edu.fjn.maternidade.domain.especialidade.Especialidade; public class EspecialidadeTeste { public static void mainas(String[] args) { EspecialidadeApplicationImpl ea = new EspecialidadeApplicationImpl(); Especialidade esp1 = new Especialidade("Obstetra", "Especialidade em acompanhar a gravidez e realizar os partos."); Especialidade esp2 = new Especialidade("Anestesista", "Especialidade em vigiar e manter equilibrado o organismo do paciente."); Especialidade esp3 = new Especialidade("Ginecologista", "Especialidade no sistema reprodutor feminino, รบtero, vagina e ovรกrios."); ea.inserir(esp1); ea.inserir(esp2); ea.inserir(esp3); } }
UTF-8
Java
768
java
EspecialidadeTeste.java
Java
[]
null
[]
package teste; import br.edu.fjn.maternidade.application.impl.EspecialidadeApplicationImpl; import br.edu.fjn.maternidade.domain.especialidade.Especialidade; public class EspecialidadeTeste { public static void mainas(String[] args) { EspecialidadeApplicationImpl ea = new EspecialidadeApplicationImpl(); Especialidade esp1 = new Especialidade("Obstetra", "Especialidade em acompanhar a gravidez e realizar os partos."); Especialidade esp2 = new Especialidade("Anestesista", "Especialidade em vigiar e manter equilibrado o organismo do paciente."); Especialidade esp3 = new Especialidade("Ginecologista", "Especialidade no sistema reprodutor feminino, รบtero, vagina e ovรกrios."); ea.inserir(esp1); ea.inserir(esp2); ea.inserir(esp3); } }
768
0.780679
0.772846
20
37.25
44.314644
132
false
false
0
0
0
0
0
0
1.8
false
false
10
aff7382dfedc9cb7dea3a91a15d51c230867febd
18,829,136,686,604
c121e33afb40a429e81bd161d130ff9ba5d5287c
/tutorial/src/main/java/com/ss/dao/impl/SubjectDAOImpl.java
b6310e6d30a038c70148e2c07fead425dcdafd29
[]
no_license
surbhissaxena/vivek_tutorial
https://github.com/surbhissaxena/vivek_tutorial
37a0e11297bd9ad58b8dabfabb3c4b2c718626f7
f0a9540f458bd8f2a8e2509e8a7566f8db1eb377
refs/heads/master
2020-03-29T12:34:15.417000
2018-09-22T18:51:33
2018-09-22T18:51:33
149,906,424
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.ss.dao.impl; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import com.ss.dao.SubjectDAO; import com.ss.dto.SubjectDTO; import com.ss.dto.UserDTO; import com.ss.util.DBResponse; import com.ss.util.JDBCUtil; import com.ss.util.Message; import com.ss.util.OpCode; import com.ss.vo.SubjectVO; public class SubjectDAOImpl implements SubjectDAO{ @Override public DBResponse addSubject(SubjectDTO dto) throws Exception { DBResponse dbResponse = new DBResponse(); Connection con = null; PreparedStatement st = null; try { con = JDBCUtil.getInstance().getConnection(); con.setAutoCommit(false); String query = "insert into subject_table (sub_name) values(?)"; st = con.prepareStatement(query); st.setString(1, dto.getSub_name()); int i = st.executeUpdate(); if (i != 0 ) { dbResponse.setOperationCode(OpCode.SUCCESS); dbResponse.setMessage(Message.RECORD_SUCCESSFULLY_SAVED); } else { dbResponse.setOperationCode(OpCode.FAIL); dbResponse.setMessage(Message.RECORD_NOT_SAVED); } con.commit(); } catch (Exception e) { e.printStackTrace(); // con.rollback(); dbResponse.setOperationCode(OpCode.EXECPTION); dbResponse.setMessage(Message.SOMETHING_WENT_WRONG); } finally { if (con != null) { st.close(); con.close(); } } return dbResponse; } @Override public DBResponse getAllSubject() throws Exception { Map<String, List<Object>> map = new HashMap<String, List<Object>>(); List<Object> userDTOList = new ArrayList<Object>(); DBResponse dbRespons = new DBResponse(); Connection con = null; PreparedStatement st = null; try { con = JDBCUtil.getInstance().getConnection(); String q = "SELECT * FROM subject_table order by sub_name"; st = con.prepareStatement(q); ResultSet rs = st.executeQuery(); while (rs.next()) { SubjectVO vo = new SubjectVO(); vo.setSub_id(rs.getInt("sub_id")); vo.setSub_name(rs.getString("sub_name")); userDTOList.add(vo); } System.out.println(userDTOList.isEmpty()); if (!userDTOList.isEmpty()) { map.put("UserList", userDTOList); dbRespons.setOperationCode(OpCode.SUCCESS); dbRespons.setDataAvailable(true); dbRespons.setData(map); dbRespons.setMessage(Message.RECORD_FOUND); } else { dbRespons.setOperationCode(OpCode.FAIL); dbRespons.setMessage(Message.RECORD_NOT_FOUND); } } catch (Exception e) { e.printStackTrace(); dbRespons.setOperationCode(OpCode.EXECPTION); dbRespons.setMessage(Message.SOMETHING_WENT_WRONG); } finally { try { if (con != null) { con.close(); } } catch (Exception e) { } } return dbRespons; } @Override public SubjectVO getSubjectBySubjectId(int sub_id, Connection con)throws Exception{ PreparedStatement st = null; SubjectVO vo = null; String q = "SELECT * FROM subject_table where sub_id = ?"; st = con.prepareStatement(q); st.setInt(1, sub_id); ResultSet rs = st.executeQuery(); while (rs.next()) { vo = new SubjectVO(); vo.setSub_id(rs.getInt("sub_id")); vo.setSub_name(rs.getString("sub_name")); } return vo; } }
UTF-8
Java
3,276
java
SubjectDAOImpl.java
Java
[]
null
[]
package com.ss.dao.impl; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import com.ss.dao.SubjectDAO; import com.ss.dto.SubjectDTO; import com.ss.dto.UserDTO; import com.ss.util.DBResponse; import com.ss.util.JDBCUtil; import com.ss.util.Message; import com.ss.util.OpCode; import com.ss.vo.SubjectVO; public class SubjectDAOImpl implements SubjectDAO{ @Override public DBResponse addSubject(SubjectDTO dto) throws Exception { DBResponse dbResponse = new DBResponse(); Connection con = null; PreparedStatement st = null; try { con = JDBCUtil.getInstance().getConnection(); con.setAutoCommit(false); String query = "insert into subject_table (sub_name) values(?)"; st = con.prepareStatement(query); st.setString(1, dto.getSub_name()); int i = st.executeUpdate(); if (i != 0 ) { dbResponse.setOperationCode(OpCode.SUCCESS); dbResponse.setMessage(Message.RECORD_SUCCESSFULLY_SAVED); } else { dbResponse.setOperationCode(OpCode.FAIL); dbResponse.setMessage(Message.RECORD_NOT_SAVED); } con.commit(); } catch (Exception e) { e.printStackTrace(); // con.rollback(); dbResponse.setOperationCode(OpCode.EXECPTION); dbResponse.setMessage(Message.SOMETHING_WENT_WRONG); } finally { if (con != null) { st.close(); con.close(); } } return dbResponse; } @Override public DBResponse getAllSubject() throws Exception { Map<String, List<Object>> map = new HashMap<String, List<Object>>(); List<Object> userDTOList = new ArrayList<Object>(); DBResponse dbRespons = new DBResponse(); Connection con = null; PreparedStatement st = null; try { con = JDBCUtil.getInstance().getConnection(); String q = "SELECT * FROM subject_table order by sub_name"; st = con.prepareStatement(q); ResultSet rs = st.executeQuery(); while (rs.next()) { SubjectVO vo = new SubjectVO(); vo.setSub_id(rs.getInt("sub_id")); vo.setSub_name(rs.getString("sub_name")); userDTOList.add(vo); } System.out.println(userDTOList.isEmpty()); if (!userDTOList.isEmpty()) { map.put("UserList", userDTOList); dbRespons.setOperationCode(OpCode.SUCCESS); dbRespons.setDataAvailable(true); dbRespons.setData(map); dbRespons.setMessage(Message.RECORD_FOUND); } else { dbRespons.setOperationCode(OpCode.FAIL); dbRespons.setMessage(Message.RECORD_NOT_FOUND); } } catch (Exception e) { e.printStackTrace(); dbRespons.setOperationCode(OpCode.EXECPTION); dbRespons.setMessage(Message.SOMETHING_WENT_WRONG); } finally { try { if (con != null) { con.close(); } } catch (Exception e) { } } return dbRespons; } @Override public SubjectVO getSubjectBySubjectId(int sub_id, Connection con)throws Exception{ PreparedStatement st = null; SubjectVO vo = null; String q = "SELECT * FROM subject_table where sub_id = ?"; st = con.prepareStatement(q); st.setInt(1, sub_id); ResultSet rs = st.executeQuery(); while (rs.next()) { vo = new SubjectVO(); vo.setSub_id(rs.getInt("sub_id")); vo.setSub_name(rs.getString("sub_name")); } return vo; } }
3,276
0.692002
0.691087
122
25.852459
18.808208
84
false
false
0
0
0
0
0
0
2.704918
false
false
10
ec7cf53e0a970398c6d26bad983878841826a0e8
36,249,523,986,729
1595cd5416698f85fd01f499d21778d43bb91cb8
/src/main/java/topThreeComments/TopThreeCommentsMapper.java
e3d5b21e2f88d82a4b18ffea38710f3c1fceed71
[]
no_license
gudbrandsc/Social-Network-Analysis-with-MapReduce
https://github.com/gudbrandsc/Social-Network-Analysis-with-MapReduce
a939b5b1d63122dbad016d2850c54cbaf9a43960
f4517b44fb54fc46de6120bd655aa5602f6e7430
refs/heads/master
2020-04-15T11:51:17.489000
2019-01-08T12:52:37
2019-01-08T12:52:37
164,642,011
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package topThreeComments; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Mapper; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; public class TopThreeCommentsMapper extends Mapper<LongWritable, Text, Text, UserCommentWritable> { @Override protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException { // tokenize into words. JSONObject obj = new JSONObject(value.toString()); String author1 = "JonAudette"; String currAuthor = obj.getString("author"); if(currAuthor.equals(author1)) { int upVotes = obj.getInt("ups"); String body = obj.getString("body"); UserCommentWritable userCommentWritable = new UserCommentWritable(body, upVotes); try { context.write(new Text(currAuthor), userCommentWritable); } catch (JSONException e) { e.printStackTrace(); } } } }
UTF-8
Java
1,092
java
TopThreeCommentsMapper.java
Java
[ { "context": "ject(value.toString());\n String author1 = \"JonAudette\";\n String currAuthor = obj.getString(\"auth", "end": 603, "score": 0.9982284307479858, "start": 593, "tag": "USERNAME", "value": "JonAudette" } ]
null
[]
package topThreeComments; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Mapper; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; public class TopThreeCommentsMapper extends Mapper<LongWritable, Text, Text, UserCommentWritable> { @Override protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException { // tokenize into words. JSONObject obj = new JSONObject(value.toString()); String author1 = "JonAudette"; String currAuthor = obj.getString("author"); if(currAuthor.equals(author1)) { int upVotes = obj.getInt("ups"); String body = obj.getString("body"); UserCommentWritable userCommentWritable = new UserCommentWritable(body, upVotes); try { context.write(new Text(currAuthor), userCommentWritable); } catch (JSONException e) { e.printStackTrace(); } } } }
1,092
0.659341
0.657509
35
30.200001
26.680973
99
false
false
0
0
0
0
0
0
0.657143
false
false
10
79bf0dfac23883e77768f9b3a36f076c34f7d5bc
1,709,397,052,700
2f298f40f59781d552d88106f2e6bb40ec23d35c
/lib-http/src/main/java/cn/carhouse/http/callback/OkFileCallback.java
e86a336a835db74bad95493068300363a5f82bf2
[]
no_license
DapengLee/http_okhttp_DAPENG
https://github.com/DapengLee/http_okhttp_DAPENG
81f9a248076072304a64ff492038e35b709b88b4
fdb2a323995c649b6bd3a1b574a76bc881888917
refs/heads/master
2023-03-15T19:11:56.626000
2020-04-24T06:46:43
2020-04-24T06:46:43
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package cn.carhouse.http.callback; import android.content.Context; import android.os.Handler; import android.os.Looper; import java.io.Closeable; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import cn.carhouse.http.core.ICallback; import cn.carhouse.http.core.RequestParams; import cn.carhouse.http.util.NetFileUtil; import okhttp3.Call; import okhttp3.Callback; import okhttp3.Response; /** * ๆ–‡ไปถไธ‹่ฝฝ็š„ๅ›ž่ฐƒ */ public class OkFileCallback implements Callback { private Handler mHandler = new Handler(Looper.getMainLooper()); private String mFileName; private ICallback mCallback; private Context mContext; private String mFileDir; public OkFileCallback(RequestParams params) { this.mContext = params.getContext(); this.mCallback = params.getCallback(); this.mFileName = params.getFileName(); this.mFileDir = params.getFileDir(); } @Override public void onFailure(Call call, IOException e) { if (mCallback != null) { mCallback.onError(e); mCallback.onAfter(); } } @Override public void onResponse(Call call, Response response) throws IOException { InputStream is = null; byte[] buf = new byte[1024 * 1024]; int len = -1; FileOutputStream fos = null; try { is = response.body().byteStream(); final long total = response.body().contentLength(); long sum = 0; NetFileUtil.init(mContext); File dir = NetFileUtil.createCacheDir(mFileDir); final File file = new File(dir, mFileName); fos = new FileOutputStream(file); while ((len = is.read(buf)) != -1) { sum += len; fos.write(buf, 0, len); final long finalSum = sum; mHandler.post(new Runnable() { @Override public void run() { mCallback.onProgress(finalSum * 100f / total, finalSum, total); } }); } fos.flush(); mHandler.post(new Runnable() { @Override public void run() { mCallback.onSucceed(file); } }); } catch (Exception e) { e.printStackTrace(); } finally { close(is); close(fos); } mHandler.post(new Runnable() { @Override public void run() { mCallback.onAfter(); } }); } private void close(Closeable closeable) { try { if (closeable != null) { closeable.close(); } } catch (Exception e) { } } }
UTF-8
Java
2,874
java
OkFileCallback.java
Java
[]
null
[]
package cn.carhouse.http.callback; import android.content.Context; import android.os.Handler; import android.os.Looper; import java.io.Closeable; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import cn.carhouse.http.core.ICallback; import cn.carhouse.http.core.RequestParams; import cn.carhouse.http.util.NetFileUtil; import okhttp3.Call; import okhttp3.Callback; import okhttp3.Response; /** * ๆ–‡ไปถไธ‹่ฝฝ็š„ๅ›ž่ฐƒ */ public class OkFileCallback implements Callback { private Handler mHandler = new Handler(Looper.getMainLooper()); private String mFileName; private ICallback mCallback; private Context mContext; private String mFileDir; public OkFileCallback(RequestParams params) { this.mContext = params.getContext(); this.mCallback = params.getCallback(); this.mFileName = params.getFileName(); this.mFileDir = params.getFileDir(); } @Override public void onFailure(Call call, IOException e) { if (mCallback != null) { mCallback.onError(e); mCallback.onAfter(); } } @Override public void onResponse(Call call, Response response) throws IOException { InputStream is = null; byte[] buf = new byte[1024 * 1024]; int len = -1; FileOutputStream fos = null; try { is = response.body().byteStream(); final long total = response.body().contentLength(); long sum = 0; NetFileUtil.init(mContext); File dir = NetFileUtil.createCacheDir(mFileDir); final File file = new File(dir, mFileName); fos = new FileOutputStream(file); while ((len = is.read(buf)) != -1) { sum += len; fos.write(buf, 0, len); final long finalSum = sum; mHandler.post(new Runnable() { @Override public void run() { mCallback.onProgress(finalSum * 100f / total, finalSum, total); } }); } fos.flush(); mHandler.post(new Runnable() { @Override public void run() { mCallback.onSucceed(file); } }); } catch (Exception e) { e.printStackTrace(); } finally { close(is); close(fos); } mHandler.post(new Runnable() { @Override public void run() { mCallback.onAfter(); } }); } private void close(Closeable closeable) { try { if (closeable != null) { closeable.close(); } } catch (Exception e) { } } }
2,874
0.548252
0.541958
102
27.039215
18.228893
87
false
false
0
0
0
0
0
0
0.568627
false
false
10
b826653d8b3d1c95dd123521d0eeb7ee06d27452
37,022,618,130,589
e51de484e96efdf743a742de1e91bce67f555f99
/Android/triviacrack_src/src/com/etermax/gamescommon/j/d.java
dc0192f6361cd3af219503afba2862b5642090e8
[]
no_license
adumbgreen/TriviaCrap
https://github.com/adumbgreen/TriviaCrap
b21e220e875f417c9939f192f763b1dcbb716c69
beed6340ec5a1611caeff86918f107ed6807d751
refs/heads/master
2021-03-27T19:24:22.401000
2015-07-12T01:28:39
2015-07-12T01:28:39
28,071,899
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
// Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov. // Jad home page: http://www.geocities.com/kpdus/jad.html // Decompiler options: braces fieldsfirst space lnc package com.etermax.gamescommon.j; import android.content.Context; import android.content.DialogInterface; import android.os.Bundle; import com.etermax.k; import com.etermax.o; import com.etermax.tools.widget.b.a; import com.etermax.tools.widget.b.b; // Referenced classes of package com.etermax.gamescommon.j: // c public class d extends a implements b { private static c a; public d() { setTargetFragment(this, 0); } public static d a(Context context, String s, String s1, c c1) { a = c1; d d1 = new d(); String s2; if (s1 == null) { s2 = context.getString(o.are_you_sure_facebook_link_guest_account); } else { s2 = String.format(context.getString(o.facebook_already_link_mail), new Object[] { s, s1 }); } d1.setArguments(b(s2, context.getString(o.accept), context.getString(o.cancel))); return d1; } public void a(Bundle bundle) { if (a != null) { a.d.d(); a.e(); a = null; } } protected int b() { return k.link_choose_dialog; } public void onAccept(Bundle bundle) { if (a != null) { com.etermax.gamescommon.j.c.a(a, getActivity(), false); a = null; } } public void onCancel(DialogInterface dialoginterface) { super.onCancel(dialoginterface); if (a != null) { a.d.d(); a.e(); a = null; } } }
UTF-8
Java
1,795
java
d.java
Java
[ { "context": "// Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov.\n// Jad home page: http://www.geocities.com/kpdus", "end": 61, "score": 0.9996473789215088, "start": 45, "tag": "NAME", "value": "Pavel Kouznetsov" } ]
null
[]
// Decompiled by Jad v1.5.8e. Copyright 2001 <NAME>. // Jad home page: http://www.geocities.com/kpdus/jad.html // Decompiler options: braces fieldsfirst space lnc package com.etermax.gamescommon.j; import android.content.Context; import android.content.DialogInterface; import android.os.Bundle; import com.etermax.k; import com.etermax.o; import com.etermax.tools.widget.b.a; import com.etermax.tools.widget.b.b; // Referenced classes of package com.etermax.gamescommon.j: // c public class d extends a implements b { private static c a; public d() { setTargetFragment(this, 0); } public static d a(Context context, String s, String s1, c c1) { a = c1; d d1 = new d(); String s2; if (s1 == null) { s2 = context.getString(o.are_you_sure_facebook_link_guest_account); } else { s2 = String.format(context.getString(o.facebook_already_link_mail), new Object[] { s, s1 }); } d1.setArguments(b(s2, context.getString(o.accept), context.getString(o.cancel))); return d1; } public void a(Bundle bundle) { if (a != null) { a.d.d(); a.e(); a = null; } } protected int b() { return k.link_choose_dialog; } public void onAccept(Bundle bundle) { if (a != null) { com.etermax.gamescommon.j.c.a(a, getActivity(), false); a = null; } } public void onCancel(DialogInterface dialoginterface) { super.onCancel(dialoginterface); if (a != null) { a.d.d(); a.e(); a = null; } } }
1,785
0.544847
0.533705
81
21.160494
21.269266
94
false
false
0
0
0
0
0
0
0.45679
false
false
10
d444c3af325c95a8e127d488a8064429f00233ee
35,527,969,518,744
0d0ac7a879df394088560b5a4cf2a4572ffb72ff
/JGame.java
cc9033bc5741ae60231ca1c1194dc844d139feb9
[]
no_license
philly-phyre/JGame
https://github.com/philly-phyre/JGame
a75c934662e9ae82351b91001a20432f9a45f17c
d430abaadfb5b8cc3682e3230175ad6d39f1836b
refs/heads/master
2021-01-10T05:36:00.864000
2015-12-07T16:09:53
2015-12-07T16:09:53
46,933,070
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.util.Arrays; import java.util.List; public class JGame { public static List<String> options = Arrays.asList("FIGHT","TRAVEL","ITEMS","STATS","SAVE","QUIT"); public static void main(String[] args) { sect("Welcome to KUSHTOPIA, where danger and adventure lurk around every threshold.", "Let's start by getting to know you a little better."); User.Player.Init(); // All user info is now initialized and stored in enums/classes // sleep(3000); sect("AMAZING! We're done getting to know each other.", "Now here are your general stats before we start telling your story."); pl("\t\t**********************************\n"); User.putStats(); pl("\t\t**********************************\n\n"); sleep(4000); sub("Now let's jump into the STORY, then. "); boolean ready = false; boolean running = true; while(!ready){ pl("\t Are you ready? >>> \t ? "); ready = TextIO.getlnBoolean(); while(!ready){ pl("Okie dokie; take your time, 'TRAVELLER'... \n"); sleep(3500); p("Ready yet? >>> \t ?"); ready = TextIO.getlnBoolean(); } } pl("\t . . . . ."); sleep(1100); pl("\t . . . ."); sleep(1100); pl("\t . . ."); sleep(1100); pl("\t . ."); sleep(1100); pl("\t !"); sleep(1700); sect("Many eons ago, the land that we know as KUSHTOPIA was as lush as could be.", "From the multitude of plant and animal species to the crops and citizens, no other \n" + "\t\t > region could come close to providing the same quality of life..."); sleep(5700); sub("When the KING was in good favors, all of his loyal constituents were blessed with his kindness.", "The KING was generally a giving man, but he would be known to be selfish from time to time.", "Of course, being the KING, his business was publicized far past the extent that he could comprehend."); sleep(5700); sect("One swarthy day, when the sky looked as though she were ready to release darkness itself, \n" + "\t\t > a band of guileful BASTION - one of the only known groups to date - razed the village \n" + "\t\t > in the dead of night."); sleep(5700); sub("...", "The group pillaged every house and store in the village surrounding the castle.", "They made a quick pull through the village and a B-line toward the castle; where the king slept, \n" + " \t\t > unaware of the terror that had befell his beloved KINGDOM."); sleep(5700); // I REALLY don't want to write more story lol /* GAME LOOP */ GAME: while(running){ sub("What would you do, " + User.Player.TITLE.desc + "?", "FIGHT \t TRAVEL", "ITEMS \t STATS", "SAVE \t QUIT"); String input = TextIO.getlnWord().toUpperCase(); if(options.contains(input)){ switch(input){ case "FIGHT": Battle.battle(); break; case "STATS": User.putStats(); break; case "QUIT": sect("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~", "############################################", "THANK YOU FOR CHOOSING KUSHTOPIA BY TEMPEST DESIGN STUDIOS 2015", "############################################", "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"); sleep(3000); sub("Please play this game as often as you would like!!", "The source code can be found online at 'https://github.com/philly-phyre/KUSHTOPIA.git' .", "Also feel free to take a look at it whenever and contact me about changes/commits or ideas!!", ""); Quit(); break; default: sub("Oops; try again, " + User.Player.TITLE.desc); } } else if(!(options.contains(input))) { pl("Please enter a valid option!"); sleep(2500); } // end if/else // continue GAME; } // end GAME loop // Quit(); }// end main() // public static void lost(){ sect("It appears that you have lost your life in battle...", "Your GUARDIAN takes your vulnerable body from the scene and partially revives you.", "HEALTH: " + (int)(User.OHEALTH/3)); User.HEALTH = (int)(User.OHEALTH/3); sleep(3200); sub("Continue on your journey, but be wary of the dangers native to this land..."); } // end lost() // public static void Quit(){ System.exit(0); } // end Quit() // public static void sleep(int x){ try{ Thread.sleep(x); } catch (InterruptedException e){ Thread.currentThread().interrupt(); } } // end sleep() // // TextIO shortened routines // public static void pl(String x) { TextIO.putln(x); } // end pl() // public static void p(String y) { TextIO.put(y); } // end p() // public static void pf(String z) { TextIO.putf(z); } // end pf() // public static void sect(String...str) { pl(" > > ********************************************************************** < < \n"); for(String x : str) { pl("\t" + x + "\n"); } } public static void sub(String...str) { pl("\t\t**********************************\n"); for(String x : str) { pl("\t" + x + "\n"); } } // thread sleep // }
UTF-8
Java
4,983
java
JGame.java
Java
[ { "context": "e code can be found online at 'https://github.com/philly-phyre/KUSHTOPIA.git' .\",\n\t\t\t\t\t\t\"Also feel free to take ", "end": 3317, "score": 0.9983026385307312, "start": 3305, "tag": "USERNAME", "value": "philly-phyre" } ]
null
[]
import java.util.Arrays; import java.util.List; public class JGame { public static List<String> options = Arrays.asList("FIGHT","TRAVEL","ITEMS","STATS","SAVE","QUIT"); public static void main(String[] args) { sect("Welcome to KUSHTOPIA, where danger and adventure lurk around every threshold.", "Let's start by getting to know you a little better."); User.Player.Init(); // All user info is now initialized and stored in enums/classes // sleep(3000); sect("AMAZING! We're done getting to know each other.", "Now here are your general stats before we start telling your story."); pl("\t\t**********************************\n"); User.putStats(); pl("\t\t**********************************\n\n"); sleep(4000); sub("Now let's jump into the STORY, then. "); boolean ready = false; boolean running = true; while(!ready){ pl("\t Are you ready? >>> \t ? "); ready = TextIO.getlnBoolean(); while(!ready){ pl("Okie dokie; take your time, 'TRAVELLER'... \n"); sleep(3500); p("Ready yet? >>> \t ?"); ready = TextIO.getlnBoolean(); } } pl("\t . . . . ."); sleep(1100); pl("\t . . . ."); sleep(1100); pl("\t . . ."); sleep(1100); pl("\t . ."); sleep(1100); pl("\t !"); sleep(1700); sect("Many eons ago, the land that we know as KUSHTOPIA was as lush as could be.", "From the multitude of plant and animal species to the crops and citizens, no other \n" + "\t\t > region could come close to providing the same quality of life..."); sleep(5700); sub("When the KING was in good favors, all of his loyal constituents were blessed with his kindness.", "The KING was generally a giving man, but he would be known to be selfish from time to time.", "Of course, being the KING, his business was publicized far past the extent that he could comprehend."); sleep(5700); sect("One swarthy day, when the sky looked as though she were ready to release darkness itself, \n" + "\t\t > a band of guileful BASTION - one of the only known groups to date - razed the village \n" + "\t\t > in the dead of night."); sleep(5700); sub("...", "The group pillaged every house and store in the village surrounding the castle.", "They made a quick pull through the village and a B-line toward the castle; where the king slept, \n" + " \t\t > unaware of the terror that had befell his beloved KINGDOM."); sleep(5700); // I REALLY don't want to write more story lol /* GAME LOOP */ GAME: while(running){ sub("What would you do, " + User.Player.TITLE.desc + "?", "FIGHT \t TRAVEL", "ITEMS \t STATS", "SAVE \t QUIT"); String input = TextIO.getlnWord().toUpperCase(); if(options.contains(input)){ switch(input){ case "FIGHT": Battle.battle(); break; case "STATS": User.putStats(); break; case "QUIT": sect("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~", "############################################", "THANK YOU FOR CHOOSING KUSHTOPIA BY TEMPEST DESIGN STUDIOS 2015", "############################################", "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"); sleep(3000); sub("Please play this game as often as you would like!!", "The source code can be found online at 'https://github.com/philly-phyre/KUSHTOPIA.git' .", "Also feel free to take a look at it whenever and contact me about changes/commits or ideas!!", ""); Quit(); break; default: sub("Oops; try again, " + User.Player.TITLE.desc); } } else if(!(options.contains(input))) { pl("Please enter a valid option!"); sleep(2500); } // end if/else // continue GAME; } // end GAME loop // Quit(); }// end main() // public static void lost(){ sect("It appears that you have lost your life in battle...", "Your GUARDIAN takes your vulnerable body from the scene and partially revives you.", "HEALTH: " + (int)(User.OHEALTH/3)); User.HEALTH = (int)(User.OHEALTH/3); sleep(3200); sub("Continue on your journey, but be wary of the dangers native to this land..."); } // end lost() // public static void Quit(){ System.exit(0); } // end Quit() // public static void sleep(int x){ try{ Thread.sleep(x); } catch (InterruptedException e){ Thread.currentThread().interrupt(); } } // end sleep() // // TextIO shortened routines // public static void pl(String x) { TextIO.putln(x); } // end pl() // public static void p(String y) { TextIO.put(y); } // end p() // public static void pf(String z) { TextIO.putf(z); } // end pf() // public static void sect(String...str) { pl(" > > ********************************************************************** < < \n"); for(String x : str) { pl("\t" + x + "\n"); } } public static void sub(String...str) { pl("\t\t**********************************\n"); for(String x : str) { pl("\t" + x + "\n"); } } // thread sleep // }
4,983
0.57054
0.557094
155
31.148388
29.527636
108
false
false
0
0
0
0
0
0
3.206452
false
false
10
2e8b9417d6eb4b063b2fa0744ca7fc56372db4c9
39,178,691,707,111
b2d1ef7ab684306085b689e7e836d82740b44d24
/project-two-dating-app/LooseCoupling/src/main/java/com/revature/data/MessagesDAO.java
47aeb29ca2ebdadd338f48bfce3fabf3cef9b864
[]
no_license
noahgabethomas/NOAHSREPOSITORY
https://github.com/noahgabethomas/NOAHSREPOSITORY
804cd6e72206b7d2994bfbe4bc1a09f137e47a7b
1946de1ca8bf1c5266f461553bb78e563ae545dd
refs/heads/master
2023-01-10T13:21:34.798000
2020-03-12T00:20:50
2020-03-12T00:20:50
246,707,948
0
0
null
false
2023-01-07T15:50:56
2020-03-12T00:25:52
2020-03-12T00:26:12
2023-01-07T15:50:56
3,441
0
0
25
Java
false
false
package com.revature.data; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import com.revature.beans.Messages; @Repository public interface MessagesDAO extends JpaRepository<Messages, Integer>{}
UTF-8
Java
262
java
MessagesDAO.java
Java
[]
null
[]
package com.revature.data; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import com.revature.beans.Messages; @Repository public interface MessagesDAO extends JpaRepository<Messages, Integer>{}
262
0.843511
0.843511
9
28.111111
25.976248
71
false
false
0
0
0
0
0
0
0.555556
false
false
10
fa12026cb92edccdb8d30a92875ea3732b7cd1d1
39,771,397,161,067
af6952a4634a03c93941063733dcd235fe1d4032
/Flooring/src/main/java/com/sg/flooring/service/FlooringServiceLayer.java
bf5ab73d94e305f54ebc41091e69e87223440c13
[]
no_license
DavidJoshuaK/Flooring
https://github.com/DavidJoshuaK/Flooring
f4f4974df1539560ec0967e55e79299032785d0f
8ad163d4394aaa3a0e8d9ca19718ee06e55aaa25
refs/heads/master
2021-09-03T05:20:18.099000
2018-01-05T23:06:05
2018-01-05T23:06:05
116,432,884
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.sg.flooring.service; import com.sg.flooring.dao.FlooringDaoPersistenceException; import com.sg.flooring.dto.Order; import com.sg.flooring.dto.Product; import com.sg.flooring.dto.Tax; import java.math.BigDecimal; import java.time.LocalDate; import java.util.List; /** * * @author apprentice */ public interface FlooringServiceLayer { Order calculateNewOrderDataInput(Order order) throws FlooringValidationException; void addOrder(Order order); List<Order> getAllOrders(); Order getOrder(Integer orderNumber); List<Order> getOrdersByDate(LocalDate date) throws FlooringValidationException; Order removeOrder(Integer orderNumber); void loadFiles() throws FlooringDaoPersistenceException; void writeOrders() throws FlooringDaoPersistenceException; Order setOrderId(Order order); boolean checkMode() throws FlooringDaoPersistenceException; }
UTF-8
Java
1,099
java
FlooringServiceLayer.java
Java
[ { "context": "calDate;\nimport java.util.List;\n\n/**\n *\n * @author apprentice\n */\npublic interface FlooringServiceLayer {\n\n O", "end": 490, "score": 0.9994826912879944, "start": 480, "tag": "USERNAME", "value": "apprentice" } ]
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.sg.flooring.service; import com.sg.flooring.dao.FlooringDaoPersistenceException; import com.sg.flooring.dto.Order; import com.sg.flooring.dto.Product; import com.sg.flooring.dto.Tax; import java.math.BigDecimal; import java.time.LocalDate; import java.util.List; /** * * @author apprentice */ public interface FlooringServiceLayer { Order calculateNewOrderDataInput(Order order) throws FlooringValidationException; void addOrder(Order order); List<Order> getAllOrders(); Order getOrder(Integer orderNumber); List<Order> getOrdersByDate(LocalDate date) throws FlooringValidationException; Order removeOrder(Integer orderNumber); void loadFiles() throws FlooringDaoPersistenceException; void writeOrders() throws FlooringDaoPersistenceException; Order setOrderId(Order order); boolean checkMode() throws FlooringDaoPersistenceException; }
1,099
0.769791
0.769791
42
25.166666
25.842855
84
false
false
0
0
0
0
0
0
0.5
false
false
10
f928c89ab15e4426cb71670f0348e42e997c0382
39,247,411,166,840
429a20a345ba35a012cadf9d09ac2aca8f2660a8
/src/main/java/com/lv/netty/msgpack/MsgpackEncode.java
e9b01dcfd15fb20ab9479f4cd7af345fde35a75e
[]
no_license
angiely1115/netty
https://github.com/angiely1115/netty
84fd67be1dc7badf2208e52fbc3621a60c0a8e50
ad9b006ec415ec287c753136b0a40a1eec57dd9b
refs/heads/master
2020-03-26T08:08:37.845000
2018-12-24T09:19:20
2018-12-24T09:19:20
144,687,730
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.lv.netty.msgpack; import com.lv.netty.BaseResult; import com.lv.netty.User; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.MessageToByteEncoder; import org.msgpack.MessagePack; /** * @Author: lvrongzhuan * @Description: ่‡ชๅฎšไน‰msgpack็ผ–็ ๅ™จ * @Date: 2018/8/9 11:38 * @Version: 1.0 * modified by: */ public class MsgpackEncode extends MessageToByteEncoder<User>{ @Override protected void encode(ChannelHandlerContext ctx, User msg, ByteBuf out) throws Exception { MessagePack messagePack = new MessagePack(); byte[] bytes = messagePack.write(msg); out.writeBytes(bytes); } /* @Override protected void encode(ChannelHandlerContext ctx, Object msg, ByteBuf out) throws Exception { MessagePack messagePack = new MessagePack(); byte[] bytes = messagePack.write(msg); out.writeBytes(bytes); }*/ }
UTF-8
Java
950
java
MsgpackEncode.java
Java
[ { "context": ";\nimport org.msgpack.MessagePack;\n\n/**\n * @Author: lvrongzhuan\n * @Description: ่‡ชๅฎšไน‰msgpack็ผ–็ ๅ™จ\n * @Date: 2018/8/9", "end": 280, "score": 0.9996650815010071, "start": 269, "tag": "USERNAME", "value": "lvrongzhuan" } ]
null
[]
package com.lv.netty.msgpack; import com.lv.netty.BaseResult; import com.lv.netty.User; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.MessageToByteEncoder; import org.msgpack.MessagePack; /** * @Author: lvrongzhuan * @Description: ่‡ชๅฎšไน‰msgpack็ผ–็ ๅ™จ * @Date: 2018/8/9 11:38 * @Version: 1.0 * modified by: */ public class MsgpackEncode extends MessageToByteEncoder<User>{ @Override protected void encode(ChannelHandlerContext ctx, User msg, ByteBuf out) throws Exception { MessagePack messagePack = new MessagePack(); byte[] bytes = messagePack.write(msg); out.writeBytes(bytes); } /* @Override protected void encode(ChannelHandlerContext ctx, Object msg, ByteBuf out) throws Exception { MessagePack messagePack = new MessagePack(); byte[] bytes = messagePack.write(msg); out.writeBytes(bytes); }*/ }
950
0.714286
0.701493
31
29.258064
24.651072
96
false
false
0
0
0
0
0
0
0.548387
false
false
10
e7164fd17d961d77185744cd9c63713f7081cd78
37,787,122,306,393
89dec6559be88ac4d54e69ef01eb8c1760eb61f8
/src/main/java/ua/org/oa/annabezkrovnaya/task4_1/Compare.java
54e3f2f5e49ac6ff24ccece56307c7623631f5fd
[]
no_license
annabezkrovnaya/JavaProgramming
https://github.com/annabezkrovnaya/JavaProgramming
7204bec75be49e8e31874f437288040f4589dbb0
403d5a0401c0336dff9eb81227dce695887e4efd
refs/heads/master
2021-08-30T03:27:52.173000
2017-12-15T21:49:33
2017-12-15T21:49:33
114,413,314
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ua.org.oa.annabezkrovnaya.task4_1; import java.util.*; public class Compare<T extends Comparable<T>> implements Comparable<Compare<T>> { T data; List<T> list; public T getMaximum(T [] array){ List<T> list = new ArrayList<>(); list.addAll(Arrays.asList(array)); list.sort(Comparator.reverseOrder()); return list.get(0); } @Override public int compareTo(Compare<T> o) { return data.compareTo(o.data); } }
UTF-8
Java
485
java
Compare.java
Java
[]
null
[]
package ua.org.oa.annabezkrovnaya.task4_1; import java.util.*; public class Compare<T extends Comparable<T>> implements Comparable<Compare<T>> { T data; List<T> list; public T getMaximum(T [] array){ List<T> list = new ArrayList<>(); list.addAll(Arrays.asList(array)); list.sort(Comparator.reverseOrder()); return list.get(0); } @Override public int compareTo(Compare<T> o) { return data.compareTo(o.data); } }
485
0.62268
0.616495
21
22.047619
21.433121
81
false
false
0
0
0
0
0
0
0.428571
false
false
10
9bff94fe28637d231f6eccafeb3962cde99f88a9
37,237,366,492,191
132b8462900a655310da72114abb745e65ddb0e5
/src/com/syn/usersys/usermgr/controller/UserController.java
16cc24b24b9a5f77607b25fe2a144501b045d996
[]
no_license
ShiYuNan/Kobe
https://github.com/ShiYuNan/Kobe
e9123cd21fb9bb11cc11ee1f6a112179271d17a1
06948d80e164042750ba4fc71b48f5fe71043a6e
refs/heads/master
2020-03-23T09:01:10.661000
2018-07-18T01:02:31
2018-07-18T01:02:31
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.syn.usersys.usermgr.controller; import com.syn.usersys.usermgr.business.service.UserService; import com.syn.usersys.usermgr.business.service.UserServiceImpl; import com.syn.usersys.usermgr.domain.UserVO; public class UserController { UserService userMgrService = UserServiceImpl.getInstance(); public UserVO doLogin(String name,String password){ UserVO user = null; try{ user = userMgrService.login(name, password); }catch(Exception e){ System.out.println("็”จๆˆท็™ปๅฝ•็š„ๆ—ถๅ€™ๅ‡บ้”™ไบ†"+e.getMessage()); } return user; } public boolean doAdd(UserVO user){ boolean flag =false; try{ flag = userMgrService.addUser(user); }catch(Exception e){ System.out.println("ๆทปๅŠ ็”จๆˆท็š„ๆ—ถๅ€™ๅ‡บ้”™ไบ†"+e.getMessage()); } return flag; } public boolean doRegister(UserVO user){ boolean flag = false; try{ flag = userMgrService.addUser(user); }catch (Exception e){ System.out.println("็”จๆˆทๆณจๅ†Œ็š„ๆ—ถๅ€™ๅ‡บ้”™ไบ†"+e.getMessage()); } return flag; } }
UTF-8
Java
1,055
java
UserController.java
Java
[]
null
[]
package com.syn.usersys.usermgr.controller; import com.syn.usersys.usermgr.business.service.UserService; import com.syn.usersys.usermgr.business.service.UserServiceImpl; import com.syn.usersys.usermgr.domain.UserVO; public class UserController { UserService userMgrService = UserServiceImpl.getInstance(); public UserVO doLogin(String name,String password){ UserVO user = null; try{ user = userMgrService.login(name, password); }catch(Exception e){ System.out.println("็”จๆˆท็™ปๅฝ•็š„ๆ—ถๅ€™ๅ‡บ้”™ไบ†"+e.getMessage()); } return user; } public boolean doAdd(UserVO user){ boolean flag =false; try{ flag = userMgrService.addUser(user); }catch(Exception e){ System.out.println("ๆทปๅŠ ็”จๆˆท็š„ๆ—ถๅ€™ๅ‡บ้”™ไบ†"+e.getMessage()); } return flag; } public boolean doRegister(UserVO user){ boolean flag = false; try{ flag = userMgrService.addUser(user); }catch (Exception e){ System.out.println("็”จๆˆทๆณจๅ†Œ็š„ๆ—ถๅ€™ๅ‡บ้”™ไบ†"+e.getMessage()); } return flag; } }
1,055
0.700503
0.700503
37
24.891891
20.469864
64
false
false
0
0
0
0
0
0
2.135135
false
false
10
e92d487485779b7747fb4383d018537e193e8ff9
36,172,214,617,619
7687e4954a2463b40020b79b80592cb40e5134e7
/src/team/aistlab/controller/WhAction/WhAction.java
2cef61db0d78430928e9561bed53035d6a99f59d
[]
no_license
ychost/BarCodeHouse
https://github.com/ychost/BarCodeHouse
8921ffe701f37e7c88b3fd29a5860f9f9f2a4a4a
2a528bebfffdbffbad9a395e2eb473843315b343
refs/heads/master
2018-01-12T08:36:17.912000
2015-12-25T03:19:10
2015-12-25T03:19:10
48,309,936
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package team.aistlab.controller.WhAction; import com.opensymphony.xwork2.ActionSupport; import team.aistlab.model.Book; import team.aistlab.model.User; import team.aistlab.model.Warehouse; import team.aistlab.model.sql.SqlDao; import java.util.HashSet; import java.util.Set; /** * @author ychost * @version V1.0 * @date 2015/12/23 20:12 */ public class WhAction extends ActionSupport { protected Set<User> setUsers(String uString) { Set<User> users = new HashSet<>(); if (uString != null) { String[] admin = uString.split(","); for (int i = 0; i < admin.length; i++) { admin[i] = admin[i].trim(); users.add(((User) SqlDao.FindDataByName(admin[i], new User()))); } } return users; } protected Set<Book> restoreBook(String id,String newWhName) { Set<Book> books = new HashSet<>(); Warehouse wh = new Warehouse(); wh = (Warehouse)SqlDao.FindDataById(id, wh); books = wh.getBooks(); //็›ธๅบ”ๅœฐไนฆ็ฑไป“ๅบ“ๆ›ดๅ for(Book book : books){ book.setWarehouse(newWhName); SqlDao.Save(book); } return books; } }
UTF-8
Java
1,216
java
WhAction.java
Java
[ { "context": "til.HashSet;\nimport java.util.Set;\n\n/**\n * @author ychost\n * @version V1.0\n * @date 2015/12/23 20:12\n */\np", "end": 299, "score": 0.9996693134307861, "start": 293, "tag": "USERNAME", "value": "ychost" } ]
null
[]
package team.aistlab.controller.WhAction; import com.opensymphony.xwork2.ActionSupport; import team.aistlab.model.Book; import team.aistlab.model.User; import team.aistlab.model.Warehouse; import team.aistlab.model.sql.SqlDao; import java.util.HashSet; import java.util.Set; /** * @author ychost * @version V1.0 * @date 2015/12/23 20:12 */ public class WhAction extends ActionSupport { protected Set<User> setUsers(String uString) { Set<User> users = new HashSet<>(); if (uString != null) { String[] admin = uString.split(","); for (int i = 0; i < admin.length; i++) { admin[i] = admin[i].trim(); users.add(((User) SqlDao.FindDataByName(admin[i], new User()))); } } return users; } protected Set<Book> restoreBook(String id,String newWhName) { Set<Book> books = new HashSet<>(); Warehouse wh = new Warehouse(); wh = (Warehouse)SqlDao.FindDataById(id, wh); books = wh.getBooks(); //็›ธๅบ”ๅœฐไนฆ็ฑไป“ๅบ“ๆ›ดๅ for(Book book : books){ book.setWarehouse(newWhName); SqlDao.Save(book); } return books; } }
1,216
0.593489
0.580134
43
26.860466
19.470409
80
false
false
0
0
0
0
0
0
0.604651
false
false
10
18c22330dc2056bc694946989547e4a317c3d040
38,465,727,131,118
c200cde1d0be183639aaa69a4371685fd1597220
/agile/src/main/java/com/mingyuechunqiu/agile/base/model/modelpart/IBaseModelPart.java
f162f785f7cca51d1d673c22f39df8ec92a4566a
[]
no_license
MingYueChunQiu/Agile
https://github.com/MingYueChunQiu/Agile
3b842a1450abb7181d82def26184d66fa6feda40
3c56c6508081c4234019e3bf5ae2ece00842a1c5
refs/heads/master
2023-04-14T15:34:52.999000
2023-03-25T04:43:09
2023-03-25T04:43:09
156,509,283
9
3
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.mingyuechunqiu.agile.base.model.modelpart; import androidx.annotation.NonNull; import com.mingyuechunqiu.agile.base.model.repository.IBaseRepository; import com.mingyuechunqiu.agile.base.model.repository.IRepositoryOwner; import java.util.Map; import java.util.Set; /** * <pre> * author : xyj * Github : https://github.com/MingYueChunQiu * e-mail : xiyujieit@163.com * time : 2019/3/4 * desc : ๆ‰€ๆœ‰Modelๅฑ‚ไธญPartๅ•ๅ…ƒๆŽฅๅฃ * ็ปงๆ‰ฟ่‡ชIDaoOwner * version: 1.0 * </pre> */ public interface IBaseModelPart extends IRepositoryOwner { @NonNull Map<IBaseRepository, Set<String>> getRepositoryMap(); /** * ้‡Šๆ”พ่ต„ๆบ */ void releaseOnDetach(); }
UTF-8
Java
741
java
IBaseModelPart.java
Java
[ { "context": "mport java.util.Set;\n\n/**\n * <pre>\n * author : xyj\n * Github : https://github.com/MingYueChunQiu", "end": 314, "score": 0.9997277855873108, "start": 311, "tag": "USERNAME", "value": "xyj" }, { "context": " author : xyj\n * Github : https://github.com/MingYueChunQiu\n * e-mail : xiyujieit@163.com\n * time :", "end": 364, "score": 0.9996128678321838, "start": 350, "tag": "USERNAME", "value": "MingYueChunQiu" }, { "context": " https://github.com/MingYueChunQiu\n * e-mail : xiyujieit@163.com\n * time : 2019/3/4\n * desc : ๆ‰€ๆœ‰Modelๅฑ‚", "end": 398, "score": 0.9999176263809204, "start": 381, "tag": "EMAIL", "value": "xiyujieit@163.com" } ]
null
[]
package com.mingyuechunqiu.agile.base.model.modelpart; import androidx.annotation.NonNull; import com.mingyuechunqiu.agile.base.model.repository.IBaseRepository; import com.mingyuechunqiu.agile.base.model.repository.IRepositoryOwner; import java.util.Map; import java.util.Set; /** * <pre> * author : xyj * Github : https://github.com/MingYueChunQiu * e-mail : <EMAIL> * time : 2019/3/4 * desc : ๆ‰€ๆœ‰Modelๅฑ‚ไธญPartๅ•ๅ…ƒๆŽฅๅฃ * ็ปงๆ‰ฟ่‡ชIDaoOwner * version: 1.0 * </pre> */ public interface IBaseModelPart extends IRepositoryOwner { @NonNull Map<IBaseRepository, Set<String>> getRepositoryMap(); /** * ้‡Šๆ”พ่ต„ๆบ */ void releaseOnDetach(); }
731
0.679325
0.663854
31
21.935484
21.685339
71
false
false
0
0
0
0
0
0
0.290323
false
false
10
7a317446a0750f3cc315d38043f3e7e7470ce2c4
36,601,711,336,433
28598007f7b5f827df9e1312eb0147b482922a5b
/src/test/java/scott/xsdanalytics/SwiftTest.java
688ea492243ff5bcc79a0fee4d2040fc8a6392b0
[]
no_license
scottysinclair/xsdanalytics
https://github.com/scottysinclair/xsdanalytics
e023ee431124d48dd6d2284bceb6bd5025ea51a1
397adee8f0cda6cc647c1cdf5d21477f7f1bef96
refs/heads/master
2020-03-30T02:19:07.958000
2018-09-27T18:09:33
2018-09-27T18:09:33
150,625,455
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package scott.xsdanalytics; /*- * #%L * BarleyDB * $Id:$ * $HeadURL:$ * %% * Copyright (C) 2014 - 2018 Scott Sinclair * <scottysinclair@gmail.com> * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. * #L% */ import static org.junit.Assert.*; import org.junit.Before; import org.junit.Test; public class SwiftTest extends ParentTest { public static final String importPath = "schemas/"; private static XsdDefinition mt940; private static XsdDefinition mtmsg; @Before public void before() throws Exception { mtmsg = loadDefinition(importPath + "mtmsg.2011.xsd"); mt940 = loadDefinition(importPath + "fin.940.2011.xsd"); } @Test public void testMt940Structure() throws Exception { XsdType finMessageComplexType = mtmsg.findType(new QualifiedName("urn:swift:xsd:mtmsg.2011", "FinMessage_Type")); assertNotNull(finMessageComplexType); XsdElement block4 = finMessageComplexType.getElement(new QualifiedName("urn:swift:xsd:mtmsg.2011", "Block4")); assertNotNull(block4); XsdElement document = mt940.findElement(new QualifiedName("urn:swift:xsd:fin.940.2011", "Document")); assertNotNull(document); /* * insert the fin 940 document element as the content of the Block4 any element. */ XsdComplexType ctype = (XsdComplexType) block4.getType(); XsdAny any = ctype.getComplexContent().getExtension().getSequence().getAny(); any.setContent(document); assertEquals(1, block4.getChildTargetElements().size()); assertSame(document.getDomElement(), block4.getChildTargetElements().get(0).getDomElement()); } }
UTF-8
Java
2,327
java
SwiftTest.java
Java
[ { "context": "$\n * $HeadURL:$\n * %%\n * Copyright (C) 2014 - 2018 Scott Sinclair\n * <scottysinclair@gmail.com>\n * %%\n * This", "end": 124, "score": 0.9997433423995972, "start": 110, "tag": "NAME", "value": "Scott Sinclair" }, { "context": "opyright (C) 2014 - 2018 Scott Sinclair\n * <scottysinclair@gmail.com>\n * %%\n * This program is free software: you can ", "end": 159, "score": 0.9999309182167053, "start": 135, "tag": "EMAIL", "value": "scottysinclair@gmail.com" } ]
null
[]
package scott.xsdanalytics; /*- * #%L * BarleyDB * $Id:$ * $HeadURL:$ * %% * Copyright (C) 2014 - 2018 <NAME> * <<EMAIL>> * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. * #L% */ import static org.junit.Assert.*; import org.junit.Before; import org.junit.Test; public class SwiftTest extends ParentTest { public static final String importPath = "schemas/"; private static XsdDefinition mt940; private static XsdDefinition mtmsg; @Before public void before() throws Exception { mtmsg = loadDefinition(importPath + "mtmsg.2011.xsd"); mt940 = loadDefinition(importPath + "fin.940.2011.xsd"); } @Test public void testMt940Structure() throws Exception { XsdType finMessageComplexType = mtmsg.findType(new QualifiedName("urn:swift:xsd:mtmsg.2011", "FinMessage_Type")); assertNotNull(finMessageComplexType); XsdElement block4 = finMessageComplexType.getElement(new QualifiedName("urn:swift:xsd:mtmsg.2011", "Block4")); assertNotNull(block4); XsdElement document = mt940.findElement(new QualifiedName("urn:swift:xsd:fin.940.2011", "Document")); assertNotNull(document); /* * insert the fin 940 document element as the content of the Block4 any element. */ XsdComplexType ctype = (XsdComplexType) block4.getType(); XsdAny any = ctype.getComplexContent().getExtension().getSequence().getAny(); any.setContent(document); assertEquals(1, block4.getChildTargetElements().size()); assertSame(document.getDomElement(), block4.getChildTargetElements().get(0).getDomElement()); } }
2,302
0.697894
0.67168
68
33.220589
32.701794
121
false
false
0
0
0
0
0
0
0.441176
false
false
10
60396621c1409b91f3f84101e038b1df8ad3e29e
2,422,361,613,702
11dcf260ca16503d1972bcfc7781c6596b70fa65
/java/com/imooc/sell/enmus/ResultEnum.java
5fc360368cc9eebb2f22ea5460dd991681b63088
[]
no_license
2017LLLLL/weChatSell
https://github.com/2017LLLLL/weChatSell
3e30bb14efafb61d5032479e3eddc6e721771be8
9d6f617ca914e1cf009f8b77ef87ba79e72c8a8c
refs/heads/master
2022-04-23T00:54:33.819000
2020-04-11T14:43:23
2020-04-11T14:43:23
254,886,272
1
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.imooc.sell.enmus; import lombok.Getter; /* * ๅ•†ๅ“ๅผ‚ๅธธ็ฑป * */ @Getter public enum ResultEnum { SUCCESS(0,"ๆˆๅŠŸ"), PARAM_ERROR(1,"ๅ‚ๆ•ฐ้”™่ฏฏ"), CARTS_ERROR(2,"่ดญ็‰ฉ่ฝฆไธบ็ฉบ"), PRODUCT_NOT_EXIST(10,"ๅ•†ๅ“ไธๅญ˜ๅœจ"), STOCK_ERROR_LESSTHAN(11,"ๅบ“ๅญ˜ไธๅคŸ"), ORDER_NOT_EXIST(12,"่ฎขๅ•ไธๅญ˜ๅœจ"), ORDERDETAIL_NOT_EXIST(13,"่ฎขๅ•่ฏฆๆƒ…ไธๅญ˜ๅœจ"), ORDERMASTER_UPDATE_ERROR(14,"่ฎขๅ•ไฟฎๆ”นๅคฑ่ดฅ๏ผŒ่ฎขๅ•ไธๅญ˜ๅœจ"), ORDERMASTER_UPDATE_STATUS_ERROR(15,"่ฎขไฟฎๆ”นๅคฑ่ดฅ๏ผŒไฟฎๆ”น่ฎขๅ•็Šถๆ€ๅคฑ่ดฅ"), ORDERMASTER_DETAIL_UPDATE_ERROR(16,"่ฎขๅ•ไฟฎๆ”นๅคฑ่ดฅ๏ผŒ่ฎขๅ•่ฏฆๆƒ…ไธๅญ˜ๅœจ"), ORDERMASTER_DB_UPDATE_ERROR(16,"่ฎขๅ•ไฟฎๆ”นๅคฑ่ดฅ๏ผŒๆ•ฐๆฎๅบ“ไฟฎๆ”นๅคฑ่ดฅ"), ORDER_UPDATE_STATUS(17,"่ฎขๅ•ไฟฎๆ”นๅคฑ่ดฅ๏ผŒ่ฎขๅ•็Šถๆ€ไธๆญฃ็กฎ"), PAY_ERROR(18,"่ฎขๅ•ๆ”ฏไป˜ๅคฑ่ดฅ๏ผŒๆ”ฏไป˜็Šถๆ€้”™่ฏฏ"), ORDER_OWNER_ERROR(19,"่ฎขๅ•OPENIDไธๅŒน้…"), ORDER_QUIT_SUCCESS(20,"่ฎขๅ•ๅ–ๆถˆๆˆๅŠŸ"), ORDER_FINISH_SUCCESS(21,"่ฎขๅ•ๅฎŒ็ป“ๆˆๅŠŸ"), PRODUCT_STATUS_ERROR(22,"ๅ•†ๅ“็Šถๆ€ไธๆญฃ็กฎ"), FILE_UP_ERROR(23,"ไธŠไผ ๆ–‡ไปถๅคฑ่ดฅ") , CATGEGORY_EXIST(24,"็ฑป็›ฎไปฅๅญ˜ๅœจ") , ; private Integer code; private String message; ResultEnum(Integer code, String message) { this.code = code; this.message = message; } }
UTF-8
Java
1,352
java
ResultEnum.java
Java
[]
null
[]
package com.imooc.sell.enmus; import lombok.Getter; /* * ๅ•†ๅ“ๅผ‚ๅธธ็ฑป * */ @Getter public enum ResultEnum { SUCCESS(0,"ๆˆๅŠŸ"), PARAM_ERROR(1,"ๅ‚ๆ•ฐ้”™่ฏฏ"), CARTS_ERROR(2,"่ดญ็‰ฉ่ฝฆไธบ็ฉบ"), PRODUCT_NOT_EXIST(10,"ๅ•†ๅ“ไธๅญ˜ๅœจ"), STOCK_ERROR_LESSTHAN(11,"ๅบ“ๅญ˜ไธๅคŸ"), ORDER_NOT_EXIST(12,"่ฎขๅ•ไธๅญ˜ๅœจ"), ORDERDETAIL_NOT_EXIST(13,"่ฎขๅ•่ฏฆๆƒ…ไธๅญ˜ๅœจ"), ORDERMASTER_UPDATE_ERROR(14,"่ฎขๅ•ไฟฎๆ”นๅคฑ่ดฅ๏ผŒ่ฎขๅ•ไธๅญ˜ๅœจ"), ORDERMASTER_UPDATE_STATUS_ERROR(15,"่ฎขไฟฎๆ”นๅคฑ่ดฅ๏ผŒไฟฎๆ”น่ฎขๅ•็Šถๆ€ๅคฑ่ดฅ"), ORDERMASTER_DETAIL_UPDATE_ERROR(16,"่ฎขๅ•ไฟฎๆ”นๅคฑ่ดฅ๏ผŒ่ฎขๅ•่ฏฆๆƒ…ไธๅญ˜ๅœจ"), ORDERMASTER_DB_UPDATE_ERROR(16,"่ฎขๅ•ไฟฎๆ”นๅคฑ่ดฅ๏ผŒๆ•ฐๆฎๅบ“ไฟฎๆ”นๅคฑ่ดฅ"), ORDER_UPDATE_STATUS(17,"่ฎขๅ•ไฟฎๆ”นๅคฑ่ดฅ๏ผŒ่ฎขๅ•็Šถๆ€ไธๆญฃ็กฎ"), PAY_ERROR(18,"่ฎขๅ•ๆ”ฏไป˜ๅคฑ่ดฅ๏ผŒๆ”ฏไป˜็Šถๆ€้”™่ฏฏ"), ORDER_OWNER_ERROR(19,"่ฎขๅ•OPENIDไธๅŒน้…"), ORDER_QUIT_SUCCESS(20,"่ฎขๅ•ๅ–ๆถˆๆˆๅŠŸ"), ORDER_FINISH_SUCCESS(21,"่ฎขๅ•ๅฎŒ็ป“ๆˆๅŠŸ"), PRODUCT_STATUS_ERROR(22,"ๅ•†ๅ“็Šถๆ€ไธๆญฃ็กฎ"), FILE_UP_ERROR(23,"ไธŠไผ ๆ–‡ไปถๅคฑ่ดฅ") , CATGEGORY_EXIST(24,"็ฑป็›ฎไปฅๅญ˜ๅœจ") , ; private Integer code; private String message; ResultEnum(Integer code, String message) { this.code = code; this.message = message; } }
1,352
0.639579
0.606119
59
16.728813
18.534285
57
false
false
0
0
0
0
0
0
0.779661
false
false
10
40eab4155372cc066c9aacf8c5af871946a63fa7
3,341,484,582,394
401c90d37f4897f8d9fce99b482cbba6a79170b3
/Mobile App/TakeMyMoney/app/src/main/java/com/biletskyi/vladyslav/takemymoney/HttpGETQuery.java
df1980c133936fab672ad06f5c1a5dd84b2c0ce3
[]
no_license
VladyslavBiletskyi/TakeMyMoney
https://github.com/VladyslavBiletskyi/TakeMyMoney
541cfa07a89dd7475806a3d21b26fbc7335e101d
455cb960792db5ca74dabd87cfef58578935bde2
refs/heads/master
2021-01-19T13:27:02.382000
2017-02-18T14:12:22
2017-02-18T14:12:22
82,390,949
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.biletskyi.vladyslav.takemymoney; import android.app.Activity; import android.app.Notification; import android.os.AsyncTask; import android.util.Base64; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; /** * Created by Vladyslav on 09.12.2016. */ public class HttpGETQuery extends AsyncTask<String,Void, String> { NetworkActivity sender; public HttpGETQuery(NetworkActivity cat){ sender=cat; } @Override protected String doInBackground(String... params) {//[0] - host, [1] - token StringBuilder answer = new StringBuilder(); try { URL url = new URL(params[0]); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); if (params.length>1){ connection.setRequestProperty("Authorization","Bearer "+params[1]); } connection.connect(); BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line = ""; while ((line = reader.readLine()) != null) { answer.append(line); } } catch (Exception e) { answer.append(e.getLocalizedMessage()); } finally { return answer.toString(); } } @Override protected void onPostExecute(String s) { sender.onBackgroundTaskFinish(s); super.onPostExecute(s); } }
UTF-8
Java
1,551
java
HttpGETQuery.java
Java
[ { "context": "onnection;\nimport java.net.URL;\n\n/**\n * Created by Vladyslav on 09.12.2016.\n */\n\npublic class HttpGETQuery ext", "end": 315, "score": 0.9983381032943726, "start": 306, "tag": "NAME", "value": "Vladyslav" } ]
null
[]
package com.biletskyi.vladyslav.takemymoney; import android.app.Activity; import android.app.Notification; import android.os.AsyncTask; import android.util.Base64; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; /** * Created by Vladyslav on 09.12.2016. */ public class HttpGETQuery extends AsyncTask<String,Void, String> { NetworkActivity sender; public HttpGETQuery(NetworkActivity cat){ sender=cat; } @Override protected String doInBackground(String... params) {//[0] - host, [1] - token StringBuilder answer = new StringBuilder(); try { URL url = new URL(params[0]); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); if (params.length>1){ connection.setRequestProperty("Authorization","Bearer "+params[1]); } connection.connect(); BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line = ""; while ((line = reader.readLine()) != null) { answer.append(line); } } catch (Exception e) { answer.append(e.getLocalizedMessage()); } finally { return answer.toString(); } } @Override protected void onPostExecute(String s) { sender.onBackgroundTaskFinish(s); super.onPostExecute(s); } }
1,551
0.630561
0.62089
50
30.02
24.200405
107
false
false
0
0
0
0
0
0
0.56
false
false
10
133153c77703e0e65d58630aa458b4c16c5826b3
16,776,142,260,609
499e49378065b74236856af55caab675237da4e7
/attm/src/main/java/com/biziitech/attm/model/ModelTicketPurchaseChd.java
1b09215e066eae8dba7dd8b54d637ca60e8088bf
[]
no_license
ToufiqAmin/Project2
https://github.com/ToufiqAmin/Project2
6d0f1be275cae398957570d16c65ee012f847b7b
3ae52b519d2cc4d0e2cc6fcf1ec60288e723f70d
refs/heads/master
2020-07-07T11:16:29.920000
2019-08-20T08:37:44
2019-08-20T08:37:44
203,333,513
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.biziitech.attm.model; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Transient; import org.hibernate.annotations.GenericGenerator; import com.biziitech.attm.bg.model.ModelCity; import com.biziitech.attm.bg.model.ModelCountry; import com.biziitech.attm.bg.model.ModelUser; @Entity(name="ATTM_TICKET_PURCHASE_CHD") public class ModelTicketPurchaseChd { @Id @GenericGenerator(name = "custom_sequence", strategy = "com.biziitech.attm.IdGenerator") @GeneratedValue(generator = "custom_sequence") @Column(name="TICKET_PURCHASE_CHD_ID") private Long ticketPurchaseChdId; @ManyToOne @JoinColumn(name="TICKET_PURCHASE_MST_ID") private ModelTicketPurchaseMst modelTicketPurchaseMst; @Column(name="TICKET_NO") private String ticketNo; @ManyToOne @JoinColumn(name="USER_ID") private ModelUser modelUser; @Column(name="PNR") private String pNR; @Column(name="TICKET_AMT_USD") private Double ticketAMTUSD; @Column(name="TICKET_AMT_BDT") private Double ticketAMTBDT; @ManyToOne @JoinColumn(name="FROM_COUNTRY") private ModelCountry countryFrom; @ManyToOne @JoinColumn(name="TO_COUNTRY") private ModelCountry countryTo; @ManyToOne @JoinColumn(name="FROM_CITY") private ModelCity cityFrom; @ManyToOne @JoinColumn(name="TO_CITY") private ModelCity cityTo; @Column(name="ACTIVE_STATUS") private int activeStatus; @Column(name="REMARKS") private String remarks; @Column(name="FLEX_FIELD1") private String flex1; @Column(name="FLEX_FIELD2") private String flex2; @Column(name="FLEX_FIELD3") private String flex3; @Transient private boolean active; @Transient private String sActive; @Column(name="ENTERED_BY") private Long enteredBy; @Column(name="ENTRY_TIMESTAMP") private Date entryTimeStamp; @Column(name="UPDATED_BY") private Long updatedBy; @Column(name="UPDATE_TIMESTAMP") private Date updateTimeStamp; @Column(name="AGENT_PASSENGER_NAME") private String agentPassengerName; @Column(name="SELLING_PRICE_USD") private Double sellingPriceUSD; @Column(name="SELLING_PRICE_BDT") private Double sellingPriceBDT; @Column(name="PURCHASE_PRICE_USD") private Double purchasePriceUSD; @Column(name="PURCHASE_PRICE_BDT") private Double purchasePriceBDT; public Long getTicketPurchaseChdId() { return ticketPurchaseChdId; } public ModelTicketPurchaseMst getModelTicketPurchaseMst() { return modelTicketPurchaseMst; } public String getTicketNo() { return ticketNo; } public ModelUser getModelUser() { return modelUser; } public String getpNR() { return pNR; } public Double getTicketAMTUSD() { return ticketAMTUSD; } public Double getTicketAMTBDT() { return ticketAMTBDT; } public ModelCountry getCountryFrom() { return countryFrom; } public ModelCountry getCountryTo() { return countryTo; } public int getActiveStatus() { return activeStatus; } public String getRemarks() { return remarks; } public String getFlex1() { return flex1; } public String getFlex2() { return flex2; } public String getFlex3() { return flex3; } public boolean isActive() { return active; } public String getsActive() { return sActive; } public Long getEnteredBy() { return enteredBy; } public Date getEntryTimeStamp() { return entryTimeStamp; } public Long getUpdatedBy() { return updatedBy; } public Date getUpdateTimeStamp() { return updateTimeStamp; } public void setTicketPurchaseChdId(Long ticketPurchaseChdId) { this.ticketPurchaseChdId = ticketPurchaseChdId; } public void setModelTicketPurchaseMst(ModelTicketPurchaseMst modelTicketPurchaseMst) { this.modelTicketPurchaseMst = modelTicketPurchaseMst; } public void setTicketNo(String ticketNo) { this.ticketNo = ticketNo; } public void setModelUser(ModelUser modelUser) { this.modelUser = modelUser; } public void setpNR(String pNR) { this.pNR = pNR; } public void setTicketAMTUSD(Double ticketAMTUSD) { this.ticketAMTUSD = ticketAMTUSD; } public void setTicketAMTBDT(Double ticketAMTBDT) { this.ticketAMTBDT = ticketAMTBDT; } public void setCountryFrom(ModelCountry countryFrom) { this.countryFrom = countryFrom; } public void setCountryTo(ModelCountry countryTo) { this.countryTo = countryTo; } public void setActiveStatus(int activeStatus) { this.activeStatus = activeStatus; } public void setRemarks(String remarks) { this.remarks = remarks; } public void setFlex1(String flex1) { this.flex1 = flex1; } public void setFlex2(String flex2) { this.flex2 = flex2; } public void setFlex3(String flex3) { this.flex3 = flex3; } public void setActive(boolean active) { this.active = active; } public void setsActive(String sActive) { this.sActive = sActive; } public void setEnteredBy(Long enteredBy) { this.enteredBy = enteredBy; } public void setEntryTimeStamp(Date entryTimeStamp) { this.entryTimeStamp = entryTimeStamp; } public void setUpdatedBy(Long updatedBy) { this.updatedBy = updatedBy; } public void setUpdateTimeStamp(Date updateTimeStamp) { this.updateTimeStamp = updateTimeStamp; } public String getAgentPassengerName() { return agentPassengerName; } public void setAgentPassengerName(String agentPassengerName) { this.agentPassengerName = agentPassengerName; } public ModelCity getCityFrom() { return cityFrom; } public void setCityFrom(ModelCity cityFrom) { this.cityFrom = cityFrom; } public ModelCity getCityTo() { return cityTo; } public void setCityTo(ModelCity cityTo) { this.cityTo = cityTo; } public Double getSellingPriceUSD() { return sellingPriceUSD; } public void setSellingPriceUSD(Double sellingPriceUSD) { this.sellingPriceUSD = sellingPriceUSD; } public Double getSellingPriceBDT() { return sellingPriceBDT; } public void setSellingPriceBDT(Double sellingPriceBDT) { this.sellingPriceBDT = sellingPriceBDT; } public Double getPurchasePriceUSD() { return purchasePriceUSD; } public void setPurchasePriceUSD(Double purchasePriceUSD) { this.purchasePriceUSD = purchasePriceUSD; } public Double getPurchasePriceBDT() { return purchasePriceBDT; } public void setPurchasePriceBDT(Double purchasePriceBDT) { this.purchasePriceBDT = purchasePriceBDT; } @Override public String toString() { return "ModelTicketPurchaseChd [ticketPurchaseChdId=" + ticketPurchaseChdId + ", modelTicketPurchaseMst=" + modelTicketPurchaseMst + ", ticketNo=" + ticketNo + ", modelUser=" + modelUser + ", pNR=" + pNR + ", ticketAMTUSD=" + ticketAMTUSD + ", ticketAMTBDT=" + ticketAMTBDT + ", countryFrom=" + countryFrom + ", countryTo=" + countryTo + ", cityFrom=" + cityFrom + ", cityTo=" + cityTo + ", activeStatus=" + activeStatus + ", remarks=" + remarks + ", flex1=" + flex1 + ", flex2=" + flex2 + ", flex3=" + flex3 + ", active=" + active + ", sActive=" + sActive + ", enteredBy=" + enteredBy + ", entryTimeStamp=" + entryTimeStamp + ", updatedBy=" + updatedBy + ", updateTimeStamp=" + updateTimeStamp + ", agentPassengerName=" + agentPassengerName + ", sellingPriceUSD=" + sellingPriceUSD + ", sellingPriceBDT=" + sellingPriceBDT + ", purchasePriceUSD=" + purchasePriceUSD + ", purchasePriceBDT=" + purchasePriceBDT + "]"; } }
UTF-8
Java
7,857
java
ModelTicketPurchaseChd.java
Java
[]
null
[]
package com.biziitech.attm.model; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Transient; import org.hibernate.annotations.GenericGenerator; import com.biziitech.attm.bg.model.ModelCity; import com.biziitech.attm.bg.model.ModelCountry; import com.biziitech.attm.bg.model.ModelUser; @Entity(name="ATTM_TICKET_PURCHASE_CHD") public class ModelTicketPurchaseChd { @Id @GenericGenerator(name = "custom_sequence", strategy = "com.biziitech.attm.IdGenerator") @GeneratedValue(generator = "custom_sequence") @Column(name="TICKET_PURCHASE_CHD_ID") private Long ticketPurchaseChdId; @ManyToOne @JoinColumn(name="TICKET_PURCHASE_MST_ID") private ModelTicketPurchaseMst modelTicketPurchaseMst; @Column(name="TICKET_NO") private String ticketNo; @ManyToOne @JoinColumn(name="USER_ID") private ModelUser modelUser; @Column(name="PNR") private String pNR; @Column(name="TICKET_AMT_USD") private Double ticketAMTUSD; @Column(name="TICKET_AMT_BDT") private Double ticketAMTBDT; @ManyToOne @JoinColumn(name="FROM_COUNTRY") private ModelCountry countryFrom; @ManyToOne @JoinColumn(name="TO_COUNTRY") private ModelCountry countryTo; @ManyToOne @JoinColumn(name="FROM_CITY") private ModelCity cityFrom; @ManyToOne @JoinColumn(name="TO_CITY") private ModelCity cityTo; @Column(name="ACTIVE_STATUS") private int activeStatus; @Column(name="REMARKS") private String remarks; @Column(name="FLEX_FIELD1") private String flex1; @Column(name="FLEX_FIELD2") private String flex2; @Column(name="FLEX_FIELD3") private String flex3; @Transient private boolean active; @Transient private String sActive; @Column(name="ENTERED_BY") private Long enteredBy; @Column(name="ENTRY_TIMESTAMP") private Date entryTimeStamp; @Column(name="UPDATED_BY") private Long updatedBy; @Column(name="UPDATE_TIMESTAMP") private Date updateTimeStamp; @Column(name="AGENT_PASSENGER_NAME") private String agentPassengerName; @Column(name="SELLING_PRICE_USD") private Double sellingPriceUSD; @Column(name="SELLING_PRICE_BDT") private Double sellingPriceBDT; @Column(name="PURCHASE_PRICE_USD") private Double purchasePriceUSD; @Column(name="PURCHASE_PRICE_BDT") private Double purchasePriceBDT; public Long getTicketPurchaseChdId() { return ticketPurchaseChdId; } public ModelTicketPurchaseMst getModelTicketPurchaseMst() { return modelTicketPurchaseMst; } public String getTicketNo() { return ticketNo; } public ModelUser getModelUser() { return modelUser; } public String getpNR() { return pNR; } public Double getTicketAMTUSD() { return ticketAMTUSD; } public Double getTicketAMTBDT() { return ticketAMTBDT; } public ModelCountry getCountryFrom() { return countryFrom; } public ModelCountry getCountryTo() { return countryTo; } public int getActiveStatus() { return activeStatus; } public String getRemarks() { return remarks; } public String getFlex1() { return flex1; } public String getFlex2() { return flex2; } public String getFlex3() { return flex3; } public boolean isActive() { return active; } public String getsActive() { return sActive; } public Long getEnteredBy() { return enteredBy; } public Date getEntryTimeStamp() { return entryTimeStamp; } public Long getUpdatedBy() { return updatedBy; } public Date getUpdateTimeStamp() { return updateTimeStamp; } public void setTicketPurchaseChdId(Long ticketPurchaseChdId) { this.ticketPurchaseChdId = ticketPurchaseChdId; } public void setModelTicketPurchaseMst(ModelTicketPurchaseMst modelTicketPurchaseMst) { this.modelTicketPurchaseMst = modelTicketPurchaseMst; } public void setTicketNo(String ticketNo) { this.ticketNo = ticketNo; } public void setModelUser(ModelUser modelUser) { this.modelUser = modelUser; } public void setpNR(String pNR) { this.pNR = pNR; } public void setTicketAMTUSD(Double ticketAMTUSD) { this.ticketAMTUSD = ticketAMTUSD; } public void setTicketAMTBDT(Double ticketAMTBDT) { this.ticketAMTBDT = ticketAMTBDT; } public void setCountryFrom(ModelCountry countryFrom) { this.countryFrom = countryFrom; } public void setCountryTo(ModelCountry countryTo) { this.countryTo = countryTo; } public void setActiveStatus(int activeStatus) { this.activeStatus = activeStatus; } public void setRemarks(String remarks) { this.remarks = remarks; } public void setFlex1(String flex1) { this.flex1 = flex1; } public void setFlex2(String flex2) { this.flex2 = flex2; } public void setFlex3(String flex3) { this.flex3 = flex3; } public void setActive(boolean active) { this.active = active; } public void setsActive(String sActive) { this.sActive = sActive; } public void setEnteredBy(Long enteredBy) { this.enteredBy = enteredBy; } public void setEntryTimeStamp(Date entryTimeStamp) { this.entryTimeStamp = entryTimeStamp; } public void setUpdatedBy(Long updatedBy) { this.updatedBy = updatedBy; } public void setUpdateTimeStamp(Date updateTimeStamp) { this.updateTimeStamp = updateTimeStamp; } public String getAgentPassengerName() { return agentPassengerName; } public void setAgentPassengerName(String agentPassengerName) { this.agentPassengerName = agentPassengerName; } public ModelCity getCityFrom() { return cityFrom; } public void setCityFrom(ModelCity cityFrom) { this.cityFrom = cityFrom; } public ModelCity getCityTo() { return cityTo; } public void setCityTo(ModelCity cityTo) { this.cityTo = cityTo; } public Double getSellingPriceUSD() { return sellingPriceUSD; } public void setSellingPriceUSD(Double sellingPriceUSD) { this.sellingPriceUSD = sellingPriceUSD; } public Double getSellingPriceBDT() { return sellingPriceBDT; } public void setSellingPriceBDT(Double sellingPriceBDT) { this.sellingPriceBDT = sellingPriceBDT; } public Double getPurchasePriceUSD() { return purchasePriceUSD; } public void setPurchasePriceUSD(Double purchasePriceUSD) { this.purchasePriceUSD = purchasePriceUSD; } public Double getPurchasePriceBDT() { return purchasePriceBDT; } public void setPurchasePriceBDT(Double purchasePriceBDT) { this.purchasePriceBDT = purchasePriceBDT; } @Override public String toString() { return "ModelTicketPurchaseChd [ticketPurchaseChdId=" + ticketPurchaseChdId + ", modelTicketPurchaseMst=" + modelTicketPurchaseMst + ", ticketNo=" + ticketNo + ", modelUser=" + modelUser + ", pNR=" + pNR + ", ticketAMTUSD=" + ticketAMTUSD + ", ticketAMTBDT=" + ticketAMTBDT + ", countryFrom=" + countryFrom + ", countryTo=" + countryTo + ", cityFrom=" + cityFrom + ", cityTo=" + cityTo + ", activeStatus=" + activeStatus + ", remarks=" + remarks + ", flex1=" + flex1 + ", flex2=" + flex2 + ", flex3=" + flex3 + ", active=" + active + ", sActive=" + sActive + ", enteredBy=" + enteredBy + ", entryTimeStamp=" + entryTimeStamp + ", updatedBy=" + updatedBy + ", updateTimeStamp=" + updateTimeStamp + ", agentPassengerName=" + agentPassengerName + ", sellingPriceUSD=" + sellingPriceUSD + ", sellingPriceBDT=" + sellingPriceBDT + ", purchasePriceUSD=" + purchasePriceUSD + ", purchasePriceBDT=" + purchasePriceBDT + "]"; } }
7,857
0.703958
0.70014
350
20.448572
22.013281
107
false
false
0
0
0
0
0
0
1.351429
false
false
10
6c51ba0c582c1e4a28007a83e72a9e488553246f
29,386,166,242,636
781d525130d3222b3de816674f04abafd8fd82ba
/src/com/ibm/replication/iidr/metadata/Settings.java
9e3e1f0795353537895ea9bf6c7588f77303c0b8
[]
no_license
fketelaars/IIDR-IGC-Integration
https://github.com/fketelaars/IIDR-IGC-Integration
efdd8b98222dd1a4c016b9ad751a70367cc17d73
9056191547db0d9de2e5c3183654547676b8fd85
refs/heads/master
2021-01-01T05:02:26.243000
2018-01-08T10:03:48
2018-01-08T10:03:48
56,077,429
0
3
null
false
2016-05-02T15:13:04
2016-04-12T15:56:02
2016-04-13T06:50:51
2016-05-02T15:13:04
80
0
0
0
Java
null
null
/**************************************************************************** ** Licensed Materials - Property of IBM ** IBM InfoSphere Change Data Capture ** 5724-U70 ** ** (c) Copyright IBM Corp. 2001, 2016 All rights reserved. ** ** The following sample of source code ("Sample") is owned by International ** Business Machines Corporation or one of its subsidiaries ("IBM") and is ** copyrighted and licensed, not sold. You may use, copy, modify, and ** distribute the Sample for your own use in any form without payment to IBM. ** ** The Sample code is provided to you on an "AS IS" basis, without warranty of ** any kind. IBM HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR ** IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF ** MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. Some jurisdictions do ** not allow for the exclusion or limitation of implied warranties, so the above ** limitations or exclusions may not apply to you. IBM shall not be liable for ** any damages you suffer as a result of using, copying, modifying or ** distributing the Sample, even if IBM has been advised of the possibility of ** such damages. *****************************************************************************/ package com.ibm.replication.iidr.metadata; import java.util.Iterator; import org.apache.commons.configuration.*; import org.apache.log4j.Logger; import com.datamirror.common.util.EncryptedDataException; import com.datamirror.common.util.Encryptor; public class Settings { final static Logger logger = Logger.getLogger(Settings.class.getName()); // Access Server connection parameters String asHostName = null; String asUserName = null; String asPassword = null; int asPort = 0; // Information Server metadata exchange settings String isHostName = null; String isUserName = null; String isPassword = null; int isPort = 0; String bundleFilePath = null; String defaultDataPath = ""; boolean trustSelfSignedCertificates = false; /** * Retrieve the settings from the given properties file. * * @param propertiesFile * @throws ConfigurationException */ public Settings(String propertiesFile) throws ConfigurationException { PropertiesConfiguration config = new PropertiesConfiguration(propertiesFile); asHostName = config.getString("asHostName"); asUserName = config.getString("asUserName"); String encryptedAsPassword = config.getString("asPassword"); asPort = config.getInt("asPort", 10101); isHostName = config.getString("isHostName"); isUserName = config.getString("isUserName"); String encryptedISPassword = config.getString("isPassword"); isPort = config.getInt("isPort", 10101); bundleFilePath = config.getString("bundleFilePath"); defaultDataPath = config.getString("defaultDataPath"); trustSelfSignedCertificates = config.getBoolean("trustSelfSignedCertificates"); // Check if the password has already been encrypted // If not, encrypt and save the properties try { asPassword = Encryptor.decodeAndDecrypt(encryptedAsPassword); } catch (EncryptedDataException e) { logger.debug("Encrypting asPassword"); asPassword = encryptedAsPassword; encryptedAsPassword = Encryptor.encryptAndEncode(encryptedAsPassword); config.setProperty("asPassword", encryptedAsPassword); config.save(); } try { isPassword = Encryptor.decodeAndDecrypt(encryptedISPassword); } catch (EncryptedDataException e) { logger.debug("Encrypting isPassword"); isPassword = encryptedISPassword; encryptedISPassword = Encryptor.encryptAndEncode(encryptedISPassword); config.setProperty("isPassword", encryptedISPassword); config.save(); } // Now log the settings logSettings(config); } /** * Log the properties in the specified configuration file * * @param config */ private void logSettings(PropertiesConfiguration config) { Iterator<String> configKeys = config.getKeys(); while (configKeys.hasNext()) { String configKey = configKeys.next(); logger.debug("Property: " + configKey + " = " + config.getProperty(configKey)); } } public static void main(String[] args) throws ConfigurationException, IllegalArgumentException, IllegalAccessException { new Settings("conf/ExportMetadata.properties"); } }
UTF-8
Java
4,307
java
Settings.java
Java
[ { "context": "l;\n\tString asUserName = null;\n\tString asPassword = null;\n\tint asPort = 0;\n\n\t// Information Server metadat", "end": 1753, "score": 0.909372091293335, "start": 1749, "tag": "PASSWORD", "value": "null" }, { "context": "g(\"asHostName\");\n\t\tasUserName = config.getString(\"asUserName\");\n\t\tString encryptedAsPassword = config.getStrin", "end": 2407, "score": 0.9659436941146851, "start": 2397, "tag": "USERNAME", "value": "asUserName" }, { "context": "g(\"isHostName\");\n\t\tisUserName = config.getString(\"isUserName\");\n\t\tString encryptedISPassword = config.getStrin", "end": 2608, "score": 0.9195988178253174, "start": 2598, "tag": "USERNAME", "value": "isUserName" }, { "context": "er.debug(\"Encrypting asPassword\");\n\t\t\tasPassword = encryptedAsPassword;\n\t\t\tencryptedAsPassword = Encryptor.encryptAndEnc", "end": 3203, "score": 0.9731011390686035, "start": 3184, "tag": "PASSWORD", "value": "encryptedAsPassword" }, { "context": "er.debug(\"Encrypting isPassword\");\n\t\t\tisPassword = encryptedISPassword;\n\t\t\tencryptedISPassword = Encryptor.encryptAndEnc", "end": 3549, "score": 0.8814546465873718, "start": 3530, "tag": "PASSWORD", "value": "encryptedISPassword" } ]
null
[]
/**************************************************************************** ** Licensed Materials - Property of IBM ** IBM InfoSphere Change Data Capture ** 5724-U70 ** ** (c) Copyright IBM Corp. 2001, 2016 All rights reserved. ** ** The following sample of source code ("Sample") is owned by International ** Business Machines Corporation or one of its subsidiaries ("IBM") and is ** copyrighted and licensed, not sold. You may use, copy, modify, and ** distribute the Sample for your own use in any form without payment to IBM. ** ** The Sample code is provided to you on an "AS IS" basis, without warranty of ** any kind. IBM HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR ** IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF ** MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. Some jurisdictions do ** not allow for the exclusion or limitation of implied warranties, so the above ** limitations or exclusions may not apply to you. IBM shall not be liable for ** any damages you suffer as a result of using, copying, modifying or ** distributing the Sample, even if IBM has been advised of the possibility of ** such damages. *****************************************************************************/ package com.ibm.replication.iidr.metadata; import java.util.Iterator; import org.apache.commons.configuration.*; import org.apache.log4j.Logger; import com.datamirror.common.util.EncryptedDataException; import com.datamirror.common.util.Encryptor; public class Settings { final static Logger logger = Logger.getLogger(Settings.class.getName()); // Access Server connection parameters String asHostName = null; String asUserName = null; String asPassword = <PASSWORD>; int asPort = 0; // Information Server metadata exchange settings String isHostName = null; String isUserName = null; String isPassword = null; int isPort = 0; String bundleFilePath = null; String defaultDataPath = ""; boolean trustSelfSignedCertificates = false; /** * Retrieve the settings from the given properties file. * * @param propertiesFile * @throws ConfigurationException */ public Settings(String propertiesFile) throws ConfigurationException { PropertiesConfiguration config = new PropertiesConfiguration(propertiesFile); asHostName = config.getString("asHostName"); asUserName = config.getString("asUserName"); String encryptedAsPassword = config.getString("asPassword"); asPort = config.getInt("asPort", 10101); isHostName = config.getString("isHostName"); isUserName = config.getString("isUserName"); String encryptedISPassword = config.getString("isPassword"); isPort = config.getInt("isPort", 10101); bundleFilePath = config.getString("bundleFilePath"); defaultDataPath = config.getString("defaultDataPath"); trustSelfSignedCertificates = config.getBoolean("trustSelfSignedCertificates"); // Check if the password has already been encrypted // If not, encrypt and save the properties try { asPassword = Encryptor.decodeAndDecrypt(encryptedAsPassword); } catch (EncryptedDataException e) { logger.debug("Encrypting asPassword"); asPassword = <PASSWORD>; encryptedAsPassword = Encryptor.encryptAndEncode(encryptedAsPassword); config.setProperty("asPassword", encryptedAsPassword); config.save(); } try { isPassword = Encryptor.decodeAndDecrypt(encryptedISPassword); } catch (EncryptedDataException e) { logger.debug("Encrypting isPassword"); isPassword = <PASSWORD>; encryptedISPassword = Encryptor.encryptAndEncode(encryptedISPassword); config.setProperty("isPassword", encryptedISPassword); config.save(); } // Now log the settings logSettings(config); } /** * Log the properties in the specified configuration file * * @param config */ private void logSettings(PropertiesConfiguration config) { Iterator<String> configKeys = config.getKeys(); while (configKeys.hasNext()) { String configKey = configKeys.next(); logger.debug("Property: " + configKey + " = " + config.getProperty(configKey)); } } public static void main(String[] args) throws ConfigurationException, IllegalArgumentException, IllegalAccessException { new Settings("conf/ExportMetadata.properties"); } }
4,295
0.723009
0.71674
122
34.30328
27.87851
84
false
false
0
0
0
0
0
0
1.606557
false
false
10
4672f69bf7c8f8d93502ed842df05b9a05c25fa0
9,019,431,372,459
8055d02b19a28380e7c26f83b3f47233dea2f0a1
/src/main/java/us/fibernet/fiberj/TiffWriter.java
8ac566981a60de3c51a5eef219076ef99f08fef9
[]
no_license
fibernet-us/FiberJ
https://github.com/fibernet-us/FiberJ
34a7fdc585c10aaa0d073bcf8e2b7720263680bb
6c59aae7edab98151ccd76bcdf4e3f72d78cc20c
refs/heads/master
2021-01-21T21:48:08.407000
2016-04-17T20:32:17
2016-04-17T20:32:17
4,438,271
1
2
null
false
2016-04-17T20:30:58
2012-05-24T21:29:41
2016-04-17T20:21:02
2016-04-17T20:30:58
404
4
3
0
Java
null
null
/* * Copyright Billy Zheng. All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, this list * of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer listed in this license in the * documentation and/or other materials provided with the distribution. * * - Neither the name of the copyright holders nor the names of its contributors may * be used to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL * THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package us.fibernet.fiberj; import java.io.DataOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; /** * A class for writing TIFF images. Currently only supports 16-bit gray-scale TIFF. */ public final class TiffWriter { private TiffWriter() { } /** * write a 16-bit TIFF image */ public static final boolean writeImage(int w, int h, byte[] pixels, String filename) { try { DataOutputStream dos = new DataOutputStream(new FileOutputStream(new File(filename))); if(!writeHeader(dos, w, h, pixels.length)) { dos.close(); return false; } dos.write(pixels); dos.close(); return true; } catch (IOException e) { e.printStackTrace(); return false; } } /* * only write 10 essential tags */ private static boolean writeHeader(DataOutputStream dos, int width, int height, int bytes) { // data type final short BYTE = 1; final short ASCII = 2; final short SHORT = 3; final short LONG = 4; final short RATIONAL = 5; // tiff info final short TIFF_MAGIC_NUMBER = 42; final byte[] TIFF_BYTEORDER = {'M', 'M'}; // big endian // tag number final short NEW_SUBFILE_TYPE = 254; final short IMAGE_WIDTH = 256; final short IMAGE_LENGTH = 257; final short BITS_PER_SAMPLE = 258; final short COMPRESSION = 259; final short PHOTOMETRIC_INTERPOLATION = 262; final short STRIP_OFFSETS = 273; final short SAMPLES_PER_PIXEL = 277; final short ROWS_PER_STRIP = 278; final short STRIP_BYTE_COUNTS = 279; final short NTAGS = 10; final int HEADER_FIRST_OFFSET = 8; final int HEADER_SIZE = 8 + 2 + 12 * NTAGS + 4; try { dos.write(TIFF_BYTEORDER); dos.writeShort(TIFF_MAGIC_NUMBER); dos.writeInt(HEADER_FIRST_OFFSET); dos.writeShort(NTAGS); dos.writeShort(NEW_SUBFILE_TYPE); // 254 dos.writeShort(LONG); dos.writeInt(1); dos.writeInt(0); dos.writeShort(IMAGE_WIDTH); // 256 dos.writeShort(LONG); dos.writeInt(1); dos.writeInt(width); dos.writeShort(IMAGE_LENGTH); // 257 dos.writeShort(LONG); dos.writeInt(1); dos.writeInt(height); dos.writeShort(BITS_PER_SAMPLE); // 258 dos.writeShort(SHORT); dos.writeInt(1); dos.writeInt(0x00100000); // 16 dos.writeShort(COMPRESSION); // 259 dos.writeShort(SHORT); dos.writeInt(1); dos.writeInt(0x00010000); // no compression dos.writeShort(PHOTOMETRIC_INTERPOLATION); // 262 dos.writeShort(SHORT); dos.writeInt(1); dos.writeInt(0x00010000); // 1, black is 0, grayscale dos.writeShort(STRIP_OFFSETS); // 273 dos.writeShort(LONG); dos.writeInt(1); dos.writeInt(HEADER_SIZE); dos.writeShort(SAMPLES_PER_PIXEL); // 277 dos.writeShort(SHORT); dos.writeInt(1); dos.writeInt(0x00010000); // 1 dos.writeShort(ROWS_PER_STRIP); dos.writeShort(SHORT); dos.writeInt(1); dos.writeShort(height); dos.writeShort(0); dos.writeShort(STRIP_BYTE_COUNTS); dos.writeShort(LONG); dos.writeInt(1); dos.writeInt(bytes); dos.writeInt(0); // end of tags return true; } catch (IOException e) { e.printStackTrace(); return false; } } }
UTF-8
Java
5,531
java
TiffWriter.java
Java
[ { "context": "/*\n * Copyright Billy Zheng. All rights reserved.\n *\n * Redistribution and us", "end": 27, "score": 0.999793529510498, "start": 16, "tag": "NAME", "value": "Billy Zheng" } ]
null
[]
/* * Copyright <NAME>. All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, this list * of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer listed in this license in the * documentation and/or other materials provided with the distribution. * * - Neither the name of the copyright holders nor the names of its contributors may * be used to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL * THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package us.fibernet.fiberj; import java.io.DataOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; /** * A class for writing TIFF images. Currently only supports 16-bit gray-scale TIFF. */ public final class TiffWriter { private TiffWriter() { } /** * write a 16-bit TIFF image */ public static final boolean writeImage(int w, int h, byte[] pixels, String filename) { try { DataOutputStream dos = new DataOutputStream(new FileOutputStream(new File(filename))); if(!writeHeader(dos, w, h, pixels.length)) { dos.close(); return false; } dos.write(pixels); dos.close(); return true; } catch (IOException e) { e.printStackTrace(); return false; } } /* * only write 10 essential tags */ private static boolean writeHeader(DataOutputStream dos, int width, int height, int bytes) { // data type final short BYTE = 1; final short ASCII = 2; final short SHORT = 3; final short LONG = 4; final short RATIONAL = 5; // tiff info final short TIFF_MAGIC_NUMBER = 42; final byte[] TIFF_BYTEORDER = {'M', 'M'}; // big endian // tag number final short NEW_SUBFILE_TYPE = 254; final short IMAGE_WIDTH = 256; final short IMAGE_LENGTH = 257; final short BITS_PER_SAMPLE = 258; final short COMPRESSION = 259; final short PHOTOMETRIC_INTERPOLATION = 262; final short STRIP_OFFSETS = 273; final short SAMPLES_PER_PIXEL = 277; final short ROWS_PER_STRIP = 278; final short STRIP_BYTE_COUNTS = 279; final short NTAGS = 10; final int HEADER_FIRST_OFFSET = 8; final int HEADER_SIZE = 8 + 2 + 12 * NTAGS + 4; try { dos.write(TIFF_BYTEORDER); dos.writeShort(TIFF_MAGIC_NUMBER); dos.writeInt(HEADER_FIRST_OFFSET); dos.writeShort(NTAGS); dos.writeShort(NEW_SUBFILE_TYPE); // 254 dos.writeShort(LONG); dos.writeInt(1); dos.writeInt(0); dos.writeShort(IMAGE_WIDTH); // 256 dos.writeShort(LONG); dos.writeInt(1); dos.writeInt(width); dos.writeShort(IMAGE_LENGTH); // 257 dos.writeShort(LONG); dos.writeInt(1); dos.writeInt(height); dos.writeShort(BITS_PER_SAMPLE); // 258 dos.writeShort(SHORT); dos.writeInt(1); dos.writeInt(0x00100000); // 16 dos.writeShort(COMPRESSION); // 259 dos.writeShort(SHORT); dos.writeInt(1); dos.writeInt(0x00010000); // no compression dos.writeShort(PHOTOMETRIC_INTERPOLATION); // 262 dos.writeShort(SHORT); dos.writeInt(1); dos.writeInt(0x00010000); // 1, black is 0, grayscale dos.writeShort(STRIP_OFFSETS); // 273 dos.writeShort(LONG); dos.writeInt(1); dos.writeInt(HEADER_SIZE); dos.writeShort(SAMPLES_PER_PIXEL); // 277 dos.writeShort(SHORT); dos.writeInt(1); dos.writeInt(0x00010000); // 1 dos.writeShort(ROWS_PER_STRIP); dos.writeShort(SHORT); dos.writeInt(1); dos.writeShort(height); dos.writeShort(0); dos.writeShort(STRIP_BYTE_COUNTS); dos.writeShort(LONG); dos.writeInt(1); dos.writeInt(bytes); dos.writeInt(0); // end of tags return true; } catch (IOException e) { e.printStackTrace(); return false; } } }
5,526
0.602242
0.578919
166
32.319279
26.128054
98
false
false
0
0
0
0
0
0
0.698795
false
false
10
5ac55654660b6dd701fbba872a97ff480f69ff2b
15,066,745,317,157
23db407e110a415f6a1fe8503a671023de88009f
/src/com/ahmad/Views/View.java
8886d972ef74f6ed83d8039f969be7c911d6591c
[]
no_license
Develorain/Coupled-Motion-Simulator
https://github.com/Develorain/Coupled-Motion-Simulator
21ae85ab7750a8f3afeb24bea32a8eef61704f7d
9f07a5e73978176988b7edfd86cfc5d40fce67c7
refs/heads/master
2021-01-19T12:31:04.684000
2021-01-08T22:05:39
2021-01-08T22:05:39
82,340,814
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.ahmad.Views; /** View * General implementable View interface in the MVC pattern * @since January 18, 2017 * @author Ahmad Gharib */ public interface View { /** Gets data from the model and updates the view */ void update(); /** Repaints the view */ void repaint(); }
UTF-8
Java
302
java
View.java
Java
[ { "context": " MVC pattern\n * @since January 18, 2017\n * @author Ahmad Gharib\n */\n\npublic interface View {\n /** Gets data fr", "end": 144, "score": 0.9998677372932434, "start": 132, "tag": "NAME", "value": "Ahmad Gharib" } ]
null
[]
package com.ahmad.Views; /** View * General implementable View interface in the MVC pattern * @since January 18, 2017 * @author <NAME> */ public interface View { /** Gets data from the model and updates the view */ void update(); /** Repaints the view */ void repaint(); }
296
0.65894
0.639073
15
19.133333
18.00321
58
false
false
0
0
0
0
0
0
0.266667
false
false
10
1368f99a75e3c95188b79ed3bed56dce7d38faf0
3,547,643,001,020
c287be8c7c56240fd4a21a714b44b4d7f6949cdc
/src/de/hexagonsoftware/abec/package-info.java
c26abec67f58886a96665ad21e4f6c8bf2c3e61d
[]
no_license
hexagon-software/BulletinBoardSystem
https://github.com/hexagon-software/BulletinBoardSystem
b47820286fdb0ea715e67369fa6d3e2c3277751d
198049150952203103694ae1a90e503e8460ef3c
refs/heads/master
2023-05-25T15:26:55.773000
2021-06-15T17:07:23
2021-06-15T17:07:23
377,197,096
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * Common Package of Bulletin Board system. * This package and subpackage should only contain code that * is relevant to both the server and the client. * * @author Felix Eckert * */ package de.hexagonsoftware.abec;
UTF-8
Java
224
java
package-info.java
Java
[ { "context": "t to both the server and the client.\n *\n * @author Felix Eckert\n * */\npackage de.hexagonsoftware.abec;", "end": 185, "score": 0.9998070001602173, "start": 173, "tag": "NAME", "value": "Felix Eckert" } ]
null
[]
/** * Common Package of Bulletin Board system. * This package and subpackage should only contain code that * is relevant to both the server and the client. * * @author <NAME> * */ package de.hexagonsoftware.abec;
218
0.736607
0.736607
8
27.125
21.079834
60
false
false
0
0
0
0
0
0
0.125
false
false
10
7749f08ecc3bc152284f2709d1d28391a2d45abd
13,915,694,107,787
49bada98ab00313f386a81bca1e3e22fc7d5288f
/src/main/java/me/sapien/plugin/sapien/Util/CCommand.java
ffcf9169cad6074f419c4a47b30d00c8cc065819
[]
no_license
fdemir/sapien
https://github.com/fdemir/sapien
80015f3ed6df49f37567ad0e2bacbabd76ca0856
9f8b436fa6754baf6a259914e3170ea0acc03d66
refs/heads/master
2022-09-20T07:02:23.166000
2020-05-30T01:43:25
2020-05-30T01:43:25
267,301,313
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package me.sapien.plugin.sapien.Util; import java.util.Arrays; import me.sapien.plugin.sapien.Sapien; import org.bukkit.ChatColor; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.command.PluginIdentifiableCommand; import org.bukkit.plugin.Plugin; public abstract class CCommand extends Command implements PluginIdentifiableCommand{ CommandSender sender; protected CCommand(String name) { super(name); } @Override public Plugin getPlugin() { return Sapien.getInstance(); } public abstract void run(CommandSender sender, String commandLabel, String[] arguments);//Just simpler and allows 'return;' instead of 'return true/false;' @Override public boolean execute(CommandSender sender, String commandLabel, String[] arguments) { this.sender = sender; run(sender, commandLabel, arguments); return true; } }
UTF-8
Java
937
java
CCommand.java
Java
[]
null
[]
package me.sapien.plugin.sapien.Util; import java.util.Arrays; import me.sapien.plugin.sapien.Sapien; import org.bukkit.ChatColor; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.command.PluginIdentifiableCommand; import org.bukkit.plugin.Plugin; public abstract class CCommand extends Command implements PluginIdentifiableCommand{ CommandSender sender; protected CCommand(String name) { super(name); } @Override public Plugin getPlugin() { return Sapien.getInstance(); } public abstract void run(CommandSender sender, String commandLabel, String[] arguments);//Just simpler and allows 'return;' instead of 'return true/false;' @Override public boolean execute(CommandSender sender, String commandLabel, String[] arguments) { this.sender = sender; run(sender, commandLabel, arguments); return true; } }
937
0.733191
0.733191
33
27.39394
32.493298
159
false
false
0
0
0
0
0
0
0.69697
false
false
10
d29c3399fc53ee50dae667748d4f4a7213e8fe21
22,883,585,756,991
103979c8aae562e11e60abcc780378042e488935
/permission/src/main/java/com/sdg/permission/AbsPermissionCallback.java
296521e2ca0f5f13f2fa4f9086274c7b140b7985
[]
no_license
sdgSnow/AndroidLibrary
https://github.com/sdgSnow/AndroidLibrary
8ebb702cb43450ee7e64790deb9c786c365683e4
6aec17faceecd0872245a00c9e88c9b7adeef15e
refs/heads/master
2023-07-10T06:44:32.551000
2021-08-10T05:42:20
2021-08-10T05:42:20
392,156,626
3
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.sdg.permission; import com.dimeno.permission.callback.PermissionCallback; public abstract class AbsPermissionCallback implements PermissionCallback { @Override public void onGrant(String[] permissions) { } }
UTF-8
Java
244
java
AbsPermissionCallback.java
Java
[]
null
[]
package com.sdg.permission; import com.dimeno.permission.callback.PermissionCallback; public abstract class AbsPermissionCallback implements PermissionCallback { @Override public void onGrant(String[] permissions) { } }
244
0.754098
0.754098
11
21.181818
25.469477
75
false
false
0
0
0
0
0
0
0.181818
false
false
10
a4bb25444f95d49e4347be8d00ccffb95230629b
36,103,495,121,784
aa168494d968c1f6e5fa6981cd3f4c0bc081fa7e
/_src/lesson-1/src/main/java/com/readlearncode/lesson1/section3/subsection1/ArrayDeclaration.java
fbf5c2b4ec5f2f80d12166eb56b7c24c0a1801dc
[ "Apache-2.0" ]
permissive
paullewallencom/java-978-1-7882-9773-8
https://github.com/paullewallencom/java-978-1-7882-9773-8
42f14fc52e8280df3801f0772e6c0da91c398f85
7c5f2d2ada7c1a4560e271c872e962d985969838
refs/heads/main
2023-02-07T13:57:06.281000
2020-12-28T04:20:30
2020-12-28T04:20:30
319,404,253
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.readlearncode.lesson1.section3.subsection1; /** * Source code github.com/readlearncode * * @author Alex Theedom www.readlearncode.com * @version 1.0 */ public class ArrayDeclaration { public void callAMethod(){ aMethodCall(new int[]{200, 100, 50}); } public void aMethodCall(int[] scores){ // Do something } }
UTF-8
Java
366
java
ArrayDeclaration.java
Java
[ { "context": "tion3.subsection1;\n\n/**\n * Source code github.com/readlearncode\n *\n * @author Alex Theedom www.readlearncode.com\n", "end": 100, "score": 0.9972624182701111, "start": 87, "tag": "USERNAME", "value": "readlearncode" }, { "context": "Source code github.com/readlearncode\n *\n * @author Alex Theedom www.readlearncode.com\n * @version 1.0\n */\npublic ", "end": 127, "score": 0.9998152256011963, "start": 115, "tag": "NAME", "value": "Alex Theedom" } ]
null
[]
package com.readlearncode.lesson1.section3.subsection1; /** * Source code github.com/readlearncode * * @author <NAME> www.readlearncode.com * @version 1.0 */ public class ArrayDeclaration { public void callAMethod(){ aMethodCall(new int[]{200, 100, 50}); } public void aMethodCall(int[] scores){ // Do something } }
360
0.655738
0.620219
23
14.956522
18.536634
55
false
false
0
0
0
0
0
0
0.173913
false
false
10
a1ed4310ea505d0bc6878ae43815e7fdc7e51392
22,668,837,453,892
a7a5ea1965def34f212d0799e5957faf198aa3a3
/android/FFmpeg/library/src/main/java/com/wlanjie/ffmpeg/video/RendererScreen.java
a5fe178e3ba8b8d6da9fa4c1e03684d0cc91675c
[]
no_license
18307612949/AndroidFFmpeg
https://github.com/18307612949/AndroidFFmpeg
dc911355659b953c893ff4af54d304505b0c552e
a91b480e530957cfe3b3d455e8a0594bc7578c35
refs/heads/master
2021-08-16T06:13:14.412000
2017-10-16T07:42:27
2017-10-16T07:42:27
107,400,346
1
0
null
true
2017-10-18T11:44:03
2017-10-18T11:44:02
2017-10-16T21:46:15
2017-10-16T07:51:03
231,380
0
0
0
null
null
null
package com.wlanjie.ffmpeg.video; import android.content.Context; import android.content.res.Resources; import android.opengl.GLES20; import com.wlanjie.ffmpeg.library.R; import com.wlanjie.ffmpeg.util.OpenGLUtils; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.FloatBuffer; import java.nio.IntBuffer; /** * Created by wlanjie on 2017/5/25. */ public class RendererScreen { private final FloatBuffer mCubeBuffer; private final FloatBuffer mTextureBuffer; // screen private int mScreenProgramId; private int mScreenPosition; private int mScreenUniformTexture; private int mScreenTextureCoordinate; private int mWidth; private int mHeight; private int mInputWidth; private int mInputHeight; private int mFboId; private IntBuffer mFboBuffer; private Resources mResources; private final FloatBuffer mReadPixelTextureBuffer; private final float[] TEXTURE_BUFFER = { 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f }; public RendererScreen(Context context) { mResources = context.getResources(); mCubeBuffer = ByteBuffer.allocateDirect(OpenGLUtils.CUBE.length * 4) .order(ByteOrder.nativeOrder()) .asFloatBuffer(); mCubeBuffer.put(OpenGLUtils.CUBE).position(0); mTextureBuffer = ByteBuffer.allocateDirect(OpenGLUtils.TEXTURE.length * 4) .order(ByteOrder.nativeOrder()) .asFloatBuffer(); mTextureBuffer.put(OpenGLUtils.TEXTURE).position(0); mReadPixelTextureBuffer = ByteBuffer.allocateDirect(TEXTURE_BUFFER.length * 4) .order(ByteOrder.nativeOrder()) .asFloatBuffer(); mReadPixelTextureBuffer.put(TEXTURE_BUFFER).position(0); } public void init() { mScreenProgramId = OpenGLUtils.loadProgram(OpenGLUtils.readSharedFromRawResource(mResources, R.raw.vertex_default), OpenGLUtils.readSharedFromRawResource(mResources, R.raw.fragment_default)); mScreenPosition = GLES20.glGetAttribLocation(mScreenProgramId, "position"); mScreenUniformTexture = GLES20.glGetUniformLocation(mScreenProgramId, "inputImageTexture"); mScreenTextureCoordinate = GLES20.glGetAttribLocation(mScreenProgramId, "inputTextureCoordinate"); } void setDisplaySize(int width, int height) { mWidth = width; mHeight = height; } void setInputSize(int width, int height) { if (mFboId != 0 && width != mInputWidth && height != mInputHeight) { destroyFboTexture(); } mFboBuffer = IntBuffer.allocate(width * height); mInputHeight = height; mInputWidth = width; int[] fbo = new int[1]; GLES20.glGenFramebuffers(1, fbo, 0); mFboId = fbo[0]; } private void destroyFboTexture() { if (mFboId != 0) { GLES20.glDeleteFramebuffers(1, new int[] { mFboId }, 0); } } public void draw(int textureId, FloatBuffer cubeBuffer, FloatBuffer textureBuffer) { GLES20.glUseProgram(mScreenProgramId); GLES20.glViewport(0, 0, mWidth, mHeight); GLES20.glActiveTexture(GLES20.GL_TEXTURE0); GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, textureId); GLES20.glUniform1i(mScreenUniformTexture, 0); GLES20.glEnableVertexAttribArray(mScreenPosition); GLES20.glVertexAttribPointer(mScreenPosition, 2, GLES20.GL_FLOAT, false, 4 * 2, cubeBuffer); GLES20.glEnableVertexAttribArray(mScreenTextureCoordinate); GLES20.glVertexAttribPointer(mScreenTextureCoordinate, 2, GLES20.GL_FLOAT, false, 4 * 2, textureBuffer); GLES20.glDrawArrays(GLES20.GL_TRIANGLE_STRIP, 0, 4); GLES20.glDisableVertexAttribArray(mScreenPosition); GLES20.glDisableVertexAttribArray(mScreenTextureCoordinate); GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, 0); GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, 0); } public void readPixel(int textureId) { GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, textureId); GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, mFboId); GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_LINEAR); GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_LINEAR); GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_S, GLES20.GL_CLAMP_TO_EDGE); GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_T, GLES20.GL_CLAMP_TO_EDGE); GLES20.glFramebufferTexture2D(GLES20.GL_FRAMEBUFFER, GLES20.GL_COLOR_ATTACHMENT0, GLES20.GL_TEXTURE_2D, textureId, 0); GLES20.glUseProgram(mScreenProgramId); GLES20.glViewport(0, 0, mInputWidth, mInputHeight); GLES20.glActiveTexture(GLES20.GL_TEXTURE0); GLES20.glUniform1i(mScreenUniformTexture, 0); GLES20.glEnableVertexAttribArray(mScreenPosition); GLES20.glVertexAttribPointer(mScreenPosition, 2, GLES20.GL_FLOAT, false, 4 * 2, mCubeBuffer); GLES20.glEnableVertexAttribArray(mScreenTextureCoordinate); GLES20.glVertexAttribPointer(mScreenTextureCoordinate, 2, GLES20.GL_FLOAT, false, 4 * 2, mTextureBuffer); GLES20.glDrawArrays(GLES20.GL_TRIANGLE_STRIP, 0, 4); GLES20.glReadPixels(0, 0, mInputWidth, mInputHeight, GLES20.GL_RGBA, GLES20.GL_UNSIGNED_BYTE, mFboBuffer); GLES20.glDisableVertexAttribArray(mScreenPosition); GLES20.glDisableVertexAttribArray(mScreenTextureCoordinate); GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, 0); GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, 0); } public IntBuffer getFboBuffer() { return mFboBuffer; } public void draw(int textureId) { draw(textureId, mCubeBuffer, mTextureBuffer); } public void destroy() { GLES20.glDeleteProgram(mScreenProgramId); } public void updateTextureCoordinate(float[] textureCords) { mTextureBuffer.clear(); mTextureBuffer.put(textureCords).position(0); } }
UTF-8
Java
5,710
java
RendererScreen.java
Java
[ { "context": "fer;\nimport java.nio.IntBuffer;\n\n/**\n * Created by wlanjie on 2017/5/25.\n */\n\npublic class RendererScreen {\n", "end": 355, "score": 0.9996353983879089, "start": 348, "tag": "USERNAME", "value": "wlanjie" } ]
null
[]
package com.wlanjie.ffmpeg.video; import android.content.Context; import android.content.res.Resources; import android.opengl.GLES20; import com.wlanjie.ffmpeg.library.R; import com.wlanjie.ffmpeg.util.OpenGLUtils; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.FloatBuffer; import java.nio.IntBuffer; /** * Created by wlanjie on 2017/5/25. */ public class RendererScreen { private final FloatBuffer mCubeBuffer; private final FloatBuffer mTextureBuffer; // screen private int mScreenProgramId; private int mScreenPosition; private int mScreenUniformTexture; private int mScreenTextureCoordinate; private int mWidth; private int mHeight; private int mInputWidth; private int mInputHeight; private int mFboId; private IntBuffer mFboBuffer; private Resources mResources; private final FloatBuffer mReadPixelTextureBuffer; private final float[] TEXTURE_BUFFER = { 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f }; public RendererScreen(Context context) { mResources = context.getResources(); mCubeBuffer = ByteBuffer.allocateDirect(OpenGLUtils.CUBE.length * 4) .order(ByteOrder.nativeOrder()) .asFloatBuffer(); mCubeBuffer.put(OpenGLUtils.CUBE).position(0); mTextureBuffer = ByteBuffer.allocateDirect(OpenGLUtils.TEXTURE.length * 4) .order(ByteOrder.nativeOrder()) .asFloatBuffer(); mTextureBuffer.put(OpenGLUtils.TEXTURE).position(0); mReadPixelTextureBuffer = ByteBuffer.allocateDirect(TEXTURE_BUFFER.length * 4) .order(ByteOrder.nativeOrder()) .asFloatBuffer(); mReadPixelTextureBuffer.put(TEXTURE_BUFFER).position(0); } public void init() { mScreenProgramId = OpenGLUtils.loadProgram(OpenGLUtils.readSharedFromRawResource(mResources, R.raw.vertex_default), OpenGLUtils.readSharedFromRawResource(mResources, R.raw.fragment_default)); mScreenPosition = GLES20.glGetAttribLocation(mScreenProgramId, "position"); mScreenUniformTexture = GLES20.glGetUniformLocation(mScreenProgramId, "inputImageTexture"); mScreenTextureCoordinate = GLES20.glGetAttribLocation(mScreenProgramId, "inputTextureCoordinate"); } void setDisplaySize(int width, int height) { mWidth = width; mHeight = height; } void setInputSize(int width, int height) { if (mFboId != 0 && width != mInputWidth && height != mInputHeight) { destroyFboTexture(); } mFboBuffer = IntBuffer.allocate(width * height); mInputHeight = height; mInputWidth = width; int[] fbo = new int[1]; GLES20.glGenFramebuffers(1, fbo, 0); mFboId = fbo[0]; } private void destroyFboTexture() { if (mFboId != 0) { GLES20.glDeleteFramebuffers(1, new int[] { mFboId }, 0); } } public void draw(int textureId, FloatBuffer cubeBuffer, FloatBuffer textureBuffer) { GLES20.glUseProgram(mScreenProgramId); GLES20.glViewport(0, 0, mWidth, mHeight); GLES20.glActiveTexture(GLES20.GL_TEXTURE0); GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, textureId); GLES20.glUniform1i(mScreenUniformTexture, 0); GLES20.glEnableVertexAttribArray(mScreenPosition); GLES20.glVertexAttribPointer(mScreenPosition, 2, GLES20.GL_FLOAT, false, 4 * 2, cubeBuffer); GLES20.glEnableVertexAttribArray(mScreenTextureCoordinate); GLES20.glVertexAttribPointer(mScreenTextureCoordinate, 2, GLES20.GL_FLOAT, false, 4 * 2, textureBuffer); GLES20.glDrawArrays(GLES20.GL_TRIANGLE_STRIP, 0, 4); GLES20.glDisableVertexAttribArray(mScreenPosition); GLES20.glDisableVertexAttribArray(mScreenTextureCoordinate); GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, 0); GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, 0); } public void readPixel(int textureId) { GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, textureId); GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, mFboId); GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_LINEAR); GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_LINEAR); GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_S, GLES20.GL_CLAMP_TO_EDGE); GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_T, GLES20.GL_CLAMP_TO_EDGE); GLES20.glFramebufferTexture2D(GLES20.GL_FRAMEBUFFER, GLES20.GL_COLOR_ATTACHMENT0, GLES20.GL_TEXTURE_2D, textureId, 0); GLES20.glUseProgram(mScreenProgramId); GLES20.glViewport(0, 0, mInputWidth, mInputHeight); GLES20.glActiveTexture(GLES20.GL_TEXTURE0); GLES20.glUniform1i(mScreenUniformTexture, 0); GLES20.glEnableVertexAttribArray(mScreenPosition); GLES20.glVertexAttribPointer(mScreenPosition, 2, GLES20.GL_FLOAT, false, 4 * 2, mCubeBuffer); GLES20.glEnableVertexAttribArray(mScreenTextureCoordinate); GLES20.glVertexAttribPointer(mScreenTextureCoordinate, 2, GLES20.GL_FLOAT, false, 4 * 2, mTextureBuffer); GLES20.glDrawArrays(GLES20.GL_TRIANGLE_STRIP, 0, 4); GLES20.glReadPixels(0, 0, mInputWidth, mInputHeight, GLES20.GL_RGBA, GLES20.GL_UNSIGNED_BYTE, mFboBuffer); GLES20.glDisableVertexAttribArray(mScreenPosition); GLES20.glDisableVertexAttribArray(mScreenTextureCoordinate); GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, 0); GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, 0); } public IntBuffer getFboBuffer() { return mFboBuffer; } public void draw(int textureId) { draw(textureId, mCubeBuffer, mTextureBuffer); } public void destroy() { GLES20.glDeleteProgram(mScreenProgramId); } public void updateTextureCoordinate(float[] textureCords) { mTextureBuffer.clear(); mTextureBuffer.put(textureCords).position(0); } }
5,710
0.747986
0.707706
154
36.077923
32.2038
195
false
false
0
0
0
0
0
0
1.077922
false
false
3
77828dc9f9f075b0873e5d3eb8c656643233fb5a
4,595,615,057,854
a5fcabebf949f626ea0f3f06ec19d569905b7f6d
/app/src/main/java/com/example/json_file_parsing/MainActivity.java
e3ceff8fff4484e13e1514dcd66dabcea82381cc
[]
no_license
monikakambojofficial96/json-file-parsing
https://github.com/monikakambojofficial96/json-file-parsing
fdf0c1a0d99323a17b29c6f7138bc5548650c108
99704a037086c448760417f165752f7b3f5d088e
refs/heads/master
2021-01-02T05:28:44.350000
2020-02-10T12:44:33
2020-02-10T12:44:33
239,509,540
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.json_file_parsing; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.os.Bundle; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; public class MainActivity extends AppCompatActivity { ArrayList<Country> countryNames = new ArrayList<>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); RecyclerView recyclerView=findViewById(R.id.recyclerView); recyclerView.setLayoutManager(new LinearLayoutManager(this)); try { String json= loadJSONFromAsset(); // create a json object JSONArray countryarray = new JSONArray(json); for(int i=0;i<countryarray.length();i++){ JSONObject countrydetail = countryarray.getJSONObject(i); Country country=new Country(countrydetail.getString("name"),""); countryNames.add(country); } } catch (JSONException e) { e.printStackTrace(); } CountryAdapter customAdapter = new CountryAdapter(MainActivity.this, countryNames); recyclerView.setAdapter(customAdapter); // set the Adapter to RecyclerView } public String loadJSONFromAsset() { try { InputStream is = getAssets().open("country.json"); int size = is.available(); byte[] buffer = new byte[size]; is.read(buffer); is.close(); return new String(buffer, "UTF-8"); } catch (IOException ex) { ex.printStackTrace(); return null; } } }
UTF-8
Java
1,933
java
MainActivity.java
Java
[]
null
[]
package com.example.json_file_parsing; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.os.Bundle; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; public class MainActivity extends AppCompatActivity { ArrayList<Country> countryNames = new ArrayList<>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); RecyclerView recyclerView=findViewById(R.id.recyclerView); recyclerView.setLayoutManager(new LinearLayoutManager(this)); try { String json= loadJSONFromAsset(); // create a json object JSONArray countryarray = new JSONArray(json); for(int i=0;i<countryarray.length();i++){ JSONObject countrydetail = countryarray.getJSONObject(i); Country country=new Country(countrydetail.getString("name"),""); countryNames.add(country); } } catch (JSONException e) { e.printStackTrace(); } CountryAdapter customAdapter = new CountryAdapter(MainActivity.this, countryNames); recyclerView.setAdapter(customAdapter); // set the Adapter to RecyclerView } public String loadJSONFromAsset() { try { InputStream is = getAssets().open("country.json"); int size = is.available(); byte[] buffer = new byte[size]; is.read(buffer); is.close(); return new String(buffer, "UTF-8"); } catch (IOException ex) { ex.printStackTrace(); return null; } } }
1,933
0.640973
0.639938
80
23.15
24.966528
91
false
false
0
0
0
0
0
0
0.4625
false
false
3
dcacf97fe955f1519bbfc07ba9910c75e111da0e
25,366,076,857,896
cec23780a70e7ac2e48f5b1721bf3cede10448e1
/app/src/main/java/assignment02/csc214/project2/Comment/CommentHolder.java
0b57b8b5cf4adba54c2d3ed6877453a14d028a5f
[]
no_license
kagusi/CSC214_AndroidDev_Project2
https://github.com/kagusi/CSC214_AndroidDev_Project2
90207a5a98065ebfbc859ba5334ac21680f6538a
609c9f199ef1cb95c6edbfe1f58130880b1e9131
refs/heads/master
2021-01-21T18:49:44.550000
2017-05-22T18:02:43
2017-05-22T18:02:43
92,082,804
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package assignment02.csc214.project2.Comment; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.support.v7.widget.RecyclerView; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import assignment02.csc214.project2.Models.Comment; import assignment02.csc214.project2.R; /** * Created by Kennedy on 4/8/2017. */ public class CommentHolder extends RecyclerView.ViewHolder { private ImageView mProfileImage; private TextView mFullNameTextView; private TextView mCommentTextView; private TextView mDateTextView; private Comment mComment; public CommentHolder(View itemView) { super(itemView); mProfileImage = (ImageView)itemView.findViewById(R.id.Comment_PosterImage); mFullNameTextView = (TextView)itemView.findViewById(R.id.Comment_PosterName); mCommentTextView = (TextView)itemView.findViewById(R.id.Comment_DisplayCommentTextView); mDateTextView = (TextView)itemView.findViewById(R.id.Comment_DateCommentedTextView); } public void bind(Comment comment) { mComment = comment; displayPic(); mFullNameTextView.setText(comment.getFullName()); mCommentTextView.setText(comment.getComment()); mDateTextView.setText(comment.getDate()); } public void displayPic() { String mImageUrl = mComment.getCommenterProfilePicLocation(); if(!mImageUrl.isEmpty()) { Bitmap bitmap = getScaledBitmap(mImageUrl, mProfileImage.getWidth(), mProfileImage.getMaxHeight()); mProfileImage.setImageBitmap(bitmap); } } public Bitmap getScaledBitmap(String path, int width, int height) { BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeFile(path, options); float srcWidth = options.outWidth; float srcHeight = options.outHeight; int sampleSize = 1; if(srcHeight > height || srcWidth > width ) { if(srcWidth > srcHeight) { sampleSize = Math.round(srcHeight / height); } else { sampleSize = Math.round(srcWidth / width); } } BitmapFactory.Options scaledOptions = new BitmapFactory.Options(); scaledOptions.inSampleSize = sampleSize; return BitmapFactory.decodeFile(path, scaledOptions); } }
UTF-8
Java
2,519
java
CommentHolder.java
Java
[ { "context": "assignment02.csc214.project2.R;\n\n/**\n * Created by Kennedy on 4/8/2017.\n */\n\npublic class CommentHolder exte", "end": 374, "score": 0.9947174191474915, "start": 367, "tag": "USERNAME", "value": "Kennedy" } ]
null
[]
package assignment02.csc214.project2.Comment; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.support.v7.widget.RecyclerView; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import assignment02.csc214.project2.Models.Comment; import assignment02.csc214.project2.R; /** * Created by Kennedy on 4/8/2017. */ public class CommentHolder extends RecyclerView.ViewHolder { private ImageView mProfileImage; private TextView mFullNameTextView; private TextView mCommentTextView; private TextView mDateTextView; private Comment mComment; public CommentHolder(View itemView) { super(itemView); mProfileImage = (ImageView)itemView.findViewById(R.id.Comment_PosterImage); mFullNameTextView = (TextView)itemView.findViewById(R.id.Comment_PosterName); mCommentTextView = (TextView)itemView.findViewById(R.id.Comment_DisplayCommentTextView); mDateTextView = (TextView)itemView.findViewById(R.id.Comment_DateCommentedTextView); } public void bind(Comment comment) { mComment = comment; displayPic(); mFullNameTextView.setText(comment.getFullName()); mCommentTextView.setText(comment.getComment()); mDateTextView.setText(comment.getDate()); } public void displayPic() { String mImageUrl = mComment.getCommenterProfilePicLocation(); if(!mImageUrl.isEmpty()) { Bitmap bitmap = getScaledBitmap(mImageUrl, mProfileImage.getWidth(), mProfileImage.getMaxHeight()); mProfileImage.setImageBitmap(bitmap); } } public Bitmap getScaledBitmap(String path, int width, int height) { BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeFile(path, options); float srcWidth = options.outWidth; float srcHeight = options.outHeight; int sampleSize = 1; if(srcHeight > height || srcWidth > width ) { if(srcWidth > srcHeight) { sampleSize = Math.round(srcHeight / height); } else { sampleSize = Math.round(srcWidth / width); } } BitmapFactory.Options scaledOptions = new BitmapFactory.Options(); scaledOptions.inSampleSize = sampleSize; return BitmapFactory.decodeFile(path, scaledOptions); } }
2,519
0.676459
0.666137
80
30.487499
25.899321
96
false
false
0
0
0
0
0
0
0.575
false
false
3
c6dde8be94ddd8dd673bd8173a8a53a7612d5bed
15,092,515,136,702
579b5a83db7252e08772518c2bfc565190cdb71b
/src/com/me/clue/custom/CustomButton.java
4330adff0803cddacbbfd8fcea54d934de9a2266
[]
no_license
drthomas/Clue
https://github.com/drthomas/Clue
ba0ada5031299dbd7f837f1620c6dc75d7c859d3
aa1a2bbcbec4e05c4591264a0f779b985d5a0ba9
refs/heads/master
2021-01-10T20:59:22.137000
2015-08-21T16:55:52
2015-08-21T16:55:52
37,152,319
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.me.clue.custom; import com.badlogic.gdx.graphics.g2d.BitmapFont; import com.badlogic.gdx.graphics.g2d.TextureAtlas; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.scenes.scene2d.ui.Skin; import com.badlogic.gdx.scenes.scene2d.ui.TextButton; public class CustomButton { public enum ClickState { RELEASED, PRESSED, } protected Vector2 _position; protected TextButton.TextButtonStyle _textButtonStyle; protected TextButton _button; protected BitmapFont _font; protected Skin _skin; protected TextureAtlas _buttonAtlas; protected ClickState _clickState = ClickState.RELEASED; protected boolean _pressed = false; public void setClickState(ClickState state) { _clickState = state; } public boolean isPressed() { return _pressed; } public void setPressed(boolean pressed) { _pressed = pressed;} public TextButton getButton(){return _button; } public void setPosition(float x, float y){ _button.setPosition(x, y);} public CustomButton(Vector2 position) { _position = position; } }
UTF-8
Java
1,106
java
CustomButton.java
Java
[]
null
[]
package com.me.clue.custom; import com.badlogic.gdx.graphics.g2d.BitmapFont; import com.badlogic.gdx.graphics.g2d.TextureAtlas; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.scenes.scene2d.ui.Skin; import com.badlogic.gdx.scenes.scene2d.ui.TextButton; public class CustomButton { public enum ClickState { RELEASED, PRESSED, } protected Vector2 _position; protected TextButton.TextButtonStyle _textButtonStyle; protected TextButton _button; protected BitmapFont _font; protected Skin _skin; protected TextureAtlas _buttonAtlas; protected ClickState _clickState = ClickState.RELEASED; protected boolean _pressed = false; public void setClickState(ClickState state) { _clickState = state; } public boolean isPressed() { return _pressed; } public void setPressed(boolean pressed) { _pressed = pressed;} public TextButton getButton(){return _button; } public void setPosition(float x, float y){ _button.setPosition(x, y);} public CustomButton(Vector2 position) { _position = position; } }
1,106
0.721519
0.71519
37
28.891891
22.890791
74
false
false
0
0
0
0
0
0
0.648649
false
false
3
bac7a304fa9ba72f98a5d70f4696fbb0fde039ab
2,508,260,972,219
4ced85e5fcaad0bf2d4d1299577e0c9379f5fae8
/src/main/entity/User.java
0c655e1c83d0b32253346a4a10890b0bf705104b
[]
no_license
lrswcg/Travel
https://github.com/lrswcg/Travel
e41011b088547329b99c5a40ed29ad3e8abfc3a1
618b51d3a1e0491a48c9ff9b8ca78e2e6de5eedc
refs/heads/master
2020-12-02T22:18:56.508000
2017-07-03T13:37:03
2017-07-03T13:37:03
96,113,909
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package main.entity; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import main.validator.Gender; import org.hibernate.validator.constraints.Email; import org.hibernate.validator.constraints.NotBlank; import org.hibernate.validator.constraints.Range; import java.util.Date; /** * Created by cnhhdn on 2017/6/12. */ @JsonSerialize public class User { private String userId; @Email @NotBlank private String email; @NotBlank private String nickname; @NotBlank private String password; @Gender(message = "invalid gender") private String gender; private String avatar; private String sign; private Date createTime; private Date updateTime; public User() { } public User(String userId, String email, String nickname, String password, String gender, String avatar) { this.userId = userId; this.email = email; this.nickname = nickname; this.password = password; this.gender = gender; this.avatar = avatar; } public User(String userId, String email, String nickname, String password, String gender, String avatar, String sign, Date createTime, Date updateTime) { this.userId = userId; this.email = email; this.nickname = nickname; this.password = password; this.gender = gender; this.avatar = avatar; this.sign = sign; this.createTime = createTime; this.updateTime = updateTime; } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getNickname() { return nickname; } public void setNickname(String nickname) { this.nickname = nickname; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getAvatar() { return avatar; } public void setAvatar(String avatar) { this.avatar = avatar; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public String getSign() { return sign; } public void setSign(String sign) { this.sign = sign; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public Date getUpdateTime() { return updateTime; } public void setUpdateTime(Date updateTime) { this.updateTime = updateTime; } @Override public String toString() { return "User{" + "userId='" + userId + '\'' + ", email='" + email + '\'' + ", nickname='" + nickname + '\'' + ", password='" + password + '\'' + ", gender='" + gender + '\'' + ", avatar='" + avatar + '\'' + ", createTime=" + createTime + ", updateTime=" + updateTime + '}'; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof User)) return false; User user = (User) o; return getUserId() != null ? getUserId().equals(user.getUserId()) : user.getUserId() == null; } @Override public int hashCode() { return getUserId() != null ? getUserId().hashCode() : 0; } }
UTF-8
Java
3,851
java
User.java
Java
[ { "context": "e;\r\n\r\nimport java.util.Date;\r\n\r\n/**\r\n * Created by cnhhdn on 2017/6/12.\r\n */\r\n@JsonSerialize\r\npublic class ", "end": 331, "score": 0.9996151328086853, "start": 325, "tag": "USERNAME", "value": "cnhhdn" }, { "context": "this.nickname = nickname;\r\n this.password = password;\r\n this.gender = gender;\r\n this.ava", "end": 1015, "score": 0.9989092946052551, "start": 1007, "tag": "PASSWORD", "value": "password" }, { "context": "this.nickname = nickname;\r\n this.password = password;\r\n this.gender = gender;\r\n this.ava", "end": 1375, "score": 0.9987826347351074, "start": 1367, "tag": "PASSWORD", "value": "password" }, { "context": "ssword(String password) {\r\n this.password = password;\r\n }\r\n\r\n public String getAvatar() {\r\n ", "end": 2160, "score": 0.7789405584335327, "start": 2152, "tag": "PASSWORD", "value": "password" }, { "context": "ickname + '\\'' +\r\n \", password='\" + password + '\\'' +\r\n \", gender='\" + gender +", "end": 3208, "score": 0.9970887303352356, "start": 3200, "tag": "PASSWORD", "value": "password" } ]
null
[]
package main.entity; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import main.validator.Gender; import org.hibernate.validator.constraints.Email; import org.hibernate.validator.constraints.NotBlank; import org.hibernate.validator.constraints.Range; import java.util.Date; /** * Created by cnhhdn on 2017/6/12. */ @JsonSerialize public class User { private String userId; @Email @NotBlank private String email; @NotBlank private String nickname; @NotBlank private String password; @Gender(message = "invalid gender") private String gender; private String avatar; private String sign; private Date createTime; private Date updateTime; public User() { } public User(String userId, String email, String nickname, String password, String gender, String avatar) { this.userId = userId; this.email = email; this.nickname = nickname; this.password = <PASSWORD>; this.gender = gender; this.avatar = avatar; } public User(String userId, String email, String nickname, String password, String gender, String avatar, String sign, Date createTime, Date updateTime) { this.userId = userId; this.email = email; this.nickname = nickname; this.password = <PASSWORD>; this.gender = gender; this.avatar = avatar; this.sign = sign; this.createTime = createTime; this.updateTime = updateTime; } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getNickname() { return nickname; } public void setNickname(String nickname) { this.nickname = nickname; } public String getPassword() { return password; } public void setPassword(String password) { this.password = <PASSWORD>; } public String getAvatar() { return avatar; } public void setAvatar(String avatar) { this.avatar = avatar; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public String getSign() { return sign; } public void setSign(String sign) { this.sign = sign; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public Date getUpdateTime() { return updateTime; } public void setUpdateTime(Date updateTime) { this.updateTime = updateTime; } @Override public String toString() { return "User{" + "userId='" + userId + '\'' + ", email='" + email + '\'' + ", nickname='" + nickname + '\'' + ", password='" + <PASSWORD> + '\'' + ", gender='" + gender + '\'' + ", avatar='" + avatar + '\'' + ", createTime=" + createTime + ", updateTime=" + updateTime + '}'; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof User)) return false; User user = (User) o; return getUserId() != null ? getUserId().equals(user.getUserId()) : user.getUserId() == null; } @Override public int hashCode() { return getUserId() != null ? getUserId().hashCode() : 0; } }
3,859
0.559076
0.556998
157
22.528662
21.974091
157
false
false
0
0
0
0
0
0
0.477707
false
false
3
81ab44dcb177e361c448e7b7db88eb5260a4b719
833,223,690,743
0e648e8f8d8a497aab892553eaae5f06a879f091
/app/src/main/java/com/enernet/eg/building/activity/ActivityUsageMonthly.java
dd99859738e17c50bda4f5ec04c5f3e4bca3ff39
[]
no_license
Freerider-song/Eg_Building_ANDROID
https://github.com/Freerider-song/Eg_Building_ANDROID
b425309ec313fa2cf2ae82c812d43fbaaea2f648
1d479145a8097d4393fd4b9639de1a369f832215
refs/heads/master
2023-05-29T03:14:09.930000
2021-06-14T06:20:50
2021-06-14T06:20:50
348,943,696
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.enernet.eg.building.activity; import android.annotation.SuppressLint; import android.graphics.Typeface; import android.os.Bundle; import android.os.SystemClock; import android.util.Log; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import com.enernet.eg.building.CaApplication; import com.enernet.eg.building.CaEngine; import com.enernet.eg.building.CaResult; import com.enernet.eg.building.EgYearMonthDayPicker; import com.enernet.eg.building.EgYearMonthPicker; import com.enernet.eg.building.IaResultHandler; import com.enernet.eg.building.R; import com.enernet.eg.building.StringUtil; import com.enernet.eg.building.model.CaMeter; import com.enernet.eg.building.model.CaMeterUsage; import com.github.mikephil.charting.charts.HorizontalBarChart; import com.github.mikephil.charting.components.Legend; import com.github.mikephil.charting.components.XAxis; import com.github.mikephil.charting.components.YAxis; import com.github.mikephil.charting.data.BarData; import com.github.mikephil.charting.data.BarDataSet; import com.github.mikephil.charting.data.BarEntry; import com.github.mikephil.charting.data.Entry; import com.github.mikephil.charting.formatter.IndexAxisValueFormatter; import com.github.mikephil.charting.formatter.ValueFormatter; import com.github.mikephil.charting.highlight.Highlight; import com.github.mikephil.charting.listener.OnChartValueSelectedListener; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.List; public class ActivityUsageMonthly extends BaseActivity implements IaResultHandler { private HorizontalBarChart m_Chart; private EgYearMonthPicker m_dlgYearMonthPicker; public int Year; public int Month; public int m_nMeter=0; public ArrayList<CaMeter> m_alMeter = new ArrayList<>(); public CaMeter m_AllMeter; private EgYearMonthDayPicker m_dlgYearMonthDayPicker; private Spinner m_spMeter; private Button btnSelectTime; SimpleDateFormat mFormat = new SimpleDateFormat("yyyy-MM"); private Long mLastClickTime = 0L; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_usage_monthly); prepareDrawer(); timeSetting(); Calendar calCurr= Calendar.getInstance(); requestUsageMonthly(calCurr.get(Calendar.YEAR), calCurr.get(Calendar.MONTH)+1); } public void timeSetting() { btnSelectTime = (Button) findViewById(R.id.btn_select_time); Calendar calToday = Calendar.getInstance(); String m_dtToday = mFormat.format(calToday.getTime()); btnSelectTime.setText(m_dtToday); } public void initSpinner(){ m_spMeter = findViewById(R.id.sp_meter); final List<String> alMeter = new ArrayList<>(); for (int i=0; i<m_alMeter.size(); i++) { CaMeter ds=m_alMeter.get(i); alMeter.add(ds.m_strDescr); } ArrayAdapter<String> AdapterMeter = new ArrayAdapter<String>(this, R.layout.eg_spinner_style, alMeter) { @NonNull @Override public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) { View v = super.getView(position, convertView, parent); Typeface externalFont=Typeface.createFromAsset(getAssets(), getString(R.string.font_open_sans_regular)); ((TextView) v).setTypeface(externalFont); ((TextView) v).setTextSize(17.0f); ((TextView) v).setTextColor(getResources().getColor(R.color.eg_cyan_dark)); return v; } }; m_spMeter.setEnabled(true); m_spMeter.setAdapter(AdapterMeter); AdapterMeter.setDropDownViewResource(R.layout.eg_spinner_item_style); m_spMeter.setSelection(m_nMeter); m_spMeter.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { m_nMeter=position; Log.i("UsageMonthly", "Selected="+alMeter.get(position)+", position="+position+", id="+id); } @Override public void onNothingSelected(AdapterView<?> parent) { } }); } public void requestUsageMonthly(int nYear, int nMonth) { Year = nYear; Month = nMonth; CaApplication.m_Engine.GetUsageForAllMeterMonth(CaApplication.m_Info.m_nSeqSite, nYear, nMonth, this, this); } public void initChartDaily() { m_Chart = findViewById(R.id.usage_chart); m_Chart.setDrawBarShadow(false); m_Chart.setDrawValueAboveBar(true); m_Chart.getDescription().setEnabled(false); m_Chart.setTouchEnabled(false); // if more than 60 entries are displayed in the chart, no values will be drawn //m_Chart.setMaxVisibleValueCount(60); // scaling can now only be done on x- and y-axis separately m_Chart.setPinchZoom(true); // draw shadows for each bar that show the maximum value // mChart.setDrawBarShadow(true); // mChart.setDrawXLabels(false); m_Chart.setDrawGridBackground(false); // mChart.setDrawYLabels(false); m_Chart.animateY(2500); Typeface tf2 = Typeface.createFromAsset(getAssets(), StringUtil.getString(this, R.string.font_open_sans_regular)); XAxis xAxis = m_Chart.getXAxis(); xAxis.setPosition(XAxis.XAxisPosition.BOTTOM); xAxis.setTypeface(tf2); xAxis.setCenterAxisLabels(true); xAxis.setGranularity(0.3f); YAxis yLeft = m_Chart.getAxisLeft(); yLeft.setTypeface(tf2); yLeft.setDrawAxisLine(true); yLeft.setDrawGridLines(true); yLeft.setGranularity(0.3f); Legend lgd = m_Chart.getLegend(); lgd.setDrawInside(false); lgd.setFormSize(8f); lgd.setXEntrySpace(6f); lgd.setYEntrySpace(12f); lgd.setTypeface(tf2); lgd.setVerticalAlignment(Legend.LegendVerticalAlignment.TOP); lgd.setHorizontalAlignment(Legend.LegendHorizontalAlignment.RIGHT); m_Chart.setOnChartValueSelectedListener(new OnChartValueSelectedListener() { @Override public void onValueSelected(Entry e, Highlight h) { float x = e.getX(); String s = Float.toString(x); float index_f = e.getY(); int index = Math.round(index_f); } @Override public void onNothingSelected() { } }); } @Override public void onBackPressed() { if (m_Drawer.isDrawerOpen()) { m_Drawer.closeDrawer(); } else { finish(); } } public void onClick(View v) { if(SystemClock.elapsedRealtime() - mLastClickTime > 400) { switch (v.getId()) { case R.id.btn_back: { finish(); } break; case R.id.btn_menu: { m_Drawer.openDrawer(); } break; case R.id.btn_select_time: { View.OnClickListener LsnConfirmYes = new View.OnClickListener() { @Override public void onClick(View v) { m_dlgYearMonthPicker.dismiss(); int nYear = m_dlgYearMonthPicker.m_npYear.getValue(); int nMonth = m_dlgYearMonthPicker.m_npMonth.getValue(); Log.i("YearMonthDatePicker", "year=" + nYear + ", month=" + nMonth); Year = nYear; Month = nMonth; String strYear = Integer.toString(nYear); String strMonth = Integer.toString(nMonth); if (nMonth <= 9) strMonth = "0" + strMonth; String chosenDate = strYear + "-" + strMonth; btnSelectTime = (Button) findViewById(R.id.btn_select_time); btnSelectTime.setText(chosenDate); } }; View.OnClickListener LsnConfirmNo = new View.OnClickListener() { @Override public void onClick(View v) { Log.i("ActivityCandidate", "No button clicked..."); m_dlgYearMonthPicker.dismiss(); } }; m_dlgYearMonthPicker = new EgYearMonthPicker(this, "์กฐํšŒํ•  ๋‚ ์งœ๋ฅผ ์„ ํƒํ•˜์„ธ์š”", LsnConfirmYes, LsnConfirmNo); m_dlgYearMonthPicker.show(); } break; case R.id.btn_search: { requestUsageMonthly(Year, Month); m_Chart.clear(); } break; } } mLastClickTime = SystemClock.elapsedRealtime(); } @Override public void onResult(CaResult Result) { if (Result.object==null) { Toast.makeText(getApplicationContext(), "Check Network", Toast.LENGTH_SHORT).show(); return; } switch (Result.m_nCallback) { case CaEngine.CB_GET_USAGE_FOR_ALL_METER_MONTH: { Log.i("ActivityAck", "Result of GetUsageOfOneMonth received..."); try { JSONObject jo = Result.object; JSONArray jaMeter = jo.getJSONArray("list_meter"); JSONArray jaAllMeter = jo.getJSONArray("list_usage_for_all_meter"); m_AllMeter=new CaMeter(); m_AllMeter.m_alMeterUsage = new ArrayList<>(); for(int j=0; j<jaAllMeter.length();j++){ JSONObject joUsage = jaAllMeter.getJSONObject(j); CaMeterUsage usage = new CaMeterUsage(); usage.m_nUnit=joUsage.getInt("unit"); if(joUsage.isNull("kwh")){ usage.m_dKwh=0.0; } else{ usage.m_dKwh=joUsage.getDouble("kwh"); } m_AllMeter.m_alMeterUsage.add(usage); } m_alMeter.clear(); initChartDaily(); if(jaMeter.length()!=0){ prepareChartData(jaMeter); } } catch (JSONException e) { e.printStackTrace(); } } break; default: { Log.i("ActivityAck", "Unknown type result received : " + Result.m_nCallback); } break; } } public void prepareChartData(JSONArray ja) { m_alMeter.clear(); try{ for(int i=0;i<ja.length();i++){ JSONObject jo = ja.getJSONObject(i); JSONArray jaUsage = jo.getJSONArray("list_usage"); CaMeter meter = new CaMeter(); meter.m_nSeqMeter=jo.getInt("seq_meter"); meter.m_strMid=jo.getString("mid"); meter.m_strDescr=jo.getString("descr"); meter.m_alMeterUsage = new ArrayList<>(); for(int j=0; j<jaUsage.length();j++){ JSONObject joUsage = jaUsage.getJSONObject(j); CaMeterUsage usage = new CaMeterUsage(); usage.m_nUnit=joUsage.getInt("unit"); if(joUsage.isNull("kwh")){ usage.m_dKwh=0.0; } else{ usage.m_dKwh=joUsage.getDouble("kwh"); } meter.m_alMeterUsage.add(usage); } m_alMeter.add(meter); } setDataChart(); initSpinner(); } catch (JSONException e){ e.printStackTrace(); } } public ArrayList<String> getAreaCount(){ int nCountUsage=m_AllMeter.m_alMeterUsage.size(); //24 ArrayList<String> label = new ArrayList<>(); for (int i = 0; i <nCountUsage; i++) { CaMeterUsage Usage=m_alMeter.get(0).m_alMeterUsage.get(nCountUsage-1-i); label.add(Usage.m_nUnit + " ์ผ"); }; return label; } public void setDataChart() { m_Chart.clear(); ArrayList<BarEntry> yValsKwhAll = new ArrayList<>(); ArrayList<BarEntry> yValsKwhMeter = new ArrayList<>(); float groupSpace = 0.2f; float barSpace = 0.10f; float barWidth = 0.30f; int nCountUsage=m_AllMeter.m_alMeterUsage.size(); for (int i=0; i<nCountUsage; i++) { CaMeterUsage UsageAll=m_AllMeter.m_alMeterUsage.get(nCountUsage-1-i); CaMeterUsage UsageMeter=m_alMeter.get(m_nMeter).m_alMeterUsage.get(nCountUsage-1-i); yValsKwhAll.add(new BarEntry(UsageAll.m_nUnit, (float)UsageAll.m_dKwh)); yValsKwhMeter.add(new BarEntry(UsageMeter.m_nUnit, (float)UsageMeter.m_dKwh)); // yValsKwhAvg.add(new BarEntry((float)Usage.m_dKwhAvg, i)); // yValsWonAvg.add(new BarEntry((float)Usage.m_dWonAvg, i)); } ValueFormatter vfKwhWithUnit=new ValueFormatter() { @Override public String getFormattedValue(float v) { if (v==0) return ""; //else return CaApplication.m_Info.m_dfKwh.format(v)+" kWh"; else return CaApplication.m_Info.m_dfKwh.format(v); } }; ValueFormatter vfKwh=new ValueFormatter() { @Override public String getFormattedValue(float v) { return CaApplication.m_Info.m_dfKwh.format(v); } }; YAxis yLeft = m_Chart.getAxisLeft(); yLeft.setValueFormatter(vfKwh); YAxis yRight = m_Chart.getAxisRight(); yRight.setValueFormatter(vfKwh); XAxis xAxis = m_Chart.getXAxis(); xAxis.setValueFormatter(new IndexAxisValueFormatter(getAreaCount())); xAxis.setLabelCount(nCountUsage); BarDataSet setKwhAll=new BarDataSet(yValsKwhAll, "์ „์ฒด ์‚ฌ์šฉ๋Ÿ‰"); setKwhAll.setColor(getResources().getColor(R.color.ks_light_gray)); setKwhAll.setValueFormatter(vfKwhWithUnit); BarDataSet setKwhMeter=new BarDataSet(yValsKwhMeter, m_alMeter.get(m_nMeter).m_strDescr); setKwhMeter.setColor(getResources().getColor(R.color.eg_yellow_dark)); setKwhMeter.setValueFormatter(vfKwhWithUnit); //m_Chart.getLegend().setEnabled(false); BarData dataKwh = new BarData(setKwhMeter, setKwhAll); dataKwh.setValueTextSize(10f); dataKwh.setBarWidth(barWidth); dataKwh.setHighlightEnabled(false); Typeface tf2 = Typeface.createFromAsset(getAssets(), "fonts/OpenSans-Regular.ttf"); dataKwh.setValueTypeface(tf2); dataKwh.setValueTextColor(getResources().getColor(R.color.eg_cyan_dark)); m_Chart.getXAxis().setAxisMinimum(0); m_Chart.getXAxis().setAxisMaximum(nCountUsage); m_Chart.setData(dataKwh); //m_Chart.setDrawValueAboveBar(true); m_Chart.getAxisLeft().setAxisMinimum(0f); m_Chart.getAxisRight().setAxisMinimum(0f); m_Chart.groupBars(0f, groupSpace, barSpace); } }
UTF-8
Java
16,185
java
ActivityUsageMonthly.java
Java
[]
null
[]
package com.enernet.eg.building.activity; import android.annotation.SuppressLint; import android.graphics.Typeface; import android.os.Bundle; import android.os.SystemClock; import android.util.Log; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import com.enernet.eg.building.CaApplication; import com.enernet.eg.building.CaEngine; import com.enernet.eg.building.CaResult; import com.enernet.eg.building.EgYearMonthDayPicker; import com.enernet.eg.building.EgYearMonthPicker; import com.enernet.eg.building.IaResultHandler; import com.enernet.eg.building.R; import com.enernet.eg.building.StringUtil; import com.enernet.eg.building.model.CaMeter; import com.enernet.eg.building.model.CaMeterUsage; import com.github.mikephil.charting.charts.HorizontalBarChart; import com.github.mikephil.charting.components.Legend; import com.github.mikephil.charting.components.XAxis; import com.github.mikephil.charting.components.YAxis; import com.github.mikephil.charting.data.BarData; import com.github.mikephil.charting.data.BarDataSet; import com.github.mikephil.charting.data.BarEntry; import com.github.mikephil.charting.data.Entry; import com.github.mikephil.charting.formatter.IndexAxisValueFormatter; import com.github.mikephil.charting.formatter.ValueFormatter; import com.github.mikephil.charting.highlight.Highlight; import com.github.mikephil.charting.listener.OnChartValueSelectedListener; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.List; public class ActivityUsageMonthly extends BaseActivity implements IaResultHandler { private HorizontalBarChart m_Chart; private EgYearMonthPicker m_dlgYearMonthPicker; public int Year; public int Month; public int m_nMeter=0; public ArrayList<CaMeter> m_alMeter = new ArrayList<>(); public CaMeter m_AllMeter; private EgYearMonthDayPicker m_dlgYearMonthDayPicker; private Spinner m_spMeter; private Button btnSelectTime; SimpleDateFormat mFormat = new SimpleDateFormat("yyyy-MM"); private Long mLastClickTime = 0L; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_usage_monthly); prepareDrawer(); timeSetting(); Calendar calCurr= Calendar.getInstance(); requestUsageMonthly(calCurr.get(Calendar.YEAR), calCurr.get(Calendar.MONTH)+1); } public void timeSetting() { btnSelectTime = (Button) findViewById(R.id.btn_select_time); Calendar calToday = Calendar.getInstance(); String m_dtToday = mFormat.format(calToday.getTime()); btnSelectTime.setText(m_dtToday); } public void initSpinner(){ m_spMeter = findViewById(R.id.sp_meter); final List<String> alMeter = new ArrayList<>(); for (int i=0; i<m_alMeter.size(); i++) { CaMeter ds=m_alMeter.get(i); alMeter.add(ds.m_strDescr); } ArrayAdapter<String> AdapterMeter = new ArrayAdapter<String>(this, R.layout.eg_spinner_style, alMeter) { @NonNull @Override public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) { View v = super.getView(position, convertView, parent); Typeface externalFont=Typeface.createFromAsset(getAssets(), getString(R.string.font_open_sans_regular)); ((TextView) v).setTypeface(externalFont); ((TextView) v).setTextSize(17.0f); ((TextView) v).setTextColor(getResources().getColor(R.color.eg_cyan_dark)); return v; } }; m_spMeter.setEnabled(true); m_spMeter.setAdapter(AdapterMeter); AdapterMeter.setDropDownViewResource(R.layout.eg_spinner_item_style); m_spMeter.setSelection(m_nMeter); m_spMeter.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { m_nMeter=position; Log.i("UsageMonthly", "Selected="+alMeter.get(position)+", position="+position+", id="+id); } @Override public void onNothingSelected(AdapterView<?> parent) { } }); } public void requestUsageMonthly(int nYear, int nMonth) { Year = nYear; Month = nMonth; CaApplication.m_Engine.GetUsageForAllMeterMonth(CaApplication.m_Info.m_nSeqSite, nYear, nMonth, this, this); } public void initChartDaily() { m_Chart = findViewById(R.id.usage_chart); m_Chart.setDrawBarShadow(false); m_Chart.setDrawValueAboveBar(true); m_Chart.getDescription().setEnabled(false); m_Chart.setTouchEnabled(false); // if more than 60 entries are displayed in the chart, no values will be drawn //m_Chart.setMaxVisibleValueCount(60); // scaling can now only be done on x- and y-axis separately m_Chart.setPinchZoom(true); // draw shadows for each bar that show the maximum value // mChart.setDrawBarShadow(true); // mChart.setDrawXLabels(false); m_Chart.setDrawGridBackground(false); // mChart.setDrawYLabels(false); m_Chart.animateY(2500); Typeface tf2 = Typeface.createFromAsset(getAssets(), StringUtil.getString(this, R.string.font_open_sans_regular)); XAxis xAxis = m_Chart.getXAxis(); xAxis.setPosition(XAxis.XAxisPosition.BOTTOM); xAxis.setTypeface(tf2); xAxis.setCenterAxisLabels(true); xAxis.setGranularity(0.3f); YAxis yLeft = m_Chart.getAxisLeft(); yLeft.setTypeface(tf2); yLeft.setDrawAxisLine(true); yLeft.setDrawGridLines(true); yLeft.setGranularity(0.3f); Legend lgd = m_Chart.getLegend(); lgd.setDrawInside(false); lgd.setFormSize(8f); lgd.setXEntrySpace(6f); lgd.setYEntrySpace(12f); lgd.setTypeface(tf2); lgd.setVerticalAlignment(Legend.LegendVerticalAlignment.TOP); lgd.setHorizontalAlignment(Legend.LegendHorizontalAlignment.RIGHT); m_Chart.setOnChartValueSelectedListener(new OnChartValueSelectedListener() { @Override public void onValueSelected(Entry e, Highlight h) { float x = e.getX(); String s = Float.toString(x); float index_f = e.getY(); int index = Math.round(index_f); } @Override public void onNothingSelected() { } }); } @Override public void onBackPressed() { if (m_Drawer.isDrawerOpen()) { m_Drawer.closeDrawer(); } else { finish(); } } public void onClick(View v) { if(SystemClock.elapsedRealtime() - mLastClickTime > 400) { switch (v.getId()) { case R.id.btn_back: { finish(); } break; case R.id.btn_menu: { m_Drawer.openDrawer(); } break; case R.id.btn_select_time: { View.OnClickListener LsnConfirmYes = new View.OnClickListener() { @Override public void onClick(View v) { m_dlgYearMonthPicker.dismiss(); int nYear = m_dlgYearMonthPicker.m_npYear.getValue(); int nMonth = m_dlgYearMonthPicker.m_npMonth.getValue(); Log.i("YearMonthDatePicker", "year=" + nYear + ", month=" + nMonth); Year = nYear; Month = nMonth; String strYear = Integer.toString(nYear); String strMonth = Integer.toString(nMonth); if (nMonth <= 9) strMonth = "0" + strMonth; String chosenDate = strYear + "-" + strMonth; btnSelectTime = (Button) findViewById(R.id.btn_select_time); btnSelectTime.setText(chosenDate); } }; View.OnClickListener LsnConfirmNo = new View.OnClickListener() { @Override public void onClick(View v) { Log.i("ActivityCandidate", "No button clicked..."); m_dlgYearMonthPicker.dismiss(); } }; m_dlgYearMonthPicker = new EgYearMonthPicker(this, "์กฐํšŒํ•  ๋‚ ์งœ๋ฅผ ์„ ํƒํ•˜์„ธ์š”", LsnConfirmYes, LsnConfirmNo); m_dlgYearMonthPicker.show(); } break; case R.id.btn_search: { requestUsageMonthly(Year, Month); m_Chart.clear(); } break; } } mLastClickTime = SystemClock.elapsedRealtime(); } @Override public void onResult(CaResult Result) { if (Result.object==null) { Toast.makeText(getApplicationContext(), "Check Network", Toast.LENGTH_SHORT).show(); return; } switch (Result.m_nCallback) { case CaEngine.CB_GET_USAGE_FOR_ALL_METER_MONTH: { Log.i("ActivityAck", "Result of GetUsageOfOneMonth received..."); try { JSONObject jo = Result.object; JSONArray jaMeter = jo.getJSONArray("list_meter"); JSONArray jaAllMeter = jo.getJSONArray("list_usage_for_all_meter"); m_AllMeter=new CaMeter(); m_AllMeter.m_alMeterUsage = new ArrayList<>(); for(int j=0; j<jaAllMeter.length();j++){ JSONObject joUsage = jaAllMeter.getJSONObject(j); CaMeterUsage usage = new CaMeterUsage(); usage.m_nUnit=joUsage.getInt("unit"); if(joUsage.isNull("kwh")){ usage.m_dKwh=0.0; } else{ usage.m_dKwh=joUsage.getDouble("kwh"); } m_AllMeter.m_alMeterUsage.add(usage); } m_alMeter.clear(); initChartDaily(); if(jaMeter.length()!=0){ prepareChartData(jaMeter); } } catch (JSONException e) { e.printStackTrace(); } } break; default: { Log.i("ActivityAck", "Unknown type result received : " + Result.m_nCallback); } break; } } public void prepareChartData(JSONArray ja) { m_alMeter.clear(); try{ for(int i=0;i<ja.length();i++){ JSONObject jo = ja.getJSONObject(i); JSONArray jaUsage = jo.getJSONArray("list_usage"); CaMeter meter = new CaMeter(); meter.m_nSeqMeter=jo.getInt("seq_meter"); meter.m_strMid=jo.getString("mid"); meter.m_strDescr=jo.getString("descr"); meter.m_alMeterUsage = new ArrayList<>(); for(int j=0; j<jaUsage.length();j++){ JSONObject joUsage = jaUsage.getJSONObject(j); CaMeterUsage usage = new CaMeterUsage(); usage.m_nUnit=joUsage.getInt("unit"); if(joUsage.isNull("kwh")){ usage.m_dKwh=0.0; } else{ usage.m_dKwh=joUsage.getDouble("kwh"); } meter.m_alMeterUsage.add(usage); } m_alMeter.add(meter); } setDataChart(); initSpinner(); } catch (JSONException e){ e.printStackTrace(); } } public ArrayList<String> getAreaCount(){ int nCountUsage=m_AllMeter.m_alMeterUsage.size(); //24 ArrayList<String> label = new ArrayList<>(); for (int i = 0; i <nCountUsage; i++) { CaMeterUsage Usage=m_alMeter.get(0).m_alMeterUsage.get(nCountUsage-1-i); label.add(Usage.m_nUnit + " ์ผ"); }; return label; } public void setDataChart() { m_Chart.clear(); ArrayList<BarEntry> yValsKwhAll = new ArrayList<>(); ArrayList<BarEntry> yValsKwhMeter = new ArrayList<>(); float groupSpace = 0.2f; float barSpace = 0.10f; float barWidth = 0.30f; int nCountUsage=m_AllMeter.m_alMeterUsage.size(); for (int i=0; i<nCountUsage; i++) { CaMeterUsage UsageAll=m_AllMeter.m_alMeterUsage.get(nCountUsage-1-i); CaMeterUsage UsageMeter=m_alMeter.get(m_nMeter).m_alMeterUsage.get(nCountUsage-1-i); yValsKwhAll.add(new BarEntry(UsageAll.m_nUnit, (float)UsageAll.m_dKwh)); yValsKwhMeter.add(new BarEntry(UsageMeter.m_nUnit, (float)UsageMeter.m_dKwh)); // yValsKwhAvg.add(new BarEntry((float)Usage.m_dKwhAvg, i)); // yValsWonAvg.add(new BarEntry((float)Usage.m_dWonAvg, i)); } ValueFormatter vfKwhWithUnit=new ValueFormatter() { @Override public String getFormattedValue(float v) { if (v==0) return ""; //else return CaApplication.m_Info.m_dfKwh.format(v)+" kWh"; else return CaApplication.m_Info.m_dfKwh.format(v); } }; ValueFormatter vfKwh=new ValueFormatter() { @Override public String getFormattedValue(float v) { return CaApplication.m_Info.m_dfKwh.format(v); } }; YAxis yLeft = m_Chart.getAxisLeft(); yLeft.setValueFormatter(vfKwh); YAxis yRight = m_Chart.getAxisRight(); yRight.setValueFormatter(vfKwh); XAxis xAxis = m_Chart.getXAxis(); xAxis.setValueFormatter(new IndexAxisValueFormatter(getAreaCount())); xAxis.setLabelCount(nCountUsage); BarDataSet setKwhAll=new BarDataSet(yValsKwhAll, "์ „์ฒด ์‚ฌ์šฉ๋Ÿ‰"); setKwhAll.setColor(getResources().getColor(R.color.ks_light_gray)); setKwhAll.setValueFormatter(vfKwhWithUnit); BarDataSet setKwhMeter=new BarDataSet(yValsKwhMeter, m_alMeter.get(m_nMeter).m_strDescr); setKwhMeter.setColor(getResources().getColor(R.color.eg_yellow_dark)); setKwhMeter.setValueFormatter(vfKwhWithUnit); //m_Chart.getLegend().setEnabled(false); BarData dataKwh = new BarData(setKwhMeter, setKwhAll); dataKwh.setValueTextSize(10f); dataKwh.setBarWidth(barWidth); dataKwh.setHighlightEnabled(false); Typeface tf2 = Typeface.createFromAsset(getAssets(), "fonts/OpenSans-Regular.ttf"); dataKwh.setValueTypeface(tf2); dataKwh.setValueTextColor(getResources().getColor(R.color.eg_cyan_dark)); m_Chart.getXAxis().setAxisMinimum(0); m_Chart.getXAxis().setAxisMaximum(nCountUsage); m_Chart.setData(dataKwh); //m_Chart.setDrawValueAboveBar(true); m_Chart.getAxisLeft().setAxisMinimum(0f); m_Chart.getAxisRight().setAxisMinimum(0f); m_Chart.groupBars(0f, groupSpace, barSpace); } }
16,185
0.583555
0.579531
490
31.963264
27.676533
122
false
false
0
0
0
0
0
0
0.614286
false
false
3