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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
d7b0e9556cbcee0386930933922db07fb7b07d5e | Java | dreamTimor/equi | /EquiSystem_SSH/src/com/action/LabBespeakAction.java | UTF-8 | 3,503 | 2.25 | 2 | [] | no_license | package com.action;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import com.bean.Lab_bespeak;
import com.bean.User;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.service.LabBespeakService;
import com.utils.JsonDateValueProcessorUtil;
@Controller
@Scope("prototype")//每次进来都是一个新实例
public class LabBespeakAction extends ActionSupport implements ModelDriven<Lab_bespeak>{
// 用于转换json数据:变量名与action里的param对应
private JSONObject result = null;
public JSONObject getResult(){
return result;
}
// Service层
@Autowired
public LabBespeakService serviceLab;
// 模型接收前端发出的post数据
public Lab_bespeak bespeak = new Lab_bespeak();
public String rows;// 每页显示的记录数
public String page;// 当前第几页
public String queryData;
@Override
public Lab_bespeak getModel() {
return bespeak;
}
/*----------------------------叶雄峰------------------------------*/
// 页面显示数据
public String getList() throws UnsupportedEncodingException{
User user = (User)ServletActionContext.getRequest().getSession().getAttribute("user");//获取登录用户信息
List<Lab_bespeak> bespeaks;//获取分页后的数据
int total;//获取总数据数
// 如果查询框有值,进入查询功能,否则正常分页
if(queryData!=null){
bespeaks = serviceLab.query(page, rows, queryData, user);
total = serviceLab.getListSize();
}else{
bespeaks = serviceLab.getList(page ,rows, user);
total = serviceLab.getListSize();
}
// 数据放入map
Map<String, Object> map = new HashMap<>();
map.put("total", total);
map.put("rows", bespeaks);
// 使用JsonConfig转换日期数据
JsonConfig jsonConfig = new JsonConfig();
jsonConfig.registerJsonValueProcessor(Date.class, new JsonDateValueProcessorUtil());
// 转换后放入result传给页面
result = JSONObject.fromObject(map, jsonConfig);
return SUCCESS;
}
// 添加:模型驱动获取form数据
public String add(){
// 直接使用对象
serviceLab.add(bespeak);
// 将map转为json返回给页面
// Map<String, Object> map = new HashMap<String, Object>();
// map.put("success", 1);
// result = JSONObject.fromObject(map);
return SUCCESS;
}
// 修改:模型驱动获取form表单信息
public String update(){
serviceLab.update(bespeak);
return SUCCESS;
}
// 页面删除记录
public String delete(){
// 转为HttpServletRequest,使用getParameter获取客户端请求数据
HttpServletRequest request = (HttpServletRequest)ServletActionContext.getRequest();
int id = Integer.parseInt(request.getParameter("id"));
// 传给service调用dao
serviceLab.delete(id);
// 将map转为json返回给页面
Map<String, Object> map = new HashMap<String, Object>();
map.put("success", 1);
result = JSONObject.fromObject(map);
return SUCCESS;
}
}
| true |
8c42d678c3c320d63c103e3c0b30f957299b6d72 | Java | Jinx009/jingan_1.0 | /parking-gateway/src/main/java/com/protops/gateway/service/SensorVoService.java | UTF-8 | 1,541 | 2.015625 | 2 | [] | no_license | package com.protops.gateway.service;
import com.protops.gateway.dao.SensorDao;
import com.protops.gateway.dao.SensorVoDao;
import com.protops.gateway.util.Page;
import com.protops.gateway.vo.ge.SensorVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* Created by fanlin on 16/7/5.
*/
@Service
@Transactional
public class SensorVoService {
@Autowired
SensorVoDao sensorVoDao;
@Autowired
SensorDao sensorDao;
public SensorVo getPreview(Integer id) {
return sensorVoDao.getPreview(id);
}
public void batchUpdate(List<Integer> sensorList, Integer areaId) {
List<Object[]> dataSet = new ArrayList<Object[]>();
for (Integer id : sensorList) {
Object[] obj = new Object[1];
obj[0] = id;
dataSet.add(obj);
}
sensorDao.batchUpdateArea(areaId, dataSet);
}
public Page<SensorVo> pagedList(Page<SensorVo> page, Map<String, String> searchMap) {
if(!searchMap.isEmpty()) {
page.setResult(sensorVoDao.pagedList(page, searchMap).getResult());
page.setTotalCount(sensorVoDao.getTotalCount(searchMap));
} else {
page.setResult(sensorVoDao.pagedList(page).getResult());
page.setTotalCount(sensorVoDao.getTotalCount());
}
return page;
}
}
| true |
a6631a981fb13c048252488e205350d5a6edcd9c | Java | apache/struts | /core/src/test/java/org/apache/struts2/interceptor/CoepInterceptorTest.java | UTF-8 | 3,452 | 1.703125 | 2 | [
"LicenseRef-scancode-free-unknown",
"Apache-2.0"
] | 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.struts2.interceptor;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.mock.MockActionInvocation;
import org.apache.logging.log4j.util.Strings;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.StrutsInternalTestCase;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import java.util.HashMap;
import java.util.Map;
public class CoepInterceptorTest extends StrutsInternalTestCase {
private final CoepInterceptor interceptor = new CoepInterceptor();
private final MockActionInvocation mai = new MockActionInvocation();
private final MockHttpServletRequest request = new MockHttpServletRequest();
private final MockHttpServletResponse response = new MockHttpServletResponse();
private final String COEP_ENFORCING_HEADER = "Cross-Origin-Embedder-Policy";
private final String COEP_REPORT_HEADER = "Cross-Origin-Embedder-Policy-Report-Only";
private final String HEADER_CONTENT = "require-corp";
public void testEnforcingHeader() throws Exception {
interceptor.setEnforcingMode("true");
interceptor.intercept(mai);
String header = response.getHeader(COEP_ENFORCING_HEADER);
assertFalse("COEP enforcing header does not exist", Strings.isEmpty(header));
assertEquals("COEP header value is incorrect", HEADER_CONTENT, header);
}
public void testExemptedPath() throws Exception{
request.setContextPath("/foo");
interceptor.setEnforcingMode("true");
interceptor.intercept(mai);
String header = response.getHeader(COEP_ENFORCING_HEADER);
assertTrue("COEP applied to exempted path", Strings.isEmpty(header));
}
public void testReportingHeader() throws Exception {
interceptor.setEnforcingMode("false");
interceptor.intercept(mai);
String header = response.getHeader(COEP_REPORT_HEADER);
assertFalse("COEP reporting header does not exist", Strings.isEmpty(header));
assertEquals("COEP header value is incorrect", HEADER_CONTENT, header);
}
@Override
protected void setUp() throws Exception {
super.setUp();
container.inject(interceptor);
interceptor.setExemptedPaths("/foo");
ServletActionContext.setRequest(request);
ServletActionContext.setResponse(response);
ActionContext context = ServletActionContext.getActionContext();
Map<String, Object> session = new HashMap<>();
context.withSession(session);
mai.setInvocationContext(context);
}
}
| true |
6afba4af20ce06fee63380b2de3e372a400a5443 | Java | git-9522/play | /sp2p_shha.app/app/controllers/app/AppController.java | UTF-8 | 47,770 | 1.789063 | 2 | [] | no_license | package controllers.app;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import net.sf.json.JSONObject;
import play.Logger;
import com.shove.Convert;
import com.shove.gateway.GeneralRestGateway;
import com.shove.gateway.GeneralRestGatewayInterface;
import common.constants.AppConstants;
import common.constants.ConfConst;
import common.constants.Constants;
import common.enums.InformationMenu;
import common.utils.LoggerUtil;
import common.utils.ResultInfo;
import common.utils.Security;
import controllers.app.Invest.DebtAction;
import controllers.app.Invest.ExpBidAction;
import controllers.app.Invest.InvestAction;
import controllers.app.aboutUs.AboutUsAction;
import controllers.app.aboutUs.AndMoreAction;
import controllers.app.account.AccountAction;
import controllers.app.expGold.ExpGoldAction;
import controllers.app.notice.ActivityCenterAction;
import controllers.app.notice.AreaAction;
import controllers.app.notice.FrequentlyAskedQuestionsAction;
import controllers.app.notice.NoticeAction;
import controllers.app.wealth.IntegralMallAction;
import controllers.app.wealth.MyDealAction;
import controllers.app.wealth.MyExpBidAction;
import controllers.app.wealth.MyFundAction;
import controllers.app.wealth.MyInfoAction;
import controllers.app.wealth.MyReceiveBillAction;
import controllers.app.wealth.MySecurityAction;
import controllers.app.wealth.RechargeAWithdrawalAction;
import controllers.common.BaseController;
import models.common.entity.t_advertisement.Location;
public class AppController extends BaseController implements GeneralRestGatewayInterface{
/**
* app端请求服务器入口
*
* @throws IOException
*
* @author yaoyi
* @createDate 2016年3月30日
*/
public static void index() throws IOException{
StringBuilder errorDescription = new StringBuilder();
AppController app = new AppController();
int code =GeneralRestGateway.handle(ConfConst.ENCRYPTION_APP_KEY_MD5, 3000, app, errorDescription);
if(code < 0) {
Logger.error("%s", errorDescription);
}
}
/**
* 扫描二维码下载
*
* @author yaoyi
* @createDate 2016年3月30日
*/
public static void download(){
render();
}
/**
* ios微信扫码下载提示页面
*
* @author huangyunsong
* @createDate 2016年5月17日
*/
public static void iosTip(String path){
render(path);
}
@Override
public String delegateHandleRequest(Map<String, String> parameters, StringBuilder errorDescription) throws RuntimeException {
String result = null;
long timestamp = new Date().getTime();
LoggerUtil.info(false, "客户端请求(%s):【%s】",timestamp+"", JSONObject.fromObject(parameters));
switch(Integer.parseInt(parameters.get("OPT"))){
case AppConstants.APP_LOGIN:
try{
result = AccountAction.logining(parameters);//123
}catch(Exception e){
e.printStackTrace();
LoggerUtil.error(true, "用户登录时:%s", e.getMessage());
result = errorHandling();
}
break;
case AppConstants.APP_SEND_CODE:
try{
result = AccountAction.sendCode(parameters);//111
}catch(Exception e){
e.printStackTrace();
LoggerUtil.error(true, "发送短信验证码时:%s", e.getMessage());
result = errorHandling();
}
break;
case AppConstants.APP_REGISTER_PROTOCOL:
try{
result = AboutUsAction.registerProtocol(parameters);//112
}catch(Exception e){
e.printStackTrace();
LoggerUtil.error(true, "加载注册协议时:%s", e.getMessage());
result = errorHandling();
}
break;
case AppConstants.APP_REGISTERING:
try{
result = AccountAction.registering(parameters);//113
}catch(Exception e){
e.printStackTrace();
LoggerUtil.error(true, "会员注册时:%s", e.getMessage());
result = errorHandling();
}
break;
case AppConstants.APP_PAYACCOUNT_OPEN_PRE:
try{
result = AccountAction.createAccountPre(parameters);//128
}catch(Exception e){
e.printStackTrace();
LoggerUtil.error(true, "会员开户准备时:%s", e.getMessage());
result = errorHandling();
}
break;
case AppConstants.APP_QUERY_CITY:
try{
result = AccountAction.queryCity(parameters);//129
}catch(Exception e){
e.printStackTrace();
LoggerUtil.error(true, "查询城市列表时:%s", e.getMessage());
result = errorHandling();
}
break;
case AppConstants.APP_PAYACCOUNT_OPEN:
try{
result = AccountAction.createAccount(parameters);//114
}catch(Exception e){
e.printStackTrace();
LoggerUtil.error(true, "会员开户时:%s", e.getMessage());
result = errorHandling();
}
break;
case AppConstants.APP_REGISTER_PRE:
try{
result = AccountAction.registerPre(parameters);//115
}catch(Exception e){
e.printStackTrace();
LoggerUtil.error(true, "准备注册时:%s", e.getMessage());
result = errorHandling();
}
break;
case AppConstants.APP_BIND_EMAIL_PRE:
try{
result = AccountAction.bindEmailPre(parameters);//124
}catch(Exception e){
e.printStackTrace();
LoggerUtil.error(true, "准备绑定邮箱时:%s", e.getMessage());
result = errorHandling();
}
break;
case AppConstants.APP_BIND_EMAIL:
try{
parameters.put("baseUrl", getBaseURL()); //获取到baseUrl
result = AccountAction.bindEmail(parameters);//125
}catch(Exception e){
e.printStackTrace();
LoggerUtil.error(true, "绑定邮箱时:%s", e.getMessage());
result = errorHandling();
}
break;
case AppConstants.APP_RNAUTH_PRE:
try{
result = AccountAction.rnAuthPre(parameters);//126
}catch(Exception e){
e.printStackTrace();
LoggerUtil.error(true, "准备实名认证时:%s", e.getMessage());
result = errorHandling();
}
break;
case AppConstants.APP_RNAUTH:
try{
result = AccountAction.rnAuth(parameters);//127
}catch(Exception e){
e.printStackTrace();
LoggerUtil.error(true, "实名认证时:%s", e.getMessage());
result = errorHandling();
}
break;
case AppConstants.APP_USER_BANK_LIST:
try{
result = MySecurityAction.listUserBankCard(parameters);//221
}catch(Exception e){
e.printStackTrace();
LoggerUtil.error(true, "查询会员银行卡列表时:%s", e.getMessage());
result = errorHandling();
}
break;
case AppConstants.APP_BIND_CARD:
try{
result = MySecurityAction.bindCard(parameters);//222
}catch(Exception e){
e.printStackTrace();
LoggerUtil.error(true, "会员绑卡时:%s", e.getMessage());
result = errorHandling();
}
break;
case AppConstants.APP_SET_DEFAULT_BANKCARD:
try{
result = MySecurityAction.setDefaultBankCard(parameters);//223
}catch(Exception e){
e.printStackTrace();
LoggerUtil.error(true, "设置默认卡时:%s", e.getMessage());
result = errorHandling();
}
break;
case AppConstants.APP_UPDATE_PWD:
try{
result = AccountAction.updateUserPwd(parameters);//122
}catch(Exception e){
e.printStackTrace();
LoggerUtil.error(true, "用户更改密码时:%s", e.getMessage());
result = errorHandling();
}
break;
case AppConstants.APP_VERIFICATION_CODE:
try{
result = AccountAction.verificationCode(parameters);//121
}catch(Exception e){
e.printStackTrace();
LoggerUtil.error(true, "验证验证码时:%s", e.getMessage());
result = errorHandling();
}
break;
case AppConstants.APP_WITHDRAWAL:
try{
result = RechargeAWithdrawalAction.withdrawal(parameters);//214
}catch(Exception e){
e.printStackTrace();
LoggerUtil.error(true, "提现时:%s", e.getMessage());
result = errorHandling();
}
break;
case AppConstants.APP_WITHDRAWAL_PRE:
try{
result = RechargeAWithdrawalAction.withdrawalPre(parameters);//213
}catch(Exception e){
e.printStackTrace();
LoggerUtil.error(true, "准备提现时:%s", e.getMessage());
result = errorHandling();
}
break;
case AppConstants.APP_WITHDRAWAL_RECORD:
try{
result = RechargeAWithdrawalAction.pageOfWithdraw(parameters);//215
}catch(Exception e){
e.printStackTrace();
LoggerUtil.error(true, "查询提现记录时:%s", e.getMessage());
result = errorHandling();
}
break;
case AppConstants.APP_USER_INFO:
try{
result = MyInfoAction.userInfomation(parameters);//251
}catch(Exception e){
e.printStackTrace();
LoggerUtil.error(true, "查询个人基本信息时:%s", e.getMessage());
result = errorHandling();
}
break;
case AppConstants.APP_RECHARGE_PRE:
try{
result = RechargeAWithdrawalAction.rechargePre(parameters);//216
}catch(Exception e){
e.printStackTrace();
LoggerUtil.error(true, "准备充值时:%s", e.getMessage());
result = errorHandling();
}
break;
case AppConstants.APP_RECHARGE:
try{
result = RechargeAWithdrawalAction.recharge(parameters);//211
}catch(Exception e){
e.printStackTrace();
LoggerUtil.error(true, "充值时:%s", e.getMessage());
result = errorHandling();
}
break;
case AppConstants.APP_RECHARGE_RECORDS:
try{
result = RechargeAWithdrawalAction.pageOfRecharge (parameters);//212
}catch(Exception e){
e.printStackTrace();
LoggerUtil.error(true, "查询充值交易记录时:%s", e.getMessage());
result = errorHandling();
}
break;
case AppConstants.APP_MESSAGE:
try{
result = MyInfoAction.pageOfUserMessage(parameters);//252
}catch(Exception e){
e.printStackTrace();
LoggerUtil.error(true, "查询消息列表时:%s", e.getMessage());
result = errorHandling();
}
break;
case AppConstants.APP_RETUEN_MONEY_PLAN:
try{
result = MyReceiveBillAction.pageOfReceiveBill(parameters);//242
}catch(Exception e){
e.printStackTrace();
LoggerUtil.error(true, "查询回款计划时:%s", e.getMessage());
result = errorHandling();
}
break;
case AppConstants.APP_MYINVEST:
try{
result = MyFundAction.pageOfMyInvest(parameters);//231
}catch(Exception e){
e.printStackTrace();
LoggerUtil.error(true, "查询我的投资时:%s", e.getMessage());
result = errorHandling();
}
break;
case AppConstants.APP_INVEST_BILL:
try{
result = MyFundAction.listOfInvestBill(parameters);//232
}catch(Exception e){
e.printStackTrace();
LoggerUtil.error(true, "查询理财账单详情时:%s", e.getMessage());
result = errorHandling();
}
break;
case AppConstants.APP_INVEST_BILL_INFO:
try{
result = MyFundAction.investBillInfo(parameters);//237
}catch(Exception e){
e.printStackTrace();
LoggerUtil.error(true, "查询理财账单详情时:%s", e.getMessage());
result = errorHandling();
}
break;
case AppConstants.APP_LOAN:
try{
result = MyFundAction.pageOfMyLoan(parameters);//233
}catch(Exception e){
e.printStackTrace();
LoggerUtil.error(true, "查询我的借款时:%s", e.getMessage());
result = errorHandling();
}
break;
case AppConstants.APP_LOAN_BILL:
try{
result = MyFundAction.listOfLoanBill(parameters);//234
}catch(Exception e){
e.printStackTrace();
LoggerUtil.error(true, "查询借款账单时:%s", e.getMessage());
result = errorHandling();
}
break;
case AppConstants.APP_LOAN_BILL_INFO:
try{
result = MyFundAction.findLoanBill(parameters);//238
}catch(Exception e){
e.printStackTrace();
LoggerUtil.error(true, "查询借款账单详情时:%s", e.getMessage());
result = errorHandling();
}
break;
case AppConstants.APP_LOAN_REPAYMENT:
try{
result = MyFundAction.repayment(parameters);//235
}catch(Exception e){
e.printStackTrace();
LoggerUtil.error(true, "还款时:%s", e.getMessage());
result = errorHandling();
}
break;
case AppConstants.APP_BID_PACT:
try{
result = MyFundAction.showBidPact(parameters);//236
}catch(Exception e){
e.printStackTrace();
LoggerUtil.error(true, "查询理财协议时:%s", e.getMessage());
result = errorHandling();
}
break;
case AppConstants.APP_DEBT://我的受让/转让
try{
result = MyFundAction.pageOfDebt(parameters);//239
}catch(Exception e){
e.printStackTrace();
LoggerUtil.error(true, "我的受让:%s", e.getMessage());
result = errorHandling();
}
break;
case AppConstants.APP_DEBT_PACT://转让协议
try{
result = MyFundAction.showDebtPact(parameters);//2312
}catch(Exception e){
e.printStackTrace();
LoggerUtil.error(true, "我的受让:%s", e.getMessage());
result = errorHandling();
}
break;
case AppConstants.APP_APPLAY_DEBT_PRE:
try{
result = MyFundAction.applyDebtPre(parameters);//2313
}catch(Exception e){
LoggerUtil.error(true, "债权申请准备:%s", e.getMessage());
result = errorHandling();
}
break;
case AppConstants.APP_APPLAY_DEBT:
try{
result = MyFundAction.applyDebtTransfer(parameters);//2314
}catch(Exception e){
LoggerUtil.error(true, "债权申请:%s", e.getMessage());
result = errorHandling();
}
break;
case AppConstants.APP_USER_DEAL_RECORD:
try{
result = MyDealAction.pageOfUserDealRecords(parameters);//241
}catch(Exception e){
e.printStackTrace();
LoggerUtil.error(true, "查询交易记录时:%s", e.getMessage());
result = errorHandling();
}
break;
case AppConstants.APP_USER_INFO_DETAIL:
try{
result = MyInfoAction.toUserInfo(parameters);//253
}catch(Exception e){
e.printStackTrace();
LoggerUtil.error(true, "查询用户信息时:%s", e.getMessage());
result = errorHandling();
}
break;
case AppConstants.APP_USER_INFO_UPDATE:
try{
result = MyInfoAction.updateUserInfo(parameters);//254
}catch(Exception e){
e.printStackTrace();
LoggerUtil.error(true, "保存用户信息时:%s", e.getMessage());
result = errorHandling();
}
break;
case AppConstants.APP_USER_PHOTO_UPDATE:
try{
result = MyInfoAction.updatePhoto(parameters);//255
}catch(Exception e){
e.printStackTrace();
LoggerUtil.error(true, "保存用户信息时:%s", e.getMessage());
result = errorHandling();
}
break;
//新版
case AppConstants.APP_PROVINCE:
try{
result =AreaAction.getAllProvince();//256
}catch(Exception e){
e.printStackTrace();
LoggerUtil.error(true, "获取省级时:%s", e.getMessage());
result = errorHandling();
}
break;
case AppConstants.APP_AREA:
try{
result =AreaAction.getAreaByProvinceId(parameters);//257
}catch(Exception e){
e.printStackTrace();
LoggerUtil.error(true, "获取市级时:%s", e.getMessage());
result = errorHandling();
}
break;
case AppConstants.APP_SECURITY:
try{
result = MySecurityAction.userSecurity(parameters);//261
}catch(Exception e){
e.printStackTrace();
LoggerUtil.error(true, "查询安全中心时:%s", e.getMessage());
result = errorHandling();
}
break;
case AppConstants.APP_UPDATE_PWDBYOLD:
try{
result = MySecurityAction.userUpdatePwdbyold(parameters);//262
}catch(Exception e){
e.printStackTrace();
LoggerUtil.error(true, "通过原密码更新密码时:%s", e.getMessage());
result = errorHandling();
}
break;
case AppConstants.APP_UPDATE_EMAIL:
try{
result = MySecurityAction.updateEmail(parameters);//263
}catch(Exception e){
e.printStackTrace();
LoggerUtil.error(true, "修改邮箱时:%s", e.getMessage());
result = errorHandling();
}
break;
case AppConstants.APP_EXP_BID_MYACCOUNT:
try{
result = MyExpBidAction.myExpBidAccount(parameters);
}catch(Exception e){
e.printStackTrace();
LoggerUtil.error(true, "查询体验金账户信息时:%s", e.getMessage());
result = errorHandling();
}
break;
case AppConstants.APP_EXP_BID_MYINVEST:
try{
result = MyExpBidAction.pageOfMyExpBidInvest(parameters);
}catch(Exception e){
e.printStackTrace();
LoggerUtil.error(true, "查询我的体验标投资记录时:%s", e.getMessage());
result = errorHandling();
}
break;
case AppConstants.APP_EXP_BID_GOLD_GET:
try{
result = MyExpBidAction.getExperienceGold(parameters);
}catch(Exception e){
e.printStackTrace();
LoggerUtil.error(true, "领取体验金时:%s", e.getMessage());
result = errorHandling();
}
break;
case AppConstants.APP_EXP_BID_INCOME_CONVERSION:
try{
result = MyExpBidAction.applayConversion(parameters);
}catch(Exception e){
e.printStackTrace();
LoggerUtil.error(true, "兑换体验金收益时:%s", e.getMessage());
result = errorHandling();
}
break;
case AppConstants.APP_INVEST_BIDS:
try{
result = InvestAction.pageOfInvestBids(parameters);//311
}catch(Exception e){
e.printStackTrace();
LoggerUtil.error(true, "查询理财产品列表时:%s", e.getMessage());
result = errorHandling();
}
break;
case AppConstants.APP_INVEST_BID_INFORMATION:
try{
result = InvestAction.investBidInformation(parameters);//312
}catch(Exception e){
e.printStackTrace();
LoggerUtil.error(true, "查询理财标详情时:%s", e.getMessage());
result = errorHandling();
}
break;
case AppConstants.APP_INVEST:
try{
result = InvestAction.invest(parameters);//321
}catch(Exception e){
e.printStackTrace();
LoggerUtil.error(true, "投标时:%s", e.getMessage());
result = errorHandling();
}
break;
case AppConstants.APP_INVEST_BIDS_DETAILS:
try{
result = InvestAction.investBidDeatils(parameters);//322
}catch(Exception e){
e.printStackTrace();
LoggerUtil.error(true, "查询借款标详情时:%s", e.getMessage());
result = errorHandling();
}
break;
case AppConstants.APP_INVEST_BIDS_REPAYMENT_PLAN:
try{
result = InvestAction.listOfRepaymentBill(parameters);//323
}catch(Exception e){
e.printStackTrace();
LoggerUtil.error(true, "查询标回款计划时:%s", e.getMessage());
result = errorHandling();
}
break;
case AppConstants.APP_INVEST_BIDS_RECORDS:
try{
result = InvestAction.investBidsRecord(parameters);//324
}catch(Exception e){
e.printStackTrace();
LoggerUtil.error(true, "查询投标记录时:%s", e.getMessage());
result = errorHandling();
}
break;
case AppConstants.APP_DEBTS:
try{
result = DebtAction.pageOfDebts(parameters);//331
}catch(Exception e){
e.printStackTrace();
LoggerUtil.error(true, "分页查询债权时:%s", e.getMessage());
result = errorHandling();
}
break;
case AppConstants.APP_DEBT_DETAIL:
try{
result = DebtAction.debtDetail(parameters);//332
}catch(Exception e){
e.printStackTrace();
LoggerUtil.error(true, "查询债权转让信息详情:%s", e.getMessage());
result = errorHandling();
}
break;
case AppConstants.APP_DEBT_BILLS:
try{
result = DebtAction.paymentsOfDebt(parameters);//333
}catch(Exception e){
e.printStackTrace();
LoggerUtil.error(true, "查询债权回款计划:%s", e.getMessage());
result = errorHandling();
}
break;
case AppConstants.APP_BUY_DEBT:
try{
result = DebtAction.buyDebt(parameters);//334
}catch(Exception e){
e.printStackTrace();
LoggerUtil.error(true, "购买债权:%s", e.getMessage());
result = errorHandling();
}
break;
case AppConstants.APP_EXP_BID:
try{
result = ExpBidAction.experienceBid(parameters);
}catch(Exception e){
e.printStackTrace();
LoggerUtil.error(true, "查询体验标信息:%s", e.getMessage());
result = errorHandling();
}
break;
case AppConstants.APP_EXP_BID_DETATIL:
try{
result = ExpBidAction.experienceBidDetail();
}catch(Exception e){
e.printStackTrace();
LoggerUtil.error(true, "查询体验标借款详情:%s", e.getMessage());
result = errorHandling();
}
break;
case AppConstants.APP_EXP_BID_INVEST_RECORD:
try{
result = ExpBidAction.expBidInvestRecord(parameters);
}catch(Exception e){
e.printStackTrace();
LoggerUtil.error(true, "查询体验标投资记录:%s", e.getMessage());
result = errorHandling();
}
break;
case AppConstants.APP_EXP_BID_INVEST:
try{
result = ExpBidAction.investExpBid(parameters);
}catch(Exception e){
e.printStackTrace();
LoggerUtil.error(true, "购买体验标:%s", e.getMessage());
result = errorHandling();
}
break;
case AppConstants.APP_COMPANY_INFO:
try{
result = AboutUsAction.aboutUs(parameters);//411
}catch(Exception e){
e.printStackTrace();
LoggerUtil.error(true, "查询公司介绍时:%s", e.getMessage());
result = errorHandling();
}
break;
case AppConstants.APP_CONTACT_US:
try{
result = AboutUsAction.contactUs(parameters);//421
}catch(Exception e){
e.printStackTrace();
LoggerUtil.error(true, "查询联系我们时:%s", e.getMessage());
result = errorHandling();
}
break;
case AppConstants.APP_PLATFORM_ICON:
try{
result = AccountAction.findPlatformIconFilename(parameters);//124
}catch(Exception e){
e.printStackTrace();
LoggerUtil.error(true, "查询平台logo时:%s", e.getMessage());
result = errorHandling();
}
break;
case AppConstants.APP_VERSION:
try{
result = AboutUsAction.getPlatformInfo(parameters);//423
}catch(Exception e){
e.printStackTrace();
LoggerUtil.error(true, "查询APP版本时:%s", e.getMessage());
result = errorHandling();
}
break;
case AppConstants.APP_INDEX:
try{
result = HomeAction.index(parameters);
}catch(Exception e){
e.printStackTrace();
LoggerUtil.error(true, "查询APP首页时:%s", e.getMessage());
result = errorHandling();
}
break;
case AppConstants.APP_MALL://611
try{
result = IntegralMallAction.showMall();
}catch(Exception e){
e.printStackTrace();
LoggerUtil.error(true, "查询APP积分商城时:%s", e.getMessage());
result = errorHandling();
}
break;
case AppConstants.APP_REDPACKET://612
try{
result = IntegralMallAction.showMyRedPacket(parameters);
}catch(Exception e){
e.printStackTrace();
LoggerUtil.error(true, "查询APP红包时:%s", e.getMessage());
result = errorHandling();
}
break;
case AppConstants.APP_ADDRATE://613
try{
result = IntegralMallAction.showMyRates(parameters);
}catch(Exception e){
e.printStackTrace();
LoggerUtil.error(true, "查询APP加息券时:%s", e.getMessage());
result = errorHandling();
}
break;
case AppConstants.APP_CASH://614
try{
result = IntegralMallAction.showMyCash(parameters);
}catch(Exception e){
e.printStackTrace();
LoggerUtil.error(true, "查询APP现金券时:%s", e.getMessage());
result = errorHandling();
}
break;
case AppConstants.APP_ADDADDRESS://622
try{
result = IntegralMallAction.addAddress(parameters);
}catch(Exception e){
e.printStackTrace();
LoggerUtil.error(true, "添加APP收货地址时:%s", e.getMessage());
result = errorHandling();
}
break;
case AppConstants.APP_ADDRESSLIST://621
try{
result = IntegralMallAction.addressList(parameters);
}catch(Exception e){
e.printStackTrace();
LoggerUtil.error(true, "查询APP地址详情时:%s", e.getMessage());
result = errorHandling();
}
break;
case AppConstants.APP_GUARANTEE://424
try{
result = AboutUsAction.Guarantee();
}catch(Exception e){
e.printStackTrace();
LoggerUtil.error(true, "查询APP安全保障时:%s", e.getMessage());
result = errorHandling();
}
break;
case AppConstants.APP_GUIDE://425
try{
result = AboutUsAction.guide(parameters);
}catch(Exception e){
e.printStackTrace();
LoggerUtil.error(true, "查询APP新手指南时:%s", e.getMessage());
result = errorHandling();
}
break;
case AppConstants.APP_ADDRESSLISTREADY://624
try{
result = IntegralMallAction.addAddressReady();
}catch(Exception e){
e.printStackTrace();
LoggerUtil.error(true, "初始化APP新增地址时:%s", e.getMessage());
result = errorHandling();
}
break;
case AppConstants.APP_SHOWMALLGOODS://631
try{
result = IntegralMallAction.showMallGoods(parameters);
}catch(Exception e){
e.printStackTrace();
LoggerUtil.error(true, "查询APP积分商品详情时:%s", e.getMessage());
result = errorHandling();
}
break;
case AppConstants.APP_EXCHANGEGOODS://632
try{
result = IntegralMallAction.exchangeGoods(parameters);
}catch(Exception e){
e.printStackTrace();
LoggerUtil.error(true, "查询APP积分商品详情时:%s", e.getMessage());
result = errorHandling();
}
break;
case AppConstants.APP_ANDMORE://426
try{
result = AndMoreAction.andMore(parameters);
}catch(Exception e){
e.printStackTrace();
LoggerUtil.error(true, "查询更多模块时:%s", e.getMessage());
result = errorHandling();
}
break;
case AppConstants.APP_SIGNIN://512
try{
result = HomeAction.signIn(parameters);
}catch(Exception e){
e.printStackTrace();
LoggerUtil.error(true, "APP签到时:%s", e.getMessage());
result = errorHandling();
}
break;
case AppConstants.APP_HELP://427
try{
result = AndMoreAction.goHelp(parameters);
}catch(Exception e){
e.printStackTrace();
LoggerUtil.error(true, "查询帮助中心时:%s", e.getMessage());
result = errorHandling();
}
break;
case AppConstants.APP_NOVICE://428
try{
result = AboutUsAction.novice();
}catch(Exception e){
e.printStackTrace();
LoggerUtil.error(true, "查询新手福利时:%s", e.getMessage());
result = errorHandling();
}
break;
case AppConstants.APP_HF_SENDSMSCODE://701
try{
result = CommonAction.sendSmsCode(parameters);
}catch(Exception e){
e.printStackTrace();
LoggerUtil.error(true, "上海银行存管发送短信验证码时:%s", e.getMessage());
result = errorHandling();
}
break;
case AppConstants.APP_CHECK_HF_NAME://702
try{
result = CommonAction.checkHfName(parameters);
}catch(Exception e){
e.printStackTrace();
LoggerUtil.error(true, "检查汇付用户号时:%s", e.getMessage());
result = errorHandling();
}
break;
case AppConstants.APP_BOSACCTACTIVATE://703
try{
result = AccountAction.bosAcctActivate(parameters);
}catch(Exception e){
e.printStackTrace();
LoggerUtil.error(true, "上海银行存管账户激活时:%s", e.getMessage());
result = errorHandling();
}
break;
case AppConstants.APP_QUICKBINDING://704
try{
result = AccountAction.quickBinding(parameters);
}catch(Exception e){
e.printStackTrace();
LoggerUtil.error(true, "上海银行存管账户激活时:%s", e.getMessage());
result = errorHandling();
}
break;
case AppConstants.APP_QUERY_SERVERFEE://705
try{
result = CommonAction.queryServFee(parameters);
}catch(Exception e){
e.printStackTrace();
LoggerUtil.error(true, "上海银行存管账户激活时:%s", e.getMessage());
result = errorHandling();
}
break;
case AppConstants.APP_NOTICE://800
try{
result = NoticeAction.getInformation();
}catch(Exception e){
e.printStackTrace();
LoggerUtil.error(true, "查询首页公告时:%s", e.getMessage());
result = errorHandling();
}
break;
case AppConstants.APP_NOTICE_INFO://801
try{
result = NoticeAction.getInformationById(parameters);
}catch(Exception e){
e.printStackTrace();
LoggerUtil.error(true, "查询首页公告详情时:%s", e.getMessage());
result = errorHandling();
}
break;
case AppConstants.APP_NOTICE_LIST://802
try{
result = NoticeAction.getInformationList(parameters);
}catch(Exception e){
e.printStackTrace();
LoggerUtil.error(true, "查询首页资讯列表时:%s", e.getMessage());
result = errorHandling();
}
break;
case AppConstants.APP_ACTIVITY_CENTER://900
try{
result = ActivityCenterAction.activityList();
}catch(Exception e){
e.printStackTrace();
LoggerUtil.error(true, "查询活动列表时:%s", e.getMessage());
result = errorHandling();
}
break;
case AppConstants.APP_FREQUENTLY_ASKED_QUESTIONS://901
try{
result = FrequentlyAskedQuestionsAction.FrequentlyAskedQuestionsList(parameters);
}catch(Exception e){
e.printStackTrace();
LoggerUtil.error(true, "查询常见问题列表时:%s", e.getMessage());
result = errorHandling();
}
break;
case AppConstants.APP_OPERATION_REPORT://1000
try{
result = ActivityCenterAction.operationReportList(parameters);
}catch(Exception e){
e.printStackTrace();
LoggerUtil.error(true, "查询活动列表时:%s", e.getMessage());
result = errorHandling();
}
break;
case AppConstants.APP_REC_EXP_GOLD://1101
try{
result = ExpGoldAction.appReceiveExpGold(parameters);
}catch(Exception e){
e.printStackTrace();
LoggerUtil.error(true, "领取体验金时:%s", e.getMessage());
result = errorHandling();
}
break;
case AppConstants.APP_QUERY_EXP_GOLD_ACCOUNT://1102
try{
result = ExpGoldAction.queryAppExpGoldAccountUserByUserId(parameters);
}catch(Exception e){
e.printStackTrace();
LoggerUtil.error(true, "查询用户体验金账户时:%s", e.getMessage());
result = errorHandling();
}
break;
case AppConstants.APP_SHOW_EXP_GOLD://1103
try{
result = ExpGoldAction.showExpGold(parameters);
}catch(Exception e){
e.printStackTrace();
LoggerUtil.error(true, "查询用户体验金账户时:%s", e.getMessage());
result = errorHandling();
}
break;
case AppConstants.APP_SCORE_RECORD://1201
try{
result = MyDealAction.listOfScoreRecordsPre(parameters);
}catch(Exception e){
e.printStackTrace();
LoggerUtil.error(true, "查询用户积分记录时:%s", e.getMessage());
result = errorHandling();
}
break;
}
LoggerUtil.info(false, "服务器响应(%s):【%s】",timestamp+"", result);
return result;
}
public static void index2(){
//首页
/* Map<String,String> parameters = new HashMap<String,String>();
parameters.put("OPT", 511+"");
String signID = Security.addSign(358L, Constants.INVEST_ID_SIGN, ConfConst.ENCRYPTION_APP_KEY_DES);
String userId= Security.addSign(33L, Constants.USER_ID_SIGN, ConfConst.ENCRYPTION_APP_KEY_DES);
parameters.put("userId",userId );
String result = new AppController().delegateHandleRequest(parameters, null);
System.out.println(result);
renderJSON(result);*/
/*
AppConstants.APP_APPLAY_DEBT_PRE债权转让申请准备
Map<String,String> parameters = new HashMap<String,String>();
parameters.put("OPT", AppConstants.APP_APPLAY_DEBT_PRE+"");
String signID = Security.addSign(358L, Constants.INVEST_ID_SIGN, ConfConst.ENCRYPTION_APP_KEY_DES);
parameters.put("investId", signID);
String result = new AppController().delegateHandleRequest(parameters, null);
System.out.println(result);
renderJSON(result);
*/
/*
//AppConstants.APP_APPLAY_DEBT债权转让申请
Map<String,String> parameters = new HashMap<String,String>();
parameters.put("OPT", AppConstants.APP_APPLAY_DEBT+"");
String signID = Security.addSign(358L, Constants.INVEST_ID_SIGN, ConfConst.ENCRYPTION_APP_KEY_DES);
parameters.put("investId", signID);
parameters.put("title", "358转让啦");
parameters.put("period", "2");
parameters.put("transferPrice", "4500");
String result = new AppController().delegateHandleRequest(parameters, null);
System.out.println(result);
renderJSON(result);
*/
/*
//AppConstants.APP_MYINVEST我的投资列表
Map<String,String> parameters = new HashMap<String,String>();
parameters.put("OPT", AppConstants.APP_MYINVEST+"");
String signID = Security.addSign(189L, Constants.USER_ID_SIGN, ConfConst.ENCRYPTION_APP_KEY_DES);
parameters.put("userId", signID);
parameters.put("currPage", "1");
parameters.put("pageSize", "5");
String result = new AppController().delegateHandleRequest(parameters, null);
System.out.println(result);
renderJSON(result);
*/
/*
//AppConstants.APP_LOAN我的投资列表
Map<String,String> parameters = new HashMap<String,String>();
parameters.put("OPT", AppConstants.APP_LOAN+"");
String signID = Security.addSign(188L, Constants.USER_ID_SIGN, ConfConst.ENCRYPTION_APP_KEY_DES);
parameters.put("userId", signID);
parameters.put("currPage", "1");
parameters.put("pageSize", "5");
String result = new AppController().delegateHandleRequest(parameters, null);
System.out.println(result);
renderJSON(result);
*/
/*
//AppConstants.APP_INDEBT我的受让
Map<String,String> parameters = new HashMap<String,String>();
parameters.put("OPT", AppConstants.APP_DEBT+"");
String signID = Security.addSign(189L, Constants.USER_ID_SIGN, ConfConst.ENCRYPTION_APP_KEY_DES);
parameters.put("userId", signID);
parameters.put("debtOf", "1");
parameters.put("currPage", "1");
parameters.put("pageSize", "5");
String result = new AppController().delegateHandleRequest(parameters, null);
System.out.println(result);
renderJSON(result);
*/
/*
//AppConstants.APP_DEBT_PACT转让协议
Map<String,String> parameters = new HashMap<String,String>();
parameters.put("OPT", AppConstants.APP_DEBT_PACT+"");
String signID = Security.addSign(37L, Constants.DEBT_TRANSFER_ID_SIGN, ConfConst.ENCRYPTION_APP_KEY_DES);
parameters.put("debtId", signID);
String result = new AppController().delegateHandleRequest(parameters, null);
System.out.println(result);
renderJSON(result);
*/
//AppConstants.APP_DEBTS债权转让列表
/* Map<String,String> parameters = new HashMap<String,String>();
parameters.put("OPT", AppConstants.APP_DEBTS+"");
String signID = Security.addSign(37L, Constants.DEBT_TRANSFER_ID_SIGN, ConfConst.ENCRYPTION_APP_KEY_DES);
parameters.put("currPage", "1");
parameters.put("pageSize", "20");
String result = new AppController().delegateHandleRequest(parameters, null);
System.out.println(result);
renderJSON(result);
*/
//AppConstants.APP_DEBT_DETAIL债权转让详细信息
/* Map<String,String> parameters = new HashMap<String,String>();
parameters.put("OPT", AppConstants.APP_DEBT_DETAIL+"");
String signID = Security.addSign(4L, Constants.DEBT_TRANSFER_ID_SIGN, ConfConst.ENCRYPTION_APP_KEY_DES);
parameters.put("debtId", signID);
String result = new AppController().delegateHandleRequest(parameters, null);
System.out.println(result);
renderJSON(result);*/
/*//AppConstants.APP_DEBT_DETAIL债权回款计划
Map<String,String> parameters = new HashMap<String,String>();
parameters.put("OPT", AppConstants.APP_DEBT_BILLS+"");
String signID = Security.addSign(357L, Constants.INVEST_ID_SIGN, ConfConst.ENCRYPTION_APP_KEY_DES);
parameters.put("investId", signID);
String result = new AppController().delegateHandleRequest(parameters, null);
System.out.println(result);
renderJSON(result);
*/
//AppConstants.APP_BUY_DEBT购买债权
/* Map<String,String> parameters = new HashMap<String,String>();
parameters.put("OPT", AppConstants.APP_BUY_DEBT+"");
String debtId = Security.addSign(1L, Constants.DEBT_TRANSFER_ID_SIGN, ConfConst.ENCRYPTION_APP_KEY_DES);
String userId = Security.addSign(13L, Constants.USER_ID_SIGN, ConfConst.ENCRYPTION_APP_KEY_DES);//17700000001
parameters.put("debtId", debtId);
parameters.put("userId", userId);
parameters.put("deviceType", "2");
String result = new AppController().delegateHandleRequest(parameters, null);
System.out.println(result);
renderJSON(result);*/
// AppConstants.APP_INVEST_BIDS 理财产品列表
/*Map<String,String> parameters = new HashMap<String,String>();
parameters.put("OPT", AppConstants.APP_INVEST_BIDS+"");
parameters.put("pageSize","5");
parameters.put("currPage", "1");
String result=new AppController().delegateHandleRequest(parameters, null);
System.out.println(result);
renderJSON(result);
*/
//AppConstants.APP_INVEST_BID_INFORMATION 标的详情 312
/* Map<String,String> parameters = new HashMap<String,String>();
parameters.put("OPT", AppConstants.APP_INVEST_BID_INFORMATION+"");
String debtId =Security.addSign(93L, Constants.BID_ID_SIGN, ConfConst.ENCRYPTION_APP_KEY_DES);//64144CC04707DB56D64F8DC34A7E2197019A23B0F0410D5Ca3e8b33d";//
String userId = Security.addSign(13L, Constants.USER_ID_SIGN, ConfConst.ENCRYPTION_APP_KEY_DES);//17700000001
parameters.put("bidIdSign",debtId);
parameters.put("userId", userId);
String result=new AppController().delegateHandleRequest(parameters, null);
System.out.println(result);
renderJSON(result);*/
//AppConstants.APP_NOTICE 首页公告接口800
/* Map<String,String> parameters = new HashMap<String,String>();
parameters.put("OPT", AppConstants.APP_NOTICE+"");
String result=new NoticeAction().getInformation();
System.out.println(result);
renderJSON(result);*/
//AppConstants.APP_NOTICE 首页公告详情接口801
/* Map<String,String> parameters = new HashMap<String,String>();
String informationIdSign="D2EA5FDA87BC1D012A95D87E141A7CE185723880B13258A79390F33595CA72B82d4efe8a";//Security.addSign(31, Constants.INFORMATION_ID_SIGN, ConfConst.ENCRYPTION_KEY_DES);
parameters.put("informationId",informationIdSign);
parameters.put("OPT", AppConstants.APP_NOTICE_INFO+"");
String result=new NoticeAction().getInformationById(parameters);
System.out.println(result);
renderJSON(result);*/
//AppConstants.APP_NOTICE 首页公告列表接口802
/*Map<String,String> parameters = new HashMap<String,String>();
List<String> informationMenus=new ArrayList<String>();
informationMenus.add(InformationMenu.INFO_BULLETIN.code);
parameters.put("currPage", "1");
parameters.put("pageSize", "5");
parameters.put("informationMenu", "3");
parameters.put("OPT", AppConstants.APP_NOTICE_LIST+"");
String result=new AppController().delegateHandleRequest(parameters, null);
System.out.println(result);
renderJSON(result);*/
//AppConstants.APP_USER_INFO 个人基本信息
/* Map<String,String> parameters = new HashMap<String,String>();
parameters.put("deviceType", "2");
parameters.put("userId",Security.addSign(13, Constants.USER_ID_SIGN, ConfConst.ENCRYPTION_APP_KEY_DES));
parameters.put("OPT", AppConstants.APP_USER_INFO +"");
String result=new AppController().delegateHandleRequest(parameters, null);
System.out.println(result);
renderJSON(result);*/
//加息卷
/* Map<String,String> parameters = new HashMap<String,String>();
parameters.put("deviceType", "2");
int pageSize=Convert.strToInt(parameters.get("pageSize"), 15);
int currPage=Convert.strToInt(parameters.get("currPage"), 1);
parameters.put("userId",Security.addSign(13, Constants.USER_ID_SIGN, ConfConst.ENCRYPTION_APP_KEY_DES) );
parameters.put("OPT", 613+"");
String result=new AppController().delegateHandleRequest(parameters, null);
System.out.println(result);
renderJSON(result);*/
//活动列表
/*Map<String,String> parameters = new HashMap<String,String>();
parameters.put("OPT", 900+"");
String result=new AppController().delegateHandleRequest(parameters, null);
System.out.println(result);
renderJSON(result);*/
//运营报告
/* Map<String,String> parameters = new HashMap<String,String>();
parameters.put("OPT", "1000");
parameters.put("pageSize", "10");
parameters.put("currPage", "1");
String result=new AppController().delegateHandleRequest(parameters, null);
System.out.println(result);
renderJSON(result);*/
//借款人详情
/* Map<String,String> parameters = new HashMap<String,String>();
parameters.put("OPT", AppConstants.APP_INVEST_BIDS_DETAILS+"");
String debtId = Security.addSign(22L, Constants.BID_ID_SIGN, ConfConst.ENCRYPTION_APP_KEY_DES);
parameters.put("bidIdSign",debtId);
String result=new AppController().delegateHandleRequest(parameters, null);
System.out.println(result);
renderJSON(result);*/
//AppConstants.APP_INVEST:投标接口
/* Map<String,String> parameters = new HashMap<String,String>();
String debtId = Security.addSign(95L, Constants.BID_ID_SIGN, ConfConst.ENCRYPTION_APP_KEY_DES);
parameters.put("OPT", AppConstants.APP_INVEST+"");
parameters.put("userId",Security.addSign(13, Constants.USER_ID_SIGN, ConfConst.ENCRYPTION_APP_KEY_DES) );
parameters.put("rateId","1B5EBE4EBACDF9F7A20CE00DD4E9B742BB8CB3CE887ADC4C5B9A79DF5EF966561a4d88e0");
parameters.put("bribeId","E84F35705BEC17C8D8E26C2713496DFE6FCE7C7FCE7B859FC5C47DBDA02C3A183bfc240d");
parameters.put("investAmt","2000");
parameters.put("bidIdSign",debtId);
parameters.put("deviceType", "3");
String result=new AppController().delegateHandleRequest(parameters, null);
System.out.println(result);
renderJSON(result);*/
//常见问题列表
/* Map<String, String > parameters=new HashMap<String, String>();
parameters.put("OPT","901");
parameters.put("pageSize","6");
parameters.put("currPage", "1");
parameters.put("column_no","9");
String result=new AppController().delegateHandleRequest(parameters,null);
System.out.println(result);
renderJSON(result);*/
//安全中心
/* Map<String, String > parameters=new HashMap<String, String>();
parameters.put("OPT","261");
parameters.put("userId",Security.addSign(13,Constants.USER_ID_SIGN, ConfConst.ENCRYPTION_APP_KEY_DES));
String result=new AppController().delegateHandleRequest(parameters,null);
System.out.println(result);
renderJSON(result);*/
// 253 客户端获取会员信息接口
/* Map<String, String > parameters=new HashMap<String, String>();
parameters.put("OPT","253");
parameters.put("userId",Security.addSign(13,Constants.USER_ID_SIGN, ConfConst.ENCRYPTION_APP_KEY_DES));
String result=new AppController().delegateHandleRequest(parameters,null);
System.out.println(result);
renderJSON(result);*/
//254客户端保存会员信息接口
/* Map<String, String > parameters=new HashMap<String, String>();
parameters.put("OPT","254");
parameters.put("userId",Security.addSign(13,Constants.USER_ID_SIGN, ConfConst.ENCRYPTION_APP_KEY_DES));
parameters.put("car","1");
parameters.put("area_id","1200");
parameters.put("work_unit","虹奥金融股份有限公司");
parameters.put("house","1");
parameters.put("education","1");
parameters.put("prov_id","0012");
parameters.put("registered_fund","22222");
parameters.put("annualIncome","3");
parameters.put("emergencyContactName","紧急联系人名");
parameters.put("workExperience","4");
parameters.put("start_time","2017-10");
parameters.put("emergencyContactMobile","13888888888");
parameters.put("emergencyContactType","3");
parameters.put("marital","2");
parameters.put("netAsset","1");
String result=new AppController().delegateHandleRequest(parameters,null);
System.out.println(result);
renderJSON(result);*/
//256 获取省级
/* Map<String, String > parameters=new HashMap<String, String>();
parameters.put("OPT","256");
String result=new AppController().delegateHandleRequest(parameters,null);
System.out.println(result);
renderJSON(result);*/
//257 获取市级
/* Map<String, String > parameters=new HashMap<String, String>();
parameters.put("OPT","257");
parameters.put("code","0014");
String result=new AppController().delegateHandleRequest(parameters,null);
System.out.println(result);
renderJSON(result);*/
//252 用户消息
/* Map<String, String > parameters=new HashMap<String, String>();
parameters.put("OPT","252");
parameters.put("userId",Security.addSign(13,Constants.USER_ID_SIGN, ConfConst.ENCRYPTION_APP_KEY_DES));
parameters.put("pageSize","3");
parameters.put("currPage","1");
String result=new AppController().delegateHandleRequest(parameters,null);
System.out.println(result);
renderJSON(result);*/
//APP签到
/* Map<String, String > parameters=new HashMap<String, String>();
parameters.put("OPT","512");
parameters.put("userId",Security.addSign(13,Constants.USER_ID_SIGN, ConfConst.ENCRYPTION_APP_KEY_DES));
String result=new AppController().delegateHandleRequest(parameters,null);
System.out.println(result);
renderJSON(result);*/
Map<String, String > parameters=new HashMap<String, String>();
parameters.put("OPT","1201");
parameters.put("pageSize","10");
parameters.put("currPage","1");
parameters.put("userId",Security.addSign(13,Constants.USER_ID_SIGN, ConfConst.ENCRYPTION_APP_KEY_DES));
String result=new AppController().delegateHandleRequest(parameters,null);
System.out.println(result);
renderJSON(result);
}
/***
*
* 程序异常 信息统一提示
* @return
* @description
*
* @author luzhiwei
* @createDate 2016-4-25
*/
private String errorHandling(){
JSONObject json = new JSONObject();
json.put("code", ResultInfo.ERROR_500);
json.put("msg", "系统繁忙,请稍后再试");
return json.toString();
}
}
| true |
8dee79d73fac73c842a35d05e9b4302260c04e02 | Java | lzhcccccch/JavaSE | /src/cn/sdut/exception/ThrowExceptionTest.java | UTF-8 | 833 | 3.625 | 4 | [] | no_license | package cn.sdut.exception;
/**
* Created by liuzhichao on 2018/8/17.
*/
public class ThrowExceptionTest {
public static void main(String[] args) throws AgeIndexOfBoundsException {
// TODO Auto-generated method stub
Person per=new Person();
per.setAge(256);
System.out.println(per.getAge());
}
}
class Person
{
private int age;
public int getAge() {
return age;
}
public void setAge(int age) throws AgeIndexOfBoundsException {
if(age<0 ||age>250)
{
/**
* 抛出异常的实例,只能抛出异常的实例
* 抛出异常之后一定要用try..catch或者throws来进行处理
*/
throw new AgeIndexOfBoundsException("年龄越界了");
}
this.age = age;
}
} | true |
36f627c7b39450548e3278ca8e9b01d118b897a6 | Java | ullf/SpringDev | /src/main/java/ru/marksblog/repository/AdRepository.java | UTF-8 | 1,447 | 2.390625 | 2 | [] | no_license | package ru.marksblog.repository;
import org.springframework.stereotype.Repository;
import ru.marksblog.model.Ad;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.util.List;
@Repository
public class AdRepository {
@PersistenceContext
EntityManager entityManager;
public void persist(Object obj) {
if (obj != null) {
entityManager.persist(obj);
}
}
public Ad findById(int id) {
Query query = entityManager.createQuery("SELECT ad FROM Ad ad WHERE ad.id=:id", Ad.class);
query.setParameter("id", id);
return (Ad) query.getResultList().get(0);
}
public List<Ad> findAll() {
Query query = entityManager.createQuery("SELECT ad FROM Ad ad", Ad.class);
return query.getResultList();
}
public void deleteById(int id) {
Query query = entityManager.createQuery("DELETE FROM Ad ad WHERE ad.id=:id");
query.setParameter("id", id);
query.executeUpdate();
}
public void update(Ad ad) {
entityManager.merge(ad);
}
public List<Ad> getAllByCategory(String category) {
Query query = entityManager.createQuery("SELECT ad FROM Ad ad WHERE ad.category=:category", Ad.class);
query.setParameter("category", category);
return query.getResultList();
}
}
| true |
28af362c6ebf583b0c523ba52f793278a9525110 | Java | Pekwerike/TCP-Socket-Client | /src/MainApplication.java | UTF-8 | 1,440 | 3.234375 | 3 | [] | no_license | import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
public class MainApplication {
public static void main(String[] args) throws IOException {
Runnable runnable = () -> {
Socket server = null;
try {
server = new Socket("192.168.43.190", 8085);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Connected to server");
VideosMovement videosMovement = new VideosMovement();
// videosMovement.receiveVideo(server);
File video1 = getVideoFile("148 Introduction to the DOM");
File video2 = getVideoFile("149 Defining the DOM");
File video3 = getVideoFile("150 Select and Manipulate");
File video4 = getVideoFile("152 Important Selector Methods");
File[] videoCollection = { video2, video1, video3, video4};
try {
// videosMovement.transferVideo(videoCollection,server);
videosMovement.receiveVideo(server);
} catch (IOException e) {
e.printStackTrace();
}
};
Thread thread = new Thread(runnable);
thread.start();
}
private static File getVideoFile(String name){
return new File("C:\\Users\\Prosper's PC\\Desktop\\the web developer bootcamp\\13 DOM Manipulation\\" + name +".mp4");
}
}
| true |
4a5ed6d401f70b398aee3738369a8b59cc88528d | Java | shashimk/spring-boot-demo | /src/test/java/com/example/demo/SpringBootStandaloneApplicationTest.java | UTF-8 | 904 | 2.03125 | 2 | [] | no_license | package com.example.demo;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.boot.test.context.SpringBootTest;
import uk.org.webcompere.systemstubs.jupiter.SystemStub;
import uk.org.webcompere.systemstubs.jupiter.SystemStubsExtension;
import uk.org.webcompere.systemstubs.stream.SystemIn;
@SpringBootTest(args = "70") @ExtendWith(SystemStubsExtension.class)
class SpringBootStandaloneApplicationTest {
@Test void testMainWithCommandLineArguments() {
Assertions.assertDoesNotThrow(() -> Exception.class);
}
@SystemStub private SystemIn systemIn = new SystemIn("50");
@Test void testMainWithoutCommandLineArguments() {
SpringBootStandaloneApplication s = new SpringBootStandaloneApplication();
s.main(new String[] {});
Assertions.assertDoesNotThrow(() -> Exception.class);
}
}
| true |
ce7cc6de357359999b2150d80f8a31a4c17db385 | Java | Carambis/TicketSystem | /src/main/java/by/tc/web/service/validation/ValidatorUser.java | UTF-8 | 2,226 | 2.359375 | 2 | [] | no_license | package by.tc.web.service.validation;
import by.tc.web.entity.user.User;
public class ValidatorUser {
private final static String VALID_LOGIN = "^[a-zA-Z](.[a-zA-Z0-9_-]*)$";
private final static String VALID_PASSWORD = "^(?!.*admin)[A-Za-z0-9_]{8,}$";
private final static String VALID_EMAIL = "^((([0-9A-Za-z]{1}[-0-9A-z\\.]{1,}[0-9A-Za-z]{1}))@([-A-Za-z]{1,}\\.){1,2}[-A-Za-z]{2,})$";
private static final int LENGTH = 20;
public static boolean authValidator(String login, String password) {
if (login.isEmpty() || password.isEmpty()) {
return false;
}
return true;
}
public static boolean regValidator(User user) {
if (user.getLogin().isEmpty()
|| user.getPassword().isEmpty()
|| user.geteMail().isEmpty()
|| user.getNickname().isEmpty()) {
return false;
}
if (user.getLogin().length() < 4 || user.getLogin().length() > LENGTH
|| user.getPassword().length() < 8 || user.getPassword().length() > LENGTH) {
return false;
}
if (!user.getLogin().matches(VALID_LOGIN)) {
return false;
}
if (!user.getPassword().matches(VALID_PASSWORD)) {
return false;
}
if (!user.geteMail().matches(VALID_EMAIL)) {
return false;
}
return true;
}
public static boolean editValidator(User user) {
if (!regValidator(user)) {
return false;
}
if (user.getPathToImage() == null || user.getPathToImage().isEmpty()) {
return false;
}
return true;
}
public static boolean banValidator(int userId, Integer banId) {
return true;
}
public static boolean profileValidator(User user)
{
if (user.getPassword().isEmpty()
|| user.geteMail().isEmpty()
|| user.getNickname().isEmpty()) {
return false;
}
if (!user.getPassword().matches(VALID_PASSWORD)) {
return false;
}
if (!user.geteMail().matches(VALID_EMAIL)) {
return false;
}
return true;
}
}
| true |
17dd10a6814978af6f0b859fb08292e4f0a570c7 | Java | shanetbyrne/OOP-Repeat | /PokemonGame/src/GamePage.java | UTF-8 | 13,786 | 3.25 | 3 | [] | no_license | import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.ArrayList;
import java.util.Random;
//MAIN CLASS//
public class GamePage extends JFrame implements ActionListener { //AddPokemon inherits from the JFrame class (super class inheritance) and implements the ActionListener interface
//GLOBAL VARIABLES
static ArrayList<Pokemon> Pokemons = new ArrayList<>(); //declares the ArrayList (of type <Pokemon>) Pokemons
public static ArrayList<Pokemon> getPokemons() { //ArrayList Getters
return Pokemons;
} //gets the ArrayList Pokemons
JMenu homeMenu; //Pokemons JMenu global variable
static JFrame frame = new JFrame("Shane's Pokemon Game");
private static JMenuItem goBack; //global variables for JMenuItems
private static JButton p1Punch, p1Kick, p1Bite, p1Slash, p2Kick, p2Punch, p2Bite, p2Slash;
int player1Health = 100, player2Health = 100;
//MAIN METHOD//
public static void main(String[] args) { //Main Method
GamePage frame = new GamePage(); //creating the AddPokemon JFrame window
frame.setVisible(true); //making the window visible
}
//CONSTRUCTOR//
public GamePage() {
Container pane; //creating the local variable for the content pane
setTitle("Shane's Pokemon Game");
setSize(1000, 600);
setResizable(false); //WINDOW PROPERTIES
setLocation(250, 200);
setDefaultCloseOperation(EXIT_ON_CLOSE);
//CONTENT PANE AND HEADER LABEL
pane = getContentPane(); //getting the content pane
pane.setLayout(null); //setting the layout to null for absolute positioning
JLabel header = new JLabel("Let the Games Begin"); //header label
Font font = new Font("monospaced", Font.PLAIN, 24);//header font
//JLABELS
JLabel title = new JLabel("You are player 1. You have 4 attack moves. Choose between punch, kick, bite and slash."); //title label
JLabel player1 = new JLabel("Player 1");
JLabel player2 = new JLabel("Player 2");
//JBUTTONS
p1Punch = new JButton("Punch"); //arraylist button (DECLARED GLOBALLY)
p1Punch.addActionListener(this); //actionlistener for add Pokemons button(this)
p1Kick = new JButton("Kick"); //arraylist button (DECLARED GLOBALLY)
p1Kick.addActionListener(this); //actionlistener for add Pokemons button(this)
p1Bite = new JButton("Bite"); //arraylist button (DECLARED GLOBALLY)
p1Bite.addActionListener(this); //actionlistener for add Pokemons button(this)
p1Slash = new JButton("Slash"); //arraylist button (DECLARED GLOBALLY)
p1Slash.addActionListener(this); //actionlistener for add Pokemons button(this)
p2Punch = new JButton("Punch"); //arraylist button (DECLARED GLOBALLY)
p2Punch.addActionListener(this); //actionlistener for add Pokemons button(this)
p2Kick = new JButton("Kick"); //arraylist button (DECLARED GLOBALLY)
p2Kick.addActionListener(this); //actionlistener for add Pokemons button(this)
p2Bite = new JButton("Bite"); //arraylist button (DECLARED GLOBALLY)
p2Bite.addActionListener(this); //actionlistener for add Pokemons button(this)
p2Slash = new JButton("Slash"); //arraylist button (DECLARED GLOBALLY)
p2Slash.addActionListener(this); //actionlistener for add Pokemons button(this)
//JMENU METHODS
homeMenu(); //calling JMenuBar components methods
JMenuBar menu = new JMenuBar(); //creating an instance of the JMenuBar class
setJMenuBar(menu); //setting the JMenuBar to the variable name 'menu'
menu.add(Box.createHorizontalGlue()); //right aligning the JMenuBar. this line of code was got from https://stackoverflow.com/questions/8560810/aligning-jmenu-on-the-right-corner-of-jmenubar-in-java-swing
menu.setBackground(Color.lightGray); //setting the JMenuBar background color to grey
menu.add(homeMenu); //adding the JMenu components to the JMenuBar
header.setFont(font); //applying the font to the header
//ADDING THE JLABELS AND JBUTTONS TO THE CONTENT PANE//
pane.add(title);
pane.add(player1);
pane.add(player2);
pane.add(p1Bite);
pane.add(p1Kick);
pane.add(p1Slash);
pane.add(p1Punch);
pane.add(p2Bite);
pane.add(p2Kick);
pane.add(p2Slash);
pane.add(p2Punch);
//BEGINNING OF ABSOLUTE POSITIONING//
Insets insets = pane.getInsets(); //creating an instance of the insets class and applying it to the content pane
Dimension size = header.getPreferredSize(); //using the getPrefferedSize(pre-written method) to create a suitable size for the visit store button
header.setBounds(200 + insets.left, 40 + insets.top, //setting the dimensions
size.width, size.height);
size = player1.getPreferredSize();
player1.setBounds(265 + insets.left, 150 + insets.top,
size.width, size.height);
size = player2.getPreferredSize();
player2.setBounds(665 + insets.left, 150 + insets.top,
size.width, size.height);
size = title.getPreferredSize();
title.setBounds(250 + insets.left, 100 + insets.top,
size.width, size.height);
size = p1Bite.getPreferredSize();
p1Bite.setBounds(200 + insets.left, 200 + insets.top,
size.width, size.height);
size = p1Kick.getPreferredSize();
p1Kick.setBounds(200 + insets.left, 300 + insets.top,
size.width, size.height);
size = p1Punch.getPreferredSize();
p1Punch.setBounds(300 + insets.left, 200 + insets.top,
size.width, size.height);
size = p1Slash.getPreferredSize();
p1Slash.setBounds(300 + insets.left, 300 + insets.top,
size.width, size.height);
size = p2Bite.getPreferredSize();
p2Bite.setBounds(600 + insets.left, 200 + insets.top,
size.width, size.height);
size = p2Kick.getPreferredSize();
p2Kick.setBounds(700 + insets.left, 200 + insets.top,
size.width, size.height);
size = p2Punch.getPreferredSize();
p2Punch.setBounds(600 + insets.left, 300 + insets.top,
size.width, size.height);
size = p2Slash.getPreferredSize();
p2Slash.setBounds(700 + insets.left, 300 + insets.top,
size.width, size.height);
//END OF ABSOLUTE POSITIONING
}
public void actionPerformed(ActionEvent e) { //event handler
if (e.getSource() == goBack) { // if 'goBack' button is clicked
JOptionPane.showMessageDialog(null, "Re-directing you to the Main Menu"); //display this message
MainMenu menu = new MainMenu(); //create a new instance of AddPokemon class
menu.setVisible(true); //set AddPokemons JFrame window to visible
this.setVisible(false); //hide the current page i.e. this page
}
if (e.getSource() == p1Punch) { // if 'p1Punch' button is clicked
punch(e);
finishOpponent(e);
return;
}
if (e.getSource() == p1Kick) { // if 'p1Kick' button is clicked
kick(e);
finishOpponent(e);
return;
}
if (e.getSource() == p1Bite) { // if 'p1Bite' button is clicked
bite(e);
finishOpponent(e);
return;
}
if (e.getSource() == p1Slash) { // if 'p1Slash' button is clicked
slash(e);
finishOpponent(e);
return;
}
}
public void punch(ActionEvent e) { //event handler
if (e.getSource() == p1Punch ) { // if 'p1Punch' button is clicked
player2Health = player2Health - 10;
JOptionPane.showMessageDialog(null, "Player 1 has punched player 2. Player 2's health is now " + player2Health); //display this message
ArrayList<JButton> buttons = new ArrayList<>(); //declares the ArrayList (of type <Pokemon>) Pokemons
buttons.add(p2Punch);
buttons.add(p2Kick);
buttons.add(p2Bite);
buttons.add(p2Slash);
Random rand = new Random();
int r = rand.nextInt(buttons.size());
JButton player2Action = buttons.get(r);
if(player2Action == p2Punch){
player1Health = player1Health - 10;
return;
}
else if (player2Action == p2Kick){
player1Health = player1Health - 20;
return;
}
else if (player2Action == p2Bite){
player1Health = player1Health - 40;
return;
}
else if (player2Action == p2Slash){
player1Health = player1Health - 30;
return;
}
}
}
public void kick(ActionEvent e) { //event handler
if (e.getSource() == p1Kick ) { // if 'p1Kick' button is clicked
player2Health = player2Health - 20;
JOptionPane.showMessageDialog(null, "Player 1 has kicked player 2. Player 2's health is now " + player2Health); //display this message
ArrayList<JButton> buttons = new ArrayList<>(); //declares the ArrayList (of type <Pokemon>) Pokemons
buttons.add(p2Punch);
buttons.add(p2Kick);
buttons.add(p2Bite);
buttons.add(p2Slash);
Random rand = new Random();
int r = rand.nextInt(buttons.size());
JButton player2Action = buttons.get(r);
if(player2Action == p2Punch){
player1Health = player1Health - 10;
return;
}
else if (player2Action == p2Kick){
player1Health = player1Health - 20;
return;
}
else if (player2Action == p2Bite){
player1Health = player1Health - 40;
return;
}
else if (player2Action == p2Slash){
player1Health = player1Health - 30;
return;
}
}
}
public void bite(ActionEvent e) { //event handler
if (e.getSource() == p1Bite ) { // if 'p1Bite' button is clicked
player2Health = player2Health - 40;
JOptionPane.showMessageDialog(null, "Player 1 has bitten player 2. Player 2's health is now " + player2Health); //display this message
ArrayList<JButton> buttons = new ArrayList<>(); //declares the ArrayList (of type <Pokemon>) Pokemons
buttons.add(p2Punch);
buttons.add(p2Kick);
buttons.add(p2Bite);
buttons.add(p2Slash);
Random rand = new Random();
int r = rand.nextInt(buttons.size());
JButton player2Action = buttons.get(r);
if(player2Action == p2Punch){
player1Health = player1Health - 10;
return;
}
else if (player2Action == p2Kick){
player1Health = player1Health - 20;
return;
}
else if (player2Action == p2Bite){
player1Health = player1Health - 40;
return;
}
else if (player2Action == p2Slash){
player1Health = player1Health - 30;
return;
}
}
}
public void slash(ActionEvent e) { //event handler
if (e.getSource() == p1Slash ) { // if 'p1Slash' button is clicked
player2Health = player2Health - 30;
JOptionPane.showMessageDialog(null, "Player 1 has slashed player 2. Player 2's health is now " + player2Health); //display this message
ArrayList<JButton> buttons = new ArrayList<>(); //declares the ArrayList (of type <Pokemon>) Pokemons
buttons.add(p2Punch);
buttons.add(p2Kick);
buttons.add(p2Bite);
buttons.add(p2Slash);
Random rand = new Random();
int r = rand.nextInt(buttons.size());
JButton player2Action = buttons.get(r);
if(player2Action == p2Punch){
player1Health = player1Health - 10;
}
else if (player2Action == p2Kick){
player1Health = player1Health - 20;
}
else if (player2Action == p2Bite){
player1Health = player1Health - 40;
}
else if (player2Action == p2Slash){
player1Health = player1Health - 30;
}
}
}
public void finishOpponent(ActionEvent e) { //event handler
if(player1Health <= 0){
JOptionPane.showMessageDialog(null, "Loser! You are dead. Player 2 has won the game. ");
System.exit(0);
}
else if (player2Health <= 0){
JOptionPane.showMessageDialog(null, "Winner! You have killed player 2. You have won the game. ");
System.exit(0);
}
}
private void homeMenu () {
homeMenu = new JMenu("Home");
goBack = new JMenuItem("Return to Main Menu");
goBack.addActionListener(this);
homeMenu.add(goBack);
}
}
| true |
73351ae35904bd50435055153d33579a067a2175 | Java | dzakyabdi/tutorial-apap | /gopud/src/test/java/apap/tutorial/gopud/service/MenuServiceImplTest.java | UTF-8 | 3,270 | 2.421875 | 2 | [] | no_license | package apap.tutorial.gopud.service;
import apap.tutorial.gopud.model.MenuModel;
import apap.tutorial.gopud.model.RestoranModel;
import apap.tutorial.gopud.repository.MenuDb;
import apap.tutorial.gopud.repository.RestoranDb;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.*;
@RunWith(MockitoJUnitRunner.class)
public class MenuServiceImplTest {
@InjectMocks
MenuService menuService = new MenuServiceImpl();
RestoranService restoranService = new RestoranServiceImpl();
@Mock
MenuDb menuDb;
RestoranDb restoranDb;
@Test
public void whenAddValidMenuItShouldCallRestoranRepositorySave() {
MenuModel newMenu = new MenuModel();
newMenu.setNama("mekdi");
newMenu.setHarga(BigInteger.valueOf(10000));
newMenu.setDurasiMasak(60);
newMenu.setDeskripsi("enak banget");
menuService.addMenu(newMenu);
verify(menuDb, times(1)).save(newMenu);
}
@Test
public void whenDeleteValidMenuItShouldCallRestoranRepositoryDelete() {
MenuModel newMenu = new MenuModel();
newMenu.setNama("mekdi");
newMenu.setHarga(BigInteger.valueOf(10000));
newMenu.setDurasiMasak(60);
newMenu.setDeskripsi("enak banget");
menuService.addMenu(newMenu);
menuService.deleteMenu(newMenu);
verify(menuDb, times(1)).delete(newMenu);
}
@Test
public void whenGetListMenuOrderByHargaAscCalledItShouldReturnAllMenu() {
RestoranModel newRestoran = new RestoranModel();
List<MenuModel> newListMenuDatabase = new ArrayList<>();
int harga = 5000;
for (int loopTimes = 4; loopTimes > 0; loopTimes--) {
MenuModel newMenu = new MenuModel();
newMenu.setHarga(BigInteger.valueOf(harga++));
newListMenuDatabase.add(newMenu);
}
when(menuService.getListMenuOrderByHargaAsc(newRestoran.getIdRestoran())).thenReturn(newListMenuDatabase);
List<MenuModel> dataFromServiceCall = menuService.getListMenuOrderByHargaAsc(newRestoran.getIdRestoran());
int tesharga = 5000;
for(int i = 0; i < 4; i++) {
assertEquals(BigInteger.valueOf(tesharga++), dataFromServiceCall.get(i).getHarga());
}
}
@Test
public void whenFindAllMenuByIdRestoranCalledItShouldReturnAllMenu() {
RestoranModel restoran = new RestoranModel();
List<MenuModel> allMenuFromOneRestoranInDataBase = new ArrayList<>();
for (int loopTimes = 3; loopTimes > 0; loopTimes--) {
allMenuFromOneRestoranInDataBase.add(new MenuModel());
}
when(menuService.findAllMenuByIdRestoran(restoran.getIdRestoran())).thenReturn(allMenuFromOneRestoranInDataBase);
List<MenuModel> dataFromServiceCall = menuService.findAllMenuByIdRestoran(restoran.getIdRestoran());
assertEquals(3, dataFromServiceCall.size());
// verify(menuDb, times(1)).findAll();
}
}
| true |
a37efd6c05bf4ddcf8ef8b249f9f99f804fcadb6 | Java | canvaser/desktop | /app/src/main/java/com/siweisoft/network/interf/OnNetWorkResInterf.java | UTF-8 | 676 | 2.078125 | 2 | [] | no_license | package com.siweisoft.network.interf;
import com.siweisoft.network.bean.res.BaseResBean;
/**
* Created by ${viwmox} on 2016-05-16.
*/
public interface OnNetWorkResInterf <T>{
/**
* 网络无连接
*/
int ERROR_TYPE_INPUT_NOT_ALL = 3;
/**
* 网络无连接
*/
int ERROR_TYPE_NETCONNETCT = 0;
/**
* 返回数据为空
*/
int ERROR_TYPE_DATANULL = 1;
/**
* success=false
*/
int ERROR_TYPE_NOTSUCCESS = 2;
/**正在发起网络请求*/
boolean onNetWorkReqStart();
/**网络请求获取数据成功*/
void onNetWorkFail(BaseResBean resBean);
void onNetWorkResSuccess(T resBean);
}
| true |
ef2764b3a35c8576266171d87a21f87a4e3f2efe | Java | jwoolley/libgdx-learning | /core/src/com/mygdx/game/games/cardfight/player/Player.java | UTF-8 | 3,887 | 2.5625 | 3 | [] | no_license | package com.mygdx.game.games.cardfight.player;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.mygdx.game.games.cardfight.cards.*;
import com.mygdx.game.games.cardfight.ui.combat.CombatUi;
import com.mygdx.game.games.cardfight.ui.ScreenPosition;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Player {
public static final int STARTING_HAND_SIZE = 3;
public final List<AbstractCard> decklist;
public final List<AbstractCard> deck;
public final List<AbstractCard> hand;
public final List<AbstractCard> discardPile;
public final PlayerInfo playerInfo;
public Player() {
decklist = new ArrayList<>();
deck = new ArrayList<>();
hand = new ArrayList<>();
discardPile = new ArrayList<>();
playerInfo = new PlayerInfo();
}
// TODO: move to hand/cardgroup class
public void renderHand(SpriteBatch sb) {
final int screenXCenter = Gdx.graphics.getWidth() / 2;
// TODO: scale these values according to screen scale
switch (this.hand.size()) {
case 1:
this.hand.get(0).xPos = screenXCenter - AbstractCard.DEFAULT_WIDTH / 2;
this.hand.get(0).yPos = CombatUi.HAND_OFFSET_Y;
break;
case 2:
this.hand.get(0).xPos = screenXCenter - (AbstractCard.DEFAULT_WIDTH + CombatUi.HAND_SPACING / 2);
this.hand.get(0).yPos = CombatUi.HAND_OFFSET_Y;
this.hand.get(1).xPos = screenXCenter + CombatUi.HAND_SPACING / 2;
this.hand.get(1).yPos = CombatUi.HAND_OFFSET_Y;
break;
case 3:
this.hand.get(0).xPos = screenXCenter - AbstractCard.DEFAULT_WIDTH / 2;
this.hand.get(0).yPos = CombatUi.HAND_OFFSET_Y;
this.hand.get(1).xPos = screenXCenter - (int)(1.5 * AbstractCard.DEFAULT_WIDTH + CombatUi.HAND_SPACING);
this.hand.get(1).yPos = CombatUi.HAND_OFFSET_Y;
this.hand.get(2).xPos = screenXCenter + (int)(0.5f * AbstractCard.DEFAULT_WIDTH + CombatUi.HAND_SPACING);
this.hand.get(2).yPos = CombatUi.HAND_OFFSET_Y;
break;
default:
break;
}
List<AbstractCard> discardList = new ArrayList<>();
for (AbstractCard c : hand) {
if (c.discardFlag) {
discardList.add(c);
} else {
ScreenPosition nudge = c.getNudgeDimensions();
c.xPos += nudge.x;
c.yPos += nudge.y;
c.render(sb);
}
}
for (AbstractCard c : discardList) {
cardToDiscardPile(c);
}
}
private static final AbstractCardBack cardBack = new DefaultCardBack();
private static final int DRAW_PILE_X_POS = 32;
private static final int DRAW_PILE_Y_POS = 32 + CombatUi.INFO_BAR_HEIGHT;
public void renderDrawPile(SpriteBatch sb){
cardBack.xPos = DRAW_PILE_X_POS;
cardBack.yPos = DRAW_PILE_Y_POS;
cardBack.render(sb);
}
private static final int DISCARD_X_POS_OFFSET = 32;
private static final int DISCARD_X_POS = Gdx.graphics.getWidth() - (AbstractCardBack.DEFAULT_WIDTH + DISCARD_X_POS_OFFSET);
private static final int DISCARD_Y_POS = 32 + CombatUi.INFO_BAR_HEIGHT;
private static final float DISCARD_PILE_SCALE = 0.75f;
public void renderDiscard(SpriteBatch sb){
if (!discardPile.isEmpty()) {
AbstractCard topCard = discardPile.get(0);
topCard.xPos = DISCARD_X_POS;
topCard.yPos = DISCARD_Y_POS;
topCard.render(sb, DISCARD_PILE_SCALE);
}
}
public void cardToDiscardPile(AbstractCard card) {
if (hand.contains(card)) {
hand.remove(card);
}
discardPile.add(0, card);
}
public void dealHand() {
deck.clear();
deck.addAll(decklist);
Collections.shuffle(deck);
final List<AbstractCard> startingHand = new ArrayList<>();
startingHand.addAll(deck.subList(0,STARTING_HAND_SIZE));
deck.removeAll(startingHand);
this.hand.clear();
this.hand.addAll(startingHand);
}
}
| true |
3ff934fd80324365755a7d17ccfdd15700de369a | Java | qianyu12138/IM | /src/com/im/service/InfoService.java | UTF-8 | 163 | 1.664063 | 2 | [] | no_license | package com.im.service;
import com.im.domain.Info;
public interface InfoService {
public void save(Info info);
public Info getInfo(Integer iid);
}
| true |
324a72f747d448ab3484617ebcb2c0b6b06b9b44 | Java | robSumo/sumo-report-generator | /src/main/java/com/sumologic/report/generator/excel/ExcelWorkbookPopulator.java | UTF-8 | 2,747 | 2.34375 | 2 | [
"Apache-2.0"
] | permissive | package com.sumologic.report.generator.excel;
import com.sumologic.report.config.ReportConfig;
import com.sumologic.report.config.ReportSheet;
import com.sumologic.report.config.WorksheetConfig;
import com.sumologic.report.generator.ReportGenerationException;
import com.sumologic.service.SumoDataService;
import com.sumologic.service.SumoDataServiceFactory;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.WorkbookUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
@Service
public class ExcelWorkbookPopulator implements WorkbookPopulator {
private static final Log LOGGER = LogFactory.getLog(ExcelWorkbookPopulator.class);
@Autowired
private SumoDataServiceFactory sumoDataServiceFactory;
@Autowired
private WorksheetPopulator worksheetPopulator;
@Override
public void populateWorkbookWithData(ReportConfig reportConfig, Workbook workbook) throws ReportGenerationException {
try {
openWorkbookAndProcessSheets(reportConfig, workbook);
} catch (IOException e) {
LOGGER.error("unable to generate workbook!");
throw new ReportGenerationException(e);
}
}
private void openWorkbookAndProcessSheets(ReportConfig reportConfig, Workbook workbook) throws IOException {
LOGGER.debug("populating workbook");
processSheets(reportConfig, workbook);
LOGGER.debug("workbook populated");
}
private void processSheets(ReportConfig reportConfig, Workbook workbook) throws IOException {
SumoDataService sumoDataService = sumoDataServiceFactory.getSumoDataService(reportConfig);
for (ReportSheet reportSheet : reportConfig.getReportSheets()) {
WorksheetConfig config = new WorksheetConfig();
config.setReportConfig(reportConfig);
config.setReportSheet(reportSheet);
config.setSumoDataService(sumoDataService);
String worksheetName = WorkbookUtil.createSafeSheetName(reportSheet.getSheetName());
Sheet workbookSheet = workbook.getSheet(worksheetName);
config.setWorkbookSheet(workbookSheet);
LOGGER.info("populating sheet " + reportSheet.getSheetName());
worksheetPopulator.populateSheetWithData(config);
FileOutputStream fileOut = new FileOutputStream(reportConfig.getDestinationFile());
workbook.write(fileOut);
fileOut.close();
}
}
} | true |
a7ba4445e4c91ae6861bc470292893067a5782cd | Java | codecypherz/yugi | /yugi/src/yugi/servlet/game/JoinGameServlet.java | UTF-8 | 6,941 | 2.21875 | 2 | [] | no_license | package yugi.servlet.game;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;
import javax.jdo.PersistenceManager;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import yugi.Config;
import yugi.Config.CookieName;
import yugi.Config.HtmlParam;
import yugi.PMF;
import yugi.Screen;
import yugi.model.GameSession;
import yugi.service.GameService;
import yugi.servlet.ResponseStatusCode;
import yugi.servlet.ServletUtil;
import com.google.appengine.api.channel.ChannelService;
import com.google.appengine.api.channel.ChannelServiceFactory;
/**
* Servlet responsible for joining games.
*/
public class JoinGameServlet extends HttpServlet {
private static final long serialVersionUID = -2913910228648599370L;
private static final Logger logger = Logger.getLogger(JoinGameServlet.class.getName());
private static final ChannelService channelService = ChannelServiceFactory.getChannelService();
private static final GameService gameService = GameService.getInstance();
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws IOException {
// To join the game, you must have the game key of the game to join and
// specify the name you desire as a player.
String gameKey = Config.getGameKey(req);
String playerName = Config.getPlayerName(req);
// Make sure the parameters were passed and valid.
if (gameKey == null || playerName == null) {
res.setStatus(ResponseStatusCode.BAD_REQUEST.getCode());
return;
}
// Get the existing client ID, if one exists.
String existingClientId = getPlayerClientId(req);
// See if the game exists, then join it.
PersistenceManager pm = PMF.get().getPersistenceManager();
GameSession game = null;
String clientId = null;
try {
// TODO This lookup will fail if a user refreshes the page while
// waiting for another player to join. A better way to solve this
// might be to just delay game destruction on player disconnect. If
// we do this, then we'll have to flag the game to not be destroyed
// once a reconnect happens.
game = gameService.getGame(pm, gameKey);
if (game == null) {
res.setStatus(ResponseStatusCode.BAD_REQUEST.getCode());
return;
}
// See if the player is reconnecting.
if (isReconnecting(existingClientId, game)) {
logger.info("Player " + playerName +
" is reconnecting to " + game.getKeyAsString());
clientId = existingClientId;
} else {
// The player is not reconnecting, just doing a simple join.
// Make sure the game is not full.
if (isGameFull(game)) {
logger.warning("Player " + playerName + " tried to join " +
"the game with game key = " + gameKey + ", but it was full.");
// TODO Write an error page. Don't redirect to the landing.
redirectWithError(req, res, Config.Error.GAME_FULL, game);
return;
}
// Join the game and get the player ID that was generated.
clientId = join(game, playerName);
// Save the game since the state changed.
pm.makePersistent(game);
logger.info("Finished saving the game.");
}
} finally {
pm.close();
}
// Double check that the client ID was set.
if (clientId == null) {
logger.severe("Failed to set the client ID");
res.setStatus(ResponseStatusCode.INTERNAL_SERVER_ERROR.getCode());
return;
}
// Create the channel token to be used for this client.
String channelToken = channelService.createChannel(clientId);
// Write the response back to the client.
Map<HtmlParam, String> paramMap = new HashMap<HtmlParam, String>();
paramMap.put(HtmlParam.GAME_KEY, game.getKeyAsString());
paramMap.put(HtmlParam.CHANNEL_TOKEN, channelToken);
paramMap.put(HtmlParam.PLAYER_NAME, playerName);
res.addCookie(new Cookie(CookieName.PLAYER_ID.name(), clientId));
ServletUtil.writeScreen(req, res, Screen.GAME, paramMap);
}
/**
* Checks to see if the player identified by the client ID is reconnecting
* to the given game.
* @param clientId The client ID of the potentially reconnecting player.
* @param game The game to check against.
* @return True if the client is reconnecting.
*/
private boolean isReconnecting(String clientId, GameSession game) {
if (clientId == null) {
return false;
} else {
// Reconnecting if the client ID equals either existing one.
return clientId.equals(game.getPlayer1ClientId()) ||
clientId.equals(game.getPlayer2ClientId());
}
}
/**
* Checks to see if the game is full.
* @param game The game to check.
* @return True if the game is full, false otherwise.
*/
private boolean isGameFull(GameSession game) {
return game.getPlayer1ClientId() != null &&
game.getPlayer2ClientId() != null;
}
/**
* Joins the game and returns the player's client ID.
* @param game The game.
* @param playerName The name of the player.
* @return The generated client ID.
*/
private String join(GameSession game, String playerName) {
String gameKey = game.getKeyAsString();
if (game.getPlayer1ClientId() == null) {
logger.info("Player " + playerName + " joined as player 1.");
String clientId = gameKey + "1";
game.setPlayer1(playerName);
game.setPlayer1ClientId(clientId);
return clientId;
} else if (game.getPlayer2ClientId() == null) {
logger.info("Player " + playerName + " joined as player 2.");
String clientId = gameKey + "2";
game.setPlayer2(playerName);
game.setPlayer2ClientId(clientId);
return clientId;
}
// Error condition.
return null;
}
/**
* Gets the player's client ID from their cookie.
* @param req The request from which to fetch the cookie.
* @return The player's ID, if found.
*/
private String getPlayerClientId(HttpServletRequest req) {
Cookie[] cookies = req.getCookies();
if (cookies != null) {
for (Cookie cookie : cookies) {
if (cookie.getName().equalsIgnoreCase(CookieName.PLAYER_ID.name())) {
return cookie.getValue();
}
}
}
return null;
}
/**
* Redirects the client back to the landing page with the given error.
* @param resp The response that will be redirected.
* @param error The error that occurred.
* @param game The game that might or might not have been looked up.
* @throws IOException Thrown if the redirect fails.
*/
private void redirectWithError(HttpServletRequest req, HttpServletResponse resp,
Config.Error error, GameSession game)
throws IOException {
Map<Config.UrlParameter, String> params = new HashMap<Config.UrlParameter, String>();
params.put(Config.UrlParameter.ERROR, error.name());
if (game != null) {
params.put(Config.UrlParameter.GAME_NAME, game.getName());
}
resp.sendRedirect(ServletUtil.createUrl(req, Config.Servlet.LANDING, params));
}
}
| true |
f2cd42f682a3268688ddb5a1e64fa590faa4a14b | Java | multiversx/mx-deprecated-node-prototype | /elrond-core/src/main/java/network/elrond/p2p/model/P2PBroadcastChannelName.java | UTF-8 | 861 | 2.375 | 2 | [
"Apache-2.0"
] | permissive | package network.elrond.p2p.model;
public enum P2PBroadcastChannelName {
BLOCK("BLOCK", P2PChannelType.SHARD_LEVEL),
TRANSACTION("TRANSACTION", P2PChannelType.SHARD_LEVEL),
TRANSACTION_RECEIPT("TRANSACTION_RECEIPT", P2PChannelType.SHARD_LEVEL),
RECEIPT_BLOCK("RECEIPT_BLOCK", P2PChannelType.SHARD_LEVEL),
XRECEIPT_BLOCK("XRECEIPT_BLOCK", P2PChannelType.GLOBAL_LEVEL),
XTRANSACTION_BLOCK("XTRANSACTION_BLOCK", P2PChannelType.GLOBAL_LEVEL),
XRECEIPT("XRECEIPT", P2PChannelType.GLOBAL_LEVEL),;
private final String _name;
private final P2PChannelType _type;
P2PBroadcastChannelName(String name, P2PChannelType type) {
this._name = name;
this._type = type;
}
public P2PChannelType getType() {
return _type;
}
@Override
public String toString() {
return _name;
}
}
| true |
7baeef3c51510961c9f0c4886a96adc2bcaf82db | Java | vishtheshnu/275-raft-server | /src/main/java/coordination/InternalFileTransferImpl.java | UTF-8 | 7,433 | 2.03125 | 2 | [] | no_license | package coordination;
import com.cmpe275.generated.*;
import io.atomix.AtomixClient;
import io.atomix.catalyst.transport.Address;
import io.grpc.stub.StreamObserver;
import org.apache.log4j.Logger;
import raft.Config;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.concurrent.ExecutionException;
public class InternalFileTransferImpl extends clusterServiceGrpc.clusterServiceImplBase {
private HashMap<String, Object> storage;
private HeartbeatService heartbeat;
private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss");
Logger logger = Logger.getLogger(InternalFileTransferImpl.class);
public InternalFileTransferImpl(HashMap<String, Object> storage, HeartbeatService hbService){
super();
this.storage = storage;
heartbeat = hbService;
}
@Override
public void liveliness(Heartbeat request, StreamObserver<Heartbeat> responseObserver) {
Timestamp ts1 = new Timestamp(System.currentTimeMillis());
logger.debug("Method liveliness started at "+ ts1);
super.liveliness(request, responseObserver);
}
//Liveliness (This file sends the message to proxies)
//updateChunkData (From proxy to This Coordination server)
@Override
public void updateChunkData(ChunkData request, StreamObserver<ChunkDataResponse> responseObserver){
Timestamp ts1 = new Timestamp(System.currentTimeMillis());
logger.debug("Method updateChunkData started at "+ ts1);
String mapvalue = null;
mapvalue = (String)storage.get(request.getFileName()+"_"+request.getChunkId());
String[] arr = mapvalue.split(",");
arr[4]= "true";
ChunkDataResponse response = ChunkDataResponse.newBuilder()
.setChunkId(request.getChunkId())
.setIsAvailable(true)
.setFileName(request.getFileName())
.build();
responseObserver.onNext(response);
responseObserver.onCompleted();
Timestamp ts2 = new Timestamp(System.currentTimeMillis());
logger.debug("Method updateChunkData ended at "+ ts2);
logger.debug("Method updateChunkData execution time : "+ (ts2.getTime() - ts1.getTime()) + "ms");
}
//isFilePresent (From edge to This coordination server)
@Override
public void isFilePresent(FileQuery request, StreamObserver<FileResponse> responseObserver){
Timestamp ts1 = new Timestamp(System.currentTimeMillis());
logger.debug("Method isFilePresent started at "+ ts1);
String mapvalue = null;
mapvalue = (String) storage.get(request.getFileName()+"_0");
String[] arr = mapvalue.split(",");
FileResponse response = null;
if("true".equals(arr[4])){
response = FileResponse.newBuilder()
.setIsFound(true)
.build();
}else{
response = FileResponse.newBuilder()
.setIsFound(false)
.build();
}
responseObserver.onNext(response);
responseObserver.onCompleted();
Timestamp ts2 = new Timestamp(System.currentTimeMillis());
logger.debug("Method isFilePresent ended at "+ ts2);
logger.debug("Method isFilePresent execution time : "+ (ts2.getTime() - ts1.getTime()) + "ms");
}
//uploadFileChunk (From client to proxy; not needed here!)
// initiateFileUpload
@Override
public void initiateFileUpload(com.cmpe275.generated.FileUploadRequest request,
io.grpc.stub.StreamObserver<com.cmpe275.generated.FileResponse> responseObserver) {
Timestamp ts1 = new Timestamp(System.currentTimeMillis());
logger.debug("Method initiateFileUpload started at "+ ts1);
System.out.println("initiateFileUpload Method arrived");
ArrayList<ChunkData> chunks = new ArrayList<ChunkData>();
ArrayList<String> proxies = new ArrayList<String>();
ArrayList<String> liveProxies = new ArrayList<String>();
String fileName = request.getFileName();
long fileSize = request.getSize();
long maxChunks = request.getMaxChunks();
long requestId = request.getRequestId();
for(Address addr : Config.proxyAddresses){
proxies.add(addr.host()+":"+addr.port());
}
/**
* For tests
*/
// proxies.add("localhost:8080");
// proxies.add("localhost:8081");
// proxies.add("localhost:8082");
// proxies.add("localhost:8083");
// proxies.add("localhost:8084");
System.out.println("Creating a map");
storage.put("bar", "Hello World!");
String value = "";
System.out.println("Retrieved value of bar: "+value);
FileResponse.Builder responseBuilder = FileResponse.newBuilder();
//Check if the file is already present
if( value != null) {
responseBuilder.setIsFound(true); // Does not return the field to Client if set false
} else {
boolean[] proxyStatus = heartbeat.getProxyStatus();
/**
* For tests
*/
// boolean[] proxyStatus = { true, false, true, true, false } ;
int proxyStatusSize = proxyStatus.length;
for(int index=0 ; index<proxyStatusSize; index++) {
if(proxyStatus[index]) {
liveProxies.add(proxies.get(index));
}
}
int n = liveProxies.size();
if(n== 0) {
System.out.println("Cannot upload right now! No live proxies available.");
throw new ArithmeticException();
} else {
for(int i=0; i < maxChunks; i++){
String uniqueId = fileName + "_" + Integer.toString(i);
int hash = uniqueId.hashCode();
String allotedProxy = liveProxies.get(Math.abs(hash % n));
String[] values = allotedProxy.split(":");
String ip = values[0];
String port = values[1];
System.out.println("ip: " + ip);
System.out.println("port: " + port);
String mapObject = uniqueId + "," + fileName + ","
+ Integer.toString(i) + "," + Long.toString(maxChunks)
+ "," + "false" + "," + ip + "," + port;
System.out.println("Creating a map");
storage.put(uniqueId, mapObject);
ChunkData eachChunk = ChunkData.newBuilder()
.setIsAvailable(false)
.setPort(port)
.setMaxChunks(maxChunks)
.setFileName(fileName)
.setChunkId((long)i) // Does not return this field to Client if set to 0
.setIp(ip)
.build();
chunks.add(eachChunk);
}
responseBuilder.setIsFound(false) // Does not return the field to Client if set false
.setRequestId(requestId)
.addAllChunks(chunks);
}
}
FileResponse response = responseBuilder.build();
responseObserver.onNext(response);
responseObserver.onCompleted();
Timestamp ts2 = new Timestamp(System.currentTimeMillis());
logger.debug("Method initiateFileUpload ended at "+ ts2);
logger.debug("Method initiateFileUpload execution time : "+ (ts2.getTime() - ts1.getTime()) + "ms");
}
}
| true |
864248c87172fcc6b3238e652c8b977e9a4e8ffb | Java | verbeen/JFS | /JFSData/src/main/java/jfs/data/dataobjects/helpers/Pair.java | UTF-8 | 242 | 2.453125 | 2 | [] | no_license | package jfs.data.dataobjects.helpers;
/**
* Created by lpuddu on 17-11-2015.
*/
public class Pair<T, U> {
public T key;
public U value;
public Pair(T key, U value) {
this.key = key;
this.value = value;
}
}
| true |
b79709072aad3483e64d2bd16cc4c26e5d04749e | Java | tzuyichao/java-basic | /java-basic/src/main/java/brute/ImplementTrie.java | UTF-8 | 1,548 | 3.5 | 4 | [] | no_license | package brute;
/**
* 208. Implement Trie (Prefix Tree)
*
* Runtime: 51 ms, faster than 65.15% of Java online submissions for Implement Trie (Prefix Tree).
* Memory Usage: 68 MB, less than 25.32% of Java online submissions for Implement Trie (Prefix Tree).
*/
public class ImplementTrie {
class TrieNode {
TrieNode[] child = new TrieNode[26];
boolean isWord;
}
class Trie {
TrieNode root;
public Trie() {
root = new TrieNode();
}
public void insert(String word) {
TrieNode p = root;
for(char c : word.toCharArray()) {
int idx = c - 'a';
if(p.child[idx] == null) {
p.child[idx] = new TrieNode();
}
p = p.child[idx];
}
p.isWord = true;
}
public boolean search(String word) {
TrieNode p = root;
for(char c: word.toCharArray()) {
int idx = c - 'a';
if(p.child[idx] == null) {
return false;
}
p = p.child[idx];
}
return p.isWord;
}
public boolean startsWith(String prefix) {
TrieNode p = root;
for(char c: prefix.toCharArray()) {
int idx = c - 'a';
if(p.child[idx] == null) {
return false;
}
p = p.child[idx];
}
return true;
}
}
}
| true |
6b14d9bbefdb644d80660494d8ba1f433c9eda70 | Java | D-MGaikwad/All_Assignments | /Java_Assignment_2_Q7/Candy.java | UTF-8 | 291 | 2.984375 | 3 | [] | no_license |
public class Candy extends DessertItem{
int quantity;
public Candy(int q)
{
quantity=q;
}
public float getCost()
{
float cost=quantity*5f*60f;
float tax=(5f/100f)*cost;
float total_cost=cost+tax;
return total_cost;
}
} | true |
a03c5fd3d3da00c47edab37760bfb238cb803ac0 | Java | dustincheung/KanbanApp | /src/main/java/kanbanapp/KanbanAppApplication.java | UTF-8 | 361 | 1.726563 | 2 | [] | no_license | /*
* Main class that starts Spring Framework
*/
package kanbanapp;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class KanbanAppApplication {
public static void main(String[] args) {
SpringApplication.run(KanbanAppApplication.class, args);
}
}
| true |
4b3a1dbd16e74f219a70c21be6575833ef9111fa | Java | hanahmily/jictorinox | /src/main/java/org/jictorinox/pandc/ProductorTask.java | UTF-8 | 2,602 | 2.609375 | 3 | [] | no_license | package org.jictorinox.pandc;
import org.apache.log4j.NDC;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
/**
* 能力框架
* <p/>
* Date: 13-9-12
* Time: 上午10:23
*
* @auth gaohongtao
*/
public class ProductorTask<GOODS> implements Runnable {
private static final Logger log = LoggerFactory.getLogger(ProductorTask.class);
private final int index;
private final Channel<GOODS> channel;
private final Productor<GOODS> productor;
private final String ndc;
public ProductorTask(int index, Productor<GOODS> productor, Channel<GOODS> channel, String ndc) {
this.index = index;
this.channel = channel;
this.productor = productor;
this.ndc = ndc;
}
private static void waitNormal() {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
}
}
@Override
public void run() {
NDC.push(ndc + "-ProductorTask-" + index);
boolean isSubmitTask = false;
try {
while (channel.isOpen()) {
if (channel.canSupply()) {
List<GOODS> goods = productor.product();
if (goods != null) {
if (log.isDebugEnabled()) {
log.debug("提交产品{}个", goods.size());
}
for (GOODS good : goods) {
channel.supply(good);
}
} else {
if (log.isDebugEnabled()) {
log.debug("不再提供商品");
}
//返回null说明没有要处理的,而且不想继续
channel.close();
}
Thread.yield();
} else {
if (log.isDebugEnabled()) {
log.debug("超市货架满,等待");
}
waitNormal();
}
}
} catch (Exception e) {
log.error("出现异常", e);
isSubmitTask = productor.exceptionAndIsContinue(e);
} finally {
productor.exitHook();
if (log.isDebugEnabled()) {
log.debug("停止生产");
}
NDC.remove();
if (isSubmitTask) {
if (log.isDebugEnabled()) {
log.error("重新启动");
}
channel.submitTask(this);
}
}
}
}
| true |
83438d9d609c6acafaa0a48f426933e09f71a7f2 | Java | LionDevelop/wanxin-p2p | /wanxinp2p-transaction-service/src/main/java/com/wanxin/transaction/message/TransactionListenerImpl.java | UTF-8 | 2,525 | 2.21875 | 2 | [
"Apache-2.0"
] | permissive | package com.wanxin.transaction.message;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.wanxin.common.domain.ProjectCode;
import com.wanxin.transaction.entity.Project;
import com.wanxin.transaction.mapper.ProjectMapper;
import com.wanxin.transaction.service.ProjectService;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;
/**
* @author yuelimin
* @version 1.0.0
* @since 1.8
*/
@Component
@RocketMQTransactionListener(txProducerGroup = "PID_START_REPAYMENT")
public class TransactionListenerImpl implements RocketMQLocalTransactionListener {
@Autowired
private ProjectService projectService;
@Autowired
private ProjectMapper projectMapper;
/**
* 执行本地事务
*
* @param message
* @param o
* @return
*/
@Override
public RocketMQLocalTransactionState executeLocalTransaction(Message message, Object o) {
// 解析消息
final JSONObject jsonObject = JSON.parseObject(new String((byte[]) message.getPayload()));
Project project = JSONObject.parseObject(jsonObject.getString("project"), Project.class);
// 执行本地事务
Boolean result = projectService.updateProjectStatusAndStartRepayment(project);
// 返回执行结果
if (result) {
return RocketMQLocalTransactionState.COMMIT;
} else {
return RocketMQLocalTransactionState.ROLLBACK;
}
}
/**
* 事务回查
*
* @param message
* @return
*/
@Override
public RocketMQLocalTransactionState checkLocalTransaction(Message message) {
// 解析消息
final JSONObject jsonObject = JSON.parseObject(new String((byte[]) message.getPayload()));
Project project = JSONObject.parseObject(jsonObject.getString("project"), Project.class);
// 查询标的状态
Project pro = projectMapper.selectById(project.getId());
// 返回结果
if (pro.getProjectStatus().equals(ProjectCode.REPAYING.getCode())) {
return RocketMQLocalTransactionState.COMMIT;
} else {
return RocketMQLocalTransactionState.ROLLBACK;
}
}
}
| true |
ccb2a8e2882243f9184dee2ea7f246f9b89abb90 | Java | taphuong/iRM-Online | /app/src/main/java/org/irestaurant/irm/DeviceListActivity.java | UTF-8 | 7,134 | 2.078125 | 2 | [] | no_license | package org.irestaurant.irm;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import org.irestaurant.irm.Database.BluetoothService;
import java.util.Set;
import static org.irestaurant.irm.BuildConfig.DEBUG;
public class DeviceListActivity extends AppCompatActivity {
protected static final String TAG = "TAG";
private BluetoothAdapter mBluetoothAdapter;
private ArrayAdapter<String> mPairedDevicesArrayAdapter;
private ArrayAdapter<String> mNewDevicesArrayAdapter;
Button scanButton;
ProgressBar pgbScanning;
private BluetoothService mService = null;
public static final String EXTRA_DEVICE_NAME = "device_name";
public static final String EXTRA_DEVICE_ADDRESS = "device_address";
private ArrayAdapter<String> newDeviceAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.activity_device_list);
setResult(Activity.RESULT_CANCELED);
pgbScanning = findViewById(R.id.pgb_scanning);
mPairedDevicesArrayAdapter = new ArrayAdapter<String>(this, R.layout.device_name);
mNewDevicesArrayAdapter = new ArrayAdapter<String>(this, R.layout.device_name);
ListView mPairedListView = (ListView) findViewById(R.id.paired_devices);
mPairedListView.setAdapter(mPairedDevicesArrayAdapter);
mPairedListView.setOnItemClickListener(mDeviceClickListener);
// Find and set up the ListView for newly discovered devices
ListView newDevicesListView = (ListView) findViewById(R.id.new_devices);
newDevicesListView.setAdapter(mNewDevicesArrayAdapter);
newDevicesListView.setOnItemClickListener(mDeviceClickListener);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
Set<BluetoothDevice> mPairedDevices = mBluetoothAdapter.getBondedDevices();
// Register for broadcasts when a device is discovered
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
this.registerReceiver(mReceiver, filter);
// Register for broadcasts when discovery has finished
filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
this.registerReceiver(mReceiver, filter);
if (mPairedDevices.size() > 0) {
findViewById(R.id.title_paired_devices).setVisibility(View.VISIBLE);
for (BluetoothDevice mDevice : mPairedDevices) {
mPairedDevicesArrayAdapter.add(mDevice.getName() + "\n" + mDevice.getAddress());
}
} else {
String mNoDevices = getResources().getText(R.string.none_paired).toString();
mPairedDevicesArrayAdapter.add(mNoDevices);
}
scanButton = (Button) findViewById(R.id.button_scan);
scanButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
doDiscovery();
v.setVisibility(View.GONE);
pgbScanning.setVisibility(View.VISIBLE);
}
});
}
private void doDiscovery() {
if (DEBUG) Log.d(TAG, "doDiscovery()");
// Indicate scanning in the title
setProgressBarIndeterminateVisibility(true);
setTitle(R.string.scanning);
// Turn on sub-title for new devices
findViewById(R.id.title_new_devices).setVisibility(View.VISIBLE);
// If we're already discovering, stop it
if (mBluetoothAdapter.isDiscovering()) {
mBluetoothAdapter.cancelDiscovery();
}
mNewDevicesArrayAdapter.clear();//20160617
// mPairedDevicesArrayAdapter.clear();//20160617
// Request discover from BluetoothAdapter
mBluetoothAdapter.startDiscovery();
}
@Override
protected void onDestroy() {
super.onDestroy();
if (mBluetoothAdapter != null) {
mBluetoothAdapter.cancelDiscovery();
}
}
private AdapterView.OnItemClickListener mDeviceClickListener = new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> mAdapterView, View mView, int mPosition, long mLong) {
String info = ((TextView) mView).getText().toString();
String address = info.substring(info.length() - 17);
String name = info.substring(0,info.length()-17);
Intent intent = new Intent();
intent.putExtra(EXTRA_DEVICE_NAME, name);
intent.putExtra(EXTRA_DEVICE_ADDRESS, address);
setResult(RESULT_OK, intent);
finish();
}
};
// The BroadcastReceiver that listens for discovered devices and changes the title when discovery is finished
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
//Device found
if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
mNewDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
}
else if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)) {
String connected = device.getName() + "\n" + device.getAddress();
Toast.makeText(context, connected, Toast.LENGTH_SHORT).show();
//Device is now connected
}
else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
//Done searching
Toast.makeText(context, "Đã quét xong", Toast.LENGTH_SHORT).show();
if (mNewDevicesArrayAdapter.getCount() == 0) {
mNewDevicesArrayAdapter.add("Không tìm thấy thiết bị");
}
}
else if (BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED.equals(action)) {
//Device is about to disconnect
}
else if (BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action)) {
//Device has disconnected
Toast.makeText(context, "Chưa kết nối máy in", Toast.LENGTH_SHORT).show();
}
}
}
};
}
| true |
a913d8a1883a7b9305aafbf03d30484e5b585425 | Java | gzuri/anime-api | /src/main/java/com/goranzuri/anime/service/AnimeUpdateService.java | UTF-8 | 3,735 | 2.765625 | 3 | [] | no_license | package com.goranzuri.anime.services;
import com.goranzuri.anime.db.dao.AnimeDAO;
import com.goranzuri.anime.db.entities.Anime;
import com.goranzuri.anime.exceptions.StorageNotFoundException;
import java.util.*;
import java.util.stream.Collectors;
/**
* Created by gzuri on 21.01.2017..
*/
public class AnimeUpdateService {
private AnimeDAO animeDAO;
private List<Anime> animeInSystem;
private List<Anime> recordedAnimeOnStorage;
private int storageId;
public AnimeUpdateService(AnimeDAO animeDAO, int storageId){
this.animeDAO = animeDAO;
this.storageId = storageId;
}
public void updateListBasedOnStorageContent(List<String> currentAnimeOnStorage) throws StorageNotFoundException {
animeInSystem = animeDAO.findAll();
recordedAnimeOnStorage = animeDAO.findAllOnStorage(storageId);
processNewAnime(currentAnimeOnStorage);
}
void processNewAnime(List<String> currentAnimeOnStorage) throws StorageNotFoundException {
List<String> existingAnimeOnStorage = recordedAnimeOnStorage.stream()
.map(x->x.getNameOnDisk()).collect(Collectors.toList());
List<String> tempCurrentListOnStorage = new ArrayList<>(currentAnimeOnStorage);
tempCurrentListOnStorage.removeAll(existingAnimeOnStorage);
for (String newItem : tempCurrentListOnStorage){
addNewAnime(newItem);
}
}
void addNewAnime(String nameOnDisk) throws StorageNotFoundException {
Optional<Anime> localAnime = animeInSystem.stream()
.filter(x -> x.getNameOnDisk().equals(nameOnDisk))
.findFirst();
Integer animeId = null;
if (!localAnime.isPresent()){
Anime insertAnime = new Anime();
insertAnime.setDateAdded(new Date());
insertAnime.setNameOnDisk(nameOnDisk);
insertAnime.setName(nameOnDisk);
animeDAO.create(insertAnime);
animeId = insertAnime.getAnimeId();
}else{
animeId = localAnime.get().getAnimeId();
}
saveLocationOfAnime(animeId.intValue());
}
void saveLocationOfAnime(int animeId) throws StorageNotFoundException {
animeDAO.saveOnStorage(animeId, this.storageId);
}
public static List<String> filterNewNames(List<String> oldList, List<String> newList){
List<String> filteredNewStrings = new ArrayList<String>();
for (String currentItem : newList){
if (!oldList.contains(currentItem)){
filteredNewStrings.add(currentItem);
}
}
return filteredNewStrings;
}
static List<String> filterNewAnime(List<Anime> recordedAnimeOnStorage, List<String> currentAnimeOnStorage){
Map<String, Integer> recordedAnimeOnStorageMap = new HashMap<String, Integer>();
for (Anime recordedAnimeOnStorageItem : recordedAnimeOnStorage){
recordedAnimeOnStorageMap.put(recordedAnimeOnStorageItem.getNameOnDisk(), recordedAnimeOnStorageItem.getAnimeId());
}
List<String> filteredAnimeOnStorage = new ArrayList<String>();
for (String currentAnimeOnStorageItem : currentAnimeOnStorage){
if (recordedAnimeOnStorageMap.containsKey(currentAnimeOnStorageItem)){
recordedAnimeOnStorageMap.remove(currentAnimeOnStorageItem);
}else{
filteredAnimeOnStorage.add(currentAnimeOnStorageItem);
}
}
return filteredAnimeOnStorage;
}
void addAnimeOnStorage(String animeNameOnStorage, int storageId){
}
void removeThoseNotOnStorage(Map<String, Integer> recordedAnimeOnStorage, List<String> currentAnimeOnStorage){
}
}
| true |
f7a18d184034445fbcb701b10d0e78a0532f1915 | Java | AgNO3/code | /runtime/eventlog/eu.agno3.runtime.eventlog/src/main/java/eu/agno3/runtime/eventlog/AuditContext.java | UTF-8 | 549 | 2.046875 | 2 | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | /**
* © 2015 AgNO3 Gmbh & Co. KG
* All right reserved.
*
* Created: 29.04.2015 by mbechler
*/
package eu.agno3.runtime.eventlog;
/**
* @author mbechler
* @param <T>
*
*/
public interface AuditContext <T extends AuditEventBuilder<T>> extends AutoCloseable {
/**
*
* @return the builder
*/
T builder ();
/**
* {@inheritDoc}
*
* @see java.lang.AutoCloseable#close()
*/
@Override
public void close ();
/**
* Supress the generated message
*/
void suppress ();
}
| true |
f608ae93992fd7010884a9f287f3843f13f45fae | Java | AbsolutelySaurabh/parkinglot_squadstack | /src/main/java/io/squadstack/parkinglot/input/ProcessorImpl.java | UTF-8 | 1,453 | 2.734375 | 3 | [] | no_license | /**
* @author AbsolutelySaurabh
*/
package io.squadstack.parkinglot.input;
import io.squadstack.parkinglot.constants.Constant;
import io.squadstack.parkinglot.model.Car;
import io.squadstack.parkinglot.service.ParkingService;
public class ProcessorImpl implements Processor {
private ParkingService parkingService;
public void setService(ParkingService parkingService) {
this.parkingService = parkingService;
}
public void execute(String input) {
//execute input
String inputs[] = input.split(" ");
String key = inputs[0];
if (Constant.CREATE_PARKING_LOT.equals(key)) {
int capacity = Integer.parseInt(inputs[1]);
parkingService.createParkingLot(capacity);
} else if (Constant.PARK.equals(key)) {
parkingService.park(new Car(inputs[1], Integer.parseInt(inputs[3])));
} else if (Constant.LEAVE.equals(key)) {
parkingService.unPark(Integer.parseInt(inputs[1]));
} else if (Constant.SLOT_NUMBER_FOR_CAR_WITH_NUMBER.equals(key)) {
parkingService.getSlotNoForRegNo(inputs[1]);
} else if (Constant.SLOT_NUMBERS_FOR_DRIVER_OF_AGE.equals(key)) {
parkingService.getSlotNosForAge(Integer.parseInt(inputs[1]));
} else if (Constant.VEHICLE_REGISTRATION_NO_FOR_DRIVER_OF_AGE.equals(key)) {
parkingService.getRegNosForAge(Integer.parseInt(inputs[1]));
}
}
}
| true |
4a4cbc97005c7c7432b120f4cc4bf690a5952662 | Java | camarapaula/Aperam-ZSAPIM43 | /java/src/com/syclo/sap/component/zaperam/stephandler/Z_TransferStepHandler.java | UTF-8 | 1,613 | 2.3125 | 2 | [] | no_license | package com.syclo.sap.component.zaperam.stephandler;
import java.util.GregorianCalendar;
import com.syclo.agentry.AgentryException;
import com.syclo.sap.BAPIFactory;
import com.syclo.sap.SAPObjectFactory;
import com.syclo.sap.StepHandler;
import com.syclo.sap.User;
import com.syclo.sap.component.zaperam.bapi.Z_MaterialDocumentCreateBAPI;
import com.syclo.sap.component.zaperam.object.MaterialDocumentItem;
/*This Step handler class is called by the Z_TransferSteplet class.
* This Step handler class is utilized to invoke the BAPI class.
* BAPI instance is created here and the standard run method is called.
* */
public class Z_TransferStepHandler extends StepHandler{
public Z_TransferStepHandler() {
}
public Z_TransferStepHandler(User user) {
super(user);
}
/*
* This method will be used to invoke the BAPI class, Z_MaterialDocumentCreateBAPI,
* Creates the SAPObject instance for the MaterialDocumentItem object.
*/
public void transferItem() throws AgentryException {
this._log.entry();
try {
MaterialDocumentItem obj = (MaterialDocumentItem) SAPObjectFactory.create(
this._user.getSAPObject("Z_MaterialDocumentItem"), new Class[] { User.class },
new Object[] { this._user });
Z_MaterialDocumentCreateBAPI bapi = (Z_MaterialDocumentCreateBAPI) BAPIFactory.create(
"Z_MaterialDocumentCreateBAPI",
new Class[] { User.class, GregorianCalendar.class },
new Object[] { this._user, new GregorianCalendar() });
bapi.run(obj);
bapi.processResults();
} catch (Exception e) {
this._user.rethrowException(e, true);
}
this._log.exit();
}
}
| true |
977a0aeb666bd702f9db4509c8e6fca1368a3630 | Java | ButItWorks/PgAr2021_ButItWorks_TamaGolem | /src/it/butitworks/model/Giocatore.java | UTF-8 | 2,203 | 3.3125 | 3 | [] | no_license | package it.butitworks.model;
import java.util.ArrayList;
public class Giocatore {
//attributi
private String nome;
private ArrayList<TamaGolem> squadra = new ArrayList<>();
private TamaGolem tamaGolemInCampo;
//costruttori
public Giocatore() { }
public Giocatore(String nome, ArrayList<TamaGolem> squadra) {
this.nome = nome;
this.squadra = squadra;
this.tamaGolemInCampo = squadra.get(0);
}
//getters & setters
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public ArrayList<TamaGolem> getSquadra() {
return squadra;
}
public void setSquadra(ArrayList<TamaGolem> squadra) {
this.squadra = squadra;
}
public TamaGolem getTamaGolemInCampo() {
return tamaGolemInCampo;
}
public void setTamaGolemInCampo(TamaGolem tamaGolemInCampo) {
this.tamaGolemInCampo = tamaGolemInCampo;
}
/**
* metodo che controlla quanti it.butitworks.model.TamaGolem sono vivi
* @return il numero di it.butitworks.model.TamaGolem vivi
*/
public int getNumeroGolemVivi() {
int numeroGolemVivi = 0;
for (TamaGolem golem : squadra) {
if(!golem.isMorto()) {
numeroGolemVivi ++;
}
}
return numeroGolemVivi;
}
//questo metodo a cosa serve??
public boolean scambiaGolemInCampo(String nomeTamaGolem) {
boolean trovato = false;
TamaGolem golemCercato = new TamaGolem();
for (TamaGolem golem : this.squadra) {
if(golem.getNome().equals(nomeTamaGolem)) {
trovato = true;
golemCercato = golem;
}
}
if(trovato && !golemCercato.isMorto()) {
this.setTamaGolemInCampo(golemCercato);
return true;
}
return false;
}
/**
* @return true se la squadra è esausta
*/
public boolean isSquadraEsausta() {
for (TamaGolem golem : this.getSquadra()) {
if(!golem.isMorto()) {
return false;
}
}
return true;
}
} | true |
13458b4de5a3aba165c17d79fe62b1b362f62ee4 | Java | KRMKGOLD/Jeju-HackaTon | /app/src/main/java/com/example/hackatonproject/data/JejuService.java | UTF-8 | 519 | 1.8125 | 2 | [] | no_license | package com.example.hackatonproject.data;
import com.google.gson.JsonObject;
import retrofit2.Call;
import retrofit2.http.Body;
import retrofit2.http.GET;
import retrofit2.http.POST;
import java.util.List;
public interface JejuService {
@GET("/cctv")
Call<List<Repo>> sendCCTVRequest();
@POST("/cctv")
Call<JsonObject> cctvData(@Body JsonObject jsonArray);
@GET("/lamp")
Call<List<Repo>> sendLightRequest();
@POST("/lamp")
Call<JsonObject> lightData(@Body JsonObject jsonArray);
} | true |
c26d2db116b02d5e54416adb03aae4e682d4519a | Java | Todd-Hiram/HiramTodd_CIT360 | /JUNIT_WORKSPACE/src/TestRunner.java | UTF-8 | 4,538 | 3.8125 | 4 | [] | no_license | import org.junit.jupiter.api.Test;
import static org.junit.Assert.assertThat;
import static org.junit.jupiter.api.Assertions.*;
public class TestRunner {
class JUnitTest {
/*This is testing our addingNumbers method from JUnit
* to make use that the method runs properly.
* We are creating a new instance of our JUnit class
* and It is saying that if that excepted result
* matches the actual result then the test
* is successful.*/
@Test
void addingTest() {
JUnit JUnit = new JUnit();
int expected = 12;
int actual = JUnit.addNumbers(4, 8);
assertEquals(expected, actual);
}
/*Here we are making sure that our Array matches what
* it is supposed to contain. In our example, the Array
* only supposed to contain the Cities in Skyrim. If something
* is added that isn't a Skyrim City or one of the Cities is
* missing, the test will fail because the expected and the actual
* don't match. */
@Test
void skyrimArray() {
String[] expected = {"Falkreath", "Riften", "Whiterun", "Windhelm", "Solitude", "Markarth", "Morthal", "Dawnstar", "Winterhold"};
String[] actual = {"Falkreath", "Riften", "Whiterun", "Windhelm", "Solitude", "Markarth", "Morthal", "Dawnstar", "Winterhold"};
assertArrayEquals(expected, actual);
}
/*Here we are creating a new instance of
* our JUnitboolean and testing that the
* greaterThan method returns false. If the
* numbers entered into the assertFalse produce
* a true, the test will fail.*/
@Test
void greaterThan() {
JUnit JUnitboolean = new JUnit();
assertFalse(JUnitboolean.greaterThan(3, 4));
}
/*In this test, we are creating a new instance
* of our JUnitHashMap and making sure that the keys
* in our HashMap all have values. If I were to put
* a Jarl in to our HashMap and not include the City
* they rule over, the test would fail. Similarly,
* if I enter a city that is not in my HashMap, that
* test will also fail. */
@Test
void SkyrimJarl() {
JUnit JUnitHashMap = new JUnit();
assertNotNull(JUnitHashMap.SkyrimJarl("Riften"));
}
/*Here we are creating a new instance of our
* JUnitCourses that reference our HashMap for
* our list of Spring Courses. This test is to
* make sure that each of our keys are referencing
* different objects. We can't have a CIT262 courses
* mistakenly referring to an Object Oriented software
* development course. If the keys are referencing the
* same object, the test will fail. */
@Test
void SpringCourses() {
JUnit JUnitCourses = new JUnit();
assertNotSame(JUnitCourses.SpringCourses("CIT262"), JUnitCourses.SpringCourses("CIT360"));
}
/*Here we are creating a new instance of our JUnit
* FallCourses that reference our HashMap for my list
* of Fall courses. This test is going to make sure
* that that key we enter is null. If the course number
* I enter is not null then it will fail. Think of it this
* way. I want to make sure the course code "CIT360" is null
* in my Fall Semester course list because I want to make sure
* I pass this class the first time and don't have to take it
* again. If this course number is Null that means I get to
* graduate in December however, if it is not null, that means
* I will not graduate in December and I will have to take
* the course again. We want this to be null!*/
@Test
void FallCourses() {
JUnit JUnitFallCourses = new JUnit();
assertNull(JUnitFallCourses.FallCourses("CIT360"));
}
/*Here we are testing to make sure that the
* two value salesPrice and homeAppraisal
* are the same. If they are not the same
* the test will fail. We want to make
* that the Appraisal and the salePrice
* on the home are the same or we can
* run into trouble when we go to sell
* house.*/
@Test
void appraisal() {
String salePrice = "279900";
String homeAppraisal = "279900";
assertSame(salePrice, homeAppraisal);
}
/*Here we are creating a new instance
* of our JunitlessThanboolean to check
* and make sure that number1 is less than number2
* it is pulling this information from out lessThan
* method in our JUnit class.*/
@Test
void lessThan() {
JUnit JUnitlessThanboolean = new JUnit();
assertTrue(JUnitlessThanboolean.lessThan(3, 4));
}
/*Here we are testing to make sure that the
* two parameters are the same.If they are not
* the same, the test will fail.*/
@Test
void hello() {
assertThat("Hello", is("Hello"));
}
}
}
| true |
ae5de13ac68b528b55ca053c060e586c3f8e7ab9 | Java | Eduworks/ec | /asd.europe.org.s_series/src/main/java/s3000l/MessageCreationDate.java | UTF-8 | 567 | 1.890625 | 2 | [
"Apache-2.0"
] | permissive | /**
*
* Generated by JaxbToStjsAssimilater.
* Assimilation Date: Thu Sep 12 10:06:02 CDT 2019
*
**/
package s3000l;
import org.cassproject.schema.general.EcRemoteLinkedData;
import org.stjs.javascript.Date;
public class MessageCreationDate extends EcRemoteLinkedData {
protected Date dateTime;
public Date getDateTime() {
return dateTime;
}
public void setDateTime(Date value) {
this.dateTime = value;
}
public MessageCreationDate() {
super("http://www.asd-europe.org/s-series/s3000l", "MessageCreationDate");
}
}
| true |
c453eca266c49054ddba6f27fe63a4d088500bf0 | Java | jacobmh98/Fagprojekt | /src/controller/Controller.java | UTF-8 | 1,558 | 2.890625 | 3 | [] | no_license | package controller;
import model.Graph;
import model.Piece;
import view.PuzzleRunner;
import java.util.ArrayList;
public class Controller {
private static Controller controller = new Controller();;
private ArrayList<Piece> boardPieces = new ArrayList<Piece>();
private final int[] BOARD_SIZE = new int[2];
private int rows;
private int columns;
private Graph graph;
private int solveSpeed;
private PuzzleRunner puzzleRunner;
public Controller() {
graph = new Graph();
}
// Getter methods for the fields in the Controller
// Written by Jacob & Oscar
public ArrayList<Piece> getBoardPieces() { return this.boardPieces; }
public Graph getGraph() { return this.graph; }
public static Controller getInstance() { return controller; }
public int[] getBoardSize(){ return this.BOARD_SIZE; }
public int getRows(){return rows;}
public int getColumns(){return columns;}
public int getSolveSpeed(){return solveSpeed;}
// Setter methods for the fields in the Controller
// Written by Jacob & Oscar
public void setPuzzleRunner(PuzzleRunner puzzleRunner){this.puzzleRunner = puzzleRunner;}
public void setBoardPieces(ArrayList<Piece> boardPieces) {
this.boardPieces = boardPieces;
}
public void setBoardSize(int width, int height) { BOARD_SIZE[0] = width; BOARD_SIZE[1] = height; }
public void setRows(int rows){this.rows = rows;}
public void setColumns(int columns){this.columns = columns;}
public void setSolveSpeed(int speed){solveSpeed = speed;}
public void setSolvedText(String text){ puzzleRunner.setIsSolvedLabelText(text);}
}
| true |
0d119d7d4c0b790e214c1d8d36cc38a842f07af8 | Java | mdvv-hub/mdvv | /src/main/java/com/mdvvproject/mdvv/util/TestRedis.java | UTF-8 | 3,441 | 2.703125 | 3 | [] | no_license | package com.mdvvproject.mdvv.util;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisCluster;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
public class TestRedis {
// public static void main(String[] args) throws IOException {
// GenericObjectPoolConfig config = new GenericObjectPoolConfig();
// // 最大连接数
// config.setMaxTotal(8);
// // 最大空闲数
// config.setMaxIdle(100);
// // 最大允许等待时间,如果超过这个时间还未获取到连接,则会报JedisException异常:
// // Could not get a resource from the pool
// config.setMaxWaitMillis(7000);
//
// Set<HostAndPort> jedisClusterNode = new HashSet<HostAndPort>();
//// jedisClusterNode.add(new HostAndPort("59.110.237.247", 7001));
// jedisClusterNode.add(new HostAndPort("59.110.237.247", 7001));
//// jedisClusterNode.add(new HostAndPort("59.110.237.247", 7003));
//// jedisClusterNode.add(new HostAndPort("59.110.237.247", 7004));
//// jedisClusterNode.add(new HostAndPort("59.110.237.247", 7005));
//// jedisClusterNode.add(new HostAndPort("59.110.237.247", 7006));
//
// //1.如果集群没有密码
//// JedisCluster jc = new JedisCluster(jedisClusterNode,config);
// //2.如果使用到密码,请使用如下构造函数
// JedisCluster jc = new JedisCluster(jedisClusterNode, 1000,30,3,"madong123",config);
//
// jc.setnx("000", "mamengqi");
//// jc.set("test", "value");
//// jc.set("52", "poolTestValue288");
//// jc.set("44", "444");
//// jc.set("name", "poolTestValue2");
// System.out.println("==================");
// System.out.println( jc.get("000"));
// jc.close();
// }
public static void main(String[] args) throws IOException {
GenericObjectPoolConfig config = new GenericObjectPoolConfig();
// 最大连接数
// config.setMaxTotal(10);
// 最大空闲数
// config.setMaxIdle(100);
// 最大允许等待时间,如果超过这个时间还未获取到连接,则会报JedisException异常:
// Could not get a resource from the pool
config.setMaxWaitMillis(7000);
HostAndPort hostAndPort1 = new HostAndPort("59.110.237.247", 7001);
HostAndPort hostAndPort2 = new HostAndPort("59.110.237.247", 7002);
HostAndPort hostAndPort3 = new HostAndPort("59.110.237.247", 7003);
HostAndPort hostAndPort4 = new HostAndPort("59.110.237.247", 7004);
HostAndPort hostAndPort5 = new HostAndPort("59.110.237.247", 7005);
HostAndPort hostAndPort6 = new HostAndPort("59.110.237.247", 7006);
Set<HostAndPort> hostAndPortSet = new HashSet<>();
hostAndPortSet.add(hostAndPort1);
hostAndPortSet.add(hostAndPort2);
hostAndPortSet.add(hostAndPort3);
hostAndPortSet.add(hostAndPort4);
hostAndPortSet.add(hostAndPort5);
hostAndPortSet.add(hostAndPort6);
JedisCluster jedis = new JedisCluster(hostAndPortSet,1000,30,3,"madong123",config);
jedis.set("test19", "sdfwefsfs1123123");
// System.out.println(jedis.get("test169"));
jedis.close();
}
}
| true |
38c78e852ebad50fa48d792b8a49f957c1003756 | Java | LxTeng/wangxin-study | /src/main/java/com/wangxin/langshu/business/edu/iservice/exam/pccommon/IExamManagementService.java | UTF-8 | 2,013 | 1.835938 | 2 | [] | no_license | package com.wangxin.langshu.business.edu.iservice.exam.pccommon;
import com.baomidou.mybatisplus.extension.service.IService;
import com.wangxin.langshu.business.edu.entity.exam.ExamManagement;
import com.wangxin.langshu.business.edu.vo.exam.examManagement.ExamManagementDeleteVo;
import com.wangxin.langshu.business.edu.vo.exam.examManagement.ExamManagementQ;
import com.wangxin.langshu.business.edu.vo.exam.examManagement.ExamManagementSaveVo;
import com.wangxin.langshu.business.edu.vo.exam.examManagement.ExamManagementUpdateVo;
import com.wangxin.langshu.business.edu.vo.exam.examManagement.ExamManagementViewVo;
import com.wangxin.langshu.business.edu.vo.exam.examManagement.ExamManagementVo;
import com.wangxin.langshu.business.edu.vo.exam.examManagementUser.ExamManagementUserQ;
import com.wangxin.langshu.business.edu.vo.exam.examManagementUser.ExamManagementUserVo;
import com.wangxin.langshu.business.util.base.Page;
import com.wangxin.langshu.business.util.base.Result;
public interface IExamManagementService extends IService<ExamManagement> {
public Page<ExamManagementVo> queryExamManagements(ExamManagementQ q) ;
public Result<Integer> saveExamManagement(ExamManagementSaveVo vo) ;
public Result<Integer> updateExamManagement(ExamManagementUpdateVo vo) ;
public Result<Integer> deleteExamManagement(ExamManagementDeleteVo vo) ;
public ExamManagementViewVo viewExamManagement(ExamManagementViewVo vo) ;
public ExamManagementViewVo viewSimpleExamManagement(ExamManagementViewVo vo) ;
public Result<ExamManagementViewVo> viewByIdAndStudentUserNo(ExamManagementViewVo examManagementViewVo) ;
/**
* 查询学生的考试
* @param q
* @return
*/
public Result<Page<ExamManagementVo>> queryExamManagementsByStudentUserNo(ExamManagementQ q) ;
/**
* 根据考试ID查询所有考试对象
* @param examManagementQ
* @return
*/
public Result<Page<ExamManagementUserVo>> queryExamObjectsByExamManagementId(ExamManagementUserQ examManagementUserQ);
}
| true |
96b8261b39cef684ce1bf5fa6b79038e02675302 | Java | antosport82/PopularMovies2 | /app/src/main/java/com/example/anfio/popularmovies/adapters/ReviewApiAdapter.java | UTF-8 | 3,172 | 2.765625 | 3 | [] | no_license | package com.example.anfio.popularmovies.adapters;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.example.anfio.popularmovies.R;
import com.example.anfio.popularmovies.models.Review;
public class ReviewApiAdapter extends RecyclerView.Adapter<ReviewApiAdapter.ReviewViewHolder> {
private Review[] mReviewData;
private final ReviewApiAdapter.ReviewApiAdapterOnClickHandler mClickHandler;
// The interface that receives onClick messages.
public interface ReviewApiAdapterOnClickHandler {
void onClick(String id, String author, String content);
}
/**
* Creates a ReviewApiAdapter.
*
* @param clickHandler The on-click handler for this adapter. This single handler is called
* when an item is clicked.
*/
public ReviewApiAdapter(ReviewApiAdapter.ReviewApiAdapterOnClickHandler clickHandler) {
mClickHandler = clickHandler;
}
@NonNull
@Override
public ReviewViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
Context context = parent.getContext();
int layoutForItem = R.layout.review_list_item;
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(layoutForItem, parent, false);
return new ReviewApiAdapter.ReviewViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull ReviewViewHolder holder, int position) {
String author = mReviewData[position].getAuthor();
String content = mReviewData[position].getContent();
holder.textViewAuthor.setText(author);
holder.textViewContent.setText(content);
}
@Override
public int getItemCount() {
if (null == mReviewData) {
return 0;
} else {
return mReviewData.length;
}
}
// custom ViewHolder that implements OnClickListener
public class ReviewViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
final TextView textViewAuthor;
final TextView textViewContent;
ReviewViewHolder(View itemView) {
super(itemView);
textViewAuthor = itemView.findViewById(R.id.tv_author);
textViewContent = itemView.findViewById(R.id.tv_content);
itemView.setOnClickListener(this);
}
@Override
public void onClick(View v) {
int adapterPosition = getAdapterPosition();
// get movie data at the current position
String id = mReviewData[adapterPosition].getId();
String author = mReviewData[adapterPosition].getAuthor();
String content = mReviewData[adapterPosition].getContent();
// call onClick and pass the review data
mClickHandler.onClick(id, author, content);
}
}
public void setReviewData(Review[] reviewData) {
mReviewData = reviewData;
notifyDataSetChanged();
}
} | true |
3d49cd730a659215db9f8f5f9ddbbea3429a2ef7 | Java | moon-zhou/advanced-java | /advancedprogramming/src/main/java/org/moonzhou/advancedprogramming/basis/string/Demo004StringSplitTest.java | UTF-8 | 837 | 3.546875 | 4 | [] | no_license | package org.moonzhou.advancedprogramming.basis.string;
/**
* String split 正则表达式里使用断言模式<br>
* 一般使用是想分割后的字符串,包含被分割的字符
*
* @author moon-zhou
* @date: 2020/5/6 19:36
* @see [相关类/方法](可选)
* @since [产品/模块版本] (可选)
*/
public class Demo004StringSplitTest {
public static void main(String[] args) {
String cmower = "竹杖芒鞋轻胜马,一蓑烟雨任平生";
if (cmower.contains(",")) {
// ?<= 正向后行断言
// ?= 正向先行断言
// ?! 负向先行断言
// ?<! 负向后行断言
String[] parts = cmower.split("(?<=,)");
System.out.println("第一部分:" + parts[0] + " 第二部分:" + parts[1]);
}
}
}
| true |
1b1ec587a4b6918c1c9dec212455ac879fa41d5c | Java | e-kobayashi-BIGLOBE/mokumoku | /src/main/java/mokumoku/modeling/movie/domain/作品Repository.java | UTF-8 | 118 | 1.796875 | 2 | [] | no_license | package mokumoku.modeling.movie.domain;
public interface 作品Repository {
作品 find(String 作品ID);
}
| true |
6ecf1781c82356a5ccba276755d08d6b0fbb189d | Java | plushkinqt/Java-Algorithms | /src/FilmReference/RatingRegister.java | UTF-8 | 2,379 | 2.6875 | 3 | [] | no_license | package reference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import reference.domain.Film;
import reference.domain.Person;
import reference.domain.Rating;
public class RatingRegister {
Map<Film, List<Rating>> ratings;
Map<Person, Map<Film,Rating>> reviewers;
public RatingRegister(){
ratings = new HashMap<Film, List<Rating>>();
reviewers = new HashMap<Person, Map<Film,Rating>>();
}
public void addRating(Film film, Rating rating){
if(ratings.containsKey(film)){
List<Rating> list = ratings.get(film);
list.add(rating);
ratings.put(film, list);
}
else {
List<Rating> list = new ArrayList<Rating>();
list.add(rating);
ratings.put(film, list);
}
}
public List<Rating> getRatings(Film film){
return ratings.get(film);
}
public Map<Film, List<Rating>> filmRatings(){
return ratings;
}
public void addRating(Person person, Film film, Rating rating){
if(!reviewers.containsKey(person)){
Map<Film, Rating> map = new HashMap<Film, Rating>();
map.put(film, rating);
addRating(film,rating);
reviewers.put(person, map);
}
if(!reviewers.get(person).containsKey(film)){
Map<Film, Rating> map = reviewers.get(person);
map.put(film,rating);
addRating(film,rating);
reviewers.put(person, map);
}
}
public Rating getRating(Person person, Film film){
if(reviewers.get(person).containsKey(film)){
return reviewers.get(person).get(film);
} else return Rating.NOT_WATCHED;
}
public Map<Film, Rating> getPersonalRatings(Person person){
if(!reviewers.containsKey(person)){
return new HashMap<Film, Rating>();
} else {
Map<Film, Rating> map = reviewers.get(person);
return map;
}
}
public List<Person> reviewers(){
List<Person> list = new ArrayList<Person>();
for(Person person:this.reviewers.keySet()){
list.add(person);
}
return list;
}
}
| true |
209019ea145224f7f22722ee3aad3817f2a17904 | Java | BinSlashBash/xcrumby | /src-v3/org/junit/rules/TestWatchman.java | UTF-8 | 1,479 | 2.171875 | 2 | [] | no_license | package org.junit.rules;
import org.junit.internal.AssumptionViolatedException;
import org.junit.runners.model.FrameworkMethod;
import org.junit.runners.model.Statement;
@Deprecated
public class TestWatchman implements MethodRule {
/* renamed from: org.junit.rules.TestWatchman.1 */
class C12541 extends Statement {
final /* synthetic */ Statement val$base;
final /* synthetic */ FrameworkMethod val$method;
C12541(FrameworkMethod frameworkMethod, Statement statement) {
this.val$method = frameworkMethod;
this.val$base = statement;
}
public void evaluate() throws Throwable {
TestWatchman.this.starting(this.val$method);
try {
this.val$base.evaluate();
TestWatchman.this.succeeded(this.val$method);
TestWatchman.this.finished(this.val$method);
} catch (AssumptionViolatedException e) {
throw e;
} catch (Throwable th) {
TestWatchman.this.finished(this.val$method);
}
}
}
public Statement apply(Statement base, FrameworkMethod method, Object target) {
return new C12541(method, base);
}
public void succeeded(FrameworkMethod method) {
}
public void failed(Throwable e, FrameworkMethod method) {
}
public void starting(FrameworkMethod method) {
}
public void finished(FrameworkMethod method) {
}
}
| true |
b76d71bff4e35b2963a08bc7a2daa25fd408437d | Java | LizBlackDesign/BOCES | /app/src/main/java/com/boces/black_stanton_boces/activity/student/AdminStudentsActivity.java | UTF-8 | 3,168 | 2.40625 | 2 | [] | no_license | /*
* BOCES
*
* Authors: Evan Black, Elizabeth Stanton
*/
package com.boces.black_stanton_boces.activity.student;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.SearchView;
import com.boces.black_stanton_boces.R;
import com.boces.black_stanton_boces.persistence.PersistenceInteractor;
import com.boces.black_stanton_boces.student.StudentAdapter;
import com.boces.black_stanton_boces.student.StudentAdapterOnclick;
/**
* Shows Existing Students and Allows User Choose to Edit or Create and New One
*/
public class AdminStudentsActivity extends AppCompatActivity {
private PersistenceInteractor persistence;
private RecyclerView studentList;
private SearchView searchAdminStudent;
/**
* Retrieve Existing Information
* @param savedInstanceState
* Bundle with Extras Set
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_admin_students);
StudentAdapterOnclick onclick = new StudentAdapterOnclick() {
@Override
public void onClick(int studentId) {
Intent editStudent = new Intent(getApplicationContext(), AdminEditStudentActivity.class);
editStudent.putExtra(AdminEditStudentActivity.BUNDLE_KEY.STUDENT_ID.name(), studentId);
startActivity(editStudent);
}
};
persistence = new PersistenceInteractor(this);
final StudentAdapter adapter = new StudentAdapter(persistence.getAllStudents(), persistence, onclick);
studentList = findViewById(R.id.recyclerSelectStudent);
studentList.setAdapter(adapter);
studentList.setLayoutManager(new LinearLayoutManager(this));
searchAdminStudent = findViewById(R.id.login_select_student_search);
searchAdminStudent.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
adapter.getFilter().filter(query);
return true;
}
@Override
public boolean onQueryTextChange(String newText) {
adapter.getFilter().filter(newText);
return true;
}
});
}
/**
* Re-retrieves Information In Case of Updates
*/
@Override
public void onResume() {
super.onResume();
((StudentAdapter) studentList.getAdapter()).setStudents(persistence.getAllStudents());
studentList.getAdapter().notifyDataSetChanged();
// If We Have A Query Resubmit It
if (searchAdminStudent.getQuery().length() > 0)
searchAdminStudent.setQuery(searchAdminStudent.getQuery(), true);
}
/**
* Starts Add Activity
* @param v
* View Holder
*/
public void onClickAdminAddStudent(View v) {
startActivity(new Intent(this, AdminAddStudentActivity.class));
}
}
| true |
6d9489793004fd6be8aa5c364b1ebea4a8f6c98f | Java | hlyRain/hello-world | /aopdemo/src/main/java/cn/exercise/design_mode/templateMethod/AnswerPaperB.java | UTF-8 | 487 | 2.453125 | 2 | [] | no_license | package cn.exercise.design_mode.templateMethod;
/**
* 答题券
*/
public class AnswerPaperB extends TestPaper{
@Override
public void setStudentName() {
super.username = "StudentB";
System.out.println("学生姓名:"+username);
}
@Override
protected String answer1() {
return "D";
}
@Override
protected String answer2() {
return "C";
}
@Override
protected String answer3() {
return "A";
}
}
| true |
69dca97ce1143e525cfa71acc026d97caccc821f | Java | wanlihua/Androidgit | /src/main/java/com/dtl/gemini/enums/AppUserGradeEnum.java | UTF-8 | 525 | 2.59375 | 3 | [] | no_license | package com.dtl.gemini.enums;
/**
* app用户等级
*/
public enum AppUserGradeEnum {
/**
* 普通
*/
STAR_ZERO("普通"),
/**
* S1
*/
STAR_ONE("S1"),
/**
* S2
*/
STAR_TWO("S2"),
/**
* S3
*/
STAR_THREE("S3"),
/**
* S4
*/
STAR_FOUR("S4"),
/**
* S5
*/
STAR_FIVE("S5"),
/**
* S6
*/
STAR_SIX("S6");
AppUserGradeEnum(String grade) {
this.grade = grade;
}
public String grade;
}
| true |
74bf8b27edeca84dd361c287d1dcd65647f5d4f5 | Java | BackupTheBerlios/e3t | /de.techjava.tla.ui/java/src/de/techjava/tla/ui/natures/TLANature.java | UTF-8 | 2,651 | 2.21875 | 2 | [] | no_license | package de.techjava.tla.ui.natures;
import org.eclipse.core.resources.ICommand;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IProjectDescription;
import org.eclipse.core.resources.IProjectNature;
import org.eclipse.core.runtime.CoreException;
import de.techjava.tla.ui.builders.TLABuilder;
/**
*
* TLA Nature
* @author Simon Zambrovski, <a href="http://simon.zambrovski.org">http://simon.zambrovski.org</a>
* @version $Id: TLANature.java,v 1.1 2007/01/29 22:29:23 tlateam Exp $
*/
public class TLANature
implements IProjectNature
{
private IProject project;
public static final String NATURE_ID = "de.techjava.tla.ui.natures.TLANature";
/**
* @see org.eclipse.core.resources.IProjectNature#configure()
*/
public void configure()
throws CoreException
{
// System.out.println("nature added");
IProjectDescription desc = project.getDescription();
ICommand[] commands = desc.getBuildSpec();
boolean found = false;
for (int i = 0; i < commands.length; ++i)
{
if (commands[i].getBuilderName().equals(TLABuilder.BUILDER_ID))
{
found = true;
break;
}
}
if (!found)
{
// System.out.println("Adding a builder");
//add builder to project
ICommand[] newCommands = new ICommand[commands.length + 1];
// Add it before other builders.
System.arraycopy(commands, 0, newCommands, 1, commands.length);
newCommands[0] = desc.newCommand();
newCommands[0].setBuilderName( TLABuilder.BUILDER_ID );
desc.setBuildSpec(newCommands);
project.setDescription(desc, null);
}
}
/**
* @see org.eclipse.core.resources.IProjectNature#deconfigure()
*/
public void deconfigure()
throws CoreException
{
// System.out.println("nature removed");
IProjectDescription desc = project.getDescription();
ICommand[] commands = desc.getBuildSpec();
ICommand[] newCommands = new ICommand[commands.length - 1];
for (int j = 0, i = 0; i < commands.length; ++i)
{
if (!commands[i].getBuilderName().equals(TLABuilder.BUILDER_ID))
{
newCommands[j++] = commands[i];
}
}
desc.setBuildSpec(newCommands);
project.setDescription(desc, null);
}
/**
* @see org.eclipse.core.resources.IProjectNature#getProject()
*/
public IProject getProject()
{
return project;
}
/**
* @see org.eclipse.core.resources.IProjectNature#setProject(org.eclipse.core.resources.IProject)
*/
public void setProject(IProject project) {
this.project = project;
}
}
| true |
a309fe3d9e402eb1ec7f102c0b00c6abf44899cd | Java | masterwdf/CleanArchitecture | /presentation/src/main/java/com/example/cleanarchitecture/feature/splash/di/SplashModule.java | UTF-8 | 851 | 2.140625 | 2 | [] | no_license | package com.example.cleanarchitecture.feature.splash.di;
import com.example.cleanarchitecture.di.PerActivity;
import com.example.domain.executor.PostExecutionThread;
import com.example.domain.executor.ThreadExecutor;
import com.example.domain.interactor.UserUseCase;
import com.example.domain.repository.UserRepository;
import dagger.Module;
import dagger.Provides;
/**
* Módulo Dagger que proporciona los casos de usos del Splash.
*/
@Module
public class SplashModule {
public SplashModule() {
}
@Provides
@PerActivity
UserUseCase providesUserUseCase(UserRepository userRepository,
ThreadExecutor threadExecutor,
PostExecutionThread postExecutionThread) {
return new UserUseCase(userRepository, threadExecutor, postExecutionThread);
}
}
| true |
181560d35d4a1b555b42402fe2bff41b962260ea | Java | core996/Spring-Boot | /Ribbon/src/main/java/core/study/config/ClientRibbonConfiguration.java | UTF-8 | 491 | 1.859375 | 2 | [] | no_license | package core.study.config;
import com.netflix.loadbalancer.BestAvailableRule;
import com.netflix.loadbalancer.IRule;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @description: 负载规则配置类
* @author: Xin Wu
* @create: 2019-09-04 11:24
**/
@Configuration
public class ClientRibbonConfiguration {
@Bean
public IRule ribbonRule(){ //轮训规则
return new BestAvailableRule();
}
}
| true |
e9c27c6e668bc9ee0ad82fd47f5cc6367d6dddf4 | Java | ngotuan12/BOTalk | /Android/CameraSDK/src/com/bigsoft/camerasdk/AudioRecoding.java | UTF-8 | 4,590 | 2.265625 | 2 | [] | no_license | package com.bigsoft.camerasdk;
import java.io.File;
import java.io.IOException;
import android.content.Context;
import android.content.res.AssetFileDescriptor;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.util.Log;
public class AudioRecoding {
private static final String LOG_TAG = "AudioRecord";
private static String mFileName = null;
private MediaRecorder mRecorder = null;
private MediaPlayer mPlayer = null;
public AudioRecoding(String filename){
if(filename==null)
{
mFileName = Environment.getExternalStorageDirectory().getAbsolutePath();
mFileName += "/audiorecordtest.3gp";
} else {
mFileName = filename;
}
}
public String isFilepath()
{
return mFileName;
}
public boolean isFile()
{
File file = new File(mFileName);
if(file.exists()) {
return true;
}
return false;
}
public boolean isRecordFile()
{
mPlayer = new MediaPlayer();
try {
mPlayer.setDataSource(mFileName);
return true;
} catch (IOException e) {
return false;
}
}
public void onPause() {
if (mRecorder != null) {
mRecorder.release();
mRecorder = null;
}
if (mPlayer != null) {
mPlayer.release();
mPlayer = null;
}
}
/**
* 레코딩 시작
*/
public void startRecording() {
stopRecording();
mRecorder = new MediaRecorder();
mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mRecorder.setOutputFile(mFileName);
if (Build.VERSION.SDK_INT >= 10) {
mRecorder.setAudioSamplingRate(44100);
mRecorder.setAudioEncodingBitRate(96000);
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
} else {
// older version of Android, use crappy sounding voice codec
mRecorder.setAudioSamplingRate(8000);
mRecorder.setAudioEncodingBitRate(12200);
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
}
try {
mRecorder.prepare();
} catch (IOException e) {
Log.e(LOG_TAG, "prepare() failed");
}
mRecorder.start();
}
public void stopRecording() {
if(mRecorder!=null){
mRecorder.stop();
mRecorder.release();
mRecorder = null;
}
}
public void startPlaying() {
mPlayer = new MediaPlayer();
try {
mPlayer.setDataSource(mFileName);
mPlayer.prepare();
mPlayer.start();
} catch (IOException e) {
Log.e(LOG_TAG, "prepare() failed");
}
}
public void startPlaying(Context context, Uri uri) {
mPlayer = new MediaPlayer();
try {
mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mPlayer.setDataSource(context, uri);
mPlayer.prepare();
mPlayer.start();
} catch (IOException e) {
Log.e(LOG_TAG, "prepare() failed");
}
}
public int getDuration() {
if (mPlayer != null) {
return mPlayer.getCurrentPosition();
}
return 0;
}
public void startWavPlaying(Context context, String name) {
mPlayer = new MediaPlayer();
try {
String packageName = context.getPackageName();
int resID = context.getResources().getIdentifier( name , "raw" , packageName ); //in res/raw folder I have filename.wav audio file
AssetFileDescriptor afd = context.getResources().openRawResourceFd(resID);
mPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
//mPlayer.setDataSource(context, Uri.parse("android.resource://"+context.getPackageName()+"/res/raw/" + name));
mPlayer.prepare();
mPlayer.start();
} catch (IOException e) {
Log.e(LOG_TAG, "prepare() failed");
}
}
public void stopPlaying() {
if (mPlayer != null) {
mPlayer.release();
mPlayer = null;
}
}
public double getAmplitude() {
if (mRecorder != null)
return mRecorder.getMaxAmplitude();
else
return 0;
}
}
| true |
33f40e7f3ac16eb35ac3c616b9028f68e161616e | Java | sanwazi/CS744-Admin-System | /src/main/java/com/example/EMR_Admin/relation_physician_department/dao/DepartmentPhysicianRelationDao.java | UTF-8 | 3,853 | 2.140625 | 2 | [] | no_license | package com.example.EMR_Admin.relation_physician_department.dao;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.example.EMR_Admin.authentication.data.Physician;
import com.example.EMR_Admin.physician.service.PhysicianService;
import com.example.EMR_Admin.relation_physician_department.data.DepartmentPhysicianRelation;
@Repository
public class DepartmentPhysicianRelationDao {
@Autowired
private SessionFactory sessionFactory;
@Autowired
private PhysicianService phyService;
public List<DepartmentPhysicianRelation> getRelationByDepartmentName(String dName){
Session session = sessionFactory.openSession();
Query q = session.createQuery("from DepartmentPhysicianRelation where department_name = '"
+ dName + "'");
Transaction transaction = session.beginTransaction();
List<DepartmentPhysicianRelation> list = q.list();
transaction.commit();
session.close();
return list;
}
public List<Physician> getNonRegisteredPhysiciansByInputPhysicianName(String input){
Session session = sessionFactory.openSession();
Query q = session
.createQuery("from Physician where physicianName like '"
+ input + "%' and physicianId not in (select physician_id from DepartmentPhysicianRelation)");
Transaction transaction = session.beginTransaction();
List<Physician> list = q.list();
transaction.commit();
session.close();
return list;
}
public List<DepartmentPhysicianRelation> getRelationByPhysicianName(String physician_name){
Session session = sessionFactory.openSession();
Query q = session.createQuery("from DepartmentPhysicianRelation where physician_name = '"
+ physician_name + "'");
Transaction transaction = session.beginTransaction();
List<DepartmentPhysicianRelation> list = q.list();
transaction.commit();
session.close();
return list;
}
public String addRelation(DepartmentPhysicianRelation inputRelation){
String physician_name = inputRelation.getPhysician_name();
if (getRelationByPhysicianName(physician_name).isEmpty()) {
if (!phyService.getPhysicianByName(physician_name).isEmpty()) {
try {
Session session = sessionFactory.openSession();
session.beginTransaction();
session.save(inputRelation);
session.getTransaction().commit();
session.close();
} catch (HibernateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "addingToDbfalse";
}
return "addingToDbSuccess";
}
return "noSuchPhysician";
}
return "relationExists";
}
public DepartmentPhysicianRelation getRelationByPhysicianId(int physician_id){
Session session = sessionFactory.openSession();
Query q = session.createQuery("from DepartmentPhysicianRelation where physician_id = '"
+ physician_id + "'");
Transaction transaction = session.beginTransaction();
List<DepartmentPhysicianRelation> list = q.list();
transaction.commit();
session.close();
return list.get(0);
}
public boolean deleteRelationByPhysicianId(int physician_id){
if(getRelationByPhysicianId(physician_id) != null){
try {
Session session = sessionFactory.openSession();
Query q = session.createQuery("delete DepartmentPhysicianRelation where physician_id = '"+physician_id+"'");
q.executeUpdate();
session.beginTransaction();
session.close();
} catch (HibernateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}
return true;
}
return false;
}
}
| true |
ba417df73cdcc1d3f3f400aa96c5cec00b4bafd5 | Java | viyski/circley | /app/src/main/java/com/gm/circley/ui/activity/explore/PhotoExploreActivity.java | UTF-8 | 8,174 | 1.757813 | 2 | [] | no_license | package com.gm.circley.ui.activity.explore;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.InputType;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;
import com.afollestad.materialdialogs.MaterialDialog;
import com.framework.dialog.ToastTip;
import com.gm.circley.R;
import com.gm.circley.base.BaseActivity;
import com.gm.circley.control.PageControl;
import com.gm.circley.control.manager.DBManager;
import com.gm.circley.db.DBPhoto;
import com.gm.circley.util.PreferenceUtil;
import com.gm.circley.widget.ViewPagerFixed;
import com.mingle.widget.LoadingView;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import butterknife.Bind;
import butterknife.OnClick;
import uk.co.senab.photoview.PhotoView;
import uk.co.senab.photoview.PhotoViewAttacher;
public class PhotoExploreActivity extends BaseActivity<PageControl> implements PhotoViewAttacher.OnPhotoTapListener, ViewPager.OnPageChangeListener {
private static final String TAG = PhotoExploreActivity.class.getName();
@Bind(R.id.tv_status)
TextView tvStatus;
@Bind(R.id.view_pager)
ViewPagerFixed viewPager;
@Bind(R.id.loadingView)
LoadingView loadingView;
@Bind(R.id.tv_photo_count)
TextView tvPhotoCount;
@Bind(R.id.iv_photo_select)
ImageView ivPhotoSelect;
@Bind(R.id.iv_photo_save)
ImageView ivPhotoSave;
private List<DBPhoto> mData;
private DBManager dbManager;
private List<PhotoView> viewList;
private int mPosition;
private String saveImageUrl;
private Set<String> photoSet;
@Override
protected void requestWindowFeature() {
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
}
@Override
protected int getLayoutRes() {
return R.layout.activity_photo_explore;
}
@Override
protected void initView() {
loadData();
}
@Override
protected void initData() {
mData = new ArrayList<>();
viewList = new ArrayList<>();
mControl.getPhotoDataFromDB(dbManager);
viewPager.setOffscreenPageLimit(1);
}
public void getDataSuccess() {
loadingView.setVisibility(View.GONE);
mData = mModel.getList(1);
if (mData != null) {
for (int i = 0; i < mData.size(); i++) {
PhotoView photoView = new PhotoView(mContext);
photoView.setScaleType(ImageView.ScaleType.CENTER_CROP);
photoView.setOnPhotoTapListener(this);
viewList.add(photoView);
}
tvPhotoCount.setText(1 + " / " + mData.size());
viewPager.setAdapter(new ImagePagerAdapter(mData, viewList));
viewPager.addOnPageChangeListener(this);
}
}
public void getDataEmpty() {
loadingView.setVisibility(View.GONE);
tvStatus.setVisibility(View.VISIBLE);
tvStatus.setText(R.string.no_data);
}
public void getDataFailed() {
loadingView.setVisibility(View.GONE);
tvStatus.setVisibility(View.VISIBLE);
tvStatus.setText(R.string.load_data_failed);
}
private void loadData() {
if (dbManager == null) {
dbManager = DBManager.getInstance(mContext);
}
boolean isAdded = PreferenceUtil.getBoolean(mContext, "isAdded");
if (!isAdded) {
boolean isSuccess = mControl.savePhotoList(mContext, dbManager);
isAdded = isSuccess;
}
}
@Override
public void onPhotoTap(View view, float x, float y) {
finish();
}
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
mPosition = position;
tvPhotoCount.setText((position + 1) + " / " + mData.size());
}
@Override
public void onPageScrollStateChanged(int state) {
}
@OnClick({R.id.iv_photo_save, R.id.iv_photo_select})
public void onClick(View view) {
switch (view.getId()) {
case R.id.iv_photo_save:
savePhotoToMediaStore();
break;
case R.id.iv_photo_select:
selectPhotoPos();
break;
}
}
private void selectPhotoPos() {
MaterialDialog.Builder builder = new MaterialDialog.Builder(mContext);
builder.title("选择图片位置");
builder.inputType(InputType.TYPE_CLASS_NUMBER);
builder.input("请输入1 - "+mData.size()+"的之间的数字","", new MaterialDialog.InputCallback() {
@Override
public void onInput(MaterialDialog dialog, CharSequence input) {
try {
if (!TextUtils.isEmpty(input)) {
int i = Integer.parseInt(input.toString());
if (i == -1 || i > mData.size()){
ToastTip.show("请按提示输入跳转位置!");
return;
}else{
viewPager.setCurrentItem(i - 1);
}
}
} catch (NumberFormatException e) {
ToastTip.show("请输入数字!");
}
}
}).show();
}
@Override
protected void onPause() {
super.onPause();
}
private void savePhotoToMediaStore() {
photoSet = PreferenceUtil.getStringSet(mContext, "photoSet");
if (photoSet != null && photoSet.contains(String.valueOf(mPosition))){
ToastTip.show("该图片已保存过!");
return;
} else {
DBPhoto dbPhoto = mData.get(mPosition);
if (dbPhoto != null) {
saveImageUrl = dbPhoto.getImageUrl();
if (!TextUtils.isEmpty(saveImageUrl)) {
mControl.savePhotoToMediaStore(mContext, saveImageUrl);
}
}
}
}
public void savePhotoSuccess() {
ToastTip.show("保存成功");
if (photoSet == null){
photoSet = new HashSet<>();
}
photoSet.add(mPosition+"");
PreferenceUtil.putStringSet(mContext, "photoSet", photoSet);
}
public void savePhotoFail() {
ToastTip.show("保存失败");
}
static class ImagePagerAdapter extends PagerAdapter {
private List<DBPhoto> data;
private List<PhotoView> viewList;
public ImagePagerAdapter(List<DBPhoto> data, List<PhotoView> viewList) {
this.data = data;
this.viewList = viewList;
}
@Override
public int getCount() {
return viewList.size();
}
@Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
container.addView(viewList.get(position));
PhotoView photoView = viewList.get(position);
Picasso.with(container.getContext())
.load(data.get(position).getImageUrl())
.placeholder(R.color.font_black_6)
.error(R.color.font_black_6)
.into(photoView);
return photoView;
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
@Override
public int getItemPosition(Object object) {
return PagerAdapter.POSITION_NONE;
}
}
}
| true |
f89b01743875d0a53f9ad0378523481023199d6f | Java | poojabhandari/LargestIncreasingSubsequence | /solution.java | UTF-8 | 1,927 | 3.34375 | 3 | [] | no_license | import java.util.ArrayList;
public class solution {
static ArrayList<int[]> longestSubsequence = new ArrayList<int[]>();
public static void main(String args[]) {
solution ob = new solution();
// int[] nums={10, 9, 2, 5, 3, 7, 101, 18};
int[] nums= { 2, 5, 3, 7, 11, 8, 10, 13, 6 };
//int[] nums = { 2, 5, 7, 9, 4, 6 };
int max = ob.lengthOfLIS(nums);
System.out.println(max);
printLIS(nums, max);
}
static void printLIS(int[] nums, int max) {
for (int[] i : longestSubsequence) {
if (max == i.length) {
System.out.println();
for (int h = 0; h < i.length; h++) {
System.out.print(i[h] + " ");
}
System.out.println();
break;
}
}
}
public int lengthOfLIS(int[] nums) {
if (nums == null || nums.length == 0) {
return 0;
}
int n = nums.length, len = 1;
int[] result = new int[n];
result[0] = nums[0];
for (int i = 1; i < n; i++) {
int currentElement = nums[i];
if (currentElement <= result[0]) {
result[0] = currentElement;
} else if (currentElement > result[len - 1]) {
result[len++] = currentElement;
} else {
int position = binarySearch(result, currentElement, 0, len - 1);
result[position] = currentElement;
}
int[] copyofresult = new int[len];
for (int t = 0; t < len; t++) {
copyofresult[t] = result[t];
}
longestSubsequence.add(copyofresult);
}
return len;
}
public int binarySearch(int[] arr, int target, int start, int end) {
int leftIndex = start, rightIndex = end;
while (rightIndex - leftIndex > 1) {
int middleIndex = (leftIndex + rightIndex) / 2;
int middleElement = arr[middleIndex];
if (middleElement == target) {
return middleIndex;
} else if (middleElement < target) {
leftIndex = middleIndex;
} else {
rightIndex = middleIndex;
}
}
return rightIndex;
}
}
| true |
7eb4a41fb6db2ab979675a9ea85da2ee4684abf9 | Java | ftiago89/OSWorks-API-REST | /src/main/java/com/felipemelo/osworks/domain/service/CadastroClienteService.java | UTF-8 | 836 | 2.328125 | 2 | [] | no_license | package com.felipemelo.osworks.domain.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.felipemelo.osworks.domain.exception.DomainException;
import com.felipemelo.osworks.domain.model.Cliente;
import com.felipemelo.osworks.domain.repository.ClienteRepository;
@Service
public class CadastroClienteService {
@Autowired
private ClienteRepository clienteRepository;
public Cliente save(Cliente cliente) {
Cliente existente = clienteRepository.findByEmail(cliente.getEmail());
if(existente != null && !existente.equals(cliente)) {
throw new DomainException("Já existe um cliente cadastrado com esse e-mail");
}
return clienteRepository.save(cliente);
}
public void delete(Long id) {
clienteRepository.deleteById(id);
}
}
| true |
539161ac780379fbe44f4dad2c4de07903131859 | Java | ding2022/Java-advanced | /JSP1/src/test1/AServlet.java | UTF-8 | 1,386 | 2.375 | 2 | [] | no_license | package test1;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class AServlet
*/
@WebServlet("/AServlet")
public class AServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public AServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String num1 = request.getParameter("num1");
String num2 = request.getParameter("num2");
int n = Integer.parseInt(num1) + Integer.parseInt(num2);
request.setAttribute("sum", n);
request.getRequestDispatcher("/t1/result.jsp").forward(request,
response);
// System.out.println(n);
}
}
| true |
9fbab5b89cebbd104884abcbcd6768bc8170f6f2 | Java | ruhibhandari21/StudentAttendance | /app/src/main/java/com/cloverinfosoft/studentattendance/teacher/TeacherHomeFragment.java | UTF-8 | 4,102 | 2.09375 | 2 | [] | no_license | package com.cloverinfosoft.studentattendance.teacher;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import com.cloverinfosoft.studentattendance.R;
public class TeacherHomeFragment extends Fragment implements View.OnClickListener {
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private View view;
private RelativeLayout rel_attendance_report,rel_attendance_entry,rel_add_exam,rel_exam_results,rel_view_timetable,rel_add_homework;
private Intent intent;
private Context mContext;
public TeacherHomeFragment() {
// Required empty public constructor
}
public static TeacherHomeFragment newInstance(String param1, String param2) {
TeacherHomeFragment fragment = new TeacherHomeFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view=inflater.inflate(R.layout.fragment_teacher_home, container, false);
mContext=getActivity();
initUI();
initListener();
return view;
}
public void initUI()
{
rel_attendance_report=(RelativeLayout)view.findViewById(R.id.rel_attendance_report);
rel_attendance_entry=(RelativeLayout)view.findViewById(R.id.rel_attendance_entry);
rel_add_exam=(RelativeLayout)view.findViewById(R.id.rel_add_exam);
rel_exam_results=(RelativeLayout)view.findViewById(R.id.rel_exam_results);
rel_view_timetable=(RelativeLayout)view.findViewById(R.id.rel_view_timetable);
rel_add_homework=(RelativeLayout)view.findViewById(R.id.rel_add_homework);
}
public void initListener()
{
rel_attendance_report.setOnClickListener(this);
rel_attendance_entry.setOnClickListener(this);
rel_add_exam.setOnClickListener(this);
rel_exam_results.setOnClickListener(this);
rel_view_timetable.setOnClickListener(this);
rel_add_homework.setOnClickListener(this);
}
@Override
public void onClick(View view) {
switch(view.getId())
{
case R.id.rel_attendance_report:
intent=new Intent(mContext,AttendanceReportActivity.class);
mContext.startActivity(intent);
break;
case R.id.rel_attendance_entry:
intent=new Intent(mContext,AttendanceEntryActivity.class);
mContext.startActivity(intent);
break;
case R.id.rel_add_exam:
intent=new Intent(mContext,AddExamActivity.class);
mContext.startActivity(intent);
break;
case R.id.rel_exam_results:
intent=new Intent(mContext,ExamResults.class);
mContext.startActivity(intent);
break;
case R.id.rel_view_timetable:
intent=new Intent(getActivity(),UploadTimeTableActivity.class);
getActivity().startActivity(intent);
break;
case R.id.rel_add_homework:
intent=new Intent(mContext,AddHomeworkActivity.class);
mContext.startActivity(intent);
break;
}
}
}
| true |
878dfb8d163820c9bc28e04e634c5f54445df1d0 | Java | schnarbiemeows/Threading | /ProblemSet2/src/TicketReservationSystem.java | UTF-8 | 1,074 | 3.375 | 3 | [] | no_license | import java.util.HashMap;
import java.util.Map;
/**
* @author dylan
*
*/
public class TicketReservationSystem {
Map<String, Integer> trainInfo = new HashMap<String, Integer>();
public Map<String, Integer> getTrainInfo() {
return trainInfo;
}
public void setTrainInfo(Map<String, Integer> trainInfo) {
this.trainInfo = trainInfo;
}
/**
*
*/
public TicketReservationSystem() {
super();
trainInfo.put("a", 100);
trainInfo.put("b", 100);
}
/**
* @param trainName
* @param ticketCount
*/
public void reserveTicket(String trainName, int ticketCount) {
int ticketsLeft = trainInfo.get(trainName).intValue();
if (ticketsLeft < ticketCount) {
System.out.println("not enough tickets!");
} else {
System.out.println("buying " + ticketCount + " tickets");
ticketsLeft -= ticketCount;
trainInfo.put(trainName, ticketsLeft);
}
}
/**
* @param trainName
* @return
*/
public int getAvailableTickets(String trainName) {
return trainInfo.get(trainName).intValue();
}
}
| true |
b91f601a3c55e3192c5b7475d8e0252b7d63e34a | Java | thiningsun/flink-test-demo | /flink_clickHouse/src/main/java/com/zhangmen/utils/ConfigUtil.java | UTF-8 | 683 | 2.3125 | 2 | [] | no_license | package com.zhangmen.utils;
import com.typesafe.config.Config;
import com.typesafe.config.ConfigFactory;
import org.apache.commons.lang3.StringUtils;
import java.util.Objects;
public class ConfigUtil {
final static String env = ConfigFactory.load("application").getString("env.profile");
final static Config config = ConfigFactory.load(getConfig(env));//获取执行环境
//获取配置文件
public static String getConfig(String env) {
if ("".equals(env) || Objects.isNull(env)) {
env = "dev";
}
return StringUtils.join("application-", env);
}
public static Config getProperties() {
return config;
}
}
| true |
e77cafb15439bb163092fa423ebf151fcd4feccb | Java | umkoin/umkoin | /src/qt/android/src/org/umkoincore/qt/UmkoinQtActivity.java | UTF-8 | 535 | 1.921875 | 2 | [
"MIT"
] | permissive | package org.umkoincore.qt;
import android.os.Bundle;
import android.system.ErrnoException;
import android.system.Os;
import org.qtproject.qt5.android.bindings.QtActivity;
import java.io.File;
public class UmkoinQtActivity extends QtActivity
{
@Override
public void onCreate(Bundle savedInstanceState)
{
final File umkoinDir = new File(getFilesDir().getAbsolutePath() + "/.umkoin");
if (!umkoinDir.exists()) {
umkoinDir.mkdir();
}
super.onCreate(savedInstanceState);
}
}
| true |
7e2449afd1d597e527b6b9f3769de2d357af23d4 | Java | Bremys/encrypted-akka-chat | /server/src/main/java/ServerOnlyMessages/EmailRequest.java | UTF-8 | 468 | 2.3125 | 2 | [
"CC0-1.0",
"LicenseRef-scancode-public-domain"
] | permissive | package ServerOnlyMessages;
import java.io.Serializable;
public class EmailRequest implements Serializable {
private String email;
private String randomizedString;
public String getEmail() {
return email;
}
public String getRandomizedString() {
return randomizedString;
}
public EmailRequest(String email, String randomizedString) {
this.email = email;
this.randomizedString = randomizedString;
}
}
| true |
e2022264cdf39669a3d3d1eb323225907962f0a4 | Java | mmajews/DistributedSystems | /Lab5/src/main/java/Application.java | UTF-8 | 332 | 2.1875 | 2 | [
"Unlicense"
] | permissive | import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class Application {
private static final Logger logger = LogManager.getLogger(Application.class);
public static void main(String[] args) {
logger.info("Starting app!");
Starter starter = new Starter();
starter.initialize();
}
}
| true |
3e451f4f5bf8ea9cf19f294cb47e0a62022588bb | Java | ihenryph/Ex-Cond | /swiex10.java | UTF-8 | 689 | 3.53125 | 4 | [] | no_license | import java.util.Scanner;
public class swiex10 {
public static void main(String[] args) {
float alt, pid;
String sx;
Scanner leitor = new Scanner(System.in);
System.out.println("Altura em metros: ");
alt = leitor.nextFloat();
System.out.println("Digite seu sexo: ");
sx = leitor.next();
if (sx.equals("masculino"))
{
pid = (float) (((72.7)*alt)-58);
System.out.println("Peso ideal: " + pid);}
else
if (sx.contentEquals("feminino"))
{
pid = (float) (((62.1)*alt)-44.7);
System.out.println("Peso ideal: " + pid);}
else;
}
} | true |
6171a5fee35f463f956369a303e73dbab6dfb283 | Java | isabella232/cr-archive | /skara/32/webrev.05/args/src/main/java/org/openjdk/skara/args/MultiCommandParser.java | UTF-8 | 3,507 | 2.25 | 2 | [] | no_license | /*
* Copyright (c) 2019 Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.skara.args;
import java.io.PrintStream;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
public class MultiCommandParser implements Main {
private final String programName;
private final String defaultCommand;
private final Map<String, Command> subCommands;
public MultiCommandParser(String programName, List<Command> commands) {
var defaults = commands.stream().filter(Default.class::isInstance).collect(Collectors.toList());
if (defaults.size() != 1) {
throw new IllegalStateException("Expecting exactly one default command");
}
this.defaultCommand = defaults.get(0).name();
this.programName = programName;
this.subCommands = commands.stream()
.collect(Collectors.toMap(
Command::name,
Function.identity()));
this.subCommands.put("help", helpCommand());
}
private Command helpCommand() {
return new Command("help", "print a help message", args -> showUsage());
}
public Executable parse(String[] args) {
if (args.length != 0) {
Command p = subCommands.get(args[0]);
if (p != null) {
String[] forwardedArgs = Arrays.copyOfRange(args, 1, args.length);
return () -> p.main(forwardedArgs);
} else {
return () -> {
System.out.println("error: unknown subcommand: " + args[0]);
showUsage();
};
}
} else {
return this::showUsage;
}
}
@Override
public void main(String[] args) throws Exception {
}
private void showUsage() {
showUsage(System.out);
}
private void showUsage(PrintStream ps) {
ps.print("usage: ");
ps.print(programName);
ps.print(subCommands.keySet().stream().collect(Collectors.joining("|", " <", ">")));
ps.println(" <input>");
int spacing = subCommands.keySet().stream().mapToInt(String::length).max().orElse(0);
spacing += 8; // some room
for (var subCommand : subCommands.values()) {
ps.println(String.format(" %-" + spacing + "s%s", subCommand.name(), subCommand.helpText()));
}
}
}
| true |
c1b4b439bcaa839e1185410e66c222edbcd5cc7f | Java | limyoujie/BigDataLab5 | /question_2/MovingAverageReducer.java | UTF-8 | 2,723 | 2.75 | 3 | [] | no_license | package tv.floe.caduceus.hadoop.movingaverage;
import java.io.IOException;
import java.util.Iterator;
import java.util.LinkedList;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapred.JobConf;
import org.apache.hadoop.mapred.MapReduceBase;
import org.apache.hadoop.mapred.OutputCollector;
import org.apache.hadoop.mapred.Reducer;
import org.apache.hadoop.mapred.Reporter;
public class MovingAverageReducer extends MapReduceBase implements
Reducer<TimeseriesKey, TimeseriesDataPoint, Text, Text> {
static enum PointCounters {
POINTS_SEEN, POINTS_ADDED_TO_WINDOWS, MOVING_AVERAGES_CALCD
};
static long day_in_ms = 24 * 60 * 60 * 1000;
private JobConf configuration;
@Override
public void configure(JobConf job) {
this.configuration = job;
}
public void reduce(TimeseriesKey key, Iterator<TimeseriesDataPoint> values,
OutputCollector<Text, Text> output, Reporter reporter)
throws IOException {
TimeseriesDataPoint next_point;
float today = 0;
float yesterday = 0;
int iWindowSizeInDays = this.configuration.getInt(
"tv.floe.caduceus.hadoop.movingaverage.windowSize", 2);
int iWindowStepSizeInDays = this.configuration.getInt(
"tv.floe.caduceus.hadoop.movingaverage.windowStepSize", 1);
long iWindowSizeInMS = iWindowSizeInDays * day_in_ms;
long iWindowStepSizeInMS = iWindowStepSizeInDays * day_in_ms;
Text out_key = new Text();
Text out_val = new Text();
SlidingWindow sliding_window = new SlidingWindow(iWindowSizeInMS,
iWindowStepSizeInMS, day_in_ms);
while (values.hasNext()) {
while (sliding_window.WindowIsFull() == false && values.hasNext()) {
reporter.incrCounter(PointCounters.POINTS_ADDED_TO_WINDOWS, 1);
next_point = values.next();
TimeseriesDataPoint p_copy = new TimeseriesDataPoint();
p_copy.copy(next_point);
try {
sliding_window.AddPoint(p_copy);
} catch (Exception e) {
e.printStackTrace();
}
}
if (sliding_window.WindowIsFull()) {
reporter.incrCounter(PointCounters.MOVING_AVERAGES_CALCD, 1);
LinkedList<TimeseriesDataPoint> oWindow = sliding_window
.GetCurrentWindow();
String strBackDate = oWindow.getLast().getDate();
// ---------- compute the moving average here -----------
out_key.set(key.getGroup() + ", "
+ strBackDate + ", ");
today = oWindow.getLast().fValue;
yesterday = oWindow.get(0).fValue;
out_val.set(today + ", " + yesterday);
output.collect(out_key, out_val);
// 2. step window forward
sliding_window.SlideWindowForward();
}
} // while
output.collect(out_key, out_val);
} // reduce
}
| true |
66bebe098f805adae1bb5924dac8ce57daa969f9 | Java | alvarosantisteban/moderation15m | /app/src/main/java/com/alvarosantisteban/moderacion15m/ModerationActivity.java | UTF-8 | 34,099 | 2.03125 | 2 | [] | no_license | package com.alvarosantisteban.moderacion15m;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Point;
import android.media.AudioManager;
import android.media.ToneGenerator;
import android.os.Bundle;
import android.os.Vibrator;
import android.preference.PreferenceManager;
import android.support.v4.app.DialogFragment;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.*;
import android.widget.*;
import com.alvarosantisteban.moderacion15m.model.InterventionTime;
import com.alvarosantisteban.moderacion15m.model.Participant;
import com.alvarosantisteban.moderacion15m.model.ParticipantID;
import com.alvarosantisteban.moderacion15m.model.ParticipantView;
import com.alvarosantisteban.moderacion15m.util.Constants;
import com.alvarosantisteban.moderacion15m.util.Utils;
import com.github.amlcurran.showcaseview.ShowcaseView;
import com.github.amlcurran.showcaseview.targets.Target;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
/**
* This activity allows the moderator to interact with the table of participants created.
* @author Alvaro Santisteban 13.11.14 - alvarosantisteban@gmail.com
*/
public class ModerationActivity extends ActionBarActivity implements ParticipantStatisticsDialogFragment.ParticipantStatisticsDialogListener{
private static final String TAG = "ModerationActivity";
// The pixels that are subtracted to the size of a row so the image in it looks fine
private static final int SUBTRACT_TO_ROW_SIZE = 10;
// The top margin defined in the layout of the table
private static final int TOP_MARGIN_OF_TABLE = 10;
private static final int DEFAULT_MAX_NUM_SEC_PARTICIPATION = 5;
private static final int DEFAULT_MAX_NUM_SEC_DEBATE = 30;
private static final int DEVICE_VIBRATION_IN_MILLISECONDS = 2000;
private static final int PARTICIPANT_INTERVENTION_TIMER = 0;
private static final int DEBATE_TOTAL_TIME_TIMER = 1;
private static final int MAX_NUM_PARTICIPANTS_TO_ADD_EXTRA_COLUMN = 28;
private static final int TIMEOUT_PARTICIPANT = 0;
private static final int TIMEOUT_DEBATE = 1;
// The table layout with the views of the participants
TableLayout tableLayoutOfParticipants;
// The participant currently talking
Participant mCurrentParticipant;
// The participant currently being edited
Participant mEditedParticipant;
// The ParticipantView currently being edited
ParticipantView mEditedParticipantView;
// The waiting list of Participants identified by their ids
List<ParticipantView> mWaitingList = new ArrayList<>();
// The list of participants
List<Participant> mParticipants = new ArrayList<>();
// A HasMap that connects the id and the ParticipantView
Map<ParticipantID, ParticipantView> mIdAndViewHashMap = new HashMap<>();
// The scheduler used as a timer for the interventions
ScheduledFuture mScheduleFutureIntervention;
// The scheduler used as a timer for the debate
ScheduledFuture mScheduleFutureDebate;
int mNumColumns;
int mNumParticipants;
private Context context;
// The maximum number of seconds that a participant can talk before the timer runs out
private int mParticipantTimeLimit;
// The maximum number of seconds that the debate can last
private int mDebateTimeLimit;
private boolean mDebateHasStarted = false;
private boolean mDebateHasEnded = false;
// The ImageView of the moderator
ImageView mModeratorImage;
// The ShowCaseView to indicate how does the timer of the moderation works
ShowcaseView mShowCaseView;
// To know if the show case of the participants has been already shown
private boolean hasParticipantShowCaseBeenShown = false;
SharedPreferences mSharedPref;
// the position in the list of participants of the ParticipantView that is in the left bottom corner
private int mParticipantPosInCorner;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_moderation);
context = this;
tableLayoutOfParticipants = (TableLayout) findViewById(R.id.participants_table);
// Get the intent to obtain its extras
Intent intentFromMain = getIntent();
//mNumColumns = intentFromMain.getIntExtra(Constants.EXTRA_NUM_COLUMNS, 0);
mNumParticipants = intentFromMain.getIntExtra(Constants.EXTRA_NUM_PARTICIPANTS, 0);
mParticipantTimeLimit = intentFromMain.getIntExtra(Constants.EXTRA_MAX_NUM_SEC_PARTICIPATION, DEFAULT_MAX_NUM_SEC_PARTICIPATION);
mDebateTimeLimit = intentFromMain.getIntExtra(Constants.EXTRA_TOTAL_TIME_DEBATE_SECS, DEFAULT_MAX_NUM_SEC_DEBATE);
// Add or subtract one column to make it look better
mNumColumns = mNumParticipants < MAX_NUM_PARTICIPANTS_TO_ADD_EXTRA_COLUMN ?
(mNumParticipants / 4) + 1 :
(mNumParticipants / 4) - 1;
// Calculate the number of needed rows
int numRows = calculateNumOfRows(mNumColumns, mNumParticipants);
// Build the table tableLayoutOfParticipants
buildTable(numRows, mNumColumns);
// Get the saved preferences to know if it is the first time
mSharedPref = PreferenceManager.getDefaultSharedPreferences(this);
boolean isFirstTime = mSharedPref.getBoolean(Constants.SHARED_PREF_FIRST_TIME, true);
isFirstTime = true;
if(isFirstTime) {
generateShowCaseViewForModerator();
}
}
/**
* Calculates the number of rows needed in order to have the number of participants passed by parameter and the asked
* number of columns.
*
* @param numColumns the desired number of columns
* @param numParticipants the desired number of participants
* @return the number of needed rows
*/
private int calculateNumOfRows(int numColumns, int numParticipants) {
/*
int extraRow = addExtraRow(numColumns, numParticipants);
// By making it an integer, we ensure that it will be the right number
int firstRowMiddleParticipants = numColumns-2;
return ((numParticipants - firstRowMiddleParticipants)/2) + extraRow;
*/
// By making it an integer, we ensure that it will be the right number
int firstRowMiddleParticipants = numColumns - 2;
return ((numParticipants - firstRowMiddleParticipants - firstRowMiddleParticipants) / 2)+1;
}
/**
*
* NOT USED ANYMORE.
*
* Checks if the adding of the two parameters produces an odd number, in which case a extra row is needed
*
* @param numColumns the number of columns of the table
* @param numParticipants the number of participants in the table
* @return 1 if a row must be added, 0 otherwise
*/
@SuppressWarnings("unused")
private int addExtraRow(int numColumns, int numParticipants){
// Check if the adding of the two parameters produces an odd number
if (Utils.isOdd(numColumns + numParticipants)){
// If so, needs an extra row
return 1;
}
return 0;
}
private boolean isMiddleColumn(int column){
int pos = mNumColumns/2 + 1;
return pos == column;
}
/**
* Creates the table layout with the participants
*
* @param rows the number of rows of the table
* @param cols the number of columns of the table
*/
private void buildTable(int rows, int cols) {
int numAddedParticipants = 0;
int pixelSizeForRow = calculatePaddingBetweenRows(rows);
boolean isModeratorAdded = false;
// Create rows
for (int i = 1; i <= rows; i++) {
TableRow row = new TableRow(this);
row.setLayoutParams(new TableLayout.LayoutParams(TableLayout.LayoutParams.MATCH_PARENT,
TableLayout.LayoutParams.WRAP_CONTENT));
// Create columns
for (int j = 1; j <= cols; j++) {
if (numAddedParticipants < mNumParticipants){
if (i == 1){ // First row
numAddedParticipants = createAndAddParticipantView(numAddedParticipants, pixelSizeForRow, row);
}else if (i == rows){ // Last row
if (isMiddleColumn(j)) {
// Add Moderator
isModeratorAdded = createAndAddModerator(pixelSizeForRow, row);
} else {
// Get the position of the participant in the bottom left corner
if (j == 1) {
mParticipantPosInCorner = numAddedParticipants;
}
// Create and add all participantView except moderator
numAddedParticipants = createAndAddParticipantView(numAddedParticipants, pixelSizeForRow, row);
}
}else if (j == 1 || j == cols){ // First or last column
// Create the ParticipantView
numAddedParticipants = createAndAddParticipantView(numAddedParticipants, pixelSizeForRow, row);
} else{ // Columns in between
// Add an empty image to the row
row.addView(new ImageView(context));
}
} else{
// Last check to see if the moderator was added
if(!isModeratorAdded){
isModeratorAdded = createAndAddModerator(pixelSizeForRow, row);
}
}
}
// Add the row to the table
tableLayoutOfParticipants.addView(row);
}
}
/**
* Creates a ImageView that represents a moderator and adds it to the row
*
* @param pixelSizeForRow the size for the row in pixels
* @param row the row where the ImageView is added
* @return true if no exception arose
*/
private boolean createAndAddModerator(int pixelSizeForRow, TableRow row) {
mModeratorImage = new ImageView(this);
mModeratorImage.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT,
pixelSizeForRow - SUBTRACT_TO_ROW_SIZE));
// Set the margins of the ParticipantView
setMargins(mModeratorImage, Constants.MARGIN_IMAGEVIEW_IN_TABLE_SIDES, Constants.MARGIN_IMAGEVIEW_IN_TABLE_BOTTOM,
Constants.MARGIN_IMAGEVIEW_IN_TABLE_SIDES, Constants.MARGIN_IMAGEVIEW_IN_TABLE_BOTTOM);
// Set the click listener
mModeratorImage.setOnClickListener(mOnModeratorClickListener);
mModeratorImage.setImageResource(R.drawable.btn_moderator_normal);
row.addView(mModeratorImage);
return true;
}
/**
*
* Creates a ParticipantView, sets the click listeners on it, adds it to the HashMap and adds it to the row.
*
* @param numAddedParticipants the number of added participants
* @param pixelSizeForRow the size for the row in pixels
* @param row the row where the ImageView is added
* @return the number of added participants so far
*/
private int createAndAddParticipantView(int numAddedParticipants, int pixelSizeForRow, TableRow row) {
// Create the ParticipantView
ParticipantView participantView = new ParticipantView(context, numAddedParticipants);
participantView.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT,
pixelSizeForRow - SUBTRACT_TO_ROW_SIZE));
// Set the margins of the ParticipantView
setMargins(participantView, Constants.MARGIN_IMAGEVIEW_IN_TABLE_SIDES, Constants.MARGIN_IMAGEVIEW_IN_TABLE_BOTTOM,
Constants.MARGIN_IMAGEVIEW_IN_TABLE_SIDES, Constants.MARGIN_IMAGEVIEW_IN_TABLE_BOTTOM);
// Set its position in the list as tag, so it can be found afterwards
participantView.setTag(numAddedParticipants);
// Set the gesture detector
final GestureDetector gdt = new GestureDetector(context, new MyGestureDetector(participantView));
participantView.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
gdt.onTouchEvent(event);
return true;
}
});
// Create and add the participant to the List
mParticipants.add(createParticipant(numAddedParticipants));
// Add it to the Hashmap
mIdAndViewHashMap.put(new ParticipantID(numAddedParticipants), participantView);
row.addView(participantView);
return ++numAddedParticipants;
}
/**
* Sets the margins of the View passed as parameter, in pixels.
*
* @param v the view whose margins are gonna be set
* @param left the left margin size
* @param top the top margin size
* @param right the right margin size
* @param bottom the bottom margin size
*/
public static void setMargins(View v, int left, int top, int right, int bottom) {
if (v.getLayoutParams() instanceof ViewGroup.MarginLayoutParams) {
ViewGroup.MarginLayoutParams p = (ViewGroup.MarginLayoutParams) v.getLayoutParams();
p.setMargins(left, top, right, bottom);
v.requestLayout();
}
}
/**
* Calculates the padding between the rows of the table so all the space in the screen is taken (that means,
* the first row is at the top and the last row at the bottom).
*
* @param numRows the number of rows of the table
* @return the padding between the rows so all the space in the screen is taken
*/
private int calculatePaddingBetweenRows(int numRows) {
// Get the height of the window
int windowHeight = Utils.getWindowHeight(this);
// Subtract to the windows height the different bars
windowHeight = windowHeight
-Utils.getActionBarHeight(this)
-Utils.getNavigationBarHeight(this)
-Utils.getStatusBarHeight(this)
-TOP_MARGIN_OF_TABLE;
return windowHeight/numRows;
}
/**
* Creates a Participant whose name is its position in the list of participants mParticipants converted to String
* and the different time statistics the current time.
*
* @param num the position of the Participant in the list of participants
* @return the created Participant
*/
private Participant createParticipant(int num) {
return new Participant.Builder(new ParticipantID(num)).name("Num"+num).build();
}
///////////////////////////////////////////////////////////
// ON CLICK LISTENERS AND RELATED METHODS
///////////////////////////////////////////////////////////
/**
* Give the turn to a participant or puts their in the waiting list
*/
private View.OnClickListener mOnModeratorClickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
if(mShowCaseView != null){
mShowCaseView.hide();
if (!hasParticipantShowCaseBeenShown) {
generateShowCaseViewForParticipant();
hasParticipantShowCaseBeenShown = true;
}
}
if (mDebateHasEnded) {
// Go to Results Activity
Intent goToResultsIntent = new Intent(context, ResultsActivity.class);
goToResultsIntent.putExtra(Constants.EXTRA_LIST_PARTICIPANTS, (ArrayList) mParticipants);
startActivity(goToResultsIntent);
} else if (!mDebateHasStarted) {
// Start the timer of the debate
startTimer(DEBATE_TOTAL_TIME_TIMER);
} else {
// Show remaining time
long remainingMinutes = mScheduleFutureDebate.getDelay(TimeUnit.SECONDS);
Toast.makeText(context, new InterventionTime(remainingMinutes).toString() + getString(R.string.moderation_toast_remaining_debate_time), Toast.LENGTH_SHORT).show();
}
}
};
///////////////////////////////////////////////////////////
// TIMER RELATED
///////////////////////////////////////////////////////////
/**
* The runnable that is called when the time for the speaker is up.
*/
private Runnable mInterventionTimeEndedRunnable = new Runnable() {
public void run() {
try {
makeDeviceVibrate();
makeDeviceBeep();
// Add the time of their intervention to their profile
mCurrentParticipant.addTime(mParticipantTimeLimit);
runOnUiThread(new Runnable() {
@Override
public void run() {
// Change the image to timeout
changeToTimeOutImage(TIMEOUT_PARTICIPANT, R.drawable.btn_participant_speaking_timeout_normal);
Toast.makeText(context, getString(R.string.moderation_toast_intervention_time_ended), Toast.LENGTH_SHORT).show();
}
});
startTimer(PARTICIPANT_INTERVENTION_TIMER);
}catch (Exception e){
Log.e(TAG, "Error. Most likely due to the use of ScheduledExecutorService." );
e.printStackTrace();
}
}
};
/**
* The runnable that is called when the time of the debate is up.
*/
private Runnable mDebateTimeEndedRunnable = new Runnable() {
public void run() {
mDebateHasEnded = true;
mDebateHasStarted = false;
makeDeviceVibrate();
makeDeviceBeep();
try{
runOnUiThread(new Runnable() {
@Override
public void run() {
// Change the image to timeout
changeToTimeOutImage(TIMEOUT_DEBATE, R.drawable.btn_moderator_timeout_normal);
Toast.makeText(context, getString(R.string.moderation_toast_debate_time_ended), Toast.LENGTH_LONG).show();
}
});
} catch (Exception e) {
Log.e(TAG, "Error. Most likely due to the use of ScheduledExecutorService.");
e.printStackTrace();
}
}
};
/**
* Starts the timer
*/
private void startTimer(int timerType) {
final ScheduledExecutorService mScheduledTaskExecutor = Executors.newScheduledThreadPool(1);
switch (timerType){
case PARTICIPANT_INTERVENTION_TIMER:
mScheduleFutureIntervention = mScheduledTaskExecutor.schedule(mInterventionTimeEndedRunnable, mParticipantTimeLimit, TimeUnit.SECONDS);
break;
case DEBATE_TOTAL_TIME_TIMER:
Toast.makeText(context, getString(R.string.moderation_toast_debate_timer_start), Toast.LENGTH_SHORT).show();
mScheduleFutureDebate = mScheduledTaskExecutor.schedule(mDebateTimeEndedRunnable, mDebateTimeLimit, TimeUnit.SECONDS);
mDebateHasStarted = true;
break;
}
}
///////////////////////////////////////////////////////////
// CURRENT-PARTICIPANT RELATED
///////////////////////////////////////////////////////////
/**
* Gives the turn to the participant passed by parameter and starts the timer. Changes its image to speaking.
*
* @param participant the participant that will receive the speaking turn
*/
private void assignSpeakingTurn(Participant participant) {
mCurrentParticipant = participant;
Toast.makeText(context, getString(R.string.moderation_toast_assign_turn_to_participant) + mCurrentParticipant.toString(), Toast.LENGTH_SHORT).show();
ParticipantView pView = mIdAndViewHashMap.get(participant.getId());
pView.setWaitingListPos("");
pView.showWaitingListPos();
pView.setParticipantImage((R.drawable.participant_speaking_selector));
startTimer(PARTICIPANT_INTERVENTION_TIMER);
}
/**
* The current participant finishes their intervention and therefore the timer is removed and the turn given to the
* first person in the waiting list
*/
private void participantFinishedTheirIntervention() {
// Add the time of their intervention to their profile
long remainingTimeFromTimer = mScheduleFutureIntervention.getDelay(TimeUnit.SECONDS);
mCurrentParticipant.addTimeAndIntervention(mParticipantTimeLimit - remainingTimeFromTimer);
// Cancel the timer
mScheduleFutureIntervention.cancel(true);
Toast.makeText(context, mCurrentParticipant.toString() + getString(R.string.moderation_toast_participant_finished_intervention), Toast.LENGTH_SHORT).show();
// Reset the view
resetParticipantView(mIdAndViewHashMap.get(mCurrentParticipant.getId()));
mCurrentParticipant = null;
}
///////////////////////////////////////////////////////////
// WAITING LIST
///////////////////////////////////////////////////////////
/**
* Puts the participant in the waiting list and changes its image to waiting in list
*
* @param participant the ParticipantView to be put in the waiting list
*/
private void putInWaitingList(ParticipantView participant) {
Toast.makeText(context, participant.getParticipantName() + getResources().getQuantityString(R.plurals.moderation_toast_participant_added_to_queue, mWaitingList.size(), mWaitingList.size()), Toast.LENGTH_SHORT).show();
mWaitingList.add(participant);
participant.setParticipantImage(R.drawable.participant_waiting_selector);
// Update the waiting list
updateWaitingListView();
}
/**
* Removes the participant from the waiting list
*
* @param participantView the ParticipantView to be removed from the waiting list
*/
private void removeFromWaitingList(ParticipantView participantView) {
// Update the view of the participant that is about to be removed
resetParticipantView(participantView);
mWaitingList.remove(participantView);
Toast.makeText(context, participantView.getParticipantName() + getResources().getQuantityString(R.plurals.moderation_toast_remove_participant_from_queue, mWaitingList.size(), mWaitingList.size()), Toast.LENGTH_SHORT).show();
// Update the waiting list
updateWaitingListView();
}
///////////////////////////////////////////////////////////
// HELPING METHODS
///////////////////////////////////////////////////////////
private boolean isTheParticipantIdInTheWaitingList(ParticipantID participantId){
return mWaitingList.contains(mIdAndViewHashMap.get(participantId));
}
private boolean isTheWaitingListEmpty(){
return mWaitingList.size() == 0;
}
private boolean isTheParticipantTalking(ParticipantID participantId){
//noinspection SimplifiableIfStatement
if(mCurrentParticipant == null) {
return false; // no one is talking
}
return participantId.equals(mCurrentParticipant.getId());
}
/**
* Resets and hides the position of the waiting list from the ParticipantView of the currentParticipant and changes
* its image to listening.
*/
private void resetParticipantView(ParticipantView pView) {
pView.setWaitingListPos("");
pView.hideWaitingListPos();
pView.setParticipantImage(R.drawable.participant_listening_selector);
}
/**
* Updates the index of all the ParticipantView in the waiting list
*/
private void updateWaitingListView() {
int i = 1;
for (ParticipantView participantView : mWaitingList) {
participantView.setWaitingListPos(Integer.toString(i++));
participantView.showWaitingListPos();
}
}
private void makeDeviceBeep() {
// Make the device beep
ToneGenerator toneG = new ToneGenerator(AudioManager.STREAM_ALARM, 100);
toneG.startTone(ToneGenerator.TONE_CDMA_ALERT_CALL_GUARD, 2000);
}
private void makeDeviceVibrate() {
// Make the device vibrate
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
v.vibrate(DEVICE_VIBRATION_IN_MILLISECONDS);
}
private void changeToTimeOutImage(int typeOfTimeout, int resourceId) {
switch (typeOfTimeout) {
case TIMEOUT_PARTICIPANT:
ParticipantView pView = mIdAndViewHashMap.get(mCurrentParticipant.getId());
pView.setParticipantImage(resourceId);
break;
case TIMEOUT_DEBATE:
mModeratorImage.setImageResource(resourceId);
break;
}
}
///////////////////////////////////////////////////////////
// POPUP / DIALOG IMPLEMENTATION
///////////////////////////////////////////////////////////
/**
* Creates and shows a ParticipantStatisticsDialogFragment with the statistics of the participant and allowing to
* change the name of their.
* @param participant the participant whose name can be changed and statistics seen.
*/
public void showParticipantStatisticsDialog(Participant participant) {
// Create an instance of the dialog fragment and show it
ParticipantStatisticsDialogFragment dialog = new ParticipantStatisticsDialogFragment();
// Give the dialog the reference to the Participant
Bundle args = new Bundle();
args.putParcelable(Constants.KEY_ARG_PARTICIPANT, participant);
dialog.setArguments(args);
dialog.show(getSupportFragmentManager(), "ParticipantStatisticsDialogFragment");
}
/**
* Changes the name of the double clicked participant mEditedParticipant to the one set by the user in the dialog
* @param dialogFragment the fragment containing the EditText with the new name for the participant
*/
@Override
public void onDialogPositiveClick(DialogFragment dialogFragment) {
Dialog dialog = dialogFragment.getDialog();
EditText inputTemp = (EditText) dialog.findViewById(R.id.participant_popup_name_editText);
String newName = inputTemp.getText().toString();
mEditedParticipant.setName(newName);
mEditedParticipantView.setParticipantName(newName);
}
///////////////////////////////////////////////////////////
// MY GESTURE DETECTOR CLASS
///////////////////////////////////////////////////////////
/**
* Small class to handle the click, long click and double click of the participantViews
*/
private class MyGestureDetector extends GestureDetector.SimpleOnGestureListener {
// The ParticipantView that was touched
ParticipantView mTouchedParticipantView;
public MyGestureDetector(ParticipantView tpv){
mTouchedParticipantView = tpv;
}
@Override
public boolean onDown(MotionEvent e) {
// Needs to return true for the other methods to work
return true;
}
/**
* Takes the turn from the speaking Participant or removes it from the waiting list
*/
@Override
public void onLongPress(MotionEvent event) {
Participant clickedParticipant = mParticipants.get((int) mTouchedParticipantView.getTag());
ParticipantID clickParticipantID = clickedParticipant.getId();
if (isTheParticipantTalking(clickParticipantID)) { // Clicked on talking person
participantFinishedTheirIntervention();
} else {
if (isTheParticipantIdInTheWaitingList(clickParticipantID)) {
removeFromWaitingList(mTouchedParticipantView);
}
}
}
/**
* Opens a ParticipantStatisticsDialog
*/
@Override
public boolean onDoubleTap(MotionEvent e) {
// Mark the participant as the edited one
mEditedParticipantView = mTouchedParticipantView;
mEditedParticipant = mParticipants.get((int) mTouchedParticipantView.getTag());
showParticipantStatisticsDialog(mEditedParticipant);
return true;
}
/**
* Give the turn to a participant or puts their in the waiting list
*/
@Override
public boolean onSingleTapConfirmed(MotionEvent event) {
if(mShowCaseView != null){
mShowCaseView.hide();
// Mark the app as having been used
SharedPreferences.Editor editor = mSharedPref.edit();
editor.putBoolean(Constants.SHARED_PREF_FIRST_TIME, false);
editor.apply();
}
Participant clickedParticipant = mParticipants.get((int) mTouchedParticipantView.getTag());
ParticipantID clickParticipantID = clickedParticipant.getId();
// No one is talking
if (mCurrentParticipant == null) {
if (isTheWaitingListEmpty()) {
assignSpeakingTurn(clickedParticipant);
} else {
if (isTheParticipantIdInTheWaitingList(clickParticipantID)) {
removeFromWaitingList(mTouchedParticipantView);
assignSpeakingTurn(clickedParticipant);
} else {
putInWaitingList(mTouchedParticipantView);
}
}
} else { // Someone talks
if (!isTheParticipantTalking(clickParticipantID)) {
// Clicked on someone not talking
if (!isTheParticipantIdInTheWaitingList(clickParticipantID)) {
putInWaitingList(mTouchedParticipantView);
}
}
}
return false;
}
}
///////////////////////////////////////////////////////////
// SHOWCASES FOR THE FIRST TIME THAT THE APP IS USED
///////////////////////////////////////////////////////////
private void generateShowCaseViewForModerator() {
Target moderatorTarget = new Target() {
@Override
public Point getPoint() {
// Store the position of the moderator
int[] location = new int[2];
mModeratorImage.getLocationInWindow(location);
int height = mModeratorImage.getHeight();
int width = mModeratorImage.getWidth();
return new Point(location[0] + height / 2, location[1] + width / 2);
}
};
mShowCaseView = new ShowcaseView.Builder(this)
.setContentTitle(getString(R.string.moderation_showcase_moderator_title))
.setContentText(getString(R.string.moderation_showcase_moderator_text))
.setTarget(moderatorTarget)
.build();
// Customize the ShowcaseView
mShowCaseView.hideButton();
mShowCaseView.setShouldCentreText(true);
}
private void generateShowCaseViewForParticipant() {
Target participantTarget = new Target() {
@Override
public Point getPoint() {
// Get position of participant in bottom left corner
ParticipantView participantView = getParticipantFromBottomLeftCorner();
int[] location = new int[2];
participantView.getLocationInWindow(location);
int height = participantView.getHeight();
int width = participantView.getWidth();
return new Point(location[0] + height / 2, location[1] + width / 2);
}
private ParticipantView getParticipantFromBottomLeftCorner() {
return mIdAndViewHashMap.get(mParticipants.get(mParticipantPosInCorner).getId());
}
};
mShowCaseView = new ShowcaseView.Builder(this)
.setContentTitle(getString(R.string.moderation_showcase_participant_title))
.setContentText(getString(R.string.moderation_showcase_participant_text))
.setTarget(participantTarget)
.build();
// Customize the ShowcaseView
mShowCaseView.hideButton();
mShowCaseView.setShouldCentreText(true);
mShowCaseView.setHideOnTouchOutside(true);
}
///////////////////////////////////////////////////////////
// MENU RELATED
///////////////////////////////////////////////////////////
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_moderation, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_add_participant) {
// TODO Add a participant
Toast.makeText(context, "Functionality not available yet",Toast.LENGTH_SHORT).show();
return true;
}
return super.onOptionsItemSelected(item);
}
}
| true |
7d3785f2d748a4fce7f7e9527d8222c78a267545 | Java | FH-SE-Master/Model-Driven-Engineering | /Project/src/eclipse/at.ooe.fh.mdm.herzog.dsl.proj.ProjectGenerator/src-gen/at/ooe/fh/mdm/herzog/dsl/proj/projectGenerator/ProjectGeneratorPackage.java | UTF-8 | 39,212 | 1.523438 | 2 | [] | no_license | /**
* generated by Xtext 2.10.0
*/
package at.ooe.fh.mdm.herzog.dsl.proj.projectGenerator;
import org.eclipse.emf.ecore.EAttribute;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EEnum;
import org.eclipse.emf.ecore.EPackage;
import org.eclipse.emf.ecore.EReference;
/**
* <!-- begin-user-doc -->
* The <b>Package</b> for the model.
* It contains accessors for the meta objects to represent
* <ul>
* <li>each class,</li>
* <li>each feature of each class,</li>
* <li>each enum,</li>
* <li>and each data type</li>
* </ul>
* <!-- end-user-doc -->
* @see at.ooe.fh.mdm.herzog.dsl.proj.projectGenerator.ProjectGeneratorFactory
* @model kind="package"
* @generated
*/
public interface ProjectGeneratorPackage extends EPackage
{
/**
* The package name.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
String eNAME = "projectGenerator";
/**
* The package namespace URI.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
String eNS_URI = "http://www.ooe.at/fh/mdm/herzog/dsl/proj/ProjectGenerator";
/**
* The package namespace name.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
String eNS_PREFIX = "projectGenerator";
/**
* The singleton instance of the package.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
ProjectGeneratorPackage eINSTANCE = at.ooe.fh.mdm.herzog.dsl.proj.projectGenerator.impl.ProjectGeneratorPackageImpl.init();
/**
* The meta object id for the '{@link at.ooe.fh.mdm.herzog.dsl.proj.projectGenerator.impl.ModuleImpl <em>Module</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see at.ooe.fh.mdm.herzog.dsl.proj.projectGenerator.impl.ModuleImpl
* @see at.ooe.fh.mdm.herzog.dsl.proj.projectGenerator.impl.ProjectGeneratorPackageImpl#getModule()
* @generated
*/
int MODULE = 0;
/**
* The feature id for the '<em><b>Name</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int MODULE__NAME = 0;
/**
* The feature id for the '<em><b>Key</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int MODULE__KEY = 1;
/**
* The feature id for the '<em><b>Cdi Enabled</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int MODULE__CDI_ENABLED = 2;
/**
* The feature id for the '<em><b>Message Bundles</b></em>' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int MODULE__MESSAGE_BUNDLES = 3;
/**
* The feature id for the '<em><b>Observers</b></em>' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int MODULE__OBSERVERS = 4;
/**
* The feature id for the '<em><b>Jpa Config</b></em>' containment reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int MODULE__JPA_CONFIG = 5;
/**
* The feature id for the '<em><b>Service Config</b></em>' containment reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int MODULE__SERVICE_CONFIG = 6;
/**
* The number of structural features of the '<em>Module</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int MODULE_FEATURE_COUNT = 7;
/**
* The meta object id for the '{@link at.ooe.fh.mdm.herzog.dsl.proj.projectGenerator.impl.ServiceConfigImpl <em>Service Config</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see at.ooe.fh.mdm.herzog.dsl.proj.projectGenerator.impl.ServiceConfigImpl
* @see at.ooe.fh.mdm.herzog.dsl.proj.projectGenerator.impl.ProjectGeneratorPackageImpl#getServiceConfig()
* @generated
*/
int SERVICE_CONFIG = 1;
/**
* The feature id for the '<em><b>Observers</b></em>' reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int SERVICE_CONFIG__OBSERVERS = 0;
/**
* The feature id for the '<em><b>Message Bundles</b></em>' reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int SERVICE_CONFIG__MESSAGE_BUNDLES = 1;
/**
* The number of structural features of the '<em>Service Config</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int SERVICE_CONFIG_FEATURE_COUNT = 2;
/**
* The meta object id for the '{@link at.ooe.fh.mdm.herzog.dsl.proj.projectGenerator.impl.ObserverImpl <em>Observer</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see at.ooe.fh.mdm.herzog.dsl.proj.projectGenerator.impl.ObserverImpl
* @see at.ooe.fh.mdm.herzog.dsl.proj.projectGenerator.impl.ProjectGeneratorPackageImpl#getObserver()
* @generated
*/
int OBSERVER = 2;
/**
* The feature id for the '<em><b>Name</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int OBSERVER__NAME = 0;
/**
* The feature id for the '<em><b>Type</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int OBSERVER__TYPE = 1;
/**
* The feature id for the '<em><b>During</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int OBSERVER__DURING = 2;
/**
* The feature id for the '<em><b>Notify</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int OBSERVER__NOTIFY = 3;
/**
* The feature id for the '<em><b>Class Name</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int OBSERVER__CLASS_NAME = 4;
/**
* The feature id for the '<em><b>Qualifier</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int OBSERVER__QUALIFIER = 5;
/**
* The number of structural features of the '<em>Observer</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int OBSERVER_FEATURE_COUNT = 6;
/**
* The meta object id for the '{@link at.ooe.fh.mdm.herzog.dsl.proj.projectGenerator.impl.JpaConfigImpl <em>Jpa Config</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see at.ooe.fh.mdm.herzog.dsl.proj.projectGenerator.impl.JpaConfigImpl
* @see at.ooe.fh.mdm.herzog.dsl.proj.projectGenerator.impl.ProjectGeneratorPackageImpl#getJpaConfig()
* @generated
*/
int JPA_CONFIG = 3;
/**
* The feature id for the '<em><b>Localized Enums</b></em>' reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int JPA_CONFIG__LOCALIZED_ENUMS = 0;
/**
* The feature id for the '<em><b>Observers</b></em>' reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int JPA_CONFIG__OBSERVERS = 1;
/**
* The number of structural features of the '<em>Jpa Config</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int JPA_CONFIG_FEATURE_COUNT = 2;
/**
* The meta object id for the '{@link at.ooe.fh.mdm.herzog.dsl.proj.projectGenerator.impl.LocalizedImpl <em>Localized</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see at.ooe.fh.mdm.herzog.dsl.proj.projectGenerator.impl.LocalizedImpl
* @see at.ooe.fh.mdm.herzog.dsl.proj.projectGenerator.impl.ProjectGeneratorPackageImpl#getLocalized()
* @generated
*/
int LOCALIZED = 4;
/**
* The feature id for the '<em><b>Name</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int LOCALIZED__NAME = 0;
/**
* The feature id for the '<em><b>Values</b></em>' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int LOCALIZED__VALUES = 1;
/**
* The number of structural features of the '<em>Localized</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int LOCALIZED_FEATURE_COUNT = 2;
/**
* The meta object id for the '{@link at.ooe.fh.mdm.herzog.dsl.proj.projectGenerator.impl.LocalizedEntryImpl <em>Localized Entry</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see at.ooe.fh.mdm.herzog.dsl.proj.projectGenerator.impl.LocalizedEntryImpl
* @see at.ooe.fh.mdm.herzog.dsl.proj.projectGenerator.impl.ProjectGeneratorPackageImpl#getLocalizedEntry()
* @generated
*/
int LOCALIZED_ENTRY = 5;
/**
* The feature id for the '<em><b>Localized Key</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int LOCALIZED_ENTRY__LOCALIZED_KEY = 0;
/**
* The feature id for the '<em><b>Values</b></em>' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int LOCALIZED_ENTRY__VALUES = 1;
/**
* The feature id for the '<em><b>Args</b></em>' attribute list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int LOCALIZED_ENTRY__ARGS = 2;
/**
* The number of structural features of the '<em>Localized Entry</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int LOCALIZED_ENTRY_FEATURE_COUNT = 3;
/**
* The meta object id for the '{@link at.ooe.fh.mdm.herzog.dsl.proj.projectGenerator.impl.LocalizedValueImpl <em>Localized Value</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see at.ooe.fh.mdm.herzog.dsl.proj.projectGenerator.impl.LocalizedValueImpl
* @see at.ooe.fh.mdm.herzog.dsl.proj.projectGenerator.impl.ProjectGeneratorPackageImpl#getLocalizedValue()
* @generated
*/
int LOCALIZED_VALUE = 6;
/**
* The feature id for the '<em><b>Locale</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int LOCALIZED_VALUE__LOCALE = 0;
/**
* The feature id for the '<em><b>Value</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int LOCALIZED_VALUE__VALUE = 1;
/**
* The number of structural features of the '<em>Localized Value</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int LOCALIZED_VALUE_FEATURE_COUNT = 2;
/**
* The meta object id for the '{@link at.ooe.fh.mdm.herzog.dsl.proj.projectGenerator.Locale <em>Locale</em>}' enum.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see at.ooe.fh.mdm.herzog.dsl.proj.projectGenerator.Locale
* @see at.ooe.fh.mdm.herzog.dsl.proj.projectGenerator.impl.ProjectGeneratorPackageImpl#getLocale()
* @generated
*/
int LOCALE = 7;
/**
* The meta object id for the '{@link at.ooe.fh.mdm.herzog.dsl.proj.projectGenerator.Boolean <em>Boolean</em>}' enum.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see at.ooe.fh.mdm.herzog.dsl.proj.projectGenerator.Boolean
* @see at.ooe.fh.mdm.herzog.dsl.proj.projectGenerator.impl.ProjectGeneratorPackageImpl#getBoolean()
* @generated
*/
int BOOLEAN = 8;
/**
* The meta object id for the '{@link at.ooe.fh.mdm.herzog.dsl.proj.projectGenerator.During <em>During</em>}' enum.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see at.ooe.fh.mdm.herzog.dsl.proj.projectGenerator.During
* @see at.ooe.fh.mdm.herzog.dsl.proj.projectGenerator.impl.ProjectGeneratorPackageImpl#getDuring()
* @generated
*/
int DURING = 9;
/**
* The meta object id for the '{@link at.ooe.fh.mdm.herzog.dsl.proj.projectGenerator.Notify <em>Notify</em>}' enum.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see at.ooe.fh.mdm.herzog.dsl.proj.projectGenerator.Notify
* @see at.ooe.fh.mdm.herzog.dsl.proj.projectGenerator.impl.ProjectGeneratorPackageImpl#getNotify()
* @generated
*/
int NOTIFY = 10;
/**
* Returns the meta object for class '{@link at.ooe.fh.mdm.herzog.dsl.proj.projectGenerator.Module <em>Module</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for class '<em>Module</em>'.
* @see at.ooe.fh.mdm.herzog.dsl.proj.projectGenerator.Module
* @generated
*/
EClass getModule();
/**
* Returns the meta object for the attribute '{@link at.ooe.fh.mdm.herzog.dsl.proj.projectGenerator.Module#getName <em>Name</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Name</em>'.
* @see at.ooe.fh.mdm.herzog.dsl.proj.projectGenerator.Module#getName()
* @see #getModule()
* @generated
*/
EAttribute getModule_Name();
/**
* Returns the meta object for the attribute '{@link at.ooe.fh.mdm.herzog.dsl.proj.projectGenerator.Module#getKey <em>Key</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Key</em>'.
* @see at.ooe.fh.mdm.herzog.dsl.proj.projectGenerator.Module#getKey()
* @see #getModule()
* @generated
*/
EAttribute getModule_Key();
/**
* Returns the meta object for the attribute '{@link at.ooe.fh.mdm.herzog.dsl.proj.projectGenerator.Module#getCdiEnabled <em>Cdi Enabled</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Cdi Enabled</em>'.
* @see at.ooe.fh.mdm.herzog.dsl.proj.projectGenerator.Module#getCdiEnabled()
* @see #getModule()
* @generated
*/
EAttribute getModule_CdiEnabled();
/**
* Returns the meta object for the containment reference list '{@link at.ooe.fh.mdm.herzog.dsl.proj.projectGenerator.Module#getMessageBundles <em>Message Bundles</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the containment reference list '<em>Message Bundles</em>'.
* @see at.ooe.fh.mdm.herzog.dsl.proj.projectGenerator.Module#getMessageBundles()
* @see #getModule()
* @generated
*/
EReference getModule_MessageBundles();
/**
* Returns the meta object for the containment reference list '{@link at.ooe.fh.mdm.herzog.dsl.proj.projectGenerator.Module#getObservers <em>Observers</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the containment reference list '<em>Observers</em>'.
* @see at.ooe.fh.mdm.herzog.dsl.proj.projectGenerator.Module#getObservers()
* @see #getModule()
* @generated
*/
EReference getModule_Observers();
/**
* Returns the meta object for the containment reference '{@link at.ooe.fh.mdm.herzog.dsl.proj.projectGenerator.Module#getJpaConfig <em>Jpa Config</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the containment reference '<em>Jpa Config</em>'.
* @see at.ooe.fh.mdm.herzog.dsl.proj.projectGenerator.Module#getJpaConfig()
* @see #getModule()
* @generated
*/
EReference getModule_JpaConfig();
/**
* Returns the meta object for the containment reference '{@link at.ooe.fh.mdm.herzog.dsl.proj.projectGenerator.Module#getServiceConfig <em>Service Config</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the containment reference '<em>Service Config</em>'.
* @see at.ooe.fh.mdm.herzog.dsl.proj.projectGenerator.Module#getServiceConfig()
* @see #getModule()
* @generated
*/
EReference getModule_ServiceConfig();
/**
* Returns the meta object for class '{@link at.ooe.fh.mdm.herzog.dsl.proj.projectGenerator.ServiceConfig <em>Service Config</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for class '<em>Service Config</em>'.
* @see at.ooe.fh.mdm.herzog.dsl.proj.projectGenerator.ServiceConfig
* @generated
*/
EClass getServiceConfig();
/**
* Returns the meta object for the reference list '{@link at.ooe.fh.mdm.herzog.dsl.proj.projectGenerator.ServiceConfig#getObservers <em>Observers</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the reference list '<em>Observers</em>'.
* @see at.ooe.fh.mdm.herzog.dsl.proj.projectGenerator.ServiceConfig#getObservers()
* @see #getServiceConfig()
* @generated
*/
EReference getServiceConfig_Observers();
/**
* Returns the meta object for the reference list '{@link at.ooe.fh.mdm.herzog.dsl.proj.projectGenerator.ServiceConfig#getMessageBundles <em>Message Bundles</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the reference list '<em>Message Bundles</em>'.
* @see at.ooe.fh.mdm.herzog.dsl.proj.projectGenerator.ServiceConfig#getMessageBundles()
* @see #getServiceConfig()
* @generated
*/
EReference getServiceConfig_MessageBundles();
/**
* Returns the meta object for class '{@link at.ooe.fh.mdm.herzog.dsl.proj.projectGenerator.Observer <em>Observer</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for class '<em>Observer</em>'.
* @see at.ooe.fh.mdm.herzog.dsl.proj.projectGenerator.Observer
* @generated
*/
EClass getObserver();
/**
* Returns the meta object for the attribute '{@link at.ooe.fh.mdm.herzog.dsl.proj.projectGenerator.Observer#getName <em>Name</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Name</em>'.
* @see at.ooe.fh.mdm.herzog.dsl.proj.projectGenerator.Observer#getName()
* @see #getObserver()
* @generated
*/
EAttribute getObserver_Name();
/**
* Returns the meta object for the attribute '{@link at.ooe.fh.mdm.herzog.dsl.proj.projectGenerator.Observer#getType <em>Type</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Type</em>'.
* @see at.ooe.fh.mdm.herzog.dsl.proj.projectGenerator.Observer#getType()
* @see #getObserver()
* @generated
*/
EAttribute getObserver_Type();
/**
* Returns the meta object for the attribute '{@link at.ooe.fh.mdm.herzog.dsl.proj.projectGenerator.Observer#getDuring <em>During</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>During</em>'.
* @see at.ooe.fh.mdm.herzog.dsl.proj.projectGenerator.Observer#getDuring()
* @see #getObserver()
* @generated
*/
EAttribute getObserver_During();
/**
* Returns the meta object for the attribute '{@link at.ooe.fh.mdm.herzog.dsl.proj.projectGenerator.Observer#getNotify <em>Notify</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Notify</em>'.
* @see at.ooe.fh.mdm.herzog.dsl.proj.projectGenerator.Observer#getNotify()
* @see #getObserver()
* @generated
*/
EAttribute getObserver_Notify();
/**
* Returns the meta object for the attribute '{@link at.ooe.fh.mdm.herzog.dsl.proj.projectGenerator.Observer#getClassName <em>Class Name</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Class Name</em>'.
* @see at.ooe.fh.mdm.herzog.dsl.proj.projectGenerator.Observer#getClassName()
* @see #getObserver()
* @generated
*/
EAttribute getObserver_ClassName();
/**
* Returns the meta object for the attribute '{@link at.ooe.fh.mdm.herzog.dsl.proj.projectGenerator.Observer#getQualifier <em>Qualifier</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Qualifier</em>'.
* @see at.ooe.fh.mdm.herzog.dsl.proj.projectGenerator.Observer#getQualifier()
* @see #getObserver()
* @generated
*/
EAttribute getObserver_Qualifier();
/**
* Returns the meta object for class '{@link at.ooe.fh.mdm.herzog.dsl.proj.projectGenerator.JpaConfig <em>Jpa Config</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for class '<em>Jpa Config</em>'.
* @see at.ooe.fh.mdm.herzog.dsl.proj.projectGenerator.JpaConfig
* @generated
*/
EClass getJpaConfig();
/**
* Returns the meta object for the reference list '{@link at.ooe.fh.mdm.herzog.dsl.proj.projectGenerator.JpaConfig#getLocalizedEnums <em>Localized Enums</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the reference list '<em>Localized Enums</em>'.
* @see at.ooe.fh.mdm.herzog.dsl.proj.projectGenerator.JpaConfig#getLocalizedEnums()
* @see #getJpaConfig()
* @generated
*/
EReference getJpaConfig_LocalizedEnums();
/**
* Returns the meta object for the reference list '{@link at.ooe.fh.mdm.herzog.dsl.proj.projectGenerator.JpaConfig#getObservers <em>Observers</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the reference list '<em>Observers</em>'.
* @see at.ooe.fh.mdm.herzog.dsl.proj.projectGenerator.JpaConfig#getObservers()
* @see #getJpaConfig()
* @generated
*/
EReference getJpaConfig_Observers();
/**
* Returns the meta object for class '{@link at.ooe.fh.mdm.herzog.dsl.proj.projectGenerator.Localized <em>Localized</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for class '<em>Localized</em>'.
* @see at.ooe.fh.mdm.herzog.dsl.proj.projectGenerator.Localized
* @generated
*/
EClass getLocalized();
/**
* Returns the meta object for the attribute '{@link at.ooe.fh.mdm.herzog.dsl.proj.projectGenerator.Localized#getName <em>Name</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Name</em>'.
* @see at.ooe.fh.mdm.herzog.dsl.proj.projectGenerator.Localized#getName()
* @see #getLocalized()
* @generated
*/
EAttribute getLocalized_Name();
/**
* Returns the meta object for the containment reference list '{@link at.ooe.fh.mdm.herzog.dsl.proj.projectGenerator.Localized#getValues <em>Values</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the containment reference list '<em>Values</em>'.
* @see at.ooe.fh.mdm.herzog.dsl.proj.projectGenerator.Localized#getValues()
* @see #getLocalized()
* @generated
*/
EReference getLocalized_Values();
/**
* Returns the meta object for class '{@link at.ooe.fh.mdm.herzog.dsl.proj.projectGenerator.LocalizedEntry <em>Localized Entry</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for class '<em>Localized Entry</em>'.
* @see at.ooe.fh.mdm.herzog.dsl.proj.projectGenerator.LocalizedEntry
* @generated
*/
EClass getLocalizedEntry();
/**
* Returns the meta object for the attribute '{@link at.ooe.fh.mdm.herzog.dsl.proj.projectGenerator.LocalizedEntry#getLocalizedKey <em>Localized Key</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Localized Key</em>'.
* @see at.ooe.fh.mdm.herzog.dsl.proj.projectGenerator.LocalizedEntry#getLocalizedKey()
* @see #getLocalizedEntry()
* @generated
*/
EAttribute getLocalizedEntry_LocalizedKey();
/**
* Returns the meta object for the containment reference list '{@link at.ooe.fh.mdm.herzog.dsl.proj.projectGenerator.LocalizedEntry#getValues <em>Values</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the containment reference list '<em>Values</em>'.
* @see at.ooe.fh.mdm.herzog.dsl.proj.projectGenerator.LocalizedEntry#getValues()
* @see #getLocalizedEntry()
* @generated
*/
EReference getLocalizedEntry_Values();
/**
* Returns the meta object for the attribute list '{@link at.ooe.fh.mdm.herzog.dsl.proj.projectGenerator.LocalizedEntry#getArgs <em>Args</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute list '<em>Args</em>'.
* @see at.ooe.fh.mdm.herzog.dsl.proj.projectGenerator.LocalizedEntry#getArgs()
* @see #getLocalizedEntry()
* @generated
*/
EAttribute getLocalizedEntry_Args();
/**
* Returns the meta object for class '{@link at.ooe.fh.mdm.herzog.dsl.proj.projectGenerator.LocalizedValue <em>Localized Value</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for class '<em>Localized Value</em>'.
* @see at.ooe.fh.mdm.herzog.dsl.proj.projectGenerator.LocalizedValue
* @generated
*/
EClass getLocalizedValue();
/**
* Returns the meta object for the attribute '{@link at.ooe.fh.mdm.herzog.dsl.proj.projectGenerator.LocalizedValue#getLocale <em>Locale</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Locale</em>'.
* @see at.ooe.fh.mdm.herzog.dsl.proj.projectGenerator.LocalizedValue#getLocale()
* @see #getLocalizedValue()
* @generated
*/
EAttribute getLocalizedValue_Locale();
/**
* Returns the meta object for the attribute '{@link at.ooe.fh.mdm.herzog.dsl.proj.projectGenerator.LocalizedValue#getValue <em>Value</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Value</em>'.
* @see at.ooe.fh.mdm.herzog.dsl.proj.projectGenerator.LocalizedValue#getValue()
* @see #getLocalizedValue()
* @generated
*/
EAttribute getLocalizedValue_Value();
/**
* Returns the meta object for enum '{@link at.ooe.fh.mdm.herzog.dsl.proj.projectGenerator.Locale <em>Locale</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for enum '<em>Locale</em>'.
* @see at.ooe.fh.mdm.herzog.dsl.proj.projectGenerator.Locale
* @generated
*/
EEnum getLocale();
/**
* Returns the meta object for enum '{@link at.ooe.fh.mdm.herzog.dsl.proj.projectGenerator.Boolean <em>Boolean</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for enum '<em>Boolean</em>'.
* @see at.ooe.fh.mdm.herzog.dsl.proj.projectGenerator.Boolean
* @generated
*/
EEnum getBoolean();
/**
* Returns the meta object for enum '{@link at.ooe.fh.mdm.herzog.dsl.proj.projectGenerator.During <em>During</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for enum '<em>During</em>'.
* @see at.ooe.fh.mdm.herzog.dsl.proj.projectGenerator.During
* @generated
*/
EEnum getDuring();
/**
* Returns the meta object for enum '{@link at.ooe.fh.mdm.herzog.dsl.proj.projectGenerator.Notify <em>Notify</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for enum '<em>Notify</em>'.
* @see at.ooe.fh.mdm.herzog.dsl.proj.projectGenerator.Notify
* @generated
*/
EEnum getNotify();
/**
* Returns the factory that creates the instances of the model.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the factory that creates the instances of the model.
* @generated
*/
ProjectGeneratorFactory getProjectGeneratorFactory();
/**
* <!-- begin-user-doc -->
* Defines literals for the meta objects that represent
* <ul>
* <li>each class,</li>
* <li>each feature of each class,</li>
* <li>each enum,</li>
* <li>and each data type</li>
* </ul>
* <!-- end-user-doc -->
* @generated
*/
interface Literals
{
/**
* The meta object literal for the '{@link at.ooe.fh.mdm.herzog.dsl.proj.projectGenerator.impl.ModuleImpl <em>Module</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see at.ooe.fh.mdm.herzog.dsl.proj.projectGenerator.impl.ModuleImpl
* @see at.ooe.fh.mdm.herzog.dsl.proj.projectGenerator.impl.ProjectGeneratorPackageImpl#getModule()
* @generated
*/
EClass MODULE = eINSTANCE.getModule();
/**
* The meta object literal for the '<em><b>Name</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute MODULE__NAME = eINSTANCE.getModule_Name();
/**
* The meta object literal for the '<em><b>Key</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute MODULE__KEY = eINSTANCE.getModule_Key();
/**
* The meta object literal for the '<em><b>Cdi Enabled</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute MODULE__CDI_ENABLED = eINSTANCE.getModule_CdiEnabled();
/**
* The meta object literal for the '<em><b>Message Bundles</b></em>' containment reference list feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EReference MODULE__MESSAGE_BUNDLES = eINSTANCE.getModule_MessageBundles();
/**
* The meta object literal for the '<em><b>Observers</b></em>' containment reference list feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EReference MODULE__OBSERVERS = eINSTANCE.getModule_Observers();
/**
* The meta object literal for the '<em><b>Jpa Config</b></em>' containment reference feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EReference MODULE__JPA_CONFIG = eINSTANCE.getModule_JpaConfig();
/**
* The meta object literal for the '<em><b>Service Config</b></em>' containment reference feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EReference MODULE__SERVICE_CONFIG = eINSTANCE.getModule_ServiceConfig();
/**
* The meta object literal for the '{@link at.ooe.fh.mdm.herzog.dsl.proj.projectGenerator.impl.ServiceConfigImpl <em>Service Config</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see at.ooe.fh.mdm.herzog.dsl.proj.projectGenerator.impl.ServiceConfigImpl
* @see at.ooe.fh.mdm.herzog.dsl.proj.projectGenerator.impl.ProjectGeneratorPackageImpl#getServiceConfig()
* @generated
*/
EClass SERVICE_CONFIG = eINSTANCE.getServiceConfig();
/**
* The meta object literal for the '<em><b>Observers</b></em>' reference list feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EReference SERVICE_CONFIG__OBSERVERS = eINSTANCE.getServiceConfig_Observers();
/**
* The meta object literal for the '<em><b>Message Bundles</b></em>' reference list feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EReference SERVICE_CONFIG__MESSAGE_BUNDLES = eINSTANCE.getServiceConfig_MessageBundles();
/**
* The meta object literal for the '{@link at.ooe.fh.mdm.herzog.dsl.proj.projectGenerator.impl.ObserverImpl <em>Observer</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see at.ooe.fh.mdm.herzog.dsl.proj.projectGenerator.impl.ObserverImpl
* @see at.ooe.fh.mdm.herzog.dsl.proj.projectGenerator.impl.ProjectGeneratorPackageImpl#getObserver()
* @generated
*/
EClass OBSERVER = eINSTANCE.getObserver();
/**
* The meta object literal for the '<em><b>Name</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute OBSERVER__NAME = eINSTANCE.getObserver_Name();
/**
* The meta object literal for the '<em><b>Type</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute OBSERVER__TYPE = eINSTANCE.getObserver_Type();
/**
* The meta object literal for the '<em><b>During</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute OBSERVER__DURING = eINSTANCE.getObserver_During();
/**
* The meta object literal for the '<em><b>Notify</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute OBSERVER__NOTIFY = eINSTANCE.getObserver_Notify();
/**
* The meta object literal for the '<em><b>Class Name</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute OBSERVER__CLASS_NAME = eINSTANCE.getObserver_ClassName();
/**
* The meta object literal for the '<em><b>Qualifier</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute OBSERVER__QUALIFIER = eINSTANCE.getObserver_Qualifier();
/**
* The meta object literal for the '{@link at.ooe.fh.mdm.herzog.dsl.proj.projectGenerator.impl.JpaConfigImpl <em>Jpa Config</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see at.ooe.fh.mdm.herzog.dsl.proj.projectGenerator.impl.JpaConfigImpl
* @see at.ooe.fh.mdm.herzog.dsl.proj.projectGenerator.impl.ProjectGeneratorPackageImpl#getJpaConfig()
* @generated
*/
EClass JPA_CONFIG = eINSTANCE.getJpaConfig();
/**
* The meta object literal for the '<em><b>Localized Enums</b></em>' reference list feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EReference JPA_CONFIG__LOCALIZED_ENUMS = eINSTANCE.getJpaConfig_LocalizedEnums();
/**
* The meta object literal for the '<em><b>Observers</b></em>' reference list feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EReference JPA_CONFIG__OBSERVERS = eINSTANCE.getJpaConfig_Observers();
/**
* The meta object literal for the '{@link at.ooe.fh.mdm.herzog.dsl.proj.projectGenerator.impl.LocalizedImpl <em>Localized</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see at.ooe.fh.mdm.herzog.dsl.proj.projectGenerator.impl.LocalizedImpl
* @see at.ooe.fh.mdm.herzog.dsl.proj.projectGenerator.impl.ProjectGeneratorPackageImpl#getLocalized()
* @generated
*/
EClass LOCALIZED = eINSTANCE.getLocalized();
/**
* The meta object literal for the '<em><b>Name</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute LOCALIZED__NAME = eINSTANCE.getLocalized_Name();
/**
* The meta object literal for the '<em><b>Values</b></em>' containment reference list feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EReference LOCALIZED__VALUES = eINSTANCE.getLocalized_Values();
/**
* The meta object literal for the '{@link at.ooe.fh.mdm.herzog.dsl.proj.projectGenerator.impl.LocalizedEntryImpl <em>Localized Entry</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see at.ooe.fh.mdm.herzog.dsl.proj.projectGenerator.impl.LocalizedEntryImpl
* @see at.ooe.fh.mdm.herzog.dsl.proj.projectGenerator.impl.ProjectGeneratorPackageImpl#getLocalizedEntry()
* @generated
*/
EClass LOCALIZED_ENTRY = eINSTANCE.getLocalizedEntry();
/**
* The meta object literal for the '<em><b>Localized Key</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute LOCALIZED_ENTRY__LOCALIZED_KEY = eINSTANCE.getLocalizedEntry_LocalizedKey();
/**
* The meta object literal for the '<em><b>Values</b></em>' containment reference list feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EReference LOCALIZED_ENTRY__VALUES = eINSTANCE.getLocalizedEntry_Values();
/**
* The meta object literal for the '<em><b>Args</b></em>' attribute list feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute LOCALIZED_ENTRY__ARGS = eINSTANCE.getLocalizedEntry_Args();
/**
* The meta object literal for the '{@link at.ooe.fh.mdm.herzog.dsl.proj.projectGenerator.impl.LocalizedValueImpl <em>Localized Value</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see at.ooe.fh.mdm.herzog.dsl.proj.projectGenerator.impl.LocalizedValueImpl
* @see at.ooe.fh.mdm.herzog.dsl.proj.projectGenerator.impl.ProjectGeneratorPackageImpl#getLocalizedValue()
* @generated
*/
EClass LOCALIZED_VALUE = eINSTANCE.getLocalizedValue();
/**
* The meta object literal for the '<em><b>Locale</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute LOCALIZED_VALUE__LOCALE = eINSTANCE.getLocalizedValue_Locale();
/**
* The meta object literal for the '<em><b>Value</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute LOCALIZED_VALUE__VALUE = eINSTANCE.getLocalizedValue_Value();
/**
* The meta object literal for the '{@link at.ooe.fh.mdm.herzog.dsl.proj.projectGenerator.Locale <em>Locale</em>}' enum.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see at.ooe.fh.mdm.herzog.dsl.proj.projectGenerator.Locale
* @see at.ooe.fh.mdm.herzog.dsl.proj.projectGenerator.impl.ProjectGeneratorPackageImpl#getLocale()
* @generated
*/
EEnum LOCALE = eINSTANCE.getLocale();
/**
* The meta object literal for the '{@link at.ooe.fh.mdm.herzog.dsl.proj.projectGenerator.Boolean <em>Boolean</em>}' enum.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see at.ooe.fh.mdm.herzog.dsl.proj.projectGenerator.Boolean
* @see at.ooe.fh.mdm.herzog.dsl.proj.projectGenerator.impl.ProjectGeneratorPackageImpl#getBoolean()
* @generated
*/
EEnum BOOLEAN = eINSTANCE.getBoolean();
/**
* The meta object literal for the '{@link at.ooe.fh.mdm.herzog.dsl.proj.projectGenerator.During <em>During</em>}' enum.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see at.ooe.fh.mdm.herzog.dsl.proj.projectGenerator.During
* @see at.ooe.fh.mdm.herzog.dsl.proj.projectGenerator.impl.ProjectGeneratorPackageImpl#getDuring()
* @generated
*/
EEnum DURING = eINSTANCE.getDuring();
/**
* The meta object literal for the '{@link at.ooe.fh.mdm.herzog.dsl.proj.projectGenerator.Notify <em>Notify</em>}' enum.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see at.ooe.fh.mdm.herzog.dsl.proj.projectGenerator.Notify
* @see at.ooe.fh.mdm.herzog.dsl.proj.projectGenerator.impl.ProjectGeneratorPackageImpl#getNotify()
* @generated
*/
EEnum NOTIFY = eINSTANCE.getNotify();
}
} //ProjectGeneratorPackage
| true |
4addcbe87169883ea0433945df433408bb5ff342 | Java | wwh51/gedcom | /src/GedcomLineParser.java | UTF-8 | 1,362 | 2.8125 | 3 | [] | no_license | import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class GedcomLineParser
{
private static final Pattern gedcomPattern = Pattern.compile("\\s*(\\d+)\\s+(\\S+)\\s*(.*)", Pattern.DOTALL);
private String m_strTag;
private String m_strValue;
private Boolean m_bHasId;
private int m_nLevel;
public GedcomLineParser()
{
Init();
}
public Boolean parse(String strLine)
{
Init();
Matcher m = gedcomPattern.matcher(strLine);
if(!m.find())
return false;
m_strTag = m.group(2);
m_strValue = m.group(3).trim();
if(m_strValue.startsWith("@") && m_strValue.endsWith("@") && m_strValue.length() > 2)
{
m_bHasId = true;
}
else if(m_strTag.startsWith("@") && m_strTag.endsWith("@") && m_strTag.length() > 2)
{
if(m_strValue.length() <= 0)
return false;
m_bHasId = true;
m_strTag = m_strValue;
m_strValue = m.group(2);
}
m_strTag = m_strTag.toLowerCase();
m_nLevel = Integer.parseInt(m.group(1));
return true;
}
public Boolean HasId()
{
return m_bHasId;
}
public int getLevel()
{
return m_nLevel;
}
public String getTag()
{
return m_strTag;
}
public String getValue()
{
return m_strValue;
}
private void Init()
{
m_strTag = m_strValue = null;
m_bHasId = false;
}
}
| true |
31bc0fc77e2c534526de811643adf2ed14414eec | Java | mostafa-emad/shop_keeper | /app/src/main/java/com/shoppament/utils/view/UploadFileController.java | UTF-8 | 6,002 | 2.203125 | 2 | [] | no_license | package com.shoppament.utils.view;
import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.provider.MediaStore;
import com.mindorks.paracamera.Camera;
import com.shoppament.R;
import com.shoppament.data.models.PictureModel;
import com.shoppament.utils.AndroidPermissions;
import com.shoppament.utils.FileUtils;
/**
* this controller to manage uploading pictures
*
* from camera or from local device files
*
*/
public class UploadFileController {
public static final int CAPTURE_PHOTO_ID = 1001;
public static final int UPLOAD_PHOTO_ID = 1002;
public static final int PERMISSIONS_CAMERA_REQUEST_CODE = 101;
public static final int PERMISSIONS_FILES_REQUEST_CODE = 102;
private static UploadFileController controller;
private Camera camera;
private AndroidPermissions permissions;
public static UploadFileController getInstance() {
if (controller == null) {
synchronized (UploadFileController.class) {
UploadFileController manager = controller;
if (manager == null) {
synchronized (UploadFileController.class) {
controller = new UploadFileController();
}
}
}
}
return controller;
}
/**
* open camera and capture picture
*
* @param activity
*/
public void capturePicture(Activity activity){
try {
if(camera == null)
initCamera(activity);
camera.takePicture();
}catch (Exception e){
e.printStackTrace();
}
}
/**
* select files from local data
*
* @param activity
*/
public void uploadPictureFromDevice(Activity activity){
try {
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("image/*");
activity.startActivityForResult(intent, UPLOAD_PHOTO_ID);
}catch (Exception e){
e.printStackTrace();
}
}
/**
* init camera to capture the picture
*
* @param activity
*/
private void initCamera(Activity activity) {
camera = new Camera.Builder()
.resetToCorrectOrientation(true)// it will rotate the camera bitmap to the correct orientation from meta data
.setTakePhotoRequestCode(CAPTURE_PHOTO_ID)
.setDirectory("pics")
.setName("pic_" + System.currentTimeMillis())
.setImageFormat(Camera.IMAGE_JPEG)
.setCompression(75)
.setImageHeight(1000)// it will try to achieve this height as close as possible maintaining the aspect ratio;
.build(activity);
}
private void deleteCameraImg(){
if(camera != null)
camera.deleteImage();
}
public Bitmap getCameraPictureSource() {
return camera.getCameraBitmap();
}
public PictureModel getCameraPicture() {
try {
PictureModel pictureModel = new PictureModel();
String path = camera.getCameraBitmapPath();
pictureModel.setPath(path);
pictureModel.setName(path.substring(path.lastIndexOf("/")+1));
return pictureModel;
}catch (Exception e){
e.printStackTrace();
return null;
}
}
public Bitmap getDevicePictureSource(Intent data,Activity activity) {
try {
Uri uri = data.getData();
return MediaStore.Images.Media.getBitmap(activity.getContentResolver(), uri);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public PictureModel getDevicePicture(Intent data, Activity activity) {
try {
Uri uri = data.getData();
if(uri == null)
return null;
PictureModel pictureModel = new PictureModel();
String path = FileUtils.getPath(activity,uri);
pictureModel.setPath(path);
assert path != null;
pictureModel.setName(path.substring(path.lastIndexOf("/")+1));
return pictureModel;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public boolean isCameraEnabled(Activity activity){
permissions = new AndroidPermissions(activity,
Manifest.permission.CAMERA
);
if(!permissions.checkPermissions()){
activity.getResources().getString(R.string.error_upload_services_disabled);
permissions.requestPermissions(PERMISSIONS_CAMERA_REQUEST_CODE);
return false;
}
return true;
}
public boolean isLocalDeviceEnabled(Activity activity){
permissions = new AndroidPermissions(activity,
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE
);
if(!permissions.checkPermissions()){
activity.getResources().getString(R.string.error_upload_services_disabled);
permissions.requestPermissions(PERMISSIONS_FILES_REQUEST_CODE);
return false;
}
return true;
}
public boolean isMediaPermissionsEnabled(Activity activity){
permissions = new AndroidPermissions(activity,
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE
);
if(!permissions.checkPermissions()){
activity.getResources().getString(R.string.error_upload_services_disabled);
permissions.requestPermissions(PERMISSIONS_FILES_REQUEST_CODE);
return false;
}
return true;
}
public AndroidPermissions getPermissions() {
return permissions;
}
}
| true |
477e9bc8245ccf5e884688f7568bc3e25cb13d86 | Java | zhongxingyu/Seer | /Diff-Raw-Data/23/23_fce8e706443240a688757672b84717f5e2718bc4/SwornParkour/23_fce8e706443240a688757672b84717f5e2718bc4_SwornParkour_s.java | UTF-8 | 10,759 | 1.757813 | 2 | [] | no_license | /**
* SwornParkour - a bukkit plugin
* Copyright (C) 2013 dmulloy2
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package net.dmulloy2.swornparkour;
import java.io.File;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.MissingResourceException;
import java.util.logging.Level;
import javax.xml.parsers.DocumentBuilderFactory;
import lombok.Getter;
import net.dmulloy2.swornparkour.commands.*;
import net.dmulloy2.swornparkour.handlers.*;
import net.dmulloy2.swornparkour.listeners.*;
import net.dmulloy2.swornparkour.parkour.objects.*;
import net.milkbowl.vault.economy.Economy;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.RegisteredServiceProvider;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitRunnable;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import com.sk89q.worldedit.bukkit.WorldEditPlugin;
/**
* @author dmulloy2
*/
public class SwornParkour extends JavaPlugin
{
/**Getters**/
private @Getter PermissionHandler permissionHandler;
private @Getter LogHandler logHandler;
private @Getter CommandHandler commandHandler;
private @Getter ResourceHandler resourceHandler;
private @Getter ParkourManager parkourManager;
private @Getter FileHelper fileHelper;
private @Getter WorldEditPlugin worldEdit;
private @Getter Economy economy;
private @Getter String prefix = ChatColor.GOLD + "[Parkour] ";
public List<ParkourZone> loadedArenas = new ArrayList<ParkourZone>();
public List<SavedParkourPlayer> savedPlayers = new ArrayList<SavedParkourPlayer>();
public List<ParkourJoinTask> waiting = new ArrayList<ParkourJoinTask>();
public HashMap<Integer, ParkourReward> parkourRewards = new HashMap<Integer, ParkourReward>();
public int teleportTimer, cashRewardMultiplier;
public boolean cumulativeRewards, itemRewardsEnabled, cashRewardsEnabled, updateChecker, debug;
private double newVersion, currentVersion;
@Override
public void onEnable()
{
long start = System.currentTimeMillis();
logHandler = new LogHandler(this);
commandHandler = new CommandHandler(this);
permissionHandler = new PermissionHandler();
saveResource("messages.properties", true);
resourceHandler = new ResourceHandler(this, this.getClassLoader());
parkourManager = new ParkourManager(this);
fileHelper = new FileHelper(this);
savedPlayers = fileHelper.loadSavedPlayers();
for (Player player : getServer().getOnlinePlayers())
{
for (SavedParkourPlayer savedParkourPlayer : savedPlayers)
{
if (savedParkourPlayer.getName().equals(player.getName()))
{
parkourManager.normalizeSavedPlayer(savedParkourPlayer);
}
}
}
currentVersion = Double.valueOf(getDescription().getVersion().replaceFirst("\\.", ""));
saveDefaultConfig();
loadConfig();
updateRewards();
createDirectories();
loadGames();
PluginManager pm = getServer().getPluginManager();
pm.registerEvents(new PlayerListener(this), this);
pm.registerEvents(new BlockListener(this), this);
setupWorldEdit(pm);
setupVault(pm);
/**Register Commands**/
getCommand("parkour").setExecutor(commandHandler);
commandHandler.setCommandPrefix("parkour");
commandHandler.registerCommand(new CmdAbandon(this));
commandHandler.registerCommand(new CmdClaim(this));
commandHandler.registerCommand(new CmdCreate(this));
commandHandler.registerCommand(new CmdDelete(this));
commandHandler.registerCommand(new CmdHelp(this));
commandHandler.registerCommand(new CmdJoin(this));
commandHandler.registerCommand(new CmdKick(this));
commandHandler.registerCommand(new CmdLeave(this));
commandHandler.registerCommand(new CmdReload(this));
commandHandler.registerCommand(new CmdSetPoint(this));
commandHandler.registerCommand(new CmdSpawn(this));
if (updateChecker)
new UpdateCheckThread().runTaskTimer(this, 0, 432000);
long finish = System.currentTimeMillis();
outConsole("{0} has been enabled ({1}ms)", getDescription().getFullName(), finish - start);
}
private void createDirectories()
{
File games = new File(getDataFolder(), "games");
if (!games.exists()) games.mkdir();
File players = new File(getDataFolder(), "players");
if (!players.exists()) players.mkdir();
}
@Override
public void onDisable()
{
long start = System.currentTimeMillis();
getServer().getServicesManager().unregisterAll(this);
getServer().getScheduler().cancelTasks(this);
for (ParkourZone zone : loadedArenas)
{
fileHelper.save(zone);
}
clearMemory();
long finish = System.currentTimeMillis();
outConsole("{0} has been disabled ({1}ms)", getDescription().getFullName(), finish - start);
}
public void loadGames()
{
File folder = new File(getDataFolder(), "games");
File[] children = folder.listFiles();
for (File file : children)
{
fileHelper.load(file);
}
}
public void loadConfig()
{
teleportTimer = getConfig().getInt("teleport-timer");
cumulativeRewards = getConfig().getBoolean("item-rewards-cumulative");
itemRewardsEnabled = getConfig().getBoolean("item-rewards-enabled");
cashRewardsEnabled = getConfig().getBoolean("cash-reward.enabled");
cashRewardMultiplier = getConfig().getInt("cash-reward.multiplier");
updateChecker = getConfig().getBoolean("update-checker");
debug = getConfig().getBoolean("debug");
}
public void reload()
{
reloadConfig();
updateRewards();
loadConfig();
}
/**Console Logging**/
public void outConsole(String string, Object... objects)
{
logHandler.log(string, objects);
}
public void outConsole(Level level, String string, Object... objects)
{
logHandler.log(level, string, objects);
}
/**Messages**/
public String getMessage(String string)
{
try
{
// TODO: Move all the messages to messages.properties
return resourceHandler.getMessages().getString(string);
}
catch (MissingResourceException ex)
{
logHandler.log(Level.WARNING, "Messages locale is missing key for: {0}", string);
return null;
}
}
private void setupWorldEdit(PluginManager pm)
{
if (pm.isPluginEnabled("WorldEdit"))
{
Plugin worldEditPlugin = pm.getPlugin("WorldEdit");
worldEdit = (WorldEditPlugin)worldEditPlugin;
}
else
{
outConsole(Level.SEVERE, "Could not find WorldEdit! Disabling!");
pm.disablePlugin(this);
}
}
/**Update Rewards Table**/
public void updateRewards()
{
parkourRewards.clear();
for (int i=0; i<25; i++)
{
String reward = getConfig().getString("item-rewards." + i);
fileHelper.readReward(i, reward);
}
outConsole("Loaded all rewards!");
}
public ParkourZone getParkourZone(int gameId)
{
for (ParkourZone zone : loadedArenas)
{
if (zone.getId() == gameId)
{
return zone;
}
}
return null;
}
private void setupVault(PluginManager pm)
{
if (pm.isPluginEnabled("Vault"))
{
setupEconomy();
outConsole(getMessage("log_vault_found"));
}
else
{
outConsole(getMessage("log_vault_notfound"));
}
}
private boolean setupEconomy()
{
RegisteredServiceProvider<Economy> economyProvider = getServer().getServicesManager().getRegistration(Economy.class);
if (economyProvider != null)
{
economy = ((Economy)economyProvider.getProvider());
}
return economy != null;
}
public double updateCheck(double currentVersion)
{
String pluginUrlString = "http://dev.bukkit.org/bukkit-mods/swornparkour/files.rss";
try
{
URL url = new URL(pluginUrlString);
Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(url.openConnection().getInputStream());
doc.getDocumentElement().normalize();
NodeList nodes = doc.getElementsByTagName("item");
Node firstNode = nodes.item(0);
if (firstNode.getNodeType() == 1)
{
Element firstElement = (Element)firstNode;
NodeList firstElementTagName = firstElement.getElementsByTagName("title");
Element firstNameElement = (Element) firstElementTagName.item(0);
NodeList firstNodes = firstNameElement.getChildNodes();
return Double.valueOf(firstNodes.item(0).getNodeValue().replaceAll("[a-zA-Z ]", "").replaceFirst("\\.", ""));
}
}
catch (Exception e)
{
if (debug) outConsole(Level.SEVERE, getMessage("log_update_error"), e.getMessage());
}
return currentVersion;
}
public boolean updateNeeded()
{
return (updateCheck(currentVersion) > currentVersion);
}
private void clearMemory()
{
parkourManager.onShutdown();
parkourRewards.clear();
loadedArenas.clear();
savedPlayers.clear();
waiting.clear();
}
public class UpdateCheckThread extends BukkitRunnable
{
@Override
public void run()
{
try
{
newVersion = updateCheck(currentVersion);
if (newVersion > currentVersion)
{
outConsole(getMessage("log_update"));
outConsole(getMessage("log_update_url"), getMessage("update_url"));
}
}
catch (Exception e)
{
if (debug) outConsole(Level.SEVERE, getMessage("log_update_error"), e.getMessage());
}
}
}
}
| true |
36a6ba1c6d7cab4d08f910d941fe3408e114fced | Java | lanxxz/spider | /src/main/java/com/alien/spider/domain/HttpResult.java | UTF-8 | 1,033 | 2.640625 | 3 | [] | no_license | package com.alien.spider.domain;
/**
* HTTP 请求返回结果
*
* @author Alien
* @since 2019/4/21 17:22
*/
public class HttpResult {
/**
* 状态码
*/
private int code;
/**
* 响应数据
*/
private String content;
public HttpResult() { }
public HttpResult(int code) {
this.code = code;
}
public HttpResult(String content) {
this.content = content;
}
public HttpResult(int code, String content) {
this.code = code;
this.content = content;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
@Override
public String toString() {
return "HttpResult{" + "\n" +
"code=" + code + "\n" +
", content='" + content + '\'' + "\n" +
'}';
}
}
| true |
ef9d307e1dd5dfae00b62bbde456d15ec71aa7b1 | Java | mapstruct/mapstruct | /processor/src/test/java/org/mapstruct/ap/test/conversion/bignumbers/BigDecimalSource.java | UTF-8 | 2,451 | 2.109375 | 2 | [
"Apache-2.0"
] | permissive | /*
* Copyright MapStruct Authors.
*
* Licensed under the Apache License version 2.0, available at http://www.apache.org/licenses/LICENSE-2.0
*/
package org.mapstruct.ap.test.conversion.bignumbers;
import java.math.BigDecimal;
public class BigDecimalSource {
private BigDecimal b;
private BigDecimal bb;
private BigDecimal s;
private BigDecimal ss;
private BigDecimal i;
private BigDecimal ii;
private BigDecimal l;
private BigDecimal ll;
private BigDecimal f;
private BigDecimal ff;
private BigDecimal d;
private BigDecimal dd;
private BigDecimal string;
private BigDecimal bigInteger;
public BigDecimal getB() {
return b;
}
public void setB(BigDecimal b) {
this.b = b;
}
public BigDecimal getBb() {
return bb;
}
public void setBb(BigDecimal bb) {
this.bb = bb;
}
public BigDecimal getS() {
return s;
}
public void setS(BigDecimal s) {
this.s = s;
}
public BigDecimal getSs() {
return ss;
}
public void setSs(BigDecimal ss) {
this.ss = ss;
}
public BigDecimal getI() {
return i;
}
public void setI(BigDecimal i) {
this.i = i;
}
public BigDecimal getIi() {
return ii;
}
public void setIi(BigDecimal ii) {
this.ii = ii;
}
public BigDecimal getL() {
return l;
}
public void setL(BigDecimal l) {
this.l = l;
}
public BigDecimal getLl() {
return ll;
}
public void setLl(BigDecimal ll) {
this.ll = ll;
}
public BigDecimal getF() {
return f;
}
public void setF(BigDecimal f) {
this.f = f;
}
public BigDecimal getFf() {
return ff;
}
public void setFf(BigDecimal ff) {
this.ff = ff;
}
public BigDecimal getD() {
return d;
}
public void setD(BigDecimal d) {
this.d = d;
}
public BigDecimal getDd() {
return dd;
}
public void setDd(BigDecimal dd) {
this.dd = dd;
}
public BigDecimal getString() {
return string;
}
public void setString(BigDecimal string) {
this.string = string;
}
public BigDecimal getBigInteger() {
return bigInteger;
}
public void setBigInteger(BigDecimal bigInteger) {
this.bigInteger = bigInteger;
}
}
| true |
b6813d3658ca87ffdeb179a0d5cd14ebd3b0d20c | Java | Orangeletbear/supsellMS | /src/com/cn/control/kuchunframe/KuCunBaoJingTableSelectAction.java | GB18030 | 1,286 | 1.867188 | 2 | [] | no_license | package com.cn.control.kuchunframe;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.Vector;
import com.cn.dao.kuchun.KunCunBaoJinJDBC;
import com.cn.dao.system.HuiYuanXinGLJDBC;
import com.cn.model.AllTableModel;
import com.cn.model.system.HYSZTableCulomns;
import com.cn.view.kuchunJFrame.KucunBaojin;
import com.cn.view.toolbar.TableCulomnModel;
/**
* 汨еѡݼ
* @author finey
*
*/
public class KuCunBaoJingTableSelectAction extends MouseAdapter {
KucunBaojin frame;
public KuCunBaoJingTableSelectAction(KucunBaojin frame) {
this.frame = frame;
}
public void mouseClicked(MouseEvent arg0) {
if(arg0.getClickCount() ==1){
int row = frame.getTable1().getSelectedRow();
String spID = frame.getTablemodel1().getValueAt(row, 0).toString();
String spName = frame.getTablemodel1().getValueAt(row, 1).toString();
frame.getTextJHXSMX().setText(spName);
Vector data = KunCunBaoJinJDBC.getBaoJingSPXSMassege(spID);
frame.getTablemodel2().setDataVector(data,
AllTableModel.getVectorFromObj(TableCulomnModel.KuCunBaoJingXiaoXi));
}
}
}
| true |
542214a102c5653cffbc6dc62ce342eba912748a | Java | impsharmab/myfca-development-repo | /src/main/java/com/imperialm/imiservices/dao/RetentionGraphDAOImpl.java | UTF-8 | 6,419 | 2.203125 | 2 | [] | no_license | package com.imperialm.imiservices.dao;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Repository;
import com.imperialm.imiservices.dto.RetentionGraphDTO;
@Repository
public class RetentionGraphDAOImpl implements RetentionGraphDAO {
private static Logger logger = LoggerFactory.getLogger(RetentionGraphDAOImpl.class);
@PersistenceContext
private EntityManager em;
@SuppressWarnings("unchecked")
@Override
@Cacheable(value="getRetentionGraphByParentTerritoryList")
public List<RetentionGraphDTO> getRetentionGraphByParentTerritoryList(List<String> list) {
List<RetentionGraphDTO> result = new ArrayList<RetentionGraphDTO>();
try {
final Query query = this.em.createNativeQuery(SELECT_BY_PARENT_TERRITORY_LIST, RetentionGraphDTO.class);
query.setParameter(0, list);
result = query.getResultList();
} catch (final NoResultException ex) {
logger.info("result in else " + result);
} catch (final Exception ex) {
logger.error("error occured in getRetentionGraphByParentTerritoryList", ex);
}
return result;
}
@SuppressWarnings("unchecked")
@Override
@Cacheable(value="getRetentionGraphByChildTerritoryList")
public List<RetentionGraphDTO> getRetentionGraphByChildTerritoryList(List<String> list) {
List<RetentionGraphDTO> result = new ArrayList<RetentionGraphDTO>();
try {
final Query query = this.em.createNativeQuery(SELECT_BY_CHILD_TERRITORY_LIST, RetentionGraphDTO.class);
query.setParameter(0, list);
result = query.getResultList();
} catch (final NoResultException ex) {
logger.info("result in else " + result);
} catch (final Exception ex) {
logger.error("error occured in getRetentionGraphByChildTerritoryList", ex);
}
return result;
}
@SuppressWarnings("unchecked")
@Override
@Cacheable(value="getRetentionGraphByParentTerritoryListAndPositionCode")
public List<RetentionGraphDTO> getRetentionGraphByParentTerritoryListAndPositionCode(List<String> list,
String positionCode) {
List<RetentionGraphDTO> result = new ArrayList<RetentionGraphDTO>();
try {
final Query query = this.em.createNativeQuery(SELECT_BY_PARENT_TERRITORY_LIST_AND_POSITIONCODE, RetentionGraphDTO.class);
query.setParameter(0, list);
query.setParameter(1, positionCode);
result = query.getResultList();
} catch (final NoResultException ex) {
logger.info("result in else " + result);
} catch (final Exception ex) {
logger.error("error occured in getRetentionGraphByParentTerritoryListAndPositionCode", ex);
}
return result;
}
@SuppressWarnings("unchecked")
@Override
@Cacheable(value="getRetentionGraphByChildTerritoryListAndPositionCode")
public List<RetentionGraphDTO> getRetentionGraphByChildTerritoryListAndPositionCode(List<String> list,
String positionCode) {
List<RetentionGraphDTO> result = new ArrayList<RetentionGraphDTO>();
try {
final Query query = this.em.createNativeQuery(SELECT_BY_CHILD_TERRITORY_LIST_AND_POSITIONCODE, RetentionGraphDTO.class);
query.setParameter(0, list);
query.setParameter(1, positionCode);
result = query.getResultList();
} catch (final NoResultException ex) {
logger.info("result in else " + result);
} catch (final Exception ex) {
logger.error("error occured in getRetentionGraphByChildTerritoryListAndPositionCode", ex);
}
return result;
}
@SuppressWarnings("unchecked")
@Override
@Cacheable(value="getRetentionGraphByChildTerritoryAndPositionCode")
public List<RetentionGraphDTO> getRetentionGraphByChildTerritoryListAndPositionCode(String list,
String positionCode) {
List<RetentionGraphDTO> result = new ArrayList<RetentionGraphDTO>();
try {
final Query query = this.em.createNativeQuery(SELECT_BY_CHILD_TERRITORY_AND_POSITIONCODE, RetentionGraphDTO.class);
query.setParameter(0, list);
query.setParameter(1, positionCode);
result = query.getResultList();
} catch (final NoResultException ex) {
logger.info("result in else " + result);
} catch (final Exception ex) {
logger.error("error occured in getRetentionGraphByChildTerritoryListAndPositionCode", ex);
}
return result;
}
@SuppressWarnings("unchecked")
@Override
@Cacheable(value="getRetentionGraphNATByPositionCode")
public List<RetentionGraphDTO> getRetentionGraphNATByPositionCode(String positionCode) {
List<RetentionGraphDTO> result = new ArrayList<RetentionGraphDTO>();
try {
final Query query = this.em.createNativeQuery(SELECT_NAT_BY_POSITIONCODE, RetentionGraphDTO.class);
query.setParameter(0, positionCode);
result = query.getResultList();
} catch (final NoResultException ex) {
logger.info("result in else " + result);
} catch (final Exception ex) {
logger.error("error occured in getRetentionGraphNATByPositionCode", ex);
}
return result;
}
@SuppressWarnings("unchecked")
@Override
@Cacheable(value="getRetentionGraphBCByBcAndPositionCodeByPositionCode")
public List<RetentionGraphDTO> getRetentionGraphBCByBcAndPositionCodeByPositionCode(String bc, String positionCode) {
List<RetentionGraphDTO> result = new ArrayList<RetentionGraphDTO>();
try {
final Query query = this.em.createNativeQuery(SELECT_BY_BC_AND_POSITIONCODE, RetentionGraphDTO.class);
query.setParameter(1, bc);
query.setParameter(0, positionCode);
result = query.getResultList();
} catch (final NoResultException ex) {
logger.info("result in else " + result);
} catch (final Exception ex) {
logger.error("error occured in getRetentionGraphBCByBcAndPositionCodeByPositionCode", ex);
}
return result;
}
@SuppressWarnings("unchecked")
@Override
@Cacheable(value="getRetentionGraphNAT")
public List<RetentionGraphDTO> getRetentionGraphNAT() {
List<RetentionGraphDTO> result = new ArrayList<RetentionGraphDTO>();
try {
final Query query = this.em.createNativeQuery(SELECT_NAT, RetentionGraphDTO.class);
result = query.getResultList();
} catch (final NoResultException ex) {
logger.info("result in else " + result);
} catch (final Exception ex) {
logger.error("error occured in getRetentionGraphNAT", ex);
}
return result;
}
}
| true |
6af0cc3c5c64513741899ebb497525943282be52 | Java | pavel-kuznetsov-5x/pillbox | /app/src/main/java/com/cucumber007/pillbox/utils/PillboxNotificationManager.java | UTF-8 | 11,225 | 1.992188 | 2 | [] | no_license | package com.cucumber007.pillbox.utils;
import android.app.AlarmManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.TaskStackBuilder;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.media.RingtoneManager;
import android.os.RecoverySystem;
import android.util.Log;
import com.cucumber007.pillbox.R;
import com.cucumber007.pillbox.activities.MainActivity;
import com.cucumber007.pillbox.activities.settings.AbstractSettingActivity;
import com.cucumber007.pillbox.activities.settings.NotificationSettingActivity;
import com.cucumber007.pillbox.models.ModelManager;
import com.cucumber007.pillbox.objects.pills.PillboxEvent;
import com.cucumber007.pillbox.objects.water.WaterNotification;
import org.threeten.bp.LocalDate;
import org.threeten.bp.LocalDateTime;
import org.threeten.bp.LocalTime;
import org.threeten.bp.ZoneId;
import org.threeten.bp.ZoneOffset;
import org.threeten.bp.ZonedDateTime;
import org.threeten.bp.temporal.ChronoUnit;
import java.util.List;
public class PillboxNotificationManager extends BroadcastReceiver {
//Class that manages Android Notifications for different events
//время выдачи в 11.00, 13.00, 15.00, 17.00, 19.00.
int START_HOURS = 11;
int QUANTITY = 5;
int DELAY_HOURS = 2;
int START_MINUTES = 0;
int DELAY_DAY_MS = 24*60*60*1000;
// int START_HOURS = LocalDateTime.now().getHour();
// int START_MINUTES = LocalDateTime.now().getMinute();
// int DELAY_HOURS = 2;
// int QUANTITY = 1;
// int DELAY_DAY_MS = 60*1000;
// int DELAY_DAY_MS = 10*1000;
int REQUEST_CODE_REMINDER = 0;
int REQUEST_CODE_WATER = 1;
private static PillboxNotificationManager instance;
private AlarmManager alarmManager;;
private Context context;
public PillboxNotificationManager() {}
public PillboxNotificationManager(Context context) {
this.context = context;
instance = this;
alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
}
public static PillboxNotificationManager getInstance(Context context) {
if (instance == null) {
instance = new PillboxNotificationManager(context);
}
return instance;
}
public void createAlarmsForWater() {
Intent intent = new Intent(context, PillboxNotificationManager.class);
intent.putExtra("type", "water");
LocalDate dateNow = LocalDate.from(LocalDateTime.now());
for (int i = 0; i < QUANTITY; i++) {
if(!isBroadcastExist(i, intent)) {
//Log.d("cutag", ""+"water created");
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, i, intent, PendingIntent.FLAG_UPDATE_CURRENT);
ZonedDateTime setTime = ZonedDateTime.of(dateNow, LocalTime.of(START_HOURS, START_MINUTES).plus(i * DELAY_HOURS, ChronoUnit.HOURS), ZoneId.systemDefault());
//todo interval_day?
ZonedDateTime zoneNow = ZonedDateTime.now(ZoneId.systemDefault()).minus(1, ChronoUnit.MINUTES);
if (setTime.isAfter(zoneNow))
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, setTime.toEpochSecond() * 1000, DELAY_DAY_MS, pendingIntent);
} //else Log.d("cutag", ""+"falsestart");
}
}
public void deleteAlarmsForWater() {
Intent intent = new Intent(context, PillboxNotificationManager.class);
intent.putExtra("type", "water");
for (int i = 0; i < QUANTITY; i++) {
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, i, intent, PendingIntent.FLAG_UPDATE_CURRENT);
alarmManager.cancel(pendingIntent);
}
}
public void createAlarmsForEvents(List<PillboxEvent> events) {
createAlarmsForEvents(events, new RecoverySystem.ProgressListener() {
@Override
public void onProgress(int progress) {
}
});
}
public void createAlarmsForEvents(List<PillboxEvent> events, RecoverySystem.ProgressListener listener) {
for (int i = 0; i < events.size(); i++) {
PillboxEvent event = events.get(i);
setAlarmForEvent(event);
listener.onProgress((int) ((float) i / events.size()));
}
}
public void setAlarmForEvent(PillboxEvent event) {
if (!LocalDateTime.of(event.getDate(), event.getTime()).isBefore(LocalDateTime.now())) {
Intent intent = new Intent(context, PillboxNotificationManager.class);
int id = event.getId();
intent.putExtra("id", id);
/*if (event.getMedName() == null || event.getMedName().equals(""))
Log.d("cutag", "GOT IT");*/
intent.putExtra("med_name", event.getMedName());
intent.putExtra("med_time", event.getTime().toString());
intent.putExtra("type", "pills");
if(!isBroadcastExist(id, intent)) {
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, id, intent, PendingIntent.FLAG_UPDATE_CURRENT);
ZonedDateTime setTime = ZonedDateTime.of(event.getDate(), event.getTime(), ZoneId.systemDefault());
alarmManager.set(AlarmManager.RTC_WAKEUP, setTime.toEpochSecond() * 1000, pendingIntent);
}
}
}
public void deleteAlarmsForEvents(List<PillboxEvent> events) {
deleteAlarmsForEvents(events, new RecoverySystem.ProgressListener() {
@Override
public void onProgress(int progress) {
}
});
}
public void deleteAlarmsForEvents(List<PillboxEvent> events, RecoverySystem.ProgressListener listener) {
for (int i = 0; i < events.size(); i++) {
PillboxEvent event = events.get(i);
deleteAlarmForEvent(event);
listener.onProgress((int)((float) i / events.size()*100));
}
}
public void deleteAlarmForEvent(PillboxEvent event) {
Intent intent = new Intent(context, PillboxNotificationManager.class);
int id = event.getId();
intent.putExtra("id", id);
intent.putExtra("med_name", event.getMedName());
intent.putExtra("med_time", event.getTime().toString());
intent.putExtra("type", "pills");
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, id, intent, PendingIntent.FLAG_UPDATE_CURRENT);
alarmManager.cancel(pendingIntent);
}
@Override
public void onReceive(Context context, Intent intent) {
switch (intent.getStringExtra("type")) {
case "pills":
sendPillboxEventNotification(context, intent);
break;
case "water":
sendWaterEventNotification(context, intent);
break;
}
}
private int buildEventUniqueId(PillboxEvent event) {
long pre = LocalDateTime.of(event.getDate(), event.getTime()).toEpochSecond(ZoneOffset.MIN);
return (int)(pre - ((pre / 1000000) * 1000000));
}
private void sendPillboxEventNotification(Context context, Intent receivedIntent) {
int id = receivedIntent.getIntExtra("id", -1);
if (id == -1) throw new IllegalArgumentException("Id can't be < 0");
String medName = receivedIntent.getStringExtra("med_name");
String medTime = receivedIntent.getStringExtra("med_time");
Log.d("cutag", medName + " " + medTime + " " + id);
Notification.Builder notificationBuilder =
new Notification.Builder(context)
.setSmallIcon(R.drawable.notification_icon)
.setContentTitle(medName)
.setContentText(medTime)
.setAutoCancel(true)
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
Intent resultIntent = new Intent(context, MainActivity.class);
resultIntent.putExtra("fragment", "reminder");
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
stackBuilder.addParentStack(MainActivity.class);
stackBuilder.addNextIntent(resultIntent);
PendingIntent pendingIntent =
stackBuilder.getPendingIntent(
REQUEST_CODE_REMINDER,
PendingIntent.FLAG_UPDATE_CURRENT
);
notificationBuilder.setContentIntent(pendingIntent);
NotificationManager mNotificationManager =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(id + 1, notificationBuilder.build());
}
private void sendWaterEventNotification(Context context, Intent intent) {
String text = WaterNotification.getRandomOne();
Notification.Builder notificationBuilder = new Notification.Builder(context);
notificationBuilder.setContentTitle("Drink water!")
.setContentText(text)
.setSmallIcon(R.drawable.notification_icon)
.setPriority(Notification.PRIORITY_MAX)
.setAutoCancel(true)
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
notificationBuilder.setStyle(new Notification.BigTextStyle(notificationBuilder)
.bigText(text)
.setBigContentTitle("Drink water!")
);
Intent resultIntent = new Intent(context, MainActivity.class);
resultIntent.putExtra("fragment", "water");
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
stackBuilder.addParentStack(MainActivity.class);
stackBuilder.addNextIntent(resultIntent);
PendingIntent pendingIntent =
stackBuilder.getPendingIntent(
REQUEST_CODE_WATER,
PendingIntent.FLAG_UPDATE_CURRENT
);
notificationBuilder.setContentIntent(pendingIntent);
NotificationManager mNotificationManager =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(0, notificationBuilder.build());
}
public void rescheduleAlarms() {
//Log.d("cutag", "reboot");
if(context.getSharedPreferences(AbstractSettingActivity.SETTINGS_SHARED_PREFERENCES, Context.MODE_PRIVATE)
.getBoolean(NotificationSettingActivity.WATER_NOTIFICATIONS, true))
createAlarmsForWater();
if(context.getSharedPreferences(AbstractSettingActivity.SETTINGS_SHARED_PREFERENCES, Context.MODE_PRIVATE)
.getBoolean(NotificationSettingActivity.PILLS_NOTIFICATIONS, true)) {
createAlarmsForEvents(ModelManager.getInstance(context).getReminderModel().getEvents());
}
}
public boolean isBroadcastExist(int id, Intent intent) {
return (PendingIntent.getBroadcast(context, id,
intent, PendingIntent.FLAG_NO_CREATE) != null);
}
}
| true |
20ed466592b402559cc6424fba603b8c396e15d9 | Java | ManaJager/Java2_DZ | /src/ru/gb/dz/java2/kochemasov/lesson2/Main.java | UTF-8 | 531 | 2.5 | 2 | [] | no_license | package ru.gb.dz.java2.kochemasov.lesson2;
import ru.gb.dz.java2.kochemasov.lesson2.exception.MyArrayDataException;
import ru.gb.dz.java2.kochemasov.lesson2.exception.MyArraySizeException;
import ru.gb.dz.java2.kochemasov.lesson2.massive.Massive;
public class Main {
public static void main(String[] args) {
try {
System.out.println(Massive.checkMassive(Massive.massive));
} catch (MyArraySizeException | MyArrayDataException e) {
System.out.println(e.getMessage());
}
}
}
| true |
f533a819f8381b025bee003868dee03086d333e1 | Java | SamuelW2018/HomeworkAssignment3 | /HomeworkAssignment3/src/Teacher.java | UTF-8 | 1,516 | 3.4375 | 3 | [] | no_license |
/**
* Teacher class: A class of teachers which are persons and employees.
* @author swynsma18
*
*/
public class Teacher extends Person implements Employee{
int GradeLevel;
String Certification;
float pay = 10000;
private static int ID = 1;
private int TID;
/**
* Main constructor for teacher.
* @param FN = first name
* @param LN = last name
* @param A = age
* @param PN = phone
*/
public Teacher(String FN, String LN, int A, String PN)
{
super(FN, LN, A, PN);
TID = ID;
ID++;
GradeLevel = 0;
Certification = "Yes";
}
/**
* This constructor is the same as the previous, but sets the certification and the grade level.
* @param G = grade level
* @param C = certification
* @param FN = first name
* @param LN = last name
* @param A = age
* @param PN = phone
*/
public Teacher(int G, String C, String FN, String LN, int A, String PN)
{
super(FN, LN, A, PN);
TID = ID;
ID++;
GradeLevel = G;
Certification = C;
}
/**
* Gets the grade level.
* @return grade level.
*/
public int getGradeLevel() {return GradeLevel;}
/**
* Gets the certification
* @return certification
*/
public String getCertification() {return Certification;}
/**
* Sets the grade level.
* @param GL is the grade level we are setting it to.
*/
public void setGradeLevel(int GL) {GradeLevel = GL;}
/**
* Pays the teacher.
*/
public float givePay() {return pay;}
/**
* Gets the teacher's employee ID.
*/
public int getID() {return TID;}
}
| true |
bb984dcb24db3a105176e29eb744b561a4f0895a | Java | pigletO/freedom | /common/src/main/java/com/pig1et/freedom/common/mapper/TDeliveryOrderMapper.java | UTF-8 | 371 | 1.609375 | 2 | [] | no_license | package com.pig1et.freedom.common.mapper;
import com.pig1et.common.entity.TDeliveryOrder;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
/**
* <p>
* 外卖订单表 t_delivery_order(收配送费和包装费) Mapper 接口
* </p>
*
* @author pig1et
* @since 2021-05-13
*/
public interface TDeliveryOrderMapper extends BaseMapper<TDeliveryOrder> {
}
| true |
7e46dd0a281717b0d8c86a4d55e499114353ada9 | Java | 289043018/Sruts2_Interceptor_Demo | /src/main/java/com/hand/action/UsersAction.java | UTF-8 | 579 | 1.8125 | 2 | [] | no_license | package com.hand.action;
import com.opensymphony.xwork2.ActionSupport;
public class UsersAction extends ActionSupport{
public String add() throws Exception {
System.out.println("进入了Useradd");
return "Userssuccess";
}
public String delete() throws Exception {
System.out.println("进入了Userdelete");
return "Userssuccess";
}
public String show() throws Exception {
System.out.println("进入了Usershow");
return "Userssuccess";
}
public String update() throws Exception {
System.out.println("进入了Userupdate");
return "Userssuccess";
}
}
| true |
fb310d9f199a03a089215630705ffb8f782e4b84 | Java | gemini9640/GAdmin | /src/com/gadmin/entity/ERPRemarks.java | UTF-8 | 1,380 | 2.40625 | 2 | [] | no_license | package com.gadmin.entity;
public class ERPRemarks {
private String REMARKS_ID;
private String REMARKS;
private String USERNAME;
public ERPRemarks(String REMARKS_ID, String REMARKS, String USERNAME) {
this.REMARKS_ID = REMARKS_ID;
this.REMARKS = REMARKS;
this.USERNAME = USERNAME;
}
public ERPRemarks() {
super();
}
public String getREMARKS_ID() {
return REMARKS_ID;
}
public void setREMARKS_ID(String REMARKS_ID) {
this.REMARKS_ID = REMARKS_ID == null ? null : REMARKS_ID.trim();
}
public String getREMARKS() {
return REMARKS;
}
public void setREMARKS(String REMARKS) {
this.REMARKS = REMARKS == null ? null : REMARKS.trim();
}
public String getUSERNAME() {
return USERNAME;
}
public void setUSERNAME(String USERNAME) {
this.USERNAME = USERNAME == null ? null : USERNAME.trim();
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", REMARKS_ID=").append(REMARKS_ID);
sb.append(", REMARKS=").append(REMARKS);
sb.append(", USERNAME=").append(USERNAME);
sb.append("]");
return sb.toString();
}
} | true |
e6439490752284f465833143ee8863cf295cf43b | Java | j256/ormlite-core | /src/test/java/com/j256/ormlite/logger/backend/JavaUtilLogBackendTest.java | UTF-8 | 276 | 1.632813 | 2 | [
"ISC"
] | permissive | package com.j256.ormlite.logger.backend;
import com.j256.ormlite.logger.backend.JavaUtilLogBackend.JavaUtilLogBackendFactory;
public class JavaUtilLogBackendTest extends BaseLogBackendTest {
public JavaUtilLogBackendTest() {
super(new JavaUtilLogBackendFactory());
}
}
| true |
f75c97e4f21960071653d6ed1b2e5f854c9c56a2 | Java | anupamanand1928/ServiceMgmt. | /app/src/main/java/com/example/anupam/zonaldesk/SignUpActivity.java | UTF-8 | 2,658 | 2.25 | 2 | [] | no_license | package com.example.anupam.zonaldesk;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseAuthException;
public class SignUpActivity extends AppCompatActivity {
EditText name,email,password;
FirebaseAuth firebaseAuth;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_up);
firebaseAuth = FirebaseAuth.getInstance();
getSupportActionBar().hide();
name = (EditText)findViewById(R.id.etName);
email = (EditText)findViewById(R.id.etEmail);
password = (EditText)findViewById(R.id.etPassword);
}
public void OnSignUp(View view){
/*String str_name = name.getText().toString().trim();*/
String str_email = email.getText().toString().trim();
String str_password = password.getText().toString();
/*String type = "register";
boolean result = false;
if(str_name.isEmpty()||str_email.isEmpty()||str_password.isEmpty()){
Toast.makeText(getApplicationContext(), "Please enter all the details",Toast.LENGTH_LONG).show();
}
else
{
result = true;
}*/
firebaseAuth.createUserWithEmailAndPassword(str_email,str_password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if(task.isSuccessful()) {
Toast.makeText(SignUpActivity.this, "Registration Successful", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(SignUpActivity.this,MainActivity.class);
startActivity(intent);
}
else{
Toast.makeText(SignUpActivity.this, "Registration Failed", Toast.LENGTH_SHORT).show();
}
}
});
/*BackgroundWorker backgroundWorker = new BackgroundWorker(this);
backgroundWorker.execute(type, str_name, str_email, str_password);*/
}
public void goLogin(View view){
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
}
}
| true |
ea0fdc30dc83607dc4155a6b7052b6274e7d4483 | Java | zglbig/baize | /src/main/java/org/baize/dao/model/PlayerDataTable.java | UTF-8 | 2,207 | 2.328125 | 2 | [] | no_license | package org.baize.dao.model;
import org.baize.utils.assemblybean.annon.DataTable;
import org.baize.utils.excel.DataTableMessage;
import org.baize.utils.excel.StaticConfigMessage;
/**
* 作者: 白泽
* 时间: 2017/11/8.
* 描述:
*/
@DataTable
public class PlayerDataTable implements DataTableMessage{
private final int id;
/**名稱*/
private final String name; // 名称
/**賬號*/
private final String account; // 账号描述
/**密码*/
private final String password;
/**賬號類型*/
private final int loginType; // 账号类型(QQ,WX)
/**排名*/
private final int rank; // 排名
/**性別*/
private final int gender; // 性别
/**頭像*/
private final int head; // 头像
/**描述*/
private final String discibe; //
private final int weekDay;
private final long gold;
private final int diamond;
public PlayerDataTable() {
this.id = 0;
this.name = "";
this.account = "";
this.password = "";
this.loginType = 0;
this.rank = 0;
this.gender = 0;
this.head = 1;
this.discibe = "";
this.weekDay = 0;
this.gold = 0;
this.diamond = 0;
}
public static PlayerDataTable get(int id){
return StaticConfigMessage.getInstance().get(PlayerDataTable.class,id);
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public String getAccount() {
return account;
}
public String getPassword() {
return password;
}
public int getLoginType() {
return loginType;
}
public int getRank() {
return rank;
}
public int getGender() {
return gender;
}
public int getHead() {
return head;
}
public String getDiscibe() {
return discibe;
}
public int getWeekDay() {
return weekDay;
}
public long getGold() {
return gold;
}
public int getDiamond() {
return diamond;
}
@Override
public int id() {
return id;
}
@Override
public void AfterInit() {
}
}
| true |
a55c034da868ad52f6a30af43d595cc6bdc44417 | Java | seokhohong/missing-word | /src/mwutils/Utils.java | UTF-8 | 1,223 | 3 | 3 | [] | no_license | package mwutils;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import utils.ArrayUtils;
import utils.ListUtils;
public class Utils
{
private static Random rnd = new Random();
public static String removeWord(String sentence)
{
String[] tokens = sentence.split(" ");
return ListUtils.join(Arrays.asList(ArrayUtils.cutout(tokens, rnd.nextInt(tokens.length - 3) + 1)), " ");
}
public static String getToken(String chunk)
{
if(chunk.isEmpty()) return "";
if(chunk.equals("_")) return "";
return chunk.split("_")[0];
}
public static String getTag(String chunk)
{
if(chunk.isEmpty()) return "";
if(chunk.equals("_")) return "";
return chunk.split("_")[1];
}
public static String getElem(String[] elems, int index)
{
if(index < 0 || index >= elems.length)
{
return "";
}
return elems[index];
}
public static double normSS(List<Integer> counts)
{
double ss = 0;
int sum = 0;
for(int val : counts)
{
ss += val * val;
sum += val;
}
return Math.sqrt(ss) / sum;
}
public static double normSS(int[] counts)
{
double ss = 0;
int sum = 0;
for(int val : counts)
{
ss += val * val;
sum += val;
}
return Math.sqrt(ss) / sum;
}
}
| true |
5c51f34364d06cbbac8224b18be4a48b010c3b05 | Java | b0xtch/codeanywhere | /MetaLibrary/src/meta/library/model/service/impl/UserManagerImpl.java | UTF-8 | 700 | 2.296875 | 2 | [] | no_license | /**
*
*/
package meta.library.model.service.impl;
import meta.library.model.bean.User;
import meta.library.model.dao.UserDao;
import meta.library.model.service.UserManager;
/**
* @author Biao Zhang
*
*/
public class UserManagerImpl extends BaseManagerImpl<UserDao, User> implements UserManager {
@Override
public User getByUsername(String username) {
return dao.getByUsername(username);
}
@Override
public User addUser(String username, String password, String email) {
User user = new User();
user.setUsername(username);
user.setPassword(password);
user.setEmail(email);
user.setPriviledge(3);
dao.save(user);
return user;
}
}
| true |
b15aa7636337eba47edfc12b5e0e2577dd0a4843 | Java | pavan152208/ToolsQAContactUs | /ToolsQaDemo/src/main/java/com/toolsqa/Runner/Runner.java | UTF-8 | 726 | 1.632813 | 2 | [] | no_license | package com.toolsqa.Runner;
import org.junit.runner.RunWith;
import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;
@RunWith(Cucumber.class)
@CucumberOptions(
features="C:/Users/Pavan/git/ToolsQaDemo/src/main/java/com/toolsqa/features/toolsqaContactUs.feature",//Path of the feature file
glue={"com/toolsqa/stepDefinitions"}// path of the step definitions file
,format={"pretty","html:test-output","json:json_output/cucumber.json","junit:junit_xml/cucumber.xml"},//out report format
monochrome=true,//formatted console output
strict=true,// All the steps need to be executed
dryRun=false // mapping the step definitions and feature file
)
public class Runner {
}
| true |
fcca88064427f3aa4d9dd0471978f3b53588b1c1 | Java | marcosSBXK/SGCM | /src/view/AgendaView.java | UTF-8 | 1,809 | 3 | 3 | [] | no_license | package view;
import java.util.ArrayList;
import java.util.Scanner;
import model.entity.Agenda;
public class AgendaView {
static Scanner entra = new Scanner(System.in);
public static Agenda salvarAgenda() {
String tipo;
int codPaciente;
int idNota;
System.out.println("\n Cadastrar agenda:");
System.out.print(" Tipo: ");
tipo = entra.nextLine();
System.out.print(" Codigo do paciente: ");
codPaciente = entra.nextInt();
System.out.print(" Id da nota: ");
idNota = entra.nextInt();
entra.nextLine();
Agenda agenda = new Agenda(tipo, codPaciente, idNota);
return agenda;
}
public static void exibirAgenda(Agenda agenda) {
System.out.println("\n\t\t Consulta");
System.out.println("-------------------------------------------------------------");
System.out.println("\n\tCod. Agenda\t Tipo\t Paciente\t Nota");
System.out.println("-------------------------------------------------------------");
System.out.printf("\t %d\t%s %d\t %d\n",
agenda.getIdA(), agenda.getTipo(),
agenda.getCodPaciente(), agenda.getIdNota());
}
public static void listarTodasAgendas(ArrayList<Agenda> lista) {
System.out.println("\n\t\t Listagem de consulta");
System.out.println("-------------------------------------------------------------------");
System.out.println("\tCod. Agenda\t Tipo\t Paciente\t Nota");
System.out.println("-------------------------------------------------------------------");
for(int i=0; i<lista.size(); i++){
Agenda agenda = lista.get(i);
System.out.printf("\t %d\t\t %s %d\t\t %d\n",
agenda.getIdA(), agenda.getTipo(),
agenda.getCodPaciente(), agenda.getIdNota());
}
}
} | true |
b9121b1eb6edcd1ec72ffadfe0e812c010716e1a | Java | Mertysahin/JavaCamp | /homeWorks/day3/kodlama-io(homework2)/src/Instructor.java | UTF-8 | 651 | 2.65625 | 3 | [] | no_license |
public class Instructor extends User
{
private String instructorId;
private String courses;
public Instructor(String instructorId,String userName, String userPassword,String firstName,String lastName,String userEmail,String courses)
{
super(userName,firstName,lastName,userEmail,userPassword);
this.instructorId=instructorId;
this.courses=courses;
}
public String getInstructorId() {
return instructorId;
}
public void setInstructorId(String instructorId) {
this.instructorId = instructorId;
}
public String getCourses() {
return courses;
}
public void setCourses(String courses) {
this.courses = courses;
}
}
| true |
25ce0c8a2c88ebf94aeaceedb37baecb332e09c7 | Java | michael0521/MUM-WAA | /StatusReportProject/src/main/java/mum/edu/cs/service/AdminService.java | UTF-8 | 1,277 | 2.375 | 2 | [] | no_license | package mum.edu.cs.service;
import mum.edu.cs.dao.AdminDAO;
import mum.edu.cs.dao.TeacherDAO;
import mum.edu.cs.domain.Professor;
import mum.edu.cs.domain.Student;
import mum.edu.cs.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import java.util.List;
/**
* Created by su on 3/14/16.
*/
@Service
public class AdminService {
@Autowired
private AdminDAO adminDAO;
public List<User> getAll(){
return adminDAO.getAll();
}
public boolean deleteUser(long uid){
return adminDAO.deleteUser(uid);
}
public boolean saveUser(User user){
if(user.getId() > 0 ){
User tmp = adminDAO.getUserById(user.getId());
if(tmp != null && !tmp.getPassword().equals(user.getPassword())){
PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
user.setPassword(passwordEncoder.encode(user.getPassword()));
}
}
return adminDAO.save(user);
}
public User getUserById(Long uid){
return adminDAO.getUserById(uid);
}
}
| true |
7c359dbbf91c91fa1bbcd9036c627b8d77212ba4 | Java | pranlolw/common-code-demo | /src/com/st/thread/MySpinLockDemo.java | UTF-8 | 1,364 | 3.5625 | 4 | [] | no_license | package com.st.thread;
import java.util.concurrent.atomic.AtomicReference;
/**
* 自旋锁
*/
public class MySpinLockDemo {
AtomicReference<Thread> atomicReference=new AtomicReference<>();
public void myLock(){
System.out.println(Thread.currentThread().getName()+"进入lock");
while(!atomicReference.compareAndSet(null,Thread.currentThread())){
}
}
public void myUnLock(){
System.out.println(Thread.currentThread().getName()+"准备解锁");
atomicReference.compareAndSet(Thread.currentThread(),null);
}
public static void main(String[] args) throws InterruptedException {
MySpinLockDemo mySpinLockDemo=new MySpinLockDemo();
new Thread(()->{
mySpinLockDemo.myLock();
System.out.println("线程A加锁,并等待5s");
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
mySpinLockDemo.myUnLock();
System.out.println("线程A解锁");
},"线程A").start();
Thread.sleep(1000);
new Thread(()->{
mySpinLockDemo.myLock();
System.out.println("线程B加锁");
mySpinLockDemo.myUnLock();
System.out.println("线程B解锁");
},"线程B").start();
}
}
| true |
b7468d30cba35e111719228df9f49eb6b12b9238 | Java | zhaowenliang/BuddiesCleanArchitecture | /domain/src/main/java/cc/buddies/cleanarch/domain/repository/PostRepository.java | UTF-8 | 827 | 2.109375 | 2 | [] | no_license | package cc.buddies.cleanarch.domain.repository;
import java.util.List;
import cc.buddies.cleanarch.domain.model.PostModel;
import cc.buddies.cleanarch.domain.request.ReleasePostParams;
import io.reactivex.rxjava3.core.Completable;
import io.reactivex.rxjava3.core.Single;
public interface PostRepository {
/**
* 帖子列表
*
* @param page 页码
* @return Single
*/
Single<List<PostModel>> posts(int page);
/**
* 发布帖子
*
* @param params 参数
* @return Single
*/
Single<PostModel> releasePost(ReleasePostParams params);
/**
* 帖子点赞
*
* @param postId 帖子id
* @param addOrCancel 点赞或取消
* @return Completable
*/
Completable praisePost(long postId, long userId, boolean addOrCancel);
}
| true |
09c870661c4f39669887b20e1f3a4411d3af84cd | Java | byan1197/StayWoke | /app/src/main/java/com/example/bond/staywoke/RingtonePlayingService.java | UTF-8 | 4,411 | 2.296875 | 2 | [] | no_license | package com.example.bond.staywoke;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v4.app.NotificationBuilderWithBuilderAccessor;
import android.util.Log;
import android.widget.Toast;
/**
* Created by bond on 12/07/17.
*/
public class RingtonePlayingService extends Service{
// Unique Identification Number for the Notification.
// We use it on Notification start, and to cancel it.
MediaPlayer mediaSong;
int startId;
boolean isRunning;
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i("LocalService", "Received start id " + startId + ": " + intent);
NotificationManager notifyManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
//SET UP AN INTENT THAT GOES TO THE MAIN ACTIVITY
Intent gameIntent = new Intent(this.getApplicationContext(), DefaultDisable.class);
int gameId= intent.getExtras().getInt("spinner");
if (gameId == 0) {
gameIntent = new Intent(this.getApplicationContext(), DefaultDisable.class);
}
else if (gameId == 1){
gameIntent = new Intent(this.getApplicationContext(), Trivia.class);
}
else if (gameId == 2){
gameIntent = new Intent(this.getApplicationContext(), MathGame.class);
}
else if (gameId == 3){
gameIntent = new Intent(this.getApplicationContext(), RPS.class);
}
else if (gameId == 4){
gameIntent = new Intent(this.getApplicationContext(), DefaultDisable.class);
}
else if (gameId == 5){
gameIntent = new Intent(this.getApplicationContext(), DefaultDisable.class);
}
//Intent intentMainActivity = new Intent(this.getApplicationContext(), MainActivity.class);
//make the notification parameters
//set up a pending intent
PendingIntent pendingIntentMainactivity = PendingIntent.getActivity(this,0,gameIntent,0);
Notification notificationPopup = new Notification.Builder(this)
.setContentTitle("An alarm is going off!")
.setContentText("CLiCK mE!")
.setSmallIcon(R.drawable.ic_access_alarms_black_24dp)
.setContentIntent(pendingIntentMainactivity)
.setAutoCancel(true)
.build();
notifyManager.notify(0,notificationPopup);
gameIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
boolean state = intent.getExtras().getBoolean("isOn");
if (state){
startId=1;
}
else if (!state){
startId=0;
}
else{
startId = 0;
}
if (state)
System.out.println("IN SERVICE: IT IS ON");
else if (!state)
System.out.println("IN SERVICE: IT IS OFF");
mediaSong = MediaPlayer.create(this, R.raw.ring);
if (!this.isRunning && startId ==1){//start the ringtone
mediaSong = MediaPlayer.create(this, R.raw.ring);
mediaSong.start();
startActivity(gameIntent);
this.isRunning=true;
this.startId=0;
}
else if (this.isRunning && startId == 0){
mediaSong.stop();
mediaSong.reset();
this.isRunning=false;
this.startId=0;
}
else if (this.isRunning && startId==1){
this.isRunning = true;
this.startId = 1;
}
else if (!this.isRunning && startId==0){
this.isRunning = false;
this.startId=0;
}
else{
mediaSong.stop();
mediaSong.reset();
this.isRunning = false;
this.startId=0;
}
return START_NOT_STICKY;
}
@Override
public void onDestroy() {
// Cancel the persistent notification.
super.onDestroy();
this.isRunning=false;
// Tell the user we stopped.
Toast.makeText(this, "ON Destroy Called", Toast.LENGTH_SHORT).show();
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
| true |
c326a6ec6f6b4bbb521a98a898188b8d0e2151ce | Java | lokeshbhattarai/designpatterns-examples | /cor/Validator.java | UTF-8 | 940 | 2.921875 | 3 | [
"Apache-2.0"
] | permissive | package cor;
import java.util.ArrayList;
import java.util.List;
public class Validator extends DataProcessor{
FileAccess fileAccess;
@SuppressWarnings("unchecked")
@Override
public void handleRecord(CallRecord callRecord) {
if(callRecord.isEmpty()){
System.out.println("Record is empty so writing to discarded files");
if(fileAccess==null)fileAccess = new FileAccess(Record.filePath);
List<CallRecord> record=null;
try {
record = (List<CallRecord>)fileAccess.read();
} catch (ClassCastException e) {
e.printStackTrace();
}
if(record==null)record = new ArrayList<>();
record.add(callRecord);
fileAccess.write(record);
}else{
System.out.println("Record is validated so passing to next processor");
if(this.nextProcessor!=null){
callRecord.setValid(true);
this.nextProcessor.handleRecord(callRecord);
}
}
}
}
| true |
36045c275866e9717b1bd70afc25bf269d92d517 | Java | rayhan-ferdous/code2vec | /codebase/selected/2185251.java | UTF-8 | 2,779 | 2.59375 | 3 | [] | no_license | package gov.lanl.locator;
import gov.lanl.identifier.sru.SRUDC;
import gov.lanl.identifier.sru.SRUException;
import gov.lanl.identifier.sru.SRUSearchRetrieveResponse;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.StringTokenizer;
public class IdLocatorProxy {
private URL baseurl;
public IdLocatorProxy(URL baseurl) {
if (baseurl == null) throw new NullPointerException("empty baseurl");
this.baseurl = baseurl;
}
public ArrayList<IdLocation> get(String identifier) throws IdLocatorException {
return doGet(identifier);
}
private ArrayList<IdLocation> doGet(String identifier) throws IdLocatorException {
String openurl = baseurl.toString() + "?url_ver=Z39.88-2004&rft_id=" + identifier;
URL url;
SRUSearchRetrieveResponse sru;
try {
url = new URL(openurl);
HttpURLConnection huc = (HttpURLConnection) (url.openConnection());
int code = huc.getResponseCode();
if (code == 200) {
sru = SRUSearchRetrieveResponse.read(huc.getInputStream());
} else throw new IdLocatorException("cannot get " + url.toString());
} catch (MalformedURLException e) {
throw new IdLocatorException("A MalformedURLException occurred for " + openurl);
} catch (IOException e) {
throw new IdLocatorException("An IOException occurred attempting to connect to " + openurl);
} catch (SRUException e) {
throw new IdLocatorException("An SRUException occurred attempting to parse the response");
}
ArrayList<IdLocation> ids = new ArrayList<IdLocation>();
for (SRUDC dc : sru.getRecords()) {
IdLocation id = new IdLocation();
id.setId(dc.getKeys(SRUDC.Key.IDENTIFIER).firstElement());
id.setRepo(dc.getKeys(SRUDC.Key.SOURCE).firstElement());
id.setDate(dc.getKeys(SRUDC.Key.DATE).firstElement());
ids.add(id);
}
Collections.sort(ids);
return ids;
}
public static void main(String[] args) {
try {
IdLocatorProxy proxy = new IdLocatorProxy(new URL(args[0]));
ArrayList<IdLocation> ids = new ArrayList<IdLocation>();
StringTokenizer st = new StringTokenizer(args[1], ",");
while (st.hasMoreTokens()) ids.addAll(proxy.get(st.nextToken()));
for (IdLocation loc : ids) {
System.out.println(loc.getId() + "," + loc.getRepo() + "," + loc.getDate());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
| true |
b9ea02a19c8f5e7d716b365e78fc4b73cd249c6b | Java | abed-nego999/colonya | /colonya-android/plugins/team.sngular.RsiAtmPlugin/src/android/atmsmap/src/main/java/sngular/com/atmsmap/data/listener/OnOfficesRequest.java | UTF-8 | 391 | 1.851563 | 2 | [] | no_license | package sngular.com.atmsmap.data.listener;
import sngular.com.atmsmap.data.model.ErrorEntity;
import sngular.com.atmsmap.data.model.office.OfficeFullResponseEntity;
/**
* Created by alberto.hernandez on 22/04/2016.
*/
public interface OnOfficesRequest {
void onResponse(OfficeFullResponseEntity officeFullResponseEntity);
void onErrorResponse(ErrorEntity error);
}
| true |
3255c0bc0aab25754dba73d548338e3fcd58341e | Java | Cestbo/JspViewListDemo | /src/servlet/SearchServlet.java | UTF-8 | 1,705 | 2.609375 | 3 | [] | no_license | package servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import dao.ItemsDao;
import entity.Items;
/**
* Servlet implementation class SearchServlet
*/
@WebServlet("/SearchServlet")
public class SearchServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public SearchServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
request.setCharacterEncoding("utf-8");
String input=request.getParameter("input");
ItemsDao dao=new ItemsDao();
ArrayList<Items> items=dao.getByKeyword(input);
String result="";
//**注意响应的数据也要编码
response.setCharacterEncoding("utf-8");
PrintWriter out=response.getWriter();
for (Items i:items)
{
String name=i.getName();
result=name+","+i.getNo()+","+result;
}
out.write(result);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
| true |
19753d3aba4bc785f39d55169031d22960c7e4a6 | Java | igormich/HGL | /src/primitives/Plane.java | UTF-8 | 1,661 | 2.78125 | 3 | [] | no_license | package primitives;
import javax.vecmath.Vector3f;
import javax.vecmath.Vector2f;
import properties.Mesh;
public class Plane {
public static Mesh build() {
Mesh result = new Mesh();
result.setRenderParts(Mesh.TEXTURE + Mesh.NORMAL + Mesh.COLOR);
Vector3f red =new Vector3f(1, 0, 0);
Vector3f green =new Vector3f(0, 1, 0);
Vector3f blue =new Vector3f(0, 0, 1);
Vector3f yellow =new Vector3f(1, 1, 0);
Vector3f centerV=new Vector3f(0.0f, 0, 0.0f);
Vector3f leftDownV=new Vector3f(-0.5f, 0, -0.5f);
Vector3f rightDownV=new Vector3f(0.5f, 0, -0.5f);
Vector3f leftUpV=new Vector3f(-0.5f, 0, 0.5f);
Vector3f rightUpV=new Vector3f(0.5f, 0, 0.5f);
result.add(leftDownV, new Vector3f(0, 1, 0), red , new Vector2f(0, 0));
result.add(centerV, new Vector3f(0, 1, 0), red, new Vector2f(0.5f, 0.5f));
result.add(rightDownV, new Vector3f(0, 1, 0), red, new Vector2f(1, 0));
result.add(leftUpV, new Vector3f(0, 1, 0), green, new Vector2f(0, 1));
result.add(centerV, new Vector3f(0, 1, 0), green, new Vector2f(0.5f, 0.5f));
result.add(leftDownV, new Vector3f(0, 1, 0), green, new Vector2f(0, 0));
result.add(rightUpV, new Vector3f(0, 1, 0), blue , new Vector2f(1, 1));
result.add(centerV, new Vector3f(0, 1, 0), blue, new Vector2f(0.5f, 0.5f));
result.add(leftUpV, new Vector3f(0, 1, 0), blue, new Vector2f(0, 1));
result.add(rightDownV, new Vector3f(0, 1, 0), yellow, new Vector2f(1, 0));
result.add(centerV, new Vector3f(0, 1, 0), yellow, new Vector2f(0.5f, 0.5f));
result.add(rightUpV, new Vector3f(0, 1, 0), yellow, new Vector2f(1, 1));
return result;
}
}
| true |
27f397923d42e05009da3d0759b07c00912663c5 | Java | Atinerlengs/android-demo-liqiang | /Contacts&Dialer&Tele&SystemUi/Dialer/java/com/mediatek/incallui/hangup/HangupOptions.java | UTF-8 | 424 | 1.945313 | 2 | [
"Apache-2.0"
] | permissive | package com.mediatek.incallui.hangup;
import android.support.annotation.IntDef;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
/** Options for hangup type. */
@Retention(RetentionPolicy.SOURCE)
@IntDef({
HangupOptions.HANGUP_ALL,
HangupOptions.HANGUP_HOLD,
})
public @interface HangupOptions {
int HANGUP_ALL = 0x00000001;
int HANGUP_HOLD = HANGUP_ALL << 1;
} | true |
16e3268390aef43ebebd325eb59b86905647fcfd | Java | benkoontz/Java-and-SQL-Practice-Problems | /unique_more_code_words.java | UTF-8 | 2,056 | 3.65625 | 4 | [] | no_license | // Here is the alphabent converted to morse code:
/*
[".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."]
return the total number of unique transformations for a set of strings in the arrary words
Example:
Input: words = ["gin", "zen", "gig", "msg"]
Output: 2
Explanation:
The transformation of each word is:
"gin" -> "--...-."
"zen" -> "--...-."
"gig" -> "--...--."
"msg" -> "--...--."
There are 2 different transformations, "--...-." and "--...--.".
*/
class Solution {
public int uniqueMorseRepresentations(String[] words) {
// create a string array to hold the alphabet coverted to morse code
String[] morse = new String[]{".-","-...","-.-.","-..",".","..-.","--.",
"....","..",".---","-.-",".-..","--","-.",
"---",".--.","--.-",".-.","...","-","..-",
"...-",".--","-..-","-.--","--.."};
// create a hashset to hold each unique transformation
// a hashset is good for this because it will disregard duplicates
Set<String> seen = new HashSet();
// loop through each of the words
for(String word: words) { // gin
// create a new string builder
StringBuilder code = new StringBuilder();
// for each charcter in words, convert it to a char array
for(char c: word.toCharArray()) // [g, i, n]
// add each more code chacter
code.append(morse[c - 'a']); // suppose the char c is g, a represent 97
// this will return 104 - 97 since g is represnted
// as 104 in ascii -> morse[7]
// add each morse code to the hashset
seen.add(code.toString());
}
// return the the size of the hashset
return seen.size();
}
}
| true |
a9b4e9212822673fcbe27e0451e821f6fdeec193 | Java | sitaramaraju123/Core | /Pandu/src/ArrayRetrieveDb.java | UTF-8 | 1,322 | 3.171875 | 3 | [] | no_license | package Collections;
import java.util.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
public class ArrayRetrieveDb {
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
Connection con =DriverManager.getConnection("jdbc:mysql:///databasename","root","mysql");
Statement st = con.createStatement();
String q ="select * from employee";
ResultSet rs = st.executeQuery(q);
ArrayList<Data> a = new ArrayList<>();
int count=0;
System.out.print("Enter id or name or age or salary: ");
int name= sc.nextInt();
while(rs.next()) {
Data d = new Data(rs.getInt(1));
a.add(d);
int n=a.size();
int num1=0;
for(int i=0; i<n; i++) {
String num=a.get(i).toString();
num1 =Integer.parseInt(num);
}
if(name==num1) {
count++;
System.out.println(rs.getInt(1)+ "\t" +rs.getString(2)+ "\t" +rs.getInt(3)+ "\t" +rs.getInt(4));
}
}
if(count==0) {
System.out.println("No Data");
}
con.close();
}
}
class Data{
private int num;
//// private String name;
//// private int age;
//// private int salary;
Data(int num){
this.num=num;
}
public String toString() {
return""+num;
}
} | true |
a6bad7496ceebb3b5d3f8053b33137bb509a1a6d | Java | thehelpsf/ChickTech | /app/src/main/java/org/chicktech/chicktech/models/DrawerMenuItem.java | UTF-8 | 396 | 2.078125 | 2 | [] | no_license | package org.chicktech.chicktech.models;
import android.graphics.drawable.Drawable;
/**
* Created by Jing Jin on 10/24/14.
*/
public class DrawerMenuItem {
public String label;
public int iconResourceId;
public DrawerMenuItem() {
}
public DrawerMenuItem(String label, int iconResourceId) {
this.label = label;
this.iconResourceId = iconResourceId;
}
}
| true |
57a4ccfe4f6cf17721c0e0010d192bcb54cbfd00 | Java | mingzhangyong/step | /src/algorithm/algorithm/algorithm/ThreeSum.java | UTF-8 | 2,159 | 3.734375 | 4 | [] | no_license | package algorithm;
import java.util.ArrayList;
import java.util.List;
/**
* @author: mingzhangyong
* @create: 2021-09-29 10:34
* 三数之和
* 给你一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?请你找出所有和为 0 且不重复的三元组。
* <p>
* 注意:答案中不可以包含重复的三元组。
**/
public class ThreeSum {
public List<List<Integer>> threeSum(int[] nums) {
if(nums.length == 0){
return new ArrayList<List<Integer>>();
}
// 排序
for (int i = nums.length -1 ; i >= 0; i--) {
for (int j = 0; j < i; j++) {
if(nums[j] > nums[j+1]){
int jj = nums[j];
nums[j] = nums[j+1];
nums[j+1] = jj;
}
}
}
for (int i = 0; i < nums.length; i++) {
System.out.println("排序后数组:" + i + " -- " + nums[i]);
}
List<List<Integer>> result = new ArrayList<List<Integer>>();
int jj = nums[nums.length - 1];
for (int j = nums.length - 1; j >= 0; j--) {
if(j < nums.length - 1 && jj == nums[j]){
continue;
}
jj = nums[j];
int ii = nums[0];
for (int i = 0; i < j; i++) {
int a = nums[i] + nums[j];
if(i > 0 && ii == nums[i]){
continue;
}
ii = nums[i];
Integer kk = null;
for (int k = i + 1; k < j; k++) {
if (a + nums[k] == 0) {
if(null != kk && kk == nums[k]){
continue;
}
kk = nums[k];
List<Integer> item = new ArrayList<Integer>();
item.add(nums[i]);
item.add(nums[j]);
item.add(nums[k]);
result.add(item);
}
}
}
}
return result;
}
}
| true |
d6fe12c0848157d748d846a274b669ca0082a93e | Java | GowriSankar1305/mm | /spring_workspace/HospitalManagementSystem/domain/src/main/java/com/jocata/model/doctor/Doctor.java | UTF-8 | 872 | 1.992188 | 2 | [] | no_license | package com.jocata.model.doctor;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import com.jocata.model.admin.Admin;
import lombok.Data;
@Data
@Entity
public class Doctor {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private long doctorId;
@Column(nullable=false)
private String doctorName;
@Column(nullable=false)
private String specialization;
@OneToOne(cascade=CascadeType.ALL)
@JoinColumn(name="admin_id",nullable=false)
private Admin admin;
@Column(nullable=false)
private String username;
@Column(nullable=false)
private String password;
private int status;
}
| true |