blob_id
stringlengths
40
40
language
stringclasses
1 value
repo_name
stringlengths
5
132
path
stringlengths
2
382
src_encoding
stringclasses
34 values
length_bytes
int64
9
3.8M
score
float64
1.5
4.94
int_score
int64
2
5
detected_licenses
listlengths
0
142
license_type
stringclasses
2 values
text
stringlengths
9
3.8M
download_success
bool
1 class
3a908b0792ca1f9804f05b8d821a0066d92f33ab
Java
waterwitness/dazhihui
/classes/com/tencent/IMCoreAvInviteCallBack.java
UTF-8
644
1.796875
2
[]
no_license
package com.tencent; import com.tencent.av.TIMAvManager; import com.tencent.imcore.IAvInviteCallBack; public class IMCoreAvInviteCallBack extends IAvInviteCallBack { private String identifer; public IMCoreAvInviteCallBack(String paramString) { this.identifer = paramString; swigReleaseOwnership(); } public void onAvInviteBuf(byte[] paramArrayOfByte) { TIMAvManager.getInstanceById(this.identifer).MsgNotify(paramArrayOfByte); } } /* Location: E:\apk\dazhihui2\classes-dex2jar.jar!\com\tencent\IMCoreAvInviteCallBack.class * Java compiler version: 6 (50.0) * JD-Core Version: 0.7.1 */
true
104229399850a938135882ee9c9408dd3d5b43db
Java
plusmancn/learn-arithmetic
/arithmetic/src/main/java/cn/plusman/arithmetic/leetcode/top/top73/Top73Soulution.java
UTF-8
179
1.59375
2
[ "Apache-2.0" ]
permissive
package cn.plusman.arithmetic.leetcode.top.top73; /** * @author plusman * @since 2021/7/14 11:44 PM */ public interface Top73Soulution { void setZeroes(int[][] matrix); }
true
f00e344bfe34f7a4fca6366150d36475edbd9c19
Java
VizLoreLabs/phasmaFoodMobileApp
/app/src/main/java/com/vizlore/phasmafood/ui/profile_setup/EditProfileFragment.java
UTF-8
3,413
2.203125
2
[ "Apache-2.0" ]
permissive
package com.vizlore.phasmafood.ui.profile_setup; import android.arch.lifecycle.ViewModelProviders; import android.os.Bundle; import android.support.annotation.NonNull; import android.view.View; import android.widget.ArrayAdapter; import android.widget.EditText; import android.widget.Spinner; import android.widget.Toast; import com.vizlore.phasmafood.R; import com.vizlore.phasmafood.model.User; import com.vizlore.phasmafood.utils.Validator; import com.vizlore.phasmafood.viewmodel.UserViewModel; import java.util.Arrays; import butterknife.BindView; import butterknife.OnClick; /** * Created by smedic on 1/21/18. */ public class EditProfileFragment extends ProfileBaseFragment { private UserViewModel userViewModel; private User currentUser; @BindView(R.id.firstName) EditText firstName; @BindView(R.id.lastName) EditText lastName; @BindView(R.id.userName) EditText username; @BindView(R.id.company) Spinner company; @OnClick({R.id.backButton, R.id.save}) void onClick(View v) { switch (v.getId()) { case R.id.backButton: profileSetupViewModel.setSelected(ProfileAction.GO_BACK); break; case R.id.save: if (Validator.validateFields(new EditText[]{firstName, lastName, username})) { // create new user User user = User.builder() .company(company.getSelectedItem().toString()) .firstName(firstName.getText().toString()) .lastName(lastName.getText().toString()) .username(username.getText().toString()) .id(currentUser.id()) .build(); if (!user.equals(currentUser)) { userViewModel.updateProfile(user).observe(this, isSaved -> { if (isSaved != null && isSaved) { Toast.makeText(getContext(), getString(R.string.profileSaved), Toast.LENGTH_SHORT).show(); profileSetupViewModel.setSelected(ProfileAction.GO_BACK); } else { Toast.makeText(getContext(), getString(R.string.profileSavingError), Toast.LENGTH_SHORT).show(); } }); } } else { Toast.makeText(getContext(), getString(R.string.fillAllFields), Toast.LENGTH_SHORT).show(); } break; } } @Override public void onViewCreated(@NonNull View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); userViewModel = ViewModelProviders.of(getActivity()).get(UserViewModel.class); // Creating adapter for spinner ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getContext(), R.array.companies, R.layout.spinner_item); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); company.setAdapter(adapter); userViewModel.getUserProfile().observe(this, user -> { if (user != null) { firstName.setText(user.firstName()); lastName.setText(user.lastName()); username.setText(user.username()); company.setSelection(getCurrentCompanyPosition(user.company())); //save user for later check if anything is changed currentUser = user; } }); } @Override protected int getFragmentLayout() { return R.layout.fragment_edit_profile; } private int getCurrentCompanyPosition(String currentCompany) { String[] companies = getResources().getStringArray(R.array.companies); if (Arrays.asList(companies).contains(currentCompany)) { for (int i = 0; i < companies.length; i++) { if (companies[i].equals(currentCompany)) { return i; } } } return 0; } }
true
dc995b52954299a1987a23e00590af1d99b21608
Java
majm0771/Bancent
/src/com/bancent/common/XMPPConfig.java
UTF-8
1,203
2.328125
2
[]
no_license
package com.bancent.common; public class XMPPConfig { private String mLoginID = null; //用户名 private String mLoginPWD = null; //用户密码 private String mHostIP = null;// 地址 private int mHostPort = 0;// 端口 private String mServiceName = null;// 服务器名称 public void SetHostIP(String ip) { this.mHostIP = ip; } public String GetHostIP() { return this.mHostIP; } public void SetHostPort(int port) { this.mHostPort = port; } public int GetHostPort() { return this.mHostPort; } public void SetServiceName(String svcName) { this.mServiceName = svcName; } public String GetServiceName() { return this.mServiceName; } public void SetLoginName(String name) { this.mLoginID = name; } public String GetLoginName() { return this.mLoginID; } public void SetLoginPWD(String pwd) { this.mLoginPWD = pwd; } public String GetLoginPWD() { return this.mLoginPWD; } }
true
fd1009717c3dc74b1849a41e8735a689dad9b648
Java
wuyounan/drawio
/huigou-uasp/src/main/java/com/huigou/uasp/bpm/engine/application/impl/ProcApprovalRuleParseServiceImpl.java
UTF-8
14,600
1.773438
2
[]
no_license
package com.huigou.uasp.bpm.engine.application.impl; import java.util.HashMap; import java.util.List; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.util.Assert; import com.huigou.cache.SystemCache; import com.huigou.context.MessageSourceContext; import com.huigou.context.Operator; import com.huigou.context.OrgUnit; import com.huigou.context.ThreadLocalUtil; import com.huigou.data.domain.model.MessageConstants; import com.huigou.data.domain.query.QueryParameter; import com.huigou.data.query.model.QueryDescriptor; import com.huigou.uasp.bmp.common.IntervalKind; import com.huigou.uasp.bmp.common.application.BaseApplication; import com.huigou.uasp.bmp.fn.impl.OrgFun; import com.huigou.uasp.bmp.opm.OpmUtil; import com.huigou.uasp.bmp.opm.domain.model.org.Org; import com.huigou.uasp.bmp.opm.proxy.OrgApplicationProxy; import com.huigou.uasp.bpm.configuration.application.ApprovalRuleApplication; import com.huigou.uasp.bpm.configuration.domain.model.ApprovalRule; import com.huigou.uasp.bpm.configuration.domain.model.ApprovalRuleElement; import com.huigou.uasp.bpm.configuration.domain.model.ApprovalRuleHandler; import com.huigou.uasp.bpm.configuration.domain.model.ApprovalRuleHandlerAssist; import com.huigou.uasp.bpm.configuration.domain.model.HandlerKind; import com.huigou.uasp.bpm.engine.application.HandlerParseService; import com.huigou.uasp.bpm.engine.application.ProcApprovalRuleParseService; import com.huigou.util.ClassHelper; import com.huigou.util.Constants; import com.huigou.util.SDO; import com.huigou.util.StringUtil; import com.huigou.util.Util; @Service("procApprovalRuleParseService") public class ProcApprovalRuleParseServiceImpl extends BaseApplication implements ProcApprovalRuleParseService { @Autowired private OrgApplicationProxy orgApplication; @Autowired private OrgFun orgFun; @Autowired private HandlerParseService handlerParseService; @Autowired private ApprovalRuleApplication approvalRuleApplication; public void setHandlerParseService(HandlerParseService handlerParseService) { this.handlerParseService = handlerParseService; } public void setOrgFun(OrgFun orgFun) { this.orgFun = orgFun; } private String getQuerySqlByName(String name) { QueryDescriptor queryDescriptor = this.sqlExecutorDao.getQuery("config/uasp/query/bmp/bpm.xml", "procApprovalRuleParse"); return queryDescriptor.getSqlByName(name); } /** * 得到最近的规则配置组织ID * * @param ownerOrgId * 业务组织ID * @param procId * 流程ID * @param procUnitId * 环节ID * @return */ private String getNearestRuleOrgId(String ownerOrgId, String procId, String procUnitId) { String sql = this.getQuerySqlByName("selectNearestRuleOrgId"); String result = this.sqlExecutorDao.queryOneToObject(sql, String.class, procId, procUnitId, ownerOrgId); if (StringUtil.isBlank(result)) { result = SystemCache.getParameter("HQOrganId", String.class); } return result; } /** * 内部解析流程规则 <br/> * <li>流程环节设置的审批规则,根据优先级排序 <li>得到一条规则的审批规则设置 <li>验证参数是否满足规则 <li>若满足规则,获取审批人 <li>若未满足返回到第2步 * * @param procId * 流程ID * @param procUnitId * 环节ID * @param params * 参数 */ private ApprovalRule internalParseProcApprovalRule(String procId, String procUnitId, Map<String, Object> params) { // 审批要素 List<ApprovalRuleElement> ruleElements; String setStringValue, inputStringValue; float setFloatValue, inputFloatValue; // 区间类型 IntervalKind intervalKind; boolean matchSuccess = true; ApprovalRule matchedRule = null; String ownerOrgId = ClassHelper.convert(params.get("ownerOrgId"), String.class, ""); String ruleOrgId = this.getNearestRuleOrgId(ownerOrgId, procId, procUnitId); // Util.check(!StringUtil.isBlank(ruleOrgId), String.format("组织机构Id“%s”没有配置审批规则。", ownerOrgId)); // // //当前机构的审批规则 // String sql = this.getQuerySqlByName("queryRule"); // Map<String, Object> queryParams = QueryParameter.buildParameters("orgId", ruleOrgId, "procId", procId, "procUnitId", procUnitId); // List<ApprovalRule> rules = this.generalRepository.query(sql, queryParams); // //别的机构分配给前机构的规则 // sql = this.getQuerySqlByName("queryScopeRule"); // List<ApprovalRule> scopeRules = this.generalRepository.query(sql, queryParams); // // rules.addAll(scopeRules); List<ApprovalRule> rules = this.queryScopeApprovalRules(procId, procUnitId, ruleOrgId, false); // end for (ApprovalRule rule : rules) { ruleElements = rule.getApprovalRuleElements(); for (ApprovalRuleElement ruleElement : ruleElements) { inputStringValue = ClassHelper.convert(params.get(ruleElement.getElementCode()), String.class, ""); Util.check(!StringUtil.isBlank(inputStringValue), String.format("审批要素%s没有赋值。", ruleElement.getElementCode())); switch (ruleElement.getOperatorKind()) { case EQ: matchSuccess = inputStringValue.equals(ruleElement.getFvalueId()); break; case NOT_EQ: matchSuccess = !inputStringValue.equals(ruleElement.getFvalueId()); break; case OIN: setStringValue = String.format(",%s,", ruleElement.getFvalueId()); matchSuccess = setStringValue.contains(String.format(",%s,", inputStringValue)); break; case LT: case LE: case GT: case GE: inputFloatValue = ClassHelper.convert(inputStringValue, Float.class); setFloatValue = ClassHelper.convert(ruleElement.getFvalueId(), Float.class); switch (ruleElement.getOperatorKind()) { case LT: matchSuccess = inputFloatValue < setFloatValue; break; case LE: matchSuccess = inputFloatValue <= setFloatValue; break; case GT: matchSuccess = inputFloatValue > setFloatValue; break; case GE: matchSuccess = inputFloatValue >= setFloatValue; break; default: matchSuccess = false; break; } break; case INTERVAL: intervalKind = IntervalKind.getIntervalKind(ruleElement.getFvalueId()); inputFloatValue = Float.parseFloat(inputStringValue); switch (intervalKind) { case OPEN: matchSuccess = (intervalKind.getOperand1() < inputFloatValue) && (inputFloatValue < intervalKind.getOperand2()); break; case LEF_OPEN: matchSuccess = (intervalKind.getOperand1() < inputFloatValue) && (inputFloatValue <= intervalKind.getOperand2()); break; case RIGHT_OPEN: matchSuccess = (intervalKind.getOperand1() <= inputFloatValue) && (inputFloatValue < intervalKind.getOperand2()); break; case CLOSE: matchSuccess = (intervalKind.getOperand1() <= inputFloatValue) && (inputFloatValue <= intervalKind.getOperand2()); break; } break; default: matchSuccess = false; break; } // 一项未匹配成功,跳出循环,匹配下一个规则 if (!matchSuccess) break; } if (matchSuccess) { matchedRule = rule; // ruleId = rule.getId(); SDO bizData = ThreadLocalUtil.getVariable(Constants.SDO, SDO.class); bizData.putProperty("procApprovalRuleFullName", rule.getFullName()); break; } } if (rules.size() > 0 && matchSuccess) { List<ApprovalRuleHandler> handlers = matchedRule.getApprovalRuleHandlers(); for (ApprovalRuleHandler ruleHandler : handlers) { buildProcHandlers(ruleHandler); } // organizeHandlers(handlers); return matchedRule; } return null; } private void internalBuildHandlers(List<OrgUnit> orgUnits, HandlerKind handlerKind, String handlerId) { this.handlerParseService.buildHandler(handlerKind, handlerId, orgUnits); } /** * 生成流程处理人 */ private void buildProcHandlers(ApprovalRuleHandler ruleHandler) { ruleHandler.getOrgUnits().clear(); internalBuildHandlers(ruleHandler.getOrgUnits(), ruleHandler.getHandlerKind(), ruleHandler.getHandlerId()); for (ApprovalRuleHandlerAssist item : ruleHandler.getAssists()) { this.internalBuildHandlers(item.getOrgUnits(), item.getHandlerKind(), item.getHandlerId()); } } /** * 填充操作员环境参数 * * @param params * @param bizParams */ private void fillOperatorContextParams(Map<String, Object> params, Map<String, Object> bizParams) { Operator operator = OpmUtil.getBizOperator(); // 当前操作员系统参数 params.put("orgAdminKind", operator.getOrgAdminKind()); // 机构类别 params.put("deptKind", operator.getDeptKind()); // 部门类别 params.put("orgId", operator.getOrgId()); // 机构ID params.put("deptId", operator.getDeptId()); // 部门ID params.put("posId", operator.getPositionId()); // 岗位ID params.put("psmId", operator.getPersonMemberId()); // 人员成员ID String ownerOrgId = null; if (bizParams != null) { ownerOrgId = ClassHelper.convert(bizParams.get("ownerOrgId"), String.class, ""); } if (StringUtil.isBlank(ownerOrgId)) { ownerOrgId = operator.getOrgId(); } params.put("ownerOrgId", ownerOrgId); } /** * 填充业务组织参数 * * @param params * @param bizParams */ private void fillBizOrgParams(Map<String, Object> params, Map<String, Object> bizParams) { String manageOrgId = null; if (bizParams != null) { manageOrgId = ClassHelper.convert(bizParams.get(OpmUtil.BIZ_MANAGE_ORG_ID_FIELD_NAME), String.class); } if (Util.isEmptyString(manageOrgId)) { SDO bizData = ThreadLocalUtil.getVariable(Constants.SDO, SDO.class); if (bizData != null) { manageOrgId = bizData.getProperty(OpmUtil.BIZ_MANAGE_ORG_ID_FIELD_NAME, String.class); } } boolean isIncludeBizOrg = !Util.isEmptyString(manageOrgId); if (isIncludeBizOrg) { Org org = orgApplication.loadOrg(manageOrgId); Assert.notNull(org, MessageSourceContext.getMessage(MessageConstants.OBJECT_NOT_FOUND_BY_ID, manageOrgId, "组织")); Util.check(org != null, String.format("没有找到“%s”对应的组织。", manageOrgId)); params.put("bizOrgAdminKind", orgFun.getOrgAdminKindById(org.getOrgId())); // 业务机构类别 params.put("bizOrgAreaKind", orgFun.getOrgProperty(org.getOrgId(), "orgAreaKind")); // 业务区域类别 params.put("deptKind", orgFun.getOrgProperty(org.getOrgId(), "deptKind")); // 部门类别 TODO 是否加biz params.put("bizOrgFullId", org.getFullId()); // ... params.put("bizOrgId", org.getOrgId()); // 业务组织(公司)ID } } /** * 调整参数 * * @param params * @param bizParams */ private void adjustParams(Map<String, Object> params, Map<String, Object> bizParams) { if (bizParams != null) { params.putAll(bizParams); } SDO bizData = ThreadLocalUtil.getVariable(Constants.SDO, SDO.class); if (bizData != null) { bizData.putProperty("bizParams", params); } } @Override @SuppressWarnings("unchecked") public List<ApprovalRule> queryScopeApprovalRules(String procId, String procUnitId, String ownerOrgId, boolean includeClassification) { // 桥接 String ruleOrgId = this.getNearestRuleOrgId(ownerOrgId, procId, procUnitId); Util.check(!StringUtil.isBlank(ruleOrgId), String.format("组织机构Id“%s”没有配置审批规则。", ownerOrgId)); Integer nodeKindId = includeClassification ? ApprovalRule.NodeKind.CATEGORY.getId() : ApprovalRule.NodeKind.RULE.getId(); // 当前机构的审批规则 String sql = this.getQuerySqlByName("queryRule"); Map<String, Object> queryParams = QueryParameter.buildParameters("orgId", ruleOrgId, "procId", procId, "procUnitId", procUnitId, "nodeKindId", nodeKindId); List<ApprovalRule> rules = this.generalRepository.query(sql, queryParams); // 别的机构分配给前机构的规则 sql = this.getQuerySqlByName("queryScopeRule"); List<ApprovalRule> scopeRules = this.generalRepository.query(sql, queryParams); rules.addAll(scopeRules); return rules; } @Override public ApprovalRule execute(String procId, String procUnitId, Map<String, Object> bizParams) { Map<String, Object> params = new HashMap<String, Object>(); fillOperatorContextParams(params, bizParams); fillBizOrgParams(params, bizParams); adjustParams(params, bizParams); return internalParseProcApprovalRule(procId, procUnitId, params); } }
true
1f51e2af103b56c97814f6ebd9ce6fb906ca2229
Java
wardenlzr/IMChat
/app/src/main/java/com/warden/imchat/utils/DBManager.java
UTF-8
14,671
2.609375
3
[]
no_license
package com.warden.imchat.utils; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.text.TextUtils; import android.util.Log; import java.util.ArrayList; import java.util.List; import com.warden.imchat.domain.ChatMessage; import com.warden.imchat.domain.ChatRoom; import com.warden.imchat.domain.ChatUser; /** * @author xiejinbo * @date 2019/9/20 0020 11:17 */ public class DBManager { private DBHelper dbHelper; private SQLiteDatabase database; public DBManager(Context context){ dbHelper = new DBHelper(context); database = dbHelper.getWritableDatabase(); } /** * 添加好友到数据库 * @param chatUsers * @return */ public boolean addChatUserData(List<ChatUser> chatUsers){ try { database.beginTransaction(); for (int i=0;i<chatUsers.size();i++){ ChatUser chatUser1 = queryChatUserByName(chatUsers.get(i).getUserName()); if (!TextUtils.isEmpty(chatUser1.getUserName())){ updateChatUserData(chatUser1); return true; }else { String sql = "INSERT INTO user VALUES(NULL,?,?,?,?)"; Object[] objects = new Object[]{chatUsers.get(i).getUserName(),chatUsers.get(i).getNickName(),chatUsers.get(i).getEmail(),chatUsers.get(i).getJid()}; database.execSQL(sql,objects); } } database.setTransactionSuccessful(); } catch (Exception e) { return false; } finally { if (database.inTransaction()) { database.endTransaction(); } } return true; } /** * 更新表中数据 * @param chatUser * @return */ public boolean updateChatUserData(ChatUser chatUser){ try { ContentValues values = new ContentValues(); values.put("jid", chatUser.getJid()); values.put("username",chatUser.getUserName()); values.put("nickname",chatUser.getNickName()); values.put("email",chatUser.getEmail()); database.beginTransaction(); database.update("user", values, "username=?", new String[]{chatUser.getUserName()}); database.setTransactionSuccessful(); } catch (Exception e) { Log.e("updateChatUserData","Exception: "+e.toString()); return false; } finally { if (database.inTransaction()) { database.endTransaction(); } } return true; } /** * 根据用户名查询用户 * @param userName * @return */ public ChatUser queryChatUserByName(String userName){ ChatUser chatUser = new ChatUser(); try { if (TextUtils.isEmpty(userName)){ return null; } String sql = "select * from user where username=? "; Cursor cursor = database.rawQuery(sql, new String[]{userName}); while (cursor.moveToNext()) { chatUser.setUserName(userName); chatUser.setNickName(cursor.getString(cursor.getColumnIndex("nickname"))); chatUser.setEmail(cursor.getString(cursor.getColumnIndex("email"))); chatUser.setJid(cursor.getString(cursor.getColumnIndex("jid"))); } cursor.close(); } catch (Exception e) { Log.e("queryChatUserByName",e.toString()); } return chatUser; } /** * 查询所有好友 * @return */ public List<ChatUser> queryAllChatUser(){ List<ChatUser> chatUsers = new ArrayList<>(); try { String sql = "select * from user "; Cursor cursor = database.rawQuery(sql,new String[]{}); while (cursor.moveToNext()) { ChatUser chatUser = new ChatUser(); chatUser.setUserName(cursor.getString(cursor.getColumnIndex("username"))); chatUser.setNickName(cursor.getString(cursor.getColumnIndex("nickname"))); chatUser.setEmail(cursor.getString(cursor.getColumnIndex("email"))); chatUser.setJid(cursor.getString(cursor.getColumnIndex("jid"))); chatUsers.add(chatUser); } cursor.close(); } catch (Exception e) { Log.e("queryAllChatUser",e.toString()); } return chatUsers; } /** * 模糊查询,包含likeName的用户 * @param likeName * @return */ public List<ChatUser> queryChatUserByLikeName(String likeName){ List<ChatUser> chatUsers = new ArrayList<>(); try { String sql = "select * from user where username like '%"+likeName+"%'"; Cursor cursor = database.rawQuery(sql,new String[]{}); while (cursor.moveToNext()) { ChatUser chatUser = new ChatUser(); chatUser.setUserName(cursor.getString(cursor.getColumnIndex("username"))); chatUser.setNickName(cursor.getString(cursor.getColumnIndex("nickname"))); chatUser.setEmail(cursor.getString(cursor.getColumnIndex("email"))); chatUser.setJid(cursor.getString(cursor.getColumnIndex("jid"))); chatUsers.add(chatUser); } cursor.close(); }catch (Exception e){ e.printStackTrace(); } return chatUsers; } /** * 添加聊天信息到数据库 * @param chatMessages * @return */ public boolean addChatMessageData(List<ChatMessage> chatMessages){ try { database.beginTransaction(); for (ChatMessage chatMessage: chatMessages){ String sql = "INSERT INTO chatMessage VALUES(NULL,?,?,?,?,?,?,?,?)"; Object[] objects = new Object[]{chatMessage.getUserName(),chatMessage.getSendName(),chatMessage.getData(),chatMessage.getMyself(), chatMessage.getSendtime(),chatMessage.getMessageId(),chatMessage.getSendId(),chatMessage.getType()}; database.execSQL(sql,objects); } database.setTransactionSuccessful(); } catch (Exception e) { return false; } finally { if (database.inTransaction()) { database.endTransaction(); } } return true; } /** * 根据用户名查询最近消息 * @param userName * @return */ public List<ChatMessage> queryChatMessageByName(String userName){ List<ChatMessage> chatMessages = new ArrayList<>(); try { //此处的group by username,sendname是把同一个人发的消息合并,取最新一条 String sql = "select * from chatMessage where username=? group by username,sendname order by history_id desc "; Cursor cursor = database.rawQuery(sql, new String[]{userName}); while (cursor.moveToNext()) { ChatMessage chatMessage = new ChatMessage(); chatMessage.setUserName(userName); chatMessage.setSendName(cursor.getString(cursor.getColumnIndex("sendname"))); chatMessage.setData(cursor.getString(cursor.getColumnIndex("data"))); chatMessage.setMyself(cursor.getString(cursor.getColumnIndex("myself"))); chatMessage.setSendtime(cursor.getString(cursor.getColumnIndex("sendtime"))); chatMessage.setMessageId(cursor.getString(cursor.getColumnIndex("messageId"))); chatMessage.setSendId(cursor.getString(cursor.getColumnIndex("sendId"))); chatMessage.setType(cursor.getString(cursor.getColumnIndex("type"))); chatMessages.add(chatMessage); } cursor.close(); } catch (Exception e) { Log.e("queryChatMessageByName",e.toString()); } return chatMessages; } /** * 根据用户名查询最近消息 * @param userName * @return */ public List<ChatMessage> queryChatMessageByName(String userName,String myself){ List<ChatMessage> chatMessages = new ArrayList<>(); try { //此处的group by username,sendname是把同一个人发的消息合并,取最新一条 String sql = "select * from chatMessage where username=? and myself=? group by username,sendname order by history_id desc "; Cursor cursor = database.rawQuery(sql, new String[]{userName,myself}); while (cursor.moveToNext()) { ChatMessage chatMessage = new ChatMessage(); chatMessage.setUserName(userName); chatMessage.setSendName(cursor.getString(cursor.getColumnIndex("sendname"))); chatMessage.setData(cursor.getString(cursor.getColumnIndex("data"))); chatMessage.setMyself(cursor.getString(cursor.getColumnIndex("myself"))); chatMessage.setSendtime(cursor.getString(cursor.getColumnIndex("sendtime"))); chatMessage.setMessageId(cursor.getString(cursor.getColumnIndex("messageId"))); chatMessage.setSendId(cursor.getString(cursor.getColumnIndex("sendId"))); chatMessage.setType(cursor.getString(cursor.getColumnIndex("type"))); chatMessages.add(chatMessage); } cursor.close(); } catch (Exception e) { Log.e("queryChatMessageByName",e.toString()); } return chatMessages; } /** * 根据用户名查询历史消息 * @param sendName * @return */ public List<ChatMessage> queryHistoryChatMessageByName(String sendName){ List<ChatMessage> chatMessages = new ArrayList<>(); try { //此处的group by username,sendname是把同一个人发的消息合并,取最新一条 String sql = "select * from chatMessage where sendname=? order by history_id "; Cursor cursor = database.rawQuery(sql, new String[]{sendName}); while (cursor.moveToNext()) { ChatMessage chatMessage = new ChatMessage(); chatMessage.setUserName(cursor.getString(cursor.getColumnIndex("username"))); chatMessage.setSendName(cursor.getString(cursor.getColumnIndex("sendname"))); chatMessage.setData(cursor.getString(cursor.getColumnIndex("data"))); chatMessage.setMyself(cursor.getString(cursor.getColumnIndex("myself"))); chatMessage.setSendtime(cursor.getString(cursor.getColumnIndex("sendtime"))); chatMessage.setMessageId(cursor.getString(cursor.getColumnIndex("messageId"))); chatMessage.setSendId(cursor.getString(cursor.getColumnIndex("sendId"))); chatMessage.setType(cursor.getString(cursor.getColumnIndex("type"))); chatMessages.add(chatMessage); } cursor.close(); } catch (Exception e) { Log.e("queryHistoryByName",e.toString()); } return chatMessages; } /** * 删除已操作后的申请信息 * @param table * @param whereClause * @param parameter * @return */ public boolean deleteData(String table, String whereClause, String[] parameter) { try { if (table != "" ) { database.beginTransaction(); database.delete(table, whereClause, parameter); database.setTransactionSuccessful(); } } catch (Exception e) { return false; } finally { if (database.inTransaction()) { database.endTransaction(); } } return true; } /** * 添加聊天房间到数据库 * @param chatRooms * @return */ public boolean addChatRoomData(List<ChatRoom> chatRooms){ try { database.beginTransaction(); for (ChatRoom chatRoom: chatRooms){ ChatRoom chatRoom1 = queryAllChatRoomByJid(chatRoom.getJid()); if (chatRoom1!=null&&!TextUtils.isEmpty(chatRoom1.getJid())){ ContentValues values = new ContentValues(); values.put("roomName",chatRoom.getRoomName()); database.update("chatRoom",values,"jid=?" ,new String[]{chatRoom.getJid()}); }else { String sql = "INSERT INTO chatRoom VALUES(NULL,?,?)"; Object[] objects = new Object[]{chatRoom.getRoomName(),chatRoom.getJid()}; database.execSQL(sql,objects); } } database.setTransactionSuccessful(); } catch (Exception e) { return false; } finally { if (database.inTransaction()) { database.endTransaction(); } } return true; } /** * 根据Jid查询所有聊天室 * @return */ public ChatRoom queryAllChatRoomByJid(String jid){ try { String sql = "select * from chatRoom where jid=? "; Cursor cursor = database.rawQuery(sql,new String[]{jid}); ChatRoom chatRoom = new ChatRoom(); while (cursor.moveToNext()) { chatRoom.setJid(cursor.getString(cursor.getColumnIndex("jid"))); chatRoom.setRoomName(cursor.getString(cursor.getColumnIndex("roomName"))); } cursor.close(); return chatRoom; } catch (Exception e) { Log.e("queryAllChatRoomByJid",e.toString()); return null; } } /** * 查询所有聊天室 * @return */ public List<ChatRoom> queryAllChatRoom(){ List<ChatRoom> chatRooms = new ArrayList<>(); try { String sql = "select * from chatRoom "; Cursor cursor = database.rawQuery(sql,new String[]{}); while (cursor.moveToNext()) { ChatRoom chatRoom = new ChatRoom(); chatRoom.setRoomName(cursor.getString(cursor.getColumnIndex("roomName"))); chatRoom.setJid(cursor.getString(cursor.getColumnIndex("jid"))); chatRooms.add(chatRoom); } cursor.close(); } catch (Exception e) { Log.e("queryAllChatRoom",e.toString()); } return chatRooms; } }
true
07ae939fd7d4324b66cb99fa4babb9b1b72cfa4d
Java
yusuiked/continuous
/src/test/java/continuous/service/impl/UserServiceImplTest.java
UTF-8
2,173
2.296875
2
[]
no_license
package continuous.service.impl; import static org.hamcrest.CoreMatchers.*; import static org.junit.Assert.*; import java.util.Date; import continuous.dao.UserDao; import continuous.entity.User; import continuous.service.UserService; import org.jmock.Expectations; import org.jmock.Mockery; import org.jmock.integration.junit4.JMock; import org.jmock.integration.junit4.JUnit4Mockery; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @RunWith(JMock.class) public class UserServiceImplTest { private Mockery context = new JUnit4Mockery(); private UserService service; private UserDao mock; @Before public void setUp() { mock = context.mock(UserDao.class); service = new UserServiceImpl(mock); } @After public void tearDown() { } @Test public void testFind() { final User user = new User(); context.checking(new Expectations() { { oneOf(mock).find(0L); will(returnValue(user)); } }); assertThat(service.find(0L), is(user)); } @Test public void testRemove() throws Exception { final User user = new User(); user.setId(1L); context.checking(new Expectations() { { oneOf(mock).delete(user); will(returnValue(true)); } }); assertThat(service.remove(user), is(true)); } @Test public void testStore() { final User user = new User(); user.setName("Test User1"); user.setEmail("test@continuous.com"); user.setPassword("password"); user.setAboutMe("テストユーザーです。"); Date date = new Date(); user.setCreatedAt(date); user.setUpdatedAt(date); context.checking(new Expectations() { { oneOf(mock).insert(user); will(returnValue(1L)); } }); assertThat(service.store(user), is(1L)); } @Test public void testUpdate() throws Exception { final User user = new User(); user.setId(1L); user.setEmail("updated@continuous.com"); context.checking(new Expectations() { { oneOf(mock).update(user); will(returnValue(true)); } }); assertThat(service.update(user), is(true)); } }
true
183e519fd214a121b24af38f0dffd50792c33003
Java
JaeDe0k/Baby_Temple
/serverNetwork/src/serverNetwork/Initial_Settings.java
UHC
590
2.53125
3
[]
no_license
package serverNetwork; public class Initial_Settings { private String serverAddress; private int TCPport; private int UDPport; public Initial_Settings() { this.serverAddress = "localhost"; //Ʈũ ּ this.TCPport = 5001; // TCP Ʈ ( ȸ ROOM ) this.UDPport = 5002; // UDP Ʈ ( ǽð Ʈũ ) } public String getServerAddress() { return serverAddress; } public int getTCPport() { return TCPport; } public int getUDPport() { return UDPport; } }
true
7b470620bd9a1933fd7e005156e936a350d0738f
Java
troyhart/yardsale
/core-rest/src/main/java/com/myco/rest/ServerSentEventProducerSupport.java
UTF-8
3,050
2.328125
2
[]
no_license
package com.myco.rest; import org.axonframework.queryhandling.SubscriptionQueryResult; import org.slf4j.Logger; import org.springframework.http.codec.ServerSentEvent; import reactor.core.publisher.Flux; import javax.servlet.http.HttpServletResponse; import java.time.Duration; public interface ServerSentEventProducerSupport { Logger logger(); /** * Turn {@link SubscriptionQueryResult}s into a flux of {@link ServerSentEvent}s of type T, with heartbeat * events merged in. * * @param queryResult subscription query results * @param seconds heartbeat period; the length of the interval duration with which "ping" events are emitted. * @param <T> the query model type. * @return flux of server sent events */ default <T> Flux<ServerSentEvent<?>> toSSEFlux( HttpServletResponse response, SubscriptionQueryResult<T, T> queryResult, long seconds ) { return Flux.merge(toSSEFlux(response, queryResult), toSSEHeartbeatFlux(seconds)) .doFinally(signalType -> logger().debug("SSE merged with heartbeat finalized; signalType: {}", signalType)); } /** * Turn {@link SubscriptionQueryResult}s into a flux of {@link ServerSentEvent}s of type T. * * @param queryResult subscription query results * @param <T> the query model type. * @return flux of server sent events */ default <T> Flux<ServerSentEvent<T>> toSSEFlux( HttpServletResponse response, SubscriptionQueryResult<T, T> queryResult ) { // refer to: https://serverfault.com/questions/801628/for-server-sent-events-sse-what-nginx-proxy-configuration-is-appropriate response.addHeader("Cache-Control", "no-cache"); response.addHeader("X-Accel-Buffering", "no"); return reactor.core.publisher.Flux.<T>create(emitter -> { queryResult.initialResult().doOnError(error -> logger().warn("Initial result error", error)) .doFinally(signalType -> logger().debug("Initial result finalized; signalType: {}", signalType)) .subscribe(emitter::next); queryResult.updates().buffer(Duration.ofMillis(500)).map(modelList -> modelList.get(modelList.size() - 1)) .doOnError(error -> logger().warn("Updates error", error)) .doFinally(signalType -> logger().debug("Updates finalized; signalType: {}", signalType)) .doOnComplete(emitter::complete).subscribe(emitter::next); }).doFinally(signalType -> logger().debug("SSE finalized; signalType: {}", signalType)) .map(data -> ServerSentEvent.<T>builder().data(data).event("message").build()); } /** * Turn the given number of seconds into an infinite flux of "ping" events with an interval duration (period) equal to seconds. * * @param seconds * @return */ default Flux<ServerSentEvent<?>> toSSEHeartbeatFlux(long seconds) { return Flux.interval(Duration.ofSeconds(seconds)) .doFinally(signalType -> logger().debug("Heartbeat finalized; signalType: {}", signalType)) .map(i -> ServerSentEvent.builder().event("ping").build()); } }
true
0888a932669a6a0099ef4511c692c25193d10093
Java
ydao10/PLE-2020
/BatchLayer/src/main/java/bigdata/UnusedClass/CovidEvolution.java
UTF-8
4,356
2.578125
3
[]
no_license
package bigdata; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import java.util.Map; import java.util.TreeMap; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.conf.Configured; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.NullWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.io.Writable; import org.apache.hadoop.mapreduce.Mapper; import org.apache.hadoop.mapreduce.Reducer; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.lib.input.TextInputFormat; import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat; import org.apache.hadoop.util.Tool; import org.apache.hadoop.util.ToolRunner; import com.google.gson.JsonParser; import com.google.gson.JsonObject; public class CovidEvolution extends Configured implements Tool{ public static class CovidEvolutionMapper extends Mapper<LongWritable, Text, Text, IntWritable> { private String word = ""; @Override public void setup(Mapper<LongWritable, Text, Text, IntWritable>.Context context) throws IOException, InterruptedException { this.word = context.getConfiguration().get("word"); } public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException { // On parse chaque ligne en objet JSON JsonParser parser = new JsonParser(); JsonObject tweetJSON = parser.parse(value.toString()).getAsJsonObject(); String texte = ""; try { texte = tweetJSON.get("text").getAsString(); } catch (Exception e) { return; } // On récupère le texte du tweet String champs[] = texte.split(" "); // Si le tweet est seulement un RT et pas une citation on ne le prend pas en compte if(champs[0]=="RT" && tweetJSON.get("is_quote_status")!=null) return ; // Si le texte ne contient pas le mot cherché on le prend pas en ciompte if(!texte.contains(word)) return ; String date = tweetJSON.get("created_at").getAsString(); String champs_date[] = date.split(" "); // On renvoie le couple date / int context.write(new Text(champs_date[1]+" "+champs_date[2]), new IntWritable(1)); } } public static class CovidEvolutionReducer extends Reducer<Text,IntWritable,Text,Text> { private TreeMap<String, Integer> march = null; @Override public void setup(Reducer<Text, IntWritable, Text, Text>.Context context) throws IOException, InterruptedException { this.march = new TreeMap<String, Integer>(); } public void reduce(Text key, Iterable<IntWritable> values,Context context) throws IOException, InterruptedException { int count = 0; for (IntWritable index : values) { count++; } this.march.put(key.toString(), count); } @Override public void cleanup(Reducer<Text, IntWritable, Text, Text>.Context context) throws IOException, InterruptedException { for(Map.Entry<String,Integer> pair : march.entrySet()) { context.write(new Text(pair.getKey()), new Text(Integer.toString(pair.getValue()))); } } } public int run(String args[]) throws IOException, ClassNotFoundException, InterruptedException { Configuration conf = new Configuration(); String word = ""; word = args[0]; conf.set("word", word); Job job = Job.getInstance(conf, "EvolutionInMarch"); job.setNumReduceTasks(1); job.setJarByClass(CovidEvolution.class); job.setMapperClass(CovidEvolutionMapper.class); job.setMapOutputKeyClass(Text.class); job.setMapOutputValueClass(IntWritable.class); job.setReducerClass(CovidEvolutionReducer.class); job.setOutputKeyClass(Text.class); job.setOutputValueClass(Text.class); job.setOutputFormatClass(TextOutputFormat.class); TextOutputFormat.setOutputPath(job, new Path(args[2])); return job.waitForCompletion(true) ? 0 : 1; } public static void main(String args[]) throws Exception { System.exit(ToolRunner.run(new CovidEvolution(), args)); } }
true
8159bd833bb7719d6d73a16c56719f0d34eedfdb
Java
openfact/openfact-plus
/src/main/java/org/clarksnut/services/util/SSOContext.java
UTF-8
3,342
2.078125
2
[ "Apache-2.0" ]
permissive
package org.clarksnut.services.util; import org.keycloak.KeycloakPrincipal; import org.keycloak.KeycloakSecurityContext; import org.keycloak.adapters.AdapterDeploymentContext; import org.keycloak.adapters.KeycloakDeployment; import org.keycloak.adapters.RefreshableKeycloakSecurityContext; import org.keycloak.jose.jws.JWSInputException; import org.keycloak.representations.AccessToken; import org.keycloak.representations.RefreshToken; import org.keycloak.util.TokenUtil; import javax.servlet.http.HttpServletRequest; import java.util.Map; public class SSOContext { private final HttpServletRequest httpServletRequest; public SSOContext(HttpServletRequest httpServletRequest) { this.httpServletRequest = httpServletRequest; } public AccessToken getParsedAccessToken() { KeycloakPrincipal<KeycloakSecurityContext> kcPrincipal = (KeycloakPrincipal<KeycloakSecurityContext>) httpServletRequest.getUserPrincipal(); return kcPrincipal.getKeycloakSecurityContext().getToken(); } public String getUsername() { KeycloakPrincipal<KeycloakSecurityContext> kcPrincipal = (KeycloakPrincipal<KeycloakSecurityContext>) httpServletRequest.getUserPrincipal(); return kcPrincipal.getKeycloakSecurityContext().getToken().getPreferredUsername(); } public Map<String, Object> getOtherClaims() { KeycloakPrincipal<KeycloakSecurityContext> kcPrincipal = (KeycloakPrincipal<KeycloakSecurityContext>) httpServletRequest.getUserPrincipal(); return kcPrincipal.getKeycloakSecurityContext().getToken().getOtherClaims(); } public String getToken() throws JWSInputException { RefreshableKeycloakSecurityContext ctx = (RefreshableKeycloakSecurityContext) httpServletRequest.getAttribute(KeycloakSecurityContext.class.getName()); return ctx.getTokenString(); } public RefreshToken getRefreshedToken() throws JWSInputException { RefreshableKeycloakSecurityContext ctx = (RefreshableKeycloakSecurityContext) httpServletRequest.getAttribute(KeycloakSecurityContext.class.getName()); String refreshToken = ctx.getRefreshToken(); return TokenUtil.getRefreshToken(refreshToken); } public boolean isOfflineToken(String refreshToken) throws JWSInputException { RefreshToken refreshTokenDecoded = TokenUtil.getRefreshToken(refreshToken); return refreshTokenDecoded.getType().equals(TokenUtil.TOKEN_TYPE_OFFLINE); } public String getRealm() { KeycloakPrincipal<KeycloakSecurityContext> kcPrincipal = (KeycloakPrincipal<KeycloakSecurityContext>) httpServletRequest.getUserPrincipal(); return kcPrincipal.getKeycloakSecurityContext().getRealm(); } public String getAccessToken() { KeycloakPrincipal<KeycloakSecurityContext> kcPrincipal = (KeycloakPrincipal<KeycloakSecurityContext>) httpServletRequest.getUserPrincipal(); return kcPrincipal.getKeycloakSecurityContext().getTokenString(); } public String getAuthServerBaseUrl() { AdapterDeploymentContext deploymentContext = (AdapterDeploymentContext) httpServletRequest.getServletContext().getAttribute(AdapterDeploymentContext.class.getName()); KeycloakDeployment deployment = deploymentContext.resolveDeployment(null); return deployment.getAuthServerBaseUrl(); } }
true
9f67db14d5ff0841093b5e1859133158d1449865
Java
apurba6211/DesignLab
/app/src/main/java/com/techsquad/MainActivity.java
UTF-8
578
1.835938
2
[]
no_license
package com.techsquad; import android.content.Intent; import android.os.Bundle; import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { setTheme(R.style.AppTheme); super.onCreate(savedInstanceState); if (!SharedPrefManager.getInstance(this).isLoggedIn()) { finish(); startActivity(new Intent(this, LandingActivity.class)); return; } setContentView(R.layout.activity_main); } }
true
85c5f57571be36f75afc1407b68c14651f416b37
Java
hyebin-seo/october
/workspace(spring)/01_NonSpring/src/main/java/com/test/nonspring03/MysqlDAO.java
UHC
234
2.0625
2
[]
no_license
package com.test.nonspring03; public class MysqlDAO implements DAO{ public MysqlDAO() { System.out.println("MysqlDAO Դϴ."); } @Override public void add() { System.out.println("MysqlDAO Դϴ."); } }
true
1ccbc574f141bcc1655ddca39155a0931804b184
Java
jasbircheema96/eight_puzzle_problem
/src/model/State.java
UTF-8
4,378
3.640625
4
[]
no_license
package model; import java.util.ArrayList; import java.util.List; import constant.Constants; public class State { private int[][] grid; public int[][] getGrid() { return grid; } public State() { this.grid = new int[Constants.GRID_SIZE][Constants.GRID_SIZE]; } State(State state) { this.grid = new int[Constants.GRID_SIZE][Constants.GRID_SIZE]; for (int row = 0; row < Constants.GRID_SIZE; row++) { for (int col = 0; col < Constants.GRID_SIZE; col++) { this.grid[row][col] = state.grid[row][col]; } } } public void print() { for (int row = 0; row < Constants.GRID_SIZE; row++) { for (int col = 0; col < Constants.GRID_SIZE; col++) { System.out.print(this.getGrid()[row][col] + " "); } System.out.println(); } } public List<State> nextPossibleStates() { List<State> nextPossibleStates = new ArrayList<State>(); Cell emptyCell = this.getEmptyCell(); Move leftMove = new Move(emptyCell, Direction.LEFT); Move rightMove = new Move(emptyCell, Direction.RIGHT); Move upMove = new Move(emptyCell, Direction.UP); Move downMove = new Move(emptyCell, Direction.DOWN); if (this.isValidMove(leftMove)) nextPossibleStates.add(this.makeMove(leftMove)); if (this.isValidMove(rightMove)) nextPossibleStates.add(this.makeMove(rightMove)); if (this.isValidMove(upMove)) nextPossibleStates.add(this.makeMove(upMove)); if (this.isValidMove(downMove)) nextPossibleStates.add(this.makeMove(downMove)); return nextPossibleStates; } public int distanceFromGoal() { // heuristic function -- sum of Manhattan distance int distance = 0; for (int row = 0; row < Constants.GRID_SIZE; row++) { for (int col = 0; col < Constants.GRID_SIZE; col++) { for (int gridRow = 0; gridRow < Constants.GRID_SIZE; gridRow++) { for (int gridCol = 0; gridCol < Constants.GRID_SIZE; gridCol++) { if (Constants.GOAL_STATE[row][col] == this.grid[gridRow][gridCol]) { distance += (Math.abs(row - gridRow) + Math.abs(col - gridCol)); } } } } } return distance; } public Cell getEmptyCell() { for (int row = 0; row < Constants.GRID_SIZE; row++) { for (int col = 0; col < Constants.GRID_SIZE; col++) { if (this.grid[row][col] == Constants.EMPTY_CELL) return new Cell(row, col); } } return null; } public State makeMove(Move move) { State state = new State(this); int row = move.getCell().getRow(); int col = move.getCell().getCol(); Direction direction = move.getDirection(); if (direction == Direction.LEFT) { state.grid[row][col] = state.grid[row][col - 1]; state.grid[row][col - 1] = Constants.EMPTY_CELL; } else if (direction == Direction.RIGHT) { state.grid[row][col] = state.grid[row][col + 1]; state.grid[row][col + 1] = Constants.EMPTY_CELL; } else if (direction == Direction.UP) { state.grid[row][col] = state.grid[row - 1][col]; state.grid[row - 1][col] = Constants.EMPTY_CELL; } else if (direction == Direction.DOWN) { state.grid[row][col] = state.grid[row + 1][col]; state.grid[row + 1][col] = Constants.EMPTY_CELL; } return state; } public boolean isValidMove(Move move) { int row = move.getCell().getRow(); int col = move.getCell().getCol(); Direction direction = move.getDirection(); if (direction == Direction.LEFT) { if (col <= 0) return false; } else if (direction == Direction.RIGHT) { if (col >= Constants.GRID_SIZE - 1) return false; } else if (direction == Direction.UP) { if (row <= 0) return false; } else if (direction == Direction.DOWN) { if (row >= Constants.GRID_SIZE - 1) return false; } return true; } public boolean isGoalState() { for (int row = 0; row < Constants.GRID_SIZE; row++) { for (int col = 0; col < Constants.GRID_SIZE; col++) { if (this.grid[row][col] != Constants.GOAL_STATE[row][col]) return false; } } return true; } public void randomlyInitialize() { List<Integer> orderedList = new ArrayList<Integer>(); for (int i = 0; i < Constants.GRID_SIZE * Constants.GRID_SIZE; i++) { orderedList.add(i); } for (int row = 0; row < Constants.GRID_SIZE; row++) { for (int col = 0; col < Constants.GRID_SIZE; col++) { int randomindex = (int) (Math.random() * orderedList.size()); this.grid[row][col] = orderedList.get(randomindex); orderedList.remove(randomindex); } } } }
true
d34e3147c7844a25d0e264dd791fdd92e075a43c
Java
rakulav/My-Android-App
/app/src/main/java/com/beamotivator/beam/fragments/NotificationFragment.java
UTF-8
4,846
2.046875
2
[]
no_license
package com.beamotivator.beam.fragments; import android.app.ActionBar; import android.graphics.drawable.Drawable; import android.os.Build; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.appcompat.widget.SwitchCompat; import androidx.fragment.app.Fragment; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.view.WindowManager; import android.widget.LinearLayout; import android.widget.TextView; import com.beamotivator.beam.R; import com.beamotivator.beam.adapters.AdapterNotifications; import com.beamotivator.beam.models.ModelNotification; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import java.util.ArrayList; import java.util.List; import java.util.Objects; public class NotificationFragment extends Fragment { //views RecyclerView notificationRv; private FirebaseAuth firebaseAuth; ArrayList<ModelNotification> notificationList; AdapterNotifications adapterNotifications; LinearLayout emptyMesg; String myId = ""; public NotificationFragment() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { Window window = getActivity().getWindow(); Drawable background = getActivity().getResources().getDrawable(R.drawable.main_gradient); window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS); window.setStatusBarColor(getActivity().getResources().getColor(android.R.color.transparent)); // window.setNavigationBarColor(getActivity().getResources().getColor(android.R.color.transparent)); window.setBackgroundDrawable(background); } View view = inflater.inflate(R.layout.fragment_notification,container,false); //init views notificationRv = view.findViewById(R.id.notificationsRv); firebaseAuth = FirebaseAuth.getInstance(); myId = Objects.requireNonNull(firebaseAuth.getCurrentUser()).getUid(); emptyMesg = view.findViewById(R.id.notificationsEmpty); notificationList = new ArrayList<>(); getAllNotifications(); return view; } private void getAllNotifications() {//linear layout for recyclerview LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity()); //show newest posts, load from last layoutManager.setStackFromEnd(true); layoutManager.setReverseLayout(true); //set this layout to recycler view notificationRv.setLayoutManager(layoutManager); DatabaseReference ref = FirebaseDatabase.getInstance().getReference("Extras"); ref.child(Objects.requireNonNull(firebaseAuth.getUid())).child("Notifications") .addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { notificationList.clear(); for(DataSnapshot ds:dataSnapshot.getChildren()){ //get data ModelNotification model = ds.getValue(ModelNotification.class); //add to list notificationList.add(model); //set adapter adapterNotifications = new AdapterNotifications(getActivity(),notificationList); //set to recycler view notificationRv.setAdapter(adapterNotifications); } if(notificationList.size() == 0) { emptyMesg.setVisibility(View.VISIBLE); notificationRv.setVisibility(View.GONE); } else{ emptyMesg.setVisibility(View.GONE); notificationRv.setVisibility(View.VISIBLE); } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); } }
true
31892f68e13f5e132fce36c9f020c6038f1b5682
Java
Tonyhui/cookbook
/food_service/src/main/java/com/cookbook/mapper/ShoppingCartMapper.java
UTF-8
4,003
1.820313
2
[]
no_license
package com.cookbook.mapper; import com.cookbook.entity.ShoppingCart; import com.cookbook.enums.Category; import com.cookbook.enums.OrderStatus; import com.cookbook.model.OrderModel; import org.apache.ibatis.annotations.Param; import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Repository; import java.math.BigDecimal; import java.util.Date; import java.util.List; @Repository public interface ShoppingCartMapper { /** * This method was generated by MyBatis Generator. * This method corresponds to the database table tb_shoppingcart * * @mbggenerated Sun Apr 26 14:12:09 CST 2015 */ int deleteByPrimaryKey(String orderId); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table tb_shoppingcart * * @mbggenerated Sun Apr 26 14:12:09 CST 2015 */ int insert(ShoppingCart record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table tb_shoppingcart * * @mbggenerated Sun Apr 26 14:12:09 CST 2015 */ int insertSelective(ShoppingCart record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table tb_shoppingcart * * @mbggenerated Sun Apr 26 14:12:09 CST 2015 */ ShoppingCart selectByPrimaryKey(String orderId); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table tb_shoppingcart * * @mbggenerated Sun Apr 26 14:12:09 CST 2015 */ int updateByPrimaryKeySelective(ShoppingCart record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table tb_shoppingcart * * @mbggenerated Sun Apr 26 14:12:09 CST 2015 */ int updateByPrimaryKey(ShoppingCart record); /** * @param userId * @param status * @return */ List<ShoppingCart> listByUserAndStatusWithPage(@Param("userId") String userId, @Param("status") List<OrderStatus> status, @Param("startRow") int startRow, @Param("pageSize") int pageSize); int countByUserAndStatusWithPage(@Param("userId") String userId, @Param("status") List<OrderStatus> status); List<ShoppingCart> listByUserAndStatusAndCategoriesWithPage(@Param("userId") String userId, @Param("status") List<OrderStatus> status, @Param("categories") List<Category> categories, @Param("startRow") int startRow, @Param("pageSize") int pageSize); List<ShoppingCart> listByUserAndStatus(@Param("userId") String userId, @Param("status") List<OrderStatus> status); @Async void waitingToSettle(@Param("userId") String userId, @Param("orders") String... orders); ShoppingCart sumAmountAndCountQuantityByUserAndOrderId(@Param("userId") String userId, @Param("orders") String... orders); ShoppingCart sumAmountAndCountQuantityByUserAndStatus(@Param("userId") String userId, @Param("statuses") List<OrderStatus> statuses); List<OrderModel> listOrderByStatusAndPeriod(@Param("statusList")List<OrderStatus> statusList,@Param("from")Date from,@Param("to")Date to, @Param("startRow")Integer startRow,@Param("pageSize")Integer pageSize); Integer sumDailyAmount(@Param("from")Date from,@Param("to")Date to,@Param("orderStatuses")List<OrderStatus> orderStatuses); int countByFoodIdAndStatus(@Param("foodId")String foodId,@Param("status")List<OrderStatus> status); int updateStatus(@Param("status")OrderStatus orderStatus,@Param("orderId")String orderId,@Param("toStatus")OrderStatus toStatus); }
true
c83c1008e2573c2aa0da79b78eaea4102105c8a7
Java
armpitfragrance/hwsys
/src/main/java/com/service/impl/TMaterialServiceImpl.java
UTF-8
3,282
2.203125
2
[]
no_license
package com.service.impl; import com.dao.impl.TMaterialDaoImpl; import com.entity.TMaterial; import com.service.TMaterialService; import com.utils.Page; import java.util.List; /** * 作者:ysq * 日期: 2020/12/16 15:40 * 描述: */ public class TMaterialServiceImpl implements TMaterialService { TMaterialDaoImpl tMaterialDao = new TMaterialDaoImpl(); @Override public int insert(TMaterial tMaterial) { return tMaterialDao.insert(tMaterial); } @Override public int delete(Integer id) { return tMaterialDao.delete(id); } @Override public int update(TMaterial tMaterial) { return tMaterialDao.update(tMaterial); } @Override public List<TMaterial> queryAll() { return tMaterialDao.queryAll(); } @Override public TMaterial queryTMaterialById(Integer id) { return tMaterialDao.queryTMaterialById(id); } @Override public Page<TMaterial> queryTMaterialByPage(int pageNo, int pageSize) { Page<TMaterial> page = new Page<>(); //设置当前页码 page.setPageNum(pageNo); //设置每页数据数量 page.setPageSize(pageSize); //设置总数据数量 int pageTotalCounts = tMaterialDao.queryPageTotalCounts(); page.setPageTotalCount(Math.toIntExact(pageTotalCounts)); //设置总页数 int pageTotal = pageTotalCounts % pageSize > 0 ? (pageTotalCounts / pageSize + 1) : (pageTotalCounts / pageSize); page.setPageTotal(pageTotal); //设置当前页数据 List<TMaterial> items = tMaterialDao.queryTMaterialByPage(pageNo, pageSize); page.setItems(items); return page; } @Override public Page<TMaterial> queryTMaterialByPageByCid(int c_id,String name,String date, int pageNo, int pageSize) { Page<TMaterial> page = new Page<>(); //设置当前页码 page.setPageNum(pageNo); //设置每页数据数量 page.setPageSize(pageSize); //设置总数据数量 int pageTotalCounts = tMaterialDao.queryPageTotalCountsByCid(c_id); page.setPageTotalCount(Math.toIntExact(pageTotalCounts)); //设置总页数 int pageTotal = pageTotalCounts % pageSize > 0 ? ((pageTotalCounts / pageSize) + 1) : (pageTotalCounts / pageSize); page.setPageTotal(pageTotal); int begin = 0; if (page.getPageNum() == 0) { begin = 0; } else { begin = (page.getPageNum() - 1) * pageSize; } //设置当前页数据 List<TMaterial> items = tMaterialDao.queryTMaterialByPageByCid(c_id, name, date, begin, pageSize); // if (title == null && time == null) { // items = noticeDao.queryNoticeByPage(begin, pageSize); // } else if (title != null && time == null) { // items = noticeDao.queryNoticeByTitle(title,begin, pageSize); // } else if (title == null && time != null) { // items = noticeDao.queryNoticeByNoticeTime(time,begin, pageSize); // } else if (title != null && time != null) { // items = noticeDao.queryNoticeByTitleAndNoticeTime(title, time,begin, pageSize); // } page.setItems(items); return page; } }
true
73460a1b655f3588622242ef83ce44c2b28d64e3
Java
alldatacenter/alldata
/olap/kylin/src/query-common/src/main/java/org/apache/kylin/query/util/QueryAliasMatchInfo.java
UTF-8
2,205
1.789063
2
[ "Apache-2.0", "BSD-3-Clause", "MIT" ]
permissive
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.kylin.query.util; import java.util.LinkedHashMap; import org.apache.kylin.query.relnode.ColumnRowType; import org.apache.kylin.metadata.model.NDataModel; import org.apache.kylin.metadata.model.alias.AliasMapping; import org.apache.kylin.guava30.shaded.common.collect.BiMap; import org.apache.kylin.guava30.shaded.common.collect.HashBiMap; public class QueryAliasMatchInfo extends AliasMapping { // each alias's ColumnRowType private LinkedHashMap<String, ColumnRowType> alias2CRT; // for model view private NDataModel model; public QueryAliasMatchInfo(BiMap<String, String> aliasMapping, LinkedHashMap<String, ColumnRowType> alias2CRT) { super(aliasMapping); this.alias2CRT = alias2CRT; } private QueryAliasMatchInfo(BiMap<String, String> aliasMapping, NDataModel model) { super(aliasMapping); this.model = model; } public static QueryAliasMatchInfo fromModelView(String queryTableAlias, NDataModel model) { BiMap<String, String> map = HashBiMap.create(); map.put(queryTableAlias, model.getAlias()); return new QueryAliasMatchInfo(map, model); } LinkedHashMap<String, ColumnRowType> getAlias2CRT() { return alias2CRT; } public boolean isModelView() { return model != null; } public NDataModel getModel() { return model; } }
true
3e66206cbc96e636f45c285909105c34cabfb347
Java
nextworks-it/MEC-applications
/MEC012/mec012-client/src/main/java/io/swagger/client/model/RabInfoUeInfo.java
UTF-8
3,409
1.992188
2
[ "Apache-2.0" ]
permissive
/* * ETSI GS MEC 012 - Radio Network Information API * The ETSI MEC ISG MEC012 Radio Network Information API described using OpenAPI. * * OpenAPI spec version: 2.1.1 * * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ package io.swagger.client.model; import com.google.gson.annotations.SerializedName; import io.swagger.v3.oas.annotations.media.Schema; import java.util.ArrayList; import java.util.List; import java.util.Objects; /** * RabInfoUeInfo */ @javax.annotation.Generated(value = "io.swagger.codegen.v3.generators.java.JavaClientCodegen", date = "2020-12-09T15:33:56.133+01:00[Europe/Rome]") public class RabInfoUeInfo { @SerializedName("associateId") private List<AssociateId> associateId = null; @SerializedName("erabInfo") private List<RabInfoErabInfo> erabInfo = null; public RabInfoUeInfo associateId(List<AssociateId> associateId) { this.associateId = associateId; return this; } public RabInfoUeInfo addAssociateIdItem(AssociateId associateIdItem) { if (this.associateId == null) { this.associateId = new ArrayList<AssociateId>(); } this.associateId.add(associateIdItem); return this; } /** * 0 to N identifiers to associate the event for a specific UE or flow. * @return associateId **/ @Schema(description = "0 to N identifiers to associate the event for a specific UE or flow.") public List<AssociateId> getAssociateId() { return associateId; } public void setAssociateId(List<AssociateId> associateId) { this.associateId = associateId; } public RabInfoUeInfo erabInfo(List<RabInfoErabInfo> erabInfo) { this.erabInfo = erabInfo; return this; } public RabInfoUeInfo addErabInfoItem(RabInfoErabInfo erabInfoItem) { if (this.erabInfo == null) { this.erabInfo = new ArrayList<RabInfoErabInfo>(); } this.erabInfo.add(erabInfoItem); return this; } /** * Information on E-RAB as defined below. * @return erabInfo **/ @Schema(description = "Information on E-RAB as defined below.") public List<RabInfoErabInfo> getErabInfo() { return erabInfo; } public void setErabInfo(List<RabInfoErabInfo> erabInfo) { this.erabInfo = erabInfo; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } RabInfoUeInfo rabInfoUeInfo = (RabInfoUeInfo) o; return Objects.equals(this.associateId, rabInfoUeInfo.associateId) && Objects.equals(this.erabInfo, rabInfoUeInfo.erabInfo); } @Override public int hashCode() { return Objects.hash(associateId, erabInfo); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class RabInfoUeInfo {\n"); sb.append(" associateId: ").append(toIndentedString(associateId)).append("\n"); sb.append(" erabInfo: ").append(toIndentedString(erabInfo)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
true
bbd3f7f82be3122bc648efea4d770094bac1d662
Java
BeomjunLee/Algorithm
/src/com/company/string/ReverseString2.java
UTF-8
1,375
4.09375
4
[]
no_license
package com.company.string; import java.util.Scanner; public class ReverseString2 { /** * 설명 * * 영어 알파벳과 특수문자로 구성된 문자열이 주어지면 영어 알파벳만 뒤집고, * * 특수문자는 자기 자리에 그대로 있는 문자열을 만들어 출력하는 프로그램을 작성하세요. * * 입력 * 첫 줄에 길이가 100을 넘지 않는 문자열이 주어집니다. * * 출력 * 첫 줄에 알파벳만 뒤집힌 문자열을 출력합니다. */ public static String solution(String str) { int left = 0; int right = str.length() - 1; char[] result = str.toCharArray(); while (left < right) { if (!Character.isAlphabetic(result[left])) left++; else if (!Character.isAlphabetic(result[right])) right--; else { char tmp = result[left]; result[left] = result[right]; result[right] = tmp; left++; right--; } } return String.valueOf(result); } public static void main(String[] args) { Scanner scan = new Scanner(System.in); String str = scan.next(); String result = solution(str); System.out.println(result); } }
true
e2bc6e2931ffd84185724e483ea76e6119a4586b
Java
LuQinPeng/Hms_lqp
/LQPhms/src/com/hms/dao/lqp/DrugDaoImp.java
UTF-8
2,179
2.28125
2
[]
no_license
package com.hms.dao.lqp; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.orm.hibernate3.HibernateTemplate; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; import com.hms.entity.Drug; import com.hms.entity.Pager; import com.hms.util.PagerHelper; @Repository("drugDaoImp") public class DrugDaoImp implements DrugDao { @Autowired private HibernateTemplate hibernateTemplate; public HibernateTemplate getHibernateTemplate() { return hibernateTemplate; } public void setHibernateTemplate(HibernateTemplate hibernateTemplate) { this.hibernateTemplate = hibernateTemplate; } public Map findById(int id) { String hql="select new Map(drugId as drugId ,drugName as drugName,drugSpell as drugSpell,drugSpec as drugSpec,drugPrice as drugPrice,state as state,DATE_FORMAT(drugdate,'%Y %m %d') as drugdate)from Drug where drugId=? "; return (Map) this.hibernateTemplate.find(hql,id).get(0); } public void delete(Drug drug) { // TODO Auto-generated method stub this.hibernateTemplate.delete(drug); } public void update(Drug drug) { // TODO Auto-generated method stub this.hibernateTemplate.update(drug); } @Transactional public void save(Drug drug) { // TODO Auto-generated method stub this.hibernateTemplate.save(drug); } public boolean isExists(String drugName) { // TODO Auto-generated method stub String hql="select count(*) from Drug where drugName= ?"; int count=Integer.parseInt(this.hibernateTemplate.find(hql,drugName).get(0).toString()); return count>0?true:false; } public Pager findByPages(Pager pager) { String hql="select new Map(drugId as drugId ,drugName as drugName,drugSpell as drugSpell,drugSpec as drugSpec,drugPrice as drugPrice,state as state,DATE_FORMAT(drugdate,'%Y %m %d') as drugdate)from Drug"; String hql1="select count(*) from Drug"; Pager p=this.hibernateTemplate.execute(new PagerHelper(hql, hql1, null, pager.getCurPage(),pager.getPageSize())); return p; } }
true
09fa14e185ea2a1ad4b49fa3b076c3d39b449330
Java
AlexandruSimon1/Tekwill-Courses
/WorkAtLesson/Bar/Bar.java
UTF-8
811
3.703125
4
[]
no_license
package TekwillCourses.WorkAtLesson.Bar; public class Bar { private Integer foo = 15; static String text = " "; public Integer getFoo() { return foo; } public void setFoo(Integer foo) { this.foo = foo; } public static int add(int a, int b) { return a + b; } public static double add(double a, int b) { return a + b; } public static double getAverage(short a, short b) { return (a + b) / 2.0; } public static double getAverage(byte a, byte b, byte c) { return (a + b + c) / 3.0; } public static double getAverage(double... values) { double result = 0; for (int i = 0; i < values.length; i++){ result +=values[i]; } return result/values.length; } }
true
973ab51679d03d0d6bbfca5cf5b5bd0228d75ed6
Java
francis-pouatcha/plhpkix
/plh.pkix.parent/plh.pkix.core/plh.pkix.core.utils/src/org/adorsys/plh/pkix/core/utils/X509CertificateHolderCollection.java
UTF-8
1,462
2.515625
3
[]
no_license
package org.adorsys.plh.pkix.core.utils; import org.bouncycastle.cert.X509CertificateHolder; import org.bouncycastle.util.Arrays; public class X509CertificateHolderCollection { private final X509CertificateHolder[] x509CertificateHolders; public X509CertificateHolderCollection( X509CertificateHolder[] x509CertificateHolders) { this.x509CertificateHolders = x509CertificateHolders; } public X509CertificateHolder findBySubjectKeyIdentifier(byte[] keyId){ if(x509CertificateHolders==null) return null; for (X509CertificateHolder x509CertificateHolder : x509CertificateHolders) { byte[] subjectKeyIdentifier = KeyIdUtils.readSubjectKeyIdentifierAsByteString(x509CertificateHolder); if(Arrays.areEqual(keyId, subjectKeyIdentifier)){ return x509CertificateHolder; } } return null; } public X509CertificateHolder findBySubjectAndIssuerKeyId(byte[] subjectKeyId, byte[] issuerKeyId){ if(x509CertificateHolders==null) return null; for (X509CertificateHolder x509CertificateHolder : x509CertificateHolders) { byte[] subjectKeyIdentifier = KeyIdUtils.readSubjectKeyIdentifierAsByteString(x509CertificateHolder); byte[] authorityKeyIdentifier = KeyIdUtils.readAuthorityKeyIdentifierAsByteString(x509CertificateHolder); if( Arrays.areEqual(subjectKeyId, subjectKeyIdentifier) && Arrays.areEqual(issuerKeyId, authorityKeyIdentifier) ){ return x509CertificateHolder; } } return null; } }
true
8f3c476bd749801e646e4eb94d9a333eb76533cf
Java
aashitasharma/code-kata
/src/main/java/com/harcyah/kata/misc/poker/HighCardComparator.java
UTF-8
367
2.90625
3
[]
no_license
package com.harcyah.kata.misc.poker; import java.util.Comparator; public class HighCardComparator implements Comparator<PokerHand> { @Override public int compare(PokerHand left, PokerHand right) { PokerCard topLeft = left.getCards().get(0); PokerCard topRight = right.getCards().get(0); return topLeft.compareTo(topRight); } }
true
337137f55910d2d460d115288e4aa5b5504c5219
Java
hengyiqun/ip
/src/main/java/duke/Duke.java
UTF-8
2,111
3.296875
3
[]
no_license
package duke; import duke.commands.ErrorCommand; import duke.parser.Parser; import duke.storage.Storage; import duke.tasks.TaskList; import duke.ui.Ui; import duke.commands.Command; import java.io.FileNotFoundException; import java.io.File; import java.io.IOException; /** * Duke allows the user to maintain a list of tasks, and responses to user commands. */ public class Duke { private Storage storage; private TaskList tasks; private Ui ui; private String filePath = ""; /** * Initialises Duke. * * @param filePath File path to a .txt file containing the list of tasks. */ public Duke(String filePath) { this.ui = new Ui(); this.storage = new Storage(filePath); this.filePath = filePath; try { tasks = new TaskList(storage.load()); } catch (FileNotFoundException e) { tasks = new TaskList(); File directory = new File("data"); directory.mkdir(); File file = new File(filePath); try { file.createNewFile(); } catch (IOException ex){ new ErrorCommand(tasks, ex.getMessage()); } } } /** * Returns response from Duke when the user keys in his / her input. * * @param input String input from the user. * @return String response from Duke. */ public String getResponse(String input) { Parser parser = new Parser(this.tasks); Command command = parser.parse(input); command = command.process(); // message is generated before modifying the task list so that we can get // the corresponding string for the deleted task when delete is called String message = command.toString(); this.tasks = command.execute(); this.storage.save(this.tasks); return "Duke says:\n" + this.ui.format(message); } /** * Returns a greeting, in String, to the user. * * @return Greeting, in String. */ public String getGreeting() { return this.ui.greet(); } }
true
5896ea85bf9e99933218dd01171796dd501780af
Java
JohanF/DatabaseLab
/StudentPortal.java
UTF-8
8,216
3.40625
3
[]
no_license
import java.sql.*; // JDBC stuff. import java.io.*; // Reading user input. public class StudentPortal { /* * This is the driving engine of the program. It parses the command-line * arguments and calls the appropriate methods in the other classes. * * You should edit this file in two ways: 1) Insert your database username * and password (no @medic1!) in the proper places. 2) Implement the three * functions getInformation, registerStudent and unregisterStudent. */ public static void main(String[] args) { if (args.length == 1) { try { DriverManager.registerDriver(new oracle.jdbc.OracleDriver()); String url = "jdbc:oracle:thin:@tycho.ita.chalmers.se:1521/kingu.ita.chalmers.se"; String userName = "vtda357_075"; // Your username goes here! String password = "sandw1cht1me"; // Your password goes here! Connection conn = DriverManager.getConnection(url, userName, password); String student = args[0]; // This is the identifier for the // student. BufferedReader input = new BufferedReader( new InputStreamReader(System.in)); System.out.println("Welcome!"); while (true) { System.out.println("Please choose a mode of operation:"); System.out.print("? > "); String mode = input.readLine(); if ((new String("information")).startsWith(mode .toLowerCase())) { /* Information mode */ getInformation(conn, student); } else if ((new String("register")).startsWith(mode .toLowerCase())) { /* Register student mode */ System.out.print("Register for what course? > "); String course = input.readLine(); registerStudent(conn, student, course); } else if ((new String("unregister")).startsWith(mode .toLowerCase())) { /* Unregister student mode */ System.out.print("Unregister from what course? > "); String course = input.readLine(); unregisterStudent(conn, student, course); } else if ((new String("quit")).startsWith(mode .toLowerCase())) { System.out.println("Goodbye!"); break; } else { System.out .println("Unknown argument, please choose either " + "information, register, unregister or quit!"); continue; } } conn.close(); } catch (SQLException e) { System.err.println(e); System.exit(2); } catch (IOException e) { System.err.println(e); System.exit(2); } } else { System.err.println("Wrong number of arguments"); System.exit(3); } } static void getInformation(Connection conn, String student) throws SQLException { Statement statement = conn.createStatement(); ResultSet resultset = statement .executeQuery("SELECT name, programme, branch " + "FROM StudentsFollowing " + "WHERE id = '" + student + "'"); System.out.println("Information for student " + student + "\n----------------------------------------------"); while (resultset.next()) { String name = resultset.getString("name"); String program = resultset.getString("programme"); String branch = resultset.getString("branch"); System.out.println("Name: " + name + "\nLine: " + program + "\nBranch: " + branch); } Statement statement2 = conn.createStatement(); ResultSet resultset2 = statement2 .executeQuery("SELECT cid, grade, credits " + "FROM FinishedCourses " + "WHERE id = '" + student + "'"); System.out.println("\n\nRead courses (code, credits: grade):"); while (resultset2.next()) { // String name = resultset.getString("name"); String cid = resultset2.getString("cid"); String credits = resultset2.getString("credits"); String grade = resultset2.getString("grade"); System.out.println(cid + " , " + credits + " : " + grade); } Statement statement3 = conn.createStatement(); String query = "SELECT * " + "FROM Registrations RIGHT INNER JOIN course ON course = course.cid " + "WHERE student = '" + student + "'"; ResultSet resultset3 = statement3 .executeQuery(query); System.out.println("\n\nRegistered courses (code, credits: status):"); while (resultset3.next()) { String cid = resultset3.getString("course"); String credits = resultset3.getString("credits"); String status = resultset3.getString("status"); if (status.equals("Registered")) { System.out.println("(" + cid + "), " + credits + " : " + status); } else { Statement statement4 = conn.createStatement(); ResultSet resultset4 = statement4 .executeQuery("SELECT queueSpot " + "FROM CourseQueuePositions " + "WHERE student = '" + student + "' AND course = '" + cid + "'"); while (resultset4.next()) { int queueSpot = resultset4.getInt("queueSpot"); System.out.println("(" + cid + "), " + credits + ": waiting as nr " + queueSpot); } } } Statement statement5 = conn.createStatement(); ResultSet resultset5 = statement5.executeQuery("SELECT * " + "FROM PathToGraduation " + "WHERE id = '" + student + "'"); while (resultset5.next()) { // String name = resultset.getString("name"); String id = resultset5.getString("id"); String totSeminar = resultset5.getString("totSeminar"); String totMathCredits = resultset5.getString("totMathCredits"); String totResearchCredits = resultset5 .getString("totResearchCredits"); String totCredits = resultset5.getString("totCredits"); String hasGraduated = resultset5.getString("hasGraduated"); System.out.println("\n\nSeminar courses taken: " + totSeminar); System.out.println("Maths credits taken: " + totMathCredits); System.out .println("Reasearch credits taken: " + totResearchCredits); System.out.println("Total credits taken: " + totCredits); if (hasGraduated.equals("Graduated")) { System.out .println("Fulfills the requirements for graduation: Yes"); } else System.out .println("Fulfills the requirements for graduation: No"); } } static void registerStudent(Connection conn, String student, String course) throws SQLException { Statement stmt = conn.createStatement(); String regQuery = "INSERT INTO Registrations VALUES ('" + student + "', '" + course + "', 'Registered')"; String checkQueueQuery = "SELECT queueSpot FROM CourseQueuePositions WHERE student = '" + student + "' AND course = '" + course + "'"; try { stmt.executeUpdate(regQuery); ResultSet queueSet = stmt.executeQuery(checkQueueQuery); System.out.println(queueSet); if (queueSet.next()) { System.out.println("Course " + course + "is full, you are put in the waiting list as number " + queueSet.getInt("queueSpot") + "."); } else { System.out .println("You are now successfully registered to course " + course + "!"); } } catch (SQLException e) { int eCode = e.getErrorCode(); if (eCode == 20001) { System.out .println("You can't register to a course you've already passed."); } else if (eCode == 20002) { System.out.println("You are already registered to " + course + "."); } else if (eCode == 20003) { System.out .println("You are missing some prerequisites to read this course."); } else if (eCode == 20004) { System.out.println("You are already in the queue for " + course + "."); } else { e.printStackTrace(); } } } static void unregisterStudent(Connection conn, String student, String course) throws SQLException { try { System.out.println("start"); Statement stmt = conn.createStatement(); System.out.println("stmt =" + stmt); String deleteQuery = "DELETE FROM Registrations " + "WHERE student = '" + student + "' AND course = '" + course + "'"; System.out.println("deleteQuery =" + deleteQuery); int result = stmt.executeUpdate(deleteQuery); if(result != 0){ System.out .println("You've succesfully been unregistered from the course: " + course); } else { System.out.println("You are neither registered nor in the queue for " + course + " and is therefore already not enlisted on the course."); } } catch (SQLException e) { e.printStackTrace(); } } }
true
2df9d1dabc1b930cf6d77d072d8ad92521c0e245
Java
ServiceDDS/mote-cloud
/httpserverapp_src/edu/uma/motecloud/apps/pachube/NewSampleListener.java
UTF-8
1,963
2.453125
2
[]
no_license
package edu.uma.motecloud.apps.pachube; import java.util.Hashtable; import MoteCloud.SampleTopic; import ServiceDDS.servicetopic.ServiceTopic; import ServiceDDS.servicetopic.ServiceTopicListener; import edu.uma.motecloud.apps.common.VariableStream; public class NewSampleListener implements ServiceTopicListener { Hashtable<String,VariableStream> variables = new Hashtable<String,VariableStream>(); public NewSampleListener(VariableStream[] vars) { System.out.println("NewSampleListener: constructor"); if (vars!= null) for (int i=0; i<vars.length;i++) { this.variables.put(vars[i].toString(), vars[i]); System.out.println("NewSampleListener: added <"+vars[i].toString()+">"); } } @Override public void on_data_available(ServiceTopic serviceTopic) { System.out.println("NewSampleListener.on_data_available"); Object[] data = serviceTopic.take(); for (int i=0; i<data.length; i++) { SampleTopic newSample = (SampleTopic)data[i]; VariableStream id = new VariableStream(newSample.variableName,newSample.moteID,newSample.location); System.out.println("NewSampleListener.on_data_available: varID=<"+id.toString()+">"); if (this.variables.containsKey(id.toString())) { id = variables.get(id.toString()); double v = new Double(newSample.data).doubleValue(); System.out.println("NewSampleListener.on_data_available: showing sample: "+newSample.sample+" with value "+v+"..."); id.updateFeed(v); System.out.println("NewSampleListener.on_data_available: done!"); } } } @Override public void on_requested_deadline_missed(ServiceTopic arg0) { // TODO Auto-generated method stub } @Override public void on_sample_lost(ServiceTopic arg0) { // TODO Auto-generated method stub } }
true
2dd72312778e96efb2c5582c6fa1dfec4987cfde
Java
matisses/BCS
/src/java/co/matisses/bcs/rest/DigitoVerificacionREST.java
UTF-8
1,699
2.5
2
[ "MIT" ]
permissive
package co.matisses.bcs.rest; import javax.ws.rs.core.Response; import java.util.logging.Logger; import javax.ejb.Stateless; import javax.ejb.TransactionAttribute; import javax.ejb.TransactionAttributeType; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; /** * * @author jguisao */ @Stateless @Path("digitoverificacion") public class DigitoVerificacionREST { private static final Logger CONSOLE = Logger.getLogger(DigitoVerificacionREST.class.getSimpleName()); private int calcularDigitoVerificacion(String nit) { int digitoChequeo = -1; int lisPeso[] = {71, 67, 59, 53, 47, 43, 41, 37, 29, 23, 19, 17, 13, 7, 3}; int liSuma = 0; if (nit != null && nit.trim().length() > 0) { while (nit.length() < 15) { nit = "0" + nit; } try { for (int i = 0; i < 15; i++) { liSuma += (new Integer(nit.substring(i, i + 1))) * lisPeso[i]; } digitoChequeo = liSuma % 11; if (digitoChequeo >= 2) { digitoChequeo = 11 - digitoChequeo; } } catch (Exception e) { return -2; } } else { return -1; } return digitoChequeo; } @GET @Path("consultar/{nit}") @Produces({MediaType.APPLICATION_JSON}) @TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED) public Response obtenerDigitoVerificacion(@PathParam("nit") String nit) { return Response.ok(calcularDigitoVerificacion(nit)).build(); } }
true
be10b600c224dd8a2780870c8cd31f12af39de6e
Java
C4rlos316/WebPokemon
/app/src/main/java/com/prueba/webpokemon/MainActivity.java
UTF-8
3,549
2.328125
2
[]
no_license
package com.prueba.webpokemon; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.GridLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.os.Bundle; import android.util.Log; import com.prueba.webpokemon.Adapter.ListaAdapter; import com.prueba.webpokemon.Models.Pokemon; import com.prueba.webpokemon.Models.PokemonRespuesta; import com.prueba.webpokemon.PokeApi.PokeApiServices; import java.util.ArrayList; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; public class MainActivity extends AppCompatActivity { private Retrofit retrofit; private RecyclerView recyclerView; private ListaAdapter adapter; private int offset; private boolean aptoCargar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); recyclerView=findViewById(R.id.recyclerView); adapter=new ListaAdapter(this); recyclerView.setAdapter(adapter); recyclerView.setHasFixedSize(true); final GridLayoutManager layoutManager = new GridLayoutManager(this,3); recyclerView.setLayoutManager(layoutManager); recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() { @Override public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) { super.onScrolled(recyclerView, dx, dy); if (dy>0){ int visibleItemCount= layoutManager.getChildCount(); int totalItemCount= layoutManager.getItemCount(); int pastVisibleItem= layoutManager.findFirstVisibleItemPosition(); if (aptoCargar){ if (visibleItemCount+pastVisibleItem>=totalItemCount){ aptoCargar=false; offset +=20; obtenerDatos(offset); } } } } }); retrofit=new Retrofit.Builder().baseUrl("https://pokeapi.co/api/v2/") .addConverterFactory(GsonConverterFactory.create()) .build(); aptoCargar=true; offset = 0; obtenerDatos(offset); } private void obtenerDatos(int offset) { PokeApiServices services=retrofit.create(PokeApiServices.class); Call<PokemonRespuesta> pokemonRespuestaCall=services.obtenerListaPokemon(20,offset); pokemonRespuestaCall.enqueue(new Callback<PokemonRespuesta>() { @Override public void onResponse(Call<PokemonRespuesta> call, Response<PokemonRespuesta> response) { aptoCargar=true; if (response.isSuccessful()){ PokemonRespuesta pokemonRespuesta= response.body(); ArrayList<Pokemon> listaPokemon=pokemonRespuesta.getResults(); adapter.adicionarPokemon(listaPokemon); } else { Log.e("","onResponse"+response.errorBody()); } } @Override public void onFailure(Call<PokemonRespuesta> call, Throwable t) { aptoCargar=true; Log.e("",t.getMessage()); } }); } }
true
11a1408a6690e8d2c0c04fce10f9825bd1087175
Java
elevy30/spark-kafka-elastic
/src/main/java/skes/kafka/consprodexample/KafkaSourceBean.java
UTF-8
1,282
2.125
2
[]
no_license
package skes.kafka.consprodexample; import org.apache.kafka.clients.consumer.ConsumerRecords; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import javax.annotation.PostConstruct; import java.util.Collection; /** * Created on 1/17/18 */ @Service public class KafkaSourceBean extends KafkaBean { @Value("${group.id}") private String groupId; private KafkaSource kafkaSource; private final Logger logger = LoggerFactory.getLogger(getClass()); @PostConstruct private void init() { kafkaSource = new KafkaSource(bootstrapServers, groupId, buildProperties()); logger.info("Kafka consumer configured for nodes: " + bootstrapServers); } public KafkaSourceBean subscribe(Collection<String> topics) { kafkaSource.subscribe(topics); return this; } public ConsumerRecords<String, String> poll(long timeout) { return kafkaSource.poll(timeout); } public KafkaSourceBean unsubscribe() { kafkaSource.unsubscribe(); return this; } public void close() { kafkaSource.close(); } public void shutdown() { kafkaSource.shutdown(); } }
true
1ca59ddc249e0a1aa87600f4819f34e0a3a5a118
Java
FrancisTheTerrible/someCourse
/src/someCourse/Section_5/LastDigitChecker.java
UTF-8
1,516
4.1875
4
[]
no_license
package Section_5; /* Write a method named hasSameLastDigit with three parameters of type int. Each number should be within the range of 10 (inclusive) - 1000 (inclusive). If one of the numbers is not within the range, the method should return false. The method should return true if at least two of the numbers share the same rightmost digit; otherwise, it should return false. Origin: Java course by Tim Buchalka */ /* This solution is incorrect even though it was marked as correct. Trouble is in high limit - hasSameLastDigit(1000,1000,1000) should return true, but following return false. */ public class LastDigitChecker { public static boolean hasSameLastDigit(int firstNumber, int secondNumber, int thirdNumber){ // Check that all numbers are within the range 10,1000 if ( firstNumber < 10 || firstNumber > 999 || // Should be firstNumber > 1000 secondNumber < 10 || secondNumber > 999 || // Should be secondNumber > 1000 thirdNumber < 10 || thirdNumber> 999 // Should be thirdNumber > 1000 ){ return false; } // Reminder after dividing by 10 is the last digit. // If they do match, then condition is fulfilled. return (firstNumber % 10) == (secondNumber % 10) || (firstNumber % 10) == (thirdNumber % 10) || (secondNumber % 10) == (thirdNumber % 10); } public static boolean isValid(int number){ return number >= 10 && number <= 1000; } }
true
34ae0e35a733855ee47c4051442fe989c12dd2d1
Java
dynastywind/ImageShifter
/ImageShifter/src/main/java/cisc/awas/image_shifter/service/ImageShiftService.java
UTF-8
441
2.21875
2
[]
no_license
package cisc.awas.image_shifter.service; public interface ImageShiftService { /** * Primary method to shift images. */ public void shiftImage(); /** * Retrieve rows count in the original image table. * @return The rows count in the original image table */ public long imageCounts(); /** * Reset current image id to resume the task if exception occurs. */ public void resetCurrentImageId(); }
true
fb0bc71a256158fc4be9aca7534339342cc4f791
Java
surendart/searchsdk-android
/SearchDemo/src/main/java/com/yahoo/android/search/showcase/Utils/Utils.java
UTF-8
3,515
2.4375
2
[ "Zlib" ]
permissive
package com.yahoo.android.search.showcase.Utils; import android.content.Context; import android.util.DisplayMetrics; import android.util.Log; import android.view.WindowManager; import com.yahoo.android.search.showcase.data.TumblrData; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.InputStream; import java.util.ArrayList; import java.util.List; public class Utils { private static DisplayMetrics displayMetrics = null; public static int getScreenWidth(Context c) { displayMetrics = getDisplayMetrics(c); return displayMetrics.widthPixels; } public static synchronized DisplayMetrics getDisplayMetrics(Context c) { if (displayMetrics == null) { displayMetrics = new DisplayMetrics(); WindowManager wm = (WindowManager) c.getSystemService(Context.WINDOW_SERVICE); wm.getDefaultDisplay().getMetrics(displayMetrics); } return displayMetrics; } public static List<TumblrData> parseTumblrDataList(Context context) { List<TumblrData> tumblrDataList = new ArrayList<TumblrData>(); String tumblrResponse = getTumblrResponse(context); try { JSONObject tumblrJson = new JSONObject(tumblrResponse); JSONArray responseObjects = tumblrJson.getJSONArray("response"); for (int counter = 0; counter < responseObjects.length(); counter++) { JSONObject responseObj = responseObjects.getJSONObject(counter); String blogName = responseObj.getString("blog_name"); String caption = responseObj.getString("caption"); String post_url = responseObj.getString("post_url"); JSONArray tags = responseObj.getJSONArray("tags"); List<String> tagList = new ArrayList<String>(); for (int index = 0; index < tags.length(); index++) { tagList.add((String)tags.get(index)); } JSONArray photos = responseObj.getJSONArray("photos"); String photoUrl = ""; for (int idx = 0; idx < photos.length(); idx++) { JSONObject item = photos.getJSONObject(idx); JSONArray photoSizes = item.getJSONArray("alt_sizes"); JSONObject photoSize = photoSizes.getJSONObject(0); photoUrl = photoSize.getString("url"); } TumblrData tumblrData = new TumblrData(blogName, post_url, tagList, caption, photoUrl); tumblrDataList.add(tumblrData); } } catch (JSONException e) { Log.e("Utils", e.getMessage()); } return tumblrDataList; } /** * * @param context * @return response String * * Reading response from local file. * Developers should be able to make network calls or get the response from any source. */ public static String getTumblrResponse(Context context) { String tumblrResponse = null; try { InputStream is = context.getAssets().open("tumblr.json"); int size = is.available(); byte[] buffer = new byte[size]; is.read(buffer); is.close(); tumblrResponse = new String(buffer, "UTF-8"); } catch (Exception e) { Log.e("Utils", e.getMessage()); } return tumblrResponse.toString(); } }
true
cebde3086f096401fe50b2aa04bc89ef14eca840
Java
github188/demodemo
/java/ReportPrint/src/org/notebook/gui/widget/LookAndFeelSelector.java
UTF-8
10,036
1.757813
2
[]
no_license
/* * aTunes 1.12.0 * Copyright (C) 2006-2009 Alex Aranda, Sylvain Gaudard, Thomas Beckers and contributors * * See http://www.atunes.org/wiki/index.php?title=Contributing for information about contributors * * http://www.atunes.org * http://sourceforge.net/projects/atunes * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ package org.notebook.gui.widget; import java.awt.Color; import java.awt.Font; import java.awt.event.ActionEvent; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Enumeration; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.BorderFactory; import javax.swing.ButtonGroup; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JRadioButtonMenuItem; import javax.swing.SwingUtilities; import javax.swing.UIManager; import javax.swing.UIManager.LookAndFeelInfo; import javax.swing.plaf.ColorUIResource; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.jvnet.lafwidget.LafWidget; import org.jvnet.lafwidget.utils.LafConstants; import org.jvnet.substance.SubstanceLookAndFeel; import org.jvnet.substance.api.SubstanceColorScheme; import org.jvnet.substance.api.SubstanceConstants; import org.jvnet.substance.api.SubstanceSkin; import org.notebook.events.BroadCastEvent; import org.notebook.events.EventAction; import org.notebook.gui.MenuToolbar; /** * The Class LookAndFeelSelector. */ public class LookAndFeelSelector { private Log log = LogFactory.getLog("ui"); /** The skins. */ private Map<String, String> skins = setListOfSkins(); /** The Constant DEFAULT_SKIN. */ public static final String DEFAULT_SKIN = "OfficeBlue2007"; private JFrame frame = null; public class LafMenuAction extends AbstractAction { private static final long serialVersionUID = -6101997393914923387L; public LafMenuAction(String name ){ super(name); this.putValue(Action.ACTION_COMMAND_KEY, name); this.putValue(Action.NAME, MenuToolbar.i18n(name)); } public void actionPerformed(ActionEvent event) { //log.info("Set Look and feel:" + event.getActionCommand()); setLookAndFeel(event.getActionCommand()); JRadioButtonMenuItem item = (JRadioButtonMenuItem)event.getSource(); SwingUtilities.updateComponentTreeUI(frame); } } @EventAction(order=1) public void GuiInited(BroadCastEvent event){ Object o = event.getSource(); if(o instanceof JFrame){ frame = (JFrame)o; JMenuBar mb = frame.getJMenuBar(); mb.add(createMenu(), 2); mb.validate(); } } protected JMenu createMenu(){ JMenu toolMenu = new JMenu(MenuToolbar.i18n("Views")); ButtonGroup group = new ButtonGroup(); JRadioButtonMenuItem item = null; for(String n : getListOfSkins()){ item = new JRadioButtonMenuItem(new LafMenuAction(n)); if(n.equals(DEFAULT_SKIN)){ item.setSelected(true); } group.add(item); toolMenu.add(item); } return toolMenu; } /** * Gets the list of skins. * * @return the list of skins */ public List<String> getListOfSkins() { List<String> result = new ArrayList<String>(skins.keySet()); Collections.sort(result, new Comparator<String>() { @Override public int compare(String o1, String o2) { return o1.toLowerCase().compareTo(o2.toLowerCase()); } }); return result; } /** * Sets the list of skins. * * @return the map< string, string> */ private Map<String, String> setListOfSkins() { Map<String, String> result = new HashMap<String, String>(); /* * toned down skins */ result.put("BusinessBlackSteel", "org.jvnet.substance.skin.SubstanceBusinessBlackSteelLookAndFeel"); result.put("Creme", "org.jvnet.substance.skin.SubstanceCremeLookAndFeel"); result.put("Business", "org.jvnet.substance.skin.SubstanceBusinessLookAndFeel"); result.put("BusinessBlueSteel", "org.jvnet.substance.skin.SubstanceBusinessBlueSteelLookAndFeel"); result.put("CremeCoffee", "org.jvnet.substance.skin.SubstanceCremeCoffeeLookAndFeel"); result.put("Sahara", "org.jvnet.substance.skin.SubstanceSaharaLookAndFeel"); result.put("Moderate", "org.jvnet.substance.skin.SubstanceModerateLookAndFeel"); result.put("OfficeSilver2007", "org.jvnet.substance.skin.SubstanceOfficeSilver2007LookAndFeel"); result.put("Nebula", "org.jvnet.substance.skin.SubstanceNebulaLookAndFeel"); result.put("NebulaBrickWall", "org.jvnet.substance.skin.SubstanceNebulaBrickWallLookAndFeel"); result.put("Autumn", "org.jvnet.substance.skin.SubstanceAutumnLookAndFeel"); result.put("MistSilver", "org.jvnet.substance.skin.SubstanceMistSilverLookAndFeel"); result.put("MistAqua", "org.jvnet.substance.skin.SubstanceMistAquaLookAndFeel"); /* * dark skins */ result.put("RavenGraphite", "org.jvnet.substance.skin.SubstanceRavenGraphiteLookAndFeel"); result.put("RavenGraphiteGlass", "org.jvnet.substance.skin.SubstanceRavenGraphiteGlassLookAndFeel"); result.put("Raven", "org.jvnet.substance.skin.SubstanceRavenLookAndFeel"); result.put("Magma", "org.jvnet.substance.skin.SubstanceMagmaLookAndFeel"); result.put("ChallengerDeep", "org.jvnet.substance.skin.SubstanceChallengerDeepLookAndFeel"); result.put("EmeraldDusk", "org.jvnet.substance.skin.SubstanceEmeraldDuskLookAndFeel"); /* * satured skins */ result.put("OfficeBlue2007", "org.jvnet.substance.skin.SubstanceOfficeBlue2007LookAndFeel"); /* * custom skins result.put("aTunes Blue", "com.wateray.ipassbook.ui.substance.SubstanceATunesBlueLookAndFeel"); result.put("aTunes Dark", "com.wateray.ipassbook.ui.substance.SubstanceATunesDarkLookAndFeel"); result.put("aTunes Gray", "com.wateray.ipassbook.ui.substance.SubstanceATunesGrayLookAndFeel"); */ for (LookAndFeelInfo lf : UIManager.getInstalledLookAndFeels()) { result.put(lf.getName(), lf.getClassName()); } return result; } /** * Sets the look and feel. * * @param theme * the new look and feel */ public void setLookAndFeel(String theme) { try { log.info("Updating skin '" + theme + "'"); if (skins.containsKey(theme)) { UIManager.setLookAndFeel(skins.get(theme)); } else { log.error("Not found skin '" + theme + "'"); return; } /** fix font bug start */ if (SwingUtilities.isEventDispatchThread()) { fixFontBug(); } else { SwingUtilities.invokeAndWait(new Runnable() { @Override public void run() { fixFontBug(); } }); } } catch (Exception e) { log.error(e.toString(), e); } /** * 如果配色方案不是系统内置的,需要把当前的配色保存,在有些特殊的地方使用。 * 例如:设置tiptool的背景色。 */ if (!isDefaultLookAndFeel(theme)) { // Get border color try { Color c = SubstanceLookAndFeel.getCurrentSkin().getMainActiveColorScheme().getMidColor(); UIManager.put("ToolTip.border", BorderFactory.createLineBorder(c)); UIManager.put("ToolTip.background", new ColorUIResource(Color.WHITE)); UIManager.put("ToolTip.foreground", new ColorUIResource(Color.BLACK)); SubstanceSkin skin = SubstanceLookAndFeel.getCurrentSkin(); SubstanceColorScheme scheme = skin.getMainActiveColorScheme(); GuiUtils.putLookAndFeelColor("borderColor", scheme.getMidColor()); GuiUtils.putLookAndFeelColor("lightColor", scheme.getLightColor()); GuiUtils.putLookAndFeelColor("lightBackgroundFillColor", scheme.getLightBackgroundFillColor()); GuiUtils.putLookAndFeelColor("darkColor", scheme.getDarkColor()); GuiUtils.putLookAndFeelColor("backgroundFillColor", scheme.getBackgroundFillColor()); GuiUtils.putLookAndFeelColor("lineColor", scheme.getLineColor()); GuiUtils.putLookAndFeelColor("selectionForegroundColor", scheme.getSelectionForegroundColor()); GuiUtils.putLookAndFeelColor("selectionBackgroundColor", scheme.getSelectionBackgroundColor()); GuiUtils.putLookAndFeelColor("foregroundColor", scheme.getForegroundColor()); GuiUtils.putLookAndFeelColor("focusRingColor", scheme.getFocusRingColor()); } catch (Exception e) { log.info("This is not a SubstanceLookAndFeel skin."); } UIManager.put(LafWidget.ANIMATION_KIND, LafConstants.AnimationKind.NONE); UIManager.put(SubstanceLookAndFeel.TABBED_PANE_CONTENT_BORDER_KIND, SubstanceConstants.TabContentPaneBorderKind.SINGLE_FULL); JFrame.setDefaultLookAndFeelDecorated(true); JDialog.setDefaultLookAndFeelDecorated(true); } } /** * */ public static boolean isDefaultLookAndFeel(String theme){ boolean defaultLF = false; for (LookAndFeelInfo lf : UIManager.getInstalledLookAndFeels()) { // not default lookAndFeel if (theme.equals(lf.getName())) { defaultLF = true; } } return defaultLF; } private static void fixFontBug() { int sizeOffset = 0; Enumeration keys = UIManager.getLookAndFeelDefaults().keys(); while (keys.hasMoreElements()) { Object key = keys.nextElement(); Object value = UIManager.get(key); if (value instanceof Font) { Font oldFont = (Font) value; // logger.info(oldFont.getName()); Font newFont = new Font("Dialog", oldFont.getStyle(), oldFont .getSize() + sizeOffset); UIManager.put(key, newFont); } } } }
true
6eef73d59284c31c4f25722d6b49368a4c55c42f
Java
cazares/ElevatorSimulator
/src/elevatorSimulator/view/FloorView.java
UTF-8
2,780
2.875
3
[]
no_license
package elevatorSimulator.view; import java.awt.BorderLayout; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFormattedTextField; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; import elevatorSimulator.controller.FloorController; import elevatorSimulator.model.FloorListModel; import elevatorSimulator.model.FloorModel; import elevatorSimulator.model.ModelEvent; /* * Displays an up and down button */ public class FloorView extends JFrameView{ public static final String UP = "Up"; public static final String DOWN = "Down"; JTextField doorsState = new JTextField(); JLabel doorsStateLabel = new JLabel("Doors: "); private JButton jDwnButton; private JButton jUpButton; public FloorView(FloorModel model, FloorController controller) { super(model, controller); Handler handler = new Handler(); this.setTitle("Floor " + ((FloorModel)getModel()).getFloorId()); this.setSize(200, 150); JPanel buttonPanel = new JPanel(); JPanel statePanel = new JPanel(); buttonPanel.setLayout(new GridLayout(3, 1 , 5, 5)); statePanel.setLayout(new GridLayout(1,1,5,5)); if(!((FloorModel)getModel()).isTopFloor()){//((FloorListModel)getModel()).getNumOfFloors()){ jUpButton = new JButton(UP); jUpButton.setEnabled(!((FloorModel)getModel()).isUpPressed()); jUpButton.addActionListener(handler); buttonPanel.add(jUpButton); } if(!((FloorModel)getModel()).isBottomFloor()){ jDwnButton = new JButton(DOWN); jDwnButton.setEnabled(!((FloorModel)getModel()).isDownPressed()); jDwnButton.addActionListener(handler); buttonPanel.add(jDwnButton); } doorsStateLabel.setLabelFor(doorsState); statePanel.add(doorsStateLabel); doorsState.setEditable(false); doorsState.setText(((FloorModel)getModel()).getDoors().getDoorState()); doorsState.setHorizontalAlignment(JFormattedTextField.RIGHT); statePanel.add(doorsState); this.getContentPane().add(buttonPanel, BorderLayout.NORTH); this.getContentPane().add(statePanel, BorderLayout.SOUTH); //pack(); } public JButton getDownButton(){ return jDwnButton; } public JButton getUpButton(){ return jUpButton; } @Override public void modelChanged(ModelEvent event) { doorsState.setText(((FloorModel)getModel()).getDoors().getDoorState()); if(jUpButton != null) jUpButton.setEnabled(!((FloorModel)getModel()).isUpPressed()); if(jDwnButton != null) jDwnButton.setEnabled(!((FloorModel)getModel()).isDownPressed()); } class Handler implements ActionListener{ public void actionPerformed(ActionEvent e){ ((FloorController)getController()).operation(e.getActionCommand()); } } }
true
b751b8b127d24d2eebda0489bdc614cb31cd7ef1
Java
kahokaho/kadai5
/IntToEng/Test/intToEng/testIntToEng.java
UTF-8
1,159
2.75
3
[]
no_license
package intToEng; import static org.hamcrest.CoreMatchers.*; import static org.junit.Assert.*; import org.junit.Test; public class testIntToEng { @Test public void testやくせるかな() { IntToEng ite = new IntToEng(); String expected = "eleven"; String actual = ite.translateEng(11); assertThat(actual, is(expected)); String expected2 = "twentyfour"; String actual2 = ite.translateEng(24); assertThat(actual2, is(expected2)); String expected3 = "onehundred"; String actual3 = ite.translateEng(100); assertThat(actual3, is(expected3)); String expected4 = "ninetynine"; String actual4 = ite.translateEng(99); assertThat(actual4, is(expected4)); String expected5 = "eightyfive"; String actual5 = ite.translateEng(85); assertThat(actual5, is(expected5)); String expected6 = "fortysix"; String actual6 = ite.translateEng(46); assertThat(actual6, is(expected6)); String expected7 = "thirtyseven"; String actual7 = ite.translateEng(37); assertThat(actual7, is(expected7)); String expected8 = "seventeen"; String actual8 = ite.translateEng(17); assertThat(actual8, is(expected8)); } }
true
150aeaca56d78a4e57c2b6ab31e8973f778134a8
Java
Rnhep/Flooring-Mastery
/FlooringMaster/src/main/java/com/mycompany/flooringmaster/dao/ProductDaoFileImpl.java
UTF-8
2,148
2.5625
3
[]
no_license
/* * 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.mycompany.flooringmaster.dao; import com.mycompany.flooringmaster.dto.Order; import com.mycompany.flooringmaster.dto.Product; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.math.BigDecimal; import java.util.ArrayList; import static java.util.Collections.list; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Scanner; /** * * @author ritheenhep */ public class ProductDaoFileImpl implements ProductDao { private Map<String, Product> productMap = new HashMap<>(); public static final String PRODUCT = "product.txt"; public static final String DELIMITER = "::"; private void loadProd() throws OrderPersistenceException { Scanner scanner; try { scanner = new Scanner(new BufferedReader(new FileReader(PRODUCT))); } catch (FileNotFoundException ex) { throw new OrderPersistenceException(""); } String currentLine; String[] currentTokens; while (scanner.hasNextLine()) { currentLine = scanner.nextLine(); currentTokens = currentLine.split(DELIMITER); Product currentProd = new Product(currentTokens[0]); currentProd.setCostPerSquareFoot(new BigDecimal(currentTokens[1])); currentProd.setLaborCostPerSquareFoot(new BigDecimal(currentTokens[2])); productMap.put(currentProd.getProductType(), currentProd); } scanner.close(); } public Product getProduct(String product) throws OrderPersistenceException { loadProd(); return productMap.get(product); } public List<Product> getAllProduct() throws OrderPersistenceException { loadProd(); List<Product> prodList = new ArrayList(productMap.values()); return prodList; } }
true
68a9e4694bd6068bd201c59be25bee23fb2d3784
Java
ChikaKanu/fashionApp
/fashion/src/main/java/com/example/codeclan/fashion/repository/fabrics/FabricRepository.java
UTF-8
483
1.617188
2
[]
no_license
package com.example.codeclan.fashion.repository.fabrics; import com.example.codeclan.fashion.models.Fabric; import com.example.codeclan.fashion.projections.FabricProjection; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.rest.core.annotation.RepositoryRestResource; @RepositoryRestResource(excerptProjection = FabricProjection.class) public interface FabricRepository extends JpaRepository<Fabric, Long>, FabricRepositoryCustom { }
true
40579dd83da7f2e71556b5508a86468a178343ab
Java
madilongamrt/spring-boot-crud-app
/backend/src/main/java/com/thedigitalacademy/intern/service/UserService.java
UTF-8
2,202
2.578125
3
[ "Apache-2.0", "MIT" ]
permissive
package com.thedigitalacademy.intern.service; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.stream.Collectors; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.thedigitalacademy.intern.entity.User; import com.thedigitalacademy.intern.repository.UserRepository; @Service public class UserService { @Autowired UserRepository userRepository;// why are we communication using service and repository //what is this for Collection<? public Collection<? extends User> getAllUsers() { List<User> userList = new ArrayList<>(); userRepository.findAll().forEach(userList::add); return userList; } public Collection<? extends User> getUserById(String userId) { List<User> userList = new ArrayList<>(); userList.add(userRepository.findById(userId).get()); return userList; } public Collection<? extends User> getAllUserById(String ids) { List<User> userList = new ArrayList<>(); List<String> idList = Arrays.asList(ids.split(",")); // userList.addAll(userRepository.findAllById(idList); userRepository.findAllById(idList).forEach(userList::add); return userList; } public String saveUser(User user) { User savedUser = userRepository.save(user); if (savedUser != null) { return "Saved : userId - " + savedUser.getId(); } else { return "Failed : userId - " + user.getId(); } } public String saveUserList(List<User> userList) { List<User> savedUserList = new ArrayList<>(); userRepository.saveAll(userList).forEach(savedUserList::add); return "saved : user ids -" + savedUserList.stream().map(u -> u.getId()).collect(Collectors.toList()); } public String deleteUser(User user) { userRepository.delete(user); return "Deleted succesfully"; } public String deleteUserById(String userId) { try { userRepository.deleteById(userId); return "User with userId- " + userId + " not exists...!!"; } catch (Exception e) { return "Deleted succesfully"; } } public String deleteAllUserList(List<User> userList) { userRepository.deleteAll(userList); return "Deleted succesfully"; } }
true
10e3294d8d63a851b7515f610f00571b439ad23c
Java
mati29/personal-developer
/src/main/java/com/mateuszjanwojtyna/personaldeveloper/Services/impl/RoleServiceImpl.java
UTF-8
738
2.1875
2
[]
no_license
package com.mateuszjanwojtyna.personaldeveloper.Services.impl; import com.mateuszjanwojtyna.personaldeveloper.Entities.Role; import com.mateuszjanwojtyna.personaldeveloper.Repositories.RoleRepository; import com.mateuszjanwojtyna.personaldeveloper.Services.RoleService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service(value = "roleService") public class RoleServiceImpl implements RoleService{ private RoleRepository roleRepository; public RoleServiceImpl(RoleRepository roleRepository) { this.roleRepository = roleRepository; } @Override public Role findByRole(String role) { return roleRepository.findByRole(role); } }
true
c8e02ced322d2688bf121f30324ad433e3578b70
Java
fruchtiger/bots_and_bidder
/src/main/java/bots/RelativePlusBidder.java
UTF-8
831
3.03125
3
[]
no_license
package bots; import static java.lang.String.format; public class RelativePlusBidder extends AbstractBidder { /** * This bot tries to bid relatively more money than the previous bid from other bot. * */ /**How much of the money left (budget) should be used to plus the last other bid*/ double budgetForPlus = 0.1; public RelativePlusBidder(double budgetForPlus) { super(format("Plus%.0f%%",budgetForPlus*100)); this.budgetForPlus = budgetForPlus; } @Override public int placeBid() { int lastOtherBidOrZero = otherBids.size() > 0 ? otherBids.get(otherBids.size()-1) : 0; int plus = (int)Math.floor(this.ownCash.doubleValue() * budgetForPlus); int bidProposal = plus + lastOtherBidOrZero; return proposalOr(bidProposal,0); } }
true
5db9d316b857829ad0053ac7aa5646e9f6a79c53
Java
ysysysysysysys/designMode
/desgin/src/decorator/v3/Type.java
UTF-8
320
2.546875
3
[]
no_license
package decorator.v3; public class Type extends People{ private People people; @Override public void moveAtoB(String type) { people.moveAtoB(type); } public People getPeople() { return people; } public void setPeople(People people) { this.people = people; } }
true
b7a6094a193015eac6df81d3d912787bc82ddae6
Java
Syedbasha82/Automation
/April Regression workSpace/BGRegression/src/bg/framework/app/functional/util/PIStubResponseHelper.java
UTF-8
2,145
2.3125
2
[]
no_license
package bg.framework.app.functional.util; import bg.framework.app.functional.common.ApplicationConfig; import org.apache.commons.lang.StringUtils; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import java.io.IOException; import java.util.Map; import java.util.Properties; import static org.apache.commons.lang.StringUtils.isNotEmpty; import static org.testng.Assert.fail; public class PIStubResponseHelper { private static Properties commonProperties = new PropertyLoader("resources/common/common.properties").load(); public void changeStubResponse(String stubService, String stubResponse) { DefaultHttpClient httpclient = new DefaultHttpClient(); HttpGet httpget = new HttpGet(ApplicationConfig.STUB_URL + stubService + "/" + stubResponse); try { httpclient.execute(httpget); } catch (IOException e) { fail("Error Setting up stub responses"); } finally { httpclient.getConnectionManager().shutdown(); } } public void stubReset() { DefaultHttpClient httpclient = new DefaultHttpClient(); HttpGet httpget = new HttpGet(ApplicationConfig.STUB_URL); try { httpclient.execute(httpget); } catch (IOException e) { fail("Error resetting stub response"); } finally { httpclient.getConnectionManager().shutdown(); } } public void setupStubResposesTo(Map<String, String> stubResponseMap) { if (isStubModeOn()) { for (String serviceName : stubResponseMap.keySet()) { changeStubResponse(serviceName, stubResponseMap.get(serviceName)); } } } public static boolean isStubModeOn() { if (StringUtils.equals("true", getPiStubMode())) { return true; } return false; } private static String getPiStubMode() { if (isNotEmpty(System.getProperty("piStubMode"))) { return System.getProperty("piStubMode"); } return commonProperties.getProperty("piStubMode"); } }
true
580641aaf9b31d6ed32eb2f6bf2fc208d742c63b
Java
sialam/PhoneGap-2.7-Android-plugins-to-make-a-phone-call
/PhoneDialer.java
UTF-8
786
2.171875
2
[]
no_license
package org.apache.cordova; import org.apache.cordova.api.CallbackContext; import org.apache.cordova.api.CordovaPlugin; import org.json.JSONArray; import org.json.JSONException; import android.net.Uri; import android.content.Intent; public class PhoneDialer extends CordovaPlugin { public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException{ if ("call".equals(action)) { try{ Uri number = Uri.parse("tel:" + args.getString(0)); Intent callIntent = new Intent(Intent.ACTION_CALL, number); this.cordova.getActivity().startActivity(callIntent); } catch (Exception e) { } callbackContext.success(); return true; } return false; } }
true
535c25e17e7115afe2ff557618c55a00ff79cbae
Java
ITPro1718/XO
/Partnerboerse/src/de/hdm/partnerboerse/shared/report/AllProfilesBySuchprofil.java
UTF-8
399
1.59375
2
[]
no_license
package de.hdm.partnerboerse.shared.report; /** * Report, der alle Partnervorschläge eines Users anhand eines * Suchprofils ausgibt. Der Report ist ein Composite Report und besteht aus * vielen SingleProfileReports * * @author Burghardt */ public class AllProfilesBySuchprofil extends CompositeReport { /** * */ private static final long serialVersionUID = 1L; }
true
686f45141e53d627dd745e905938f21aaa41e8a2
Java
antonio63j/AngularjsSpringRestManyToMany
/src/main/java/com/antonio/modelo/Movimiento.java
UTF-8
3,025
2.421875
2
[]
no_license
package com.antonio.modelo; import java.math.BigDecimal; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import javax.validation.constraints.Digits; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import org.hibernate.annotations.Type; import org.hibernate.validator.constraints.NotEmpty; import org.joda.time.LocalDate; import org.springframework.format.annotation.DateTimeFormat; @Entity @Table(name="MOVIMIENTOS") public class Movimiento { @Override public String toString() { return "Movimiento [id=" + id + ", date=" + date + ", accion=" + accion + ",employeeId="+ employeeId +",employeeName=" + employeeName + ", employeeJoiningDate=" + employeeJoiningDate + ", employeeSalary=" + employeeSalary + ", employeeSsn=" + employeeSsn + "]"; } @Id @GeneratedValue(strategy = GenerationType.AUTO) private int id; @DateTimeFormat(pattern="dd/MM/yyyy") @Column(name="DATE", nullable=false) private java.sql.Date date; @NotNull @Column(name="ACCION", nullable=false) private String accion; @Column(name="EMPLOYEE_ID", nullable=false) private int employeeId; @Column(name="EMPLOYEE_NAME", nullable=false) private String employeeName; @Column(name="EMPLOYEE_JOINING_DATE") private java.sql.Date employeeJoiningDate; @NotNull @Digits(integer=8, fraction=2) @Column(name="EMPLOYEE_SALARY", nullable=false) private BigDecimal employeeSalary; @NotEmpty @Column(name="EMPLOYEE_SSN", nullable=false) private String employeeSsn; public int getId() { return id; } public void setId(int id) { this.id = id; } public java.sql.Date getDate() { return date; } public void setDate(java.sql.Date date) { this.date = date; } public String getAccion() { return accion; } public void setAccion(String accion) { this.accion = accion; } public void setEmployeeId(int id){ this.employeeId = id; } public int getEmployeeId(){ return employeeId; } public String getEmployeeName() { return employeeName; } public void setEmployeeName(String employeeName) { this.employeeName = employeeName; } public java.sql.Date getEmployeeJoiningDate() { return employeeJoiningDate; } public void setEmployeeJoiningDate(java.sql.Date employeeJoiningDate) { this.employeeJoiningDate = employeeJoiningDate; } public BigDecimal getEmployeeSalary() { return employeeSalary; } public void setEmployeeSalary(BigDecimal employeeSalary) { this.employeeSalary = employeeSalary; } public String getEmployeeSsn() { return employeeSsn; } public void setEmployeeSsn(String employeeSsn) { this.employeeSsn = employeeSsn; } }
true
786c6071e4ed3ab8ce11d41c45ba69583334ed3c
Java
iFrankWu/MyGithub
/DataSourse/src/com/shinetech/sql/impl/DefaultDatabaseAccess.java
UTF-8
25,509
1.992188
2
[]
no_license
package com.shinetech.sql.impl; import java.lang.reflect.Method; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.apache.commons.lang.StringUtils; import com.shinetech.sql.DatabaseConst; import com.shinetech.sql.FieldParameter; import com.shinetech.sql.IDatabaseAccess; import com.shinetech.sql.ParameterCreatorUtil; import com.shinetech.sql.ReflectUtil; import com.shinetech.sql.ResultSetHandler; import com.shinetech.sql.SqlParameter; import com.shinetech.sql.dialect.Dialect; import com.shinetech.sql.exception.DBException; import com.shinetech.sql.pools.ConnectionPoolsBuilder; import com.shinetech.sql.pools.DBConfigManager; import com.shinetech.sql.type.ITypeReader; import com.shinetech.sql.type.ITypeWriter; /** * Copyright (C), 2010-2011, ShineTech. Co., Ltd.<br> * 文件名 :DefaultDatabaseAccess.java<br> * 包名:com.shinetech.sql.impl<br> * 作者 : husw<br> * 创建日期 : 2011/2/23<br> * 版本:1.0.0 <br> * 功能描述:数据库操作接口的默认实现 <br> * * 作者 : loong<br> * 修改日期 : 2011/3/2<br> * 版本:1.0.1 <br> * 修改原因:具体类实现<br> */ public class DefaultDatabaseAccess<T> implements IDatabaseAccess<T> { /** * poolName: 连接池名称 */ private String poolName = DatabaseConst.DEFAULT_POOL_NAME; /** * typeReaderMap: 注入字段数据类型读取器集合 */ private Map<String, ITypeReader<?>> typeReaderMap = null; /** * typeWriterMap: 注入字段数据类型写入器集合 */ private Map<Integer, ITypeWriter<?>> typeWriterMap = null; /** * lobWriterList: 处理字段类型写操作需要释放的临时对象集合 */ private List<ITypeWriter<?>> lobWriterList = null; @Override public void execute(String sql) throws DBException { // TODO Auto-generated method stub Connection conn = getConnection(); Statement stmt = getStatement(conn); try { stmt.executeUpdate(sql); } catch (SQLException e) { // TODO Auto-generated catch block throw new DBException("执行更新失败", e); } finally { closeStatement(stmt); freeConnection(conn); } } @Override public void execute(String sql, List<FieldParameter> paraList) throws DBException { // TODO Auto-generated method stub Connection conn = getConnection(); PreparedStatement pstmt = getPreparedStatement(conn, sql); try { bindFieldParameter(conn, pstmt, paraList); } catch (DBException e) { throw new DBException("绑定参数到PreparedStatement对象失败:" + sql, e); } try { pstmt.executeUpdate(); } catch (SQLException e) { // TODO Auto-generated catch block throw new DBException("执行操作失败", e); } finally { unRegisterTypeMap(); clearLobWriterList(); closeStatement(pstmt); freeConnection(conn); } } @Override public void executeBatch(List<String> sqlList) throws DBException { // TODO Auto-generated method stub Connection conn = getConnection(); Statement stmt = getStatement(conn); try { conn.setAutoCommit(false); for (String sql : sqlList) { stmt.addBatch(sql); } stmt.executeBatch(); conn.commit(); conn.setAutoCommit(true); } catch (SQLException e) { // TODO Auto-generated catch block try { if (!conn.getAutoCommit()) { conn.rollback(); } } catch (SQLException e1) { // TODO Auto-generated catch block throw new DBException("执行回滚操作失败", e1); } throw new DBException("执行批量操作失败", e); } finally { try { conn.setAutoCommit(true); } catch (SQLException e) { // TODO Auto-generated catch block throw new DBException("设置自动提交操作失败", e); } closeStatement(stmt); freeConnection(conn); } } @Override public void executePrepareBatch(String sql, List<List<FieldParameter>> listParaList) throws DBException { // TODO Auto-generated method stub Connection conn = getConnection(); PreparedStatement pstmt = getPreparedStatement(conn, sql); try { conn.setAutoCommit(false); for (List<FieldParameter> paraList : listParaList) { try { bindFieldParameter(conn, pstmt, paraList); } catch (DBException e) { throw new DBException("绑定参数到PreparedStatement对象失败:" + sql, e); } pstmt.addBatch(); } pstmt.executeBatch(); conn.commit(); conn.setAutoCommit(true); } catch (SQLException e) { // TODO Auto-generated catch block try { if (!conn.getAutoCommit()) { conn.rollback(); } } catch (SQLException e1) { // TODO Auto-generated catch block throw new DBException("执行回滚操作失败", e1); } throw new DBException("执行批量操作失败", e); } finally { try { conn.setAutoCommit(true); } catch (SQLException e) { // TODO Auto-generated catch block throw new DBException("设置自动提交操作失败", e); } unRegisterTypeMap(); clearLobWriterList(); closeStatement(pstmt); freeConnection(conn); } } @Override public void executePrepareMultiBath(List<SqlParameter> list) throws DBException { // TODO Auto-generated method stub Connection conn = getConnection(); PreparedStatement pstmt = null; try { conn.setAutoCommit(false); for (SqlParameter sqlParameter : list) { pstmt = getPreparedStatement(conn, sqlParameter.getSql()); try { bindFieldParameter(conn, pstmt, sqlParameter.getParaList()); } catch (DBException e) { throw new DBException("绑定参数到PreparedStatement对象失败:" + sqlParameter.getSql(), e); } pstmt.executeUpdate(); closeStatement(pstmt); } conn.commit(); conn.setAutoCommit(true); } catch (SQLException e) { // TODO Auto-generated catch block try { if (!conn.getAutoCommit()) { conn.rollback(); } } catch (SQLException e1) { // TODO Auto-generated catch block throw new DBException("执行回滚操作失败", e1); } throw new DBException("执行批量操作失败", e); } finally { try { conn.setAutoCommit(true); } catch (SQLException e) { // TODO Auto-generated catch block throw new DBException("设置自动提交操作失败", e); } unRegisterTypeMap(); clearLobWriterList(); closeStatement(pstmt); freeConnection(conn); } } @Override public T queryFirst(Class<T> clazz, String sql) throws DBException { // TODO Auto-generated method stub T t = null; Connection conn = getConnection(); Statement stmt = getStatement(conn); ResultSet rs = null; try { rs = stmt.executeQuery(sql); Map<String, Integer> metaMap = getMetaDataMap(rs); if (rs.next()) { t = getClazzBean(clazz, rs, metaMap); } } catch (SQLException e) { // TODO Auto-generated catch block throw new DBException("执行查询失败", e); } finally { unRegisterTypeMap(); closeResult(rs); closeStatement(stmt); freeConnection(conn); } return t; } @Override public List<T> queryList(Class<T> clazz, String sql) throws DBException { // TODO Auto-generated method stub List<T> tList = new ArrayList<T>(); Connection conn = getConnection(); Statement stmt = getStatement(conn); ResultSet rs = null; try { rs = stmt.executeQuery(sql); Map<String, Integer> metaMap = getMetaDataMap(rs); while (rs.next()) { tList.add(getClazzBean(clazz, rs, metaMap)); } } catch (SQLException e) { // TODO Auto-generated catch block throw new DBException("执行查询失败", e); } finally { unRegisterTypeMap(); closeResult(rs); closeStatement(stmt); freeConnection(conn); } return tList; } @Override public List<T> queryPage(Class<T> clazz, String sql, int pageSize, int currentPage) throws DBException { // TODO Auto-generated method stub List<T> tList = new ArrayList<T>(); Connection conn = getConnection(); PreparedStatement pstmt = getPreparedStatement(conn, DBConfigManager.getInstance().getDialect(poolName).getLimitString(sql)); bindFieldParameter(pstmt, 0, pageSize, currentPage); ResultSet rs = null; try { rs = pstmt.executeQuery(); Map<String, Integer> metaMap = getMetaDataMap(rs); while (rs.next()) { tList.add(getClazzBean(clazz, rs, metaMap)); } } catch (SQLException e) { // TODO Auto-generated catch block throw new DBException("执行查询失败", e); } finally { unRegisterTypeMap(); closeResult(rs); closeStatement(pstmt); freeConnection(conn); } return tList; } @Override public T queryPrepareFirst(Class<T> clazz, String sql, List<FieldParameter> paraList) throws DBException { // TODO Auto-generated method stub T t = null; Connection conn = getConnection(); PreparedStatement pstmt = getPreparedStatement(conn, sql); try { bindFieldParameter(conn, pstmt, paraList); } catch (DBException e) { throw new DBException("绑定参数到PreparedStatement对象失败:" + sql, e); } ResultSet rs = null; try { rs = pstmt.executeQuery(); Map<String, Integer> metaMap = getMetaDataMap(rs); if (rs.next()) { t = getClazzBean(clazz, rs, metaMap); } } catch (SQLException e) { // TODO Auto-generated catch block throw new DBException("执行查询失败", e); } finally { unRegisterTypeMap(); closeResult(rs); closeStatement(pstmt); freeConnection(conn); } return t; } @Override public List<T> queryPrepareList(Class<T> clazz, String sql, List<FieldParameter> paraList) throws DBException { // TODO Auto-generated method stub List<T> tList = new ArrayList<T>(); Connection conn = getConnection(); PreparedStatement pstmt = getPreparedStatement(conn, sql); try { bindFieldParameter(conn, pstmt, paraList); } catch (DBException e) { throw new DBException("绑定参数到PreparedStatement对象失败:" + sql, e); } ResultSet rs = null; try { rs = pstmt.executeQuery(); Map<String, Integer> metaMap = getMetaDataMap(rs); while (rs.next()) { tList.add(getClazzBean(clazz, rs, metaMap)); } } catch (SQLException e) { // TODO Auto-generated catch block throw new DBException("执行查询失败", e); } finally { unRegisterTypeMap(); closeResult(rs); closeStatement(pstmt); freeConnection(conn); } return tList; } @Override public List<T> queryPreparePage(Class<T> clazz, String sql, List<FieldParameter> paraList, int pageSize, int currentPage) throws DBException { // TODO Auto-generated method stub List<T> tList = new ArrayList<T>(); Connection conn = getConnection(); PreparedStatement pstmt = getPreparedStatement(conn, DBConfigManager.getInstance().getDialect(poolName).getLimitString(sql)); try { bindFieldParameter(conn, pstmt, paraList); } catch (DBException e) { throw new DBException("绑定参数到PreparedStatement对象失败:" + sql, e); } bindFieldParameter(pstmt, paraList.size(), pageSize, currentPage); ResultSet rs = null; try { rs = pstmt.executeQuery(); Map<String, Integer> metaMap = getMetaDataMap(rs); while (rs.next()) { tList.add(getClazzBean(clazz, rs, metaMap)); } } catch (SQLException e) { // TODO Auto-generated catch block throw new DBException("执行查询失败", e); } finally { unRegisterTypeMap(); closeResult(rs); closeStatement(pstmt); freeConnection(conn); } return tList; } @Override public void registerTypeReadHandle(String fieldName, ITypeReader<?> typeReader) throws Exception { // TODO Auto-generated method stub if (this.typeReaderMap == null) { this.typeReaderMap = new HashMap<String, ITypeReader<?>>(); } this.typeReaderMap.put(StringUtils.upperCase(fieldName), typeReader); } @Override public void registerTypeWriteHandle(int index, ITypeWriter<?> typeWriter) throws Exception { // TODO Auto-generated method stub if (this.typeWriterMap == null) { this.typeWriterMap = new HashMap<Integer, ITypeWriter<?>>(); } this.typeWriterMap.put(index, typeWriter); } @Override public void setDatabase(String poolName) { // TODO Auto-generated method stub this.poolName = poolName; } /** * 功能:返回指定连接池的一个空闲连接 <br> * 注意事项:<font color="red">TODO</font> <br> * * @return * @throws DBException * Connection */ private Connection getConnection() throws DBException { Connection conn = ConnectionPoolsBuilder.getConnectionPools().getConnection(poolName); if (conn == null) throw new DBException("从连接池[" + poolName + "]获取空闲连接失败"); return conn; } /** * 功能:释放指定连接 <br> * 注意事项:<font color="red">TODO</font> <br> * * @param conn * void * @throws DBException */ private void freeConnection(Connection conn) throws DBException { if (conn != null) ConnectionPoolsBuilder.getConnectionPools().freeConnection(poolName, conn); } /** * 功能:返回指定连接的一个Statement对象 <br> * 注意事项:<font color="red">TODO</font> <br> * * @param conn * @return * @throws DBException * Statement */ private Statement getStatement(Connection conn) throws DBException { try { Statement stmt = conn.createStatement(); if (stmt == null) throw new DBException("创建Statement对象失败"); return stmt; } catch (SQLException e) { // TODO Auto-generated catch block throw new DBException("创建Statement对象失败", e); } } /** * 功能:返回指定连接的一个PreparedStatement对象 <br> * 注意事项:<font color="red">TODO</font> <br> * * @param conn * @param sql * @return * @throws DBException * PreparedStatement */ private PreparedStatement getPreparedStatement(Connection conn, String sql) throws DBException { try { PreparedStatement pstmt = conn.prepareStatement(sql); if (pstmt == null) throw new DBException("创建PreparedStatement对象失败"); return pstmt; } catch (SQLException e) { // TODO Auto-generated catch block throw new DBException("创建PreparedStatement对象失败, ", e); } } /** * 功能:关闭Statement对象 <br> * 注意事项:<font color="red">TODO</font> <br> * * @param stmt * @throws DBException * void */ private void closeStatement(Statement stmt) throws DBException { if (stmt != null) try { stmt.close(); } catch (SQLException e) { // TODO Auto-generated catch block throw new DBException("关闭Statement对象失败", e); } } /** * 功能:关闭ResultSet对象 <br> * 注意事项:<font color="red">TODO</font> <br> * * @param rs * @throws DBException * void */ private void closeResult(ResultSet rs) throws DBException { if (rs != null) try { rs.close(); } catch (SQLException e) { // TODO Auto-generated catch block throw new DBException("关闭ResultSet对象失败", e); } } /** * 功能:注销已注册的自定义字段数据类型处理器 <br> * 注意事项:<font color="red">TODO</font> <br> * void */ private void unRegisterTypeMap() { if (typeReaderMap != null && !typeReaderMap.isEmpty()) { typeReaderMap.clear(); } if (typeWriterMap != null && !typeWriterMap.isEmpty()) { typeWriterMap.clear(); } } /** * 功能:关闭写临时大字段对象 <br> * 注意事项:<font color="red">TODO</font> <br> * * @throws DBException * void */ private void clearLobWriterList() throws DBException { if (lobWriterList != null) { while (!lobWriterList.isEmpty()) { try { lobWriterList.remove(0).free(); } catch (Exception e) { // TODO Auto-generated catch block throw new DBException("关闭写临时数据处理器对象失败", e); } } } } /** * 功能:获取 ResultSet对象中列的类型和属性信息 <br> * 注意事项:<font color="red">TODO</font> <br> * * @param rs * @return * @throws DBException * Map<String,Integer> */ private Map<String, Integer> getMetaDataMap(ResultSet rs) throws DBException { try { ResultSetMetaData rsd = rs.getMetaData(); int columnCount = rsd.getColumnCount(); Map<String, Integer> metaMap = new HashMap<String, Integer>(columnCount); for (int i = 1; i <= columnCount; i++) { metaMap.put(StringUtils.upperCase(rsd.getColumnLabel(i)), rsd.getColumnType(i)); } return metaMap; } catch (SQLException e) { throw new DBException("获取 ResultSet对象中列的类型和属性信息失败", e); } } /** * 功能:从Resultset对象中获取值到指定clazz对象中 <br> * 注意事项:<font color="red">TODO</font> <br> * * @param clazz * @param rs * @param metaMap * @param fieldMap * @return * @throws DBException * T */ @SuppressWarnings("unchecked") private T getClazzBean(Class<T> clazz, ResultSet rs, Map<String, Integer> metaMap) throws DBException { T t = null; // 检查是否基本数据类型 if (ReflectUtil.isPrimitive(clazz)) { t = (T) getResult(rs, 1, clazz); } else { try { // 创建对象实例 t = ReflectUtil.newInstance(clazz); // 遍历查询到的结果集 for (Iterator<String> iter = metaMap.keySet().iterator(); iter.hasNext();) { // 结果集列名称 String fieldName = iter.next(); // 获取该属性setter方法 Method method = ReflectUtil.getMethod(clazz, fieldName, "set"); // 检查对象实例是否包含此结果集名称的对应的属性名称 if (method != null) { // 调用该方法 method.invoke(t, new Object[] { getResult(rs, fieldName, metaMap.get(fieldName)) }); } } } catch (Exception e) { throw new DBException("从Resultset对象中获取值到[" + clazz.getName() + "]对象中失败", e); } } return t; } /** * 功能:从指定RestultSet中获取基本数据类型的值 <br> * 注意事项:<font color="red">TODO</font> <br> * * @param rs * @param columnIndex * @param clazz * @return * @throws DBException * Object */ private Object getResult(ResultSet rs, int columnIndex, Class<?> clazz) throws DBException { // 直接从ResultSet中返回值 try { String method = "get" + DBConfigManager.getInstance().getDialect(poolName).getReflectType(clazz); Method m = ResultSet.class.getDeclaredMethod(method, new Class[] { int.class }); return m.invoke(rs, new Object[] { columnIndex }); } catch (Exception e) { // TODO Auto-generated catch block throw new DBException("从ResultSet中返回字段索引[" + columnIndex + "]值失败", e); } } /** * 功能:从指定RestultSet中获取指定字段名称的值 <br> * 注意事项:<font color="red">TODO</font> <br> * * @param rs * @param fieldName * @param fieldType * @return * @throws DBException * Object */ private Object getResult(ResultSet rs, String fieldName, int fieldType) throws DBException { Object object = null; if (isDefaultTypeByRead(fieldName, fieldType)) { // 直接从ResultSet中返回值 try { String method = "get" + DBConfigManager.getInstance().getDialect(poolName).getReflectType(fieldType); Method m = ResultSet.class.getDeclaredMethod(method, new Class[] { String.class }); object = m.invoke(rs, new Object[] { fieldName }); } catch (Exception e) { // TODO Auto-generated catch block throw new DBException("从ResultSet中返回字段[" + fieldName + "]值失败", e); } } else { // 自定义处理 try { object = getTypeReader(fieldName, fieldType).read(rs, fieldName); } catch (Exception e) { // TODO Auto-generated catch block throw new DBException("自定义类处理从ResultSet中返回字段[" + fieldName + "]值失败", e); } } return object; } /** * 功能:绑定参数到PreparedStatement对象 <br> * 注意事项:<font color="red">TODO</font> <br> * * @param conn * @param pstmt * @param paraList * @throws DBException * void */ @SuppressWarnings( { "unchecked", "rawtypes" }) private void bindFieldParameter(Connection conn, PreparedStatement pstmt, List<FieldParameter> paraList) throws DBException { for (FieldParameter parameter : paraList) { int index = parameter.getIndex(); int type = parameter.getType(); Object value = parameter.getValue(); try { if (value == null) { pstmt.setNull(index, type); } else { if (isDefaultTypeByWrite(index, type)) pstmt.setObject(index, value, type); else { ITypeWriter typeWriter = getTypeWriter(index, type); typeWriter.write(conn, pstmt, index, value); if (typeWriter.isFree()) { if (lobWriterList == null) { lobWriterList = new ArrayList<ITypeWriter<?>>(); } lobWriterList.add(typeWriter); } } } } catch (Exception e) { throw new DBException(ParameterCreatorUtil.toString(parameter), e); } } } /** * 功能:绑定查询条件参数到PreparedStatement对象 <br> * 注意事项:<font color="red">TODO</font> <br> * * @param pstmt * @param paraCount * @param pageSize * @param currentPage * @throws DBException * void */ private void bindFieldParameter(PreparedStatement pstmt, int paraCount, int pageSize, int currentPage) throws DBException { Dialect dbDialect = DBConfigManager.getInstance().getDialect(poolName); if (dbDialect.supportsLimit()) { try { if (pageSize < 1) pageSize = 10; if (currentPage < 1) currentPage = 1; pstmt.setInt(paraCount + 1, pageSize * currentPage); if (dbDialect.supportsLimitOffset()) pstmt.setInt(paraCount + 2, pageSize * (currentPage - 1)); } catch (Exception e) { throw new DBException("绑定翻页参数到PreparedStatement对象失败:[" + pageSize + ", " + currentPage + "]", e); } } } /** * 功能:判断是否按默认字段数据类型读取数据 <br> * 注意事项:<font color="red">TODO</font> <br> * * @param fileName * @param fieldType * @return boolean * @throws DBException */ private boolean isDefaultTypeByRead(String fieldName, int fieldType) throws DBException { if ((typeReaderMap != null && typeReaderMap.containsKey(fieldName)) || DBConfigManager.getInstance().getDialect(poolName).containDefaultTypeReader(fieldType)) { return false; } return true; } /** * 功能:判断是否按默认数据类型写入数据 <br> * 注意事项:<font color="red">TODO</font> <br> * * @param index * @param fieldType * @return boolean * @throws DBException */ private boolean isDefaultTypeByWrite(int index, int fieldType) throws DBException { if ((typeWriterMap != null && typeWriterMap.containsKey(index)) || DBConfigManager.getInstance().getDialect(poolName).containDefaultTypeWriter(fieldType)) { return false; } return true; } /** * 功能:返回自定义读取器处理器对象 <br> * 注意事项:<font color="red">TODO</font> <br> * * @param fileName * @param fieldType * @return ITypeReader<?> * @throws DBException */ private ITypeReader<?> getTypeReader(String fieldName, int fieldType) throws DBException { if (typeReaderMap != null && typeReaderMap.containsKey(fieldName)) { return typeReaderMap.get(fieldName); } return DBConfigManager.getInstance().getDialect(poolName).getDefaultTypeReader(fieldType); } /** * 功能:返回自定义写入器处理器对象 <br> * 注意事项:<font color="red">TODO</font> <br> * * @param index * @param fieldType * @return ITypeWriter<?> * @throws DBException */ private ITypeWriter<?> getTypeWriter(int index, int fieldType) throws DBException { if (typeWriterMap != null && typeWriterMap.containsKey(index)) { return typeWriterMap.get(index); } return DBConfigManager.getInstance().getDialect(poolName).getDefaultTypeWriter(fieldType); } @Override public void handleList(String sql, ResultSetHandler handler) throws DBException { // TODO Auto-generated method stub Connection conn = getConnection(); Statement stmt = getStatement(conn); ResultSet rs = null; try { rs = stmt.executeQuery(sql); while (rs.next()) { handler.handle(rs); } } catch (SQLException e) { // TODO Auto-generated catch block throw new DBException("执行查询失败", e); } finally { unRegisterTypeMap(); closeResult(rs); closeStatement(stmt); freeConnection(conn); } } @Override public void handleList(String sql, List<FieldParameter> paraList, ResultSetHandler handler) throws DBException { Connection conn = getConnection(); PreparedStatement pstmt = getPreparedStatement(conn, sql); try { bindFieldParameter(conn, pstmt, paraList); } catch (DBException e) { throw new DBException("绑定参数到PreparedStatement对象失败:" + sql, e); } ResultSet rs = null; try { rs = pstmt.executeQuery(); while (rs.next()) { handler.handle(rs); } } catch (SQLException e) { // TODO Auto-generated catch block throw new DBException("执行查询失败", e); } finally { unRegisterTypeMap(); closeResult(rs); closeStatement(pstmt); freeConnection(conn); } } }
true
e9bbf2592c10319b4c403cd791ffead612518cc8
Java
javagurulv/ok_ru_admin_group_2
/src/main/java/student_andrey_domas/lesson15/components/Component1.java
UTF-8
228
1.78125
2
[]
no_license
package student_andrey_domas.lesson15.components; import org.springframework.stereotype.Component; @Component public class Component1 extends DemoComponent { public Component1() { this.name = "component1"; } }
true
a1b4879cfb59863996982299b1bcedb01aabb297
Java
Srchavier/academia-daryoku
/src/main/java/br/com/academiaDaryoku/controle/PessoaControle.java
ISO-8859-1
12,883
1.65625
2
[]
no_license
package br.com.academiaDaryoku.controle; import java.io.Serializable; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Date; import java.util.List; import javax.annotation.PostConstruct; import javax.faces.view.ViewScoped; import javax.inject.Inject; import javax.inject.Named; import javax.persistence.NoResultException; import org.primefaces.PrimeFaces; import br.com.academiaDaryoku.converter.ConverterCidade; import br.com.academiaDaryoku.converter.ConverterEstado; import br.com.academiaDaryoku.converter.ConverterTurma; import br.com.academiaDaryoku.model.TbCidade; import br.com.academiaDaryoku.model.TbContato; import br.com.academiaDaryoku.model.TbEndereco; import br.com.academiaDaryoku.model.TbEstado; import br.com.academiaDaryoku.model.TbPessoa; import br.com.academiaDaryoku.model.TbTurma; import br.com.academiaDaryoku.model.TbUsuario; import br.com.academiaDaryoku.model.TipoEnum; import br.com.academiaDaryoku.model.TipoFaixa; import br.com.academiaDaryoku.respository.filter.FilterAll; import br.com.academiaDaryoku.service.CidadeService; import br.com.academiaDaryoku.service.ContatoService; import br.com.academiaDaryoku.service.EnderencoService; import br.com.academiaDaryoku.service.EstadoService; import br.com.academiaDaryoku.service.LoginService; import br.com.academiaDaryoku.service.PessoaService; import br.com.academiaDaryoku.service.TurmaService; import br.com.academiaDaryoku.ultils.Sha256; import br.com.academiaDaryoku.ultils.UtilErros; import br.com.academiaDaryoku.ultils.UtilMensagens; @Named(value = "pessoaControle") @ViewScoped public class PessoaControle implements Serializable { private static final long serialVersionUID = 6835397027661347473L; private String pesquisar; private TbEndereco tbEndereco; private TbCidade tbCidade; private TbEstado tbEstado; private TbTurma tbTurma; private TbPessoa tbPessoa; private TbContato tbContato; private TbUsuario tbUsuario; private TbPessoa tbPessoaSelecionada; private List<TbPessoa> pessoa; private List<TbCidade> listaCidades; private TipoEnum tipo; @Inject private PessoaService pessoaService; @Inject private ContatoService contatoService; @Inject private EnderencoService enderencoService; @Inject private LoginService usuarioService; @Inject private TurmaService turmaService; @Inject private CidadeService cidadeService; @Inject private EstadoService estadoService; @Inject private ConverterTurma converterTurma; @Inject private ConverterEstado converterEstado; @Inject private ConverterCidade converterCidade; @PostConstruct public void inicializar() { newModel(); tbPessoaSelecionada = null; buscarTodos(); } public void novo() { newModel(); String gg = gerarMatricula(); try { TbUsuario gerar = usuarioService.porMatLogin(gg); if(gerar != null) { novo(); } tbUsuario.setMatLogin(gg); } catch (NoResultException e) { UtilMensagens.mensagemErro("Erro ao gerar!"); } tbPessoaSelecionada = null; } private void newModel() { tbPessoa = new TbPessoa(); tbContato = new TbContato(); tbTurma = new TbTurma(); tbUsuario = new TbUsuario(); tbEndereco = new TbEndereco(); tbEstado = new TbEstado(); tbCidade = new TbCidade(); } public void buscarTodos() { pessoa = new ArrayList<>(); listaCidades = new ArrayList<>(); pessoa = pessoaService.buscatodos(); } public void pesquisarNome() { FilterAll filter = new FilterAll(); filter.setNome(pesquisar); pessoa = new ArrayList<>(); if (!(pessoa = pessoaService.buscaPorNome(filter)).isEmpty()) { UtilMensagens.mensagemInformacao(pessoa.size() + " Registro encontrad(o)!"); } else { UtilMensagens.mensagemInformacao("No encontrado!"); } PrimeFaces.current().ajax().update(Arrays.asList("form:msgs", "form:pessoa-table")); } public TbPessoa getTbPessoaSelecionada() { return tbPessoaSelecionada; } public void setTbPessoaSelecionada(TbPessoa tbPessoaSelecionada) { this.tbPessoaSelecionada = tbPessoaSelecionada; this.tipo = tbPessoaSelecionada.getTipo(); } public void editarPessoa() { try { tbTurma = tbPessoa.getTbTurma(); tbEndereco = enderencoService.porIdPessoa(tbPessoaSelecionada.getIdPessoa()); tbContato = contatoService.porIdPessoa(tbPessoaSelecionada.getIdPessoa()); tbUsuario = usuarioService.porIdPessoa(tbPessoaSelecionada.getIdPessoa()); tbUsuario.setMatSenha(""); tbCidade = tbEndereco.getTbCidade(); tbEstado = tbEndereco.getTbCidade().getTbEstado(); listaCidades = (cidadeService.findPorIdEstado(tbEndereco.getTbCidade().getTbEstado().getIdEstado())); } catch (Exception e) { UtilMensagens.mensagemErro("Erro ao editar!"); } } public List<TbCidade> EstadoSelecionadoCidade() { int id = tbEstado.getIdEstado(); try { return listaCidades = cidadeService.findPorIdEstado(id); } catch (Exception e) { UtilErros.getMensagemErro(e); UtilMensagens.mensagemErro("Erro ao selecionar!"); return null; } } public void salvar() { if (salvarUsuario()) { PrimeFaces.current().ajax().addCallbackParam("validacaoMat", true); PrimeFaces.current().ajax().update(Arrays.asList("form:msgs", "form:pessoa-table")); } } private synchronized boolean salvarUsuario() { if(this.tbUsuario.getMatSenha().length() >= 16 && this.tbUsuario.getMatSenha().length() <= 4) { UtilMensagens.mensagemInformacao("senha deve ser maior 5 e menor 16!"); PrimeFaces.current().ajax().addCallbackParam("validacaoMat", false); return false; } if (this.tbPessoa.getTipo().equals(TipoEnum.PF)) { if (turmaService.isProfessor(this.tbPessoa) && tbPessoa.getTipo() != tipo) { UtilMensagens.mensagemInformacao("Professor j existe, primeiro altere o perfil existente!"); PrimeFaces.current().ajax().addCallbackParam("validacaoMat", false); return false; } else { if (tbPessoa.getDataCadastro() == null && tbPessoa.getTipo() != tipo) { Date data = new Date(); this.tbPessoa.setDataCadastro(data); } TbPessoa pessoaSalvar = pessoaService.salvar(this.tbPessoa); tbTurma = pessoaSalvar.getTbTurma(); turmaService.isNullPessoaTurma(pessoaSalvar); tbTurma.setTbPessoa(pessoaSalvar); turmaService.alterar(tbTurma); tbContato.setTbPessoa(pessoaSalvar); contatoService.salvar(this.tbContato); tbEndereco.setTbCidade(this.tbCidade); tbEndereco.setTbPessoa(pessoaSalvar); enderencoService.salvar(this.tbEndereco); tbUsuario.setMatSenha(Sha256.shaSet(this.tbUsuario.getMatSenha())); tbUsuario.setTbPessoa(pessoaSalvar); usuarioService.salvar(this.tbUsuario); tbUsuario.setMatSenha(""); buscarTodos(); UtilMensagens.mensagemInformacao("Professor Salvo/Alternada com sucesso!"); PrimeFaces.current().ajax().update(Arrays.asList("form:pessoa-table")); return true; } } if (this.tbPessoa.getTipo().equals(TipoEnum.ADM) || this.tbPessoa.getTipo().equals(TipoEnum.EST)) { if (tbPessoaSelecionada != null) { TbPessoa pessoaSalvar = pessoaService.salvar(this.tbPessoa); turmaService.isNullPessoaTurma(pessoaSalvar); tbContato.setTbPessoa(pessoaSalvar); contatoService.salvar(this.tbContato); tbEndereco.setTbCidade(this.tbCidade); tbEndereco.setTbPessoa(pessoaSalvar); enderencoService.salvar(this.tbEndereco); tbUsuario.setMatSenha(Sha256.shaSet(this.tbUsuario.getMatSenha())); tbUsuario.setTbPessoa(pessoaSalvar); usuarioService.salvar(this.tbUsuario); tbUsuario.setMatSenha(""); buscarTodos(); UtilMensagens.mensagemInformacao("Pessoa alterando com sucesso!"); PrimeFaces.current().ajax().update(Arrays.asList("form:pessoa-table")); return true; } else { if (usuarioService.porMatLogin(this.tbUsuario.getMatLogin()) != null) { UtilMensagens.mensagemInformacao("Erro ao cadastrar matrcula j existe!"); PrimeFaces.current().ajax().addCallbackParam("validacaoMat", false); return false; } else { try { Date data = new Date(); this.tbPessoa.setDataCadastro(data); TbPessoa pessoaSalvar = pessoaService.salvar(this.tbPessoa); tbContato.setTbPessoa(pessoaSalvar); contatoService.salvar(this.tbContato); tbEndereco.setTbCidade(this.tbCidade); tbEndereco.setTbPessoa(pessoaSalvar); enderencoService.salvar(this.tbEndereco); tbUsuario.setMatSenha(Sha256.shaSet(this.tbUsuario.getMatSenha())); tbUsuario.setTbPessoa(pessoaSalvar); usuarioService.salvar(this.tbUsuario); tbUsuario.setMatSenha(""); buscarTodos(); UtilMensagens.mensagemInformacao("Pessoa salva com sucesso!"); PrimeFaces.current().ajax().update(Arrays.asList("form:pessoa-table")); return true; } catch (NoResultException e) { return true; } } } } else { UtilMensagens.mensagemErro("Erro ao salva!"); return false; } } public void excluir() { if (tbPessoaSelecionada == null) { UtilMensagens.mensagemErro("Error"); } try { turmaService.isNullPessoaTurma(tbPessoaSelecionada); enderencoService.delete(tbPessoaSelecionada.getIdPessoa()); contatoService.delete(tbPessoaSelecionada.getIdPessoa()); usuarioService.delete(tbPessoaSelecionada.getIdPessoa()); pessoaService.delete(tbPessoaSelecionada); tbPessoaSelecionada = null; buscarTodos(); UtilMensagens.mensagemInformacao("Pessoa excluda com sucesso!"); } catch (Exception e) { UtilErros.getMensagemErro(e); UtilMensagens.mensagemErro("Erro ao excluir!"); } PrimeFaces.current().ajax().update(Arrays.asList("form:msgs", "form:pessoa-table")); } public void atualizar() { PrimeFaces.current().ajax().update(Arrays.asList("form:pessoa-table")); } public List<TbTurma> listTurma() { return turmaService.listarTodos(); } public List<TbEstado> listEstado() { return estadoService.lista(); } public List<TipoFaixa> listaFaixas() { return Arrays.asList(TipoFaixa.values()); } public String gerarMatricula() { Calendar c = Calendar.getInstance(); Date data = c.getTime(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy"); char[] carct = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' }; StringBuilder senha = new StringBuilder(); senha.append(sdf.format(data)); for (int x = 0; x < 5; x++) { int j = (int) (Math.random() * carct.length); senha.append(carct[j]); } return senha.toString(); } public TbTurma getTbTurma() { return tbTurma; } public void setTbTurma(TbTurma tbTurma) { this.tbTurma = tbTurma; } public TbCidade getTbCidade() { return tbCidade; } public void setTbCidade(TbCidade tbCidade) { this.tbCidade = tbCidade; } public TbContato getTbContato() { return tbContato; } public void setTbContato(TbContato tbContato) { this.tbContato = tbContato; } public TbPessoa getTbPessoa() { return tbPessoa; } public void setTbPessoa(TbPessoa tbPessoa) { this.tbPessoa = tbPessoa; } public List<TbPessoa> getPessoa() { return pessoa; } public void setPessoa(List<TbPessoa> pessoa) { this.pessoa = pessoa; } public TbUsuario getTbUsuario() { return tbUsuario; } public void setTbUsuario(TbUsuario tbUsuario) { this.tbUsuario = tbUsuario; } public ConverterTurma getConverterTurma() { return converterTurma; } public void setConverterTurma(ConverterTurma converterTurma) { this.converterTurma = converterTurma; } public ConverterEstado getConverterEstado() { return converterEstado; } public void setConverterEstado(ConverterEstado converterEstado) { this.converterEstado = converterEstado; } public TbEndereco getTbEndereco() { return tbEndereco; } public void setTbEndereco(TbEndereco tbEndereco) { this.tbEndereco = tbEndereco; } public TbEstado getTbEstado() { return tbEstado; } public void setTbEstado(TbEstado tbEstado) { this.tbEstado = tbEstado; } public List<TbCidade> getListaCidades() { return listaCidades; } public void setListaCidades(List<TbCidade> listaCidades) { this.listaCidades = listaCidades; } public ConverterCidade getConverterCidade() { return converterCidade; } public void setConverterCidade(ConverterCidade converterCidade) { this.converterCidade = converterCidade; } public String getPesquisar() { return pesquisar; } public void setPesquisar(String pesquisar) { this.pesquisar = pesquisar; } }
true
4bad4c433cc73bcc2148c047c211a56030679995
Java
defrac/defrac-sample-uievent
/src/java/defrac/sample/uievent/Animator.java
UTF-8
1,769
2.9375
3
[]
no_license
package defrac.sample.uievent; import defrac.display.DisplayObject; import defrac.event.Event; import defrac.event.EventListener; import javax.annotation.Nonnull; // The Animator is attached to the onEnterFrame event. // Therefore it must implement EventListener<EnterFrameEvent> or just EventListener<Event> // // Each time this Animator is notified about an event, it's apply method is called. // Have a look at defrac.lang.* to check some of the fundamental types and utilities // we use in the framework public final class Animator implements EventListener<Event> { @Nonnull private final DisplayObject[] displayObjects; private final float inertia; public Animator(@Nonnull final DisplayObject[] displayObjects, final float inertia) { this.displayObjects = displayObjects; this.inertia = inertia; } @Override public void onEvent(@Nonnull final Event event) { for(final DisplayObject displayObject : displayObjects) { final float alpha = displayObject.alpha(); final float rotation = displayObject.rotation(); final float scaleX = displayObject.scaleX(); final float scaleY = displayObject.scaleY(); // Perform some kind of animation here ... // // Hint: Start this sample with "jvm:run" and then type "~jvm:compile" // Then tweak some of those values here and you will instantly // see the result in the running application displayObject. alpha(interpolate(alpha, 1.0f)). rotation(interpolate(rotation, 0.0f)). scaleX(interpolate(scaleX, 1.0f)). scaleY(interpolate(scaleY, 1.0f)); } } private float interpolate(final float src, final float dst) { return src + (dst - src) * inertia; } }
true
0e2c2b545bc3fe94db7be45f21139df638b0b5d4
Java
piyu031191/Core-Programs
/src/basicProgram/QuotientRemainder.java
UTF-8
640
3.5
4
[]
no_license
package basicProgram; import java.util.Scanner; public class QuotientRemainder { public static void main(String[] args) { System.out.println("Enter the value of num1 and num2"); Scanner input = new Scanner(System.in); int num1 = input.nextInt(); int num2 = input.nextInt(); int quotient = 0; int reminder = 0; quotient = num1/num2; reminder = num1 % num2; System.out.println("Quotient when" +num1 + "/" +num2+ "is: " +quotient); System.out.println("Reminder when " +num1 + " is divided by " +num2+ " is: " +reminder); } }
true
6912c8fa6a38d7050c6dedb2cb09ac4cf1209be8
Java
pyhundan/InfixToPostfix
/src/analyse/StateAnalyze.java
UTF-8
2,790
2.953125
3
[]
no_license
package analyse; import error.CodeException; import java.util.LinkedList; /* exp -> term {addop term} addop -> + \ - term -> Negative {mulop Negative} mulop -> *|/ Nagative -> -factor|factor factor -> (exp) |number */ public class StateAnalyze { public LinkedList<Toke> tokes; public Toke tok; public int index; String fail; public String output=""; public StateAnalyze(LinkedList<Toke> list) { this.tokes=list; } public void Error(String a) throws CodeException { System.err.print(a); throw new CodeException(a); } public void match(String a) throws CodeException { if (tok.word.equals(a)||tok.type.equals(a)) { if (index<tokes.size()) { tok=tokes.get(index++); } } else { Error("wrong word! expected:"+a+" actually:"+tok.word+"index:"+(index+1)+";line:"+tok.line); } } public void start_analyse() { index=0; try { tok= tokes.get(index++); exp(); }catch (CodeException e) { fail=e.message; } } public void exp() throws CodeException { term(); while(tok.word.equals("+")||tok.word.equals("-")) { String s=tok.word; match(tok.word); term(); output+=s; output+="|"; } } public void term() throws CodeException { Negative(); while (tok.word.equals("*")||tok.word.equals("/")) { String s=tok.word; match(tok.word); Negative(); output+=s; output+="|"; } } public void Negative() throws CodeException { if (tok.word.equals("-")) { String s=tok.word; match("-"); output+=s; factor(); } else factor(); } public void factor() throws CodeException { char c=tok.word.charAt(0); if (tok.word.equals("(")) { match("("); exp(); match(")"); } else if (tok.type.equals("number")) { //int temp=Integer.parseInt(tok.word); String s=tok.word; match("number"); output+=s; output+="|"; } else Error("not a factor! (index:"+(index)+",line:"+tok.line+")"); } public static void main(String args[]) { Users users=new Users("src/自动生成.txt"); System.out.println(users.wordAnalyse.tokes); users.stateAnalyze.start_analyse(); System.out.println(users.stateAnalyze.output); } }
true
d351396a1788412c9a93c0ef69e8d7a0ba57e401
Java
chomnoue/swagger-core
/modules/swagger-models/src/test/java/io/swagger/models/properties/StringPropertyTest.java
UTF-8
797
2.4375
2
[ "Apache-2.0" ]
permissive
package io.swagger.models.properties; import static org.testng.Assert.*; import org.testng.annotations.Test; public class StringPropertyTest { @Test public void testGettersAndSetters() { StringProperty stringProperty = new StringProperty(); String vendorName = "x-vendor"; String value = "value"; stringProperty.vendorExtension(vendorName, value); assertEquals(stringProperty.getVendorExtensions().get(vendorName), value); stringProperty._enum(value); assertTrue(stringProperty.getEnum().contains(value)); } @Test public void testFromName() { assertEquals(StringProperty.Format.fromName("byte"), StringProperty.Format.BYTE); assertNull(StringProperty.Format.fromName("unknown")); assertEquals(StringProperty.Format.valueOf("BYTE"), StringProperty.Format.BYTE); } }
true
06d82f62c01a246a17c72004f440564b6252398a
Java
creamjiang/DZYHAndroidClient
/src/com/dld/android/pay/NetworkManager.java
UTF-8
5,871
2.125
2
[]
no_license
package com.dld.android.pay; import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.InetSocketAddress; import java.net.Proxy.Type; import java.net.URL; import java.util.ArrayList; import java.util.List; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLSession; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.message.BasicNameValuePair; public class NetworkManager { static final String TAG = "NetworkManager"; private int connectTimeout = 30000; Context mContext; java.net.Proxy mProxy = null; private int readTimeout = 30000; public NetworkManager(Context paramContext) { this.mContext = paramContext; setDefaultHostnameVerifier(); } private void setDefaultHostnameVerifier() { HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() { public boolean verify(String paramString, SSLSession paramSSLSession) { return true; } }); } public String SendAndWaitResponse(String paramString1, String paramString2) { detectProxy(); String str = null; Object localObject2 = new ArrayList(); ((ArrayList) localObject2).add(new BasicNameValuePair("requestData", paramString1)); HttpURLConnection localHttpURLConnection = null; try { localObject2 = new UrlEncodedFormEntity((List) localObject2, "utf-8"); Object localObject3 = new URL(paramString2); if (this.mProxy != null) ; for (localHttpURLConnection = (HttpURLConnection) ((URL) localObject3) .openConnection(this.mProxy);; localHttpURLConnection = (HttpURLConnection) ((URL) localObject3) .openConnection()) { localHttpURLConnection.setConnectTimeout(this.connectTimeout); localHttpURLConnection.setReadTimeout(this.readTimeout); localHttpURLConnection.setDoOutput(true); localHttpURLConnection.addRequestProperty("Content-type", "application/x-www-form-urlencoded;charset=utf-8"); localHttpURLConnection.connect(); localObject3 = localHttpURLConnection.getOutputStream(); ((UrlEncodedFormEntity) localObject2) .writeTo((OutputStream) localObject3); ((OutputStream) localObject3).flush(); str = BaseHelper.convertStreamToString(localHttpURLConnection .getInputStream()); str = str; return str; } } catch (IOException localIOException) { while (true) { localIOException.printStackTrace(); localHttpURLConnection.disconnect(); } } finally { localHttpURLConnection.disconnect(); } // throw localObject1; } public void detectProxy() { NetworkInfo localNetworkInfo = ((ConnectivityManager) this.mContext .getSystemService("connectivity")).getActiveNetworkInfo(); if ((localNetworkInfo != null) && (localNetworkInfo.isAvailable()) && (localNetworkInfo.getType() == 0)) { String str = android.net.Proxy.getDefaultHost(); int i = android.net.Proxy.getDefaultPort(); if (str != null) { InetSocketAddress localInetSocketAddress = new InetSocketAddress( str, i); this.mProxy = new java.net.Proxy(java.net.Proxy.Type.HTTP, localInetSocketAddress); } } } public boolean urlDownloadToFile(Context paramContext, String paramString1, String paramString2) { boolean i = false; detectProxy(); try { Object localObject = new URL(paramString1); FileOutputStream localFileOutputStream = null; byte[] arrayOfByte = null; if (this.mProxy != null) { localObject = (HttpURLConnection) ((URL) localObject) .openConnection(this.mProxy); ((HttpURLConnection) localObject) .setConnectTimeout(this.connectTimeout); ((HttpURLConnection) localObject) .setReadTimeout(this.readTimeout); ((HttpURLConnection) localObject).setDoInput(true); ((HttpURLConnection) localObject).connect(); localObject = ((HttpURLConnection) localObject) .getInputStream(); File localFile = new File(paramString2); localFile.createNewFile(); localFileOutputStream = new FileOutputStream(localFile); arrayOfByte = new byte[1024]; } while (true) { int j = ((InputStream) localObject).read(arrayOfByte); if (j <= 0) { localFileOutputStream.close(); ((InputStream) localObject).close(); i = true; // break label171; localObject = (HttpURLConnection) ((URL) localObject) .openConnection(); break; } localFileOutputStream.write(arrayOfByte, 0, j); } } catch (IOException localIOException) { localIOException.printStackTrace(); } label171: return i; } }
true
4dd8a82c5014be2311638e203f1c11d18a18074d
Java
hollyroberts/volcano-infiltration
/src/game_base/Screen.java
UTF-8
2,131
3
3
[]
no_license
package game_base; import game_logic.Camera; import game_logic.LevelState; import game_logic.Score; import interfaceComponents.MenuHandler; import particles.ParticleHandler; import audio.SoundEffectsHandler; public class Screen { private static int screen = 5; private static boolean renderScreen = true; //Render content of game rather than loading screen /* * Screen 1 = In game * Screen 2 = In game paused * Screen 3 = Level Complete * Screen 4 = Game Over * Screen 5 = Name selection screen * Screen 6 = No levels :( * Screen 7 = Level selection screen * Screen 8 = Help/instruction */ public static boolean renderScreen() { //Return if the screen is on loading mode return renderScreen; } public static void setRenderScreen(boolean renderScreen) { Screen.renderScreen = renderScreen; } public static void setScreen(int newScreen) { //Change the screen and update game as appropriate MenuHandler.unload(); setRenderScreen(false); screen = newScreen; //Set mouse down to false to make user have to click twice Mouse.setIsDown(false); Mouse.reset(); switch (screen) { case 1: break; case 2: MenuHandler.load_Pause(); break; case 3: ParticleHandler.deleteAll(); Score.calcLevelComplete(); MenuHandler.load_LevelComplete(); SoundEffectsHandler.playSound("you win", 0); //Play sound Camera.reset(); LevelState.cleanup(); break; case 4: ParticleHandler.deleteAll(); Score.calcGameOver(); MenuHandler.load_GameOver(); SoundEffectsHandler.playSound("you lose", 0); //Play sound Camera.reset(); LevelState.cleanup(); break; case 5: ParticleHandler.deleteAll(); MenuHandler.load_MenuNames(); Camera.reset(); break; case 6: ParticleHandler.deleteAll(); MenuHandler.load_NoMoreLevels(); Camera.reset(); break; case 7: ParticleHandler.deleteAll(); MenuHandler.load_LevelSelect(); Camera.reset(); break; case 8: ParticleHandler.deleteAll(); MenuHandler.load_MenuHelp(); break; } setRenderScreen(true); } public static int getScreen() { return screen; } }
true
9162ff7b52ffc110abfb8bf5808120e50f2302f4
Java
shruthisetty/integration-toolkit-sample-code-java
/mhr-b2b-client/src/src/main/java/au/gov/nehta/vendorlibrary/pcehr/clients/common/util/CommonHeaderValidator.java
UTF-8
4,076
2.25
2
[ "LicenseRef-scancode-warranty-disclaimer", "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
/* * Copyright 2012 NEHTA * * Licensed under the NEHTA Open Source (Apache) License; you may not use this * file except in compliance with the License. A copy of the License is in the * 'license.txt' file, which should be provided with this work. * * 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 au.gov.nehta.vendorlibrary.pcehr.clients.common.util; import au.net.electronichealth.ns.pcehr.xsd.common.commoncoreelements._1.PCEHRHeader; import org.apache.commons.lang.Validate; import java.math.BigInteger; /** * Utility class used to validate the common header of a PCEHR client request. */ public final class CommonHeaderValidator { private static final int EXPECTED_IHI_LENGTH = 16; /** * Private constructor. */ private CommonHeaderValidator() { } /** * Validate the contents of the {@link PCEHRHeader}. * * @param commonHeader A {@link PCEHRHeader}. * @param requireIHINumber Is the IHINumber required? */ public static void validate(PCEHRHeader commonHeader, boolean requireIHINumber) { Validate.notNull(commonHeader, "'commonHeader' cannot be null."); if (requireIHINumber) { Validate.notEmpty(commonHeader.getIhiNumber(), "'commonHeader.IHINumber' cannot be null nor empty."); validateIhi(commonHeader.getIhiNumber()); } Validate.notNull(commonHeader.getUser(), "'commonHeader.user' cannot be null."); Validate.notNull(commonHeader.getUser().getIDType(), "'commonHeader.user.idType' cannot be null."); Validate.notEmpty(commonHeader.getUser().getID(), "'commonHeader.user.id' cannot be null nor empty."); Validate.notEmpty(commonHeader.getUser().getUserName(), "'commonHeader.user.userName' cannot be null nor empty."); if (commonHeader.getUser().isUseRoleForAudit()) { Validate.notEmpty( commonHeader.getUser().getRole(), "'commonHeader.user.role' must be specified as 'commonHeader.user.userRoleForAudit' is true." ); } Validate.notNull(commonHeader.getProductType(), "'commonHeader.productType' cannot be null."); Validate.notEmpty(commonHeader.getProductType().getVendor(), "'commonHeader.productType.vendor' cannot be null nor empty."); Validate.notEmpty(commonHeader.getProductType().getProductName(), "'commonHeader.productType.productName' cannot be null nor empty."); Validate.notEmpty(commonHeader.getProductType().getProductVersion(), "'commonHeader.productType.productVersion' cannot be null nor empty."); Validate.notEmpty(commonHeader.getProductType().getPlatform(), "'commonHeader.productType.platform' cannot be null nor empty."); Validate.notNull(commonHeader.getClientSystemType(), "'commonHeader.clientSystemType' cannot be null."); if (commonHeader.getAccessingOrganisation() != null) { Validate.notEmpty( commonHeader.getAccessingOrganisation().getOrganisationID(), "'commonHeader.accessingOrganisation.organisationId' cannot be null nor empty." ); Validate.notEmpty( commonHeader.getAccessingOrganisation().getOrganisationName(), "'commonHeader.accessingOrganisation.organisationName' cannot be null nor empty." ); } } private static void validateIhi(final String ihi) { Validate.notEmpty(ihi, "'ihi' must not be null nor empty."); // check length. if (ihi.length() != EXPECTED_IHI_LENGTH) { throw new IllegalArgumentException("'ihi' length must be 16 digits."); } // check digits. try { new BigInteger(ihi); } catch (NumberFormatException e) { throw new IllegalArgumentException("'ihi' must only contain digits.", e); } // check format. if (!ihi.startsWith("800360")) { throw new IllegalArgumentException("'ihi' must be of the format 800360XXXXXXXXXX."); } } }
true
8002a49bbbc8f08422ffab16dcf63281e19da55e
Java
bertillemenguy/GestionFestival
/FrontJavaFX/src/FrontJavaFX/Button.java
UTF-8
413
1.859375
2
[]
no_license
package FrontJavaFX; import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.layout.BorderPane; import javafx.stage.Stage; public class Button extends Application{ // private Button back_emploi_du_temps = new Button(); public void start(Stage button) { button.show(); } public static void main(String[] args) { Application.launch(App.class, args); } }
true
1bb25b4b017ef21855e417d97fb67213bf08f769
Java
perfall/Tetris
/TetrominoMaker.java
UTF-8
2,831
3.75
4
[]
no_license
package tetris; /** * This class can be viewed as the "factory" for the Poly's, based on what type of Poly it is it returns * the two-dimensional array representation of it. */ public class TetrominoMaker { public Poly getPoly(int n) { switch (n) { case 0: //I return new Poly(createShapeI());//), SquareType.I); case 1: //O return new Poly(createShapeO());//), SquareType.I);, SquareType.O); case 2: //T return new Poly(createShapeT());//), SquareType.I);, SquareType.T); case 3: //S return new Poly(createShapeS());//), SquareType.I);, SquareType.S); case 4: //Z return new Poly(createShapeZ());//), SquareType.I);, SquareType.Z); case 5: //J return new Poly(createShapeJ());//), SquareType.I);, SquareType.J); case 6: //L return new Poly(createShapeL());//), SquareType.I);, SquareType.L); default: throw new IllegalArgumentException("Invalid index: " + n); } } public SquareType[][] createEmptyShell(int dim){ // Create dim x dim array SquareType[][] polyShell = new SquareType[dim][dim]; // Fill with EMPTY for (int row = 0; row < dim; row++) { for (int col = 0; col < dim; col++) { polyShell[col][row] = SquareType.EMPTY; } } return polyShell; } public SquareType[][] createShapeI(){ SquareType[][] shape = createEmptyShell(4); shape[1][0] = SquareType.I; shape[1][1] = SquareType.I; shape[1][2] = SquareType.I; shape[1][3] = SquareType.I; return shape; } public SquareType[][] createShapeO(){ SquareType[][] shape = createEmptyShell(2); shape[0][0] = SquareType.O; shape[0][1] = SquareType.O; shape[1][0] = SquareType.O; shape[1][1] = SquareType.O; return shape; } public SquareType[][] createShapeT() { SquareType[][] shape = createEmptyShell(3); shape[0][1] = SquareType.T; shape[1][0] = SquareType.T; shape[1][1] = SquareType.T; shape[1][2] = SquareType.T; return shape; } public SquareType[][] createShapeS() { SquareType[][] shape = createEmptyShell(3); shape[0][1] = SquareType.S; shape[0][2] = SquareType.S; shape[1][0] = SquareType.S; shape[1][1] = SquareType.S; return shape; } public SquareType[][] createShapeZ() { SquareType[][] shape = createEmptyShell(3); shape[0][0] = SquareType.Z; shape[0][1] = SquareType.Z; shape[1][1] = SquareType.Z; shape[1][2] = SquareType.Z; return shape; } public SquareType[][] createShapeJ() { SquareType[][] shape = createEmptyShell(3); shape[0][0] = SquareType.J; shape[1][0] = SquareType.J; shape[1][1] = SquareType.J; shape[1][2] = SquareType.J; return shape; } public SquareType[][] createShapeL() { SquareType[][] shape = createEmptyShell(3); shape[0][2] = SquareType.L; shape[1][0] = SquareType.L; shape[1][1] = SquareType.L; shape[1][2] = SquareType.L; return shape; } }
true
a75b1e4a48e8462001fe4b6e5779eeefef9544f3
Java
mousesd/Spring5Recipe
/Chapter13/App15/src/main/java/net/homenet/configuration/WeatherAppInitializer.java
UTF-8
915
1.851563
2
[]
no_license
package net.homenet.configuration; import org.apache.cxf.transport.servlet.CXFServlet; import org.springframework.web.WebApplicationInitializer; import org.springframework.web.context.ContextLoaderListener; import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; import javax.servlet.ServletContext; import javax.servlet.ServletRegistration; public class WeatherAppInitializer implements WebApplicationInitializer { @Override public void onStartup(ServletContext servletContext) { AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext(); context.register(WeatherConfiguration.class); servletContext.addListener(new ContextLoaderListener(context)); ServletRegistration.Dynamic cxf = servletContext.addServlet("cxf", new CXFServlet()); cxf.setLoadOnStartup(1); cxf.addMapping("/*"); } }
true
b5c1178f7e07a5d8273212cfac6876dcf880c0b3
Java
Shinjice/CodeWars
/8kyu/Sort My Textbooks/Demo.java
UTF-8
389
2.84375
3
[]
no_license
import java.util.List; import java.util.Collections; class sorter { public static List<String> sort(List<String> textbooks) { //use sort() from Collections with the static field of String class to ensure case insensitivity Collections.sort(textbooks, String.CASE_INSENSITIVE_ORDER); return textbooks; } } //https://www.codewars.com/kata/5a07e5b7ffe75fd049000051/train/java
true
e4e00736cacdd583e96b7bff61b2951cf74c1085
Java
biancama/meoni-projects
/EasyShipment/src/com/biancama/utils/ByteBufferEntry.java
UTF-8
1,667
3.015625
3
[]
no_license
package com.biancama.utils; import java.nio.ByteBuffer; public class ByteBufferEntry { public ByteBuffer buffer = null; private int size = 0; private boolean unused = true; public static ByteBufferEntry getByteBufferEntry(int size) { ByteBufferEntry ret = ByteBufferController.getInstance().getByteBufferEntry(size); if (ret != null) { return ret.getbytebufferentry(size); } else { return new ByteBufferEntry(size).getbytebufferentry(size); } } private ByteBufferEntry(int size) { this.size = size; buffer = ByteBuffer.allocateDirect(size); clear(); } public int capacity() { return buffer.capacity(); } public void clear() { buffer.clear(); buffer.limit(size); } public void clear(int size) { this.size = size; buffer.clear(); buffer.limit(size); } public int size() { return size; } public void limit(int size) { this.size = size; buffer.limit(size); } protected ByteBufferEntry getbytebufferentry(int size) { unused = false; this.size = size; clear(); return this; } /* * may be called only once in lifetime of the bytebufferentry!, please call * this only at the end of usage, because buffer is instantly available for * others to use */ public void setUnused() { if (unused) { return; } unused = true; ByteBufferController.getInstance().putByteBufferEntry(this); } }
true
428869514f05e2e68358ef861059103c9a7e17c1
Java
P79N6A/icse_20_user_study
/methods/Method_39277.java
UTF-8
550
2.46875
2
[]
no_license
/** * Adds received attachment. * @param part {@link Part}. * @param content Content as byte array. * @return this * @see #attachment(EmailAttachment) */ private ReceivedEmail addAttachment(final Part part,final byte[] content) throws MessagingException { final EmailAttachmentBuilder builder=addAttachmentInfo(part); builder.content(content,part.getContentType()); final EmailAttachment<ByteArrayDataSource> attachment=builder.buildByteArrayDataSource(); attachment.setSize(content.length); return storeAttachment(attachment); }
true
f0f3a654328843beaa8f2b78c5dabf1eed8c56df
Java
proteauj/api
/src/main/java/com/versatile/api/ressource/StatusRessource.java
UTF-8
596
2.28125
2
[]
no_license
package com.versatile.api.ressource; public class StatusRessource { private Integer idStatus; private String status; public StatusRessource() { } public StatusRessource(Integer idStatus, String status) { this.idStatus = idStatus; this.status = status; } public Integer getIdStatus() { return idStatus; } public void setIdStatus(Integer idStatus) { this.idStatus = idStatus; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } }
true
d66116dc7629dad0bcc3864b7dbb539348241497
Java
kriishna/showcaseview-android
/Sample/src/main/java/co/naughtyspirit/sample/CustomThemeWithBtnBackgroundDrawable.java
UTF-8
1,192
2.09375
2
[ "Apache-2.0" ]
permissive
package co.naughtyspirit.sample; import android.app.Activity; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.support.v7.app.AppCompatActivity; import android.widget.Button; import co.naughtyspirit.showcaseview.ShowcaseView; import co.naughtyspirit.showcaseview.targets.TargetView; import co.naughtyspirit.showcaseview.utils.PositionsUtil; /** * Created by kevintanhongann on 5/21/15. */ public class CustomThemeWithBtnBackgroundDrawable extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_custom_btn_background); Button button = (Button) findViewById(R.id.button); TargetView targetView = new TargetView(button, TargetView.ShowcaseType.CIRCLE); ShowcaseView showcaseView = new ShowcaseView.Builder(this, "showcaseView") .setDescription(" ", PositionsUtil.ItemPosition.CENTER) .setTarget(targetView) .setButton("Okay", PositionsUtil.ItemPosition.BOTTOM_CENTER).setCustomTheme(R.style.CustomShowcaseBackgroundDrawable).build(); } }
true
82604af4b51fbafc062b35153cf944fc05b0490f
Java
samabcde/leetcode
/src/main/java/q977/Solution.java
UTF-8
1,528
3.34375
3
[]
no_license
package q977; import java.util.Arrays; public class Solution { public static void main(String[] args) { Solution a = new Solution(); System.out.println(Arrays.toString(a.sortedSquares(new int[] { -2, 0, 1 }))); } public int[] sortedSquares(int[] A) { if (A.length == 0) { return A; } int changeSignIndex = -1; for (int i = 0; i < A.length - 1; i++) { if (A[i] < 0 && A[i + 1] >= 0) { changeSignIndex = i; break; } } if (changeSignIndex == -1) { boolean reverse = false; if (A[0] < 0) { reverse = true; } for (int i = 0; i < A.length; i++) { A[i] = A[i] * A[i]; } if (reverse) { for (int i = 0; i < A.length / 2; i++) { int temp = A[i]; A[i] = A[A.length - i - 1]; A[A.length - i - 1] = temp; } } return A; } int[] sorted = new int[A.length]; int negativeStart = changeSignIndex; int positiveStart = changeSignIndex + 1; int sortedIndex = 0; while (negativeStart > -1 || positiveStart < A.length) { if (negativeStart == -1) { sorted[sortedIndex] = A[positiveStart] * A[positiveStart]; positiveStart++; } else if (positiveStart == A.length) { sorted[sortedIndex] = A[negativeStart] * A[negativeStart]; negativeStart--; } else if (-A[negativeStart] < A[positiveStart]) { sorted[sortedIndex] = A[negativeStart] * A[negativeStart]; negativeStart--; } else { sorted[sortedIndex] = A[positiveStart] * A[positiveStart]; positiveStart++; } sortedIndex++; } return sorted; } }
true
f9aa0148aa039bd20c76fe82f62b0b4c1a4bedf4
Java
gdrapic/test
/ResponseDetails.java
UTF-8
5,017
2.046875
2
[]
no_license
import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; public class ResponseDetails<T> { public enum RESP_KEY { apiResponse, responseDetails }; public enum CATEGORY { SUCCESS, ERROR, WARNING,INFO }; public enum COMPONENT { ALL, RSSSERV, USERPROFILESRV }; public enum CODE { SUCCESS(CATEGORY.SUCCESS, COMPONENT.ALL, 200, "Success"), //RSSSERV //Errors:... RSSSERV_ERR_GENERAL(CATEGORY.ERROR, COMPONENT.RSSSERV, 1000, "General Error"), RSSSERV_ERR_REQUIRED(CATEGORY.ERROR,COMPONENT.RSSSERV, 1010, "Required fields are missing"), RSSSERV_ERR_AUTHORIZATION(CATEGORY.ERROR,COMPONENT.RSSSERV, 1020, "Not Authorized"), RSSSERV_ERR_SOURCE_OWNERSHIP(CATEGORY.ERROR,COMPONENT.RSSSERV, 1030, "Source Ownership Info is missing"), RSSSERV_ERR_FILE_TYPE_INVALID(CATEGORY.ERROR,COMPONENT.RSSSERV, 1040, "Attached File Type is invalid"), //Warnings RSSSERV_WARN_GENERAL(CATEGORY.WARNING, COMPONENT.RSSSERV, 1500, "General Warning"), RSSSERV_WARN_NOTIFICATION_FAILURE(CATEGORY.WARNING, COMPONENT.RSSSERV, 1510, "Failed to send notification"), RSSSERV_RACE_CONDITION(CATEGORY.ERROR, COMPONENT.RSSSERV, 1600, "Action by different users at the same time"), RSSSERV_INVALID_DOMAIN(CATEGORY.ERROR, COMPONENT.RSSSERV, 1610, "Invalid Domain"), //TODO: keep adding codes here.. //USERPROFILESRV //Errors:... USERPROFILESRV_ERR_GENERAL(CATEGORY.ERROR, COMPONENT.USERPROFILESRV, 2000, "General Error"), USERPROFILESRV_ERR_SUPPPORT(CATEGORY.ERROR,COMPONENT.USERPROFILESRV, 2001, "Unknow Exception,Support Required"), USERPROFILESRV_ERR_ADD_POLICY_FAILURE(CATEGORY.ERROR,COMPONENT.USERPROFILESRV, 2010, "Failed to add policy"), USERPROFILESRV_ERR_REMOVE_POLICY_FAILURE(CATEGORY.ERROR,COMPONENT.USERPROFILESRV, 2011, "Failed to remove policy"), public final CATEGORY category; public final COMPONENT component; public final Integer code; public final String description; private CODE(CATEGORY category, COMPONENT component, Integer code, String description) { this.category = category; this.component = component; this.code = code; this.description = description; } }; @JsonProperty("responseCode") private Integer responseCode; @JsonProperty("category") private CATEGORY category; @JsonProperty("component") private COMPONENT component; @JsonProperty("description") private String description; @JsonProperty("details") private String details; @JsonProperty("apiResponse") private T apiResponse; public ResponseDetails(CODE code) { this(code, null); } public ResponseDetails(@JsonProperty("responseCode") Integer responseCode, @JsonProperty("category") CATEGORY category, @JsonProperty("component") COMPONENT component, @JsonProperty("description") String description, @JsonProperty("details") String details, @JsonProperty("apiResponse") T apiResponse) { super(); this.responseCode = responseCode; this.category = category; this.component = component; this.description = description; this.details = details; this.apiResponse = apiResponse; } public ResponseDetails(CODE code, String details) { this.responseCode = code.code; this.category = code.category; this.component = code.component; this.description = code.description; this.details = details; } @JsonProperty("responseCode") public Integer getResponseCode() { return responseCode; } @JsonIgnore public static CODE getCode(Integer responseCode) throws Exception { CODE[] codes = CODE.values(); for ( int i = 0 ; i < codes.length ; i++ ) { if ( codes[i].code.intValue() == responseCode ){ return codes[i]; } } throw new Exception("Invalid responseCode: " + responseCode); } @JsonProperty("category") public CATEGORY getCategory() { return category; } @JsonProperty("component") public COMPONENT getComponent() { return component; } @JsonProperty("description") public String getDescription() { return description; } @JsonProperty("details") public String getDetails() { return details; } @JsonProperty("apiResponse") public T getApiResponse() { return apiResponse; } @JsonIgnore public ResponseEntity<ResponseDetails> getResponseEntity() { return getResponseEntity(null, HttpStatus.OK); } @JsonIgnore public ResponseEntity<ResponseDetails> getResponseEntity(T apiResponse) { return getResponseEntity(apiResponse, HttpStatus.OK); } @JsonIgnore public ResponseEntity<ResponseDetails> getResponseEntity(T apiResponse, HttpStatus httpStatus) { this.apiResponse = apiResponse; return new ResponseEntity<ResponseDetails>(this, httpStatus); } @Override public String toString() { return "ResponseDetails [responseCode=" + responseCode + ", category=" + category + ", component=" + component + ", description=" + description + ", details=" + details + "]"; } }
true
772131e587d032502a55bb8fbad45a3cc2849ce4
Java
kha0213/Today-I-Learn
/Spring/spring-advanced/advanced/src/test/java/hello/advanced/trace/strategy/code/Strategy.java
UTF-8
228
1.898438
2
[]
no_license
package hello.advanced.trace.strategy.code; /** * Created by Kim Young Long. * My Git Blog : https://kha0213.github.io/ * Date: 2021-11-08 * Time: 오후 8:30 */ @FunctionalInterface public interface Strategy { void call(); }
true
582374789dfc68534037d23f531da676aea0450d
Java
xiaoningzvj/world-oriented-programming
/2020-09-02/fhj/GetMaxTree.java
UTF-8
2,428
3.625
4
[]
no_license
package com.example.demo; import java.util.HashMap; import java.util.Map; import java.util.Stack; public class GetMaxTree { public static void main(String[] args) { int arr[] ={1,2,3,4,5}; GetMaxTree getMaxTree = new GetMaxTree(); Node head = getMaxTree.buildMaxTree(arr); //验证结果 //层序遍历 看结果 //todo } public Node buildMaxTree(int[] arr) { Node head = null; Map<Node, Node> leftMaxMap = new HashMap<>(); Map<Node, Node> rightMaxMap = new HashMap<>(); Node[] nodes = new Node[arr.length]; Stack<Node> tempStack = new Stack<>(); for (int i = 0; i < arr.length; i++) { Node current = new Node(arr[i]); nodes[i] = current; } for (Node current : nodes) { pushLeft(leftMaxMap, tempStack, current); } tempStack.clear(); for (int i = arr.length - 1; i >= 0; i--) { pushLeft(rightMaxMap, tempStack, nodes[i]); } //tempStack.clear(); for (int i = 0; i < arr.length; i++) { Node current = nodes[i]; //先查验左 Node left = leftMaxMap.get(current); Node right = rightMaxMap.get(current); Node parent = null; if (left == null && right == null) { head = current; continue; } if (left == null && right != null) { parent = right; } if (left != null && right == null) { parent = left; } if (left != null && right != null) { parent = left.value < right.value ? left : right; } if (parent != null) { if (parent.left == null) { parent.left = current; } else { parent.right = current; } } } return head; } public void pushLeft(Map<Node, Node> leftMap, Stack<Node> stack, Node current) { if (stack.isEmpty()) { leftMap.put(current, null); } while (!stack.isEmpty() && stack.peek().value < current.value) { stack.pop(); } if (stack.empty()) { leftMap.put(current, null); } else { leftMap.put(current, stack.peek()); } } }
true
abcbf7aca25e78f999165cf1085c91e200a4eaa8
Java
fangxiaoguang/FrameLibrary
/app/src/main/java/com/game/gaika/scene/dialg/BlueRepairYesNoDialog.java
UTF-8
3,107
1.984375
2
[]
no_license
package com.game.gaika.scene.dialg; import com.game.frame.fsm.MSG_ID; import com.game.frame.fsm.TouchMessage; import com.game.frame.scene.BaseLogicScene; import com.game.frame.scene.SCENE_ID; import com.game.frame.scene.dialg.DialogScene; import com.game.frame.sprite.NormalSprite; import com.game.frame.sprite.TextSprite; import com.game.frame.texture.TexRegionManager; import com.game.gaika.data.GameDataManager; import com.game.gaika.data.weapon.BaseWeapon; import static com.game.frame.texture.TexRegionManager.getFont16; /** * Created by fangxg on 2015/9/1. */ public class BlueRepairYesNoDialog extends DialogScene { public BlueRepairYesNoDialog(BaseLogicScene pParentScene, int pWeaponID, int pFromLifeEx, int pToLifeEx, int pNeedSupply) { super(SCENE_ID.BLUE_REPAIR_YES_NO_DIALOG, 0.0f, 0.0f, 406, 185, pParentScene, EPointModel.POINT_MODEL_CENTER); GameDataManager gdm =GameDataManager.getInstance(); BaseWeapon blueNode = gdm.weapons.get(pWeaponID); NormalSprite bkSprite = new NormalSprite(0, 0, "dialg4"); addSprite(bkSprite); NormalSprite weapSprite = new NormalSprite(50, 40, "weap_nm1", blueNode.info.texIndex); addSprite(weapSprite); NormalSprite typeSprite = new NormalSprite(50, 50, "font_typ", blueNode.info.type.ordinal()); addSprite(typeSprite); NormalSprite unitSprite = new NormalSprite(50, 60, "unit02", blueNode.info.texIndex); addSprite(unitSprite); NormalSprite flagSprite = new NormalSprite(50, 90 - 5, "flag01", blueNode.info.country.ordinal()); addSprite(flagSprite); NormalSprite lvSprite = new NormalSprite(90, 95 - 5, "font_lv1", blueNode.getLv()); addSprite(lvSprite); NormalSprite fromLifeExSprite = new NormalSprite(55, 105, "font01", pFromLifeEx); addSprite(fromLifeExSprite); NormalSprite toLifeExSprite = new NormalSprite(90, 105, "font01", pToLifeEx); addSprite(toLifeExSprite); TextSprite text1Sprite = new TextSprite(130, 45, true, "消耗" + pNeedSupply + "补给物资", getFont16()); addSprite(text1Sprite); TextSprite text2Sprite = new TextSprite(130, 70, true,"补充" + (pToLifeEx - pFromLifeEx) + blueNode.info.getUnitString(), getFont16()); addSprite(text2Sprite); TextSprite text3Sprite = new TextSprite(130, 95,true, blueNode.info.name, getFont16()); addSprite(text3Sprite); NormalSprite buttonYesSprite = new NormalSprite(43, 137, "dialg6bt", 0, new TouchMessage( MSG_ID.MSG_SCENE_BATTLEFIELD__BLUE_REPAIR_YES, null, pParentScene, pWeaponID) ); addSprite(buttonYesSprite); NormalSprite buttonNoSprite = new NormalSprite(287, 137, "dialg6bt", 1, new TouchMessage( MSG_ID.MSG_SCENE_BATTLEFIELD__BLUE_REPAIR_NO, null, pParentScene, pWeaponID)); addSprite(buttonNoSprite); } @Override public boolean isBacegroundEnabled() { return false; } @Override public void buildScene() { } @Override public void onHandlMessage(TouchMessage pTouchMessage) { } }
true
95620085753dd0ef3bed2cadd44df36758a8aa14
Java
DogaruMonica/Backend
/src/main/java/iss/sirius/Model/Catalog.java
UTF-8
1,261
2.296875
2
[]
no_license
package iss.sirius.Model; import com.fasterxml.jackson.annotation.JsonBackReference; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.OneToMany; import javax.persistence.OneToOne; import javax.persistence.Table; import java.util.Set; @Entity @Table(name = "catalogs") public class Catalog { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; @JsonBackReference @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER) @JoinColumn(name = "classroomid", referencedColumnName = "id") private Classroom classroom; @OneToMany(mappedBy = "catalog", cascade = CascadeType.ALL) private Set<Grade> grades; public Catalog() { }; public Catalog(int id) { this.id = id; } public int getId() { return id; } public void setId(int id) { this.id = id; } public Classroom getClassroom() { return classroom; } public void setClassroom(Classroom classroom) { this.classroom = classroom; } }
true
68d613aa448895a5559f34fccf004c35952da514
Java
156420591/algorithm-problems-java
/leetcode-advanced-java/src/main/java/johnny/leetcode/advanced/ZumeDepth.java
UTF-8
1,038
2.953125
3
[]
no_license
package johnny.leetcode.advanced; import java.util.ArrayList; import java.util.List; import java.util.Random; public class ZumeDepth { public int[][] print = null; int[][] grid = null; List<Integer> list = null; public int total = 0; int count = 0; public ZumeDepth(int[][] grid) { this.grid = grid; this.list = new ArrayList<>(); int m = grid.length; int n = grid[0].length; print = new int[m][n]; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (grid[i][j] < 0) { list.add(i * n + j); total += -grid[i][j]; } } } } public void drop() { Random rand = new Random(); int pos = rand.nextInt(list.size()); int val = list.get(pos); int n = grid[0].length; grid[val/n][val%n]++; print[val/n][val%n]++; if (grid[val/n][val%n] == 0) { list.remove(pos); } } }
true
8ce662ce29caf877721281c30f38cbc777d94a91
Java
Sudhanshu-bluespace/EmailApp_Backend
/EmailApp/src/main/java/com/bluespacetech/security/controller/UserAccountController.java
UTF-8
12,739
1.960938
2
[ "MIT" ]
permissive
package com.bluespacetech.security.controller; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationEventPublisher; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; import com.bluespacetech.contact.service.ContactService; import com.bluespacetech.core.controller.AbstractBaseController; import com.bluespacetech.core.exceptions.BusinessException; import com.bluespacetech.security.OnRegistrationCompleteEvent; import com.bluespacetech.security.constants.UserAccountTypeConstant; import com.bluespacetech.security.exceptions.UserAccountDoesNotExistException; import com.bluespacetech.security.model.CompanyRegistration; import com.bluespacetech.security.model.UserAccount; import com.bluespacetech.security.model.UserAccountUserGroup; import com.bluespacetech.security.model.UserGroup; import com.bluespacetech.security.repository.CompanyRegistrationRepository; import com.bluespacetech.security.repository.VerificationTokenRepository; import com.bluespacetech.security.resources.UserAccountChangePasswordResource; import com.bluespacetech.security.resources.UserAccountResource; import com.bluespacetech.security.resources.assembler.UserAccountResourceAssembler; import com.bluespacetech.security.searchcriterias.UserAccountSearchCriteria; import com.bluespacetech.security.service.BlueSpaceTechUserAccountService; import com.bluespacetech.security.service.UserGroupService; /** * The Class UserAccountController. * @author Sudhanshu Tripathy */ @RestController @RequestMapping("/userAccounts") public class UserAccountController extends AbstractBaseController { /** The blue space tech user account service. */ @Autowired BlueSpaceTechUserAccountService blueSpaceTechUserAccountService; /** The user group service. */ @Autowired UserGroupService userGroupService; /** The contact service. */ @Autowired ContactService contactService; /** The event publisher. */ @Autowired ApplicationEventPublisher eventPublisher; /** The company registration repository. */ @Autowired CompanyRegistrationRepository companyRegistrationRepository; /** The verification token repository. */ @Autowired VerificationTokenRepository verificationTokenRepository; /** The Constant LOGGER. */ private static final Logger LOGGER = LogManager.getLogger(UserAccountController.class.getName()); /** * Retrieve All Financial Years. * * @return the user accounts */ @RequestMapping(value = "", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<List<UserAccountResource>> getUserAccounts() { final List<UserAccount> userAccounts = blueSpaceTechUserAccountService.getAllUserAccounts(); final List<UserAccountResource> userAccountResources = new UserAccountResourceAssembler() .toResources(userAccounts); return new ResponseEntity<List<UserAccountResource>>(userAccountResources, HttpStatus.OK); } /** * Gets the company list. * * @return the company list */ @RequestMapping(value = "/getCompanyList", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<List<CompanyRegistration>> getCompanyList() { final List<CompanyRegistration> companyList = companyRegistrationRepository.findAll(); return new ResponseEntity<List<CompanyRegistration>>(companyList, HttpStatus.OK); } /** * Retrieve Financial year by Id. * * @param id id of Financial year to be retrieved. * @return the user account by id */ @RequestMapping(value = "/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<UserAccountResource> getUserAccountById(@PathVariable final Long id) { final UserAccount userAccount = blueSpaceTechUserAccountService.getUserAccountById(id); if (userAccount == null) { throw new UserAccountDoesNotExistException("Supplied Financial year is invalid."); } final List<Long> userGroupIds = new ArrayList<Long>(); for (final UserAccountUserGroup userAccountUserGroup : userAccount.getUserAccountUserGroups()) { userGroupIds.add(userAccountUserGroup.getUserGroupId()); } final List<UserGroup> userGroups = userGroupService.getUserGroupByIds(userGroupIds); final Map<Long, UserGroup> userGroupsMap = new HashMap<Long, UserGroup>(); for (final UserGroup userGroup : userGroups) { userGroupsMap.put(userGroup.getId(), userGroup); } final UserAccountResource userAccountResource = new UserAccountResourceAssembler() .toCompleteResource(userAccount, userGroupsMap); return new ResponseEntity<UserAccountResource>(userAccountResource, HttpStatus.OK); } /** * Retrieve Financial year by Id. * * @param userAccountSearchCriteria the user account search criteria * @return the user accounts * @throws BusinessException the business exception */ @RequestMapping(value = "/search", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<List<UserAccountResource>> getUserAccounts( @RequestBody final UserAccountSearchCriteria userAccountSearchCriteria) throws BusinessException { final List<UserAccount> userAccounts = blueSpaceTechUserAccountService .findUserAccountsBySearchCriteria(userAccountSearchCriteria); List<UserAccountResource> userAccountResources = new ArrayList<UserAccountResource>(); if (userAccounts != null) { userAccountResources = new UserAccountResourceAssembler().toResources(userAccounts); } return new ResponseEntity<List<UserAccountResource>>(userAccountResources, HttpStatus.OK); } /** * Creates the. * * @param userAccountResource the user account resource * @param request the request * @return the response entity * @throws BusinessException the business exception */ @ResponseStatus(HttpStatus.CREATED) @RequestMapping(method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<Void> create(@RequestBody final UserAccountResource userAccountResource, HttpServletRequest request) throws BusinessException { final UserAccount userAccount = UserAccountResourceAssembler.getUserAccountFromResource(userAccountResource); CompanyRegistration reg = companyRegistrationRepository .findCompanyRegistrationByCompanyNameIgnoreCase(userAccountResource.getCompanyName()); if (reg == null) { CompanyRegistration reg1 = new CompanyRegistration(); reg1.setCompanyName(userAccountResource.getCompanyName()); reg1.setApproved(true); reg1.setDescription(userAccountResource.getCompanyName()); reg = companyRegistrationRepository.save(reg1); } userAccount.setUserAccountType(UserAccountTypeConstant.ACC_TYPE_USER); userAccount.setCompanyRegistration(reg); Map<UserAccount,String> retrievedUserWithdecryptedPassword = blueSpaceTechUserAccountService.createUserAccount(userAccount); UserAccount user=null; String password = null; for(UserAccount acc : retrievedUserWithdecryptedPassword.keySet()) { user=acc; password=retrievedUserWithdecryptedPassword.get(acc); user.setPassword(password); } try { /*URL url = new URL(request.getRequestURL().toString()); String host = url.getHost(); String scheme = url.getProtocol(); int port = url.getPort(); URI uri = new URI(scheme, null, host, port, null, null, null); LOGGER.info("Captured Server Url : " + uri.toString());*/ OnRegistrationCompleteEvent event = new OnRegistrationCompleteEvent(user, request.getLocale(), null, true,"ADMIN"); LOGGER.debug("Event : " + event); eventPublisher.publishEvent(event); LOGGER.info("Sent Account Creation Email to user successfully"); return new ResponseEntity<Void>(HttpStatus.OK); } catch (Exception me) { LOGGER.error("Account creation email sending failed: " + me.getMessage()); return new ResponseEntity<Void>(HttpStatus.INTERNAL_SERVER_ERROR); } } /** * Update. * * @param id the id * @param userAccountResource the user account resource * @return the response entity * @throws BusinessException the business exception */ @RequestMapping(value = "/{id}", method = RequestMethod.PUT, consumes = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<Void> update(@PathVariable final Long id, @RequestBody final UserAccountResource userAccountResource) throws BusinessException { // Get existing Financial Year final UserAccount currentUserAccount = blueSpaceTechUserAccountService.getUserAccountById(id); if (currentUserAccount == null) { throw new UserAccountDoesNotExistException("Supplied Financial year is invalid."); } if (!currentUserAccount.getVersion().equals(userAccountResource.getVersion())) { throw new BusinessException("Stale Financial Year. Please update."); } // Extract the Financial Year from Resource final UserAccount sourceUserAccount = UserAccountResourceAssembler .getUserAccountFromResource(userAccountResource); // Copy changes from source to destination including version so that if // some one updated the branch then JPA will throw exception UserAccountResourceAssembler.copyUserAccountInto(sourceUserAccount, currentUserAccount); blueSpaceTechUserAccountService.updateUserAccount(currentUserAccount); return new ResponseEntity<Void>(HttpStatus.OK); } /** * Update password. * * @param userAccountChangePasswordResource the user account change password resource * @return the response entity * @throws BusinessException the business exception */ @RequestMapping(value = "/changepassword", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<Void> updatePassword( @RequestBody final UserAccountChangePasswordResource userAccountChangePasswordResource) throws BusinessException { blueSpaceTechUserAccountService.changePasswordUserAccount(userAccountChangePasswordResource.getOldPassword(), userAccountChangePasswordResource.getNewPassword(), userAccountChangePasswordResource.getConfirmPassword()); return new ResponseEntity<Void>(HttpStatus.OK); } /** * Delete. * * @param id the id * @return the response entity */ @ResponseStatus(HttpStatus.NO_CONTENT) @RequestMapping(value = "/{id}", method = RequestMethod.DELETE) public ResponseEntity<Void> delete(@PathVariable final Long id) { System.out.println("deleting user account with id "+id); blueSpaceTechUserAccountService.deleteUserAccount(id); return new ResponseEntity<Void>(HttpStatus.OK); } /** * Handle user account not found exception. * * @param e the e * @return the response entity */ @ExceptionHandler(UserAccountDoesNotExistException.class) ResponseEntity<String> handleUserAccountNotFoundException(final Exception e) { return new ResponseEntity<String>(String.format("{\"reason\":\"%s\"}", e.getMessage()), HttpStatus.NOT_FOUND); } }
true
9c99809836af16fef440d4757c0b0d54e33dce11
Java
kaviya0408/Genie
/src/main/java/genie/framework/rules/dataobject/results/MessageType.java
UTF-8
103
1.6875
2
[]
no_license
package genie.framework.rules.dataobject.results; public enum MessageType { INFO,WARNING,ERROR; }
true
361e31487a6a418947bab1855b86479aac56c59b
Java
lfijas/BIP_project
/BipApp/src/com/example/bipapp/CustomRenderer.java
UTF-8
413
2.28125
2
[]
no_license
package com.example.bipapp; import android.graphics.Paint; import org.afree.chart.renderer.category.BarRenderer; public class CustomRenderer extends BarRenderer { private Paint[] colors; public CustomRenderer(final Paint[] colors) { this.colors = colors; } public Paint getItemPaint(final int row, final int column) { return this.colors[column % this.colors.length]; } }
true
28ddd77a644fb460122058ee289330abede45428
Java
chunjiangshieh/android-library-tools
/src/com/xcj/android/util/DeviceHelper.java
UTF-8
7,229
2.0625
2
[]
no_license
package com.xcj.android.util; import java.util.List; import android.app.Service; import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.Build; import android.os.Vibrator; import android.provider.Settings.Secure; import android.telephony.NeighboringCellInfo; import android.telephony.TelephonyManager; /** * @author hljdrl@gmail.com * */ public class DeviceHelper { public String UA = Build.MODEL; private String mIMEI; private String mSIM; private String mMobileVersion; private String mNetwrokIso; private String mNetType; private String mDeviceID; private List<NeighboringCellInfo> mCellinfos; Context mContext; //----------------------------------------------------------- private static DeviceHelper INSTANCE = null; public static synchronized DeviceHelper getInstance(Context context) { if (INSTANCE == null) { INSTANCE = new DeviceHelper(context); } return INSTANCE; } /** * * */ public DeviceHelper(Context context) { mContext = context; findData(); } /** * * 设置手机立刻震动 * */ public void Vibrate(Context context, long milliseconds) { Vibrator vib = (Vibrator) context .getSystemService(Service.VIBRATOR_SERVICE); vib.vibrate(milliseconds); } TelephonyManager mTm = null; private void findData() { mTm = (TelephonyManager) mContext .getSystemService(Context.TELEPHONY_SERVICE); mIMEI = mTm.getDeviceId(); mMobileVersion = mTm.getDeviceSoftwareVersion(); mCellinfos = mTm.getNeighboringCellInfo(); mNetwrokIso = mTm.getNetworkCountryIso(); mSIM = mTm.getSimSerialNumber(); mDeviceID = getDeviceId(); // try { ConnectivityManager cm = (ConnectivityManager) mContext .getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo info = cm.getActiveNetworkInfo(); // WIFI/MOBILE mNetType = info.getTypeName(); } catch (Exception ex) { ex.printStackTrace(); } } public void onRefresh() { findData(); } /** * 获得android设备-唯一标识,android2.2 之前无法稳定运行. * */ public static String getDeviceId(Context mCm) { return Secure.getString(mCm.getContentResolver(), Secure.ANDROID_ID); } private String getDeviceId() { return Secure.getString(mContext.getContentResolver(), Secure.ANDROID_ID); } public String getImei() { return mIMEI; } public String getSIM() { return mSIM; } public String getUA() { return UA; } public String getDeviceInfo() { StringBuffer info = new StringBuffer(); info.append("IMEI:").append(getImei()); info.append("\n"); info.append("SIM:").append(getSIM()); info.append("\n"); info.append("UA:").append(getUA()); info.append("\n"); info.append("MobileVersion:").append(mMobileVersion); info.append("\n"); info.append("SDK: ").append(android.os.Build.VERSION.SDK); info.append("\n"); info.append(getCallState()); info.append("\n"); info.append("SIM_STATE: ").append(getSimState()); info.append("\n"); info.append("SIM: ").append(getSIM()); info.append("\n"); info.append(getSimOpertorName()); info.append("\n"); info.append(getPhoneType()); info.append("\n"); info.append(getPhoneSettings()); info.append("\n"); return info.toString(); } public String getSimState() { switch (mTm.getSimState()) { case android.telephony.TelephonyManager.SIM_STATE_UNKNOWN: return "未知SIM状态_" + android.telephony.TelephonyManager.SIM_STATE_UNKNOWN; case android.telephony.TelephonyManager.SIM_STATE_ABSENT: return "没插SIM卡_" + android.telephony.TelephonyManager.SIM_STATE_ABSENT; case android.telephony.TelephonyManager.SIM_STATE_PIN_REQUIRED: return "锁定SIM状态_需要用户的PIN码解锁_" + android.telephony.TelephonyManager.SIM_STATE_PIN_REQUIRED; case android.telephony.TelephonyManager.SIM_STATE_PUK_REQUIRED: return "锁定SIM状态_需要用户的PUK码解锁_" + android.telephony.TelephonyManager.SIM_STATE_PUK_REQUIRED; case android.telephony.TelephonyManager.SIM_STATE_NETWORK_LOCKED: return "锁定SIM状态_需要网络的PIN码解锁_" + android.telephony.TelephonyManager.SIM_STATE_NETWORK_LOCKED; case android.telephony.TelephonyManager.SIM_STATE_READY: return "就绪SIM状态_" + android.telephony.TelephonyManager.SIM_STATE_READY; default: return "未知SIM状态_" + android.telephony.TelephonyManager.SIM_STATE_UNKNOWN; } } public String getPhoneType() { switch (mTm.getPhoneType()) { case android.telephony.TelephonyManager.PHONE_TYPE_NONE: return "PhoneType: 无信号_" + android.telephony.TelephonyManager.PHONE_TYPE_NONE; case android.telephony.TelephonyManager.PHONE_TYPE_GSM: return "PhoneType: GSM信号_" + android.telephony.TelephonyManager.PHONE_TYPE_GSM; case android.telephony.TelephonyManager.PHONE_TYPE_CDMA: return "PhoneType: CDMA信号_" + android.telephony.TelephonyManager.PHONE_TYPE_CDMA; default: return "PhoneType: 无信号_" + android.telephony.TelephonyManager.PHONE_TYPE_NONE; } } /** * 服务商名称:例如:中国移动、联通    SIM卡的状态必须是 SIM_STATE_READY(使用getSimState()判断).    */ public String getSimOpertorName() { if (mTm.getSimState() == android.telephony.TelephonyManager.SIM_STATE_READY) { StringBuffer sb = new StringBuffer(); sb.append("SimOperatorName: ").append(mTm.getSimOperatorName()); sb.append("\n"); sb.append("SimOperator: ").append(mTm.getSimOperator()); sb.append("\n"); sb.append("Phone:").append(mTm.getLine1Number()); return sb.toString(); } else { StringBuffer sb = new StringBuffer(); sb.append("SimOperatorName: ").append("未知"); sb.append("\n"); sb.append("SimOperator: ").append("未知"); return sb.toString(); } } public String getPhoneSettings() { StringBuffer buf = new StringBuffer(); String str = Secure.getString(mContext.getContentResolver(), Secure.BLUETOOTH_ON); buf.append("蓝牙:"); if (str.equals("0")) { buf.append("禁用"); } else { buf.append("开启"); } // str = Secure.getString(mContext.getContentResolver(), Secure.BLUETOOTH_ON); buf.append("WIFI:"); buf.append(str); str = Secure.getString(mContext.getContentResolver(), Secure.INSTALL_NON_MARKET_APPS); buf.append("APP位置来源:"); buf.append(str); return buf.toString(); } public String getCallState() { switch (mTm.getCallState()) { case android.telephony.TelephonyManager.CALL_STATE_IDLE: return "电话状态[CallState]: 无活动"; case android.telephony.TelephonyManager.CALL_STATE_OFFHOOK: return "电话状态[CallState]: 无活动"; case android.telephony.TelephonyManager.CALL_STATE_RINGING: return "电话状态[CallState]: 无活动"; default: return "电话状态[CallState]: 未知"; } } public String getNetwrokIso() { return mNetwrokIso; } /** * @return the mDeviceID */ public String getDeviceID() { return mDeviceID; } /** * @return the mNetType */ public String getNetType() { return mNetType; } /** * @return the mCellinfos */ public List<NeighboringCellInfo> getCellinfos() { return mCellinfos; } }
true
2ae8e4c1d5417710f7810ffdf8c2e5bb6700c774
Java
zhzhxxyy/shipin
/Android原生/shipin/app/src/main/java/com/duomizhibo/phonelive/ui/dialog/LiveCommon.java
UTF-8
7,757
2.0625
2
[]
no_license
package com.duomizhibo.phonelive.ui.dialog; import android.app.Dialog; import android.content.Context; import android.text.Spannable; import android.text.SpannableStringBuilder; import android.text.style.ForegroundColorSpan; import android.view.View; import android.widget.TextView; import com.duomizhibo.phonelive.R; import com.duomizhibo.phonelive.interf.DialogInterface; import com.duomizhibo.phonelive.widget.AvatarView; /** * UI公共类 */ public class LiveCommon { public static void showInputContentDialog(Context context, String title, final DialogInterface dialogInterface) { final Dialog dialog = new Dialog(context, R.style.dialog); dialog.setContentView(R.layout.dialog_set_room_pass); dialog.setCanceledOnTouchOutside(false); dialog.setCancelable(false); dialog.show(); ((TextView) dialog.findViewById(R.id.tv_title)).setText(title); dialog.findViewById(R.id.btn_cancel).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { dialogInterface.cancelDialog(view, dialog); } }); dialog.findViewById(R.id.btn_confirm).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { dialogInterface.determineDialog(view, dialog); } }); } public static void showIRtcDialog(Context context, String title, String content, final DialogInterface dialogInterface) { final Dialog dialog = new Dialog(context, R.style.dialog); dialog.setContentView(R.layout.dialog_show_rtcmsg); dialog.setCanceledOnTouchOutside(false); dialog.setCancelable(false); dialog.show(); ((TextView) dialog.findViewById(R.id.tv_title)).setText(title); dialog.findViewById(R.id.btn_cancel).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { dialogInterface.cancelDialog(view, dialog); } }); TextView textView = (TextView) dialog.findViewById(R.id.et_input); textView.setText(content); dialog.findViewById(R.id.btn_confirm).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { dialogInterface.determineDialog(view, dialog); } }); } public static void showMainTainDialog(Context context, String content) { final Dialog dialog = new Dialog(context, R.style.dialog); dialog.setContentView(R.layout.dialog_maintain); dialog.setCanceledOnTouchOutside(false); dialog.setCancelable(false); dialog.show(); ((TextView) dialog.findViewById(R.id.tv_content)).setText(content); dialog.findViewById(R.id.btn_confirm).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { dialog.dismiss(); } }); } public static Dialog loadingDialog(Context context) { final Dialog dialog = new Dialog(context, R.style.loading_dialog); dialog.setContentView(R.layout.dialog_loading); dialog.setCanceledOnTouchOutside(false); dialog.setCancelable(false); return dialog; } public static Dialog noMoneyDialog(String msg, Context context, final DialogInterface dialogInterface) { final Dialog dialog = new Dialog(context, R.style.loading_dialog); dialog.setContentView(R.layout.dialog_no_money); ( (TextView)dialog.findViewById(R.id.tv_content)).setText(msg); dialog.findViewById(R.id.tv_confirm).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dialogInterface.determineDialog(v,dialog); } }); dialog.setCanceledOnTouchOutside(false); dialog.setCancelable(false); return dialog; } //私播弹窗 public static void showPersonDialog(Context context, String type,String type2,String content,String content2,String cancel,String confrim,final DialogInterface dialogInterface) { final Dialog dialog = new Dialog(context, R.style.dialog); dialog.setContentView(R.layout.dialog_person); dialog.setCanceledOnTouchOutside(false); dialog.show(); TextView tv_content=((TextView) dialog.findViewById(R.id.tv_content)); TextView tv_content2=((TextView) dialog.findViewById(R.id.tv_content2)); TextView tv_cancel=((TextView) dialog.findViewById(R.id.tv_cancel)); TextView tv_confirm=((TextView) dialog.findViewById(R.id.tv_confirm)); View line=dialog.findViewById(R.id.line); if (type.equals("1")){ tv_confirm.setVisibility(View.GONE); line.setVisibility(View.GONE); } if (type2.equals("1")) { tv_content2.setVisibility(View.GONE); } tv_content.setText(content); tv_content2.setText(content2); tv_cancel.setText(cancel); tv_confirm.setText(confrim); // tv_content.postDelayed(new Runnable() { // @Override // public void run() { // // } // }) setTVColor(content2,"钟",context.getResources().getColor(R.color.global2),tv_content2); tv_cancel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { dialogInterface.cancelDialog(view,dialog); } }); tv_confirm.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { dialogInterface.determineDialog(view,dialog); } }); } //私播连麦主播弹窗 public static Dialog showPersonLianMaiDialog(Context context, String head, String name, final DialogInterface dialogInterface) { final Dialog dialog = new Dialog(context, R.style.dialog_no_background); dialog.setContentView(R.layout.dialog_acceptlianmai); dialog.setCanceledOnTouchOutside(false); dialog.show(); TextView tv_cancel=((TextView) dialog.findViewById(R.id.tv_cancel)); TextView tv_confirm=((TextView) dialog.findViewById(R.id.tv_confirm)); TextView tv_name=((TextView) dialog.findViewById(R.id.tv_name)); AvatarView av_head=((AvatarView) dialog.findViewById(R.id.av_head)); av_head.setAvatarUrl(head); tv_name.setText(name); tv_cancel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { dialogInterface.cancelDialog(view,dialog); } }); tv_confirm.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { dialogInterface.determineDialog(view,dialog); } }); return dialog; } private static void setTVColor(String str , String ch2 , int color , TextView tv){ int a =0; //从字符ch1的下标开始 int b = str.indexOf(ch2)+1; //到字符ch2的下标+1结束,因为SpannableStringBuilder的setSpan方法中区间为[ a,b )左闭右开 SpannableStringBuilder builder = new SpannableStringBuilder(str); builder.setSpan(new ForegroundColorSpan(color), a, b, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); tv.setText(builder); } }
true
f467ba7d5a72c5ed9075a3bf99290634dacc80e7
Java
MiketheViking90/LeetCode
/src/designpatterns/adapter/Chicken.java
UTF-8
99
2.453125
2
[]
no_license
package designpatterns.adapter; public interface Chicken { void cluck(); void fly(); }
true
9fdb2b8b01f77bc4ed2da79375b6393513f024a5
Java
dearcode2018/jdk-entire
/jdk8/src/main/java/com/hua/jdk/Good.java
UTF-8
241
1.625
2
[]
no_license
/** * @filename Good.java * @description * @version 1.0 * @author qianye.zheng */ package com.hua.jdk; /** * @type Good * @description * @author qianye.zheng */ public class Good extends Foo implements DefaultMethod { }
true
c3726aea4ac0273c045210e829e4e5e8889b1122
Java
wolong625/myshop
/myshop-module/src/test/java/com/lang/myshop/module/user/mapper/UserMapperTest.java
UTF-8
1,139
2.125
2
[]
no_license
package com.lang.myshop.module.user.mapper; import com.lang.myshop.module.user.entity.TbUser; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import java.util.Date; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration({"classpath:spring-context.xml"}) public class UserMapperTest { @Autowired private TbUserMapper tbUserMapper; @Test public void testInsert(){ TbUser tbUser = new TbUser(); tbUser.setId(4L); tbUser.setUsername("root"); tbUser.setPassword("root"); tbUser.setEmail("admin@admin.com"); tbUser.setPhone("139999999999"); tbUser.setCreated(new Date()); tbUser.setUpdated(new Date()); tbUserMapper.insert(tbUser); } @Test public void testSelect(){ TbUser tbUser = tbUserMapper.selectByPrimaryKey(1L); System.out.println("username="+tbUser.getUsername()); } }
true
188f6d28d32c036ba0d891a63d83ac93d5096ab8
Java
jess232017/Tu-Finca
/app/src/main/java/com/example/tufinca2/Registro_Activity.java
UTF-8
5,983
2.25
2
[]
no_license
package com.example.tufinca2; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import android.annotation.SuppressLint; import android.content.Intent; import android.database.Cursor; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.aminography.choosephotohelper.ChoosePhotoHelper; import com.aminography.choosephotohelper.callback.ChoosePhotoCallback; import com.bumptech.glide.Glide; import com.example.tufinca2.Sqlite.BDAdapter; import com.google.android.material.appbar.AppBarLayout; import java.util.Objects; public class Registro_Activity extends AppCompatActivity { private String PassTrought = ""; private TextView txtName, txtUser, txtPass; private String Name, Mail, Pass; private ChoosePhotoHelper choosePhotoHelper; private ImageView imageView; String Image; @SuppressLint("SetTextI18n") @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_registro); Toolbar toolbar = findViewById(R.id.toolbar); toolbar.setTitle("Actualizar Datos"); setSupportActionBar(toolbar); Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true); if (getIntent().hasExtra("PassTrought")){ PassTrought = getIntent().getStringExtra("PassTrought"); TextView textView = findViewById(R.id.information); TextView Button = findViewById(R.id.ingresar); AppBarLayout appBarLayout = findViewById(R.id.appBar); appBarLayout.setVisibility(View.VISIBLE); textView.setText("Actualizar Registro"); Button.setText("Actualizar"); } imageView = findViewById(R.id.CargarImagen); choosePhotoHelper = ChoosePhotoHelper.with(Registro_Activity.this) .asFilePath() .build(new ChoosePhotoCallback<String>() { @Override public void onChoose(String photo) { Glide.with(Registro_Activity.this) .load(photo) .into(imageView); Image = photo; } }); BDAdapter db = new BDAdapter(this); db.openDB(); try { Cursor c = db.obtenerUsuario(); if(c.moveToNext()){ Name = c.getString(2); Mail = c.getString(3); Pass = c.getString(4); } db.closeDB(); } catch (Exception e) { Log.e("Error", Objects.requireNonNull(e.getMessage())); } txtName = findViewById(R.id.Name); txtUser = findViewById(R.id.User); txtPass = findViewById(R.id.password); if((Name.equals("Default") && Mail.equals("Default") && Pass.equals("Default"))){ }else{ if(PassTrought.equals("")){ //Intent intent = new Intent(this, Login_Activity.class); Intent intent = new Intent(this, RFinca_Activity.class); startActivity(intent); }else{ txtName.setText(Name); txtUser.setText(Mail); txtPass.setText(Pass); } } } public void Guardar(View view) { String strUser = Objects.requireNonNull(txtName.getText()).toString().trim(); String strMail = Objects.requireNonNull(txtUser.getText()).toString().trim(); String strPassword = Objects.requireNonNull(txtPass.getText()).toString().trim(); try { if (strUser.isEmpty() || strMail.isEmpty() || strPassword.isEmpty()) { Toast.makeText(this, "Rellene todos los campos", Toast.LENGTH_SHORT).show(); } else{ BDAdapter db = new BDAdapter(this); db.openDB(); db.actualizarUsuario(strMail,strUser,strPassword); db.closeDB(); Toast.makeText(this, "Los datos han sido actualizados", Toast.LENGTH_SHORT).show(); assert PassTrought != null; if(PassTrought.equals("")){ Intent intent = new Intent(this, RFinca_Activity.class); startActivity(intent); }else{ Intent intent = new Intent(this, Dashboard_Activity.class); startActivity(intent); } } }catch (Exception e) { Log.e("Error", Objects.requireNonNull(e.getMessage())); } } public void cargar(View view) { choosePhotoHelper.showChooser(); } @Override protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { super.onActivityResult(requestCode, resultCode, data); choosePhotoHelper.onActivityResult(requestCode, resultCode, data); } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); choosePhotoHelper.onRequestPermissionsResult(requestCode, permissions, grantResults); } private void showToolbar(String tittle, View view){ Toolbar toolbar = view.findViewById(R.id.toolbar); Objects.requireNonNull(this).setSupportActionBar(toolbar); Objects.requireNonNull(this.getSupportActionBar()).setTitle(tittle); Objects.requireNonNull(this.getSupportActionBar()).setDisplayHomeAsUpEnabled(true); } @Override public boolean onSupportNavigateUp() { onBackPressed(); return true; } }
true
51cbe6ad46cf4fb0c46caf35827a21aa2e8be76f
Java
1996sayan/movie-booking-app
/UserService/src/main/java/com/movie/user/exception/UserNameAlreadyExistException.java
UTF-8
632
2.140625
2
[]
no_license
package com.movie.user.exception; public class UserNameAlreadyExistException extends UserRegistractionException { /** * serialVersionUID */ private static final long serialVersionUID = 1L; public UserNameAlreadyExistException() { super(); } public UserNameAlreadyExistException(String arg0, Throwable arg1, boolean arg2, boolean arg3) { super(arg0, arg1, arg2, arg3); } public UserNameAlreadyExistException(String arg0, Throwable arg1) { super(arg0, arg1); } public UserNameAlreadyExistException(String arg0) { super(arg0); } public UserNameAlreadyExistException(Throwable arg0) { super(arg0); } }
true
caee83ab5632350811dc091f7c072384253397e8
Java
attrideepak/DS-Algo
/algos/src/javaproblems/FindMissingNumberInArray.java
UTF-8
1,277
4
4
[]
no_license
package javaproblems; import java.util.BitSet; /*You are given a list of n-1 integers and these integers are in the range of 1 to n. There are no duplicates in list. One of the integers is missing in the list. Write an efficient code to find the missing integer.*/ public class FindMissingNumberInArray { static int missingNumber(int[] arr) { int n = arr.length; int sum = (n+1)*(n+2)/2; //added 1 becoz one element is missing int arraySum = 0; for(int i =0; i<n;i++) { arraySum += arr[i]; } int miss = sum-arraySum; return miss; } //using bitset we can find n missing elements but the list should start from 1. static void printMissingNumber(int[] numbers, int count) { int missingCount = count - numbers.length; BitSet bitSet = new BitSet(count); for (int number : numbers) { bitSet.set(number-1); } int lastMissingIndex = 0; for(int i = 0;i<missingCount;i++) { lastMissingIndex = bitSet.nextClearBit(lastMissingIndex); System.out.println(++lastMissingIndex); } //System.out.println(bitSet.cardinality()); } public static void main(String[] args) { int[] array = {3,4,5,7,8}; //int[] array = {102,103,104,105,107,108}; //System.out.println(missingNumber(array)); printMissingNumber(array, 9); } }
true
ea0580c9b1efe890db5d162fc547f1c8a8b362a2
Java
kalibai/test
/src/com/MY/test/TestMybatisDeleteBatch.java
UTF-8
552
1.992188
2
[]
no_license
package com.MY.test; import org.apache.ibatis.session.SqlSession; import org.apache.log4j.Logger; import com.MY.mapper.StudentMapper; import com.MY.utils.SqlSessionFactoryUtils; public class TestMybatisDeleteBatch { public static void main(String[] args) { Logger logger = Logger.getLogger(TestMybatisDeleteBatch.class); SqlSession session = SqlSessionFactoryUtils.getSqlSession(); StudentMapper mapper = session.getMapper(StudentMapper.class); int [] ids = {11,12,15}; mapper.deleteBatch(ids); session.commit(); } }
true
5616ae698e74ac23127219c4bc82177fe809c6ad
Java
vyvydkf628/FOUNDERS_3rd
/Submission/17_대가리/Brain/app/src/main/java/com/example/brain/SimpleData.java
UTF-8
362
2.6875
3
[]
no_license
package com.example.brain; public class SimpleData { private String name; private String sketches; public SimpleData(String name, String sketches) { this.name = name; this.sketches = sketches; } public String getName(){ return this.name; } public String getSketches() { return this.sketches; } }
true
9f0ecb51dab7394bb306c526559d5b25b5a02156
Java
aeuan/BBE2101.aliados.android
/app/src/main/java/com/dacodes/bepensa/adapters/OpportunitiesAdapter.java
UTF-8
5,587
2.359375
2
[]
no_license
package com.dacodes.bepensa.adapters; import android.app.Activity; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.constraintlayout.widget.ConstraintLayout; import androidx.recyclerview.widget.RecyclerView; import com.dacodes.bepensa.R; import com.dacodes.bepensa.entities.OpportunityType; import com.dacodes.bepensa.entities.PackegeOpportunity.DivisionEntity; import java.util.ArrayList; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; public class OpportunitiesAdapter extends RecyclerView.Adapter<OpportunitiesAdapter.ViewHolder> { private Context context; private Activity activity; private List<DivisionEntity> divisions = new ArrayList<>(); private List<OpportunityType> oportunities = new ArrayList<>(); private OpportunitiesAdapter.AddDivisionType addDivisionType; private AddOpportunityType addOpportunityType; private int type;//1 Division 2 Opportunity public OpportunitiesAdapter(Context context, Activity activity, List<DivisionEntity> divisions, OpportunitiesAdapter.AddDivisionType addDivisionType) { this.context = context; this.activity = activity; this.divisions = divisions; this.addDivisionType = addDivisionType; type = 1; } public OpportunitiesAdapter(Context context, Activity activity, List<OpportunityType> opportunities, AddOpportunityType addOpportunityType) { this.context = context; this.activity = activity; this.oportunities = opportunities; this.addOpportunityType = addOpportunityType; type = 2; } public interface AddDivisionType{ void onAddDivisionType(DivisionEntity division); } public interface AddOpportunityType{ void onAddOportunityType(OpportunityType opportunity); } @NonNull @Override public OpportunitiesAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { LayoutInflater inflater = LayoutInflater.from(parent.getContext()); View view = inflater.inflate(R.layout.item_division_opportunity, parent, false); return new ViewHolder(view); } @Override public void onBindViewHolder(@NonNull OpportunitiesAdapter.ViewHolder holder, final int position) { switch (type){ case 1: holder.tvDivision.setText(divisions.get(position).getName()); holder.container.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { addDivisionType.onAddDivisionType(divisions.get(position)); /* AlertDialog.Builder builder = new AlertDialog.Builder(activity); builder.setMessage("Se agregará la división"); builder.setPositiveButton("ACEPTAR", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { addDivisionType.onAddDivisionType(divisions.get(position)); } }); builder.setNegativeButton("CANCELAR", null); AlertDialog dialog = builder.create(); dialog.setCancelable(false); dialog.show();*/ } }); break; case 2: holder.tvDivision.setText(oportunities.get(position).getName()); holder.container.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { addOpportunityType.onAddOportunityType(oportunities.get(position)); /* AlertDialog.Builder builder = new AlertDialog.Builder(activity); builder.setMessage("Se agregará la oportunidad"); builder.setPositiveButton("ACEPTAR", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { addOpportunityType.onAddOportunityType(oportunities.get(position)); } }); builder.setNegativeButton("CANCELAR", null); AlertDialog dialog = builder.create(); dialog.setCancelable(false); dialog.show();*/ } }); break; } } @Override public int getItemCount() { int size = 0; switch (type){ case 1: size = divisions.size(); break; case 2: size = oportunities.size(); break; } return size; } public class ViewHolder extends RecyclerView.ViewHolder{ @BindView(R.id.tvDivision) TextView tvDivision; @BindView(R.id.container) ConstraintLayout container; public ViewHolder(View itemView) { super(itemView); ButterKnife.bind(this, itemView); } } }
true
5a71c28d606e44cbf84de969f9b9363205aa0b6d
Java
Herman513/simple-mvc
/web/src/main/java/org/simplemvc/web/bind/annotation/RequestMapping.java
UTF-8
296
1.859375
2
[]
no_license
package org.simplemvc.web.bind.annotation; import java.lang.annotation.*; /** * Created by wuyuhuan on 2017/1/20. * Usage: */ @Target({ElementType.METHOD,ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface RequestMapping { String value() default ""; }
true
24ea680c7ffb4eda35aa88957beea35b3ea7be6b
Java
AntonZhao/LeetCodeTrip
/src/LC332_findItinerary.java
UTF-8
1,865
3.578125
4
[]
no_license
import java.util.*; public class LC332_findItinerary { public List<String> findItinerary(List<List<String>> tickets) { // 因为逆序插入,所以用链表 LinkedList<String> res = new LinkedList<>(); if (tickets == null || tickets.size() == 0) return res; HashMap<String, List<String>> graph = new HashMap<>(); for (List<String> pair : tickets) { // 因为涉及删除操作,我们用链表 List<String> near = graph.computeIfAbsent(pair.get(0), k -> new LinkedList<>()); near.add(pair.get(1)); } graph.values().forEach(k -> k.sort(String::compareTo)); dfs(graph, "JFK", res); return res; } private void dfs(HashMap<String, List<String>> graph, String FROM, LinkedList<String> res) { List<String> near = graph.get(FROM); while (near != null && near.size() > 0) { String TO = near.remove(0); dfs(graph, TO, res); } res.addFirst(FROM); // 逆序插入 } public static void main(String[] args) { LC332_findItinerary ll = new LC332_findItinerary(); ArrayList<String> list1 = new ArrayList<>(); list1.add("MUC"); list1.add("LHR"); ArrayList<String> list2 = new ArrayList<>(); list2.add("JFK"); list2.add("MUC"); ArrayList<String> list3 = new ArrayList<>(); list3.add("SFO"); list3.add("SJC"); ArrayList<String> list4 = new ArrayList<>(); list4.add("LHR"); list4.add("SFO"); ArrayList<List<String>> lists = new ArrayList<>(); lists.add(list1); lists.add(list2); lists.add(list3); lists.add(list4); List<String> itinerary = ll.findItinerary(lists); System.out.println(itinerary.toString()); } }
true
cd41ddea7ede571c115087742ff529b50da94900
Java
theDeepanshuMourya/DataStructuresAndAlgorithms
/src/sorts/ShellSort.java
UTF-8
1,474
4.1875
4
[ "MIT" ]
permissive
/* ShellSort is mainly a variation of Insertion Sort. * In insertion sort, we move elements only one position * ahead. When an element has to be moved far ahead, * many movements are involved. The idea of shellSort is * to allow exchange of far items. In shellSort, we make * the array h-sorted for a large value of h. We keep * reducing the value of h until it becomes 1. An array * is said to be h-sorted if all sublists of every h’th * element is sorted. * * Time complexity of above implementation of shellsort is O(n^2). */ package DataStructuresAndAlgorithms.src.sorts; import java.util.Scanner; public class ShellSort { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Enter the no. of elements: "); int n = sc.nextInt(); int[] intArray = new int[n]; System.out.println("Enter the elements:"); for (int i = 0; i < intArray.length; i++) { intArray[i] = sc.nextInt(); } for (int gap = intArray.length /2; gap > 0; gap /= 2) { for (int i = gap; i < intArray.length; i++) { int newElement = intArray[i]; int j = i; while (j >= gap && intArray[j-gap] > newElement) { intArray[j] = intArray[j-gap]; j -= gap; } intArray[j] = newElement; } } System.out.println("The Sorted Array is:"); for (int i = 0; i < intArray.length; i++) { System.out.println(intArray[i]); } sc.close(); } }
true
eb26a532b7495be8306cd2c4ad612c493473837f
Java
MilitaryIntelligence6/DbStudyDemo
/src/main/java/cn/misection/dbstudy/entity/StudentPay.java
UTF-8
692
2.203125
2
[]
no_license
package cn.misection.dbstudy.entity; public class StudentPay { private String sno; private String stype; private String time; private int amount; public String getSno() { return sno; } public void setSno(String sno) { this.sno = sno; } public String getStype() { return stype; } public void setStype(String stype) { this.stype = stype; } public String getTime() { return time; } public void setTime(String time) { this.time = time; } public int getAmount() { return amount; } public void setAmount(int amount) { this.amount = amount; } }
true
d11a62d85b7c729f994345572b70ec91195b84f5
Java
equinor/neqsim
/src/test/java/neqsim/thermo/util/example/TestVHflash.java
UTF-8
4,640
2.609375
3
[ "Apache-2.0" ]
permissive
package neqsim.thermo.util.example; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import neqsim.thermo.system.SystemInterface; import neqsim.thermo.system.SystemSrkEos; import neqsim.thermodynamicOperations.ThermodynamicOperations; /** * <p> * TestVHflash class. * </p> * * @author esol * @version $Id: $Id * @since 2.2.3 */ public class TestVHflash { static Logger logger = LogManager.getLogger(TestVHflash.class); /** * <p> * main. * </p> * * @param args an array of {@link java.lang.String} objects */ public static void main(String args[]) { double pressureInTank = 1.01325; // Pa double temperatureInTank = 293.15; double totalMolesInTank = 136000 * pressureInTank * 1.0e5 / 8.314 / temperatureInTank; double molefractionNitrogenInTank = 0.95; double molesInjectedLNG = 200000.0; double molesInjecedVacumBreakerGas = 18 * pressureInTank * 1.0e5 / 8.314 / temperatureInTank; SystemInterface testSystem = new SystemSrkEos(temperatureInTank, pressureInTank); ThermodynamicOperations testOps = new ThermodynamicOperations(testSystem); testSystem.addComponent("methane", totalMolesInTank * (1.0 - molefractionNitrogenInTank)); testSystem.addComponent("nitrogen", totalMolesInTank * molefractionNitrogenInTank); testSystem.createDatabase(true); testSystem.setMixingRule(2); SystemInterface testSystem2 = new SystemSrkEos(273.15 - 165.0, pressureInTank); ThermodynamicOperations testOps2 = new ThermodynamicOperations(testSystem2); testSystem2.addComponent("methane", molesInjectedLNG); testSystem2.createDatabase(true); testSystem2.setMixingRule(2); SystemInterface testSystem3 = new SystemSrkEos(temperatureInTank, pressureInTank); ThermodynamicOperations testOps3 = new ThermodynamicOperations(testSystem3); testSystem3.addComponent("methane", totalMolesInTank * (1.0 - molefractionNitrogenInTank) + molesInjectedLNG); testSystem3.addComponent("nitrogen", totalMolesInTank * molefractionNitrogenInTank); testSystem3.createDatabase(true); testSystem3.setMixingRule(2); SystemInterface testSystem4 = new SystemSrkEos(temperatureInTank, pressureInTank); ThermodynamicOperations testOps4 = new ThermodynamicOperations(testSystem4); testSystem4.addComponent("nitrogen", molesInjecedVacumBreakerGas); testSystem4.createDatabase(true); testSystem4.setMixingRule(2); try { testOps.TPflash(); testOps2.TPflash(); testOps3.TPflash(); testOps4.TPflash(); testSystem.display(); testSystem2.display(); testSystem3.display(); testSystem4.display(); // logger.info("Cp " + // testSystem.getPhase(0).getCp()/testSystem.getPhase(0).getNumberOfMolesInPhase()); logger.info( "Volume Nitrogen " + testSystem.getPhase(0).getMolarMass() * testSystem.getNumberOfMoles() / testSystem.getPhase(0).getPhysicalProperties().getDensity()); logger.info("Volume Liquid Methane " + testSystem2.getPhase(0).getMolarMass() * testSystem2.getNumberOfMoles() / testSystem2.getPhase(0).getPhysicalProperties().getDensity()); logger.info("Volume Nitrogen from vacum breaker system " + testSystem4.getPhase(0).getMolarMass() * testSystem4.getNumberOfMoles() / testSystem4.getPhase(0).getPhysicalProperties().getDensity()); testOps3.VHflash(testSystem.getVolume(), testSystem.getEnthalpy() + testSystem2.getEnthalpy()); testSystem3.display(); // logger.info("total number of moles " + testSystem3.getTotalNumberOfMoles() ); } catch (Exception ex) { logger.error(ex.getMessage(), ex); } // logger.info("JT " + testSystem.getPhase(0).getJouleThomsonCoefficient()); // logger.info("wt%MEG " + // testSystem.getPhase(1).getComponent("MEG").getMolarMass()*testSystem.getPhase(1).getComponent("MEG").getx()/testSystem.getPhase(1).getMolarMass()); // logger.info("fug" // +testSystem.getPhase(0).getComponent("water").getx()*testSystem.getPhase(0).getPressure()*testSystem.getPhase(0).getComponent(0).getFugacityCoefficient()); } } // testSystem = testSystem.setModel("GERG-water"); // testSystem.setMixingRule(8); // testSystem = testSystem.autoSelectModel(); // testSystem.autoSelectMixingRule(); // testSystem.setMultiPhaseCheck(true); // testOps.setSystem(testSystem); // logger.info("new model name " + testSystem.getModelName()); // try{ // testOps.TPflash(); // testSystem.display(); // } // catch(Exception ex){ // logger.info(ex.toString()); // } // } // }
true
9b14fe081eba8683c65bbb70626115ec863aa3de
Java
huangleisir/Chat
/chat-server/src/main/java/cn/sinjinsong/chat/server/property/PromptMsgProperty.java
UTF-8
930
2.328125
2
[]
no_license
package cn.sinjinsong.chat.server.property; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; /** * Created by SinjinSong on 2017/5/24. */ public class PromptMsgProperty { public static final String LOGIN_SUCCESS = "登录成功,当前共有%d位在线用户"; public static final String LOGIN_FAILURE = "用户名或密码错误或重复登录,登录失败"; public static final String LOGOUT_SUCCESS = "注销成功"; public static final String RECEIVER_LOGGED_OFF = "接收者不存在或已下线"; public static final String TASK_FAILURE = "任务执行失败,请重试"; public static final String LOGIN_BROADCAST = "%s用户已上线"; public static final String LOGOUT_BROADCAST = "%s用户已下线"; public static final String SERVER_ERROR = "服务器内部出现错误,请重试"; public static final Charset charset = StandardCharsets.UTF_8; }
true
d23d699f3062fbaf26ffbd4f6276289987e6d314
Java
Privod123/Home-Works
/src/lesson16/zadacha1/ReadConsole.java
UTF-8
2,515
3.28125
3
[]
no_license
package lesson16.zadacha1; import java.io.File; import java.io.IOException; import java.util.Scanner; /** * Created by Hello on 01.12.2018. */ public class ReadConsole { int startLimit; int finishLimit; String inputNameFile; String outputNameFile; String outputNameDir; public void readConsol(){ try (Scanner in = new Scanner(System.in)) { while (true) { System.out.println("Введите колличество символов содержащихся в слове , например 4-6 :"); String diapazon = in.nextLine(); String[] limitDiapazon = diapazon.split("-"); try { startLimit = Integer.parseInt(limitDiapazon[0].trim()); finishLimit = Integer.parseInt(limitDiapazon[1].trim()); } catch (NumberFormatException e) { System.out.println("Диапазон символов был введен не правильно."); continue; } System.out.println("Введите имя файла который читаем, например z.txt"); inputNameFile = in.nextLine(); if (!checkFileTxt(inputNameFile)) continue; System.out.println("Введите диркторию куда записывается файл, например MyFile"); outputNameDir = in.nextLine(); System.out.println("Введите имя файла в который записываем, например y.txt"); outputNameFile = in.nextLine(); break; } } } private boolean checkFileTxt(String file){ if (file.toLowerCase().endsWith(".txt") ){ if (checkFile(file)){ return true; }else { return false; } }else { System.out.println("Введенный файл из которого читаем не является текстовым(не имеет расширение TXT)"); return false; } } private boolean checkFile(String file){ File file1 = new File("src\\lesson16\\TxtFileLesson16\\" + file); if (file1.exists()) return true; else { System.out.println("Данного файла нет по указанному пути."); return false; } } }
true
aa5a5ad63e13e4fb491e843da679ce449fd56a27
Java
nicPorcu/GeometryDash
/src/com/company/Pillar.java
UTF-8
759
3.0625
3
[]
no_license
package com.company; /** * Created by apcsaper3 on 5/10/17. */ public class Pillar { private int x; private int y; private int width; private int height; private int initialX; private int initialY; public Pillar (int x, int y, int w, int h){ this.x = x; initialX=x; this.y = y; initialY=y; width = w; height = h; } public int getX() { return x; } public int getY() { return y; } public int getWidth() { return width; } public int getHeight() {return height;} public void shiftLeft(int spd){ x -= spd; } public void reset() { x=initialX; y= initialY; } }
true
e9d3493ddcca1efd5d113d5689c9fc59c84a5a4f
Java
ChenAmazing/coolweather
/app/src/main/java/com/example/amazing_chen/coolweather/adapter/CityAdapter.java
UTF-8
1,352
2.453125
2
[ "Apache-2.0" ]
permissive
package com.example.amazing_chen.coolweather.adapter; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import com.example.amazing_chen.coolweather.R; import java.util.List; /** * Created by Amazing_Chen on 2018/6/12. */ public class CityAdapter extends RecyclerView.Adapter<CityAdapter.ViewHolder> { private final List<String> mdataList; static class ViewHolder extends RecyclerView.ViewHolder{ private final Button cityName; public ViewHolder(View itemView) { super(itemView); cityName = (Button) itemView.findViewById(R.id.bt_city); } } public CityAdapter(List<String> dataList){ mdataList = dataList; } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.city_item, parent, false); ViewHolder holder = new ViewHolder(view); return holder; } @Override public void onBindViewHolder(ViewHolder holder, int position) { String city = mdataList.get(position); holder.cityName.setText(city); } @Override public int getItemCount() { return mdataList.size(); } }
true
ebb7b19a5cb36a7d11fad7e315db2ebb0c0bf06b
Java
PrakharGupta22/Project
/onlineshopping/src/main/java/com/cg/onlineshopping/controller/ProductController.java
UTF-8
5,098
2.328125
2
[]
no_license
package com.cg.onlineshopping.controller; import java.util.List; import javax.validation.Valid; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.cg.onlineshopping.entities.Product; import com.cg.onlineshopping.exception.ProductAlreadyExistsException; import com.cg.onlineshopping.exception.ProductNotFoundException; import com.cg.onlineshopping.model.CreateProductRequest; import com.cg.onlineshopping.model.ProductDetails; import com.cg.onlineshopping.model.UpdateProductRequest; import com.cg.onlineshopping.service.IProductService; import com.cg.onlineshopping.util.ProductUtil; @Validated @RequestMapping("/products") @RestController public class ProductController { private static final Logger LOGGER = LoggerFactory.getLogger(ProductController.class); @Autowired private IProductService service; @Autowired private ProductUtil productUtil; @PostMapping("/add") public ResponseEntity<ProductDetails> addProduct(@RequestBody @Valid CreateProductRequest requestData) throws ProductAlreadyExistsException { try { Product product = new Product( requestData.getProductName(), requestData.getPrice(), requestData.getColor(), requestData.getDimension(), requestData.getSpecification(), requestData.getManufacturer(), requestData.getQuantity() ,requestData.getCategory()); product = service.addProduct(product); ProductDetails details = productUtil.toDetails(product); return new ResponseEntity<>(details, HttpStatus.OK); } catch (Exception e) { LOGGER.error("unable to add product:{} errorlog: ", requestData.getProductName(), e); return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR); } } @PutMapping("/update") public ResponseEntity<ProductDetails> update(@RequestBody @Valid UpdateProductRequest requestData) throws ProductNotFoundException { try { Product product = new Product( requestData.getProductName(), requestData.getPrice(), requestData.getColor(), requestData.getDimension(), requestData.getSpecification(), requestData.getManufacturer(), requestData.getQuantity() ,requestData.getCategory()); product.setProductId(requestData.getProductId()); product= service.updateProduct(product); ProductDetails details = productUtil.toDetails(product); return new ResponseEntity<>(details, HttpStatus.OK); } catch (Exception e) { LOGGER.error("unable to update product for productId:{} errlog: ", requestData.getProductId(), e); return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR); } } @GetMapping("/get/id/{id}") public ResponseEntity<ProductDetails> viewProduct(@PathVariable("id") Integer productId) throws ProductNotFoundException { try { Product product = service.viewProduct(productId); ProductDetails details = productUtil.toDetails(product); return new ResponseEntity<>(details, HttpStatus.OK); } catch (ProductNotFoundException e) { LOGGER.error("unable to view product for productId:{} errlog", productId, e); return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR); } } @GetMapping("/viewall") public ResponseEntity<List<Product>> viewAllProducts() throws Exception { try { return new ResponseEntity<>(service.viewAllProducts(), HttpStatus.OK); } catch (Exception e) { LOGGER.error("unable to view all the products: ", e); return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR); } } @DeleteMapping("/remove/{productId}") public ResponseEntity<Void> removeProduct(@PathVariable("productId") Integer productId) throws ProductNotFoundException { try { service.removeProduct(productId); return new ResponseEntity<Void>(HttpStatus.OK); } catch (ProductNotFoundException e) { LOGGER.error("unable to delete product for productId:{} errlog", productId, e); return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR); } } @GetMapping("/viewProductByCategory/{catId}") public ResponseEntity<List<ProductDetails>> viewProductsByCategory(@PathVariable("catId") String catId)throws ProductNotFoundException { try { return new ResponseEntity<>(productUtil.toDetails(service.viewProductsByCategory(catId)), HttpStatus.OK); } catch (ProductNotFoundException e) { LOGGER.error("unable to find products with catId:{} errlog", catId, e); return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR); } } }
true
b1df89ff94e8e923b2d1526a107bbfcc0a1d0ddd
Java
TAPATOP/AStarConcept
/src/usecases/swipeblockpuzzle/SwipeBlockStage.java
UTF-8
737
2.765625
3
[]
no_license
package usecases.swipeblockpuzzle; import concept.stage.Stage; public class SwipeBlockStage extends Stage<SwipeBlock> { private String lastDirection; public SwipeBlockStage(SwipeBlock state) { super(state); } public SwipeBlockStage(SwipeBlock state, String lastDirection) { super(state); this.lastDirection = lastDirection; } public SwipeBlockStage(SwipeBlock state, SwipeBlockStage previous, String lastDirection) { super(state, previous); this.lastDirection = lastDirection; } public String getLastDirection() { return lastDirection; } @Override public String toString() { return state.toString() + " " + lastDirection; } }
true
3a88b9902aa2a1ce154606fb80080eca4a84d53d
Java
himym1989/Karel
/src/com/shpp/p2p/cs/lzhukova/assignment3/Assignment3Part2.java
UTF-8
1,517
4.375
4
[]
no_license
package com.shpp.p2p.cs.lzhukova.assignment3; import com.shpp.cs.a.console.TextProgram; /** * This program describes the fun math game - Hailstone Numbers. * Start with any positive integer n. If the current number is even, * divide it by two; else if it is odd, * multiply it by three and add one. * Repeat, while number will become 1. */ public class Assignment3Part2 extends TextProgram { public void run() { int n = readDataFromUser(); printHailstoneNumbers(n); } /** * This method describes getting data from the user * and check, if the number is positive. * * @return n - positive integer, that the user inputs. */ private int readDataFromUser() { int n = readInt("put a positive integer: "); while (n <= 0) { println("This number is not positive."); n = readInt("put a positive integer: "); } return n; } /** * Method describes mathematical actions depending on the fact, * is a number odd or even. * * @param n - number, that changes in the loop. * The loop stops when n==1; */ private void printHailstoneNumbers(int n) { while (n != 1) { if (n % 2 == 0) { println(n + " is even so I take half: " + n / 2); n = n / 2; } else { println(n + " is odd so I make 3n + 1: " + ((n * 3) + 1)); n = (n * 3) + 1; } } } }
true
2c8be2e784df6cb2c71da3033d851b9f9bcb4e58
Java
wulawrence/zcwJDBC-Demo
/src/test/java/com/zipcodewilmington/jdbc/tools/database/PokemonDatabaseTest.java
UTF-8
340
1.851563
2
[]
no_license
package com.zipcodewilmington.jdbc.tools.database; import org.junit.Test; public class PokemonDatabaseTest { @Test public void use() { Database.POKEMON.use(); } @Test public void drop() { Database.POKEMON.drop(); } @Test public void create() { Database.POKEMON.create(); } }
true
ffc1a73580aa1dbd5923b98eaecd7a6f79dfc8ee
Java
ericmedvet/jgea
/io.github.ericmedvet.jgea.problem/src/main/java/io/github/ericmedvet/jgea/problem/booleanfunction/BooleanFunctionFitness.java
UTF-8
2,871
2.40625
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2023 eric * * 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 io.github.ericmedvet.jgea.problem.booleanfunction; import io.github.ericmedvet.jgea.core.fitness.ListCaseBasedFitness; import io.github.ericmedvet.jgea.core.representation.tree.Tree; import io.github.ericmedvet.jgea.core.representation.tree.booleanfunction.Element; import java.util.Arrays; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.function.BiFunction; import java.util.function.Function; /** * @author eric */ public class BooleanFunctionFitness extends ListCaseBasedFitness<List<Tree<Element>>, boolean[], Boolean, Double> { public BooleanFunctionFitness(TargetFunction targetFunction, List<boolean[]> observations) { super(observations, new Error(targetFunction), new ErrorRate()); } public interface TargetFunction extends Function<boolean[], boolean[]> { String[] varNames(); static TargetFunction from(final Function<boolean[], boolean[]> function, final String... varNames) { return new TargetFunction() { @Override public boolean[] apply(boolean[] values) { return function.apply(values); } @Override public String[] varNames() { return varNames; } }; } } private static class Error implements BiFunction<List<Tree<Element>>, boolean[], Boolean> { private final BooleanFunctionFitness.TargetFunction targetFunction; public Error(BooleanFunctionFitness.TargetFunction targetFunction) { this.targetFunction = targetFunction; } @Override public Boolean apply(List<Tree<Element>> solution, boolean[] observation) { Map<String, Boolean> varValues = new LinkedHashMap<>(); for (int i = 0; i < targetFunction.varNames().length; i++) { varValues.put(targetFunction.varNames()[i], observation[i]); } boolean[] computed = BooleanUtils.compute(solution, varValues); return Arrays.equals(computed, targetFunction.apply(observation)); } } private static class ErrorRate implements Function<List<Boolean>, Double> { @Override public Double apply(List<Boolean> vs) { double errors = 0; for (Boolean v : vs) { errors = errors + (v ? 0d : 1d); } return errors / (double) vs.size(); } } }
true
caf8666a342d81477adbe64e17a2949f3a2105b7
Java
WelpImDone/Learning-Java-The-Hard-Way
/ThereAndBackAgian.java
UTF-8
347
2.921875
3
[]
no_license
public class ThereAndBackAgian { public static void main ( String[] args){ System.out.println( "Here."); erebor(); System.out.println( "Back the first time."); erebor(); System.out.println( "Back the second time."); } public static void erebor() { System.out.println( "There."); } }
true