blob_id
stringlengths
40
40
__id__
int64
225
39,780B
directory_id
stringlengths
40
40
path
stringlengths
6
313
content_id
stringlengths
40
40
detected_licenses
list
license_type
stringclasses
2 values
repo_name
stringlengths
6
132
repo_url
stringlengths
25
151
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
70
visit_date
timestamp[ns]
revision_date
timestamp[ns]
committer_date
timestamp[ns]
github_id
int64
7.28k
689M
star_events_count
int64
0
131k
fork_events_count
int64
0
48k
gha_license_id
stringclasses
23 values
gha_fork
bool
2 classes
gha_event_created_at
timestamp[ns]
gha_created_at
timestamp[ns]
gha_updated_at
timestamp[ns]
gha_pushed_at
timestamp[ns]
gha_size
int64
0
40.4M
gha_stargazers_count
int32
0
112k
gha_forks_count
int32
0
39.4k
gha_open_issues_count
int32
0
11k
gha_language
stringlengths
1
21
gha_archived
bool
2 classes
gha_disabled
bool
1 class
content
stringlengths
7
4.37M
src_encoding
stringlengths
3
16
language
stringclasses
1 value
length_bytes
int64
7
4.37M
extension
stringclasses
24 values
filename
stringlengths
4
174
language_id
stringclasses
1 value
entities
list
contaminating_dataset
stringclasses
0 values
malware_signatures
list
redacted_content
stringlengths
7
4.37M
redacted_length_bytes
int64
7
4.37M
alphanum_fraction
float32
0.25
0.94
alpha_fraction
float32
0.25
0.94
num_lines
int32
1
84k
avg_line_length
float32
0.76
99.9
std_line_length
float32
0
220
max_line_length
int32
5
998
is_vendor
bool
2 classes
is_generated
bool
1 class
max_hex_length
int32
0
319
hex_fraction
float32
0
0.38
max_unicode_length
int32
0
408
unicode_fraction
float32
0
0.36
max_base64_length
int32
0
506
base64_fraction
float32
0
0.5
avg_csv_sep_count
float32
0
4
is_autogen_header
bool
1 class
is_empty_html
bool
1 class
shard
stringclasses
16 values
1c53a31c8700afb62a47710dbeb2df2c2b212319
12,575,664,309,789
1091a59e9a582a4d45b4bbce74188b3b561c6825
/kzscrm-util/src/main/java/com/hd/kzscrm/common/util/ServiceUtil.java
2d5ee57a68d59f6fb344e9377936a546f185fafc
[]
no_license
DongMing0103/RMc
https://github.com/DongMing0103/RMc
d5782e2661a68e62737022d0d8ed55c0d190bb41
ead713f72c47ee2032ea05c7da6b7d842984ff4f
refs/heads/master
2021-06-26T21:57:40.750000
2017-09-15T09:53:11
2017-09-15T09:53:11
103,642,852
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * */ package com.hd.kzscrm.common.util; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.apache.commons.lang.StringUtils; import com.hd.kzscrm.common.enums.DatabaseTableNameEnum; import com.hd.kzscrm.common.enums.OrderFlowNum; import com.hd.kzscrm.common.model.portal.PortalRespModel; import com.hd.kzscrm.common.model.portal.PortalRespModel.RespCode; import com.hd.wolverine.cache.CacheServiceImpl; import com.hd.wolverine.cache.WolverineJedisCluster; /** * @author 黄霄仪 * @date 2017年3月13日 上午11:13:21 * */ public class ServiceUtil { // 用户信息放入session,"session_user"应该定义成常量 static CacheServiceImpl cacheService = new CacheServiceImpl(); /** * 据KEY生成全局ID * @param keyIn table名称 * @return */ public static Long genNextIDValue(DatabaseTableNameEnum databaseTableName) { return cacheService.genNextIDValue("KZS", databaseTableName.name()); } /** * 自定义消息 * @author 黄霄仪 * @param respCode 响应状态 * @date 2017年3月7日 下午1:59:54 */ public static PortalRespModel getPortalRespModel(RespCode respCode,Object rows,String customMessage){ PortalRespModel portalRespModel=new PortalRespModel(); portalRespModel.setDesc(customMessage); portalRespModel.setStatusCode(respCode.getStatusCode()); portalRespModel.setRows(rows); return portalRespModel; } /** * 获取基本PortalRespModel * @author 黄霄仪 * @param respCode 响应状态 * @date 2017年3月7日 下午1:59:54 */ public static PortalRespModel getPortalRespModel(RespCode respCode,Object rows){ PortalRespModel portalRespModel=new PortalRespModel(); portalRespModel.setDesc(respCode.getDesc()); portalRespModel.setStatusCode(respCode.getStatusCode()); portalRespModel.setRows(rows); return portalRespModel; } /** * 自定义单据前缀流水号拼接 * @author 黄霄仪 * @date 2017年4月10日 下午7:11:47 * @param orderFlowNum 流水单项目 * @param prefix 单据前缀 * @param prefixPad 前缀补足字符 * @param prefixPadSize 被补足的总字符数 */ public static String getOrderFlowNum(OrderFlowNum orderFlowNum,String prefix,String prefixPad,int prefixPadSize){ Long incValue = cacheService.genNextIDValue("orderFlowNum", orderFlowNum.name()); return prefix+StringUtils.leftPad(incValue.toString(), prefixPadSize, prefixPad); } /** * 加上时间的单据流水号 * @author 黄霄仪 * @date 2017年4月10日 下午7:17:00 */ public static String getOrderFlowNumRule(OrderFlowNum orderFlowNum,String prefixPad,int prefixPadSize){ return getOrderFlowNum(orderFlowNum,DateUtils.dateToString(new Date(),"yyyyMMddHHmmss"),prefixPad,prefixPadSize); } /** * 根据单据类型,生成单据号 * @author 黄霄仪 * @date 2017年4月10日 下午7:17:00 * @param padSize 填充大小 * @param orderFlowNum 填充类型 */ public static synchronized String getOrderFlowNumByOrderFlowNum(OrderFlowNum orderFlowNum,int padSize){ WolverineJedisCluster wolverineJedisCluster=AppUtil.getBean(WolverineJedisCluster.class); String currentDate = DateUtils.dateToString(new Date(),"yyyyMMdd");//当前时间的年月日 return currentDate+StringUtils.leftPad(wolverineJedisCluster.incr(orderFlowNum.name()+currentDate).toString(), padSize, "0"); } /** * 提现批次号,用于支付宝提现功能 * @author 黄霄仪 * @date 2017年4月24日 上午9:48:15 * 格式:当天日期[8位]+序列号[3至16位],如:201008010000001,最高支持除年月日外的16位序列号 */ public static synchronized String alipayBatchPayNo(){ WolverineJedisCluster wolverineJedisCluster=AppUtil.getBean(WolverineJedisCluster.class); String currentDate = DateUtils.dateToString(new Date(),"yyyyMMdd");//当前时间的年月日 String key = "alipayBatchPay"+currentDate; String alipayBatchPayNo = currentDate+StringUtils.leftPad(wolverineJedisCluster.incr(key).toString(), 16, "0"); wolverineJedisCluster.expire(key, 32*60*60);//32小时后过期 return alipayBatchPayNo; } /** * 提现流水号,用于支付宝提现功能的客户提现流水号 * @author 黄霄仪 * @date 2017年4月24日 上午9:48:15 * 格式:当天日期[8位]+序列号[3至16位],如:201008010000001,最高支持除年月日外的16位序列号 */ public static synchronized String alipayBatchPayFlowNo(){ WolverineJedisCluster wolverineJedisCluster=AppUtil.getBean(WolverineJedisCluster.class); String currentDate = DateUtils.dateToString(new Date(),"yyyyMMdd");//当前时间的年月日 String key = "alipayBatchPayFlowNo"+currentDate; String alipayBatchPayNo = currentDate+StringUtils.leftPad(wolverineJedisCluster.incr(key).toString(), 16, "0"); wolverineJedisCluster.expire(key, 32*60*60);//32小时后过期 return alipayBatchPayNo; } /** * 支付宝回调参数封装 * @author 黄霄仪 * @date 2017年4月11日 下午8:25:41 */ public static Map<String,String> alipayParam(HttpServletRequest request){ Map<String, String> params = new HashMap<>(); Map requestParams = request.getParameterMap(); System.out.println(requestParams); for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) { String name = (String) iter.next(); String[] values = (String[]) requestParams.get(name); String valueStr = ""; for (int i = 0; i < values.length; i++) { valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ","; } // 乱码解决,这段代码在出现乱码时使用。 // valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8"); params.put(name, valueStr); } return params; } }
UTF-8
Java
5,803
java
ServiceUtil.java
Java
[ { "context": "rine.cache.WolverineJedisCluster;\n\n/**\n * @author 黄霄仪\n * @date 2017年3月13日 上午11:13:21\n * \n */\npublic cla", "end": 589, "score": 0.9926798939704895, "start": 586, "tag": "NAME", "value": "黄霄仪" }, { "context": "bleName.name());\n\n\t}\n\t\n\t/**\n\t * 自定义消息\n\t * @author 黄霄仪\n\t * @param respCode 响应状态\n\t * @date 2017年3月7日 下午1:", "end": 1010, "score": 0.9788468480110168, "start": 1007, "tag": "NAME", "value": "黄霄仪" }, { "context": "el;\n\t}\n\t\n\t/**\n\t * 获取基本PortalRespModel\n\t * @author 黄霄仪\n\t * @param respCode 响应状态\n\t * @date 2017年3月7日 下午1:", "end": 1440, "score": 0.9928191304206848, "start": 1437, "tag": "NAME", "value": "黄霄仪" }, { "context": "alRespModel;\n\t}\n\t/**\n\t * 自定义单据前缀流水号拼接\n\t * @author 黄霄仪\n\t * @date 2017年4月10日 下午7:11:47\n\t * @param orderFl", "end": 1845, "score": 0.815826416015625, "start": 1842, "tag": "USERNAME", "value": "黄霄仪" }, { "context": "e, prefixPad);\n\t}\n\t/**\n\t * 加上时间的单据流水号\n\t * @author 黄霄仪\n\t * @date 2017年4月10日 下午7:17:00\n\t */\n\tpublic stati", "end": 2318, "score": 0.8872251510620117, "start": 2315, "tag": "USERNAME", "value": "黄霄仪" }, { "context": "ixPadSize); \n\t}\n\t/**\n\t * 根据单据类型,生成单据号\n\t * @author 黄霄仪\n\t * @date 2017年4月10日 下午7:17:00\n\t * @param padSize", "end": 2617, "score": 0.934973418712616, "start": 2614, "tag": "USERNAME", "value": "黄霄仪" }, { "context": "ze, \"0\");\n\t}\n\t/**\n\t * 提现批次号,用于支付宝提现功能\n\t * @author 黄霄仪\n\t * @date 2017年4月24日 上午9:48:15\n\t * 格式:当天日期[8位]+序列", "end": 3155, "score": 0.9985381960868835, "start": 3152, "tag": "NAME", "value": "黄霄仪" }, { "context": "new Date(),\"yyyyMMdd\");//当前时间的年月日\n\t\tString key = \"alipayBatchPay\"+currentDate;\n\t\tString alipayBatchPayNo = current", "end": 3511, "score": 0.8503549695014954, "start": 3497, "tag": "KEY", "value": "alipayBatchPay" }, { "context": ";\n\t}\n\t/**\n\t * 提现流水号,用于支付宝提现功能的客户提现流水号\n\t * @author 黄霄仪\n\t * @date 2017年4月24日 上午9:48:15\n\t * 格式:当天日期[8位]+序列", "end": 3774, "score": 0.9985557794570923, "start": 3771, "tag": "NAME", "value": "黄霄仪" }, { "context": "new Date(),\"yyyyMMdd\");//当前时间的年月日\n\t\tString key = \"alipayBatchPayFlowNo\"+currentDate;\n\t\tString alipayBatchPayNo = currentDa", "end": 4142, "score": 0.974061906337738, "start": 4120, "tag": "KEY", "value": "alipayBatchPayFlowNo\"+" }, { "context": ";//当前时间的年月日\n\t\tString key = \"alipayBatchPayFlowNo\"+currentDate;\n\t\tString alipayBatchPayNo = currentDate+StringUt", "end": 4153, "score": 0.815220057964325, "start": 4142, "tag": "KEY", "value": "currentDate" }, { "context": "ayBatchPayNo;\n\t}\n\t\n\t/**\n\t * 支付宝回调参数封装\n\t * @author 黄霄仪\n\t * @date 2017年4月11日 下午8:25:41\n\t */\n\tpublic stati", "end": 4391, "score": 0.9994522333145142, "start": 4388, "tag": "NAME", "value": "黄霄仪" } ]
null
[]
/** * */ package com.hd.kzscrm.common.util; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.apache.commons.lang.StringUtils; import com.hd.kzscrm.common.enums.DatabaseTableNameEnum; import com.hd.kzscrm.common.enums.OrderFlowNum; import com.hd.kzscrm.common.model.portal.PortalRespModel; import com.hd.kzscrm.common.model.portal.PortalRespModel.RespCode; import com.hd.wolverine.cache.CacheServiceImpl; import com.hd.wolverine.cache.WolverineJedisCluster; /** * @author 黄霄仪 * @date 2017年3月13日 上午11:13:21 * */ public class ServiceUtil { // 用户信息放入session,"session_user"应该定义成常量 static CacheServiceImpl cacheService = new CacheServiceImpl(); /** * 据KEY生成全局ID * @param keyIn table名称 * @return */ public static Long genNextIDValue(DatabaseTableNameEnum databaseTableName) { return cacheService.genNextIDValue("KZS", databaseTableName.name()); } /** * 自定义消息 * @author 黄霄仪 * @param respCode 响应状态 * @date 2017年3月7日 下午1:59:54 */ public static PortalRespModel getPortalRespModel(RespCode respCode,Object rows,String customMessage){ PortalRespModel portalRespModel=new PortalRespModel(); portalRespModel.setDesc(customMessage); portalRespModel.setStatusCode(respCode.getStatusCode()); portalRespModel.setRows(rows); return portalRespModel; } /** * 获取基本PortalRespModel * @author 黄霄仪 * @param respCode 响应状态 * @date 2017年3月7日 下午1:59:54 */ public static PortalRespModel getPortalRespModel(RespCode respCode,Object rows){ PortalRespModel portalRespModel=new PortalRespModel(); portalRespModel.setDesc(respCode.getDesc()); portalRespModel.setStatusCode(respCode.getStatusCode()); portalRespModel.setRows(rows); return portalRespModel; } /** * 自定义单据前缀流水号拼接 * @author 黄霄仪 * @date 2017年4月10日 下午7:11:47 * @param orderFlowNum 流水单项目 * @param prefix 单据前缀 * @param prefixPad 前缀补足字符 * @param prefixPadSize 被补足的总字符数 */ public static String getOrderFlowNum(OrderFlowNum orderFlowNum,String prefix,String prefixPad,int prefixPadSize){ Long incValue = cacheService.genNextIDValue("orderFlowNum", orderFlowNum.name()); return prefix+StringUtils.leftPad(incValue.toString(), prefixPadSize, prefixPad); } /** * 加上时间的单据流水号 * @author 黄霄仪 * @date 2017年4月10日 下午7:17:00 */ public static String getOrderFlowNumRule(OrderFlowNum orderFlowNum,String prefixPad,int prefixPadSize){ return getOrderFlowNum(orderFlowNum,DateUtils.dateToString(new Date(),"yyyyMMddHHmmss"),prefixPad,prefixPadSize); } /** * 根据单据类型,生成单据号 * @author 黄霄仪 * @date 2017年4月10日 下午7:17:00 * @param padSize 填充大小 * @param orderFlowNum 填充类型 */ public static synchronized String getOrderFlowNumByOrderFlowNum(OrderFlowNum orderFlowNum,int padSize){ WolverineJedisCluster wolverineJedisCluster=AppUtil.getBean(WolverineJedisCluster.class); String currentDate = DateUtils.dateToString(new Date(),"yyyyMMdd");//当前时间的年月日 return currentDate+StringUtils.leftPad(wolverineJedisCluster.incr(orderFlowNum.name()+currentDate).toString(), padSize, "0"); } /** * 提现批次号,用于支付宝提现功能 * @author 黄霄仪 * @date 2017年4月24日 上午9:48:15 * 格式:当天日期[8位]+序列号[3至16位],如:201008010000001,最高支持除年月日外的16位序列号 */ public static synchronized String alipayBatchPayNo(){ WolverineJedisCluster wolverineJedisCluster=AppUtil.getBean(WolverineJedisCluster.class); String currentDate = DateUtils.dateToString(new Date(),"yyyyMMdd");//当前时间的年月日 String key = "alipayBatchPay"+currentDate; String alipayBatchPayNo = currentDate+StringUtils.leftPad(wolverineJedisCluster.incr(key).toString(), 16, "0"); wolverineJedisCluster.expire(key, 32*60*60);//32小时后过期 return alipayBatchPayNo; } /** * 提现流水号,用于支付宝提现功能的客户提现流水号 * @author 黄霄仪 * @date 2017年4月24日 上午9:48:15 * 格式:当天日期[8位]+序列号[3至16位],如:201008010000001,最高支持除年月日外的16位序列号 */ public static synchronized String alipayBatchPayFlowNo(){ WolverineJedisCluster wolverineJedisCluster=AppUtil.getBean(WolverineJedisCluster.class); String currentDate = DateUtils.dateToString(new Date(),"yyyyMMdd");//当前时间的年月日 String key = "alipayBatchPayFlowNo"+currentDate; String alipayBatchPayNo = currentDate+StringUtils.leftPad(wolverineJedisCluster.incr(key).toString(), 16, "0"); wolverineJedisCluster.expire(key, 32*60*60);//32小时后过期 return alipayBatchPayNo; } /** * 支付宝回调参数封装 * @author 黄霄仪 * @date 2017年4月11日 下午8:25:41 */ public static Map<String,String> alipayParam(HttpServletRequest request){ Map<String, String> params = new HashMap<>(); Map requestParams = request.getParameterMap(); System.out.println(requestParams); for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) { String name = (String) iter.next(); String[] values = (String[]) requestParams.get(name); String valueStr = ""; for (int i = 0; i < values.length; i++) { valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ","; } // 乱码解决,这段代码在出现乱码时使用。 // valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8"); params.put(name, valueStr); } return params; } }
5,803
0.750633
0.715593
154
32.357143
30.784058
127
false
false
0
0
0
0
0
0
1.785714
false
false
7
40fb3da27ca5db69cdd1194ec1917e07b6ec2a8c
1,151,051,298,110
0bbe663d013860abccd21303b0c17b8d9584c602
/src/main/java/lu/uni/owl/mutatingowlsgenerator/mutant/MutantGenerationInterface.java
5ae4673c5d613c32d6f5038d1ee63ea2efe31d4b
[]
no_license
guerret/lu.uni.owl.mutatingowls
https://github.com/guerret/lu.uni.owl.mutatingowls
eb5e62c6941e67211b34334bb10d74c8b487b6f2
ef92b7428baf6250a21c2c804252f1c758e25a2a
refs/heads/master
2021-01-10T10:58:28.263000
2018-09-28T12:51:31
2018-09-28T12:51:31
50,585,733
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package lu.uni.owl.mutatingowlsgenerator.mutant; import java.util.HashMap; import java.util.List; import org.semanticweb.owlapi.model.OWLEntity; import lu.uni.owl.mutatingowls.Mutant; import lu.uni.owl.mutatingowls.OpData; public interface MutantGenerationInterface { public HashMap<String, List<Mutant>> generateMutants(); public List<OpData> getOps(OWLEntity entity); }
UTF-8
Java
381
java
MutantGenerationInterface.java
Java
[]
null
[]
package lu.uni.owl.mutatingowlsgenerator.mutant; import java.util.HashMap; import java.util.List; import org.semanticweb.owlapi.model.OWLEntity; import lu.uni.owl.mutatingowls.Mutant; import lu.uni.owl.mutatingowls.OpData; public interface MutantGenerationInterface { public HashMap<String, List<Mutant>> generateMutants(); public List<OpData> getOps(OWLEntity entity); }
381
0.80315
0.80315
17
21.411764
21.436798
56
false
false
0
0
0
0
0
0
0.647059
false
false
7
4086b8aa12e0f9574b1c8c09732786abb5801ccb
7,043,746,371,937
08fad0b57741f3914a4fa43d9eb6df276901c5fa
/app/src/main/java/com/consultoraestrategia/messengeracademico/test/firebase/FireChildViewModel.java
51d93ce415bd0caa2b34b4dead9e1e3a6c8c05d4
[]
no_license
consultorasystemstrategy/AcademicAppMessenger
https://github.com/consultorasystemstrategy/AcademicAppMessenger
dd12ac2e06f76306c133ce9b952cb65e2ae6bc43
d9c039876ce58ae884a60bdc02cc7d1ce371e95f
refs/heads/master
2018-12-25T08:47:18.042000
2018-12-05T22:15:26
2018-12-05T22:15:26
150,488,593
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.consultoraestrategia.messengeracademico.test.firebase; import android.arch.lifecycle.LiveData; import android.arch.lifecycle.MediatorLiveData; import android.arch.lifecycle.Observer; import android.arch.lifecycle.ViewModel; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.util.Log; import com.consultoraestrategia.messengeracademico.UseCase; import com.consultoraestrategia.messengeracademico.UseCaseHandler; import com.consultoraestrategia.messengeracademico.test.usecase.ParseSnapshotUseCase; import com.google.firebase.database.DataSnapshot; public abstract class FireChildViewModel<T> extends ViewModel { private static final String TAG = "FireChildViewModel"; private final FirebaseQueryLiveData firebaseQueryLiveData; private final MediatorLiveData<T> liveData = new MediatorLiveData<>(); private final UseCaseHandler handler; private final Class<T> tClass; public FireChildViewModel(final UseCaseHandler handler, FirebaseQueryLiveData firebaseQueryLiveData, Class<T> tClass) { Log.d(TAG, "FireChildViewModel: "); this.handler = handler; this.firebaseQueryLiveData = firebaseQueryLiveData; this.tClass = tClass; startMediatorLiveData(); } private void startMediatorLiveData() { Log.d(TAG, "startMediatorLiveData: "); liveData.addSource( firebaseQueryLiveData, new Observer<DataSnapshot>() { @Override public void onChanged(@Nullable DataSnapshot dataSnapshot) { //Log.d(TAG, "onChanged\n: " + dataSnapshot); if (dataSnapshot == null) return; handler.execute( new ParseSnapshotUseCase<T>(), new ParseSnapshotUseCase.RequestValues<>(dataSnapshot, tClass), new UseCase.UseCaseCallback<ParseSnapshotUseCase.ResponseValue<T>>() { @Override public void onSuccess(ParseSnapshotUseCase.ResponseValue<T> response) { T child = response.getData(); Log.d(TAG, "onSuccess: \n" + child.toString()); liveData.setValue(child); } @Override public void onError() { } } ); } } ); } @NonNull public LiveData<T> getDataSnapshotLiveData() { return liveData; } }
UTF-8
Java
2,793
java
FireChildViewModel.java
Java
[]
null
[]
package com.consultoraestrategia.messengeracademico.test.firebase; import android.arch.lifecycle.LiveData; import android.arch.lifecycle.MediatorLiveData; import android.arch.lifecycle.Observer; import android.arch.lifecycle.ViewModel; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.util.Log; import com.consultoraestrategia.messengeracademico.UseCase; import com.consultoraestrategia.messengeracademico.UseCaseHandler; import com.consultoraestrategia.messengeracademico.test.usecase.ParseSnapshotUseCase; import com.google.firebase.database.DataSnapshot; public abstract class FireChildViewModel<T> extends ViewModel { private static final String TAG = "FireChildViewModel"; private final FirebaseQueryLiveData firebaseQueryLiveData; private final MediatorLiveData<T> liveData = new MediatorLiveData<>(); private final UseCaseHandler handler; private final Class<T> tClass; public FireChildViewModel(final UseCaseHandler handler, FirebaseQueryLiveData firebaseQueryLiveData, Class<T> tClass) { Log.d(TAG, "FireChildViewModel: "); this.handler = handler; this.firebaseQueryLiveData = firebaseQueryLiveData; this.tClass = tClass; startMediatorLiveData(); } private void startMediatorLiveData() { Log.d(TAG, "startMediatorLiveData: "); liveData.addSource( firebaseQueryLiveData, new Observer<DataSnapshot>() { @Override public void onChanged(@Nullable DataSnapshot dataSnapshot) { //Log.d(TAG, "onChanged\n: " + dataSnapshot); if (dataSnapshot == null) return; handler.execute( new ParseSnapshotUseCase<T>(), new ParseSnapshotUseCase.RequestValues<>(dataSnapshot, tClass), new UseCase.UseCaseCallback<ParseSnapshotUseCase.ResponseValue<T>>() { @Override public void onSuccess(ParseSnapshotUseCase.ResponseValue<T> response) { T child = response.getData(); Log.d(TAG, "onSuccess: \n" + child.toString()); liveData.setValue(child); } @Override public void onError() { } } ); } } ); } @NonNull public LiveData<T> getDataSnapshotLiveData() { return liveData; } }
2,793
0.58754
0.58754
66
41.31818
29.319122
123
false
false
0
0
0
0
0
0
0.621212
false
false
7
1825562c10bef15f242f059b737db0333de5e927
11,141,145,173,410
86b4ec448c2bef89055fa8ddf2ab8ce61b7eeb6d
/src/main/java/com/theadora/lucene/TheadoraCIndexFile.java
c1daddfb0600dcfe1f0491e3bd95602c26b9ea41
[ "MIT" ]
permissive
jwlyn/Lucene-Cranfield-theadora
https://github.com/jwlyn/Lucene-Cranfield-theadora
2a7083ba524acf1ac261559785f7e22d1127b9c8
d6932b58107ce2b2d992cbf40ea9f964318c50cc
refs/heads/master
2021-02-15T12:16:26.181000
2020-03-04T12:42:53
2020-03-04T12:42:53
244,897,887
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.theadora.lucene; import org.apache.lucene.document.*; import org.apache.lucene.index.IndexWriter; import org.apache.lucene.index.IndexWriterConfig; import org.apache.lucene.index.IndexWriterConfig.OpenMode; import org.apache.lucene.index.Term; import org.apache.lucene.store.Directory; import org.apache.lucene.store.FSDirectory; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.nio.charset.StandardCharsets; import java.nio.file.*; import java.nio.file.attribute.BasicFileAttributes; import java.util.Date; /** * @author theadora */ public class TheadoraCIndexFile { private TheadoraCIndexFile() {} public static void main(String[] args) { String usage = "java com.theadora.lucene.TheadoraCIndexFile" + " [-index INDEX_PATH] [-docs DOCS_PATH] [-update]\n\n" + "This indexes the documents in DOCS_PATH, creating a Lucene index" + "in INDEX_PATH that can be searched with TheadoraSFile"; String indexPath = "index"; String docsPath = "doc"; boolean create = true; for(int i=0;i<args.length;i++) { if ("-index".equals(args[i])) { indexPath = args[i+1]; i++; } else if ("-docs".equals(args[i])) { docsPath = args[i+1]; i++; } else if ("-update".equals(args[i])) { create = false; } } if (docsPath == null) { System.exit(1); } final Path docDir = Paths.get(docsPath); if (!Files.isReadable(docDir)) { System.out.println("doc directory '" +docDir.toAbsolutePath()+ "' does not exist or is not readable, please check the path"); System.exit(1); } Date start = new Date(); try { Directory directory = FSDirectory.open(Paths.get(indexPath)); TheadoraAnalyzer analyzer = new TheadoraAnalyzer(TheadoraEnglishStopWordsSet.ENGLISH_STOP_WORDS_SET); IndexWriterConfig iwc = new IndexWriterConfig(analyzer); if (create) { iwc.setOpenMode(OpenMode.CREATE); } else { iwc.setOpenMode(OpenMode.CREATE_OR_APPEND); } IndexWriter writer = new IndexWriter(directory, iwc); indexTheadoraDocs(writer, docDir); writer.close(); Date end = new Date(); System.out.println(end.getTime() - start.getTime() + " total milliseconds"); } catch (IOException e) { e.printStackTrace(); } } static void indexTheadoraDocs(final IndexWriter writer, Path path) throws IOException { if (Files.isDirectory(path)) { Files.walkFileTree(path, new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { try { indexTheadoraDoc(writer, file, attrs.lastModifiedTime().toMillis()); } catch (IOException ignore) { ignore.printStackTrace(); } return FileVisitResult.CONTINUE; } }); } else { indexTheadoraDoc(writer, path, Files.getLastModifiedTime(path).toMillis()); } } static void indexTheadoraDoc(IndexWriter writer, Path file, long lastModified) throws IOException { try (InputStream stream = Files.newInputStream(file)) { Document document = new Document(); Field pathField = new StringField("path", file.toString(), Field.Store.YES); document.add(pathField); document.add(new LongPoint("modified", lastModified)); document.add(new TextField("contents", new BufferedReader(new InputStreamReader(stream, StandardCharsets.UTF_8)))); if (writer.getConfig().getOpenMode() == OpenMode.CREATE) { writer.addDocument(document); } else { writer.updateDocument(new Term("path", file.toString()), document); } } } }
UTF-8
Java
3,901
java
TheadoraCIndexFile.java
Java
[ { "context": "Attributes;\nimport java.util.Date;\n\n/**\n * @author theadora\n */\npublic class TheadoraCIndexFile {\n \n privat", "end": 630, "score": 0.9995846748352051, "start": 622, "tag": "USERNAME", "value": "theadora" } ]
null
[]
package com.theadora.lucene; import org.apache.lucene.document.*; import org.apache.lucene.index.IndexWriter; import org.apache.lucene.index.IndexWriterConfig; import org.apache.lucene.index.IndexWriterConfig.OpenMode; import org.apache.lucene.index.Term; import org.apache.lucene.store.Directory; import org.apache.lucene.store.FSDirectory; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.nio.charset.StandardCharsets; import java.nio.file.*; import java.nio.file.attribute.BasicFileAttributes; import java.util.Date; /** * @author theadora */ public class TheadoraCIndexFile { private TheadoraCIndexFile() {} public static void main(String[] args) { String usage = "java com.theadora.lucene.TheadoraCIndexFile" + " [-index INDEX_PATH] [-docs DOCS_PATH] [-update]\n\n" + "This indexes the documents in DOCS_PATH, creating a Lucene index" + "in INDEX_PATH that can be searched with TheadoraSFile"; String indexPath = "index"; String docsPath = "doc"; boolean create = true; for(int i=0;i<args.length;i++) { if ("-index".equals(args[i])) { indexPath = args[i+1]; i++; } else if ("-docs".equals(args[i])) { docsPath = args[i+1]; i++; } else if ("-update".equals(args[i])) { create = false; } } if (docsPath == null) { System.exit(1); } final Path docDir = Paths.get(docsPath); if (!Files.isReadable(docDir)) { System.out.println("doc directory '" +docDir.toAbsolutePath()+ "' does not exist or is not readable, please check the path"); System.exit(1); } Date start = new Date(); try { Directory directory = FSDirectory.open(Paths.get(indexPath)); TheadoraAnalyzer analyzer = new TheadoraAnalyzer(TheadoraEnglishStopWordsSet.ENGLISH_STOP_WORDS_SET); IndexWriterConfig iwc = new IndexWriterConfig(analyzer); if (create) { iwc.setOpenMode(OpenMode.CREATE); } else { iwc.setOpenMode(OpenMode.CREATE_OR_APPEND); } IndexWriter writer = new IndexWriter(directory, iwc); indexTheadoraDocs(writer, docDir); writer.close(); Date end = new Date(); System.out.println(end.getTime() - start.getTime() + " total milliseconds"); } catch (IOException e) { e.printStackTrace(); } } static void indexTheadoraDocs(final IndexWriter writer, Path path) throws IOException { if (Files.isDirectory(path)) { Files.walkFileTree(path, new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { try { indexTheadoraDoc(writer, file, attrs.lastModifiedTime().toMillis()); } catch (IOException ignore) { ignore.printStackTrace(); } return FileVisitResult.CONTINUE; } }); } else { indexTheadoraDoc(writer, path, Files.getLastModifiedTime(path).toMillis()); } } static void indexTheadoraDoc(IndexWriter writer, Path file, long lastModified) throws IOException { try (InputStream stream = Files.newInputStream(file)) { Document document = new Document(); Field pathField = new StringField("path", file.toString(), Field.Store.YES); document.add(pathField); document.add(new LongPoint("modified", lastModified)); document.add(new TextField("contents", new BufferedReader(new InputStreamReader(stream, StandardCharsets.UTF_8)))); if (writer.getConfig().getOpenMode() == OpenMode.CREATE) { writer.addDocument(document); } else { writer.updateDocument(new Term("path", file.toString()), document); } } } }
3,901
0.64727
0.645732
113
33
28.951591
131
false
false
0
0
0
0
0
0
0.663717
false
false
7
2f0122dabd9fb5255c72deaacb67b1bbea63863d
2,130,303,800,038
4acf7f1a5e63c1cfa1feaf4506f91b71dbace533
/app/src/main/java/com/bogdanorzea/regexquiz/QuestionAdapter.java
542810485bad934cb7fecf5fdddd596086f1e174
[]
no_license
bogdanorzea/RegexQuiz
https://github.com/bogdanorzea/RegexQuiz
196b4da77fa22729238a51c91e65f3aec5b49a5a
5af602595cceb0377bbb02c01434f6abb6e0ca4d
refs/heads/master
2021-01-19T08:53:46.125000
2017-05-08T23:02:40
2017-05-08T23:02:40
87,694,261
0
0
null
false
2017-05-08T22:56:00
2017-04-09T08:35:04
2017-04-09T09:19:26
2017-05-08T22:56:00
832
0
0
1
Java
null
null
package com.bogdanorzea.regexquiz; import android.support.v7.widget.RecyclerView; import android.text.Editable; import android.text.TextWatcher; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.CheckBox; import android.widget.RadioButton; import android.widget.Toast; import java.io.Serializable; import java.util.List; class QuestionAdapter extends RecyclerView.Adapter<ViewHolder> implements Serializable { private static final String QUESTION_ADAPTER = "QUESTION_ADAPTER"; private List<Question> mQuestionList; private transient OnCheckClickListener onCheckClickListener; QuestionAdapter(List<Question> qList) { mQuestionList = qList; } // Create new views (invoked by the layout manager) @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.answer_card_view, parent, false); return new ViewHolder(v); } // Replace the contents of a view (invoked by the layout manager) @Override public void onBindViewHolder(final ViewHolder holder, int position) { final Question tempQuestion = mQuestionList.get(position); holder.mTitle.setText(tempQuestion.getTitle()); holder.mDescription.setText(tempQuestion.getDescription()); // Hide unnecessary elements if (tempQuestion.getAvailableChoices() == null || tempQuestion.getAvailableChoices().length == 0) { // Add logic to update user choice as he types the answer holder.mInput.setVisibility(View.VISIBLE); holder.mInput.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) { } @Override public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) { } @Override public void afterTextChanged(Editable editable) { tempQuestion.addExclusiveUserChoice(holder.mInput.getText().toString()); } }); if (!tempQuestion.getUserChoices().isEmpty()) { holder.mInput.setText(tempQuestion.getUserChoices().get(0)); } holder.mSingleChoiceLayout.setVisibility(View.GONE); holder.mMultipleChoiceLayout.setVisibility(View.GONE); } else { String[] tc = tempQuestion.getAvailableChoices(); if (tempQuestion.getAnswers().size() == 1) { holder.mInput.setVisibility(View.GONE); holder.mSingleChoiceLayout.setVisibility(View.VISIBLE); holder.mRButton1.setText(tc[0]); holder.mRButton2.setText(tc[1]); holder.mRButton3.setText(tc[2]); holder.mRButton4.setText(tc[3]); // Check the radio buttons if needed if (tempQuestion.hasAsAnswer(tc[0])) { holder.mRButton1.setChecked(true); } else { holder.mRButton1.setChecked(false); } if (tempQuestion.hasAsAnswer(tc[1])) { holder.mRButton2.setChecked(true); } else { holder.mRButton2.setChecked(false); } if (tempQuestion.hasAsAnswer(tc[2])) { holder.mRButton3.setChecked(true); } else { holder.mRButton3.setChecked(false); } if (tempQuestion.hasAsAnswer(tc[3])) { holder.mRButton4.setChecked(true); } else { holder.mRButton4.setChecked(false); } holder.mRButton1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onRadioButtonClick(v, tempQuestion); } }); holder.mRButton2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onRadioButtonClick(v, tempQuestion); } }); holder.mRButton3.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onRadioButtonClick(v, tempQuestion); } }); holder.mRButton4.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onRadioButtonClick(v, tempQuestion); } }); holder.mMultipleChoiceLayout.setVisibility(View.GONE); } else { holder.mInput.setVisibility(View.GONE); holder.mSingleChoiceLayout.setVisibility(View.GONE); holder.mMultipleChoiceLayout.setVisibility(View.VISIBLE); holder.mCBox1.setText(tc[0]); holder.mCBox2.setText(tc[1]); holder.mCBox3.setText(tc[2]); holder.mCBox4.setText(tc[3]); // Check the check buttons if needed if (tempQuestion.hasAsAnswer(tc[0])) { holder.mCBox1.setChecked(true); } else { holder.mCBox1.setChecked(false); } if (tempQuestion.hasAsAnswer(tc[1])) { holder.mCBox2.setChecked(true); } else { holder.mCBox2.setChecked(false); } if (tempQuestion.hasAsAnswer(tc[2])) { holder.mCBox3.setChecked(true); } else { holder.mCBox3.setChecked(false); } if (tempQuestion.hasAsAnswer(tc[3])) { holder.mCBox4.setChecked(true); } else { holder.mCBox4.setChecked(false); } holder.mCBox1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onCheckBoxClick(v, tempQuestion); } }); holder.mCBox2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onCheckBoxClick(v, tempQuestion); } }); holder.mCBox3.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onCheckBoxClick(v, tempQuestion); } }); holder.mCBox4.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onCheckBoxClick(v, tempQuestion); } }); } } holder.mButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { onSubmitButtonClick(view, tempQuestion, holder); } }); if (tempQuestion.wasAnswered()) { setEnableHolder(holder, false); } } private void setEnableHolder(ViewHolder holder, boolean mode) { holder.mTitle.setEnabled(mode); holder.mDescription.setEnabled(mode); holder.mInput.setEnabled(mode); holder.mRButton1.setEnabled(mode); holder.mRButton2.setEnabled(mode); holder.mRButton3.setEnabled(mode); holder.mRButton4.setEnabled(mode); holder.mCBox1.setEnabled(mode); holder.mCBox2.setEnabled(mode); holder.mCBox3.setEnabled(mode); holder.mCBox4.setEnabled(mode); holder.mButton.setEnabled(mode); } private void onSubmitButtonClick(View view, Question tempQuestion, ViewHolder holder) { Log.d(QUESTION_ADAPTER, String.format("Final answer for %s is: %s.", tempQuestion.getTitle(), tempQuestion.getUserChoices())); if (!tempQuestion.hasChoices()) { Toast.makeText(view.getContext(), "Please make at least a choice!", Toast.LENGTH_SHORT).show(); return; } if (!tempQuestion.hasSufficientChoices()) { Toast.makeText(view.getContext(), "Wrong answer!", Toast.LENGTH_SHORT).show(); } else { if (tempQuestion.isCorrectlyAnswered()) { Toast.makeText(view.getContext(), "Correct answer!", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(view.getContext(), "Wrong answer!", Toast.LENGTH_SHORT).show(); } } // Disables question card from being clicked again tempQuestion.markAnswered(); setEnableHolder(holder, false); onCheckClickListener.onCheckClick(tempQuestion); } private void onRadioButtonClick(View v, Question tempQuestion) { boolean checked = ((RadioButton) v).isChecked(); if (checked) { tempQuestion.addExclusiveUserChoice(((RadioButton) v).getText().toString()); Log.d(QUESTION_ADAPTER, String.format("User clicked on: %s.", tempQuestion.getUserChoices())); } } private void onCheckBoxClick(View v, Question tempQuestion) { boolean checked = ((CheckBox) v).isChecked(); if (checked) { tempQuestion.addUserChoice(((CheckBox) v).getText().toString()); } else { tempQuestion.removeUserChoice(((CheckBox) v).getText().toString()); } Log.d(QUESTION_ADAPTER, String.format("User clicked on: %s.", tempQuestion.getUserChoices())); } // Return the size of your dataset (invoked by the layout manager) @Override public int getItemCount() { return mQuestionList.size(); } public OnCheckClickListener getOnCheckClickListener() { return onCheckClickListener; } public void setOnCheckClickListener(OnCheckClickListener onCheckClickListener) { this.onCheckClickListener = onCheckClickListener; } }
UTF-8
Java
10,532
java
QuestionAdapter.java
Java
[]
null
[]
package com.bogdanorzea.regexquiz; import android.support.v7.widget.RecyclerView; import android.text.Editable; import android.text.TextWatcher; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.CheckBox; import android.widget.RadioButton; import android.widget.Toast; import java.io.Serializable; import java.util.List; class QuestionAdapter extends RecyclerView.Adapter<ViewHolder> implements Serializable { private static final String QUESTION_ADAPTER = "QUESTION_ADAPTER"; private List<Question> mQuestionList; private transient OnCheckClickListener onCheckClickListener; QuestionAdapter(List<Question> qList) { mQuestionList = qList; } // Create new views (invoked by the layout manager) @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.answer_card_view, parent, false); return new ViewHolder(v); } // Replace the contents of a view (invoked by the layout manager) @Override public void onBindViewHolder(final ViewHolder holder, int position) { final Question tempQuestion = mQuestionList.get(position); holder.mTitle.setText(tempQuestion.getTitle()); holder.mDescription.setText(tempQuestion.getDescription()); // Hide unnecessary elements if (tempQuestion.getAvailableChoices() == null || tempQuestion.getAvailableChoices().length == 0) { // Add logic to update user choice as he types the answer holder.mInput.setVisibility(View.VISIBLE); holder.mInput.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) { } @Override public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) { } @Override public void afterTextChanged(Editable editable) { tempQuestion.addExclusiveUserChoice(holder.mInput.getText().toString()); } }); if (!tempQuestion.getUserChoices().isEmpty()) { holder.mInput.setText(tempQuestion.getUserChoices().get(0)); } holder.mSingleChoiceLayout.setVisibility(View.GONE); holder.mMultipleChoiceLayout.setVisibility(View.GONE); } else { String[] tc = tempQuestion.getAvailableChoices(); if (tempQuestion.getAnswers().size() == 1) { holder.mInput.setVisibility(View.GONE); holder.mSingleChoiceLayout.setVisibility(View.VISIBLE); holder.mRButton1.setText(tc[0]); holder.mRButton2.setText(tc[1]); holder.mRButton3.setText(tc[2]); holder.mRButton4.setText(tc[3]); // Check the radio buttons if needed if (tempQuestion.hasAsAnswer(tc[0])) { holder.mRButton1.setChecked(true); } else { holder.mRButton1.setChecked(false); } if (tempQuestion.hasAsAnswer(tc[1])) { holder.mRButton2.setChecked(true); } else { holder.mRButton2.setChecked(false); } if (tempQuestion.hasAsAnswer(tc[2])) { holder.mRButton3.setChecked(true); } else { holder.mRButton3.setChecked(false); } if (tempQuestion.hasAsAnswer(tc[3])) { holder.mRButton4.setChecked(true); } else { holder.mRButton4.setChecked(false); } holder.mRButton1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onRadioButtonClick(v, tempQuestion); } }); holder.mRButton2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onRadioButtonClick(v, tempQuestion); } }); holder.mRButton3.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onRadioButtonClick(v, tempQuestion); } }); holder.mRButton4.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onRadioButtonClick(v, tempQuestion); } }); holder.mMultipleChoiceLayout.setVisibility(View.GONE); } else { holder.mInput.setVisibility(View.GONE); holder.mSingleChoiceLayout.setVisibility(View.GONE); holder.mMultipleChoiceLayout.setVisibility(View.VISIBLE); holder.mCBox1.setText(tc[0]); holder.mCBox2.setText(tc[1]); holder.mCBox3.setText(tc[2]); holder.mCBox4.setText(tc[3]); // Check the check buttons if needed if (tempQuestion.hasAsAnswer(tc[0])) { holder.mCBox1.setChecked(true); } else { holder.mCBox1.setChecked(false); } if (tempQuestion.hasAsAnswer(tc[1])) { holder.mCBox2.setChecked(true); } else { holder.mCBox2.setChecked(false); } if (tempQuestion.hasAsAnswer(tc[2])) { holder.mCBox3.setChecked(true); } else { holder.mCBox3.setChecked(false); } if (tempQuestion.hasAsAnswer(tc[3])) { holder.mCBox4.setChecked(true); } else { holder.mCBox4.setChecked(false); } holder.mCBox1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onCheckBoxClick(v, tempQuestion); } }); holder.mCBox2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onCheckBoxClick(v, tempQuestion); } }); holder.mCBox3.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onCheckBoxClick(v, tempQuestion); } }); holder.mCBox4.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onCheckBoxClick(v, tempQuestion); } }); } } holder.mButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { onSubmitButtonClick(view, tempQuestion, holder); } }); if (tempQuestion.wasAnswered()) { setEnableHolder(holder, false); } } private void setEnableHolder(ViewHolder holder, boolean mode) { holder.mTitle.setEnabled(mode); holder.mDescription.setEnabled(mode); holder.mInput.setEnabled(mode); holder.mRButton1.setEnabled(mode); holder.mRButton2.setEnabled(mode); holder.mRButton3.setEnabled(mode); holder.mRButton4.setEnabled(mode); holder.mCBox1.setEnabled(mode); holder.mCBox2.setEnabled(mode); holder.mCBox3.setEnabled(mode); holder.mCBox4.setEnabled(mode); holder.mButton.setEnabled(mode); } private void onSubmitButtonClick(View view, Question tempQuestion, ViewHolder holder) { Log.d(QUESTION_ADAPTER, String.format("Final answer for %s is: %s.", tempQuestion.getTitle(), tempQuestion.getUserChoices())); if (!tempQuestion.hasChoices()) { Toast.makeText(view.getContext(), "Please make at least a choice!", Toast.LENGTH_SHORT).show(); return; } if (!tempQuestion.hasSufficientChoices()) { Toast.makeText(view.getContext(), "Wrong answer!", Toast.LENGTH_SHORT).show(); } else { if (tempQuestion.isCorrectlyAnswered()) { Toast.makeText(view.getContext(), "Correct answer!", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(view.getContext(), "Wrong answer!", Toast.LENGTH_SHORT).show(); } } // Disables question card from being clicked again tempQuestion.markAnswered(); setEnableHolder(holder, false); onCheckClickListener.onCheckClick(tempQuestion); } private void onRadioButtonClick(View v, Question tempQuestion) { boolean checked = ((RadioButton) v).isChecked(); if (checked) { tempQuestion.addExclusiveUserChoice(((RadioButton) v).getText().toString()); Log.d(QUESTION_ADAPTER, String.format("User clicked on: %s.", tempQuestion.getUserChoices())); } } private void onCheckBoxClick(View v, Question tempQuestion) { boolean checked = ((CheckBox) v).isChecked(); if (checked) { tempQuestion.addUserChoice(((CheckBox) v).getText().toString()); } else { tempQuestion.removeUserChoice(((CheckBox) v).getText().toString()); } Log.d(QUESTION_ADAPTER, String.format("User clicked on: %s.", tempQuestion.getUserChoices())); } // Return the size of your dataset (invoked by the layout manager) @Override public int getItemCount() { return mQuestionList.size(); } public OnCheckClickListener getOnCheckClickListener() { return onCheckClickListener; } public void setOnCheckClickListener(OnCheckClickListener onCheckClickListener) { this.onCheckClickListener = onCheckClickListener; } }
10,532
0.563046
0.556969
271
37.863468
27.678036
134
false
false
0
0
0
0
0
0
0.564576
false
false
7
55e1ec3fc608868b37894132e19bf055d8c3ab5a
31,851,477,508,390
4e55592507eb7c5c40a6dba1612d42e8d267cc6b
/src/nl/hanze/experience/parkinggarage/views/QueueGraphView.java
f02c36726e1dad97944ea55385905f099bd54c0b
[]
no_license
Prusias/Parking-garage
https://github.com/Prusias/Parking-garage
99234d7617e39148646abe74194f3832cab3a498
6f4a6e3a3ef4a210111e1a605fb37d907de76f46
refs/heads/master
2023-04-03T04:23:46.263000
2023-03-20T20:00:06
2023-03-20T20:00:06
164,677,728
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package nl.hanze.experience.parkinggarage.views; import nl.hanze.experience.mvc.JPanelView; import nl.hanze.experience.mvc.Model; import nl.hanze.experience.parkinggarage.models.QueueGraphModel; import org.jfree.chart.ChartFactory; import org.jfree.chart.ChartPanel; import org.jfree.chart.JFreeChart; import org.jfree.chart.plot.CategoryPlot; import org.jfree.chart.plot.PlotOrientation; import org.jfree.chart.renderer.category.BarRenderer; import org.jfree.data.category.DefaultCategoryDataset; import java.awt.*; /** * The view for queues graph where all graphical operations regarding the queues graph happens * @author Mike van der Velde * @author Zein Bseis * @author Steven Woudstra * @author Ivo Gerner * @version 0.0.4 * @since 0.0.4 */ public class QueueGraphView extends JPanelView { private static final int WIDTH = 300; private static final int HEIGHT = 300; private DefaultCategoryDataset set; private JFreeChart jFreeChart; public QueueGraphView() { set = new DefaultCategoryDataset(); this.setAlignmentX(LEFT_ALIGNMENT); this.setAlignmentY(BOTTOM_ALIGNMENT); this.setBackground(Color.WHITE); jFreeChart = ChartFactory.createBarChart("Queues Graph", "Queues", "Amount of cars", set, PlotOrientation.VERTICAL, true, true, false ); CategoryPlot plot = jFreeChart.getCategoryPlot(); BarRenderer renderer = (BarRenderer) plot.getRenderer(); renderer.setSeriesPaint(0, new Color(255, 30, 30)); renderer.setSeriesPaint(1, new Color(68, 68, 68)); renderer.setSeriesPaint(2, new Color(100, 255, 255)); renderer.setShadowVisible(false); plot.setRenderer(renderer); plot.setBackgroundPaint(new Color(255, 255, 255)); jFreeChart.setAntiAlias(true); jFreeChart.setTextAntiAlias(true); jFreeChart.setBorderVisible(false); ChartPanel chartPanel = new ChartPanel(jFreeChart); chartPanel.setSize(WIDTH, HEIGHT); chartPanel.setMaximumDrawHeight(HEIGHT * 2); chartPanel.setMaximumDrawWidth(WIDTH * 2); add(chartPanel); } /** * update the information in the graph * @param model Model with the new information */ @Override public void update(Model model) { QueueGraphModel queueGraphModel = (QueueGraphModel) model; set = queueGraphModel.getDataset(); CategoryPlot plot = (CategoryPlot)jFreeChart.getPlot(); plot.setDataset(set); } }
UTF-8
Java
2,620
java
QueueGraphView.java
Java
[ { "context": "ions regarding the queues graph happens\n * @author Mike van der Velde\n * @author Zein Bseis\n * @author Steven Woudstra\n", "end": 648, "score": 0.9998749494552612, "start": 630, "tag": "NAME", "value": "Mike van der Velde" }, { "context": "h happens\n * @author Mike van der Velde\n * @author Zein Bseis\n * @author Steven Woudstra\n * @author Ivo Gerner\n", "end": 670, "score": 0.9998849034309387, "start": 660, "tag": "NAME", "value": "Zein Bseis" }, { "context": "ike van der Velde\n * @author Zein Bseis\n * @author Steven Woudstra\n * @author Ivo Gerner\n * @version 0.0.4\n * @since", "end": 697, "score": 0.9998775720596313, "start": 682, "tag": "NAME", "value": "Steven Woudstra" }, { "context": "r Zein Bseis\n * @author Steven Woudstra\n * @author Ivo Gerner\n * @version 0.0.4\n * @since 0.0.4\n */\npublic clas", "end": 719, "score": 0.9998607635498047, "start": 709, "tag": "NAME", "value": "Ivo Gerner" } ]
null
[]
package nl.hanze.experience.parkinggarage.views; import nl.hanze.experience.mvc.JPanelView; import nl.hanze.experience.mvc.Model; import nl.hanze.experience.parkinggarage.models.QueueGraphModel; import org.jfree.chart.ChartFactory; import org.jfree.chart.ChartPanel; import org.jfree.chart.JFreeChart; import org.jfree.chart.plot.CategoryPlot; import org.jfree.chart.plot.PlotOrientation; import org.jfree.chart.renderer.category.BarRenderer; import org.jfree.data.category.DefaultCategoryDataset; import java.awt.*; /** * The view for queues graph where all graphical operations regarding the queues graph happens * @author <NAME> * @author <NAME> * @author <NAME> * @author <NAME> * @version 0.0.4 * @since 0.0.4 */ public class QueueGraphView extends JPanelView { private static final int WIDTH = 300; private static final int HEIGHT = 300; private DefaultCategoryDataset set; private JFreeChart jFreeChart; public QueueGraphView() { set = new DefaultCategoryDataset(); this.setAlignmentX(LEFT_ALIGNMENT); this.setAlignmentY(BOTTOM_ALIGNMENT); this.setBackground(Color.WHITE); jFreeChart = ChartFactory.createBarChart("Queues Graph", "Queues", "Amount of cars", set, PlotOrientation.VERTICAL, true, true, false ); CategoryPlot plot = jFreeChart.getCategoryPlot(); BarRenderer renderer = (BarRenderer) plot.getRenderer(); renderer.setSeriesPaint(0, new Color(255, 30, 30)); renderer.setSeriesPaint(1, new Color(68, 68, 68)); renderer.setSeriesPaint(2, new Color(100, 255, 255)); renderer.setShadowVisible(false); plot.setRenderer(renderer); plot.setBackgroundPaint(new Color(255, 255, 255)); jFreeChart.setAntiAlias(true); jFreeChart.setTextAntiAlias(true); jFreeChart.setBorderVisible(false); ChartPanel chartPanel = new ChartPanel(jFreeChart); chartPanel.setSize(WIDTH, HEIGHT); chartPanel.setMaximumDrawHeight(HEIGHT * 2); chartPanel.setMaximumDrawWidth(WIDTH * 2); add(chartPanel); } /** * update the information in the graph * @param model Model with the new information */ @Override public void update(Model model) { QueueGraphModel queueGraphModel = (QueueGraphModel) model; set = queueGraphModel.getDataset(); CategoryPlot plot = (CategoryPlot)jFreeChart.getPlot(); plot.setDataset(set); } }
2,591
0.678626
0.660305
75
33.933334
20.443962
94
false
false
0
0
0
0
0
0
0.8
false
false
7
f5d6a6bae58e1d887ff05e2c6267972f25848d65
3,513,283,257,983
969e00f4b0d4c5eb0fc6f013b5dae528328c33a1
/Tenta 2014-10-31/src/uppg4_tenta2010_10_29/BinaryTree.java
8d4fe21a293d897ea8871fb65509d14d9c2e8554
[]
no_license
Ovhagen/My-first-repository
https://github.com/Ovhagen/My-first-repository
a89ba593f64904ed6d455cd41940e68223af4e31
a061ae08156230dda6afb2ea2b3612ea91ebe406
refs/heads/master
2021-01-10T15:59:46.383000
2015-10-22T16:24:20
2015-10-22T16:24:20
43,389,417
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package uppg4_tenta2010_10_29; public interface BinaryTree { public void printNodes(); }
UTF-8
Java
96
java
BinaryTree.java
Java
[]
null
[]
package uppg4_tenta2010_10_29; public interface BinaryTree { public void printNodes(); }
96
0.729167
0.635417
5
17.200001
13.702555
30
false
false
0
0
0
0
0
0
0.6
false
false
7
6fdc189cabf83f576d9f13230793b7eb8a0a3bf6
9,706,626,147,576
40d38003df4807bf1f00ed1ebcf29d4ce444460d
/src/com/jeta/foundation/gui/editor/options/KeySequenceInputPanel.java
daff770c701cddcdc7a9ea96f05dbae06eace344
[]
no_license
jeff-tassin/abeilledb
https://github.com/jeff-tassin/abeilledb
c869dbd95fc229abc88b7f3938cd932dcedd8099
94ffd3d3dff345e35ed64173833d254685af13a1
refs/heads/master
2023-08-10T16:36:08.328000
2022-01-31T19:46:41
2022-01-31T19:46:41
225,102,904
2
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.jeta.foundation.gui.editor.options; import java.awt.Dimension; import java.awt.event.KeyEvent; import java.util.Vector; import javax.swing.KeyStroke; import javax.swing.JLabel; import javax.swing.JTextArea; import javax.swing.JTextField; import com.jeta.foundation.gui.components.TSPanel; import com.jeta.foundation.gui.utils.TSGuiToolbox; /** * Panel that allows the user to type key strokes * */ public class KeySequenceInputPanel extends TSPanel { public static String PROP_KEYSEQUENCE = "keySequence"; private Vector m_strokes = new Vector(); private StringBuffer m_text = new StringBuffer(); private JLabel keySequenceLabel; private JTextArea collisionLabel; private JTextField keySequenceInputField; /** Creates new form KeySequenceInputPanel with empty sequence */ public KeySequenceInputPanel() { initComponents(); } /** * Clears actual sequence of KeyStrokes */ public void clear() { m_strokes.clear(); m_text.setLength(0); keySequenceInputField.setText(m_text.toString()); firePropertyChange(PROP_KEYSEQUENCE, null, null); } /* * Sets the text of JLabel locaten on the bottom of this panel */ public void setInfoText(String s) { collisionLabel.setText(s + ' '); // NOI18N } /** * Returns sequence of completed KeyStrokes as KeyStroke[] */ public KeyStroke[] getKeySequence() { return (KeyStroke[]) m_strokes.toArray(new KeyStroke[0]); } /** * Makes it trying to be bigger */ public Dimension getPreferredSize() { return TSGuiToolbox.getWindowDimension(6, 5); } /** * We're redirecting our focus to proper component. */ public void requestFocus() { keySequenceInputField.requestFocus(); } /** * Visual part and event handling: */ private void initComponents() { // GEN-BEGIN:initComponents java.awt.GridBagConstraints gridBagConstraints; keySequenceLabel = new javax.swing.JLabel(); keySequenceInputField = new javax.swing.JTextField(); collisionLabel = new javax.swing.JTextArea(); setLayout(new java.awt.GridBagLayout()); setBorder(new javax.swing.border.EmptyBorder(new java.awt.Insets(12, 12, 11, 11))); keySequenceLabel.setText("Key_Sequence"); keySequenceLabel.setBorder(new javax.swing.border.EmptyBorder(new java.awt.Insets(0, 0, 0, 8))); keySequenceLabel.setLabelFor(keySequenceInputField); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 12); add(keySequenceLabel, gridBagConstraints); keySequenceInputField.addKeyListener(new java.awt.event.KeyAdapter() { public void keyTyped(java.awt.event.KeyEvent evt) { keySequenceInputFieldKeyTyped(evt); } public void keyPressed(java.awt.event.KeyEvent evt) { keySequenceInputFieldKeyPressed(evt); } public void keyReleased(java.awt.event.KeyEvent evt) { keySequenceInputFieldKeyReleased(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.weightx = 1.0; add(keySequenceInputField, gridBagConstraints); collisionLabel.setLineWrap(true); collisionLabel.setEditable(false); collisionLabel.setRows(2); collisionLabel.setForeground(java.awt.Color.red); collisionLabel.setBackground(getBackground()); collisionLabel.setDisabledTextColor(java.awt.Color.red); collisionLabel.setEnabled(false); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.gridwidth = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; gridBagConstraints.insets = new java.awt.Insets(12, 0, 0, 0); add(collisionLabel, gridBagConstraints); } private void keySequenceInputFieldKeyTyped(java.awt.event.KeyEvent evt) { evt.consume(); } private void keySequenceInputFieldKeyReleased(java.awt.event.KeyEvent evt) { evt.consume(); keySequenceInputField.setText(m_text.toString()); } private void keySequenceInputFieldKeyPressed(java.awt.event.KeyEvent evt) { evt.consume(); String modif = KeyEvent.getKeyModifiersText(evt.getModifiers()); if (isModifier(evt.getKeyCode())) { keySequenceInputField.setText(m_text.toString() + modif + '+'); // NOI18N } else { KeyStroke stroke = KeyStroke.getKeyStrokeForEvent(evt); m_strokes.add(stroke); m_text.append(org.netbeans.editor.Utilities.keyStrokeToString(stroke)); m_text.append(' '); keySequenceInputField.setText(m_text.toString()); firePropertyChange(PROP_KEYSEQUENCE, null, null); } } private boolean isModifier(int keyCode) { return (keyCode == KeyEvent.VK_ALT) || (keyCode == KeyEvent.VK_ALT_GRAPH) || (keyCode == KeyEvent.VK_CONTROL) || (keyCode == KeyEvent.VK_SHIFT) || (keyCode == KeyEvent.VK_META); } /** * This method simply sets the text in the sequence input field. It does not * parse the strokes here. This is mainly for initialization. */ public void setKeyStrokesText(String txt) { keySequenceInputField.setText(txt); keySequenceInputField.selectAll(); } }
UTF-8
Java
5,468
java
KeySequenceInputPanel.java
Java
[]
null
[]
package com.jeta.foundation.gui.editor.options; import java.awt.Dimension; import java.awt.event.KeyEvent; import java.util.Vector; import javax.swing.KeyStroke; import javax.swing.JLabel; import javax.swing.JTextArea; import javax.swing.JTextField; import com.jeta.foundation.gui.components.TSPanel; import com.jeta.foundation.gui.utils.TSGuiToolbox; /** * Panel that allows the user to type key strokes * */ public class KeySequenceInputPanel extends TSPanel { public static String PROP_KEYSEQUENCE = "keySequence"; private Vector m_strokes = new Vector(); private StringBuffer m_text = new StringBuffer(); private JLabel keySequenceLabel; private JTextArea collisionLabel; private JTextField keySequenceInputField; /** Creates new form KeySequenceInputPanel with empty sequence */ public KeySequenceInputPanel() { initComponents(); } /** * Clears actual sequence of KeyStrokes */ public void clear() { m_strokes.clear(); m_text.setLength(0); keySequenceInputField.setText(m_text.toString()); firePropertyChange(PROP_KEYSEQUENCE, null, null); } /* * Sets the text of JLabel locaten on the bottom of this panel */ public void setInfoText(String s) { collisionLabel.setText(s + ' '); // NOI18N } /** * Returns sequence of completed KeyStrokes as KeyStroke[] */ public KeyStroke[] getKeySequence() { return (KeyStroke[]) m_strokes.toArray(new KeyStroke[0]); } /** * Makes it trying to be bigger */ public Dimension getPreferredSize() { return TSGuiToolbox.getWindowDimension(6, 5); } /** * We're redirecting our focus to proper component. */ public void requestFocus() { keySequenceInputField.requestFocus(); } /** * Visual part and event handling: */ private void initComponents() { // GEN-BEGIN:initComponents java.awt.GridBagConstraints gridBagConstraints; keySequenceLabel = new javax.swing.JLabel(); keySequenceInputField = new javax.swing.JTextField(); collisionLabel = new javax.swing.JTextArea(); setLayout(new java.awt.GridBagLayout()); setBorder(new javax.swing.border.EmptyBorder(new java.awt.Insets(12, 12, 11, 11))); keySequenceLabel.setText("Key_Sequence"); keySequenceLabel.setBorder(new javax.swing.border.EmptyBorder(new java.awt.Insets(0, 0, 0, 8))); keySequenceLabel.setLabelFor(keySequenceInputField); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 12); add(keySequenceLabel, gridBagConstraints); keySequenceInputField.addKeyListener(new java.awt.event.KeyAdapter() { public void keyTyped(java.awt.event.KeyEvent evt) { keySequenceInputFieldKeyTyped(evt); } public void keyPressed(java.awt.event.KeyEvent evt) { keySequenceInputFieldKeyPressed(evt); } public void keyReleased(java.awt.event.KeyEvent evt) { keySequenceInputFieldKeyReleased(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.weightx = 1.0; add(keySequenceInputField, gridBagConstraints); collisionLabel.setLineWrap(true); collisionLabel.setEditable(false); collisionLabel.setRows(2); collisionLabel.setForeground(java.awt.Color.red); collisionLabel.setBackground(getBackground()); collisionLabel.setDisabledTextColor(java.awt.Color.red); collisionLabel.setEnabled(false); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.gridwidth = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; gridBagConstraints.insets = new java.awt.Insets(12, 0, 0, 0); add(collisionLabel, gridBagConstraints); } private void keySequenceInputFieldKeyTyped(java.awt.event.KeyEvent evt) { evt.consume(); } private void keySequenceInputFieldKeyReleased(java.awt.event.KeyEvent evt) { evt.consume(); keySequenceInputField.setText(m_text.toString()); } private void keySequenceInputFieldKeyPressed(java.awt.event.KeyEvent evt) { evt.consume(); String modif = KeyEvent.getKeyModifiersText(evt.getModifiers()); if (isModifier(evt.getKeyCode())) { keySequenceInputField.setText(m_text.toString() + modif + '+'); // NOI18N } else { KeyStroke stroke = KeyStroke.getKeyStrokeForEvent(evt); m_strokes.add(stroke); m_text.append(org.netbeans.editor.Utilities.keyStrokeToString(stroke)); m_text.append(' '); keySequenceInputField.setText(m_text.toString()); firePropertyChange(PROP_KEYSEQUENCE, null, null); } } private boolean isModifier(int keyCode) { return (keyCode == KeyEvent.VK_ALT) || (keyCode == KeyEvent.VK_ALT_GRAPH) || (keyCode == KeyEvent.VK_CONTROL) || (keyCode == KeyEvent.VK_SHIFT) || (keyCode == KeyEvent.VK_META); } /** * This method simply sets the text in the sequence input field. It does not * parse the strokes here. This is mainly for initialization. */ public void setKeyStrokesText(String txt) { keySequenceInputField.setText(txt); keySequenceInputField.selectAll(); } }
5,468
0.749451
0.741405
176
30.068182
25.479624
111
false
false
0
0
0
0
0
0
1.948864
false
false
7
fafaa3fe9a8160f2462c98ba01321794736a92d2
18,262,200,995,029
c78bed8d07c2a8baf3ef0c24ec2c197cd6247989
/app/src/main/java/org/dhis2/utils/timber/ReleaseTree.java
9bca458cb5e6786dc13554cad48c60bcaf84e6d1
[ "BSD-3-Clause" ]
permissive
jaboto/dhis2-android-capture-app
https://github.com/jaboto/dhis2-android-capture-app
a8f00e055b696c9afa389cf38fbc23a619b2801b
7d8b077198532753384b3eb979589aeabb072e39
refs/heads/master
2020-12-11T11:46:23.061000
2020-05-07T13:46:34
2020-05-07T13:46:34
220,835,057
1
0
BSD-3-Clause
true
2019-11-10T18:54:05
2019-11-10T18:54:04
2019-11-04T09:14:07
2019-11-08T14:36:58
24,953
0
0
0
null
false
false
package org.dhis2.utils.timber; import androidx.annotation.NonNull; import android.util.Log; import com.crashlytics.android.Crashlytics; import org.jetbrains.annotations.Nullable; import timber.log.Timber; /** * QUADRAM. Created by ppajuelo on 06/06/2018. */ public class ReleaseTree extends Timber.Tree { @Override protected boolean isLoggable(@Nullable String tag, int priority) { // Don't log VERBOSE, DEBUG and INFO only ERROR, WARN and WTF return priority != Log.VERBOSE && priority != Log.DEBUG && priority != Log.INFO; } @Override protected void log(int priority, String tag, @NonNull final String message, final Throwable t) { if (isLoggable(tag, priority)) Crashlytics.log(priority, tag, message); } }
UTF-8
Java
781
java
ReleaseTree.java
Java
[ { "context": "ort timber.log.Timber;\n\n/**\n * QUADRAM. Created by ppajuelo on 06/06/2018.\n */\n\npublic class ReleaseTree exte", "end": 246, "score": 0.9995757937431335, "start": 238, "tag": "USERNAME", "value": "ppajuelo" } ]
null
[]
package org.dhis2.utils.timber; import androidx.annotation.NonNull; import android.util.Log; import com.crashlytics.android.Crashlytics; import org.jetbrains.annotations.Nullable; import timber.log.Timber; /** * QUADRAM. Created by ppajuelo on 06/06/2018. */ public class ReleaseTree extends Timber.Tree { @Override protected boolean isLoggable(@Nullable String tag, int priority) { // Don't log VERBOSE, DEBUG and INFO only ERROR, WARN and WTF return priority != Log.VERBOSE && priority != Log.DEBUG && priority != Log.INFO; } @Override protected void log(int priority, String tag, @NonNull final String message, final Throwable t) { if (isLoggable(tag, priority)) Crashlytics.log(priority, tag, message); } }
781
0.700384
0.68886
29
25.931034
28.582525
100
false
false
0
0
0
0
0
0
0.586207
false
false
7
a33c6da1d98fd7da9d6975a93d089b99e68d6f35
18,262,200,993,421
d245254a501847e2189e2aa52559aba512a02ea5
/app/src/main/java/com/example/demo/ReferenceRegister.java
584b6645c827d739c0051fc2bc88f42209fd40a3
[]
no_license
magegs/My-MiniProject
https://github.com/magegs/My-MiniProject
365d04ea6d1e84e95ad3f17863e9b683676dd786
49c94e4fcf5204eb7fb690b326dcf16afc4c6caa
refs/heads/master
2023-01-24T14:02:08.556000
2020-11-29T20:17:18
2020-11-29T20:17:18
310,593,409
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.demo; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import android.app.ProgressDialog; import android.content.Intent; import android.os.Bundle; import android.text.TextUtils; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.database.ChildEventListener; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.Query; import com.google.firebase.database.ValueEventListener; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.HashMap; import java.util.List; public class ReferenceRegister extends AppCompatActivity { private EditText refkey; private String cust_id = ""; private Button skip, add; private ProgressDialog loadbar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_reference_register); loadbar = new ProgressDialog(this); refkey = (EditText) findViewById(R.id.referencekey); cust_id = getIntent().getStringExtra("cust_phno"); skip = (Button) findViewById(R.id.skip); add = (Button) findViewById(R.id.addref); add.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { ValidRefno(); } }); skip.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(ReferenceRegister.this, login.class); startActivity(intent); } }); } @Override public void onBackPressed() { super.onBackPressed(); Intent startmain=new Intent(Intent.ACTION_MAIN); startmain.addCategory(Intent.CATEGORY_HOME); startmain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(startmain); } private void ValidRefno() { String refno = refkey.getText().toString(); if (TextUtils.isEmpty(refno)) { Toast.makeText(this, "Enter the Reference Key...", Toast.LENGTH_SHORT).show(); } else { loadbar.setTitle("create Account"); loadbar.setMessage("please waait loading..."); loadbar.setCanceledOnTouchOutside(false); loadbar.show(); AddRef(refno); } } private void AddRef(final String refno) { final DatabaseReference RootRef; RootRef = FirebaseDatabase.getInstance().getReference(); ValueEventListener valueEventListener = new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { if (dataSnapshot.child("reference").child(refno).exists()) { UpdateAddRef(refno); } else { Toast.makeText(ReferenceRegister.this, "This" + refno + "Invalid..!", Toast.LENGTH_LONG).show(); Intent intent = new Intent(ReferenceRegister.this, ReferenceRegister.class); startActivity(intent); } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }; RootRef.addListenerForSingleValueEvent(valueEventListener); RootRef.removeEventListener(valueEventListener); } private void UpdateAddRef(final String refno) { final DatabaseReference Updateref; Updateref = FirebaseDatabase.getInstance().getReference(); HashMap<String, Object> usermap = new HashMap<>(); usermap.put("jp_id", cust_id); usermap.put("ref_id", refno); Updateref.child("reference").child(refno).child(cust_id).updateChildren(usermap).addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if (task.isSuccessful()) { UpdatePoints(refno); } } }); } private void UpdatePoints(String refno) { DatabaseReference bonustable = FirebaseDatabase.getInstance().getReference().child("reference").child(refno); ValueEventListener valueEventListener = new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { String refpernum = dataSnapshot.child("ref_num").getValue().toString(); UpdateRefPoints(refpernum); } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }; bonustable.addListenerForSingleValueEvent(valueEventListener); bonustable.removeEventListener(valueEventListener); } private void UpdateRefPoints(String refpernum) { final DatabaseReference PointTable = FirebaseDatabase.getInstance().getReference().child("BonusTable").child(refpernum); ValueEventListener valueEventListener = new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { final String currentpoint = dataSnapshot.child("points").getValue().toString(); int a = Integer.parseInt(currentpoint); int b = 50; final int pointtablevalue = a + b; final String currentfriends=dataSnapshot.child("Total_ref").getValue().toString(); int c=Integer.parseInt(currentfriends); int d=1; final int totalref=c+1; String Bonuscust_id = dataSnapshot.child("cust_id").getValue().toString(); UpdateFinal(Bonuscust_id, pointtablevalue,totalref); } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }; PointTable.addListenerForSingleValueEvent(valueEventListener); PointTable.removeEventListener(valueEventListener); } private void UpdateFinal(final String bonuscust_id, int pointtablevalue, final int totalref) { final DatabaseReference Updaterefpoint = FirebaseDatabase.getInstance().getReference(); Updaterefpoint.child("BonusTable").child(bonuscust_id).child("points").setValue(pointtablevalue).addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if (task.isSuccessful()) { Updaterefpoint.child("BonusTable").child(bonuscust_id).child("Total_ref").setValue(totalref).addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if(task.isSuccessful()){ Toast.makeText(ReferenceRegister.this, "Register Successful!", Toast.LENGTH_LONG).show(); loadbar.dismiss(); Intent intent = new Intent(ReferenceRegister.this, login.class); startActivity(intent); } } }); } else { Toast.makeText(ReferenceRegister.this, "error Successful!", Toast.LENGTH_LONG).show(); } } }); } }
UTF-8
Java
8,012
java
ReferenceRegister.java
Java
[]
null
[]
package com.example.demo; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import android.app.ProgressDialog; import android.content.Intent; import android.os.Bundle; import android.text.TextUtils; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.database.ChildEventListener; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.Query; import com.google.firebase.database.ValueEventListener; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.HashMap; import java.util.List; public class ReferenceRegister extends AppCompatActivity { private EditText refkey; private String cust_id = ""; private Button skip, add; private ProgressDialog loadbar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_reference_register); loadbar = new ProgressDialog(this); refkey = (EditText) findViewById(R.id.referencekey); cust_id = getIntent().getStringExtra("cust_phno"); skip = (Button) findViewById(R.id.skip); add = (Button) findViewById(R.id.addref); add.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { ValidRefno(); } }); skip.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(ReferenceRegister.this, login.class); startActivity(intent); } }); } @Override public void onBackPressed() { super.onBackPressed(); Intent startmain=new Intent(Intent.ACTION_MAIN); startmain.addCategory(Intent.CATEGORY_HOME); startmain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(startmain); } private void ValidRefno() { String refno = refkey.getText().toString(); if (TextUtils.isEmpty(refno)) { Toast.makeText(this, "Enter the Reference Key...", Toast.LENGTH_SHORT).show(); } else { loadbar.setTitle("create Account"); loadbar.setMessage("please waait loading..."); loadbar.setCanceledOnTouchOutside(false); loadbar.show(); AddRef(refno); } } private void AddRef(final String refno) { final DatabaseReference RootRef; RootRef = FirebaseDatabase.getInstance().getReference(); ValueEventListener valueEventListener = new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { if (dataSnapshot.child("reference").child(refno).exists()) { UpdateAddRef(refno); } else { Toast.makeText(ReferenceRegister.this, "This" + refno + "Invalid..!", Toast.LENGTH_LONG).show(); Intent intent = new Intent(ReferenceRegister.this, ReferenceRegister.class); startActivity(intent); } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }; RootRef.addListenerForSingleValueEvent(valueEventListener); RootRef.removeEventListener(valueEventListener); } private void UpdateAddRef(final String refno) { final DatabaseReference Updateref; Updateref = FirebaseDatabase.getInstance().getReference(); HashMap<String, Object> usermap = new HashMap<>(); usermap.put("jp_id", cust_id); usermap.put("ref_id", refno); Updateref.child("reference").child(refno).child(cust_id).updateChildren(usermap).addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if (task.isSuccessful()) { UpdatePoints(refno); } } }); } private void UpdatePoints(String refno) { DatabaseReference bonustable = FirebaseDatabase.getInstance().getReference().child("reference").child(refno); ValueEventListener valueEventListener = new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { String refpernum = dataSnapshot.child("ref_num").getValue().toString(); UpdateRefPoints(refpernum); } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }; bonustable.addListenerForSingleValueEvent(valueEventListener); bonustable.removeEventListener(valueEventListener); } private void UpdateRefPoints(String refpernum) { final DatabaseReference PointTable = FirebaseDatabase.getInstance().getReference().child("BonusTable").child(refpernum); ValueEventListener valueEventListener = new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { final String currentpoint = dataSnapshot.child("points").getValue().toString(); int a = Integer.parseInt(currentpoint); int b = 50; final int pointtablevalue = a + b; final String currentfriends=dataSnapshot.child("Total_ref").getValue().toString(); int c=Integer.parseInt(currentfriends); int d=1; final int totalref=c+1; String Bonuscust_id = dataSnapshot.child("cust_id").getValue().toString(); UpdateFinal(Bonuscust_id, pointtablevalue,totalref); } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }; PointTable.addListenerForSingleValueEvent(valueEventListener); PointTable.removeEventListener(valueEventListener); } private void UpdateFinal(final String bonuscust_id, int pointtablevalue, final int totalref) { final DatabaseReference Updaterefpoint = FirebaseDatabase.getInstance().getReference(); Updaterefpoint.child("BonusTable").child(bonuscust_id).child("points").setValue(pointtablevalue).addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if (task.isSuccessful()) { Updaterefpoint.child("BonusTable").child(bonuscust_id).child("Total_ref").setValue(totalref).addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if(task.isSuccessful()){ Toast.makeText(ReferenceRegister.this, "Register Successful!", Toast.LENGTH_LONG).show(); loadbar.dismiss(); Intent intent = new Intent(ReferenceRegister.this, login.class); startActivity(intent); } } }); } else { Toast.makeText(ReferenceRegister.this, "error Successful!", Toast.LENGTH_LONG).show(); } } }); } }
8,012
0.623065
0.622566
214
36.439251
32.27993
167
false
false
0
0
0
0
0
0
0.551402
false
false
7
e0743e2e60321002de17cfa8aea94754bdb0c06f
2,087,354,149,371
dfb94a6242bae7781abb091e6cea48ee16749f70
/segmentBinarySearchTrees/src/SegmentTree.java
2ec1646345b2ed41cffc8d3d263c061d85eb3a67
[]
no_license
Mashaido/Algorithms
https://github.com/Mashaido/Algorithms
f4edfda3b2e39ab82c725d27a49f75d90124b215
58a1c7de84d2c21b905d893c80305c7c7bcbc174
refs/heads/master
2022-12-18T23:12:41.339000
2020-09-18T02:08:34
2020-09-18T02:08:34
261,889,299
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.util.List; public class SegmentTree { // segment tree private SegmentNode root = null; // Player information provided as an ArrayList of Player objects to SegmentTree constructor public SegmentTree(List<Player> players) { // set to first person in list int minId = players.get(0).getPlayerId(); int maxId = players.get(0).getPlayerId(); for (Player player : players) { // set to smallest id minId = Math.min(minId, player.getPlayerId()); // set to highest id maxId = Math.max(maxId, player.getPlayerId()); } // retrieve the rull range for (Player player : players) { root = build(root, player, minId, maxId); } } // helper method to build each node of the Segment Tree, given a list of players, start and end index private SegmentNode build(SegmentNode root, Player player, int from, int to) { // from lowest playerdId to highest SegmentNode node = root; if (from == to) { // start and end ids are the same return new SegmentNode(from, to, player.getScore()); } if (node == null) { node = new SegmentNode(from, to, 0); } // start is different from end id int mid = (from + to) / 2; if (player.getPlayerId() <= mid) { // go left since it belongs to the left child node.left = build(node.left, player, from, mid); } else { // go right since it belongs to the right child node.right = build(node.right, player, mid + 1, to); } node.maxScore = Math.max(node.maxScore, player.getScore()); return node; } // return the highest score among the players within the given id range. Segment tree --> O(logn) public int rangeHighestQuery(int lowId, int highId) { return rangeHighestQuery_helper(this.root, lowId, highId); } // helper func private int rangeHighestQuery_helper(SegmentNode node, int lowId, int highId) { if (node == null) { return 0; } if (node.lowId >= lowId && node.highId <= highId) { // CASE 1 : node interval lies within needed interval i.e complete overlap return node.maxScore; } else if (node.lowId > highId || node.highId < lowId) { // CASE 2 : node interval falls outside needed interval i.e no overlap return 0; } else { // CASE 3 : partial overlap so call left or right child to find respective answer int midIndex = (node.lowId + node.highId) / 2; int max = 0; if (highId <= midIndex) { // go left max = Math.max(max, rangeHighestQuery_helper(node.left, lowId, highId)); } else if (lowId > midIndex) { // go right max = Math.max(max, rangeHighestQuery_helper(node.right, lowId, highId)); } else { // call both children int left = rangeHighestQuery_helper(node.left, lowId, highId); int right = rangeHighestQuery_helper(node.right, lowId, highId); max = Math.max(max, Math.max(left, right)); } return max; } } // update method called by BST update public void update(int id, int score) { int res = update_helper(this.root, id, score); } // helper func private int update_helper(SegmentNode node, int id, int score) { if (node.lowId == id && node.highId == id && score > node.maxScore) { // base case: score to insert > existing node's maxScore and we're at the leaf node node.maxScore = score; } else { // start is different from end id int mid = (node.lowId + node.highId) / 2; if (id <= mid) { // go left since it belongs to the left child node.maxScore = Math.max(node.maxScore, update_helper(node.left, id, score)); } else { // go right since it belongs to the right child node.maxScore = Math.max(node.maxScore, update_helper(node.right, id, score)); } } return node.maxScore; } }
UTF-8
Java
4,414
java
SegmentTree.java
Java
[]
null
[]
import java.util.List; public class SegmentTree { // segment tree private SegmentNode root = null; // Player information provided as an ArrayList of Player objects to SegmentTree constructor public SegmentTree(List<Player> players) { // set to first person in list int minId = players.get(0).getPlayerId(); int maxId = players.get(0).getPlayerId(); for (Player player : players) { // set to smallest id minId = Math.min(minId, player.getPlayerId()); // set to highest id maxId = Math.max(maxId, player.getPlayerId()); } // retrieve the rull range for (Player player : players) { root = build(root, player, minId, maxId); } } // helper method to build each node of the Segment Tree, given a list of players, start and end index private SegmentNode build(SegmentNode root, Player player, int from, int to) { // from lowest playerdId to highest SegmentNode node = root; if (from == to) { // start and end ids are the same return new SegmentNode(from, to, player.getScore()); } if (node == null) { node = new SegmentNode(from, to, 0); } // start is different from end id int mid = (from + to) / 2; if (player.getPlayerId() <= mid) { // go left since it belongs to the left child node.left = build(node.left, player, from, mid); } else { // go right since it belongs to the right child node.right = build(node.right, player, mid + 1, to); } node.maxScore = Math.max(node.maxScore, player.getScore()); return node; } // return the highest score among the players within the given id range. Segment tree --> O(logn) public int rangeHighestQuery(int lowId, int highId) { return rangeHighestQuery_helper(this.root, lowId, highId); } // helper func private int rangeHighestQuery_helper(SegmentNode node, int lowId, int highId) { if (node == null) { return 0; } if (node.lowId >= lowId && node.highId <= highId) { // CASE 1 : node interval lies within needed interval i.e complete overlap return node.maxScore; } else if (node.lowId > highId || node.highId < lowId) { // CASE 2 : node interval falls outside needed interval i.e no overlap return 0; } else { // CASE 3 : partial overlap so call left or right child to find respective answer int midIndex = (node.lowId + node.highId) / 2; int max = 0; if (highId <= midIndex) { // go left max = Math.max(max, rangeHighestQuery_helper(node.left, lowId, highId)); } else if (lowId > midIndex) { // go right max = Math.max(max, rangeHighestQuery_helper(node.right, lowId, highId)); } else { // call both children int left = rangeHighestQuery_helper(node.left, lowId, highId); int right = rangeHighestQuery_helper(node.right, lowId, highId); max = Math.max(max, Math.max(left, right)); } return max; } } // update method called by BST update public void update(int id, int score) { int res = update_helper(this.root, id, score); } // helper func private int update_helper(SegmentNode node, int id, int score) { if (node.lowId == id && node.highId == id && score > node.maxScore) { // base case: score to insert > existing node's maxScore and we're at the leaf node node.maxScore = score; } else { // start is different from end id int mid = (node.lowId + node.highId) / 2; if (id <= mid) { // go left since it belongs to the left child node.maxScore = Math.max(node.maxScore, update_helper(node.left, id, score)); } else { // go right since it belongs to the right child node.maxScore = Math.max(node.maxScore, update_helper(node.right, id, score)); } } return node.maxScore; } }
4,414
0.552333
0.549388
124
34.572582
29.716991
118
false
false
0
0
0
0
0
0
0.677419
false
false
7
09a504d402dc177e2b705d717ad05bba1217a3f7
17,763,984,747,438
fa94c270905ae6f8cd1247b5a4d6267b9ec208ba
/src/it/polimi/ingsw2020/ex3/Square.java
2f57c0aa31c5c950792123fd14cd143c598c5b3d
[]
no_license
gioenn/ingsw-2020
https://github.com/gioenn/ingsw-2020
c7955842b813f8124f882d5c76b148a9ab695555
cf86585c0195e6b572fb3702e04b4d3bb5c5151a
refs/heads/master
2023-01-20T08:58:39.207000
2020-11-24T08:45:09
2020-11-24T08:45:09
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package it.polimi.ingsw2020.ex3; public class Square extends Rectangle { public Square(float edge){ super(edge, edge); } @Override public String getName() { return "Quadrato"; } }
UTF-8
Java
219
java
Square.java
Java
[]
null
[]
package it.polimi.ingsw2020.ex3; public class Square extends Rectangle { public Square(float edge){ super(edge, edge); } @Override public String getName() { return "Quadrato"; } }
219
0.616438
0.593607
13
15.846154
14.12497
39
false
false
0
0
0
0
0
0
0.307692
false
false
7
2ee5ca6674bffa34cf4b769c0d18eff717017883
5,755,256,179,359
1ba89a434111361ad6101b98cff7d3ff2a21d042
/DoublyLinkedList/Node.java
c46e892d591196bd8d2224802b100c8a8c37ac4e
[]
no_license
spiderweb1801/DS
https://github.com/spiderweb1801/DS
c4651d84925db131344b3a6e19c9c022dc7f4e1d
2aaf4eddef3c96e56562a0094b8824b583424200
refs/heads/master
2020-04-17T22:33:17.018000
2019-01-23T06:26:11
2019-01-23T06:26:11
166,998,959
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package DoublyLinkedList; public class Node { Node prev, next; int value; public Node(int value) { this.value=value; prev=null; next=null; } }
UTF-8
Java
160
java
Node.java
Java
[]
null
[]
package DoublyLinkedList; public class Node { Node prev, next; int value; public Node(int value) { this.value=value; prev=null; next=null; } }
160
0.6625
0.6625
15
9.666667
8.881942
25
false
false
0
0
0
0
0
0
1.333333
false
false
7
8a460cebbce6d2f75c03f9398ac436e673307d6e
5,755,256,181,078
46877eaa45800da09852f907e867ccab91bb2ac6
/src/main/java/com/student/book_advisor/security/redis/RedisUtil.java
a29b201379ec2405df1f1d0b718ac02f4aa2367b
[]
no_license
Carlo-Turrini/BookAdvisor
https://github.com/Carlo-Turrini/BookAdvisor
1a6d0d81a003dca801c94aa4b4875279a3e31573
ab2ba5734c9f7cb1ff50a64f33b9b22b60b6b74d
refs/heads/master
2022-12-06T18:40:44.597000
2020-09-01T13:03:22
2020-09-01T13:03:22
285,547,749
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.student.book_advisor.security.redis; import org.springframework.stereotype.Component; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool; import redis.clients.jedis.JedisPoolConfig; import java.util.Date; @Component public class RedisUtil { private final JedisPool pool = new JedisPool(new JedisPoolConfig(), "localhost"); public void set(String key, String value, Date expirationDate) { Jedis jedis = null; try { Long timeout = (expirationDate.getTime() - new Date().getTime())/1000; jedis = pool.getResource(); jedis.set(key, value); jedis.expireAt(key, timeout); } catch(Exception e) { throw new RuntimeException(e); } finally { if(jedis != null) { jedis.close(); } } } public boolean isMember(String key, String value) { Jedis jedis = null; try { jedis = pool.getResource(); String cachedToken = jedis.get(key); if(cachedToken != null) { return cachedToken.equals(value); } else return false; } catch(Exception e) { throw new RuntimeException(e); } finally { if(jedis != null) { jedis.close(); } } } }
UTF-8
Java
1,403
java
RedisUtil.java
Java
[]
null
[]
package com.student.book_advisor.security.redis; import org.springframework.stereotype.Component; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool; import redis.clients.jedis.JedisPoolConfig; import java.util.Date; @Component public class RedisUtil { private final JedisPool pool = new JedisPool(new JedisPoolConfig(), "localhost"); public void set(String key, String value, Date expirationDate) { Jedis jedis = null; try { Long timeout = (expirationDate.getTime() - new Date().getTime())/1000; jedis = pool.getResource(); jedis.set(key, value); jedis.expireAt(key, timeout); } catch(Exception e) { throw new RuntimeException(e); } finally { if(jedis != null) { jedis.close(); } } } public boolean isMember(String key, String value) { Jedis jedis = null; try { jedis = pool.getResource(); String cachedToken = jedis.get(key); if(cachedToken != null) { return cachedToken.equals(value); } else return false; } catch(Exception e) { throw new RuntimeException(e); } finally { if(jedis != null) { jedis.close(); } } } }
1,403
0.550249
0.547398
51
26.509804
20.253658
85
false
false
0
0
0
0
0
0
0.529412
false
false
7
d85b5f5a1ecb165528267963c32b7734f0feaa2b
11,252,814,320,034
94aa18f6113a44953aa9d47edac21fa98e4efe96
/src/uk/co/bbc/videofactorydemo/GtiElemental.java
aecfdf628aff083f20e0d286827582d958ad574b
[]
no_license
bbc/VideoFactoryDemo
https://github.com/bbc/VideoFactoryDemo
4158f647acd6a2b7214adcb6fafe9cc7d4c08007
48810e5b4bc7f725be25c1bb9d0068f38d3c62e3
refs/heads/master
2020-10-01T20:25:49.354000
2020-01-09T11:21:25
2020-01-09T11:21:25
227,618,668
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package uk.co.bbc.videofactorydemo; import me.acdean.factory.Component; import me.acdean.factory.Factory; public class GtiElemental extends Component { public static final String NAME = "GtiElemental"; public static final String DESCRIPTION = "General purpose encoder."; public GtiElemental(Factory factory, int x, int y) { super(factory, x, y, NAME); setDescription(DESCRIPTION); addInput(GtiRouter2.NAME); } @Override public void emit() { routeToDestination(); } // reads from s3, processes, writes to s3 @Override public void processMessage() { readWorkWriteEmit(); } }
UTF-8
Java
663
java
GtiElemental.java
Java
[]
null
[]
package uk.co.bbc.videofactorydemo; import me.acdean.factory.Component; import me.acdean.factory.Factory; public class GtiElemental extends Component { public static final String NAME = "GtiElemental"; public static final String DESCRIPTION = "General purpose encoder."; public GtiElemental(Factory factory, int x, int y) { super(factory, x, y, NAME); setDescription(DESCRIPTION); addInput(GtiRouter2.NAME); } @Override public void emit() { routeToDestination(); } // reads from s3, processes, writes to s3 @Override public void processMessage() { readWorkWriteEmit(); } }
663
0.671192
0.666667
27
23.555555
20.353056
72
false
false
0
0
0
0
0
0
0.62963
false
false
7
d14196efcedbda870193b3ff739460c3857fd8db
3,616,362,479,591
ac8b9c36773a9b025d8384d29f810bc8a894b23f
/src/main/java/org/flowr/framework/core/security/policy/EnterprisePolicy.java
b5977e27aa64b5596115ef7376dfbe88da05f062
[]
no_license
chandraspandey/flowR
https://github.com/chandraspandey/flowR
d69948d684113a5fc3573f4dcd1326c32bfbf2cb
0a5cc233b15c71da41b648722e31b2a5da0d0f20
refs/heads/master
2021-06-04T02:22:52.990000
2020-06-06T16:04:55
2020-06-06T16:04:55
89,334,795
0
0
null
false
2020-10-12T23:31:34
2017-04-25T08:11:13
2020-06-06T16:04:58
2020-10-12T23:31:33
1,022
0
0
1
Java
false
false
/** * * * @author Chandra Shekhar Pandey * Copyright � 2018 by Chandra Shekhar Pandey. All rights reserved. * */ package org.flowr.framework.core.security.policy; import java.util.ArrayList; import org.flowr.framework.core.context.Context.PolicyContext; import org.flowr.framework.core.security.audit.AuditHandler; import org.flowr.framework.core.security.audit.Auditable.AuditType; public class EnterprisePolicy implements Policy{ private PolicyType policyType; private AuditHandler auditHandler; private Version policyVersion; private ArrayList<PolicyConstraint> policyConstraintList; private Exemption exemption; private PolicyLoader policyLoader; @Override public void setPolicyType(PolicyType policyType) { this.policyType=policyType; } @Override public PolicyType getPolicyType() { return this.policyType; } @Override public Policy loadPolicy(PolicyContext policyContext) { return policyLoader.loadPolicy(policyContext); } @Override public void setPolicyVersion(Version version) { this.policyVersion=version; } @Override public Version getPolicyVersion() { return this.policyVersion; } @Override public void setPolicyConstraint( ArrayList<PolicyConstraint> policyConstraintList) { this.policyConstraintList = policyConstraintList; policyConstraintList.forEach( c -> this.auditHandler.logChange(AuditType.ADD, c) ); } @Override public ArrayList<PolicyConstraint> getPolicyConstraint() { return this.policyConstraintList; } @Override public void addPolicyConstraint(PolicyConstraint policyConstraint) { if(policyConstraintList != null){ policyConstraintList = new ArrayList<>(); policyConstraintList.add(policyConstraint); this.auditHandler.logChange(AuditType.ADD, policyConstraint); } } @Override public Exemption getExemption() { return this.exemption; } @Override public void setExemption(Exemption exemption) { this.exemption = exemption; this.auditHandler.logChange(AuditType.ADD, exemption); } @Override public void setPolicyLoader(PolicyLoader policyLoader) { this.policyLoader = policyLoader; } @Override public PolicyLoader getPolicyLoader() { return this.policyLoader; } @Override public void setAuditHandler(AuditHandler auditHandler) { this.auditHandler = auditHandler; } }
UTF-8
Java
2,781
java
EnterprisePolicy.java
Java
[ { "context": "\r\n/**\r\n * \r\n * \r\n * @author Chandra Shekhar Pandey\r\n * Copyright � 2018 by Chandra Shekhar Pandey. A", "end": 50, "score": 0.9998892545700073, "start": 28, "tag": "NAME", "value": "Chandra Shekhar Pandey" }, { "context": "hor Chandra Shekhar Pandey\r\n * Copyright � 2018 by Chandra Shekhar Pandey. All rights reserved.\r\n *\r\n */\r\npackage org.flowr", "end": 97, "score": 0.9998874664306641, "start": 75, "tag": "NAME", "value": "Chandra Shekhar Pandey" } ]
null
[]
/** * * * @author <NAME> * Copyright � 2018 by <NAME>. All rights reserved. * */ package org.flowr.framework.core.security.policy; import java.util.ArrayList; import org.flowr.framework.core.context.Context.PolicyContext; import org.flowr.framework.core.security.audit.AuditHandler; import org.flowr.framework.core.security.audit.Auditable.AuditType; public class EnterprisePolicy implements Policy{ private PolicyType policyType; private AuditHandler auditHandler; private Version policyVersion; private ArrayList<PolicyConstraint> policyConstraintList; private Exemption exemption; private PolicyLoader policyLoader; @Override public void setPolicyType(PolicyType policyType) { this.policyType=policyType; } @Override public PolicyType getPolicyType() { return this.policyType; } @Override public Policy loadPolicy(PolicyContext policyContext) { return policyLoader.loadPolicy(policyContext); } @Override public void setPolicyVersion(Version version) { this.policyVersion=version; } @Override public Version getPolicyVersion() { return this.policyVersion; } @Override public void setPolicyConstraint( ArrayList<PolicyConstraint> policyConstraintList) { this.policyConstraintList = policyConstraintList; policyConstraintList.forEach( c -> this.auditHandler.logChange(AuditType.ADD, c) ); } @Override public ArrayList<PolicyConstraint> getPolicyConstraint() { return this.policyConstraintList; } @Override public void addPolicyConstraint(PolicyConstraint policyConstraint) { if(policyConstraintList != null){ policyConstraintList = new ArrayList<>(); policyConstraintList.add(policyConstraint); this.auditHandler.logChange(AuditType.ADD, policyConstraint); } } @Override public Exemption getExemption() { return this.exemption; } @Override public void setExemption(Exemption exemption) { this.exemption = exemption; this.auditHandler.logChange(AuditType.ADD, exemption); } @Override public void setPolicyLoader(PolicyLoader policyLoader) { this.policyLoader = policyLoader; } @Override public PolicyLoader getPolicyLoader() { return this.policyLoader; } @Override public void setAuditHandler(AuditHandler auditHandler) { this.auditHandler = auditHandler; } }
2,749
0.649874
0.648435
106
24.198112
23.669668
88
false
false
0
0
0
0
0
0
0.292453
false
false
7
faf1551f2e9abe5f8524b8d21b205d45bfb873dc
24,068,996,736,195
39538883e89270f24917de7c261aa61b1032a203
/src/com/guozha/buy/entry/cart/ShowTime.java
bc60aa003ea8f3f08e6494f3677428f722061abb
[]
no_license
Guozha/BUY
https://github.com/Guozha/BUY
ac2aa19f0f2107af27d384f7f46a9ae19cac7353
fdfc616dd6122084d8bed62b05a469fc8f7b16e0
refs/heads/master
2021-03-27T14:01:59.240000
2015-06-14T06:57:44
2015-06-14T06:57:44
30,394,161
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.guozha.buy.entry.cart; public class ShowTime { private String dayname; private String fromTime; private String toTime; public ShowTime(String dayname, String fromTime, String toTime) { super(); this.dayname = dayname; this.fromTime = fromTime; this.toTime = toTime; } public String getDayname() { return dayname; } public void setDayname(String dayname) { this.dayname = dayname; } public String getFromTime() { return fromTime; } public void setFromTime(String fromTime) { this.fromTime = fromTime; } public String getToTime() { return toTime; } public void setToTime(String toTime) { this.toTime = toTime; } }
UTF-8
Java
708
java
ShowTime.java
Java
[]
null
[]
package com.guozha.buy.entry.cart; public class ShowTime { private String dayname; private String fromTime; private String toTime; public ShowTime(String dayname, String fromTime, String toTime) { super(); this.dayname = dayname; this.fromTime = fromTime; this.toTime = toTime; } public String getDayname() { return dayname; } public void setDayname(String dayname) { this.dayname = dayname; } public String getFromTime() { return fromTime; } public void setFromTime(String fromTime) { this.fromTime = fromTime; } public String getToTime() { return toTime; } public void setToTime(String toTime) { this.toTime = toTime; } }
708
0.673729
0.673729
36
17.666666
15.705626
66
false
false
0
0
0
0
0
0
1.611111
false
false
7
9167fc9ca6ebcd2b5668e5b4937d83a669457391
24,163,486,029,368
ac7753b9ef81c54dab64abbdf2cd7309220d867a
/src/main/java/com/example/sweater/util/UserUtil.java
39459e90f1b2422dd7b00fb4cb8cad10523ac1de
[]
no_license
Lamekhova/votingApp
https://github.com/Lamekhova/votingApp
106e877115c07f198aea5bdfc6a3ce0847f380d9
af53ab05021afb2d1d57c9dc036df69e7b7a946e
refs/heads/master
2020-04-08T20:34:37.852000
2019-03-12T09:11:34
2019-03-12T09:11:34
159,705,763
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.sweater.util; import com.example.sweater.model.Role; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import java.util.Collection; import java.util.Set; import java.util.stream.Collectors; public class UserUtil { private static BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder(10); public static String encodePassword(String password) { return passwordEncoder.encode(password); } public static String checkEncodePassword(String rawPassword, String encodePassword) { String actualPassword = encodePassword; if (!passwordEncoder.matches(rawPassword, encodePassword)) { actualPassword = passwordEncoder.encode(rawPassword); } return actualPassword; } public static Set<Role> getRolesFromAuthorities(Collection<? extends GrantedAuthority> authorities) { return authorities.stream() .map(gr -> Role.valueOf(gr.getAuthority())) .collect(Collectors.toSet()); } }
UTF-8
Java
1,103
java
UserUtil.java
Java
[]
null
[]
package com.example.sweater.util; import com.example.sweater.model.Role; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import java.util.Collection; import java.util.Set; import java.util.stream.Collectors; public class UserUtil { private static BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder(10); public static String encodePassword(String password) { return passwordEncoder.encode(password); } public static String checkEncodePassword(String rawPassword, String encodePassword) { String actualPassword = encodePassword; if (!passwordEncoder.matches(rawPassword, encodePassword)) { actualPassword = passwordEncoder.encode(rawPassword); } return actualPassword; } public static Set<Role> getRolesFromAuthorities(Collection<? extends GrantedAuthority> authorities) { return authorities.stream() .map(gr -> Role.valueOf(gr.getAuthority())) .collect(Collectors.toSet()); } }
1,103
0.731641
0.729828
32
33.46875
30.411741
105
false
false
0
0
0
0
0
0
0.46875
false
false
7
84f57d78a0848bf65bb0ea22ab056c3076188dcc
24,670,292,159,271
07895a28b12f33917855e2ddf7a573622c29c4fe
/src/poopfinal/MGNombres.java
5a93ff08b5d6aae6988caecea1c0a2e3d28abcfa
[]
no_license
Adrian2902/POOPFinalCodigo
https://github.com/Adrian2902/POOPFinalCodigo
a47bf4ef86d5ec9607c3b20d6a2964a8d2ea707a
a3590d806091bc7d1d5edfc58974b9547e84c536
refs/heads/main
2023-07-07T09:46:37.682000
2021-08-16T06:24:30
2021-08-16T06:24:30
396,646,045
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package poopfinal; import java.util.Random; /** * * @author De La Cruz Padilla Marlene Mariana, Gutierrez Carbajal Adrian */ public class MGNombres { public String generaNombre(){ String Nombres[] = {"Juan Miguel", "Luis Felipe", "Laura", "Susana", "Alvaro", "Sara", "Carlos Alberto", "Jose Alvaro", "Maria Lucinda", "Jesus", "Hector Gerardo", "Josefina Maria", "Maria Dolores", "Manuel", "Jorge", "Erick", "Paloma", "Mario Arturo", "Patricia", "Celia", "Carlos Alfonso", "Maria Isabel", "Rafael", "Maria Asuncion", "Francisco Javier", "Pablo", "Jose", "Jose Dante", "Maria del Carmen", "Arturo", "Alberto Manuel", "Rogelio", "Joaquin", "Angel Antonio", "Heriberto", "Maria de Lourdes", "Roberto", "Ruben", "Jose Antonio", "Cuauhtemoc", "Juan Socorro", "Jose Hugo", "Jaime Jacobo", "Lourdes", "Andrea", "Oscar Gerardo", "Pedro", "Ana", "Cristina", "Adrian"}; Random nombreAlu = new Random(); int nNombre = nombreAlu.nextInt(49-0+1) + 0; String nombre = Nombres[nNombre]; return nombre; } public String generaApellido(){ String Apellidos [] = {"Vera Lastra", "Aguilar Navarro", "Salinas Aguilar", "Aguirre Cruz", "Alberu Gomez", "Alcantar Curiel", "Alcaraz Verduzco", "Alcocer Varela", "Alexanderson Rosas", "Almeda Valdes", "Alonson Vanegas", "Alpuche Aranda", "Barrangan Garcia", "Barquera Cervera", "Barrera Saldaña", "Barrientos Melendez", "Blanco Favela", "Calderon Colmenero", "Calva Mercado", "Cardona Perez", "Carranza Lira", "Carrillo Ruiz", "Castillo Martinez", "Chavez Negrete", "De La Fuente Ramirez", "Del Rio Navarro", "Diaz Quiñonez", "Dominguez Carrillo", "Elizondo Riojas", "Escalante Acosta","Eslava Campos", "Espinola Zavaleta", "Fajardo Ortiz", "Feria Bernal", "Flores Rivera", "Fuente Del Campo", "Gomez Perez", "Gonzalez Ortiz", "Guadalajara Boo", "Hernandez Avila", "Herrera Abarca", "Hinojosa Becerril", "Iglesias Morales", "Jimenez Ponce", "Jung Cook", "Kimura Fujikami", "Lara Muñoz", "Lemus Bravo", "Madrazo Navarro"}; Random apellidoAlu = new Random(); int nApellido = apellidoAlu.nextInt(49-0+1) + 0; String apellido = Apellidos[nApellido]; return apellido; } }
UTF-8
Java
2,486
java
MGNombres.java
Java
[ { "context": "\n\r\nimport java.util.Random;\r\n\r\n/**\r\n *\r\n * @author De La Cruz Padilla Marlene Mariana, Gutierrez Carbajal Adrian\r\n */\r\n", "end": 88, "score": 0.999312698841095, "start": 70, "tag": "NAME", "value": "De La Cruz Padilla" }, { "context": ".Random;\r\n\r\n/**\r\n *\r\n * @author De La Cruz Padilla Marlene Mariana, Gutierrez Carbajal Adrian\r\n */\r\npublic class MGN", "end": 104, "score": 0.9998524188995361, "start": 89, "tag": "NAME", "value": "Marlene Mariana" }, { "context": " *\r\n * @author De La Cruz Padilla Marlene Mariana, Gutierrez Carbajal Adrian\r\n */\r\npublic class MGNombres {\r\n \r\n public ", "end": 131, "score": 0.9997021555900574, "start": 106, "tag": "NAME", "value": "Gutierrez Carbajal Adrian" }, { "context": "eneraNombre(){\r\n \r\n String Nombres[] = {\"Juan Miguel\", \"Luis Felipe\", \"Laura\", \"Susana\", \"Alvaro\", \"Sa", "end": 250, "score": 0.9998706579208374, "start": 239, "tag": "NAME", "value": "Juan Miguel" }, { "context": "\n \r\n String Nombres[] = {\"Juan Miguel\", \"Luis Felipe\", \"Laura\", \"Susana\", \"Alvaro\", \"Sara\", \"Carlos Al", "end": 265, "score": 0.9998672604560852, "start": 254, "tag": "NAME", "value": "Luis Felipe" }, { "context": "tring Nombres[] = {\"Juan Miguel\", \"Luis Felipe\", \"Laura\", \"Susana\", \"Alvaro\", \"Sara\", \"Carlos Alberto\", \"", "end": 274, "score": 0.9998364448547363, "start": 269, "tag": "NAME", "value": "Laura" }, { "context": "bres[] = {\"Juan Miguel\", \"Luis Felipe\", \"Laura\", \"Susana\", \"Alvaro\", \"Sara\", \"Carlos Alberto\", \"Jose Alvar", "end": 284, "score": 0.9998101592063904, "start": 278, "tag": "NAME", "value": "Susana" }, { "context": "\"Juan Miguel\", \"Luis Felipe\", \"Laura\", \"Susana\", \"Alvaro\", \"Sara\", \"Carlos Alberto\", \"Jose Alvaro\", \"Maria", "end": 294, "score": 0.9998148083686829, "start": 288, "tag": "NAME", "value": "Alvaro" }, { "context": "el\", \"Luis Felipe\", \"Laura\", \"Susana\", \"Alvaro\", \"Sara\", \"Carlos Alberto\", \"Jose Alvaro\", \"Maria Lucinda", "end": 302, "score": 0.9998176097869873, "start": 298, "tag": "NAME", "value": "Sara" }, { "context": "is Felipe\", \"Laura\", \"Susana\", \"Alvaro\", \"Sara\", \"Carlos Alberto\", \"Jose Alvaro\", \"Maria Lucinda\", \"Jesus\", \"Hecto", "end": 320, "score": 0.9998534917831421, "start": 306, "tag": "NAME", "value": "Carlos Alberto" }, { "context": "\", \"Susana\", \"Alvaro\", \"Sara\", \"Carlos Alberto\", \"Jose Alvaro\", \"Maria Lucinda\", \"Jesus\", \"Hector Gerardo\", \"Jo", "end": 335, "score": 0.99986732006073, "start": 324, "tag": "NAME", "value": "Jose Alvaro" }, { "context": "lvaro\", \"Sara\", \"Carlos Alberto\", \"Jose Alvaro\", \"Maria Lucinda\", \"Jesus\", \"Hector Gerardo\", \"Josefina Maria\", \"M", "end": 352, "score": 0.9998562932014465, "start": 339, "tag": "NAME", "value": "Maria Lucinda" }, { "context": "Carlos Alberto\", \"Jose Alvaro\", \"Maria Lucinda\", \"Jesus\", \"Hector Gerardo\", \"Josefina Maria\", \"Maria Dolo", "end": 361, "score": 0.9998626112937927, "start": 356, "tag": "NAME", "value": "Jesus" }, { "context": "berto\", \"Jose Alvaro\", \"Maria Lucinda\", \"Jesus\", \"Hector Gerardo\", \"Josefina Maria\", \"Maria Dolores\", \r\n ", "end": 379, "score": 0.999863862991333, "start": 365, "tag": "NAME", "value": "Hector Gerardo" }, { "context": "ro\", \"Maria Lucinda\", \"Jesus\", \"Hector Gerardo\", \"Josefina Maria\", \"Maria Dolores\", \r\n ", "end": 397, "score": 0.9998639225959778, "start": 383, "tag": "NAME", "value": "Josefina Maria" }, { "context": "a\", \"Jesus\", \"Hector Gerardo\", \"Josefina Maria\", \"Maria Dolores\", \r\n \"Manuel\", \"Jorge\"", "end": 414, "score": 0.9998654127120972, "start": 401, "tag": "NAME", "value": "Maria Dolores" }, { "context": ", \"Maria Dolores\", \r\n \"Manuel\", \"Jorge\", \"Erick\", \"Paloma\", \"Mario Arturo\", \"Pa", "end": 454, "score": 0.9998395442962646, "start": 448, "tag": "NAME", "value": "Manuel" }, { "context": "olores\", \r\n \"Manuel\", \"Jorge\", \"Erick\", \"Paloma\", \"Mario Arturo\", \"Patricia\", ", "end": 463, "score": 0.9998166561126709, "start": 458, "tag": "NAME", "value": "Jorge" }, { "context": "\r\n \"Manuel\", \"Jorge\", \"Erick\", \"Paloma\", \"Mario Arturo\", \"Patricia\", \"Celia\", ", "end": 472, "score": 0.9998161792755127, "start": 467, "tag": "NAME", "value": "Erick" }, { "context": " \"Manuel\", \"Jorge\", \"Erick\", \"Paloma\", \"Mario Arturo\", \"Patricia\", \"Celia\", \"Carlos Al", "end": 482, "score": 0.9998149275779724, "start": 476, "tag": "NAME", "value": "Paloma" }, { "context": " \"Manuel\", \"Jorge\", \"Erick\", \"Paloma\", \"Mario Arturo\", \"Patricia\", \"Celia\", \"Carlos Alfonso\", \"Maria I", "end": 498, "score": 0.9998641610145569, "start": 486, "tag": "NAME", "value": "Mario Arturo" }, { "context": "el\", \"Jorge\", \"Erick\", \"Paloma\", \"Mario Arturo\", \"Patricia\", \"Celia\", \"Carlos Alfonso\", \"Maria Isabel\", \"Raf", "end": 510, "score": 0.9998553395271301, "start": 502, "tag": "NAME", "value": "Patricia" }, { "context": ", \"Erick\", \"Paloma\", \"Mario Arturo\", \"Patricia\", \"Celia\", \"Carlos Alfonso\", \"Maria Isabel\", \"Rafael\", \"Ma", "end": 519, "score": 0.999817430973053, "start": 514, "tag": "NAME", "value": "Celia" }, { "context": ", \"Paloma\", \"Mario Arturo\", \"Patricia\", \"Celia\", \"Carlos Alfonso\", \"Maria Isabel\", \"Rafael\", \"Maria Asuncion\", \"Fr", "end": 537, "score": 0.9998576045036316, "start": 523, "tag": "NAME", "value": "Carlos Alfonso" }, { "context": " Arturo\", \"Patricia\", \"Celia\", \"Carlos Alfonso\", \"Maria Isabel\", \"Rafael\", \"Maria Asuncion\", \"Francisco Javier\",", "end": 553, "score": 0.9998562335968018, "start": 541, "tag": "NAME", "value": "Maria Isabel" }, { "context": "cia\", \"Celia\", \"Carlos Alfonso\", \"Maria Isabel\", \"Rafael\", \"Maria Asuncion\", \"Francisco Javier\", \"Pablo\", ", "end": 563, "score": 0.9998487830162048, "start": 557, "tag": "NAME", "value": "Rafael" }, { "context": "ia\", \"Carlos Alfonso\", \"Maria Isabel\", \"Rafael\", \"Maria Asuncion\", \"Francisco Javier\", \"Pablo\", \"Jose\", \"Jose Dant", "end": 581, "score": 0.9998606443405151, "start": 567, "tag": "NAME", "value": "Maria Asuncion" }, { "context": "so\", \"Maria Isabel\", \"Rafael\", \"Maria Asuncion\", \"Francisco Javier\", \"Pablo\", \"Jose\", \"Jose Dante\",\r\n ", "end": 601, "score": 0.9998586773872375, "start": 585, "tag": "NAME", "value": "Francisco Javier" }, { "context": " \"Rafael\", \"Maria Asuncion\", \"Francisco Javier\", \"Pablo\", \"Jose\", \"Jose Dante\",\r\n ", "end": 610, "score": 0.9998260736465454, "start": 605, "tag": "NAME", "value": "Pablo" }, { "context": ", \"Maria Asuncion\", \"Francisco Javier\", \"Pablo\", \"Jose\", \"Jose Dante\",\r\n \"Mar", "end": 618, "score": 0.9998300075531006, "start": 614, "tag": "NAME", "value": "Jose" }, { "context": " Asuncion\", \"Francisco Javier\", \"Pablo\", \"Jose\", \"Jose Dante\",\r\n \"Maria del Carmen\"", "end": 632, "score": 0.9998506903648376, "start": 622, "tag": "NAME", "value": "Jose Dante" }, { "context": "ose\", \"Jose Dante\",\r\n \"Maria del Carmen\", \"Arturo\", \"Alberto Manuel\", \"Rogelio\", \"Joaquin", "end": 681, "score": 0.9998682141304016, "start": 665, "tag": "NAME", "value": "Maria del Carmen" }, { "context": "\n \"Maria del Carmen\", \"Arturo\", \"Alberto Manuel\", \"Rogelio\", \"Joaquin\", \"Angel ", "end": 691, "score": 0.9998477697372437, "start": 685, "tag": "NAME", "value": "Arturo" }, { "context": " \"Maria del Carmen\", \"Arturo\", \"Alberto Manuel\", \"Rogelio\", \"Joaquin\", \"Angel Antonio\", \"Heriber", "end": 709, "score": 0.9998559355735779, "start": 695, "tag": "NAME", "value": "Alberto Manuel" }, { "context": " \"Maria del Carmen\", \"Arturo\", \"Alberto Manuel\", \"Rogelio\", \"Joaquin\", \"Angel Antonio\", \"Heriberto\", \"Maria", "end": 720, "score": 0.9998608231544495, "start": 713, "tag": "NAME", "value": "Rogelio" }, { "context": " Carmen\", \"Arturo\", \"Alberto Manuel\", \"Rogelio\", \"Joaquin\", \"Angel Antonio\", \"Heriberto\", \"Maria de Lourdes", "end": 731, "score": 0.9998612999916077, "start": 724, "tag": "NAME", "value": "Joaquin" }, { "context": "Arturo\", \"Alberto Manuel\", \"Rogelio\", \"Joaquin\", \"Angel Antonio\", \"Heriberto\", \"Maria de Lourdes\", \"Roberto\", \"Ru", "end": 748, "score": 0.9998595118522644, "start": 735, "tag": "NAME", "value": "Angel Antonio" }, { "context": " Manuel\", \"Rogelio\", \"Joaquin\", \"Angel Antonio\", \"Heriberto\", \"Maria de Lourdes\", \"Roberto\", \"Ruben\", \"Jose A", "end": 761, "score": 0.9998638033866882, "start": 752, "tag": "NAME", "value": "Heriberto" }, { "context": "gelio\", \"Joaquin\", \"Angel Antonio\", \"Heriberto\", \"Maria de Lourdes\", \"Roberto\", \"Ruben\", \"Jose Antonio\", \"Cuauhtemoc", "end": 781, "score": 0.9998579025268555, "start": 765, "tag": "NAME", "value": "Maria de Lourdes" }, { "context": "Angel Antonio\", \"Heriberto\", \"Maria de Lourdes\", \"Roberto\", \"Ruben\", \"Jose Antonio\", \"Cuauhtemoc\", \"Juan So", "end": 792, "score": 0.9998382329940796, "start": 785, "tag": "NAME", "value": "Roberto" }, { "context": "io\", \"Heriberto\", \"Maria de Lourdes\", \"Roberto\", \"Ruben\", \"Jose Antonio\", \"Cuauhtemoc\", \"Juan Socorro\", \r", "end": 801, "score": 0.999833345413208, "start": 796, "tag": "NAME", "value": "Ruben" }, { "context": "iberto\", \"Maria de Lourdes\", \"Roberto\", \"Ruben\", \"Jose Antonio\", \"Cuauhtemoc\", \"Juan Socorro\", \r\n ", "end": 817, "score": 0.999854326248169, "start": 805, "tag": "NAME", "value": "Jose Antonio" }, { "context": "de Lourdes\", \"Roberto\", \"Ruben\", \"Jose Antonio\", \"Cuauhtemoc\", \"Juan Socorro\", \r\n \"", "end": 831, "score": 0.9995151162147522, "start": 821, "tag": "NAME", "value": "Cuauhtemoc" }, { "context": "Roberto\", \"Ruben\", \"Jose Antonio\", \"Cuauhtemoc\", \"Juan Socorro\", \r\n \"Jose Hugo\", \"Jai", "end": 847, "score": 0.9998689293861389, "start": 835, "tag": "NAME", "value": "Juan Socorro" }, { "context": "\", \"Juan Socorro\", \r\n \"Jose Hugo\", \"Jaime Jacobo\", \"Lourdes\", \"Andrea\", \"Oscar Ger", "end": 890, "score": 0.9998671412467957, "start": 881, "tag": "NAME", "value": "Jose Hugo" }, { "context": "rro\", \r\n \"Jose Hugo\", \"Jaime Jacobo\", \"Lourdes\", \"Andrea\", \"Oscar Gerardo\", \"Pedro\", ", "end": 906, "score": 0.9998723268508911, "start": 894, "tag": "NAME", "value": "Jaime Jacobo" }, { "context": " \"Jose Hugo\", \"Jaime Jacobo\", \"Lourdes\", \"Andrea\", \"Oscar Gerardo\", \"Pedro\", \"Ana\", \"Cri", "end": 917, "score": 0.9998406767845154, "start": 910, "tag": "NAME", "value": "Lourdes" }, { "context": " \"Jose Hugo\", \"Jaime Jacobo\", \"Lourdes\", \"Andrea\", \"Oscar Gerardo\", \"Pedro\", \"Ana\", \"Cristina\", \"A", "end": 927, "score": 0.9998468160629272, "start": 921, "tag": "NAME", "value": "Andrea" }, { "context": "Jose Hugo\", \"Jaime Jacobo\", \"Lourdes\", \"Andrea\", \"Oscar Gerardo\", \"Pedro\", \"Ana\", \"Cristina\", \"Adrian\"};\r\n\r\n ", "end": 944, "score": 0.999860405921936, "start": 931, "tag": "NAME", "value": "Oscar Gerardo" }, { "context": "e Jacobo\", \"Lourdes\", \"Andrea\", \"Oscar Gerardo\", \"Pedro\", \"Ana\", \"Cristina\", \"Adrian\"};\r\n\r\n Random", "end": 953, "score": 0.9998546838760376, "start": 948, "tag": "NAME", "value": "Pedro" }, { "context": ", \"Lourdes\", \"Andrea\", \"Oscar Gerardo\", \"Pedro\", \"Ana\", \"Cristina\", \"Adrian\"};\r\n\r\n Random nombre", "end": 960, "score": 0.9998185038566589, "start": 957, "tag": "NAME", "value": "Ana" }, { "context": "des\", \"Andrea\", \"Oscar Gerardo\", \"Pedro\", \"Ana\", \"Cristina\", \"Adrian\"};\r\n\r\n Random nombreAlu = new Ra", "end": 972, "score": 0.9998614192008972, "start": 964, "tag": "NAME", "value": "Cristina" }, { "context": "a\", \"Oscar Gerardo\", \"Pedro\", \"Ana\", \"Cristina\", \"Adrian\"};\r\n\r\n Random nombreAlu = new Random();\r\n ", "end": 982, "score": 0.9998231530189514, "start": 976, "tag": "NAME", "value": "Adrian" }, { "context": "eneraApellido(){\r\n String Apellidos [] = {\"Vera Lastra\", \"Aguilar Navarro\", \"Salinas Aguilar\", \"Aguirre ", "end": 1261, "score": 0.9998711347579956, "start": 1250, "tag": "NAME", "value": "Vera Lastra" }, { "context": "{\r\n String Apellidos [] = {\"Vera Lastra\", \"Aguilar Navarro\", \"Salinas Aguilar\", \"Aguirre Cruz\", \"Alberu Gome", "end": 1280, "score": 0.9998815059661865, "start": 1265, "tag": "NAME", "value": "Aguilar Navarro" }, { "context": "pellidos [] = {\"Vera Lastra\", \"Aguilar Navarro\", \"Salinas Aguilar\", \"Aguirre Cruz\", \"Alberu Gomez\", \"Alcantar Curie", "end": 1299, "score": 0.9998750686645508, "start": 1284, "tag": "NAME", "value": "Salinas Aguilar" }, { "context": "a Lastra\", \"Aguilar Navarro\", \"Salinas Aguilar\", \"Aguirre Cruz\", \"Alberu Gomez\", \"Alcantar Curiel\", \"Alcaraz Ver", "end": 1315, "score": 0.999872624874115, "start": 1303, "tag": "NAME", "value": "Aguirre Cruz" }, { "context": "lar Navarro\", \"Salinas Aguilar\", \"Aguirre Cruz\", \"Alberu Gomez\", \"Alcantar Curiel\", \"Alcaraz Verduzco\", \"Alcocer", "end": 1331, "score": 0.9998754858970642, "start": 1319, "tag": "NAME", "value": "Alberu Gomez" }, { "context": "alinas Aguilar\", \"Aguirre Cruz\", \"Alberu Gomez\", \"Alcantar Curiel\", \"Alcaraz Verduzco\", \"Alcocer Varela\", \"Alexande", "end": 1350, "score": 0.9998730421066284, "start": 1335, "tag": "NAME", "value": "Alcantar Curiel" }, { "context": "guirre Cruz\", \"Alberu Gomez\", \"Alcantar Curiel\", \"Alcaraz Verduzco\", \"Alcocer Varela\", \"Alexanderson Rosas\", \"Almeda", "end": 1370, "score": 0.9998735785484314, "start": 1354, "tag": "NAME", "value": "Alcaraz Verduzco" }, { "context": "u Gomez\", \"Alcantar Curiel\", \"Alcaraz Verduzco\", \"Alcocer Varela\", \"Alexanderson Rosas\", \"Almeda Valdes\",\r\n ", "end": 1388, "score": 0.9998615384101868, "start": 1374, "tag": "NAME", "value": "Alcocer Varela" }, { "context": "r Curiel\", \"Alcaraz Verduzco\", \"Alcocer Varela\", \"Alexanderson Rosas\", \"Almeda Valdes\",\r\n \"", "end": 1410, "score": 0.9998674392700195, "start": 1392, "tag": "NAME", "value": "Alexanderson Rosas" }, { "context": "rduzco\", \"Alcocer Varela\", \"Alexanderson Rosas\", \"Almeda Valdes\",\r\n \"Alonson Vanegas\",", "end": 1427, "score": 0.999864399433136, "start": 1414, "tag": "NAME", "value": "Almeda Valdes" }, { "context": "\", \"Almeda Valdes\",\r\n \"Alonson Vanegas\", \"Alpuche Aranda\", \"Barrangan Garcia\", \"Barquera", "end": 1475, "score": 0.9998677372932434, "start": 1460, "tag": "NAME", "value": "Alonson Vanegas" }, { "context": "\r\n \"Alonson Vanegas\", \"Alpuche Aranda\", \"Barrangan Garcia\", \"Barquera Cervera\", \"Barrer", "end": 1493, "score": 0.9998373985290527, "start": 1479, "tag": "NAME", "value": "Alpuche Aranda" }, { "context": " \"Alonson Vanegas\", \"Alpuche Aranda\", \"Barrangan Garcia\", \"Barquera Cervera\", \"Barrera Saldaña\", \"Barrien", "end": 1513, "score": 0.9998593926429749, "start": 1497, "tag": "NAME", "value": "Barrangan Garcia" }, { "context": " Vanegas\", \"Alpuche Aranda\", \"Barrangan Garcia\", \"Barquera Cervera\", \"Barrera Saldaña\", \"Barrientos Melendez\", \"Blan", "end": 1533, "score": 0.999788761138916, "start": 1517, "tag": "NAME", "value": "Barquera Cervera" }, { "context": "Aranda\", \"Barrangan Garcia\", \"Barquera Cervera\", \"Barrera Saldaña\", \"Barrientos Melendez\", \"Blanco Favela\", \"Calder", "end": 1552, "score": 0.9977176189422607, "start": 1537, "tag": "NAME", "value": "Barrera Saldaña" }, { "context": " Garcia\", \"Barquera Cervera\", \"Barrera Saldaña\", \"Barrientos Melendez\", \"Blanco Favela\", \"Calderon Colmenero\", \"Calva M", "end": 1575, "score": 0.9998571872711182, "start": 1556, "tag": "NAME", "value": "Barrientos Melendez" }, { "context": "vera\", \"Barrera Saldaña\", \"Barrientos Melendez\", \"Blanco Favela\", \"Calderon Colmenero\", \"Calva Mercado\",\r\n ", "end": 1592, "score": 0.9997996091842651, "start": 1579, "tag": "NAME", "value": "Blanco Favela" }, { "context": "aldaña\", \"Barrientos Melendez\", \"Blanco Favela\", \"Calderon Colmenero\", \"Calva Mercado\",\r\n \"", "end": 1614, "score": 0.9998709559440613, "start": 1596, "tag": "NAME", "value": "Calderon Colmenero" }, { "context": "elendez\", \"Blanco Favela\", \"Calderon Colmenero\", \"Calva Mercado\",\r\n \"Cardona Perez\", \"", "end": 1631, "score": 0.9995197057723999, "start": 1618, "tag": "NAME", "value": "Calva Mercado" }, { "context": "\", \"Calva Mercado\",\r\n \"Cardona Perez\", \"Carranza Lira\", \"Carrillo Ruiz\", \"Castillo Mar", "end": 1677, "score": 0.9998620748519897, "start": 1664, "tag": "NAME", "value": "Cardona Perez" }, { "context": "\",\r\n \"Cardona Perez\", \"Carranza Lira\", \"Carrillo Ruiz\", \"Castillo Martinez\", \"Chavez N", "end": 1694, "score": 0.9998680353164673, "start": 1681, "tag": "NAME", "value": "Carranza Lira" }, { "context": " \"Cardona Perez\", \"Carranza Lira\", \"Carrillo Ruiz\", \"Castillo Martinez\", \"Chavez Negrete\", \"De La F", "end": 1711, "score": 0.9998698830604553, "start": 1698, "tag": "NAME", "value": "Carrillo Ruiz" }, { "context": "ardona Perez\", \"Carranza Lira\", \"Carrillo Ruiz\", \"Castillo Martinez\", \"Chavez Negrete\", \"De La Fuente Ramirez\", \"Del ", "end": 1732, "score": 0.9998567700386047, "start": 1715, "tag": "NAME", "value": "Castillo Martinez" }, { "context": "nza Lira\", \"Carrillo Ruiz\", \"Castillo Martinez\", \"Chavez Negrete\", \"De La Fuente Ramirez\", \"Del Rio Navarro\", \"Dia", "end": 1750, "score": 0.9998664855957031, "start": 1736, "tag": "NAME", "value": "Chavez Negrete" }, { "context": "lo Ruiz\", \"Castillo Martinez\", \"Chavez Negrete\", \"De La Fuente Ramirez\", \"Del Rio Navarro\", \"Diaz Quiñonez\", \"Dominguez ", "end": 1774, "score": 0.9981614351272583, "start": 1754, "tag": "NAME", "value": "De La Fuente Ramirez" }, { "context": "ete\", \"De La Fuente Ramirez\", \"Del Rio Navarro\", \"Diaz Quiñonez\", \"Dominguez Carrillo\", \"Elizondo Riojas\",\r\n ", "end": 1810, "score": 0.999864935874939, "start": 1797, "tag": "NAME", "value": "Diaz Quiñonez" }, { "context": "te Ramirez\", \"Del Rio Navarro\", \"Diaz Quiñonez\", \"Dominguez Carrillo\", \"Elizondo Riojas\",\r\n ", "end": 1832, "score": 0.9998480081558228, "start": 1814, "tag": "NAME", "value": "Dominguez Carrillo" }, { "context": "Navarro\", \"Diaz Quiñonez\", \"Dominguez Carrillo\", \"Elizondo Riojas\",\r\n \"Escalante Acosta\"", "end": 1851, "score": 0.9997506737709045, "start": 1836, "tag": "NAME", "value": "Elizondo Riojas" }, { "context": " \"Elizondo Riojas\",\r\n \"Escalante Acosta\",\"Eslava Campos\", \"Espinola Zavaleta\", \"Fajardo O", "end": 1900, "score": 0.9997738003730774, "start": 1884, "tag": "NAME", "value": "Escalante Acosta" }, { "context": "\r\n \"Escalante Acosta\",\"Eslava Campos\", \"Espinola Zavaleta\", \"Fajardo Ortiz\", \"Feria Be", "end": 1916, "score": 0.9995468258857727, "start": 1903, "tag": "NAME", "value": "Eslava Campos" }, { "context": " \"Escalante Acosta\",\"Eslava Campos\", \"Espinola Zavaleta\", \"Fajardo Ortiz\", \"Feria Bernal\", \"Flores Rivera", "end": 1937, "score": 0.9998025894165039, "start": 1920, "tag": "NAME", "value": "Espinola Zavaleta" }, { "context": "te Acosta\",\"Eslava Campos\", \"Espinola Zavaleta\", \"Fajardo Ortiz\", \"Feria Bernal\", \"Flores Rivera\", \"Fuente Del Ca", "end": 1954, "score": 0.9998571276664734, "start": 1941, "tag": "NAME", "value": "Fajardo Ortiz" }, { "context": "a Campos\", \"Espinola Zavaleta\", \"Fajardo Ortiz\", \"Feria Bernal\", \"Flores Rivera\", \"Fuente Del Campo\", \"Gomez Per", "end": 1970, "score": 0.9998562932014465, "start": 1958, "tag": "NAME", "value": "Feria Bernal" }, { "context": "nola Zavaleta\", \"Fajardo Ortiz\", \"Feria Bernal\", \"Flores Rivera\", \"Fuente Del Campo\", \"Gomez Perez\", \"Gonzalez Or", "end": 1987, "score": 0.9998170733451843, "start": 1974, "tag": "NAME", "value": "Flores Rivera" }, { "context": "Fajardo Ortiz\", \"Feria Bernal\", \"Flores Rivera\", \"Fuente Del Campo\", \"Gomez Perez\", \"Gonzalez Ortiz\", \"Guadalajara B", "end": 2007, "score": 0.9997743964195251, "start": 1991, "tag": "NAME", "value": "Fuente Del Campo" }, { "context": "ia Bernal\", \"Flores Rivera\", \"Fuente Del Campo\", \"Gomez Perez\", \"Gonzalez Ortiz\", \"Guadalajara Boo\",\r\n ", "end": 2022, "score": 0.999854326248169, "start": 2011, "tag": "NAME", "value": "Gomez Perez" }, { "context": "ores Rivera\", \"Fuente Del Campo\", \"Gomez Perez\", \"Gonzalez Ortiz\", \"Guadalajara Boo\",\r\n ", "end": 2040, "score": 0.9998476505279541, "start": 2026, "tag": "NAME", "value": "Gonzalez Ortiz" }, { "context": "nte Del Campo\", \"Gomez Perez\", \"Gonzalez Ortiz\", \"Guadalajara Boo\",\r\n \"Hernandez Avila\",", "end": 2059, "score": 0.9998512268066406, "start": 2044, "tag": "NAME", "value": "Guadalajara Boo" }, { "context": " \"Guadalajara Boo\",\r\n \"Hernandez Avila\", \"Herrera Abarca\", \"Hinojosa Becerril\", \"Iglesia", "end": 2107, "score": 0.9998504519462585, "start": 2092, "tag": "NAME", "value": "Hernandez Avila" }, { "context": "\r\n \"Hernandez Avila\", \"Herrera Abarca\", \"Hinojosa Becerril\", \"Iglesias Morales\", \"Jimen", "end": 2125, "score": 0.9998586177825928, "start": 2111, "tag": "NAME", "value": "Herrera Abarca" }, { "context": " \"Hernandez Avila\", \"Herrera Abarca\", \"Hinojosa Becerril\", \"Iglesias Morales\", \"Jimenez Ponce\", \"Jung Cook", "end": 2146, "score": 0.9996917247772217, "start": 2129, "tag": "NAME", "value": "Hinojosa Becerril" }, { "context": "z Avila\", \"Herrera Abarca\", \"Hinojosa Becerril\", \"Iglesias Morales\", \"Jimenez Ponce\", \"Jung Cook\", \"Kimura Fujikami\"", "end": 2166, "score": 0.9998462796211243, "start": 2150, "tag": "NAME", "value": "Iglesias Morales" }, { "context": "barca\", \"Hinojosa Becerril\", \"Iglesias Morales\", \"Jimenez Ponce\", \"Jung Cook\", \"Kimura Fujikami\", \"Lara Muñoz\", \"", "end": 2183, "score": 0.9998471140861511, "start": 2170, "tag": "NAME", "value": "Jimenez Ponce" }, { "context": " Becerril\", \"Iglesias Morales\", \"Jimenez Ponce\", \"Jung Cook\", \"Kimura Fujikami\", \"Lara Muñoz\", \"Lemus Bravo\",", "end": 2196, "score": 0.9998574256896973, "start": 2187, "tag": "NAME", "value": "Jung Cook" }, { "context": "Iglesias Morales\", \"Jimenez Ponce\", \"Jung Cook\", \"Kimura Fujikami\", \"Lara Muñoz\", \"Lemus Bravo\", \"Madrazo Navarro\"}", "end": 2215, "score": 0.9998710751533508, "start": 2200, "tag": "NAME", "value": "Kimura Fujikami" }, { "context": "\"Jimenez Ponce\", \"Jung Cook\", \"Kimura Fujikami\", \"Lara Muñoz\", \"Lemus Bravo\", \"Madrazo Navarro\"};\r\n \r\n ", "end": 2229, "score": 0.9998636245727539, "start": 2219, "tag": "NAME", "value": "Lara Muñoz" }, { "context": "\", \"Jung Cook\", \"Kimura Fujikami\", \"Lara Muñoz\", \"Lemus Bravo\", \"Madrazo Navarro\"};\r\n \r\n Random a", "end": 2244, "score": 0.9998404383659363, "start": 2233, "tag": "NAME", "value": "Lemus Bravo" }, { "context": " \"Kimura Fujikami\", \"Lara Muñoz\", \"Lemus Bravo\", \"Madrazo Navarro\"};\r\n \r\n Random apellidoAlu = new Ra", "end": 2263, "score": 0.999865710735321, "start": 2248, "tag": "NAME", "value": "Madrazo Navarro" } ]
null
[]
package poopfinal; import java.util.Random; /** * * @author <NAME> <NAME>, <NAME> */ public class MGNombres { public String generaNombre(){ String Nombres[] = {"<NAME>", "<NAME>", "Laura", "Susana", "Alvaro", "Sara", "<NAME>", "<NAME>", "<NAME>", "Jesus", "<NAME>", "<NAME>", "<NAME>", "Manuel", "Jorge", "Erick", "Paloma", "<NAME>", "Patricia", "Celia", "<NAME>", "<NAME>", "Rafael", "<NAME>", "<NAME>", "Pablo", "Jose", "<NAME>", "<NAME>", "Arturo", "<NAME>", "Rogelio", "Joaquin", "<NAME>", "Heriberto", "<NAME>", "Roberto", "Ruben", "<NAME>", "Cuauhtemoc", "<NAME>", "<NAME>", "<NAME>", "Lourdes", "Andrea", "<NAME>", "Pedro", "Ana", "Cristina", "Adrian"}; Random nombreAlu = new Random(); int nNombre = nombreAlu.nextInt(49-0+1) + 0; String nombre = Nombres[nNombre]; return nombre; } public String generaApellido(){ String Apellidos [] = {"<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "Del Rio Navarro", "<NAME>", "<NAME>", "<NAME>", "<NAME>","<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>"}; Random apellidoAlu = new Random(); int nApellido = apellidoAlu.nextInt(49-0+1) + 0; String apellido = Apellidos[nApellido]; return apellido; } }
1,882
0.595248
0.59122
41
58.560974
78.395203
218
false
false
0
0
0
0
0
0
2.682927
false
false
7
874df8db347bbe766c89a384577c5ebbf9f64534
15,650,860,854,337
339e321927422f35cb2ed933273f2e6fc4318026
/Acme-Newspaper2.0/src/main/java/services/UnderwriteService.java
b31a46fe0a939888d052f459e4d3ac1e25421870
[]
no_license
espisepi/jugandoConAngularJS
https://github.com/espisepi/jugandoConAngularJS
c0969d7b1d38337934b9fa8cf8eebdb16189d9a8
44ad4529361a6c4f4bf5ad81aee135f355923b65
refs/heads/master
2021-06-26T08:49:53.393000
2019-03-04T18:00:39
2019-03-04T18:00:39
135,864,284
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package services; import java.util.ArrayList; import java.util.Calendar; import java.util.Collection; import java.util.GregorianCalendar; import javax.transaction.Transactional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.util.Assert; import org.springframework.validation.BindingResult; import org.springframework.validation.Validator; import repositories.UnderwriteRepository; import domain.CreditCard; import domain.Customer; import domain.Newspaper; import domain.Subscription; import domain.Underwrite; import domain.Volume; @Service @Transactional public class UnderwriteService { @Autowired UnderwriteRepository underwriteRepository; @Autowired VolumeService volumeService; @Autowired CustomerService customerService; @Autowired SubscriptionService subscriptionService; @Autowired NewspaperService newspaperService; @Autowired private Validator validator; public UnderwriteService() { } // Simple CRUD methods ---------------------------------------------------- //CREATE public Underwrite create(final int volumeId) { Underwrite result; Volume volume; volume = this.volumeService.findOne(volumeId); result = new Underwrite(); result.setVolume(volume); return result; } //SAVE public Underwrite save(final Underwrite underwrite) { Customer customerPrincipal; Underwrite result; Subscription subcripcion; Assert.notNull(underwrite); customerPrincipal = this.customerService.findByPrincipal(); Assert.isTrue(!this.volumeService.volumesWithUnderwriteOneCustomer().contains(underwrite.getVolume()), "this subcription al ready exits"); //newspapaer a las que ahi que susbcribirse Collection<Newspaper> newspapersnewsupcription; //Hay que hacer una copia porque si no al realizar la instruccion: newspapersnewsupcription.removeAll(newspapersubcripto); //se elimina del propio volume las newspapers tambien newspapersnewsupcription = new ArrayList<Newspaper>(underwrite.getVolume().getNewspapers()); //newspapaer a las que ya estoy subscrito Collection<Newspaper> newspapersubcripto; newspapersubcripto = this.newspaperService.findNewspapersSubscribedByCustomerId(customerPrincipal.getId()); //DONE subscribirse a un volumen significa subscribirsea todos sus periodicos. newspapersnewsupcription.removeAll(newspapersubcripto); Assert.isTrue(this.checkCreditCard(underwrite.getCreditCard()), "Invalid credit card"); result = this.underwriteRepository.save(underwrite); customerPrincipal.getUnderwrites().add(result); //Me subscribo a los periodicos for (final Newspaper n : newspapersnewsupcription) if (n.isOpen() == false) { subcripcion = this.subscriptionService.create(n.getId()); subcripcion.setCreditCard(underwrite.getCreditCard()); subcripcion.setCustomer(customerPrincipal); this.subscriptionService.reconstruct(subcripcion); this.subscriptionService.save(subcripcion); } return result; } public Underwrite reconstruct(final Underwrite underwrite, final BindingResult binding) { Underwrite result; if (underwrite.getId() == 0) result = underwrite; else { Assert.notNull(null, "a subscription can not be modified"); result = underwrite; } this.validator.validate(result, binding); return result; } public void flush() { this.underwriteRepository.flush(); } //Other method public CreditCard credictcardByVolumenAndCustomer(final int volumeId, final int customerId) { CreditCard resul; resul = this.underwriteRepository.credictcardByVolumenAndCustomer(volumeId, customerId); return resul; } public boolean checkCreditCard(final CreditCard creditCard) { boolean res; Calendar calendar; int actualYear; int actualMonth; res = false; calendar = new GregorianCalendar(); actualYear = calendar.get(Calendar.YEAR); actualMonth = (calendar.get(Calendar.MONTH) + 1); actualYear = actualYear % 100; actualMonth = actualMonth % 100; if (creditCard.getExpirationYear() != null) if (Integer.parseInt(creditCard.getExpirationYear()) > actualYear) res = true; else if (Integer.parseInt(creditCard.getExpirationYear()) == actualYear && Integer.parseInt(creditCard.getExpirationMonth()) > calendar.get(Calendar.MONTH) + 1) res = true; else if (Integer.parseInt(creditCard.getExpirationYear()) == actualYear && Integer.parseInt(creditCard.getExpirationMonth()) == actualMonth) res = false; return res; } }
UTF-8
Java
4,503
java
UnderwriteService.java
Java
[]
null
[]
package services; import java.util.ArrayList; import java.util.Calendar; import java.util.Collection; import java.util.GregorianCalendar; import javax.transaction.Transactional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.util.Assert; import org.springframework.validation.BindingResult; import org.springframework.validation.Validator; import repositories.UnderwriteRepository; import domain.CreditCard; import domain.Customer; import domain.Newspaper; import domain.Subscription; import domain.Underwrite; import domain.Volume; @Service @Transactional public class UnderwriteService { @Autowired UnderwriteRepository underwriteRepository; @Autowired VolumeService volumeService; @Autowired CustomerService customerService; @Autowired SubscriptionService subscriptionService; @Autowired NewspaperService newspaperService; @Autowired private Validator validator; public UnderwriteService() { } // Simple CRUD methods ---------------------------------------------------- //CREATE public Underwrite create(final int volumeId) { Underwrite result; Volume volume; volume = this.volumeService.findOne(volumeId); result = new Underwrite(); result.setVolume(volume); return result; } //SAVE public Underwrite save(final Underwrite underwrite) { Customer customerPrincipal; Underwrite result; Subscription subcripcion; Assert.notNull(underwrite); customerPrincipal = this.customerService.findByPrincipal(); Assert.isTrue(!this.volumeService.volumesWithUnderwriteOneCustomer().contains(underwrite.getVolume()), "this subcription al ready exits"); //newspapaer a las que ahi que susbcribirse Collection<Newspaper> newspapersnewsupcription; //Hay que hacer una copia porque si no al realizar la instruccion: newspapersnewsupcription.removeAll(newspapersubcripto); //se elimina del propio volume las newspapers tambien newspapersnewsupcription = new ArrayList<Newspaper>(underwrite.getVolume().getNewspapers()); //newspapaer a las que ya estoy subscrito Collection<Newspaper> newspapersubcripto; newspapersubcripto = this.newspaperService.findNewspapersSubscribedByCustomerId(customerPrincipal.getId()); //DONE subscribirse a un volumen significa subscribirsea todos sus periodicos. newspapersnewsupcription.removeAll(newspapersubcripto); Assert.isTrue(this.checkCreditCard(underwrite.getCreditCard()), "Invalid credit card"); result = this.underwriteRepository.save(underwrite); customerPrincipal.getUnderwrites().add(result); //Me subscribo a los periodicos for (final Newspaper n : newspapersnewsupcription) if (n.isOpen() == false) { subcripcion = this.subscriptionService.create(n.getId()); subcripcion.setCreditCard(underwrite.getCreditCard()); subcripcion.setCustomer(customerPrincipal); this.subscriptionService.reconstruct(subcripcion); this.subscriptionService.save(subcripcion); } return result; } public Underwrite reconstruct(final Underwrite underwrite, final BindingResult binding) { Underwrite result; if (underwrite.getId() == 0) result = underwrite; else { Assert.notNull(null, "a subscription can not be modified"); result = underwrite; } this.validator.validate(result, binding); return result; } public void flush() { this.underwriteRepository.flush(); } //Other method public CreditCard credictcardByVolumenAndCustomer(final int volumeId, final int customerId) { CreditCard resul; resul = this.underwriteRepository.credictcardByVolumenAndCustomer(volumeId, customerId); return resul; } public boolean checkCreditCard(final CreditCard creditCard) { boolean res; Calendar calendar; int actualYear; int actualMonth; res = false; calendar = new GregorianCalendar(); actualYear = calendar.get(Calendar.YEAR); actualMonth = (calendar.get(Calendar.MONTH) + 1); actualYear = actualYear % 100; actualMonth = actualMonth % 100; if (creditCard.getExpirationYear() != null) if (Integer.parseInt(creditCard.getExpirationYear()) > actualYear) res = true; else if (Integer.parseInt(creditCard.getExpirationYear()) == actualYear && Integer.parseInt(creditCard.getExpirationMonth()) > calendar.get(Calendar.MONTH) + 1) res = true; else if (Integer.parseInt(creditCard.getExpirationYear()) == actualYear && Integer.parseInt(creditCard.getExpirationMonth()) == actualMonth) res = false; return res; } }
4,503
0.771486
0.769487
140
31.157143
30.841362
163
false
false
0
0
0
0
0
0
2.007143
false
false
7
ed7d0d05d9aac32d9e1d8cdc6abd60bde0ec6afd
19,877,108,667,989
0e0ee96c3e96419b2292278f58389b63ffd6900b
/app/src/main/java/com/example/kakicomeets_buy/Kakicomeets_Buy_Activity.java
05ebec29914e1beb6083ec407b2c3c67e6b508f9
[]
no_license
takuya-ux/Kakicomeets_buy
https://github.com/takuya-ux/Kakicomeets_buy
85e5dd201cf8d049d8ed1bcbf7ae5b1f9dc20849
ea1a1188765aa33a38c12cef3679a89626b73909
refs/heads/master
2020-08-15T01:15:09.781000
2019-10-15T17:44:36
2019-10-15T17:44:36
215,258,788
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.kakicomeets_buy; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; public class Kakicomeets_Buy_Activity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.kakicomeets_buy); } }
UTF-8
Java
355
java
Kakicomeets_Buy_Activity.java
Java
[]
null
[]
package com.example.kakicomeets_buy; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; public class Kakicomeets_Buy_Activity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.kakicomeets_buy); } }
355
0.76338
0.76338
14
24.357143
23.490446
65
false
false
0
0
0
0
0
0
0.357143
false
false
7
e68f859df6601166fd21e7beac392242e9fbf5c4
10,995,116,291,188
32fb2c63ef31de8259c1561e154d935f451b803a
/src/main/java/com/beitech/common/dao/impl/CustomerDaoImpl.java
082d3bb2f291bf237d82213abe654457a1477225
[]
no_license
smilena33/ventas
https://github.com/smilena33/ventas
c50414b6c7d8616be8b8d8768d449c2aa7559ae3
50f0812a12604702ed97fb83bf1da184ec0d5611
refs/heads/master
2020-03-22T10:28:34.261000
2017-11-14T16:35:59
2017-11-14T16:35:59
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.beitech.common.dao.impl; import java.util.List; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import com.beitech.common.dao.CustomerDao; import com.beitech.common.model.entities.Customer; /** * Clase encargada del acceso a datos para la tabla CUSTOMER. * * @author pablo.perez * */ @Repository public class CustomerDaoImpl implements CustomerDao { @Autowired private SessionFactory sessionFactory; /* * (non-Javadoc) * * @see com.beitech.common.dao.CustomerDao#consultarPorId(java.lang.Long) */ @SuppressWarnings("unchecked") @Override public List<Customer> consultarPorId(Long customerId) { return sessionFactory.getCurrentSession().getNamedQuery("CUSTOMER.consultarPorId") .setParameter("customerId", customerId).list(); } /* * (non-Javadoc) * * @see com.beitech.common.dao.CustomerDao#listarClientes() */ @SuppressWarnings("unchecked") @Override public List<Customer> listarClientes() { return sessionFactory.getCurrentSession().getNamedQuery("CUSTOMER.findAll").list(); } }
UTF-8
Java
1,146
java
CustomerDaoImpl.java
Java
[ { "context": "eso a datos para la tabla CUSTOMER.\n * \n * @author pablo.perez\n *\n */\n@Repository\npublic class Custome", "end": 390, "score": 0.6537771821022034, "start": 389, "tag": "NAME", "value": "p" }, { "context": "o a datos para la tabla CUSTOMER.\n * \n * @author pablo.perez\n *\n */\n@Repository\npublic class CustomerDaoImpl", "end": 398, "score": 0.7821925282478333, "start": 390, "tag": "USERNAME", "value": "ablo.per" }, { "context": "s para la tabla CUSTOMER.\n * \n * @author pablo.perez\n *\n */\n@Repository\npublic class CustomerDaoImpl i", "end": 400, "score": 0.8160424828529358, "start": 398, "tag": "NAME", "value": "ez" } ]
null
[]
package com.beitech.common.dao.impl; import java.util.List; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import com.beitech.common.dao.CustomerDao; import com.beitech.common.model.entities.Customer; /** * Clase encargada del acceso a datos para la tabla CUSTOMER. * * @author pablo.perez * */ @Repository public class CustomerDaoImpl implements CustomerDao { @Autowired private SessionFactory sessionFactory; /* * (non-Javadoc) * * @see com.beitech.common.dao.CustomerDao#consultarPorId(java.lang.Long) */ @SuppressWarnings("unchecked") @Override public List<Customer> consultarPorId(Long customerId) { return sessionFactory.getCurrentSession().getNamedQuery("CUSTOMER.consultarPorId") .setParameter("customerId", customerId).list(); } /* * (non-Javadoc) * * @see com.beitech.common.dao.CustomerDao#listarClientes() */ @SuppressWarnings("unchecked") @Override public List<Customer> listarClientes() { return sessionFactory.getCurrentSession().getNamedQuery("CUSTOMER.findAll").list(); } }
1,146
0.759162
0.759162
47
23.382978
25.374266
85
false
false
0
0
0
0
0
0
0.829787
false
false
7
0e79fb99686eb2b1af1c7f49c4501ce5ab13e420
10,952,166,647,591
6967e402b349e4387a2e7d40d86e3ded716b9da8
/Game/src/Maths/Circle2D.java
9fafd3c914bcf4c729400cdc8325cbe79ecf98e6
[]
no_license
tariqbroadnax/Project
https://github.com/tariqbroadnax/Project
3f5358634cb1a8c13a0158788291b191dd37c592
be10f1ae226224271b5a29fc6467d581fe0d4cf8
refs/heads/master
2021-01-11T01:04:52.470000
2017-03-06T23:14:11
2017-03-06T23:14:11
70,843,203
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package Maths; import static java.lang.Math.*; import java.awt.geom.Ellipse2D; import java.awt.geom.Point2D; public class Circle2D { @SuppressWarnings("serial") public static class Double extends Ellipse2D.Double { public double radius; public Double() { super(0, 0, 20, 20); radius = 10; } public Double(Circle2D.Double circ) { this(circ.getX(), circ.getY(), circ.radius); } public Double(double x, double y, double radius) { super(x - radius, y - radius, 2 * radius, 2 * radius); this.radius = radius; } public boolean contains(Point2D.Double pt) { return getCenter().distanceSq(pt) < radius * radius; } public double diam() { return 2 * radius; } public Point2D.Double randomPoint() { double angle = 2 * PI * random(), rad = radius * sqrt(random()); return new Point2D.Double( getCenterX() + rad * cos(angle), getCenterY() + rad * sin(angle)); } public Point2D.Double getCenter() { return new Point2D.Double(getCenterX(), getCenterY()); } public void setRadius(double radius) { this.radius = radius; this.setFrame(x, y, 2 * radius, 2 * radius); } public double getRadius() { return radius; } public String toString() { return "[x=" + x + ",y=" + y + ",r=" + radius + "]"; } } }
UTF-8
Java
1,358
java
Circle2D.java
Java
[]
null
[]
package Maths; import static java.lang.Math.*; import java.awt.geom.Ellipse2D; import java.awt.geom.Point2D; public class Circle2D { @SuppressWarnings("serial") public static class Double extends Ellipse2D.Double { public double radius; public Double() { super(0, 0, 20, 20); radius = 10; } public Double(Circle2D.Double circ) { this(circ.getX(), circ.getY(), circ.radius); } public Double(double x, double y, double radius) { super(x - radius, y - radius, 2 * radius, 2 * radius); this.radius = radius; } public boolean contains(Point2D.Double pt) { return getCenter().distanceSq(pt) < radius * radius; } public double diam() { return 2 * radius; } public Point2D.Double randomPoint() { double angle = 2 * PI * random(), rad = radius * sqrt(random()); return new Point2D.Double( getCenterX() + rad * cos(angle), getCenterY() + rad * sin(angle)); } public Point2D.Double getCenter() { return new Point2D.Double(getCenterX(), getCenterY()); } public void setRadius(double radius) { this.radius = radius; this.setFrame(x, y, 2 * radius, 2 * radius); } public double getRadius() { return radius; } public String toString() { return "[x=" + x + ",y=" + y + ",r=" + radius + "]"; } } }
1,358
0.603829
0.586156
76
16.868422
17.362499
57
false
false
0
0
0
0
0
0
2.526316
false
false
7
ea44f6f3559fe97820ff5563ec95166403d1e403
30,880,814,872,741
c07e45a7d42ffdcfb0e64e820933fe0988e2af7f
/src/main/java/com/gkhn/sendingplatform/module/prisontocourt/mapper/CrimInfoMapper.java
516493114a1d71f52e97a564530a8c9b17b8ad7e
[]
no_license
penghaining93/sending-platform
https://github.com/penghaining93/sending-platform
337972129b5e653c04f063ef17d86f60f028a5a3
025379f5085205b6afd69c26aaceb0a77c9e62ab
refs/heads/master
2020-03-12T05:27:28.225000
2018-04-21T10:53:11
2018-04-21T10:53:11
130,433,971
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.gkhn.sendingplatform.module.prisontocourt.mapper; import com.gkhn.sendingplatform.module.prisontocourt.model.CrimInfo; import com.gkhn.sendingplatform.module.prisontocourt.model.CrimInfoKey; public interface CrimInfoMapper { int deleteByPrimaryKey(CrimInfoKey key); int insert(CrimInfo record); int insertSelective(CrimInfo record); CrimInfo selectByPrimaryKey(CrimInfoKey key); int updateByPrimaryKeySelective(CrimInfo record); int updateByPrimaryKey(CrimInfo record); }
UTF-8
Java
514
java
CrimInfoMapper.java
Java
[]
null
[]
package com.gkhn.sendingplatform.module.prisontocourt.mapper; import com.gkhn.sendingplatform.module.prisontocourt.model.CrimInfo; import com.gkhn.sendingplatform.module.prisontocourt.model.CrimInfoKey; public interface CrimInfoMapper { int deleteByPrimaryKey(CrimInfoKey key); int insert(CrimInfo record); int insertSelective(CrimInfo record); CrimInfo selectByPrimaryKey(CrimInfoKey key); int updateByPrimaryKeySelective(CrimInfo record); int updateByPrimaryKey(CrimInfo record); }
514
0.807393
0.807393
18
27.611111
26.394735
71
false
false
0
0
0
0
0
0
0.5
false
false
7
c9d30cd9588849781bb232e15214cc9d085bb132
30,880,814,872,095
d1bd1246f161b77efb418a9c24ee544d59fd1d20
/java/Raptor/src/org/javenstudio/raptor/dfs/protocol/QuotaExceededException.java
ffd8341f875d58a4772b528b041c7ffbc74ff232
[]
no_license
navychen2003/javen
https://github.com/navychen2003/javen
f9a94b2e69443291d4b5c3db5a0fc0d1206d2d4a
a3c2312bc24356b1c58b1664543364bfc80e816d
refs/heads/master
2021-01-20T12:12:46.040000
2015-03-03T06:14:46
2015-03-03T06:14:46
30,912,222
0
1
null
false
2023-03-20T11:55:50
2015-02-17T10:24:28
2015-03-03T06:15:44
2017-05-18T15:33:18
64,024
0
0
0
Java
false
false
package org.javenstudio.raptor.dfs.protocol; import java.io.IOException; /** * This exception is thrown when modification to HDFS results in violation * of a directory quota. A directory quota might be namespace quota (limit * on number of files and directories) or a diskspace quota (limit on space * taken by all the file under the directory tree). <br> <br> * * The message for the exception specifies the directory where the quota * was violated and actual quotas. Specific message is generated in the * corresponding Exception class: * DSQuotaExceededException or * NSQuotaExceededException */ public class QuotaExceededException extends IOException { protected static final long serialVersionUID = 1L; protected String pathName=null; protected long quota; // quota protected long count; // actual value protected QuotaExceededException(String msg) { super(msg); } protected QuotaExceededException(long quota, long count) { this.quota = quota; this.count = count; } public void setPathName(String path) { this.pathName = path; } public String getMessage() { return super.getMessage(); } }
UTF-8
Java
1,172
java
QuotaExceededException.java
Java
[]
null
[]
package org.javenstudio.raptor.dfs.protocol; import java.io.IOException; /** * This exception is thrown when modification to HDFS results in violation * of a directory quota. A directory quota might be namespace quota (limit * on number of files and directories) or a diskspace quota (limit on space * taken by all the file under the directory tree). <br> <br> * * The message for the exception specifies the directory where the quota * was violated and actual quotas. Specific message is generated in the * corresponding Exception class: * DSQuotaExceededException or * NSQuotaExceededException */ public class QuotaExceededException extends IOException { protected static final long serialVersionUID = 1L; protected String pathName=null; protected long quota; // quota protected long count; // actual value protected QuotaExceededException(String msg) { super(msg); } protected QuotaExceededException(long quota, long count) { this.quota = quota; this.count = count; } public void setPathName(String path) { this.pathName = path; } public String getMessage() { return super.getMessage(); } }
1,172
0.733788
0.732935
39
29.02564
25.09519
76
false
false
0
0
0
0
0
0
0.307692
false
false
7
cb7d5be07d521bb5c6f9affdac0ec1fa7c01a125
11,055,245,847,857
03ae816aeccd7ffadb586c1af57f49afa53c4da2
/10.13 homework/src/ex6_22.java
04ae414401338e9d61d8144e1ad49072be2903d6
[]
no_license
sique0725/CBNU-JAVA
https://github.com/sique0725/CBNU-JAVA
e56364cffc616034b6b4d9f976fb3f9214264770
22c922a480975acfbdbef01f57a964b100b99301
refs/heads/master
2021-03-19T14:00:47.949000
2017-11-10T07:13:57
2017-11-10T07:13:57
104,442,009
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
public class ex6_22 { }
UTF-8
Java
30
java
ex6_22.java
Java
[]
null
[]
public class ex6_22 { }
30
0.533333
0.433333
3
7.333333
9.672412
21
false
false
0
0
0
0
0
0
0
false
false
7
0c0480e856d7de85d90fa8ee4ee938ea9e2a949a
15,178,414,443,001
40a0c48abb3a09d6cd7c924eadda90cb38981884
/src/cleanarc/Persistencia/Direccion.java
3f9b0ba294837e61d9242d947c38827b6c4792dc
[]
no_license
israv87/FoodCare
https://github.com/israv87/FoodCare
cfb2c4b0f997f1a9d889c3f8faafe72a0639cddb
e65be596fb6ddc25d2d8fe9b3d63f980b3526aec
refs/heads/master
2023-05-07T07:00:17.022000
2021-05-25T16:39:44
2021-05-25T16:39:44
331,468,528
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package cleanarc.persistencia; import java.io.Serializable; import javax.persistence.Basic; 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.ManyToOne; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.Table; import javax.xml.bind.annotation.XmlRootElement; /** * * @author halo_ */ @Entity @Table(name = "direccion") @XmlRootElement @NamedQueries({ @NamedQuery(name = "Direccion.findAll", query = "SELECT d FROM Direccion d"), @NamedQuery(name = "Direccion.findByIdDireccion", query = "SELECT d FROM Direccion d WHERE d.idDireccion = :idDireccion"), @NamedQuery(name = "Direccion.findBySector", query = "SELECT d FROM Direccion d WHERE d.sector = :sector"), @NamedQuery(name = "Direccion.findByBarrio", query = "SELECT d FROM Direccion d WHERE d.barrio = :barrio"), @NamedQuery(name = "Direccion.findByCalleP", query = "SELECT d FROM Direccion d WHERE d.calleP = :calleP"), @NamedQuery(name = "Direccion.findByCalleS", query = "SELECT d FROM Direccion d WHERE d.calleS = :calleS"), @NamedQuery(name = "Direccion.findByReferencia", query = "SELECT d FROM Direccion d WHERE d.referencia = :referencia")}) public class Direccion implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Basic(optional = false) @Column(name = "idDireccion") private Integer idDireccion; @Column(name = "sector") private String sector; @Column(name = "barrio") private String barrio; @Column(name = "calleP") private String calleP; @Column(name = "calleS") private String calleS; @Column(name = "referencia") private String referencia; @JoinColumn(name = "idBeneficiario", referencedColumnName = "idBeneficiario") @ManyToOne(optional = false) private Beneficiario idBeneficiario; public Direccion() { } public Direccion(Integer idDireccion) { this.idDireccion = idDireccion; } public Integer getIdDireccion() { return idDireccion; } public void setIdDireccion(Integer idDireccion) { this.idDireccion = idDireccion; } public String getSector() { return sector; } public void setSector(String sector) { this.sector = sector; } public String getBarrio() { return barrio; } public void setBarrio(String barrio) { this.barrio = barrio; } public String getCalleP() { return calleP; } public void setCalleP(String calleP) { this.calleP = calleP; } public String getCalleS() { return calleS; } public void setCalleS(String calleS) { this.calleS = calleS; } public String getReferencia() { return referencia; } public void setReferencia(String referencia) { this.referencia = referencia; } public Beneficiario getIdBeneficiario() { return idBeneficiario; } public void setIdBeneficiario(Beneficiario idBeneficiario) { this.idBeneficiario = idBeneficiario; } @Override public int hashCode() { int hash = 0; hash += (idDireccion != null ? idDireccion.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof Direccion)) { return false; } Direccion other = (Direccion) object; if ((this.idDireccion == null && other.idDireccion != null) || (this.idDireccion != null && !this.idDireccion.equals(other.idDireccion))) { return false; } return true; } @Override public String toString() { return "cleanarc.persistencia.Direccion[ idDireccion=" + idDireccion + " ]"; } }
UTF-8
Java
4,292
java
Direccion.java
Java
[ { "context": "bind.annotation.XmlRootElement;\n\n/**\n *\n * @author halo_\n */\n@Entity\n@Table(name = \"direccion\")\n@XmlRootEl", "end": 709, "score": 0.9996055960655212, "start": 704, "tag": "USERNAME", "value": "halo_" } ]
null
[]
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package cleanarc.persistencia; import java.io.Serializable; import javax.persistence.Basic; 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.ManyToOne; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.Table; import javax.xml.bind.annotation.XmlRootElement; /** * * @author halo_ */ @Entity @Table(name = "direccion") @XmlRootElement @NamedQueries({ @NamedQuery(name = "Direccion.findAll", query = "SELECT d FROM Direccion d"), @NamedQuery(name = "Direccion.findByIdDireccion", query = "SELECT d FROM Direccion d WHERE d.idDireccion = :idDireccion"), @NamedQuery(name = "Direccion.findBySector", query = "SELECT d FROM Direccion d WHERE d.sector = :sector"), @NamedQuery(name = "Direccion.findByBarrio", query = "SELECT d FROM Direccion d WHERE d.barrio = :barrio"), @NamedQuery(name = "Direccion.findByCalleP", query = "SELECT d FROM Direccion d WHERE d.calleP = :calleP"), @NamedQuery(name = "Direccion.findByCalleS", query = "SELECT d FROM Direccion d WHERE d.calleS = :calleS"), @NamedQuery(name = "Direccion.findByReferencia", query = "SELECT d FROM Direccion d WHERE d.referencia = :referencia")}) public class Direccion implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Basic(optional = false) @Column(name = "idDireccion") private Integer idDireccion; @Column(name = "sector") private String sector; @Column(name = "barrio") private String barrio; @Column(name = "calleP") private String calleP; @Column(name = "calleS") private String calleS; @Column(name = "referencia") private String referencia; @JoinColumn(name = "idBeneficiario", referencedColumnName = "idBeneficiario") @ManyToOne(optional = false) private Beneficiario idBeneficiario; public Direccion() { } public Direccion(Integer idDireccion) { this.idDireccion = idDireccion; } public Integer getIdDireccion() { return idDireccion; } public void setIdDireccion(Integer idDireccion) { this.idDireccion = idDireccion; } public String getSector() { return sector; } public void setSector(String sector) { this.sector = sector; } public String getBarrio() { return barrio; } public void setBarrio(String barrio) { this.barrio = barrio; } public String getCalleP() { return calleP; } public void setCalleP(String calleP) { this.calleP = calleP; } public String getCalleS() { return calleS; } public void setCalleS(String calleS) { this.calleS = calleS; } public String getReferencia() { return referencia; } public void setReferencia(String referencia) { this.referencia = referencia; } public Beneficiario getIdBeneficiario() { return idBeneficiario; } public void setIdBeneficiario(Beneficiario idBeneficiario) { this.idBeneficiario = idBeneficiario; } @Override public int hashCode() { int hash = 0; hash += (idDireccion != null ? idDireccion.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof Direccion)) { return false; } Direccion other = (Direccion) object; if ((this.idDireccion == null && other.idDireccion != null) || (this.idDireccion != null && !this.idDireccion.equals(other.idDireccion))) { return false; } return true; } @Override public String toString() { return "cleanarc.persistencia.Direccion[ idDireccion=" + idDireccion + " ]"; } }
4,292
0.669385
0.668686
147
28.197279
28.694412
147
false
false
0
0
0
0
0
0
0.435374
false
false
7
714fcf7b08bdbf4fcaa0fea2d91dfbf18fbbb52d
19,765,439,545,593
3954def560b971ff35c36e18056be2424e2e5b6e
/src/cz/siret/knn/pivot/FeatureWithPartitionBase.java
9ce3cb1c55f248bb3794f288f97a43f813d7824d
[ "MIT" ]
permissive
PremyslCech/kNN-joins-spark
https://github.com/PremyslCech/kNN-joins-spark
c32816ea0ce5aaba39cd8350a3218f01ecc8f208
2b04d24cdeea62d5cb41cdfba1e113787ff4a1e2
refs/heads/master
2021-05-14T11:12:22.554000
2018-07-25T09:00:40
2018-07-25T09:00:40
116,374,257
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package cz.siret.knn.pivot; import cz.siret.knn.model.Feature; @SuppressWarnings("serial") public abstract class FeatureWithPartitionBase implements IFeatureWithPartition { private final Feature feature; private final float distanceToPivot; private final boolean isDatabase; // is a query otherwise private final float[] distancesToStaticPivots; public FeatureWithPartitionBase(Feature feature, float distanceToPivot, boolean isDatabase, float[] distancesToStaticPivots) { this.feature = feature; this.distanceToPivot = distanceToPivot; this.isDatabase = isDatabase; this.distancesToStaticPivots = distancesToStaticPivots; } @Override public Feature getFeature() { return feature; } @Override public boolean isDatabase() { return isDatabase; } @Override public float getDistanceToPivot() { return distanceToPivot; } @Override public float[] getDistancesToStaticPivots() { return distancesToStaticPivots; } }
UTF-8
Java
950
java
FeatureWithPartitionBase.java
Java
[]
null
[]
package cz.siret.knn.pivot; import cz.siret.knn.model.Feature; @SuppressWarnings("serial") public abstract class FeatureWithPartitionBase implements IFeatureWithPartition { private final Feature feature; private final float distanceToPivot; private final boolean isDatabase; // is a query otherwise private final float[] distancesToStaticPivots; public FeatureWithPartitionBase(Feature feature, float distanceToPivot, boolean isDatabase, float[] distancesToStaticPivots) { this.feature = feature; this.distanceToPivot = distanceToPivot; this.isDatabase = isDatabase; this.distancesToStaticPivots = distancesToStaticPivots; } @Override public Feature getFeature() { return feature; } @Override public boolean isDatabase() { return isDatabase; } @Override public float getDistanceToPivot() { return distanceToPivot; } @Override public float[] getDistancesToStaticPivots() { return distancesToStaticPivots; } }
950
0.787368
0.787368
39
23.358974
26.056631
127
false
false
0
0
0
0
0
0
1.307692
false
false
7
4ba5d4a3b708f1ffdece0673e784023d879a6061
11,802,570,141,115
e80cb4531f8a4caeae1d25761bdc42cb660ac6c5
/jsaga-engine/src/fr/in2p3/jsaga/impl/namespace/AbstractAsyncNSDirectoryImpl.java
b89e292b149ed4a0600ff7333cf0f1fde263ce1c
[]
no_license
ccin2p3/jsaga
https://github.com/ccin2p3/jsaga
67cfbc8f00a4ff8336ec1c977caffdc60108e0cf
040e268f1a80cb44a4cf449a694b33ac415eac3d
refs/heads/master
2021-01-20T17:12:30.074000
2017-04-25T11:13:18
2017-04-25T11:13:18
62,138,791
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package fr.in2p3.jsaga.impl.namespace; import fr.in2p3.jsaga.adaptor.data.DataAdaptor; import fr.in2p3.jsaga.impl.file.AbstractSyncDirectoryImpl; import fr.in2p3.jsaga.impl.file.copy.AbstractCopyTask; import fr.in2p3.jsaga.impl.task.AbstractThreadedTask; import org.ogf.saga.error.*; import org.ogf.saga.namespace.Flags; import org.ogf.saga.namespace.NSDirectory; import org.ogf.saga.namespace.NSEntry; import org.ogf.saga.session.Session; import org.ogf.saga.task.Task; import org.ogf.saga.task.TaskMode; import org.ogf.saga.url.URL; import java.util.List; /* *************************************************** * *** Centre de Calcul de l'IN2P3 - Lyon (France) *** * *** http://cc.in2p3.fr/ *** * *************************************************** * File: AbstractAsyncNSDirectoryImpl * Author: Sylvain Reynaud (sreynaud@in2p3.fr) * Date: 17 sept. 2007 * *************************************************** * Description: */ /** * */ public abstract class AbstractAsyncNSDirectoryImpl extends AbstractSyncNSDirectoryImpl implements NSDirectory { /** constructor for factory */ protected AbstractAsyncNSDirectoryImpl(Session session, URL url, DataAdaptor adaptor, int flags) throws NotImplementedException, IncorrectURLException, AuthenticationFailedException, AuthorizationFailedException, PermissionDeniedException, BadParameterException, AlreadyExistsException, DoesNotExistException, TimeoutException, NoSuccessException { super(session, url, adaptor, flags); } /** constructor for NSDirectory.open() */ protected AbstractAsyncNSDirectoryImpl(AbstractNSDirectoryImpl dir, URL relativeUrl, int flags) throws NotImplementedException, IncorrectURLException, AuthenticationFailedException, AuthorizationFailedException, PermissionDeniedException, BadParameterException, AlreadyExistsException, DoesNotExistException, TimeoutException, NoSuccessException { super(dir, relativeUrl, flags); } /** constructor for NSEntry.openAbsolute() */ protected AbstractAsyncNSDirectoryImpl(AbstractNSEntryImpl entry, String absolutePath, int flags) throws NotImplementedException, IncorrectURLException, AuthenticationFailedException, AuthorizationFailedException, PermissionDeniedException, BadParameterException, AlreadyExistsException, DoesNotExistException, TimeoutException, NoSuccessException { super(entry, absolutePath, flags); } ////////////////////////////////////////// interface NSDirectory ////////////////////////////////////////// public Task<NSDirectory, Void> changeDir(TaskMode mode, final URL dir) throws NotImplementedException { return new AbstractThreadedTask<NSDirectory,Void>(mode) { public Void invoke() throws NotImplementedException, IncorrectURLException, AuthenticationFailedException, AuthorizationFailedException, PermissionDeniedException, BadParameterException, IncorrectStateException, AlreadyExistsException, DoesNotExistException, TimeoutException, NoSuccessException { AbstractAsyncNSDirectoryImpl.super.changeDirSync(dir); return null; } }; } public Task<NSDirectory, List<URL>> list(TaskMode mode, final String pattern, final int flags) throws NotImplementedException { return new AbstractThreadedTask<NSDirectory,List<URL>>(mode) { public List<URL> invoke() throws NotImplementedException, IncorrectURLException, AuthenticationFailedException, AuthorizationFailedException, PermissionDeniedException, BadParameterException, IncorrectStateException, AlreadyExistsException, DoesNotExistException, TimeoutException, NoSuccessException { return AbstractAsyncNSDirectoryImpl.super.listSync(pattern, flags); } }; } public Task<NSDirectory, List<URL>> list(TaskMode mode, final String pattern) throws NotImplementedException { return new AbstractThreadedTask<NSDirectory,List<URL>>(mode) { public List<URL> invoke() throws NotImplementedException, IncorrectURLException, AuthenticationFailedException, AuthorizationFailedException, PermissionDeniedException, BadParameterException, IncorrectStateException, AlreadyExistsException, DoesNotExistException, TimeoutException, NoSuccessException { return AbstractAsyncNSDirectoryImpl.super.listSync(pattern); } }; } public Task<NSDirectory, List<URL>> list(TaskMode mode, final int flags) throws NotImplementedException { return new AbstractThreadedTask<NSDirectory,List<URL>>(mode) { public List<URL> invoke() throws NotImplementedException, IncorrectURLException, AuthenticationFailedException, AuthorizationFailedException, PermissionDeniedException, BadParameterException, IncorrectStateException, AlreadyExistsException, DoesNotExistException, TimeoutException, NoSuccessException { return AbstractAsyncNSDirectoryImpl.super.listSync(flags); } }; } public Task<NSDirectory, List<URL>> list(TaskMode mode) throws NotImplementedException { return new AbstractThreadedTask<NSDirectory,List<URL>>(mode) { public List<URL> invoke() throws NotImplementedException, IncorrectURLException, AuthenticationFailedException, AuthorizationFailedException, PermissionDeniedException, BadParameterException, IncorrectStateException, AlreadyExistsException, DoesNotExistException, TimeoutException, NoSuccessException { return AbstractAsyncNSDirectoryImpl.super.listSync(); } }; } public Task<NSDirectory, List<URL>> find(TaskMode mode, final String pattern, final int flags) throws NotImplementedException { return new AbstractThreadedTask<NSDirectory,List<URL>>(mode) { public List<URL> invoke() throws NotImplementedException, IncorrectURLException, AuthenticationFailedException, AuthorizationFailedException, PermissionDeniedException, BadParameterException, IncorrectStateException, AlreadyExistsException, DoesNotExistException, TimeoutException, NoSuccessException { return AbstractAsyncNSDirectoryImpl.super.findSync(pattern, flags); } }; } public Task<NSDirectory, List<URL>> find(TaskMode mode, final String pattern) throws NotImplementedException { return new AbstractThreadedTask<NSDirectory,List<URL>>(mode) { public List<URL> invoke() throws NotImplementedException, IncorrectURLException, AuthenticationFailedException, AuthorizationFailedException, PermissionDeniedException, BadParameterException, IncorrectStateException, AlreadyExistsException, DoesNotExistException, TimeoutException, NoSuccessException { return AbstractAsyncNSDirectoryImpl.super.findSync(pattern); } }; } public Task<NSDirectory, Boolean> exists(TaskMode mode, final URL name) throws NotImplementedException { return new AbstractThreadedTask<NSDirectory,Boolean>(mode) { public Boolean invoke() throws NotImplementedException, IncorrectURLException, AuthenticationFailedException, AuthorizationFailedException, PermissionDeniedException, BadParameterException, IncorrectStateException, AlreadyExistsException, DoesNotExistException, TimeoutException, NoSuccessException { return AbstractAsyncNSDirectoryImpl.super.existsSync(name); } }; } public Task<NSDirectory, Boolean> isDir(TaskMode mode, final URL name) throws NotImplementedException { return new AbstractThreadedTask<NSDirectory,Boolean>(mode) { public Boolean invoke() throws NotImplementedException, IncorrectURLException, AuthenticationFailedException, AuthorizationFailedException, PermissionDeniedException, BadParameterException, IncorrectStateException, AlreadyExistsException, DoesNotExistException, TimeoutException, NoSuccessException { return AbstractAsyncNSDirectoryImpl.super.isDirSync(name); } }; } public Task<NSDirectory, Boolean> isEntry(TaskMode mode, final URL name) throws NotImplementedException { return new AbstractThreadedTask<NSDirectory,Boolean>(mode) { public Boolean invoke() throws NotImplementedException, IncorrectURLException, AuthenticationFailedException, AuthorizationFailedException, PermissionDeniedException, BadParameterException, IncorrectStateException, AlreadyExistsException, DoesNotExistException, TimeoutException, NoSuccessException { return AbstractAsyncNSDirectoryImpl.super.isEntrySync(name); } }; } public Task<NSDirectory, Boolean> isLink(TaskMode mode, final URL name) throws NotImplementedException { return new AbstractThreadedTask<NSDirectory,Boolean>(mode) { public Boolean invoke() throws NotImplementedException, IncorrectURLException, AuthenticationFailedException, AuthorizationFailedException, PermissionDeniedException, BadParameterException, IncorrectStateException, AlreadyExistsException, DoesNotExistException, TimeoutException, NoSuccessException { return AbstractAsyncNSDirectoryImpl.super.isLinkSync(name); } }; } public Task<NSDirectory, Long> getMTime(TaskMode mode, final URL name) throws NotImplementedException { return new AbstractThreadedTask<NSDirectory,Long>(mode) { public Long invoke() throws NotImplementedException, IncorrectURLException, AuthenticationFailedException, AuthorizationFailedException, PermissionDeniedException, BadParameterException, IncorrectStateException, AlreadyExistsException, DoesNotExistException, TimeoutException, NoSuccessException { return AbstractAsyncNSDirectoryImpl.super.getMTimeSync(name); } }; } public Task<NSDirectory, URL> readLink(TaskMode mode, final URL name) throws NotImplementedException { return new AbstractThreadedTask<NSDirectory,URL>(mode) { public URL invoke() throws NotImplementedException, IncorrectURLException, AuthenticationFailedException, AuthorizationFailedException, PermissionDeniedException, BadParameterException, IncorrectStateException, AlreadyExistsException, DoesNotExistException, TimeoutException, NoSuccessException { return AbstractAsyncNSDirectoryImpl.super.readLinkSync(name); } }; } public Task<NSDirectory, Integer> getNumEntries(TaskMode mode) throws NotImplementedException { return new AbstractThreadedTask<NSDirectory,Integer>(mode) { public Integer invoke() throws NotImplementedException, IncorrectURLException, AuthenticationFailedException, AuthorizationFailedException, PermissionDeniedException, BadParameterException, IncorrectStateException, AlreadyExistsException, DoesNotExistException, TimeoutException, NoSuccessException { return AbstractAsyncNSDirectoryImpl.super.getNumEntriesSync(); } }; } public Task<NSDirectory, URL> getEntry(TaskMode mode, final int entry) throws NotImplementedException { return new AbstractThreadedTask<NSDirectory,URL>(mode) { public URL invoke() throws NotImplementedException, IncorrectURLException, AuthenticationFailedException, AuthorizationFailedException, PermissionDeniedException, BadParameterException, IncorrectStateException, AlreadyExistsException, DoesNotExistException, TimeoutException, NoSuccessException { return AbstractAsyncNSDirectoryImpl.super.getEntrySync(entry); } }; } public Task<NSDirectory, Void> copy(TaskMode mode, final URL source, final URL target, final int flags) throws NotImplementedException { return new AbstractThreadedTask<NSDirectory,Void>(mode) { public Void invoke() throws NotImplementedException, IncorrectURLException, AuthenticationFailedException, AuthorizationFailedException, PermissionDeniedException, BadParameterException, IncorrectStateException, AlreadyExistsException, DoesNotExistException, TimeoutException, NoSuccessException { AbstractAsyncNSDirectoryImpl.super.copySync(source, target, flags); return null; } }; } public Task<NSDirectory, Void> copy(TaskMode mode, final URL source, final URL target) throws NotImplementedException { return new AbstractThreadedTask<NSDirectory,Void>(mode) { public Void invoke() throws NotImplementedException, IncorrectURLException, AuthenticationFailedException, AuthorizationFailedException, PermissionDeniedException, BadParameterException, IncorrectStateException, AlreadyExistsException, DoesNotExistException, TimeoutException, NoSuccessException { AbstractAsyncNSDirectoryImpl.super.copySync(source, target); return null; } }; } public Task<NSDirectory, Void> copy(TaskMode mode, final String sourcePattern, final URL target, final int flags) throws NotImplementedException { return new AbstractThreadedTask<NSDirectory,Void>(mode) { public Void invoke() throws NotImplementedException, IncorrectURLException, AuthenticationFailedException, AuthorizationFailedException, PermissionDeniedException, BadParameterException, IncorrectStateException, AlreadyExistsException, DoesNotExistException, TimeoutException, NoSuccessException { AbstractAsyncNSDirectoryImpl.super.copySync(sourcePattern, target, flags); return null; } }; } public Task<NSDirectory, Void> copy(TaskMode mode, final String sourcePattern, final URL target) throws NotImplementedException { return new AbstractThreadedTask<NSDirectory,Void>(mode) { public Void invoke() throws NotImplementedException, IncorrectURLException, AuthenticationFailedException, AuthorizationFailedException, PermissionDeniedException, BadParameterException, IncorrectStateException, AlreadyExistsException, DoesNotExistException, TimeoutException, NoSuccessException { AbstractAsyncNSDirectoryImpl.super.copySync(sourcePattern, target); return null; } }; } public Task<NSDirectory, Void> link(TaskMode mode, final URL source, final URL target, final int flags) throws NotImplementedException { return new AbstractThreadedTask<NSDirectory,Void>(mode) { public Void invoke() throws NotImplementedException, IncorrectURLException, AuthenticationFailedException, AuthorizationFailedException, PermissionDeniedException, BadParameterException, IncorrectStateException, AlreadyExistsException, DoesNotExistException, TimeoutException, NoSuccessException { AbstractAsyncNSDirectoryImpl.super.linkSync(source, target, flags); return null; } }; } public Task<NSDirectory, Void> link(TaskMode mode, final URL source, final URL target) throws NotImplementedException { return new AbstractThreadedTask<NSDirectory,Void>(mode) { public Void invoke() throws NotImplementedException, IncorrectURLException, AuthenticationFailedException, AuthorizationFailedException, PermissionDeniedException, BadParameterException, IncorrectStateException, AlreadyExistsException, DoesNotExistException, TimeoutException, NoSuccessException { AbstractAsyncNSDirectoryImpl.super.linkSync(source, target); return null; } }; } public Task<NSDirectory, Void> link(TaskMode mode, final String sourcePattern, final URL target, final int flags) throws NotImplementedException { return new AbstractThreadedTask<NSDirectory,Void>(mode) { public Void invoke() throws NotImplementedException, IncorrectURLException, AuthenticationFailedException, AuthorizationFailedException, PermissionDeniedException, BadParameterException, IncorrectStateException, AlreadyExistsException, DoesNotExistException, TimeoutException, NoSuccessException { AbstractAsyncNSDirectoryImpl.super.linkSync(sourcePattern, target, flags); return null; } }; } public Task<NSDirectory, Void> link(TaskMode mode, final String sourcePattern, final URL target) throws NotImplementedException { return new AbstractThreadedTask<NSDirectory,Void>(mode) { public Void invoke() throws NotImplementedException, IncorrectURLException, AuthenticationFailedException, AuthorizationFailedException, PermissionDeniedException, BadParameterException, IncorrectStateException, AlreadyExistsException, DoesNotExistException, TimeoutException, NoSuccessException { AbstractAsyncNSDirectoryImpl.super.linkSync(sourcePattern, target); return null; } }; } public Task<NSDirectory, Void> move(TaskMode mode, final URL source, final URL target, final int flags) throws NotImplementedException { return new AbstractThreadedTask<NSDirectory,Void>(mode) { public Void invoke() throws NotImplementedException, IncorrectURLException, AuthenticationFailedException, AuthorizationFailedException, PermissionDeniedException, BadParameterException, IncorrectStateException, AlreadyExistsException, DoesNotExistException, TimeoutException, NoSuccessException { AbstractAsyncNSDirectoryImpl.super.moveSync(source, target, flags); return null; } }; } public Task<NSDirectory, Void> move(TaskMode mode, final URL source, final URL target) throws NotImplementedException { return new AbstractThreadedTask<NSDirectory,Void>(mode) { public Void invoke() throws NotImplementedException, IncorrectURLException, AuthenticationFailedException, AuthorizationFailedException, PermissionDeniedException, BadParameterException, IncorrectStateException, AlreadyExistsException, DoesNotExistException, TimeoutException, NoSuccessException { AbstractAsyncNSDirectoryImpl.super.moveSync(source, target); return null; } }; } public Task<NSDirectory, Void> move(TaskMode mode, final String sourcePattern, final URL target, final int flags) throws NotImplementedException { return new AbstractThreadedTask<NSDirectory,Void>(mode) { public Void invoke() throws NotImplementedException, IncorrectURLException, AuthenticationFailedException, AuthorizationFailedException, PermissionDeniedException, BadParameterException, IncorrectStateException, AlreadyExistsException, DoesNotExistException, TimeoutException, NoSuccessException { AbstractAsyncNSDirectoryImpl.super.moveSync(sourcePattern, target, flags); return null; } }; } public Task<NSDirectory, Void> move(TaskMode mode, final String sourcePattern, final URL target) throws NotImplementedException { return new AbstractThreadedTask<NSDirectory,Void>(mode) { public Void invoke() throws NotImplementedException, IncorrectURLException, AuthenticationFailedException, AuthorizationFailedException, PermissionDeniedException, BadParameterException, IncorrectStateException, AlreadyExistsException, DoesNotExistException, TimeoutException, NoSuccessException { AbstractAsyncNSDirectoryImpl.super.moveSync(sourcePattern, target); return null; } }; } public Task<NSDirectory, Void> remove(TaskMode mode, final URL target, final int flags) throws NotImplementedException { return new AbstractThreadedTask<NSDirectory,Void>(mode) { public Void invoke() throws NotImplementedException, IncorrectURLException, AuthenticationFailedException, AuthorizationFailedException, PermissionDeniedException, BadParameterException, IncorrectStateException, AlreadyExistsException, DoesNotExistException, TimeoutException, NoSuccessException { AbstractAsyncNSDirectoryImpl.super.removeSync(target, flags); return null; } }; } public Task<NSDirectory, Void> remove(TaskMode mode, final URL target) throws NotImplementedException { return new AbstractThreadedTask<NSDirectory,Void>(mode) { public Void invoke() throws NotImplementedException, IncorrectURLException, AuthenticationFailedException, AuthorizationFailedException, PermissionDeniedException, BadParameterException, IncorrectStateException, AlreadyExistsException, DoesNotExistException, TimeoutException, NoSuccessException { AbstractAsyncNSDirectoryImpl.super.removeSync(target); return null; } }; } public Task<NSDirectory, Void> remove(TaskMode mode, final String targetPattern, final int flags) throws NotImplementedException { return new AbstractThreadedTask<NSDirectory,Void>(mode) { public Void invoke() throws NotImplementedException, IncorrectURLException, AuthenticationFailedException, AuthorizationFailedException, PermissionDeniedException, BadParameterException, IncorrectStateException, AlreadyExistsException, DoesNotExistException, TimeoutException, NoSuccessException { AbstractAsyncNSDirectoryImpl.super.removeSync(targetPattern, flags); return null; } }; } public Task<NSDirectory, Void> remove(TaskMode mode, final String targetPattern) throws NotImplementedException { return new AbstractThreadedTask<NSDirectory,Void>(mode) { public Void invoke() throws NotImplementedException, IncorrectURLException, AuthenticationFailedException, AuthorizationFailedException, PermissionDeniedException, BadParameterException, IncorrectStateException, AlreadyExistsException, DoesNotExistException, TimeoutException, NoSuccessException { AbstractAsyncNSDirectoryImpl.super.removeSync(targetPattern); return null; } }; } public Task<NSDirectory, Void> makeDir(TaskMode mode, final URL target, final int flags) throws NotImplementedException { return new AbstractThreadedTask<NSDirectory,Void>(mode) { public Void invoke() throws NotImplementedException, IncorrectURLException, AuthenticationFailedException, AuthorizationFailedException, PermissionDeniedException, BadParameterException, IncorrectStateException, AlreadyExistsException, DoesNotExistException, TimeoutException, NoSuccessException { AbstractAsyncNSDirectoryImpl.super.makeDirSync(target, flags); return null; } }; } public Task<NSDirectory, Void> makeDir(TaskMode mode, final URL target) throws NotImplementedException { return new AbstractThreadedTask<NSDirectory,Void>(mode) { public Void invoke() throws NotImplementedException, IncorrectURLException, AuthenticationFailedException, AuthorizationFailedException, PermissionDeniedException, BadParameterException, IncorrectStateException, AlreadyExistsException, DoesNotExistException, TimeoutException, NoSuccessException { AbstractAsyncNSDirectoryImpl.super.makeDirSync(target); return null; } }; } public Task<NSDirectory, NSDirectory> openDir(TaskMode mode, final URL name, final int flags) throws NotImplementedException { return new AbstractThreadedTask<NSDirectory,NSDirectory>(mode) { public NSDirectory invoke() throws NotImplementedException, IncorrectURLException, AuthenticationFailedException, AuthorizationFailedException, PermissionDeniedException, BadParameterException, IncorrectStateException, AlreadyExistsException, DoesNotExistException, TimeoutException, NoSuccessException { return AbstractAsyncNSDirectoryImpl.this.openDir(name, flags); } }; } public Task<NSDirectory, NSDirectory> openDir(TaskMode mode, final URL name) throws NotImplementedException { return new AbstractThreadedTask<NSDirectory,NSDirectory>(mode) { public NSDirectory invoke() throws NotImplementedException, IncorrectURLException, AuthenticationFailedException, AuthorizationFailedException, PermissionDeniedException, BadParameterException, IncorrectStateException, AlreadyExistsException, DoesNotExistException, TimeoutException, NoSuccessException { return AbstractAsyncNSDirectoryImpl.this.openDir(name); } }; } public Task<NSDirectory, NSEntry> open(TaskMode mode, final URL name, final int flags) throws NotImplementedException { return new AbstractThreadedTask<NSDirectory,NSEntry>(mode) { public NSEntry invoke() throws NotImplementedException, IncorrectURLException, AuthenticationFailedException, AuthorizationFailedException, PermissionDeniedException, BadParameterException, IncorrectStateException, AlreadyExistsException, DoesNotExistException, TimeoutException, NoSuccessException { return AbstractAsyncNSDirectoryImpl.this.open(name, flags); } }; } public Task<NSDirectory, NSEntry> open(TaskMode mode, final URL name) throws NotImplementedException { return new AbstractThreadedTask<NSDirectory,NSEntry>(mode) { public NSEntry invoke() throws NotImplementedException, IncorrectURLException, AuthenticationFailedException, AuthorizationFailedException, PermissionDeniedException, BadParameterException, IncorrectStateException, AlreadyExistsException, DoesNotExistException, TimeoutException, NoSuccessException { return AbstractAsyncNSDirectoryImpl.this.open(name); } }; } public Task<NSDirectory, Void> permissionsAllow(TaskMode mode, final URL target, final String id, final int permissions, final int flags) throws NotImplementedException { return new AbstractThreadedTask<NSDirectory,Void>(mode) { public Void invoke() throws NotImplementedException, IncorrectURLException, AuthenticationFailedException, AuthorizationFailedException, PermissionDeniedException, BadParameterException, IncorrectStateException, AlreadyExistsException, DoesNotExistException, TimeoutException, NoSuccessException { AbstractAsyncNSDirectoryImpl.super.permissionsAllowSync(target, id, permissions, flags); return null; } }; } public Task<NSDirectory, Void> permissionsAllow(TaskMode mode, final URL target, final String id, final int permissions) throws NotImplementedException { return new AbstractThreadedTask<NSDirectory,Void>(mode) { public Void invoke() throws NotImplementedException, IncorrectURLException, AuthenticationFailedException, AuthorizationFailedException, PermissionDeniedException, BadParameterException, IncorrectStateException, AlreadyExistsException, DoesNotExistException, TimeoutException, NoSuccessException { AbstractAsyncNSDirectoryImpl.super.permissionsAllowSync(target, id, permissions); return null; } }; } public Task<NSDirectory, Void> permissionsAllow(TaskMode mode, final String targetPattern, final String id, final int permissions, final int flags) throws NotImplementedException { return new AbstractThreadedTask<NSDirectory,Void>(mode) { public Void invoke() throws NotImplementedException, IncorrectURLException, AuthenticationFailedException, AuthorizationFailedException, PermissionDeniedException, BadParameterException, IncorrectStateException, AlreadyExistsException, DoesNotExistException, TimeoutException, NoSuccessException { AbstractAsyncNSDirectoryImpl.super.permissionsAllowSync(targetPattern, id, permissions, flags); return null; } }; } public Task<NSDirectory, Void> permissionsAllow(TaskMode mode, final String targetPattern, final String id, final int permissions) throws NotImplementedException { return new AbstractThreadedTask<NSDirectory,Void>(mode) { public Void invoke() throws NotImplementedException, IncorrectURLException, AuthenticationFailedException, AuthorizationFailedException, PermissionDeniedException, BadParameterException, IncorrectStateException, AlreadyExistsException, DoesNotExistException, TimeoutException, NoSuccessException { AbstractAsyncNSDirectoryImpl.super.permissionsAllowSync(targetPattern, id, permissions); return null; } }; } public Task<NSDirectory, Void> permissionsDeny(TaskMode mode, final URL target, final String id, final int permissions, final int flags) throws NotImplementedException { return new AbstractThreadedTask<NSDirectory,Void>(mode) { public Void invoke() throws NotImplementedException, IncorrectURLException, AuthenticationFailedException, AuthorizationFailedException, PermissionDeniedException, BadParameterException, IncorrectStateException, AlreadyExistsException, DoesNotExistException, TimeoutException, NoSuccessException { AbstractAsyncNSDirectoryImpl.super.permissionsDenySync(target, id, permissions, flags); return null; } }; } public Task<NSDirectory, Void> permissionsDeny(TaskMode mode, final URL target, final String id, final int permissions) throws NotImplementedException { return new AbstractThreadedTask<NSDirectory,Void>(mode) { public Void invoke() throws NotImplementedException, IncorrectURLException, AuthenticationFailedException, AuthorizationFailedException, PermissionDeniedException, BadParameterException, IncorrectStateException, AlreadyExistsException, DoesNotExistException, TimeoutException, NoSuccessException { AbstractAsyncNSDirectoryImpl.super.permissionsDenySync(target, id, permissions); return null; } }; } public Task<NSDirectory, Void> permissionsDeny(TaskMode mode, final String targetPattern, final String id, final int permissions, final int flags) throws NotImplementedException { return new AbstractThreadedTask<NSDirectory,Void>(mode) { public Void invoke() throws NotImplementedException, IncorrectURLException, AuthenticationFailedException, AuthorizationFailedException, PermissionDeniedException, BadParameterException, IncorrectStateException, AlreadyExistsException, DoesNotExistException, TimeoutException, NoSuccessException { AbstractAsyncNSDirectoryImpl.super.permissionsDenySync(targetPattern, id, permissions, flags); return null; } }; } public Task<NSDirectory, Void> permissionsDeny(TaskMode mode, final String targetPattern, final String id, final int permissions) throws NotImplementedException { return new AbstractThreadedTask<NSDirectory,Void>(mode) { public Void invoke() throws NotImplementedException, IncorrectURLException, AuthenticationFailedException, AuthorizationFailedException, PermissionDeniedException, BadParameterException, IncorrectStateException, AlreadyExistsException, DoesNotExistException, TimeoutException, NoSuccessException { AbstractAsyncNSDirectoryImpl.super.permissionsDenySync(targetPattern, id, permissions); return null; } }; } /////////////////////////////////////// override some methods of NSEntry /////////////////////////////////////// /** override super.getCWD() */ public Task<NSEntry, URL> getCWD(TaskMode mode) throws NotImplementedException { return new AbstractThreadedTask<NSEntry,URL>(mode) { public URL invoke() throws NotImplementedException, IncorrectURLException, AuthenticationFailedException, AuthorizationFailedException, PermissionDeniedException, BadParameterException, IncorrectStateException, AlreadyExistsException, DoesNotExistException, TimeoutException, NoSuccessException { return AbstractAsyncNSDirectoryImpl.super.getCWDSync(); } }; } /** override super.copy() */ public Task<NSEntry, Void> copy(TaskMode mode, final URL target, final int flags) throws NotImplementedException { if (this instanceof AbstractSyncDirectoryImpl) { final AbstractSyncDirectoryImpl source = (AbstractSyncDirectoryImpl) this; return new AbstractCopyTask<NSEntry,Void>(mode, m_session, target, flags) { public void doCopy(URL target, int flags) throws NotImplementedException, AuthenticationFailedException, AuthorizationFailedException, PermissionDeniedException, BadParameterException, IncorrectStateException, DoesNotExistException, AlreadyExistsException, TimeoutException, NoSuccessException, IncorrectURLException { source._copyAndMonitor(target, flags, this); } }; } else { return new AbstractThreadedTask<NSEntry,Void>(mode) { public Void invoke() throws NotImplementedException, IncorrectURLException, AuthenticationFailedException, AuthorizationFailedException, PermissionDeniedException, BadParameterException, IncorrectStateException, AlreadyExistsException, DoesNotExistException, TimeoutException, NoSuccessException { AbstractAsyncNSDirectoryImpl.super.copySync(target, flags); return null; } }; } } /** override super.move() */ public Task<NSEntry, Void> move(TaskMode mode, final URL target, final int flags) throws NotImplementedException { if (this instanceof AbstractSyncDirectoryImpl) { final AbstractSyncDirectoryImpl source = (AbstractSyncDirectoryImpl) this; return new AbstractCopyTask<NSEntry,Void>(mode, m_session, target, flags) { public void doCopy(URL target, int flags) throws NotImplementedException, AuthenticationFailedException, AuthorizationFailedException, PermissionDeniedException, BadParameterException, IncorrectStateException, DoesNotExistException, AlreadyExistsException, TimeoutException, NoSuccessException, IncorrectURLException { source._copyAndMonitor(target, flags, this); // For remove, ignore all flags except DEREFERENCE int removeFlags = Flags.RECURSIVE.getValue(); if (Flags.DEREFERENCE.isSet(flags)) { removeFlags += Flags.DEREFERENCE.getValue(); } source.removeSync(removeFlags); } }; } else { return new AbstractThreadedTask<NSEntry,Void>(mode) { public Void invoke() throws NotImplementedException, IncorrectURLException, AuthenticationFailedException, AuthorizationFailedException, PermissionDeniedException, BadParameterException, IncorrectStateException, AlreadyExistsException, DoesNotExistException, TimeoutException, NoSuccessException { AbstractAsyncNSDirectoryImpl.super.moveSync(target, flags); return null; } }; } } /** override super.remove() */ public Task<NSEntry, Void> remove(TaskMode mode, final int flags) throws NotImplementedException { return new AbstractThreadedTask<NSEntry,Void>(mode) { public Void invoke() throws NotImplementedException, IncorrectURLException, AuthenticationFailedException, AuthorizationFailedException, PermissionDeniedException, BadParameterException, IncorrectStateException, AlreadyExistsException, DoesNotExistException, TimeoutException, NoSuccessException { AbstractAsyncNSDirectoryImpl.super.removeSync(flags); return null; } }; } }
UTF-8
Java
35,910
java
AbstractAsyncNSDirectoryImpl.java
Java
[ { "context": "*\n* File: AbstractAsyncNSDirectoryImpl\n* Author: Sylvain Reynaud (sreynaud@in2p3.fr)\n* Date: 17 sept. 2007\n* ***", "end": 842, "score": 0.9998941421508789, "start": 827, "tag": "NAME", "value": "Sylvain Reynaud" }, { "context": "ctAsyncNSDirectoryImpl\n* Author: Sylvain Reynaud (sreynaud@in2p3.fr)\n* Date: 17 sept. 2007\n* **********************", "end": 861, "score": 0.9999324679374695, "start": 844, "tag": "EMAIL", "value": "sreynaud@in2p3.fr" } ]
null
[]
package fr.in2p3.jsaga.impl.namespace; import fr.in2p3.jsaga.adaptor.data.DataAdaptor; import fr.in2p3.jsaga.impl.file.AbstractSyncDirectoryImpl; import fr.in2p3.jsaga.impl.file.copy.AbstractCopyTask; import fr.in2p3.jsaga.impl.task.AbstractThreadedTask; import org.ogf.saga.error.*; import org.ogf.saga.namespace.Flags; import org.ogf.saga.namespace.NSDirectory; import org.ogf.saga.namespace.NSEntry; import org.ogf.saga.session.Session; import org.ogf.saga.task.Task; import org.ogf.saga.task.TaskMode; import org.ogf.saga.url.URL; import java.util.List; /* *************************************************** * *** Centre de Calcul de l'IN2P3 - Lyon (France) *** * *** http://cc.in2p3.fr/ *** * *************************************************** * File: AbstractAsyncNSDirectoryImpl * Author: <NAME> (<EMAIL>) * Date: 17 sept. 2007 * *************************************************** * Description: */ /** * */ public abstract class AbstractAsyncNSDirectoryImpl extends AbstractSyncNSDirectoryImpl implements NSDirectory { /** constructor for factory */ protected AbstractAsyncNSDirectoryImpl(Session session, URL url, DataAdaptor adaptor, int flags) throws NotImplementedException, IncorrectURLException, AuthenticationFailedException, AuthorizationFailedException, PermissionDeniedException, BadParameterException, AlreadyExistsException, DoesNotExistException, TimeoutException, NoSuccessException { super(session, url, adaptor, flags); } /** constructor for NSDirectory.open() */ protected AbstractAsyncNSDirectoryImpl(AbstractNSDirectoryImpl dir, URL relativeUrl, int flags) throws NotImplementedException, IncorrectURLException, AuthenticationFailedException, AuthorizationFailedException, PermissionDeniedException, BadParameterException, AlreadyExistsException, DoesNotExistException, TimeoutException, NoSuccessException { super(dir, relativeUrl, flags); } /** constructor for NSEntry.openAbsolute() */ protected AbstractAsyncNSDirectoryImpl(AbstractNSEntryImpl entry, String absolutePath, int flags) throws NotImplementedException, IncorrectURLException, AuthenticationFailedException, AuthorizationFailedException, PermissionDeniedException, BadParameterException, AlreadyExistsException, DoesNotExistException, TimeoutException, NoSuccessException { super(entry, absolutePath, flags); } ////////////////////////////////////////// interface NSDirectory ////////////////////////////////////////// public Task<NSDirectory, Void> changeDir(TaskMode mode, final URL dir) throws NotImplementedException { return new AbstractThreadedTask<NSDirectory,Void>(mode) { public Void invoke() throws NotImplementedException, IncorrectURLException, AuthenticationFailedException, AuthorizationFailedException, PermissionDeniedException, BadParameterException, IncorrectStateException, AlreadyExistsException, DoesNotExistException, TimeoutException, NoSuccessException { AbstractAsyncNSDirectoryImpl.super.changeDirSync(dir); return null; } }; } public Task<NSDirectory, List<URL>> list(TaskMode mode, final String pattern, final int flags) throws NotImplementedException { return new AbstractThreadedTask<NSDirectory,List<URL>>(mode) { public List<URL> invoke() throws NotImplementedException, IncorrectURLException, AuthenticationFailedException, AuthorizationFailedException, PermissionDeniedException, BadParameterException, IncorrectStateException, AlreadyExistsException, DoesNotExistException, TimeoutException, NoSuccessException { return AbstractAsyncNSDirectoryImpl.super.listSync(pattern, flags); } }; } public Task<NSDirectory, List<URL>> list(TaskMode mode, final String pattern) throws NotImplementedException { return new AbstractThreadedTask<NSDirectory,List<URL>>(mode) { public List<URL> invoke() throws NotImplementedException, IncorrectURLException, AuthenticationFailedException, AuthorizationFailedException, PermissionDeniedException, BadParameterException, IncorrectStateException, AlreadyExistsException, DoesNotExistException, TimeoutException, NoSuccessException { return AbstractAsyncNSDirectoryImpl.super.listSync(pattern); } }; } public Task<NSDirectory, List<URL>> list(TaskMode mode, final int flags) throws NotImplementedException { return new AbstractThreadedTask<NSDirectory,List<URL>>(mode) { public List<URL> invoke() throws NotImplementedException, IncorrectURLException, AuthenticationFailedException, AuthorizationFailedException, PermissionDeniedException, BadParameterException, IncorrectStateException, AlreadyExistsException, DoesNotExistException, TimeoutException, NoSuccessException { return AbstractAsyncNSDirectoryImpl.super.listSync(flags); } }; } public Task<NSDirectory, List<URL>> list(TaskMode mode) throws NotImplementedException { return new AbstractThreadedTask<NSDirectory,List<URL>>(mode) { public List<URL> invoke() throws NotImplementedException, IncorrectURLException, AuthenticationFailedException, AuthorizationFailedException, PermissionDeniedException, BadParameterException, IncorrectStateException, AlreadyExistsException, DoesNotExistException, TimeoutException, NoSuccessException { return AbstractAsyncNSDirectoryImpl.super.listSync(); } }; } public Task<NSDirectory, List<URL>> find(TaskMode mode, final String pattern, final int flags) throws NotImplementedException { return new AbstractThreadedTask<NSDirectory,List<URL>>(mode) { public List<URL> invoke() throws NotImplementedException, IncorrectURLException, AuthenticationFailedException, AuthorizationFailedException, PermissionDeniedException, BadParameterException, IncorrectStateException, AlreadyExistsException, DoesNotExistException, TimeoutException, NoSuccessException { return AbstractAsyncNSDirectoryImpl.super.findSync(pattern, flags); } }; } public Task<NSDirectory, List<URL>> find(TaskMode mode, final String pattern) throws NotImplementedException { return new AbstractThreadedTask<NSDirectory,List<URL>>(mode) { public List<URL> invoke() throws NotImplementedException, IncorrectURLException, AuthenticationFailedException, AuthorizationFailedException, PermissionDeniedException, BadParameterException, IncorrectStateException, AlreadyExistsException, DoesNotExistException, TimeoutException, NoSuccessException { return AbstractAsyncNSDirectoryImpl.super.findSync(pattern); } }; } public Task<NSDirectory, Boolean> exists(TaskMode mode, final URL name) throws NotImplementedException { return new AbstractThreadedTask<NSDirectory,Boolean>(mode) { public Boolean invoke() throws NotImplementedException, IncorrectURLException, AuthenticationFailedException, AuthorizationFailedException, PermissionDeniedException, BadParameterException, IncorrectStateException, AlreadyExistsException, DoesNotExistException, TimeoutException, NoSuccessException { return AbstractAsyncNSDirectoryImpl.super.existsSync(name); } }; } public Task<NSDirectory, Boolean> isDir(TaskMode mode, final URL name) throws NotImplementedException { return new AbstractThreadedTask<NSDirectory,Boolean>(mode) { public Boolean invoke() throws NotImplementedException, IncorrectURLException, AuthenticationFailedException, AuthorizationFailedException, PermissionDeniedException, BadParameterException, IncorrectStateException, AlreadyExistsException, DoesNotExistException, TimeoutException, NoSuccessException { return AbstractAsyncNSDirectoryImpl.super.isDirSync(name); } }; } public Task<NSDirectory, Boolean> isEntry(TaskMode mode, final URL name) throws NotImplementedException { return new AbstractThreadedTask<NSDirectory,Boolean>(mode) { public Boolean invoke() throws NotImplementedException, IncorrectURLException, AuthenticationFailedException, AuthorizationFailedException, PermissionDeniedException, BadParameterException, IncorrectStateException, AlreadyExistsException, DoesNotExistException, TimeoutException, NoSuccessException { return AbstractAsyncNSDirectoryImpl.super.isEntrySync(name); } }; } public Task<NSDirectory, Boolean> isLink(TaskMode mode, final URL name) throws NotImplementedException { return new AbstractThreadedTask<NSDirectory,Boolean>(mode) { public Boolean invoke() throws NotImplementedException, IncorrectURLException, AuthenticationFailedException, AuthorizationFailedException, PermissionDeniedException, BadParameterException, IncorrectStateException, AlreadyExistsException, DoesNotExistException, TimeoutException, NoSuccessException { return AbstractAsyncNSDirectoryImpl.super.isLinkSync(name); } }; } public Task<NSDirectory, Long> getMTime(TaskMode mode, final URL name) throws NotImplementedException { return new AbstractThreadedTask<NSDirectory,Long>(mode) { public Long invoke() throws NotImplementedException, IncorrectURLException, AuthenticationFailedException, AuthorizationFailedException, PermissionDeniedException, BadParameterException, IncorrectStateException, AlreadyExistsException, DoesNotExistException, TimeoutException, NoSuccessException { return AbstractAsyncNSDirectoryImpl.super.getMTimeSync(name); } }; } public Task<NSDirectory, URL> readLink(TaskMode mode, final URL name) throws NotImplementedException { return new AbstractThreadedTask<NSDirectory,URL>(mode) { public URL invoke() throws NotImplementedException, IncorrectURLException, AuthenticationFailedException, AuthorizationFailedException, PermissionDeniedException, BadParameterException, IncorrectStateException, AlreadyExistsException, DoesNotExistException, TimeoutException, NoSuccessException { return AbstractAsyncNSDirectoryImpl.super.readLinkSync(name); } }; } public Task<NSDirectory, Integer> getNumEntries(TaskMode mode) throws NotImplementedException { return new AbstractThreadedTask<NSDirectory,Integer>(mode) { public Integer invoke() throws NotImplementedException, IncorrectURLException, AuthenticationFailedException, AuthorizationFailedException, PermissionDeniedException, BadParameterException, IncorrectStateException, AlreadyExistsException, DoesNotExistException, TimeoutException, NoSuccessException { return AbstractAsyncNSDirectoryImpl.super.getNumEntriesSync(); } }; } public Task<NSDirectory, URL> getEntry(TaskMode mode, final int entry) throws NotImplementedException { return new AbstractThreadedTask<NSDirectory,URL>(mode) { public URL invoke() throws NotImplementedException, IncorrectURLException, AuthenticationFailedException, AuthorizationFailedException, PermissionDeniedException, BadParameterException, IncorrectStateException, AlreadyExistsException, DoesNotExistException, TimeoutException, NoSuccessException { return AbstractAsyncNSDirectoryImpl.super.getEntrySync(entry); } }; } public Task<NSDirectory, Void> copy(TaskMode mode, final URL source, final URL target, final int flags) throws NotImplementedException { return new AbstractThreadedTask<NSDirectory,Void>(mode) { public Void invoke() throws NotImplementedException, IncorrectURLException, AuthenticationFailedException, AuthorizationFailedException, PermissionDeniedException, BadParameterException, IncorrectStateException, AlreadyExistsException, DoesNotExistException, TimeoutException, NoSuccessException { AbstractAsyncNSDirectoryImpl.super.copySync(source, target, flags); return null; } }; } public Task<NSDirectory, Void> copy(TaskMode mode, final URL source, final URL target) throws NotImplementedException { return new AbstractThreadedTask<NSDirectory,Void>(mode) { public Void invoke() throws NotImplementedException, IncorrectURLException, AuthenticationFailedException, AuthorizationFailedException, PermissionDeniedException, BadParameterException, IncorrectStateException, AlreadyExistsException, DoesNotExistException, TimeoutException, NoSuccessException { AbstractAsyncNSDirectoryImpl.super.copySync(source, target); return null; } }; } public Task<NSDirectory, Void> copy(TaskMode mode, final String sourcePattern, final URL target, final int flags) throws NotImplementedException { return new AbstractThreadedTask<NSDirectory,Void>(mode) { public Void invoke() throws NotImplementedException, IncorrectURLException, AuthenticationFailedException, AuthorizationFailedException, PermissionDeniedException, BadParameterException, IncorrectStateException, AlreadyExistsException, DoesNotExistException, TimeoutException, NoSuccessException { AbstractAsyncNSDirectoryImpl.super.copySync(sourcePattern, target, flags); return null; } }; } public Task<NSDirectory, Void> copy(TaskMode mode, final String sourcePattern, final URL target) throws NotImplementedException { return new AbstractThreadedTask<NSDirectory,Void>(mode) { public Void invoke() throws NotImplementedException, IncorrectURLException, AuthenticationFailedException, AuthorizationFailedException, PermissionDeniedException, BadParameterException, IncorrectStateException, AlreadyExistsException, DoesNotExistException, TimeoutException, NoSuccessException { AbstractAsyncNSDirectoryImpl.super.copySync(sourcePattern, target); return null; } }; } public Task<NSDirectory, Void> link(TaskMode mode, final URL source, final URL target, final int flags) throws NotImplementedException { return new AbstractThreadedTask<NSDirectory,Void>(mode) { public Void invoke() throws NotImplementedException, IncorrectURLException, AuthenticationFailedException, AuthorizationFailedException, PermissionDeniedException, BadParameterException, IncorrectStateException, AlreadyExistsException, DoesNotExistException, TimeoutException, NoSuccessException { AbstractAsyncNSDirectoryImpl.super.linkSync(source, target, flags); return null; } }; } public Task<NSDirectory, Void> link(TaskMode mode, final URL source, final URL target) throws NotImplementedException { return new AbstractThreadedTask<NSDirectory,Void>(mode) { public Void invoke() throws NotImplementedException, IncorrectURLException, AuthenticationFailedException, AuthorizationFailedException, PermissionDeniedException, BadParameterException, IncorrectStateException, AlreadyExistsException, DoesNotExistException, TimeoutException, NoSuccessException { AbstractAsyncNSDirectoryImpl.super.linkSync(source, target); return null; } }; } public Task<NSDirectory, Void> link(TaskMode mode, final String sourcePattern, final URL target, final int flags) throws NotImplementedException { return new AbstractThreadedTask<NSDirectory,Void>(mode) { public Void invoke() throws NotImplementedException, IncorrectURLException, AuthenticationFailedException, AuthorizationFailedException, PermissionDeniedException, BadParameterException, IncorrectStateException, AlreadyExistsException, DoesNotExistException, TimeoutException, NoSuccessException { AbstractAsyncNSDirectoryImpl.super.linkSync(sourcePattern, target, flags); return null; } }; } public Task<NSDirectory, Void> link(TaskMode mode, final String sourcePattern, final URL target) throws NotImplementedException { return new AbstractThreadedTask<NSDirectory,Void>(mode) { public Void invoke() throws NotImplementedException, IncorrectURLException, AuthenticationFailedException, AuthorizationFailedException, PermissionDeniedException, BadParameterException, IncorrectStateException, AlreadyExistsException, DoesNotExistException, TimeoutException, NoSuccessException { AbstractAsyncNSDirectoryImpl.super.linkSync(sourcePattern, target); return null; } }; } public Task<NSDirectory, Void> move(TaskMode mode, final URL source, final URL target, final int flags) throws NotImplementedException { return new AbstractThreadedTask<NSDirectory,Void>(mode) { public Void invoke() throws NotImplementedException, IncorrectURLException, AuthenticationFailedException, AuthorizationFailedException, PermissionDeniedException, BadParameterException, IncorrectStateException, AlreadyExistsException, DoesNotExistException, TimeoutException, NoSuccessException { AbstractAsyncNSDirectoryImpl.super.moveSync(source, target, flags); return null; } }; } public Task<NSDirectory, Void> move(TaskMode mode, final URL source, final URL target) throws NotImplementedException { return new AbstractThreadedTask<NSDirectory,Void>(mode) { public Void invoke() throws NotImplementedException, IncorrectURLException, AuthenticationFailedException, AuthorizationFailedException, PermissionDeniedException, BadParameterException, IncorrectStateException, AlreadyExistsException, DoesNotExistException, TimeoutException, NoSuccessException { AbstractAsyncNSDirectoryImpl.super.moveSync(source, target); return null; } }; } public Task<NSDirectory, Void> move(TaskMode mode, final String sourcePattern, final URL target, final int flags) throws NotImplementedException { return new AbstractThreadedTask<NSDirectory,Void>(mode) { public Void invoke() throws NotImplementedException, IncorrectURLException, AuthenticationFailedException, AuthorizationFailedException, PermissionDeniedException, BadParameterException, IncorrectStateException, AlreadyExistsException, DoesNotExistException, TimeoutException, NoSuccessException { AbstractAsyncNSDirectoryImpl.super.moveSync(sourcePattern, target, flags); return null; } }; } public Task<NSDirectory, Void> move(TaskMode mode, final String sourcePattern, final URL target) throws NotImplementedException { return new AbstractThreadedTask<NSDirectory,Void>(mode) { public Void invoke() throws NotImplementedException, IncorrectURLException, AuthenticationFailedException, AuthorizationFailedException, PermissionDeniedException, BadParameterException, IncorrectStateException, AlreadyExistsException, DoesNotExistException, TimeoutException, NoSuccessException { AbstractAsyncNSDirectoryImpl.super.moveSync(sourcePattern, target); return null; } }; } public Task<NSDirectory, Void> remove(TaskMode mode, final URL target, final int flags) throws NotImplementedException { return new AbstractThreadedTask<NSDirectory,Void>(mode) { public Void invoke() throws NotImplementedException, IncorrectURLException, AuthenticationFailedException, AuthorizationFailedException, PermissionDeniedException, BadParameterException, IncorrectStateException, AlreadyExistsException, DoesNotExistException, TimeoutException, NoSuccessException { AbstractAsyncNSDirectoryImpl.super.removeSync(target, flags); return null; } }; } public Task<NSDirectory, Void> remove(TaskMode mode, final URL target) throws NotImplementedException { return new AbstractThreadedTask<NSDirectory,Void>(mode) { public Void invoke() throws NotImplementedException, IncorrectURLException, AuthenticationFailedException, AuthorizationFailedException, PermissionDeniedException, BadParameterException, IncorrectStateException, AlreadyExistsException, DoesNotExistException, TimeoutException, NoSuccessException { AbstractAsyncNSDirectoryImpl.super.removeSync(target); return null; } }; } public Task<NSDirectory, Void> remove(TaskMode mode, final String targetPattern, final int flags) throws NotImplementedException { return new AbstractThreadedTask<NSDirectory,Void>(mode) { public Void invoke() throws NotImplementedException, IncorrectURLException, AuthenticationFailedException, AuthorizationFailedException, PermissionDeniedException, BadParameterException, IncorrectStateException, AlreadyExistsException, DoesNotExistException, TimeoutException, NoSuccessException { AbstractAsyncNSDirectoryImpl.super.removeSync(targetPattern, flags); return null; } }; } public Task<NSDirectory, Void> remove(TaskMode mode, final String targetPattern) throws NotImplementedException { return new AbstractThreadedTask<NSDirectory,Void>(mode) { public Void invoke() throws NotImplementedException, IncorrectURLException, AuthenticationFailedException, AuthorizationFailedException, PermissionDeniedException, BadParameterException, IncorrectStateException, AlreadyExistsException, DoesNotExistException, TimeoutException, NoSuccessException { AbstractAsyncNSDirectoryImpl.super.removeSync(targetPattern); return null; } }; } public Task<NSDirectory, Void> makeDir(TaskMode mode, final URL target, final int flags) throws NotImplementedException { return new AbstractThreadedTask<NSDirectory,Void>(mode) { public Void invoke() throws NotImplementedException, IncorrectURLException, AuthenticationFailedException, AuthorizationFailedException, PermissionDeniedException, BadParameterException, IncorrectStateException, AlreadyExistsException, DoesNotExistException, TimeoutException, NoSuccessException { AbstractAsyncNSDirectoryImpl.super.makeDirSync(target, flags); return null; } }; } public Task<NSDirectory, Void> makeDir(TaskMode mode, final URL target) throws NotImplementedException { return new AbstractThreadedTask<NSDirectory,Void>(mode) { public Void invoke() throws NotImplementedException, IncorrectURLException, AuthenticationFailedException, AuthorizationFailedException, PermissionDeniedException, BadParameterException, IncorrectStateException, AlreadyExistsException, DoesNotExistException, TimeoutException, NoSuccessException { AbstractAsyncNSDirectoryImpl.super.makeDirSync(target); return null; } }; } public Task<NSDirectory, NSDirectory> openDir(TaskMode mode, final URL name, final int flags) throws NotImplementedException { return new AbstractThreadedTask<NSDirectory,NSDirectory>(mode) { public NSDirectory invoke() throws NotImplementedException, IncorrectURLException, AuthenticationFailedException, AuthorizationFailedException, PermissionDeniedException, BadParameterException, IncorrectStateException, AlreadyExistsException, DoesNotExistException, TimeoutException, NoSuccessException { return AbstractAsyncNSDirectoryImpl.this.openDir(name, flags); } }; } public Task<NSDirectory, NSDirectory> openDir(TaskMode mode, final URL name) throws NotImplementedException { return new AbstractThreadedTask<NSDirectory,NSDirectory>(mode) { public NSDirectory invoke() throws NotImplementedException, IncorrectURLException, AuthenticationFailedException, AuthorizationFailedException, PermissionDeniedException, BadParameterException, IncorrectStateException, AlreadyExistsException, DoesNotExistException, TimeoutException, NoSuccessException { return AbstractAsyncNSDirectoryImpl.this.openDir(name); } }; } public Task<NSDirectory, NSEntry> open(TaskMode mode, final URL name, final int flags) throws NotImplementedException { return new AbstractThreadedTask<NSDirectory,NSEntry>(mode) { public NSEntry invoke() throws NotImplementedException, IncorrectURLException, AuthenticationFailedException, AuthorizationFailedException, PermissionDeniedException, BadParameterException, IncorrectStateException, AlreadyExistsException, DoesNotExistException, TimeoutException, NoSuccessException { return AbstractAsyncNSDirectoryImpl.this.open(name, flags); } }; } public Task<NSDirectory, NSEntry> open(TaskMode mode, final URL name) throws NotImplementedException { return new AbstractThreadedTask<NSDirectory,NSEntry>(mode) { public NSEntry invoke() throws NotImplementedException, IncorrectURLException, AuthenticationFailedException, AuthorizationFailedException, PermissionDeniedException, BadParameterException, IncorrectStateException, AlreadyExistsException, DoesNotExistException, TimeoutException, NoSuccessException { return AbstractAsyncNSDirectoryImpl.this.open(name); } }; } public Task<NSDirectory, Void> permissionsAllow(TaskMode mode, final URL target, final String id, final int permissions, final int flags) throws NotImplementedException { return new AbstractThreadedTask<NSDirectory,Void>(mode) { public Void invoke() throws NotImplementedException, IncorrectURLException, AuthenticationFailedException, AuthorizationFailedException, PermissionDeniedException, BadParameterException, IncorrectStateException, AlreadyExistsException, DoesNotExistException, TimeoutException, NoSuccessException { AbstractAsyncNSDirectoryImpl.super.permissionsAllowSync(target, id, permissions, flags); return null; } }; } public Task<NSDirectory, Void> permissionsAllow(TaskMode mode, final URL target, final String id, final int permissions) throws NotImplementedException { return new AbstractThreadedTask<NSDirectory,Void>(mode) { public Void invoke() throws NotImplementedException, IncorrectURLException, AuthenticationFailedException, AuthorizationFailedException, PermissionDeniedException, BadParameterException, IncorrectStateException, AlreadyExistsException, DoesNotExistException, TimeoutException, NoSuccessException { AbstractAsyncNSDirectoryImpl.super.permissionsAllowSync(target, id, permissions); return null; } }; } public Task<NSDirectory, Void> permissionsAllow(TaskMode mode, final String targetPattern, final String id, final int permissions, final int flags) throws NotImplementedException { return new AbstractThreadedTask<NSDirectory,Void>(mode) { public Void invoke() throws NotImplementedException, IncorrectURLException, AuthenticationFailedException, AuthorizationFailedException, PermissionDeniedException, BadParameterException, IncorrectStateException, AlreadyExistsException, DoesNotExistException, TimeoutException, NoSuccessException { AbstractAsyncNSDirectoryImpl.super.permissionsAllowSync(targetPattern, id, permissions, flags); return null; } }; } public Task<NSDirectory, Void> permissionsAllow(TaskMode mode, final String targetPattern, final String id, final int permissions) throws NotImplementedException { return new AbstractThreadedTask<NSDirectory,Void>(mode) { public Void invoke() throws NotImplementedException, IncorrectURLException, AuthenticationFailedException, AuthorizationFailedException, PermissionDeniedException, BadParameterException, IncorrectStateException, AlreadyExistsException, DoesNotExistException, TimeoutException, NoSuccessException { AbstractAsyncNSDirectoryImpl.super.permissionsAllowSync(targetPattern, id, permissions); return null; } }; } public Task<NSDirectory, Void> permissionsDeny(TaskMode mode, final URL target, final String id, final int permissions, final int flags) throws NotImplementedException { return new AbstractThreadedTask<NSDirectory,Void>(mode) { public Void invoke() throws NotImplementedException, IncorrectURLException, AuthenticationFailedException, AuthorizationFailedException, PermissionDeniedException, BadParameterException, IncorrectStateException, AlreadyExistsException, DoesNotExistException, TimeoutException, NoSuccessException { AbstractAsyncNSDirectoryImpl.super.permissionsDenySync(target, id, permissions, flags); return null; } }; } public Task<NSDirectory, Void> permissionsDeny(TaskMode mode, final URL target, final String id, final int permissions) throws NotImplementedException { return new AbstractThreadedTask<NSDirectory,Void>(mode) { public Void invoke() throws NotImplementedException, IncorrectURLException, AuthenticationFailedException, AuthorizationFailedException, PermissionDeniedException, BadParameterException, IncorrectStateException, AlreadyExistsException, DoesNotExistException, TimeoutException, NoSuccessException { AbstractAsyncNSDirectoryImpl.super.permissionsDenySync(target, id, permissions); return null; } }; } public Task<NSDirectory, Void> permissionsDeny(TaskMode mode, final String targetPattern, final String id, final int permissions, final int flags) throws NotImplementedException { return new AbstractThreadedTask<NSDirectory,Void>(mode) { public Void invoke() throws NotImplementedException, IncorrectURLException, AuthenticationFailedException, AuthorizationFailedException, PermissionDeniedException, BadParameterException, IncorrectStateException, AlreadyExistsException, DoesNotExistException, TimeoutException, NoSuccessException { AbstractAsyncNSDirectoryImpl.super.permissionsDenySync(targetPattern, id, permissions, flags); return null; } }; } public Task<NSDirectory, Void> permissionsDeny(TaskMode mode, final String targetPattern, final String id, final int permissions) throws NotImplementedException { return new AbstractThreadedTask<NSDirectory,Void>(mode) { public Void invoke() throws NotImplementedException, IncorrectURLException, AuthenticationFailedException, AuthorizationFailedException, PermissionDeniedException, BadParameterException, IncorrectStateException, AlreadyExistsException, DoesNotExistException, TimeoutException, NoSuccessException { AbstractAsyncNSDirectoryImpl.super.permissionsDenySync(targetPattern, id, permissions); return null; } }; } /////////////////////////////////////// override some methods of NSEntry /////////////////////////////////////// /** override super.getCWD() */ public Task<NSEntry, URL> getCWD(TaskMode mode) throws NotImplementedException { return new AbstractThreadedTask<NSEntry,URL>(mode) { public URL invoke() throws NotImplementedException, IncorrectURLException, AuthenticationFailedException, AuthorizationFailedException, PermissionDeniedException, BadParameterException, IncorrectStateException, AlreadyExistsException, DoesNotExistException, TimeoutException, NoSuccessException { return AbstractAsyncNSDirectoryImpl.super.getCWDSync(); } }; } /** override super.copy() */ public Task<NSEntry, Void> copy(TaskMode mode, final URL target, final int flags) throws NotImplementedException { if (this instanceof AbstractSyncDirectoryImpl) { final AbstractSyncDirectoryImpl source = (AbstractSyncDirectoryImpl) this; return new AbstractCopyTask<NSEntry,Void>(mode, m_session, target, flags) { public void doCopy(URL target, int flags) throws NotImplementedException, AuthenticationFailedException, AuthorizationFailedException, PermissionDeniedException, BadParameterException, IncorrectStateException, DoesNotExistException, AlreadyExistsException, TimeoutException, NoSuccessException, IncorrectURLException { source._copyAndMonitor(target, flags, this); } }; } else { return new AbstractThreadedTask<NSEntry,Void>(mode) { public Void invoke() throws NotImplementedException, IncorrectURLException, AuthenticationFailedException, AuthorizationFailedException, PermissionDeniedException, BadParameterException, IncorrectStateException, AlreadyExistsException, DoesNotExistException, TimeoutException, NoSuccessException { AbstractAsyncNSDirectoryImpl.super.copySync(target, flags); return null; } }; } } /** override super.move() */ public Task<NSEntry, Void> move(TaskMode mode, final URL target, final int flags) throws NotImplementedException { if (this instanceof AbstractSyncDirectoryImpl) { final AbstractSyncDirectoryImpl source = (AbstractSyncDirectoryImpl) this; return new AbstractCopyTask<NSEntry,Void>(mode, m_session, target, flags) { public void doCopy(URL target, int flags) throws NotImplementedException, AuthenticationFailedException, AuthorizationFailedException, PermissionDeniedException, BadParameterException, IncorrectStateException, DoesNotExistException, AlreadyExistsException, TimeoutException, NoSuccessException, IncorrectURLException { source._copyAndMonitor(target, flags, this); // For remove, ignore all flags except DEREFERENCE int removeFlags = Flags.RECURSIVE.getValue(); if (Flags.DEREFERENCE.isSet(flags)) { removeFlags += Flags.DEREFERENCE.getValue(); } source.removeSync(removeFlags); } }; } else { return new AbstractThreadedTask<NSEntry,Void>(mode) { public Void invoke() throws NotImplementedException, IncorrectURLException, AuthenticationFailedException, AuthorizationFailedException, PermissionDeniedException, BadParameterException, IncorrectStateException, AlreadyExistsException, DoesNotExistException, TimeoutException, NoSuccessException { AbstractAsyncNSDirectoryImpl.super.moveSync(target, flags); return null; } }; } } /** override super.remove() */ public Task<NSEntry, Void> remove(TaskMode mode, final int flags) throws NotImplementedException { return new AbstractThreadedTask<NSEntry,Void>(mode) { public Void invoke() throws NotImplementedException, IncorrectURLException, AuthenticationFailedException, AuthorizationFailedException, PermissionDeniedException, BadParameterException, IncorrectStateException, AlreadyExistsException, DoesNotExistException, TimeoutException, NoSuccessException { AbstractAsyncNSDirectoryImpl.super.removeSync(flags); return null; } }; } }
35,891
0.748677
0.748065
481
73.656967
94.382782
353
false
false
0
0
0
0
0
0
1.991684
false
false
7
40589927463321a9c22c2c608c17b8392a1a6ada
884,763,297,806
87be8f2f0396d855e2b5e624f738070a8844d260
/governator-core/src/main/java/com/netflix/governator/SingletonModule.java
ff19fe8087b24a0fdb7f9df51d54a09b3f9c382b
[ "Apache-2.0" ]
permissive
Netflix/governator
https://github.com/Netflix/governator
0c02727e548b35bc5784cf0965fb975ed30a9815
961df38b5c18aed39fb1a6e5e76cf839a303da4a
refs/heads/master
2023-07-10T01:28:25.394000
2023-03-20T23:24:31
2023-03-20T23:24:31
4,941,867
731
167
Apache-2.0
false
2023-06-26T19:49:09
2012-07-07T22:28:42
2023-06-18T09:26:34
2023-06-26T19:48:27
4,569
818
184
62
Java
false
false
package com.netflix.governator; import java.lang.reflect.Modifier; import com.google.inject.AbstractModule; /** * Base module that ensures only one module is used when multiple modules * are installed using the concrete module class as the dedup key. To * ensure 'best practices' this class also forces the concrete module to * be final. This is done to prevent the use of inheritance for overriding * behavior in favor of using Modules.override(). * * @deprecated Extend AbstractModule directly and add the following equals and hashCode * * {@code @Override public boolean equals(Object obj) { return obj != null && getClass().equals(obj.getClass()); } @Override public int hashCode() { return getClass().hashCode(); } } */ @Deprecated public abstract class SingletonModule extends AbstractModule { public SingletonModule() { if (!Modifier.isFinal(getClass().getModifiers())) { throw new RuntimeException("Module " + getClass().getName() + " must be final"); } } @Override protected void configure() { } @Override public boolean equals(Object obj) { return obj != null && getClass().equals(obj.getClass()); } @Override public int hashCode() { return getClass().hashCode(); } @Override public String toString() { return getClass().getName(); } }
UTF-8
Java
1,419
java
SingletonModule.java
Java
[]
null
[]
package com.netflix.governator; import java.lang.reflect.Modifier; import com.google.inject.AbstractModule; /** * Base module that ensures only one module is used when multiple modules * are installed using the concrete module class as the dedup key. To * ensure 'best practices' this class also forces the concrete module to * be final. This is done to prevent the use of inheritance for overriding * behavior in favor of using Modules.override(). * * @deprecated Extend AbstractModule directly and add the following equals and hashCode * * {@code @Override public boolean equals(Object obj) { return obj != null && getClass().equals(obj.getClass()); } @Override public int hashCode() { return getClass().hashCode(); } } */ @Deprecated public abstract class SingletonModule extends AbstractModule { public SingletonModule() { if (!Modifier.isFinal(getClass().getModifiers())) { throw new RuntimeException("Module " + getClass().getName() + " must be final"); } } @Override protected void configure() { } @Override public boolean equals(Object obj) { return obj != null && getClass().equals(obj.getClass()); } @Override public int hashCode() { return getClass().hashCode(); } @Override public String toString() { return getClass().getName(); } }
1,419
0.657505
0.657505
54
25.277779
26.113298
92
false
false
0
0
0
0
0
0
0.166667
false
false
7
40e845374d4ab9340eea49793603efff90fe84a7
429,496,759,589
823bb46b8ad5747656773ce2905811d53d4aa954
/src/pt/webdetails/cda/connections/olap4j/JndiConnection.java
c2945ffb3ac717a98123b9e755315e61566a01cc
[]
no_license
erwanj/cda
https://github.com/erwanj/cda
5f31193ef51b663c639e420bcf65c63611fed862
57585769f5e7c83aa4d13bbc5e75a0a83b1b24e2
refs/heads/master
2020-12-25T13:45:39.943000
2012-07-10T16:05:29
2012-07-10T16:05:29
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package pt.webdetails.cda.connections.olap4j; import java.sql.Connection; import java.sql.SQLException; import java.util.ArrayList; import org.dom4j.Element; import org.pentaho.reporting.engine.classic.extensions.datasources.olap4j.connections.JndiConnectionProvider; import org.pentaho.reporting.engine.classic.extensions.datasources.olap4j.connections.OlapConnectionProvider; import pt.webdetails.cda.connections.AbstractConnection; import pt.webdetails.cda.connections.ConnectionCatalog.ConnectionType; import pt.webdetails.cda.connections.InvalidConnectionException; import pt.webdetails.cda.dataaccess.PropertyDescriptor; import pt.webdetails.cda.utils.Util; /** * Todo: Document me! * <p/> * Date: 16.02.2010 * Time: 12:59:15 * * @author Thomas Morgner. */ public class JndiConnection extends AbstractConnection implements Olap4JConnection { private OlapJndiConnectionInfo connectionInfo; public JndiConnection(final Element connection) throws InvalidConnectionException { super(connection); } public JndiConnection() { } public OlapConnectionProvider getInitializedConnectionProvider() throws InvalidConnectionException { final JndiConnectionProvider connectionProvider = new JndiConnectionProvider(); connectionProvider.setConnectionPath(connectionInfo.getJndi()); connectionProvider.setUsername(connectionInfo.getUser()); connectionProvider.setPassword(connectionInfo.getPass()); try { final Connection connection = connectionProvider.createConnection(null, null); connection.close(); } catch (SQLException e) { throw new InvalidConnectionException("JdbcConnection: Found SQLException: " + Util.getExceptionDescription(e), e); } return connectionProvider; } protected void initializeConnection(final Element connection) throws InvalidConnectionException { connectionInfo = new OlapJndiConnectionInfo(connection); } public String getType() { return "olapJndi"; } public boolean equals(final Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } final JndiConnection that = (JndiConnection) o; if (!connectionInfo.equals(that.connectionInfo)) { return false; } return true; } public int hashCode() { return connectionInfo.hashCode(); } @Override public ConnectionType getGenericType() { return ConnectionType.OLAP4J; } @Override public ArrayList<PropertyDescriptor> getProperties() { ArrayList<PropertyDescriptor> properties = new ArrayList<PropertyDescriptor>(); properties.add(new PropertyDescriptor("id", PropertyDescriptor.Type.STRING, PropertyDescriptor.Placement.ATTRIB)); properties.add(new PropertyDescriptor("jndi", PropertyDescriptor.Type.STRING, PropertyDescriptor.Placement.CHILD)); return properties; } public String getRoleField() { return connectionInfo.getRoleField(); } public String getUserField() { return connectionInfo.getUserField(); } public String getPasswordField() { return connectionInfo.getPasswordField(); } }
UTF-8
Java
3,150
java
JndiConnection.java
Java
[ { "context": "* Date: 16.02.2010\n * Time: 12:59:15\n *\n * @author Thomas Morgner.\n */\npublic class JndiConnection extends Abstract", "end": 767, "score": 0.9988107681274414, "start": 753, "tag": "NAME", "value": "Thomas Morgner" } ]
null
[]
package pt.webdetails.cda.connections.olap4j; import java.sql.Connection; import java.sql.SQLException; import java.util.ArrayList; import org.dom4j.Element; import org.pentaho.reporting.engine.classic.extensions.datasources.olap4j.connections.JndiConnectionProvider; import org.pentaho.reporting.engine.classic.extensions.datasources.olap4j.connections.OlapConnectionProvider; import pt.webdetails.cda.connections.AbstractConnection; import pt.webdetails.cda.connections.ConnectionCatalog.ConnectionType; import pt.webdetails.cda.connections.InvalidConnectionException; import pt.webdetails.cda.dataaccess.PropertyDescriptor; import pt.webdetails.cda.utils.Util; /** * Todo: Document me! * <p/> * Date: 16.02.2010 * Time: 12:59:15 * * @author <NAME>. */ public class JndiConnection extends AbstractConnection implements Olap4JConnection { private OlapJndiConnectionInfo connectionInfo; public JndiConnection(final Element connection) throws InvalidConnectionException { super(connection); } public JndiConnection() { } public OlapConnectionProvider getInitializedConnectionProvider() throws InvalidConnectionException { final JndiConnectionProvider connectionProvider = new JndiConnectionProvider(); connectionProvider.setConnectionPath(connectionInfo.getJndi()); connectionProvider.setUsername(connectionInfo.getUser()); connectionProvider.setPassword(connectionInfo.getPass()); try { final Connection connection = connectionProvider.createConnection(null, null); connection.close(); } catch (SQLException e) { throw new InvalidConnectionException("JdbcConnection: Found SQLException: " + Util.getExceptionDescription(e), e); } return connectionProvider; } protected void initializeConnection(final Element connection) throws InvalidConnectionException { connectionInfo = new OlapJndiConnectionInfo(connection); } public String getType() { return "olapJndi"; } public boolean equals(final Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } final JndiConnection that = (JndiConnection) o; if (!connectionInfo.equals(that.connectionInfo)) { return false; } return true; } public int hashCode() { return connectionInfo.hashCode(); } @Override public ConnectionType getGenericType() { return ConnectionType.OLAP4J; } @Override public ArrayList<PropertyDescriptor> getProperties() { ArrayList<PropertyDescriptor> properties = new ArrayList<PropertyDescriptor>(); properties.add(new PropertyDescriptor("id", PropertyDescriptor.Type.STRING, PropertyDescriptor.Placement.ATTRIB)); properties.add(new PropertyDescriptor("jndi", PropertyDescriptor.Type.STRING, PropertyDescriptor.Placement.CHILD)); return properties; } public String getRoleField() { return connectionInfo.getRoleField(); } public String getUserField() { return connectionInfo.getUserField(); } public String getPasswordField() { return connectionInfo.getPasswordField(); } }
3,142
0.753016
0.746667
110
27.636364
31.521919
120
false
false
0
0
0
0
0
0
0.418182
false
false
7
531d6abb6b5d969c540985b4f913cc522e636d2c
11,940,009,140,194
ef1994a343f7c4cfc14788b0d5d84cad280fc7d3
/src/no/npolar/data/api/Contributor.java
4a4b0c25185f500934496ca48ea7f03adf3e1b5a
[]
no_license
paulflakstad/no.npolar.data.api
https://github.com/paulflakstad/no.npolar.data.api
2a34db3b8678d3e74a48bcada68d6b73cd457e66
f173ff29926ffd307baa2e6283eabd65d86c2fcc
refs/heads/master
2021-04-18T19:40:44.619000
2017-04-19T08:49:28
2017-04-19T08:49:28
34,445,463
0
0
null
false
2017-02-24T11:18:56
2015-04-23T09:00:16
2016-11-17T13:26:13
2017-02-24T11:18:56
451
0
0
0
Java
null
null
package no.npolar.data.api; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import no.npolar.data.api.util.APIUtil; /** * A contributor is typically an author, but can have other roles as well. * <p> * This class is also the base class for others, e.g. * {@link PublicationContributor}. * <p> * Note that a contributor is not necessarily a person - organisations can also * be contributors. * * @author Paul-Inge Flakstad, Norwegian Polar Institute */ public class Contributor implements Comparable<Contributor> { /** The ID, like "john.doe" or "npolar.no". */ protected String id = null; /** The (localized) name, like "John Doe" or "Norwegian Polar Institute". */ protected String name = null; /** The last name, like "Doe". */ protected String lastName = null; /** The first name, like "John". */ protected String firstName = null; /** The organisation name(s), like "Norwegian Polar Institute". */ protected String organisation = null; /** Holds the contributor's roles. */ protected List<String> roles = null; /** * Creates a new, blank contributor. */ public Contributor() { this(null); } /** * Creates a new contributor by invoking the main constructor, passing the * given info. * * @param id The ID, like "npolar.no" or "john.doe". */ public Contributor(String id) { this(id, null); } /** * Creates a new contributor by invoking the main constructor, passing the * given info. * * @param id The ID, like "npolar.no" or "john.doe". * @param name The name, like "Norwegian Polar Institute" or "John Doe". */ public Contributor(String id, String name) { this(id, name, null, null, null); } /** * Creates a new contributor by invoking the main constructor, passing the * given info. * * @param id The ID, e.g. "npolar.no" or "john.doe". * @param firstName The (person's) first name, like "John". * @param lastName The (person's) last name, like "Doe". */ public Contributor(String id, String firstName, String lastName) { this(id, null, firstName, lastName, null); } /** * Creates a new contributor by invoking the main constructor, passing the * given info. * * @param id The ID, e.g. "npolar.no" or "john.doe". * @param firstName The (person's) first name, like "John". * @param lastName The (person's) last name, like "Doe". * @param organisation The organisation name, like "Norwegian Polar Institute". * @see #Contributor(java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String) */ public Contributor(String id, String firstName, String lastName, String organisation) { this(id, null, firstName, lastName, organisation); } /** * Main constructor. * <p> * Only the ID is required. All other arguments that are not passed into * this method will will be set as best guesses, see {@link #init()}. * <p> * For example, if the first and last name is set, but not the name, then * the name is set based on the first and last name. * * @param id The ID, like "npolar.no" or "john.doe". * @param name The name, like "Norwegian Polar Institute" or "John Doe". * @param firstName The (person's) first name, like "John". * @param lastName The (person's) last name, like "Doe". * @param organisation The organisation name, like "Norwegian Polar Institute". */ public Contributor(String id, String name, String firstName, String lastName, String organisation) { this.id = id; this.name = name; this.firstName = firstName; this.lastName = lastName; this.organisation = organisation; init(); } /** * Initializes the name and ID. */ private void init() { initName(); initId(); } /** * Initializes the name, making sure it is non-null. * <p> * The name can take on many values. In order of priority: * <ul> * <li>The name</li> * <li>[first name] [last name] (or just one of the two)</li> * <li>The organisation</li> * <li>The ID</li> * </ul> */ private void initName() { if (name == null) { if (firstName != null || lastName != null) { name = getFirstName(); if (getLastName().isEmpty()) { name += name.isEmpty() ? "" : " "; name += getLastName(); } } else if (organisation != null) { name = organisation; } else { // Final fallback name = id; } } else if (organisation == null) { // "name" was set ... if (firstName == null && lastName == null) { // ...but not personal names => assume "name" was name of org. organisation = name; } } } /** * Initializes the ID, making sure it is non-null. * <p> * The ID, if missing, will take on the value of the name. If that is also * missing, the ID will take on a fallback "unknown" value. */ private void initId() { if (id == null) { if (name != null) { id = name; } } if (id == null) { id = "[UNKNOWN ID]"; } } /** * Gets the name. * <p> * The name can be many things; see {@link #initName()}. * * @return The name. */ public String getName() { return name; } /** * Gets the contributor's name, in an URL-friendly form. * <p> * The returned string will be in the form "[first name].[last name]". * * @return the contributor's name, in an URL-friendly form. * @see APIUtil#toURLFriendlyForm(java.lang.String) */ public String getNameURLFriendly() { return APIUtil.toURLFriendlyForm(getName()); } /** * Gets the ID, or an empty string if none. * * @return The ID. */ public String getId() { return id == null ? "" : id; } /** * Gets the last name, or an empty string if none. * * @return The last name. */ public String getLastName() { return lastName == null ? "" : lastName; } /** * Gets the first name, or an empty string if none. * * @return The first name. */ public String getFirstName() { return firstName == null ? "" : firstName; } /** * Gets the organisation, or an empty string if none. * * @return The organisation. */ public String getOrganisation() { return organisation == null ? "" : organisation; } /** * Sets the organisation. * * @param organisation The organisation to set. * @return This instance, updated. */ public Contributor setOrganization(String organisation) { this.organisation = organisation; return this; } /** * Checks if this contributor has an organisation set. * * @return <code>true</code> if this contributor has an organisation set, <code>false</code> if not. */ public boolean hasOrganisation() { return organisation != null && !getOrganisation().isEmpty(); } /** * Checks if this contributor has an ID set. * * @return <code>true</code> if this contributor has an ID set, <code>false</code> if not. */ public boolean hasId() { return id != null && !id.isEmpty(); } /** * Checks if this contributor is assigned the given role. * * @param role The role to check for. * @return <code>true</code> if this contributor is assigned the given role, <code>false</code> if not. */ public boolean hasRole(String role) { return roles.contains(role); } /** * Checks if this contributor is assigned only the given role, and no other * role. * * @param role The role to check for. * @return <code>true</code> if this contributor is assigned only the given role, <code>false</code> if not. */ public boolean hasRoleOnly(String role) { return roles.size() == 1 && roles.contains(role); } /** * Adds the given role for this contributor. * <p> * Every role is assigned only once. If the contributor was already assigned * the given role, no change is made. * * @param role The role to add. * @return The list of roles for this contributor, including the given role. */ protected final List<String> addRole(String role) { if (roles == null) { roles = new ArrayList<String>(1); } if (!roles.contains(role)) { roles.add(role); } return roles; } /** * Adds the given roles for this contributor. * * @see #addRole(String) * @param roles A list containing all roles to add. * @return The list of roles for this contributor, after this method has finished modifying it. */ public List<String> addRoles(List<String> roles) { Iterator<String> i = roles.iterator(); while (i.hasNext()) { this.addRole(i.next()); } return roles; } /** * Gets all roles for this contributor. * * @return The list of roles for this contributor. */ public List<String> getRoles() { return roles; } /** * Returns this contributor's name. * * @return This contributor's name. */ @Override public String toString() { return name; } /** * Gets the hash code for this instance. * <p> * The return value is the hash code of a combination of the return values * from {@link #getName()} and {@link #getId()}. * * @return The hash code for this instance. */ @Override public int hashCode() { return getId().concat(getName()).hashCode(); } /** * Checks for equality on getName() and getId() return values. * * @param that The Contributor to compare with. * @return <code>true</code> if both instances share the same name and ID, <code>false</code> otherwise. */ @Override public boolean equals(Object that) { if (!(that instanceof Contributor)) { return false; } return this.getName().equals(((Contributor)that).getName()) && this.getId().equals(((Contributor)that).getId()); } /** * Compares by comparing each instance's {@link #getName()} return value. * * @param that The Contributor to compare with. * @return A comparison via the {@link #getName()} method. */ @Override public int compareTo(Contributor that) { return this.getName().compareTo( that.getName() ); } }
UTF-8
Java
11,290
java
Contributor.java
Java
[ { "context": "tions can also \n * be contributors.\n * \n * @author Paul-Inge Flakstad, Norwegian Polar Institute\n */\npublic class Contr", "end": 465, "score": 0.9998977780342102, "start": 447, "tag": "NAME", "value": "Paul-Inge Flakstad" }, { "context": "parable<Contributor> {\n \n /** The ID, like \"john.doe\" or \"npolar.no\". */\n protected String id = nul", "end": 594, "score": 0.9934471249580383, "start": 586, "tag": "USERNAME", "value": "john.doe" }, { "context": " = null;\n \n /** The (localized) name, like \"John Doe\" or \"Norwegian Polar Institute\". */\n protected", "end": 696, "score": 0.999872088432312, "start": 688, "tag": "NAME", "value": "John Doe" }, { "context": "ng name = null;\n \n /** The last name, like \"Doe\". */\n protected String lastName = null;\n \n ", "end": 804, "score": 0.9998825192451477, "start": 801, "tag": "NAME", "value": "Doe" }, { "context": "stName = null;\n \n /** The first name, like \"John\". */\n protected String firstName = null;\n \n", "end": 887, "score": 0.9998699426651001, "start": 883, "tag": "NAME", "value": "John" }, { "context": " * \n * @param id The ID, like \"npolar.no\" or \"john.doe\".\n */\n public Contributor(String id) {\n ", "end": 1428, "score": 0.9873341917991638, "start": 1420, "tag": "USERNAME", "value": "john.doe" }, { "context": " * \n * @param id The ID, like \"npolar.no\" or \"john.doe\".\n * @param name The name, like \"Norwegian Po", "end": 1679, "score": 0.9908713698387146, "start": 1671, "tag": "USERNAME", "value": "john.doe" }, { "context": "me The name, like \"Norwegian Polar Institute\" or \"John Doe\".\n */\n public Contributor(String id, Strin", "end": 1756, "score": 0.9998680949211121, "start": 1748, "tag": "NAME", "value": "John Doe" }, { "context": " * \n * @param id The ID, e.g. \"npolar.no\" or \"john.doe\".\n * @param firstName The (person's) first na", "end": 2038, "score": 0.9937239289283752, "start": 2030, "tag": "USERNAME", "value": "john.doe" }, { "context": "@param firstName The (person's) first name, like \"John\".\n * @param lastName The (person's) last name", "end": 2102, "score": 0.9998310208320618, "start": 2098, "tag": "NAME", "value": "John" }, { "context": "* @param lastName The (person's) last name, like \"Doe\".\n */\n public Contributor(String id, Strin", "end": 2163, "score": 0.9997878074645996, "start": 2160, "tag": "NAME", "value": "Doe" }, { "context": " * \n * @param id The ID, e.g. \"npolar.no\" or \"john.doe\".\n * @param firstName The (person's) first na", "end": 2476, "score": 0.992624044418335, "start": 2468, "tag": "USERNAME", "value": "john.doe" }, { "context": "@param firstName The (person's) first name, like \"John\".\n * @param lastName The (person's) last name", "end": 2540, "score": 0.9998244047164917, "start": 2536, "tag": "NAME", "value": "John" }, { "context": "* @param lastName The (person's) last name, like \"Doe\".\n * @param organisation The organisation nam", "end": 2601, "score": 0.9997923970222473, "start": 2598, "tag": "NAME", "value": "Doe" }, { "context": ")\n */\n public Contributor(String id, String firstName, String lastName, String organisation) {\n ", "end": 2861, "score": 0.7642983198165894, "start": 2852, "tag": "NAME", "value": "firstName" }, { "context": "ic Contributor(String id, String firstName, String lastName, String organisation) {\n this(id, null, fi", "end": 2878, "score": 0.7640425562858582, "start": 2870, "tag": "NAME", "value": "lastName" }, { "context": "ame, String organisation) {\n this(id, null, firstName, lastName, organisation);\n }\n \n /**\n ", "end": 2935, "score": 0.9419542551040649, "start": 2926, "tag": "NAME", "value": "firstName" }, { "context": " organisation) {\n this(id, null, firstName, lastName, organisation);\n }\n \n /**\n * Main co", "end": 2945, "score": 0.8010693788528442, "start": 2937, "tag": "NAME", "value": "lastName" }, { "context": " * \n * @param id The ID, like \"npolar.no\" or \"john.doe\".\n * @param name The name, like \"Norwegian Po", "end": 3378, "score": 0.9559776186943054, "start": 3370, "tag": "USERNAME", "value": "john.doe" }, { "context": "me The name, like \"Norwegian Polar Institute\" or \"John Doe\".\n * @param firstName The (person's) first na", "end": 3455, "score": 0.9997247457504272, "start": 3447, "tag": "NAME", "value": "John Doe" }, { "context": "@param firstName The (person's) first name, like \"John\".\n * @param lastName The (person's) last name", "end": 3519, "score": 0.9998312592506409, "start": 3515, "tag": "NAME", "value": "John" }, { "context": "* @param lastName The (person's) last name, like \"Doe\".\n * @param organisation The organisation nam", "end": 3580, "score": 0.9998121857643127, "start": 3577, "tag": "NAME", "value": "Doe" }, { "context": " public Contributor(String id, String name, String firstName, String lastName, String organisation) {\n ", "end": 3738, "score": 0.8937955498695374, "start": 3729, "tag": "NAME", "value": "firstName" }, { "context": "r(String id, String name, String firstName, String lastName, String organisation) {\n this.id = id;\n ", "end": 3755, "score": 0.7456523776054382, "start": 3747, "tag": "NAME", "value": "lastName" }, { "context": "this.name = name; \n this.firstName = firstName;\n this.lastName = lastName; \n ", "end": 3870, "score": 0.9985009431838989, "start": 3861, "tag": "NAME", "value": "firstName" }, { "context": "his.firstName = firstName;\n this.lastName = lastName; \n this.organisation = organisation", "end": 3904, "score": 0.9939405918121338, "start": 3896, "tag": "NAME", "value": "lastName" } ]
null
[]
package no.npolar.data.api; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import no.npolar.data.api.util.APIUtil; /** * A contributor is typically an author, but can have other roles as well. * <p> * This class is also the base class for others, e.g. * {@link PublicationContributor}. * <p> * Note that a contributor is not necessarily a person - organisations can also * be contributors. * * @author <NAME>, Norwegian Polar Institute */ public class Contributor implements Comparable<Contributor> { /** The ID, like "john.doe" or "npolar.no". */ protected String id = null; /** The (localized) name, like "<NAME>" or "Norwegian Polar Institute". */ protected String name = null; /** The last name, like "Doe". */ protected String lastName = null; /** The first name, like "John". */ protected String firstName = null; /** The organisation name(s), like "Norwegian Polar Institute". */ protected String organisation = null; /** Holds the contributor's roles. */ protected List<String> roles = null; /** * Creates a new, blank contributor. */ public Contributor() { this(null); } /** * Creates a new contributor by invoking the main constructor, passing the * given info. * * @param id The ID, like "npolar.no" or "john.doe". */ public Contributor(String id) { this(id, null); } /** * Creates a new contributor by invoking the main constructor, passing the * given info. * * @param id The ID, like "npolar.no" or "john.doe". * @param name The name, like "Norwegian Polar Institute" or "<NAME>". */ public Contributor(String id, String name) { this(id, name, null, null, null); } /** * Creates a new contributor by invoking the main constructor, passing the * given info. * * @param id The ID, e.g. "npolar.no" or "john.doe". * @param firstName The (person's) first name, like "John". * @param lastName The (person's) last name, like "Doe". */ public Contributor(String id, String firstName, String lastName) { this(id, null, firstName, lastName, null); } /** * Creates a new contributor by invoking the main constructor, passing the * given info. * * @param id The ID, e.g. "npolar.no" or "john.doe". * @param firstName The (person's) first name, like "John". * @param lastName The (person's) last name, like "Doe". * @param organisation The organisation name, like "Norwegian Polar Institute". * @see #Contributor(java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String) */ public Contributor(String id, String firstName, String lastName, String organisation) { this(id, null, firstName, lastName, organisation); } /** * Main constructor. * <p> * Only the ID is required. All other arguments that are not passed into * this method will will be set as best guesses, see {@link #init()}. * <p> * For example, if the first and last name is set, but not the name, then * the name is set based on the first and last name. * * @param id The ID, like "npolar.no" or "john.doe". * @param name The name, like "Norwegian Polar Institute" or "<NAME>". * @param firstName The (person's) first name, like "John". * @param lastName The (person's) last name, like "Doe". * @param organisation The organisation name, like "Norwegian Polar Institute". */ public Contributor(String id, String name, String firstName, String lastName, String organisation) { this.id = id; this.name = name; this.firstName = firstName; this.lastName = lastName; this.organisation = organisation; init(); } /** * Initializes the name and ID. */ private void init() { initName(); initId(); } /** * Initializes the name, making sure it is non-null. * <p> * The name can take on many values. In order of priority: * <ul> * <li>The name</li> * <li>[first name] [last name] (or just one of the two)</li> * <li>The organisation</li> * <li>The ID</li> * </ul> */ private void initName() { if (name == null) { if (firstName != null || lastName != null) { name = getFirstName(); if (getLastName().isEmpty()) { name += name.isEmpty() ? "" : " "; name += getLastName(); } } else if (organisation != null) { name = organisation; } else { // Final fallback name = id; } } else if (organisation == null) { // "name" was set ... if (firstName == null && lastName == null) { // ...but not personal names => assume "name" was name of org. organisation = name; } } } /** * Initializes the ID, making sure it is non-null. * <p> * The ID, if missing, will take on the value of the name. If that is also * missing, the ID will take on a fallback "unknown" value. */ private void initId() { if (id == null) { if (name != null) { id = name; } } if (id == null) { id = "[UNKNOWN ID]"; } } /** * Gets the name. * <p> * The name can be many things; see {@link #initName()}. * * @return The name. */ public String getName() { return name; } /** * Gets the contributor's name, in an URL-friendly form. * <p> * The returned string will be in the form "[first name].[last name]". * * @return the contributor's name, in an URL-friendly form. * @see APIUtil#toURLFriendlyForm(java.lang.String) */ public String getNameURLFriendly() { return APIUtil.toURLFriendlyForm(getName()); } /** * Gets the ID, or an empty string if none. * * @return The ID. */ public String getId() { return id == null ? "" : id; } /** * Gets the last name, or an empty string if none. * * @return The last name. */ public String getLastName() { return lastName == null ? "" : lastName; } /** * Gets the first name, or an empty string if none. * * @return The first name. */ public String getFirstName() { return firstName == null ? "" : firstName; } /** * Gets the organisation, or an empty string if none. * * @return The organisation. */ public String getOrganisation() { return organisation == null ? "" : organisation; } /** * Sets the organisation. * * @param organisation The organisation to set. * @return This instance, updated. */ public Contributor setOrganization(String organisation) { this.organisation = organisation; return this; } /** * Checks if this contributor has an organisation set. * * @return <code>true</code> if this contributor has an organisation set, <code>false</code> if not. */ public boolean hasOrganisation() { return organisation != null && !getOrganisation().isEmpty(); } /** * Checks if this contributor has an ID set. * * @return <code>true</code> if this contributor has an ID set, <code>false</code> if not. */ public boolean hasId() { return id != null && !id.isEmpty(); } /** * Checks if this contributor is assigned the given role. * * @param role The role to check for. * @return <code>true</code> if this contributor is assigned the given role, <code>false</code> if not. */ public boolean hasRole(String role) { return roles.contains(role); } /** * Checks if this contributor is assigned only the given role, and no other * role. * * @param role The role to check for. * @return <code>true</code> if this contributor is assigned only the given role, <code>false</code> if not. */ public boolean hasRoleOnly(String role) { return roles.size() == 1 && roles.contains(role); } /** * Adds the given role for this contributor. * <p> * Every role is assigned only once. If the contributor was already assigned * the given role, no change is made. * * @param role The role to add. * @return The list of roles for this contributor, including the given role. */ protected final List<String> addRole(String role) { if (roles == null) { roles = new ArrayList<String>(1); } if (!roles.contains(role)) { roles.add(role); } return roles; } /** * Adds the given roles for this contributor. * * @see #addRole(String) * @param roles A list containing all roles to add. * @return The list of roles for this contributor, after this method has finished modifying it. */ public List<String> addRoles(List<String> roles) { Iterator<String> i = roles.iterator(); while (i.hasNext()) { this.addRole(i.next()); } return roles; } /** * Gets all roles for this contributor. * * @return The list of roles for this contributor. */ public List<String> getRoles() { return roles; } /** * Returns this contributor's name. * * @return This contributor's name. */ @Override public String toString() { return name; } /** * Gets the hash code for this instance. * <p> * The return value is the hash code of a combination of the return values * from {@link #getName()} and {@link #getId()}. * * @return The hash code for this instance. */ @Override public int hashCode() { return getId().concat(getName()).hashCode(); } /** * Checks for equality on getName() and getId() return values. * * @param that The Contributor to compare with. * @return <code>true</code> if both instances share the same name and ID, <code>false</code> otherwise. */ @Override public boolean equals(Object that) { if (!(that instanceof Contributor)) { return false; } return this.getName().equals(((Contributor)that).getName()) && this.getId().equals(((Contributor)that).getId()); } /** * Compares by comparing each instance's {@link #getName()} return value. * * @param that The Contributor to compare with. * @return A comparison via the {@link #getName()} method. */ @Override public int compareTo(Contributor that) { return this.getName().compareTo( that.getName() ); } }
11,272
0.56333
0.563153
380
28.713158
25.953995
114
false
false
0
0
0
0
0
0
0.365789
false
false
7
ebaf34dcc08afa7377aa6c42522d8d2db3de85b9
28,475,633,222,349
43fa1d0be3e45ac897f7b44056bb634d597632a8
/E-bike rental system/src/test/java/com/team15/ebrs/TestTrip.java
ffa1146fc29c4b7af5d23c02207ccb52230ee114
[]
no_license
hermar98/e-bike-rental-system
https://github.com/hermar98/e-bike-rental-system
bba732da160dd6b25168d9ff18da2bffab61e1ad
b4b2457166c5504033ccc1f253fdbb186a2677f4
refs/heads/main
2023-02-15T09:14:11.105000
2021-01-15T12:51:00
2021-01-15T12:51:00
329,889,604
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package test.java.com.team15.ebrs; import main.java.com.team15.ebrs.dao.BikeDAO; import main.java.com.team15.ebrs.dao.DockingStationDAO; import main.java.com.team15.ebrs.data.Bike; import main.java.com.team15.ebrs.data.BikeData; import main.java.com.team15.ebrs.data.DockingStation; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.Random; import main.java.com.team15.ebrs.dao.TripDAO; import main.java.com.team15.ebrs.data.Customer; import main.java.com.team15.ebrs.util.TripManager; public class TestTrip { TripManager tManager; Random rn = new Random(); Bike bike; BikeData bikeData; BikeDAO bikeDAO = new BikeDAO(); TripDAO tDAO = new TripDAO(); DockingStationDAO stationDAO = new DockingStationDAO(); DockingStation prevStation; DockingStation randomStation; public TestTrip (Bike bike, Customer customer){ tManager = new TripManager(bike, customer); this.bike = bike; ArrayList<DockingStation> stations = stationDAO.getAllDockingStations(); for (int i = 0; i < stations.size(); i++) { if(bike.getStationId()==stations.get(i).getStationId()){ prevStation = stations.get(i); break; }else{ prevStation = null; } } randomStation = findRandomStation(); } public void startSimulation(){ tManager.startTrip(); } //Cycling, coords & charge lvl every minute public DockingStation simulateCycling () { //System.out.println(bike); bikeData = bikeDAO.getRecentData(bike); //System.out.println(bikeData); bikeData.setDateTime(LocalDateTime.now()); double latCoords = bikeData.getLatitude(); double longCoords = bikeData.getLongitude(); //powerusage down double d = 1000; double powerUsage = (Math.round(((Math.random()*20+1)/10)*d))/d; bikeData.setChargingLvl((bikeData.getChargingLvl()-powerUsage)); //new random coords double randomMovementLat = (Math.random()*1)/200; //100 standard double randomMovementLong = (Math.random()*1)/200; double closeEnough = 0.002; double diffLat = randomStation.getCoordinateLat()-bikeData.getLatitude(); double diffLong = randomStation.getCoordinateLng()-bikeData.getLongitude(); if(Math.abs(diffLat)>closeEnough) { if (diffLat > 0) { latCoords += randomMovementLat; } else if (diffLat < 0) { latCoords -= randomMovementLat; } } bikeData.setLatitude(latCoords); if(Math.abs(diffLong)>closeEnough) { if (diffLong > 0) { longCoords += randomMovementLong; } else if (diffLong < 0) { longCoords -= randomMovementLong; } } bikeData.setLongitude(longCoords); //Add entry to database tManager.updateCoordinates(bikeData); System.out.println("Bikeid: "+ bike.getBikeId() +"\ndiffLat: " + diffLat + "\ndiffLong: " + diffLong); System.out.println("Going to: " + randomStation.getStationName() + " ID: " + randomStation.getStationId()); if(Math.abs(diffLat)<=closeEnough && Math.abs(diffLong)<=closeEnough){ return simulateCheckIn(); } return null; } //Checkin Power Usage UP set Station ID public DockingStation simulateCheckIn () { tManager.endTrip(randomStation); return randomStation; } public void chargeBike(){ double STANDARD_CHARGING_VALUE = 1.3; double chargingLvl = bikeData.getChargingLvl() + STANDARD_CHARGING_VALUE; if(chargingLvl > 100){ bikeData.setChargingLvl(100); }else{ bikeData.setChargingLvl(chargingLvl); } bikeData.setDateTime(LocalDateTime.now()); bikeDAO.addBikeData(bikeData, tManager.getTripId()); } private DockingStation findRandomStation() { ArrayList<DockingStation> stations = stationDAO.getAllDockingStations(); int rNumber = rn.nextInt(stations.size()); if(prevStation!=null) { //System.out.println("INNE I IF"); while (stations.get(rNumber).getStationId() == prevStation.getStationId()) { System.out.println("INNE I WHILE"); rNumber = rn.nextInt(stations.size()); } } return stations.get(rNumber); } public static void main (String [] args) { BikeDAO bd = new BikeDAO(); //TestTrip trip = new TestTrip(bd.getBike(1)); //System.out.println(trip.bikeCycling()); } }
UTF-8
Java
4,740
java
TestTrip.java
Java
[]
null
[]
package test.java.com.team15.ebrs; import main.java.com.team15.ebrs.dao.BikeDAO; import main.java.com.team15.ebrs.dao.DockingStationDAO; import main.java.com.team15.ebrs.data.Bike; import main.java.com.team15.ebrs.data.BikeData; import main.java.com.team15.ebrs.data.DockingStation; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.Random; import main.java.com.team15.ebrs.dao.TripDAO; import main.java.com.team15.ebrs.data.Customer; import main.java.com.team15.ebrs.util.TripManager; public class TestTrip { TripManager tManager; Random rn = new Random(); Bike bike; BikeData bikeData; BikeDAO bikeDAO = new BikeDAO(); TripDAO tDAO = new TripDAO(); DockingStationDAO stationDAO = new DockingStationDAO(); DockingStation prevStation; DockingStation randomStation; public TestTrip (Bike bike, Customer customer){ tManager = new TripManager(bike, customer); this.bike = bike; ArrayList<DockingStation> stations = stationDAO.getAllDockingStations(); for (int i = 0; i < stations.size(); i++) { if(bike.getStationId()==stations.get(i).getStationId()){ prevStation = stations.get(i); break; }else{ prevStation = null; } } randomStation = findRandomStation(); } public void startSimulation(){ tManager.startTrip(); } //Cycling, coords & charge lvl every minute public DockingStation simulateCycling () { //System.out.println(bike); bikeData = bikeDAO.getRecentData(bike); //System.out.println(bikeData); bikeData.setDateTime(LocalDateTime.now()); double latCoords = bikeData.getLatitude(); double longCoords = bikeData.getLongitude(); //powerusage down double d = 1000; double powerUsage = (Math.round(((Math.random()*20+1)/10)*d))/d; bikeData.setChargingLvl((bikeData.getChargingLvl()-powerUsage)); //new random coords double randomMovementLat = (Math.random()*1)/200; //100 standard double randomMovementLong = (Math.random()*1)/200; double closeEnough = 0.002; double diffLat = randomStation.getCoordinateLat()-bikeData.getLatitude(); double diffLong = randomStation.getCoordinateLng()-bikeData.getLongitude(); if(Math.abs(diffLat)>closeEnough) { if (diffLat > 0) { latCoords += randomMovementLat; } else if (diffLat < 0) { latCoords -= randomMovementLat; } } bikeData.setLatitude(latCoords); if(Math.abs(diffLong)>closeEnough) { if (diffLong > 0) { longCoords += randomMovementLong; } else if (diffLong < 0) { longCoords -= randomMovementLong; } } bikeData.setLongitude(longCoords); //Add entry to database tManager.updateCoordinates(bikeData); System.out.println("Bikeid: "+ bike.getBikeId() +"\ndiffLat: " + diffLat + "\ndiffLong: " + diffLong); System.out.println("Going to: " + randomStation.getStationName() + " ID: " + randomStation.getStationId()); if(Math.abs(diffLat)<=closeEnough && Math.abs(diffLong)<=closeEnough){ return simulateCheckIn(); } return null; } //Checkin Power Usage UP set Station ID public DockingStation simulateCheckIn () { tManager.endTrip(randomStation); return randomStation; } public void chargeBike(){ double STANDARD_CHARGING_VALUE = 1.3; double chargingLvl = bikeData.getChargingLvl() + STANDARD_CHARGING_VALUE; if(chargingLvl > 100){ bikeData.setChargingLvl(100); }else{ bikeData.setChargingLvl(chargingLvl); } bikeData.setDateTime(LocalDateTime.now()); bikeDAO.addBikeData(bikeData, tManager.getTripId()); } private DockingStation findRandomStation() { ArrayList<DockingStation> stations = stationDAO.getAllDockingStations(); int rNumber = rn.nextInt(stations.size()); if(prevStation!=null) { //System.out.println("INNE I IF"); while (stations.get(rNumber).getStationId() == prevStation.getStationId()) { System.out.println("INNE I WHILE"); rNumber = rn.nextInt(stations.size()); } } return stations.get(rNumber); } public static void main (String [] args) { BikeDAO bd = new BikeDAO(); //TestTrip trip = new TestTrip(bd.getBike(1)); //System.out.println(trip.bikeCycling()); } }
4,740
0.619198
0.607384
143
32.146854
24.851435
115
false
false
0
0
0
0
0
0
0.538462
false
false
7
8647b6bfc9f832a98a93b82b7489f5e825e32e54
29,180,007,872,358
10440971d16de83e51ea012694912ca8ca9afd3b
/Initial Code SMA 2013-2014/src/sma/ScoutAgent.java
85fa9d06c002e15127357e747562c4ca00179a26
[]
no_license
MarcBS/IMAS-Project
https://github.com/MarcBS/IMAS-Project
150e3d741ae73cdba592edc47f5a1206644bc96e
d1999cf99f9b9d02bb8913bc7a42c64faf7d1663
refs/heads/master
2016-09-06T17:11:44.816000
2014-01-17T18:32:39
2014-01-17T18:32:39
12,923,085
0
3
null
null
null
null
null
null
null
null
null
null
null
null
null
package sma; import java.awt.Point; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.PriorityQueue; import java.util.Queue; import java.util.Set; import java.util.Stack; import java.util.Random; import org.newdawn.slick.util.pathfinding.AStarPathFinder; import org.newdawn.slick.util.pathfinding.Path; import org.newdawn.slick.util.pathfinding.Path.Step; import jade.core.AID; import jade.core.Agent; import jade.core.behaviours.FSMBehaviour; import jade.core.behaviours.OneShotBehaviour; import jade.core.behaviours.SimpleBehaviour; import jade.domain.DFService; import jade.domain.FIPAException; import jade.domain.FIPANames.InteractionProtocol; import jade.domain.FIPAAgentManagement.DFAgentDescription; import jade.domain.FIPAAgentManagement.ServiceDescription; import jade.lang.acl.ACLMessage; import jade.lang.acl.UnreadableException; import sma.ScoutCoordinatorAgent.InitialSendToScout; import sma.ScoutCoordinatorAgent.RequestGameInfo; import sma.gui.LogPanel; import sma.ontology.AStar; import sma.ontology.AuxInfo; import sma.ontology.Cell; import sma.ontology.DelimitingZone; import sma.ontology.InfoAgent; import sma.ontology.InfoGame; public class ScoutAgent extends Agent { // Indicates if we want to show the debugging messages private boolean debugging = true; private boolean debuggingPatrolingPath = false; private AID scoutCoordinatorAgent; // array storing the not handled messages private MessagesList messagesQueue = new MessagesList(this); private AuxInfo auxInfo; private DelimitingZone patrolZone; // object describing the zone where the scout must patrol //Patrol path parameters private ArrayList<Boolean> visitedBuildings; private ArrayList<Point> buildings; private int noVisited; private ArrayList<Point> patrollPath; private int patrollPoint = 0; private boolean sign=true; private Point objectivePoint; private boolean patroling = false; private AID myAID; private HashMap<Integer, int[]> moviment = new HashMap<Integer, int[]>(); private final int NORT = 1, SUD = 2, EST = 3, WEST = 4; boolean has_collision = false, cantMove = false; int contrari_colisio = 0; private AID preference_over = null; private boolean followingOptimalPath = true; private Cell lastOptimalPoint = null; AStar astar; public ScoutAgent(){ super(); int[] N = {-1,0}, E={0,1}, S = {1,0}, W= {0,-1}; moviment.put(NORT, N); moviment.put(SUD, S); moviment.put(EST, E); moviment.put(WEST, W); } /** * A message is shown in the log area of the GUI * @param str String to show */ private void showMessage(String str) { LogPanel.showMessage(getLocalName() + ": " + str+"\n"); if(debugging) System.out.println(getLocalName() + ": " + str); } private void showMessageWithBoolean(Boolean b, String str) { if(b) System.out.println(getLocalName() + ": " + str); } protected void setup(){ this.myAID = getAID(); /**** Very Important Line (VIL) *********/ this.setEnabledO2ACommunication(true, 1); /****************************************/ // Register the agent to the DF ServiceDescription sd1 = new ServiceDescription(); sd1.setType(UtilsAgents.SCOUT_AGENT); sd1.setName(getLocalName()); sd1.setOwnership(UtilsAgents.OWNER); DFAgentDescription dfd = new DFAgentDescription(); dfd.addServices(sd1); dfd.setName(getAID()); try { DFService.register(this, dfd); showMessage("Scout Registered to the DF"); } catch (FIPAException e) { System.err.println(getLocalName() + " registration with DF " + "unsucceeded. Reason: " + e.getMessage()); doDelete(); } // move(); visitedBuildings = new ArrayList<Boolean>(); // search ScoutsCoordinatorAgent ServiceDescription searchCriterion = new ServiceDescription(); searchCriterion.setType(UtilsAgents.SCOUT_COORDINATOR_AGENT); this.scoutCoordinatorAgent = UtilsAgents.searchAgent(this, searchCriterion); // Finite State Machine FSMBehaviour fsm = new FSMBehaviour(this) { private static final long serialVersionUID = 1L; public int onEnd() { myAgent.doDelete(); return super.onEnd(); } }; // Behaviour to receive first AuxInfo and DelimitingZone where it will have to patrol. fsm.registerFirstState(new InitialRecieve(this, scoutCoordinatorAgent), "STATE_1"); // Behaviour to send the list of garbage positions that is has found in this turn. fsm.registerState(new SendGarbagePositions(this, scoutCoordinatorAgent), "STATE_2"); // Behaviour to receive AuxInfo for each turn. fsm.registerState(new RecieveGameInfo(this, scoutCoordinatorAgent), "STATE_3"); // Behaviour to decide where to move and send that information to the ScoutCoordinator fsm.registerState(new MoveAgent(this, scoutCoordinatorAgent), "STATE_4"); fsm.registerDefaultTransition("STATE_1", "STATE_2"); fsm.registerDefaultTransition("STATE_2", "STATE_4"); fsm.registerDefaultTransition("STATE_4", "STATE_3"); fsm.registerDefaultTransition("STATE_3", "STATE_2"); // Version 1 (Marc) Diria que no �s correcte /*fsm.registerDefaultTransition("STATE_1", "STATE_2"); fsm.registerDefaultTransition("STATE_2", "STATE_3"); fsm.registerDefaultTransition("STATE_4", "STATE_2"); fsm.registerDefaultTransition("STATE_3", "STATE_4");*/ addBehaviour(fsm); } /** * * @author David Sanchez Pinsach * Class that implements behavior for requesting game info (map) */ protected class InitialRecieve extends SimpleBehaviour { private AID receptor; private Agent a; public InitialRecieve (Agent a, AID r) { super(a); this.receptor = r; } @Override public void action() { // Make the request ACLMessage request = new ACLMessage(ACLMessage.REQUEST); request.clearAllReceiver(); request.addReceiver(receptor); request.setProtocol(InteractionProtocol.FIPA_REQUEST); showMessage("Connection STATE_1 between scout->scout coordinator: OK"); /*Reception of game info * * The protocol is in two steps: * 1. Sender sent an AGREE/FAILURE message * 2. Sender sent INFORM message containing the AuxInfo object */ boolean okInfo = false; while(!okInfo) { ACLMessage reply = messagesQueue.getMessage(); if (reply != null) { switch (reply.getPerformative()) { case ACLMessage.AGREE: showMessage("Recieved AGREE from "+reply.getSender()); break; case ACLMessage.INFORM: try { auxInfo = (AuxInfo) reply.getContentObject(); // Getting object with the information about the game showMessage("Receiving game info from "+receptor); } catch (UnreadableException e) { messagesQueue.add(reply); System.err.println(getLocalName() + " Recieved game info unsucceeded. Reason: " + e.getMessage()); } catch (ClassCastException e){ try { patrolZone = (DelimitingZone) reply.getContentObject(); astar = new AStar(auxInfo); showMessage("Receiving patrol zone from "+receptor); //if(this.getAgent().getName().equals("s0@192.168.1.130:1099/JADE")){ createPatrolPath(); //} // Send the cell ---> USLESS!!!! //ACLMessage reply2 = reply.createReply(); //reply2.setPerformative(ACLMessage.INFORM); //Cell c = null; try { AID myAID = this.myAgent.getAID(); //Cell c = auxInfo.getAgentCell(myAID); /** * Create the patrol zone with the bounds of the delimiting zone * of each agent. Add in arrayList of objective positions */ int x=(int) patrolZone.getUL().getX(); int y=(int) patrolZone.getUL().getY(); objectivePoint = checkInitialPosition(patrolZone.getUL()); // Useless.....?? //First movement Following the best position to the path /*Cell newC = getBestPositionToObjective(auxInfo.getMap(), c, new Cell(objectivePoint.x, objectivePoint.y)); if (newC == null) newC = getRandomPosition(auxInfo.getMap(), c); c = newC; //Or random //c = getRandomPosition(auxInfo.getMap(), c); reply2.setContentObject(c); //Return a new cell to scout coordinator*/ } catch (Exception e1) { //reply2.setPerformative(ACLMessage.FAILURE); System.err.println(e1.toString()); } //send(reply2); //showMessage("Sending the cell ["+c.getRow()+","+c.getColumn()+"] position to "+receptor); okInfo = true; } catch (UnreadableException e1) { messagesQueue.add(reply); System.err.println(getLocalName() + " Recieved objective postionunsucceeded. Reason: " + e.getMessage()); } //Getting the objective position } break; case ACLMessage.FAILURE: System.err.println(getLocalName() + " Recieved game info unsucceeded. Reason: Performative was FAILURE"); break; default: // Unexpected messages received must be added to the queue. messagesQueue.add(reply); break; } } } messagesQueue.endRetrieval(); } @Override public boolean done() { return true; } public int onEnd(){ showMessage("STATE_1 return OK, AuxInfo and DelimitingZone received."); return 0; } } /** * * @author Marc Bola���os Sol��� * Looks for any position around it with garbage and sends them to the ScoutsCoordinator. */ protected class SendGarbagePositions extends SimpleBehaviour { private AID receptor; private Agent a; public SendGarbagePositions (Agent a, AID r) { super(a); this.receptor = r; } @Override public void action() { // Finds garbage positions ArrayList garbageDiscoveries = checkScoutDiscoveries(); try { // Make the request ACLMessage request = new ACLMessage(ACLMessage.INFORM); request.clearAllReceiver(); request.setContentObject(garbageDiscoveries); request.addReceiver(receptor); request.setProtocol(InteractionProtocol.FIPA_REQUEST); send(request); showMessage("Connection STATE_2 between scout->scout coordinator: OK"); } catch (IOException e) { showMessage("Problem found when sending new discoveries."); } } @Override public boolean done() { return true; } public int onEnd(){ showMessage("STATE_2 return OK"); return 0; } } protected class MoveAgent extends SimpleBehaviour { private AID receptor; public MoveAgent(Agent a, AID r){ super(a); this.receptor = r; } private Cell moveNormally(){ AID myAID = this.myAgent.getAID(); Cell c = auxInfo.getAgentCell(myAID); int c_x = c.getRow(); int c_y = c.getColumn(); //Case when you don't have objective point if(objectivePoint==null){ //If you have not got a objective you will follow the patrolling path. Point patrollMovement= patrollPath.get(patrollPoint); //newPositionCell.addAgent(c.getAgent()); //Save infoagent to the new position showMessageWithBoolean(debuggingPatrolingPath, "Patrolling path"); c = checkIfPositionIsOccupied(auxInfo.getMap()[patrollMovement.x][patrollMovement.y],auxInfo.getMap(), c); //Update the pointer in the patrollPath if(sign){ patrollPoint++; }else{ patrollPoint--; } //Check if the agent arrives on the final o on the initially of the array of patroll path if((patrollPoint<0) || (patrollPoint==patrollPath.size())){ sign = !sign; // if(sign){ patrollPoint++; patrollPoint++; }else{ patrollPoint--; patrollPoint--; } } showMessage("Doing patrol."); //Case when you have objective point }else{ Point UL = checkInitialPosition(patrolZone.getUL()); // case when we had shifted from the correct path (for collision avoidance) if(((objectivePoint.getX() != UL.x) || (objectivePoint.getY() != UL.y)) && (objectivePoint.getX()==c_x) && (objectivePoint.getY()==c_y)){ if(!patroling){ objectivePoint = checkInitialPosition(patrolZone.getUL()); c = getBestPositionToObjective(auxInfo.getMap(), c, new Cell(objectivePoint.x, objectivePoint.y)); showMessage("Returning to path to UL position."); } else { Point patrollMovement = patrollPath.get(patrollPoint); c = checkIfPositionIsOccupied(auxInfo.getMap()[patrollMovement.x][patrollMovement.y],auxInfo.getMap(), c); //Check if the patroll movement is possible or not (if not occupated) // if((patrollMovement.x != c.getRow()) && (patrollMovement.y != c.getColumn())){ // objectivePoint = patrollMovement; //Save the patroll movement as to the new objective because you do not follow the patrol path. // } //Update the pointer in the patrollPath if(sign){ patrollPoint++; }else{ patrollPoint--; } if(patrollPoint<0 && patrollPoint>=patrollPath.size()){ showMessage("Changing the direction of the patrolling path"); sign = !sign; // if(sign){ patrollPoint++; }else{ patrollPoint--; } } objectivePoint = null; showMessage("Returning to patrol."); } } // we are on the corner UL else if((objectivePoint.getX() == UL.x) && (objectivePoint.getY() == UL.y) && (objectivePoint.getX()==c_x) && (objectivePoint.getY()==c_y)){ objectivePoint = null; Point patrollMovement = patrollPath.get(patrollPoint); c = checkIfPositionIsOccupied(auxInfo.getMap()[patrollMovement.x][patrollMovement.y],auxInfo.getMap(), c); //Check if the patroll movement is possible or not (if not occupated) if((patrollMovement.x != c.getRow()) && (patrollMovement.y != c.getColumn())){ objectivePoint = patrollMovement; //Save the patroll movement as to the new objective because you do not follow the patrol path. } //Update the pointer in the patrollPath if(sign){ patrollPoint++; }else{ patrollPoint--; } if(patrollPoint<0 && patrollPoint>=patrollPath.size()){ showMessage("Changing the direction of the patrolling path"); sign = !sign; // if(sign){ patrollPoint++; }else{ patrollPoint--; } } patroling = true; showMessage("Starting patrol."); }else{ c = getBestPositionToObjective(auxInfo.getMap(), c, new Cell(objectivePoint.x, objectivePoint.y)); showMessage("Doing getBestPositionToObjective."); } } if(c == null){ try { c = getRandomPosition(auxInfo.getMap(), auxInfo.getAgentCell(this.myAgent.getAID())); showMessage("Doing random movement."); } catch (IOException e) { e.printStackTrace(); } } return c; } public void action() { Cell actualPosition = auxInfo.getAgentCell(myAID); // Collision avoidance module Cell c = checkCollisions(auxInfo.getMap(), actualPosition); // Move normally if(c == null){ if(followingOptimalPath){ c = moveNormally(); } else { // we have recently been avoiding a collision followingOptimalPath = true; // modify the optimal path adding the steps to go back to the lastOptimalPoint!! objectivePoint = new Point(lastOptimalPoint.getRow(), lastOptimalPoint.getColumn()); c = moveNormally(); } } else if(followingOptimalPath) { // We are avoiding a collision and we where recently following the optimal path followingOptimalPath = false; lastOptimalPoint = auxInfo.getAgentCell(this.myAgent.getAID()); } // Send the cell ACLMessage reply2 = new ACLMessage(ACLMessage.REQUEST); reply2.clearAllReceiver(); reply2.addReceiver(receptor); //reply2.setProtocol(InteractionProtocol.FIPA_REQUEST); reply2.setPerformative(ACLMessage.INFORM); try { reply2.setContentObject(c); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } //Return a new cell to harvester coordinator send(reply2); showMessage("Sending the cell position to "+receptor); } @Override public boolean done() { return true; } public int onEnd(){ showMessage("STATE_4: Position sent."); return 0; } } /** * * @author David Sanchez Pinsach * Class that implements behavior for requesting game info (map) */ protected class RecieveGameInfo extends SimpleBehaviour { private AID receptor; private Agent a; public RecieveGameInfo (Agent a, AID r) { super(a); this.receptor = r; } @Override public void action() { // Make the request ACLMessage request = new ACLMessage(ACLMessage.REQUEST); request.clearAllReceiver(); request.addReceiver(receptor); request.setProtocol(InteractionProtocol.FIPA_REQUEST); showMessage("Connection STATE_3 between scout->scout coordinator: OK"); /*Reception of game info * * The protocol is in two steps: * 1. Sender sent an AGREE/FAILURE message * 2. Sender sent INFORM message containing the AuxInfo object */ boolean okInfo = false; while(!okInfo) { ACLMessage reply = messagesQueue.getMessage(); if (reply != null) { switch (reply.getPerformative()) { case ACLMessage.AGREE: showMessage("Recieved AGREE from "+reply.getSender()); break; case ACLMessage.INFORM: try { auxInfo = (AuxInfo) reply.getContentObject(); // Getting object with the information about the game showMessage("Receiving game info from "+receptor); okInfo = true; } catch (UnreadableException e) { messagesQueue.add(reply); System.err.println(getLocalName() + " Recieved game info unsucceeded. Reason: " + e.getMessage()); } catch(ClassCastException e){ messagesQueue.add(reply); System.err.println(getLocalName() + " Recieved game info unsucceeded. Reason: " + e.getMessage()); } break; case ACLMessage.FAILURE: System.err.println(getLocalName() + " Recieved game info unsucceeded. Reason: Performative was FAILURE"); break; default: // Unexpected messages received must be added to the queue. messagesQueue.add(reply); break; } } } messagesQueue.endRetrieval(); } @Override public boolean done() { return true; } public int onEnd(){ showMessage("STATE_3 return OK"); return 0; } } private Cell getBestPositionToObjective(Cell[][] cells, Cell actualPosition, Cell objectivePosition) { Cell newPosition = null; showMessage("I am in the cell = ["+actualPosition.getRow()+","+actualPosition.getColumn()+"]"); showMessage("I wanna go to the cell = ["+objectivePosition.getRow()+","+objectivePosition.getColumn()+"]"); newPosition = astar.shortestPath(cells, actualPosition, objectivePosition); if (newPosition == null) return null; int xi = newPosition.getRow(); int yi = newPosition.getColumn(); int maxRows = auxInfo.getMapRows(); int maxColumns = auxInfo.getMapColumns(); if (xi < maxRows && xi >= 0 && yi >= 0 && yi < maxColumns) { Cell position = cells[xi][yi]; if (position.getCellType() == Cell.STREET) { try { if (!newPosition.equals(actualPosition)) { newPosition.removeAgent(this.myAID); newPosition.addAgent(auxInfo.getInfoAgent(this.getAID())); } } catch (Exception e) { e.printStackTrace(); } } } //newPosition = checkIfPositionIsOccupied(newPosition, cells, actualPosition); return newPosition; } private Cell checkIfPositionIsOccupied(Cell newPosition, Cell[][] cells, Cell actualPosition) { if (!newPosition.equals(actualPosition)) { newPosition.removeAgent(this.getAID()); try { newPosition.addAgent(auxInfo.getInfoAgent(this.getAID())); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } return newPosition; } private Cell moveToFreePlace(Cell[][] cells, Cell actualPosition, Cell newPosition, InfoAgent infoAgent) { int x = actualPosition.getRow(); int y = actualPosition.getColumn(); int maxRows = auxInfo.getMapRows(); int maxColumns = auxInfo.getMapColumns(); int [][] nearPlaces = {{x+1,y},{x,y+1},{x-1,y},{x,y-1}}; List<int[]> intList = Arrays.asList(nearPlaces); ArrayList<int[]> arrayList = new ArrayList<int[]>(intList); int[] list = null; // Search a cell street while (arrayList.size() != 0) { Random a = new Random(); list = arrayList.remove(a.nextInt(arrayList.size())); int xi = list[0]; int yi = list[1]; if (xi < maxRows && xi >= 0 && yi >= 0 && yi < maxColumns) { Cell position = cells[xi][yi]; if (position.getCellType() == Cell.STREET) { if(!position.isThereAnAgent()){ return position; } } } } return actualPosition; } /** * Method to send a movement (A cell) * @param reply Recieve message * @param c Cell to send * @throws IOException Error of sending message */ public Cell getRandomPosition(Cell[][] map, Cell actualPosition) throws IOException{ Cell newPosition = null, positionToReturn = actualPosition; boolean trobat = false; showMessage("Checking random movement..."); int x=actualPosition.getRow(), y=actualPosition.getColumn(), z = 0, xi=0, yi=0; int maxRows=0, maxColumns=0; maxRows = auxInfo.getMapRows(); maxColumns = auxInfo.getMapColumns(); newPosition = actualPosition; int [][] posibleMovements = {{x+1,y},{x,y+1},{x-1,y},{x,y-1}}; List<int[]> intList = Arrays.asList(posibleMovements); ArrayList<int[]> arrayList = new ArrayList<int[]>(intList); int [] list = null; //Search a cell street while(arrayList.size()!=0 && !trobat) { z= auxInfo.getRandomPosition(arrayList.size()); list = arrayList.remove(z); xi = list[0]; yi = list[1]; if(xi < maxRows && xi >= 0 && yi >= 0 && yi < maxColumns) //Check if the position it's in the range of the map { newPosition = map[xi][yi]; if(Cell.STREET == newPosition.getCellType() ) //Check the limits of the map { try { showMessage("Position before moving "+"["+x+","+y+"]"); if (!newPosition.equals(actualPosition)) { newPosition.removeAgent(this.myAID); newPosition.addAgent(auxInfo.getInfoAgent(this.getAID())); //Save infoagent to the new position } positionToReturn = newPosition; //actualPosition.removeAgent(actualPosition.getAgent()); } catch (Exception e) { showMessage("ERROR: Failed to save the infoagent to the new position: "+e.getMessage()); } trobat = true; /* If there is a scout agent in front of */ /*if (newPosition.isThereAnAgent() && newPosition.getAgent().getAgentType() == InfoAgent.SCOUT) { Compare the ID's of each scout. The bigger one will be moved to desired position int h1 = auxInfo.getInfoAgent(this.scoutCoordinatorAgent).getAID().hashCode(); int h2 = newPosition.getAgent().getAID().hashCode(); if (h1 > h2) { try { showMessage("Position before moving "+"["+x+","+y+"]"); newPosition.addAgent(auxInfo.getInfoAgent(this.getAID())); //Save infoagent to the new position positionToReturn = newPosition; //actualPosition.removeAgent(actualPosition.getAgent()); } catch (Exception e) { showMessage("ERROR: Failed to save the infoagent to the new position: "+e.getMessage()); } trobat = true; } } If there is a harvester agent in front of else if (newPosition.isThereAnAgent() && newPosition.getAgent().getAgentType() == InfoAgent.HARVESTER) { // Do nothing. } If there is not an agent else { try { showMessage("Position before moving "+"["+x+","+y+"]"); newPosition.addAgent(auxInfo.getInfoAgent(this.getAID())); //Save infoagent to the new position positionToReturn = newPosition; //actualPosition.removeAgent(actualPosition.getAgent()); } catch (Exception e) { showMessage("ERROR: Failed to save the infoagent to the new position: "+e.getMessage()); } trobat = true; }*/ } } } return positionToReturn; } /** * Checks if any of the surrounding buildings there is any unit of garbage. * * @return ArrayList with the information about the garbage found with the following format * for each garbage cell (ArrayList): * - int row in the map * - int column in the map * - Cell datatype storing information about the content of the cell. */ private ArrayList checkScoutDiscoveries(){ showMessage("Checking New Discoveries..."); ArrayList garbageFound = new ArrayList(); Cell a = auxInfo.getAgentCell(this.getAID()); Cell b; // cell possibly with garbage Cell[][] map = auxInfo.getMap(); for (int i = 0; i < auxInfo.getMapRows(); i++){ for (int j = 0; j < auxInfo.getMapColumns(); j++){ b = map[i][j]; try { if(b.getCellType() == Cell.BUILDING && b.getGarbageUnits() > 0){ int x=a.getRow(); int y=a.getColumn(); int xb=b.getRow(); int yb=b.getColumn(); if (x>0){ if ((xb==x-1) && (yb==y)) {garbageFound.add(createGarbage(xb, yb, b));}// remove.add(b);} if ((y>0) && (xb==x-1) && (yb==y-1)) {garbageFound.add(createGarbage(xb, yb, b));}// remove.add(b);} if ((y<auxInfo.getMap()[x].length-1) && (xb==x-1) && (yb==y+1)) {garbageFound.add(createGarbage(xb, yb, b));}// remove.add(b);} } if (x<auxInfo.getMap().length-1){ if ((xb==x+1) && (yb==y)) {garbageFound.add(createGarbage(xb, yb, b));}// remove.add(b);} if ((y>0) && (xb==x+1) && (yb==y-1)) {garbageFound.add(createGarbage(xb, yb, b));}// remove.add(b);} if ((y<auxInfo.getMap()[x].length-1) && (xb==x+1) && (yb==y+1)) {garbageFound.add(createGarbage(xb, yb, b));}// remove.add(b);} } if ((y>0) && (xb==x) && (yb==y-1)) {garbageFound.add(createGarbage(xb, yb, b));}// remove.add(b);} if ((y<auxInfo.getMap()[x].length-1) && (xb==x) && (yb==y+1)) {garbageFound.add(createGarbage(xb, yb, b));}// remove.add(b);} } } catch (Exception e) { e.printStackTrace(); } } } //for (Cell r : remove) game.getBuildingsGarbage().remove(r); return garbageFound; } private ArrayList createGarbage(int x, int y, Cell b){ ArrayList garbage = new ArrayList(); garbage.add(x); garbage.add(y); garbage.add(b); return garbage; } private void createPatrolPath(){ showMessageWithBoolean(this.debuggingPatrolingPath,"Creating the patrolling path!"); Point UL = patrolZone.getUL(); //We will use the UL as initial point on the patroll path. buildings = patrolZone.getBuildingsPositions(); for(int i=0;i<buildings.size();i++){ visitedBuildings.add(false); } this.noVisited = visitedBuildings.size(); //Initial point of the path it is possible or not Point currentPos = checkInitialPosition(UL); showMessageWithBoolean(this.debuggingPatrolingPath,"Initial point:"+currentPos); patrollPath = new ArrayList<Point>(); //Points of patrol path Stack<Point> stack =new Stack<Point>(); Set<Point> cellsVisited = new HashSet<Point>(); stack.add(currentPos); //While not visit all the buildings while(this.noVisited!=0 && !stack.isEmpty()){ currentPos = stack.pop(); if(!cellsVisited.contains(currentPos)){ cellsVisited.add(currentPos); patrollPath.add(currentPos); int num = 0; for(Point p : getChilds(currentPos)){ if(!cellsVisited.contains(p)){ stack.push(p); num++; } } //Need backtracking because you already visited all of your neighbours if(num==0 && !stack.isEmpty()){ showMessageWithBoolean(this.debuggingPatrolingPath,"\nBacktracking is neeeded!"); Point objectivePos; objectivePos = stack.pop(); while(cellsVisited.contains(objectivePos)&&!stack.isEmpty()){ showMessageWithBoolean(this.debuggingPatrolingPath,"Pos->"+objectivePos); objectivePos = stack.pop(); } showMessageWithBoolean(this.debuggingPatrolingPath,"Current->"+currentPos); showMessageWithBoolean(this.debuggingPatrolingPath,"Objective->"+objectivePos); //Compute A* to the current position to the objective AStarPathFinder pathFinder = new AStarPathFinder(astar.map, 1000,false);// Diagonal movement not allowed false, true allowed Path path = pathFinder.findPath(null, currentPos.y, currentPos.x, objectivePos.y, objectivePos.x); for(int i=1; i<path.getLength()-1; i++){ Step s = path.getStep(i); Point p = new Point(s.getY(),s.getX()); patrollPath.add(p); showMessageWithBoolean(this.debuggingPatrolingPath,"Backtracking..."+p); } //Push the non visited position stack.add(objectivePos); showMessageWithBoolean(this.debuggingPatrolingPath,"Finish backtracking! \n"); } } showMessageWithBoolean(this.debuggingPatrolingPath,"The patrolling path was finished!"); } if(this.debuggingPatrolingPath){ showMessageWithBoolean(this.debuggingPatrolingPath,"Patrol path have been created!"); for(int i=0; i<this.visitedBuildings.size(); i++){ if(!this.visitedBuildings.get(i)) System.out.println(this.buildings.get(i)); } } if(this.debuggingPatrolingPath){ showMessageWithBoolean(this.debuggingPatrolingPath,"Printing the patrol path"); showMessageWithBoolean(this.debuggingPatrolingPath,"Path size"+patrollPath.size()); for(Point p : patrollPath){ showMessageWithBoolean(this.debuggingPatrolingPath,p.toString()); } showMessageWithBoolean(this.debuggingPatrolingPath,"Process finished!"); } patrollPath.remove(0); } /** * Check and correct if the initial point is or not a building * @param p Initial point * @return Return a correct initial point */ private Point checkInitialPosition(Point p){ Cell[][] map = auxInfo.getMap(); Cell c = map[p.x][p.y]; c.setColumn(p.y); c.setRow(p.x); int count = 0; while(c.getCellType()!=c.STREET){ c = map[p.x][p.y+count]; c.setColumn(p.y+count); c.setRow(p.x); count++; } return new Point(c.getRow(),c.getColumn()); } /** * Method to check the buildings around the current position * @param movements All the possible movements * @return Return the all the possible movements filtered */ private ArrayList<Point> checkBuilding(ArrayList<Point> movements){ Point b; Point UL = patrolZone.getUL(); Point BR = patrolZone.getBR(); Cell[][] map = auxInfo.getMap(); ArrayList<Point> possibleMovements = new ArrayList<Point>(); for(Point p : movements){ int i = 0; boolean found = false; while(i<buildings.size() && !found){ b = buildings.get(i); //Check if the point p is a building if((b.getX()==p.getX()) &&(b.getY()==p.getY())) found = true; else i++; } if(found){ if(!visitedBuildings.get(i)){ visitedBuildings.set(i, true); this.noVisited--; showMessageWithBoolean(this.debuggingPatrolingPath," Visiting->"+buildings.get(i)+" Num non visites->"+this.noVisited); } }else{ //Check if the movement it can be possible, it is in the delimited zone. if((p.x>=0)&&(p.y>=0)&&(p.x<auxInfo.getMapRows())&&(p.y<auxInfo.getMapColumns()) && (UL.getX()<=p.getX()) && (UL.getY()<=p.getY()) && (BR.getX()>=p.getX()) && (BR.getY()>=p.getY())){ //Check the cell type of the new movement is a street int type = map[p.x][p.y].getCellType(); if(Cell.STREET==type) possibleMovements.add(p); } } } return possibleMovements; } /** * Get the child cells of the current position * @param currentPos Current position * @return Return the possible movements of the childs of the current position */ private ArrayList<Point> getChilds(Point currentPos){ Point up, right, left, down; double x,y; ArrayList<Point> possibleMovements = new ArrayList<Point>(); x = currentPos.getX(); y = currentPos.getY(); //Move in the 4 possible directions up=new Point((int)currentPos.getX()-1,(int)currentPos.getY()); right=new Point((int)currentPos.getX(),(int)currentPos.getY()+1); left=new Point((int)currentPos.getX(),(int)currentPos.getY()-1); down=new Point((int)currentPos.getX()+1,(int)currentPos.getY()); //Remove the building in the list of no visited buildings. possibleMovements.add(up); possibleMovements.add(left); possibleMovements.add(right); possibleMovements.add(down); return checkBuilding(possibleMovements); } private int mapPosWithDirection(int[] pos, Cell actualPos) { int x = pos[0], y = pos[1], actual_x = actualPos.getRow(), actual_y = actualPos.getColumn(); int x_dif = actual_x - x; int y_dif = actual_y - y; if(actual_x > x && actual_y == y ) return this.NORT; if(actual_x < x && actual_y == y ) return this.SUD; if(actual_x == x && actual_y > y ) return this.WEST; if(actual_x == x && actual_y < y ) return this.EST; /*if (x_dif == 1 && y_dif == 0) return this.NORT; if (x_dif == 0 && y_dif == 1) return this.WEST; if (x_dif == -1 && y_dif == 0) return this.SUD; if ( x_dif == 0 && y_dif == -1) return this.EST; */ System.err.println("Position not correct"); return -1; } private int getOppositeDirection (int direction) { if (direction == this.NORT) return this.SUD; if (direction == this.EST) return this.WEST; if (direction == this.SUD) return this.NORT; if (direction == this.WEST) return this.EST; System.err.println("Direction not correct"); return -1; } /* * Return a Cell to move in order to avoid collitions. Return null when there not exist collisions. */ private Cell checkCollisions(Cell[][] map, Cell actualPosition) { Cell positionToReturn = null; if (!this.has_collision) { ArrayList<int[]> listColisions = detectCollision(map, actualPosition); if ( !listColisions.isEmpty()) { for (int[] col : listColisions) { int xi = col[0], yi = col[1]; InfoAgent other_agent = map[xi][yi].getAgent(); if (other_agent.hasCollision() && other_agent.getAID() != this.preference_over) { this.has_collision = true; this.preference_over = null; int other_direction = mapPosWithDirection(col, actualPosition); this.contrari_colisio = getOppositeDirection(other_direction); } else if (!applyPolitic(col, map) && !this.cantMove) { this.has_collision = true; this.preference_over = null; int other_direction = mapPosWithDirection(col, actualPosition); this.contrari_colisio = getOppositeDirection(other_direction); } else if (applyPolitic(col, map)) { this.preference_over = other_agent.getAID(); if (other_agent.cantMove()) { this.has_collision = true; this.preference_over = null; int other_direction = mapPosWithDirection(col, actualPosition); this.contrari_colisio = getOppositeDirection(other_direction); } } } } else { this.has_collision = false; this.contrari_colisio = -1; this.cantMove = false; } } else { ArrayList<int[]> listColisions = detectCollision(map, actualPosition); if ( listColisions.isEmpty()) { this.has_collision = false; this.contrari_colisio = -1; //this.cantMove = false; ??? } else if (!listColisions.isEmpty() && this.cantMove) { for (int[] col : listColisions) // Aquest for esta be???? { int xi = col[0], yi = col[1]; InfoAgent other_agent = map[xi][yi].getAgent(); this.has_collision = false; this.contrari_colisio = -1; this.preference_over = other_agent.getAID(); } } else if(!listColisions.isEmpty()) // if there is any collision { for (int[] col : listColisions) // for each collisions { int xi = col[0], yi = col[1]; InfoAgent other_agent = map[xi][yi].getAgent(); if (other_agent.cantMove()) // if the other agent can't move, then we have to give him priority { this.has_collision = true; this.preference_over = null; int other_direction = mapPosWithDirection(col, actualPosition); this.contrari_colisio = getOppositeDirection(other_direction); this.cantMove = true; } } } } // Let's decide where to move if (this.has_collision) { if (this.contrari_colisio == this.NORT || this.contrari_colisio == this.SUD) { int directionToMove; // Random movement to contrari direction Random r = new Random(); if ( r.nextInt(1) == 1 ) directionToMove = this.EST; else directionToMove = this.WEST; if (canMoveToCell(actualPosition, directionToMove, map)) { positionToReturn = map[ actualPosition.getRow() + moviment.get(directionToMove)[0] ] [actualPosition.getColumn() + moviment.get(directionToMove)[1]]; } else if ( canMoveToCell(actualPosition, getOppositeDirection(directionToMove), map) ) { directionToMove = getOppositeDirection(directionToMove); positionToReturn = map[ actualPosition.getRow() + moviment.get(directionToMove)[0] ] [actualPosition.getColumn() + moviment.get(directionToMove)[1]]; } // MOVE TO CONTRARI COLISIO else if ( canMoveToCell(actualPosition, contrari_colisio, map) ) { directionToMove = contrari_colisio; positionToReturn = map[ actualPosition.getRow() + moviment.get(directionToMove)[0] ] [actualPosition.getColumn() + moviment.get(directionToMove)[1]]; } // CAS EN QUE HI HA PARETS else if ( isSurroundedByWalls(actualPosition,map) ) { this.cantMove = true; positionToReturn = actualPosition; } } else if (this.contrari_colisio == this.EST || this.contrari_colisio == this.WEST) { int directionToMove; // Random movement to contrari direction Random r = new Random(); if ( r.nextInt(1) == 1 ) directionToMove = this.NORT; else directionToMove = this.SUD; if (canMoveToCell(actualPosition, directionToMove, map)) { positionToReturn = map[ actualPosition.getRow() + moviment.get(directionToMove)[0] ] [actualPosition.getColumn() + moviment.get(directionToMove)[1]]; } else if ( canMoveToCell(actualPosition, getOppositeDirection(directionToMove), map) ) { directionToMove = getOppositeDirection(directionToMove); positionToReturn = map[ actualPosition.getRow() + moviment.get(directionToMove)[0] ] [actualPosition.getColumn() + moviment.get(directionToMove)[1]]; } // MOVE TO CONTRARI COLISIO else if ( canMoveToCell(actualPosition, contrari_colisio, map) ) { directionToMove = contrari_colisio; positionToReturn = map[ actualPosition.getRow() + moviment.get(directionToMove)[0] ] [actualPosition.getColumn() + moviment.get(directionToMove)[1]]; } // CAS EN QUE HI HA PARETS else if ( isSurroundedByWalls(actualPosition,map) ) { this.cantMove = true; positionToReturn = actualPosition; } } // Update info agent in the new cell if (positionToReturn != null && !positionToReturn.equals(actualPosition)) { positionToReturn.removeAgent(this.myAID); try { positionToReturn.addAgent(auxInfo.getInfoAgent(this.getAID())); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } //Save infoagent to the new position } } else // WE ARE GONNA MOVE OPTIMAL WAY { positionToReturn = null; // MEANS THAT THERE IS NO COLLISION } // Update INFOAGENT InfoAgent thisInfoAgent = auxInfo.getInfoAgent(this.myAID); thisInfoAgent.setHasCollision(this.has_collision); thisInfoAgent.setCantMove(this.cantMove); return positionToReturn; } private boolean isSurroundedByWalls (Cell actualPosition, Cell[][] map) { int x=actualPosition.getRow(), y=actualPosition.getColumn(), z = 0, xi=0, yi=0; int maxRows=0, maxColumns=0; maxRows = auxInfo.getMapRows(); maxColumns = auxInfo.getMapColumns(); int [][] nearPlaces = {{x+1,y},{x,y+1},{x-1,y},{x,y-1}}; List<int[]> intList = Arrays.asList(nearPlaces); ArrayList<int[]> arrayList = new ArrayList<int[]>(intList); int valid_position = 0, not_street_cells = 0; int[] list = null; // Search a cell street while (arrayList.size() != 0) { Random a = new Random(); list = arrayList.remove(a.nextInt(arrayList.size())); xi = list[0]; yi = list[1]; if (xi < maxRows && xi >= 0 && yi >= 0 && yi < maxColumns) { Cell position = map[xi][yi]; valid_position++; if (position.getCellType() != Cell.STREET) { not_street_cells++; } } } // If the agent has only 1 factible movement and the other non valid position are street cells, then the agent is surrounded by walls if (valid_position - not_street_cells == 1) return true; else return false; } private boolean canMoveToCell (Cell actualPosition, int DIRECTION, Cell[][] map) { int x=actualPosition.getRow(), y=actualPosition.getColumn(), z = 0, xi=0, yi=0; int maxRows=0, maxColumns=0; maxRows = auxInfo.getMapRows(); maxColumns = auxInfo.getMapColumns(); int[] list = moviment.get(DIRECTION); xi = list[0] + x; yi = list[1] + y; if (xi < maxRows && xi >= 0 && yi >= 0 && yi < maxColumns) { Cell dest = map[xi][yi]; if (dest.getCellType() == Cell.STREET) { if(!dest.isThereAnAgent()) { return true; } } } return false; } private ArrayList<int[]> detectCollision (Cell[][] map, Cell actualPosition) { int x=actualPosition.getRow(), y=actualPosition.getColumn(), z = 0, xi=0, yi=0; int maxRows=0, maxColumns=0; maxRows = auxInfo.getMapRows(); maxColumns = auxInfo.getMapColumns(); ArrayList<int[]> list_colisions = new ArrayList<int[]>(); int [][] nearPlaces = {{x+1,y},{x,y+1},{x-1,y},{x,y-1}}; List<int[]> intList = Arrays.asList(nearPlaces); ArrayList<int[]> arrayList = new ArrayList<int[]>(intList); int[] list = null; // Search a cell street while (arrayList.size() != 0) { Random a = new Random(); list = arrayList.remove(a.nextInt(arrayList.size())); xi = list[0]; yi = list[1]; if (xi < maxRows && xi >= 0 && yi >= 0 && yi < maxColumns) { Cell position = map[xi][yi]; if (position.getCellType() == Cell.STREET) { if(position.isThereAnAgent()) { int[] idx_colision = {xi,yi}; list_colisions.add(idx_colision); } } } } return list_colisions; } private boolean applyPolitic(int[] colision_pos, Cell[][] map) { int xi=0, yi=0; int maxRows=0, maxColumns=0; maxRows = auxInfo.getMapRows(); maxColumns = auxInfo.getMapColumns(); Cell newPosition; xi = colision_pos[0]; yi = colision_pos[1]; if (xi < maxRows && xi >= 0 && yi >= 0 && yi < maxColumns) { newPosition = map[xi][yi]; if(Cell.STREET == newPosition.getCellType() ) //Check the limits of the map { /* If there is a scout agent in front of */ if (newPosition.isThereAnAgent() && newPosition.getAgent().getAgentType() == InfoAgent.SCOUT) { /*Compare the ID's of each scout. The bigger one will be moved to desired position*/ int h1 = auxInfo.getInfoAgent(this.myAID).getAID().hashCode(); int h2 = newPosition.getAgent().getAID().hashCode(); if (h1 > h2) { return true; } else return false; } /*If there is a harvester agent in front of */ else if (newPosition.isThereAnAgent() && newPosition.getAgent().getAgentType() == InfoAgent.HARVESTER) { return false; } /*If there is not an agent*/ else { return true; } } } return false; } }
UTF-8
Java
47,491
java
ScoutAgent.java
Java
[ { "context": "dBehaviour(fsm);\r\n\t}\t \r\n\t\r\n\t/**\r\n\t * \r\n\t * @author David Sanchez Pinsach \r\n\t * Class that implements behavior for requesti", "end": 5840, "score": 0.9998607039451599, "start": 5819, "tag": "NAME", "value": "David Sanchez Pinsach" }, { "context": "\t\t\t\t\t\t\t\t//if(this.getAgent().getName().equals(\"s0@192.168.1.130:1099/JADE\")){\r\n\t\t\t\t\t\t\t\t\tcreatePatrolPath();\r\n\t\t\t\t", "end": 7689, "score": 0.9997527599334717, "start": 7676, "tag": "IP_ADDRESS", "value": "192.168.1.130" }, { "context": "turn 0;\r\n\t }\r\n\t}\r\n\t\r\n\t\r\n\t/**\r\n\t * \r\n\t * @author Marc Bola���os Sol���\r\n\t * Looks for any position around it with garbag", "end": 10391, "score": 0.9797270894050598, "start": 10373, "tag": "NAME", "value": "Marc Bola���os Sol" }, { "context": "urn 0;\r\n\t }\t\r\n\t}\r\n\t\r\n\t\r\n\t/**\r\n\t * \r\n\t * @author David Sanchez Pinsach \r\n\t * Class that implements behavior for requesti", "end": 18922, "score": 0.9998348951339722, "start": 18901, "tag": "NAME", "value": "David Sanchez Pinsach" } ]
null
[]
package sma; import java.awt.Point; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.PriorityQueue; import java.util.Queue; import java.util.Set; import java.util.Stack; import java.util.Random; import org.newdawn.slick.util.pathfinding.AStarPathFinder; import org.newdawn.slick.util.pathfinding.Path; import org.newdawn.slick.util.pathfinding.Path.Step; import jade.core.AID; import jade.core.Agent; import jade.core.behaviours.FSMBehaviour; import jade.core.behaviours.OneShotBehaviour; import jade.core.behaviours.SimpleBehaviour; import jade.domain.DFService; import jade.domain.FIPAException; import jade.domain.FIPANames.InteractionProtocol; import jade.domain.FIPAAgentManagement.DFAgentDescription; import jade.domain.FIPAAgentManagement.ServiceDescription; import jade.lang.acl.ACLMessage; import jade.lang.acl.UnreadableException; import sma.ScoutCoordinatorAgent.InitialSendToScout; import sma.ScoutCoordinatorAgent.RequestGameInfo; import sma.gui.LogPanel; import sma.ontology.AStar; import sma.ontology.AuxInfo; import sma.ontology.Cell; import sma.ontology.DelimitingZone; import sma.ontology.InfoAgent; import sma.ontology.InfoGame; public class ScoutAgent extends Agent { // Indicates if we want to show the debugging messages private boolean debugging = true; private boolean debuggingPatrolingPath = false; private AID scoutCoordinatorAgent; // array storing the not handled messages private MessagesList messagesQueue = new MessagesList(this); private AuxInfo auxInfo; private DelimitingZone patrolZone; // object describing the zone where the scout must patrol //Patrol path parameters private ArrayList<Boolean> visitedBuildings; private ArrayList<Point> buildings; private int noVisited; private ArrayList<Point> patrollPath; private int patrollPoint = 0; private boolean sign=true; private Point objectivePoint; private boolean patroling = false; private AID myAID; private HashMap<Integer, int[]> moviment = new HashMap<Integer, int[]>(); private final int NORT = 1, SUD = 2, EST = 3, WEST = 4; boolean has_collision = false, cantMove = false; int contrari_colisio = 0; private AID preference_over = null; private boolean followingOptimalPath = true; private Cell lastOptimalPoint = null; AStar astar; public ScoutAgent(){ super(); int[] N = {-1,0}, E={0,1}, S = {1,0}, W= {0,-1}; moviment.put(NORT, N); moviment.put(SUD, S); moviment.put(EST, E); moviment.put(WEST, W); } /** * A message is shown in the log area of the GUI * @param str String to show */ private void showMessage(String str) { LogPanel.showMessage(getLocalName() + ": " + str+"\n"); if(debugging) System.out.println(getLocalName() + ": " + str); } private void showMessageWithBoolean(Boolean b, String str) { if(b) System.out.println(getLocalName() + ": " + str); } protected void setup(){ this.myAID = getAID(); /**** Very Important Line (VIL) *********/ this.setEnabledO2ACommunication(true, 1); /****************************************/ // Register the agent to the DF ServiceDescription sd1 = new ServiceDescription(); sd1.setType(UtilsAgents.SCOUT_AGENT); sd1.setName(getLocalName()); sd1.setOwnership(UtilsAgents.OWNER); DFAgentDescription dfd = new DFAgentDescription(); dfd.addServices(sd1); dfd.setName(getAID()); try { DFService.register(this, dfd); showMessage("Scout Registered to the DF"); } catch (FIPAException e) { System.err.println(getLocalName() + " registration with DF " + "unsucceeded. Reason: " + e.getMessage()); doDelete(); } // move(); visitedBuildings = new ArrayList<Boolean>(); // search ScoutsCoordinatorAgent ServiceDescription searchCriterion = new ServiceDescription(); searchCriterion.setType(UtilsAgents.SCOUT_COORDINATOR_AGENT); this.scoutCoordinatorAgent = UtilsAgents.searchAgent(this, searchCriterion); // Finite State Machine FSMBehaviour fsm = new FSMBehaviour(this) { private static final long serialVersionUID = 1L; public int onEnd() { myAgent.doDelete(); return super.onEnd(); } }; // Behaviour to receive first AuxInfo and DelimitingZone where it will have to patrol. fsm.registerFirstState(new InitialRecieve(this, scoutCoordinatorAgent), "STATE_1"); // Behaviour to send the list of garbage positions that is has found in this turn. fsm.registerState(new SendGarbagePositions(this, scoutCoordinatorAgent), "STATE_2"); // Behaviour to receive AuxInfo for each turn. fsm.registerState(new RecieveGameInfo(this, scoutCoordinatorAgent), "STATE_3"); // Behaviour to decide where to move and send that information to the ScoutCoordinator fsm.registerState(new MoveAgent(this, scoutCoordinatorAgent), "STATE_4"); fsm.registerDefaultTransition("STATE_1", "STATE_2"); fsm.registerDefaultTransition("STATE_2", "STATE_4"); fsm.registerDefaultTransition("STATE_4", "STATE_3"); fsm.registerDefaultTransition("STATE_3", "STATE_2"); // Version 1 (Marc) Diria que no �s correcte /*fsm.registerDefaultTransition("STATE_1", "STATE_2"); fsm.registerDefaultTransition("STATE_2", "STATE_3"); fsm.registerDefaultTransition("STATE_4", "STATE_2"); fsm.registerDefaultTransition("STATE_3", "STATE_4");*/ addBehaviour(fsm); } /** * * @author <NAME> * Class that implements behavior for requesting game info (map) */ protected class InitialRecieve extends SimpleBehaviour { private AID receptor; private Agent a; public InitialRecieve (Agent a, AID r) { super(a); this.receptor = r; } @Override public void action() { // Make the request ACLMessage request = new ACLMessage(ACLMessage.REQUEST); request.clearAllReceiver(); request.addReceiver(receptor); request.setProtocol(InteractionProtocol.FIPA_REQUEST); showMessage("Connection STATE_1 between scout->scout coordinator: OK"); /*Reception of game info * * The protocol is in two steps: * 1. Sender sent an AGREE/FAILURE message * 2. Sender sent INFORM message containing the AuxInfo object */ boolean okInfo = false; while(!okInfo) { ACLMessage reply = messagesQueue.getMessage(); if (reply != null) { switch (reply.getPerformative()) { case ACLMessage.AGREE: showMessage("Recieved AGREE from "+reply.getSender()); break; case ACLMessage.INFORM: try { auxInfo = (AuxInfo) reply.getContentObject(); // Getting object with the information about the game showMessage("Receiving game info from "+receptor); } catch (UnreadableException e) { messagesQueue.add(reply); System.err.println(getLocalName() + " Recieved game info unsucceeded. Reason: " + e.getMessage()); } catch (ClassCastException e){ try { patrolZone = (DelimitingZone) reply.getContentObject(); astar = new AStar(auxInfo); showMessage("Receiving patrol zone from "+receptor); //if(this.getAgent().getName().equals("s0@192.168.1.130:1099/JADE")){ createPatrolPath(); //} // Send the cell ---> USLESS!!!! //ACLMessage reply2 = reply.createReply(); //reply2.setPerformative(ACLMessage.INFORM); //Cell c = null; try { AID myAID = this.myAgent.getAID(); //Cell c = auxInfo.getAgentCell(myAID); /** * Create the patrol zone with the bounds of the delimiting zone * of each agent. Add in arrayList of objective positions */ int x=(int) patrolZone.getUL().getX(); int y=(int) patrolZone.getUL().getY(); objectivePoint = checkInitialPosition(patrolZone.getUL()); // Useless.....?? //First movement Following the best position to the path /*Cell newC = getBestPositionToObjective(auxInfo.getMap(), c, new Cell(objectivePoint.x, objectivePoint.y)); if (newC == null) newC = getRandomPosition(auxInfo.getMap(), c); c = newC; //Or random //c = getRandomPosition(auxInfo.getMap(), c); reply2.setContentObject(c); //Return a new cell to scout coordinator*/ } catch (Exception e1) { //reply2.setPerformative(ACLMessage.FAILURE); System.err.println(e1.toString()); } //send(reply2); //showMessage("Sending the cell ["+c.getRow()+","+c.getColumn()+"] position to "+receptor); okInfo = true; } catch (UnreadableException e1) { messagesQueue.add(reply); System.err.println(getLocalName() + " Recieved objective postionunsucceeded. Reason: " + e.getMessage()); } //Getting the objective position } break; case ACLMessage.FAILURE: System.err.println(getLocalName() + " Recieved game info unsucceeded. Reason: Performative was FAILURE"); break; default: // Unexpected messages received must be added to the queue. messagesQueue.add(reply); break; } } } messagesQueue.endRetrieval(); } @Override public boolean done() { return true; } public int onEnd(){ showMessage("STATE_1 return OK, AuxInfo and DelimitingZone received."); return 0; } } /** * * @author <NAME>��� * Looks for any position around it with garbage and sends them to the ScoutsCoordinator. */ protected class SendGarbagePositions extends SimpleBehaviour { private AID receptor; private Agent a; public SendGarbagePositions (Agent a, AID r) { super(a); this.receptor = r; } @Override public void action() { // Finds garbage positions ArrayList garbageDiscoveries = checkScoutDiscoveries(); try { // Make the request ACLMessage request = new ACLMessage(ACLMessage.INFORM); request.clearAllReceiver(); request.setContentObject(garbageDiscoveries); request.addReceiver(receptor); request.setProtocol(InteractionProtocol.FIPA_REQUEST); send(request); showMessage("Connection STATE_2 between scout->scout coordinator: OK"); } catch (IOException e) { showMessage("Problem found when sending new discoveries."); } } @Override public boolean done() { return true; } public int onEnd(){ showMessage("STATE_2 return OK"); return 0; } } protected class MoveAgent extends SimpleBehaviour { private AID receptor; public MoveAgent(Agent a, AID r){ super(a); this.receptor = r; } private Cell moveNormally(){ AID myAID = this.myAgent.getAID(); Cell c = auxInfo.getAgentCell(myAID); int c_x = c.getRow(); int c_y = c.getColumn(); //Case when you don't have objective point if(objectivePoint==null){ //If you have not got a objective you will follow the patrolling path. Point patrollMovement= patrollPath.get(patrollPoint); //newPositionCell.addAgent(c.getAgent()); //Save infoagent to the new position showMessageWithBoolean(debuggingPatrolingPath, "Patrolling path"); c = checkIfPositionIsOccupied(auxInfo.getMap()[patrollMovement.x][patrollMovement.y],auxInfo.getMap(), c); //Update the pointer in the patrollPath if(sign){ patrollPoint++; }else{ patrollPoint--; } //Check if the agent arrives on the final o on the initially of the array of patroll path if((patrollPoint<0) || (patrollPoint==patrollPath.size())){ sign = !sign; // if(sign){ patrollPoint++; patrollPoint++; }else{ patrollPoint--; patrollPoint--; } } showMessage("Doing patrol."); //Case when you have objective point }else{ Point UL = checkInitialPosition(patrolZone.getUL()); // case when we had shifted from the correct path (for collision avoidance) if(((objectivePoint.getX() != UL.x) || (objectivePoint.getY() != UL.y)) && (objectivePoint.getX()==c_x) && (objectivePoint.getY()==c_y)){ if(!patroling){ objectivePoint = checkInitialPosition(patrolZone.getUL()); c = getBestPositionToObjective(auxInfo.getMap(), c, new Cell(objectivePoint.x, objectivePoint.y)); showMessage("Returning to path to UL position."); } else { Point patrollMovement = patrollPath.get(patrollPoint); c = checkIfPositionIsOccupied(auxInfo.getMap()[patrollMovement.x][patrollMovement.y],auxInfo.getMap(), c); //Check if the patroll movement is possible or not (if not occupated) // if((patrollMovement.x != c.getRow()) && (patrollMovement.y != c.getColumn())){ // objectivePoint = patrollMovement; //Save the patroll movement as to the new objective because you do not follow the patrol path. // } //Update the pointer in the patrollPath if(sign){ patrollPoint++; }else{ patrollPoint--; } if(patrollPoint<0 && patrollPoint>=patrollPath.size()){ showMessage("Changing the direction of the patrolling path"); sign = !sign; // if(sign){ patrollPoint++; }else{ patrollPoint--; } } objectivePoint = null; showMessage("Returning to patrol."); } } // we are on the corner UL else if((objectivePoint.getX() == UL.x) && (objectivePoint.getY() == UL.y) && (objectivePoint.getX()==c_x) && (objectivePoint.getY()==c_y)){ objectivePoint = null; Point patrollMovement = patrollPath.get(patrollPoint); c = checkIfPositionIsOccupied(auxInfo.getMap()[patrollMovement.x][patrollMovement.y],auxInfo.getMap(), c); //Check if the patroll movement is possible or not (if not occupated) if((patrollMovement.x != c.getRow()) && (patrollMovement.y != c.getColumn())){ objectivePoint = patrollMovement; //Save the patroll movement as to the new objective because you do not follow the patrol path. } //Update the pointer in the patrollPath if(sign){ patrollPoint++; }else{ patrollPoint--; } if(patrollPoint<0 && patrollPoint>=patrollPath.size()){ showMessage("Changing the direction of the patrolling path"); sign = !sign; // if(sign){ patrollPoint++; }else{ patrollPoint--; } } patroling = true; showMessage("Starting patrol."); }else{ c = getBestPositionToObjective(auxInfo.getMap(), c, new Cell(objectivePoint.x, objectivePoint.y)); showMessage("Doing getBestPositionToObjective."); } } if(c == null){ try { c = getRandomPosition(auxInfo.getMap(), auxInfo.getAgentCell(this.myAgent.getAID())); showMessage("Doing random movement."); } catch (IOException e) { e.printStackTrace(); } } return c; } public void action() { Cell actualPosition = auxInfo.getAgentCell(myAID); // Collision avoidance module Cell c = checkCollisions(auxInfo.getMap(), actualPosition); // Move normally if(c == null){ if(followingOptimalPath){ c = moveNormally(); } else { // we have recently been avoiding a collision followingOptimalPath = true; // modify the optimal path adding the steps to go back to the lastOptimalPoint!! objectivePoint = new Point(lastOptimalPoint.getRow(), lastOptimalPoint.getColumn()); c = moveNormally(); } } else if(followingOptimalPath) { // We are avoiding a collision and we where recently following the optimal path followingOptimalPath = false; lastOptimalPoint = auxInfo.getAgentCell(this.myAgent.getAID()); } // Send the cell ACLMessage reply2 = new ACLMessage(ACLMessage.REQUEST); reply2.clearAllReceiver(); reply2.addReceiver(receptor); //reply2.setProtocol(InteractionProtocol.FIPA_REQUEST); reply2.setPerformative(ACLMessage.INFORM); try { reply2.setContentObject(c); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } //Return a new cell to harvester coordinator send(reply2); showMessage("Sending the cell position to "+receptor); } @Override public boolean done() { return true; } public int onEnd(){ showMessage("STATE_4: Position sent."); return 0; } } /** * * @author <NAME> * Class that implements behavior for requesting game info (map) */ protected class RecieveGameInfo extends SimpleBehaviour { private AID receptor; private Agent a; public RecieveGameInfo (Agent a, AID r) { super(a); this.receptor = r; } @Override public void action() { // Make the request ACLMessage request = new ACLMessage(ACLMessage.REQUEST); request.clearAllReceiver(); request.addReceiver(receptor); request.setProtocol(InteractionProtocol.FIPA_REQUEST); showMessage("Connection STATE_3 between scout->scout coordinator: OK"); /*Reception of game info * * The protocol is in two steps: * 1. Sender sent an AGREE/FAILURE message * 2. Sender sent INFORM message containing the AuxInfo object */ boolean okInfo = false; while(!okInfo) { ACLMessage reply = messagesQueue.getMessage(); if (reply != null) { switch (reply.getPerformative()) { case ACLMessage.AGREE: showMessage("Recieved AGREE from "+reply.getSender()); break; case ACLMessage.INFORM: try { auxInfo = (AuxInfo) reply.getContentObject(); // Getting object with the information about the game showMessage("Receiving game info from "+receptor); okInfo = true; } catch (UnreadableException e) { messagesQueue.add(reply); System.err.println(getLocalName() + " Recieved game info unsucceeded. Reason: " + e.getMessage()); } catch(ClassCastException e){ messagesQueue.add(reply); System.err.println(getLocalName() + " Recieved game info unsucceeded. Reason: " + e.getMessage()); } break; case ACLMessage.FAILURE: System.err.println(getLocalName() + " Recieved game info unsucceeded. Reason: Performative was FAILURE"); break; default: // Unexpected messages received must be added to the queue. messagesQueue.add(reply); break; } } } messagesQueue.endRetrieval(); } @Override public boolean done() { return true; } public int onEnd(){ showMessage("STATE_3 return OK"); return 0; } } private Cell getBestPositionToObjective(Cell[][] cells, Cell actualPosition, Cell objectivePosition) { Cell newPosition = null; showMessage("I am in the cell = ["+actualPosition.getRow()+","+actualPosition.getColumn()+"]"); showMessage("I wanna go to the cell = ["+objectivePosition.getRow()+","+objectivePosition.getColumn()+"]"); newPosition = astar.shortestPath(cells, actualPosition, objectivePosition); if (newPosition == null) return null; int xi = newPosition.getRow(); int yi = newPosition.getColumn(); int maxRows = auxInfo.getMapRows(); int maxColumns = auxInfo.getMapColumns(); if (xi < maxRows && xi >= 0 && yi >= 0 && yi < maxColumns) { Cell position = cells[xi][yi]; if (position.getCellType() == Cell.STREET) { try { if (!newPosition.equals(actualPosition)) { newPosition.removeAgent(this.myAID); newPosition.addAgent(auxInfo.getInfoAgent(this.getAID())); } } catch (Exception e) { e.printStackTrace(); } } } //newPosition = checkIfPositionIsOccupied(newPosition, cells, actualPosition); return newPosition; } private Cell checkIfPositionIsOccupied(Cell newPosition, Cell[][] cells, Cell actualPosition) { if (!newPosition.equals(actualPosition)) { newPosition.removeAgent(this.getAID()); try { newPosition.addAgent(auxInfo.getInfoAgent(this.getAID())); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } return newPosition; } private Cell moveToFreePlace(Cell[][] cells, Cell actualPosition, Cell newPosition, InfoAgent infoAgent) { int x = actualPosition.getRow(); int y = actualPosition.getColumn(); int maxRows = auxInfo.getMapRows(); int maxColumns = auxInfo.getMapColumns(); int [][] nearPlaces = {{x+1,y},{x,y+1},{x-1,y},{x,y-1}}; List<int[]> intList = Arrays.asList(nearPlaces); ArrayList<int[]> arrayList = new ArrayList<int[]>(intList); int[] list = null; // Search a cell street while (arrayList.size() != 0) { Random a = new Random(); list = arrayList.remove(a.nextInt(arrayList.size())); int xi = list[0]; int yi = list[1]; if (xi < maxRows && xi >= 0 && yi >= 0 && yi < maxColumns) { Cell position = cells[xi][yi]; if (position.getCellType() == Cell.STREET) { if(!position.isThereAnAgent()){ return position; } } } } return actualPosition; } /** * Method to send a movement (A cell) * @param reply Recieve message * @param c Cell to send * @throws IOException Error of sending message */ public Cell getRandomPosition(Cell[][] map, Cell actualPosition) throws IOException{ Cell newPosition = null, positionToReturn = actualPosition; boolean trobat = false; showMessage("Checking random movement..."); int x=actualPosition.getRow(), y=actualPosition.getColumn(), z = 0, xi=0, yi=0; int maxRows=0, maxColumns=0; maxRows = auxInfo.getMapRows(); maxColumns = auxInfo.getMapColumns(); newPosition = actualPosition; int [][] posibleMovements = {{x+1,y},{x,y+1},{x-1,y},{x,y-1}}; List<int[]> intList = Arrays.asList(posibleMovements); ArrayList<int[]> arrayList = new ArrayList<int[]>(intList); int [] list = null; //Search a cell street while(arrayList.size()!=0 && !trobat) { z= auxInfo.getRandomPosition(arrayList.size()); list = arrayList.remove(z); xi = list[0]; yi = list[1]; if(xi < maxRows && xi >= 0 && yi >= 0 && yi < maxColumns) //Check if the position it's in the range of the map { newPosition = map[xi][yi]; if(Cell.STREET == newPosition.getCellType() ) //Check the limits of the map { try { showMessage("Position before moving "+"["+x+","+y+"]"); if (!newPosition.equals(actualPosition)) { newPosition.removeAgent(this.myAID); newPosition.addAgent(auxInfo.getInfoAgent(this.getAID())); //Save infoagent to the new position } positionToReturn = newPosition; //actualPosition.removeAgent(actualPosition.getAgent()); } catch (Exception e) { showMessage("ERROR: Failed to save the infoagent to the new position: "+e.getMessage()); } trobat = true; /* If there is a scout agent in front of */ /*if (newPosition.isThereAnAgent() && newPosition.getAgent().getAgentType() == InfoAgent.SCOUT) { Compare the ID's of each scout. The bigger one will be moved to desired position int h1 = auxInfo.getInfoAgent(this.scoutCoordinatorAgent).getAID().hashCode(); int h2 = newPosition.getAgent().getAID().hashCode(); if (h1 > h2) { try { showMessage("Position before moving "+"["+x+","+y+"]"); newPosition.addAgent(auxInfo.getInfoAgent(this.getAID())); //Save infoagent to the new position positionToReturn = newPosition; //actualPosition.removeAgent(actualPosition.getAgent()); } catch (Exception e) { showMessage("ERROR: Failed to save the infoagent to the new position: "+e.getMessage()); } trobat = true; } } If there is a harvester agent in front of else if (newPosition.isThereAnAgent() && newPosition.getAgent().getAgentType() == InfoAgent.HARVESTER) { // Do nothing. } If there is not an agent else { try { showMessage("Position before moving "+"["+x+","+y+"]"); newPosition.addAgent(auxInfo.getInfoAgent(this.getAID())); //Save infoagent to the new position positionToReturn = newPosition; //actualPosition.removeAgent(actualPosition.getAgent()); } catch (Exception e) { showMessage("ERROR: Failed to save the infoagent to the new position: "+e.getMessage()); } trobat = true; }*/ } } } return positionToReturn; } /** * Checks if any of the surrounding buildings there is any unit of garbage. * * @return ArrayList with the information about the garbage found with the following format * for each garbage cell (ArrayList): * - int row in the map * - int column in the map * - Cell datatype storing information about the content of the cell. */ private ArrayList checkScoutDiscoveries(){ showMessage("Checking New Discoveries..."); ArrayList garbageFound = new ArrayList(); Cell a = auxInfo.getAgentCell(this.getAID()); Cell b; // cell possibly with garbage Cell[][] map = auxInfo.getMap(); for (int i = 0; i < auxInfo.getMapRows(); i++){ for (int j = 0; j < auxInfo.getMapColumns(); j++){ b = map[i][j]; try { if(b.getCellType() == Cell.BUILDING && b.getGarbageUnits() > 0){ int x=a.getRow(); int y=a.getColumn(); int xb=b.getRow(); int yb=b.getColumn(); if (x>0){ if ((xb==x-1) && (yb==y)) {garbageFound.add(createGarbage(xb, yb, b));}// remove.add(b);} if ((y>0) && (xb==x-1) && (yb==y-1)) {garbageFound.add(createGarbage(xb, yb, b));}// remove.add(b);} if ((y<auxInfo.getMap()[x].length-1) && (xb==x-1) && (yb==y+1)) {garbageFound.add(createGarbage(xb, yb, b));}// remove.add(b);} } if (x<auxInfo.getMap().length-1){ if ((xb==x+1) && (yb==y)) {garbageFound.add(createGarbage(xb, yb, b));}// remove.add(b);} if ((y>0) && (xb==x+1) && (yb==y-1)) {garbageFound.add(createGarbage(xb, yb, b));}// remove.add(b);} if ((y<auxInfo.getMap()[x].length-1) && (xb==x+1) && (yb==y+1)) {garbageFound.add(createGarbage(xb, yb, b));}// remove.add(b);} } if ((y>0) && (xb==x) && (yb==y-1)) {garbageFound.add(createGarbage(xb, yb, b));}// remove.add(b);} if ((y<auxInfo.getMap()[x].length-1) && (xb==x) && (yb==y+1)) {garbageFound.add(createGarbage(xb, yb, b));}// remove.add(b);} } } catch (Exception e) { e.printStackTrace(); } } } //for (Cell r : remove) game.getBuildingsGarbage().remove(r); return garbageFound; } private ArrayList createGarbage(int x, int y, Cell b){ ArrayList garbage = new ArrayList(); garbage.add(x); garbage.add(y); garbage.add(b); return garbage; } private void createPatrolPath(){ showMessageWithBoolean(this.debuggingPatrolingPath,"Creating the patrolling path!"); Point UL = patrolZone.getUL(); //We will use the UL as initial point on the patroll path. buildings = patrolZone.getBuildingsPositions(); for(int i=0;i<buildings.size();i++){ visitedBuildings.add(false); } this.noVisited = visitedBuildings.size(); //Initial point of the path it is possible or not Point currentPos = checkInitialPosition(UL); showMessageWithBoolean(this.debuggingPatrolingPath,"Initial point:"+currentPos); patrollPath = new ArrayList<Point>(); //Points of patrol path Stack<Point> stack =new Stack<Point>(); Set<Point> cellsVisited = new HashSet<Point>(); stack.add(currentPos); //While not visit all the buildings while(this.noVisited!=0 && !stack.isEmpty()){ currentPos = stack.pop(); if(!cellsVisited.contains(currentPos)){ cellsVisited.add(currentPos); patrollPath.add(currentPos); int num = 0; for(Point p : getChilds(currentPos)){ if(!cellsVisited.contains(p)){ stack.push(p); num++; } } //Need backtracking because you already visited all of your neighbours if(num==0 && !stack.isEmpty()){ showMessageWithBoolean(this.debuggingPatrolingPath,"\nBacktracking is neeeded!"); Point objectivePos; objectivePos = stack.pop(); while(cellsVisited.contains(objectivePos)&&!stack.isEmpty()){ showMessageWithBoolean(this.debuggingPatrolingPath,"Pos->"+objectivePos); objectivePos = stack.pop(); } showMessageWithBoolean(this.debuggingPatrolingPath,"Current->"+currentPos); showMessageWithBoolean(this.debuggingPatrolingPath,"Objective->"+objectivePos); //Compute A* to the current position to the objective AStarPathFinder pathFinder = new AStarPathFinder(astar.map, 1000,false);// Diagonal movement not allowed false, true allowed Path path = pathFinder.findPath(null, currentPos.y, currentPos.x, objectivePos.y, objectivePos.x); for(int i=1; i<path.getLength()-1; i++){ Step s = path.getStep(i); Point p = new Point(s.getY(),s.getX()); patrollPath.add(p); showMessageWithBoolean(this.debuggingPatrolingPath,"Backtracking..."+p); } //Push the non visited position stack.add(objectivePos); showMessageWithBoolean(this.debuggingPatrolingPath,"Finish backtracking! \n"); } } showMessageWithBoolean(this.debuggingPatrolingPath,"The patrolling path was finished!"); } if(this.debuggingPatrolingPath){ showMessageWithBoolean(this.debuggingPatrolingPath,"Patrol path have been created!"); for(int i=0; i<this.visitedBuildings.size(); i++){ if(!this.visitedBuildings.get(i)) System.out.println(this.buildings.get(i)); } } if(this.debuggingPatrolingPath){ showMessageWithBoolean(this.debuggingPatrolingPath,"Printing the patrol path"); showMessageWithBoolean(this.debuggingPatrolingPath,"Path size"+patrollPath.size()); for(Point p : patrollPath){ showMessageWithBoolean(this.debuggingPatrolingPath,p.toString()); } showMessageWithBoolean(this.debuggingPatrolingPath,"Process finished!"); } patrollPath.remove(0); } /** * Check and correct if the initial point is or not a building * @param p Initial point * @return Return a correct initial point */ private Point checkInitialPosition(Point p){ Cell[][] map = auxInfo.getMap(); Cell c = map[p.x][p.y]; c.setColumn(p.y); c.setRow(p.x); int count = 0; while(c.getCellType()!=c.STREET){ c = map[p.x][p.y+count]; c.setColumn(p.y+count); c.setRow(p.x); count++; } return new Point(c.getRow(),c.getColumn()); } /** * Method to check the buildings around the current position * @param movements All the possible movements * @return Return the all the possible movements filtered */ private ArrayList<Point> checkBuilding(ArrayList<Point> movements){ Point b; Point UL = patrolZone.getUL(); Point BR = patrolZone.getBR(); Cell[][] map = auxInfo.getMap(); ArrayList<Point> possibleMovements = new ArrayList<Point>(); for(Point p : movements){ int i = 0; boolean found = false; while(i<buildings.size() && !found){ b = buildings.get(i); //Check if the point p is a building if((b.getX()==p.getX()) &&(b.getY()==p.getY())) found = true; else i++; } if(found){ if(!visitedBuildings.get(i)){ visitedBuildings.set(i, true); this.noVisited--; showMessageWithBoolean(this.debuggingPatrolingPath," Visiting->"+buildings.get(i)+" Num non visites->"+this.noVisited); } }else{ //Check if the movement it can be possible, it is in the delimited zone. if((p.x>=0)&&(p.y>=0)&&(p.x<auxInfo.getMapRows())&&(p.y<auxInfo.getMapColumns()) && (UL.getX()<=p.getX()) && (UL.getY()<=p.getY()) && (BR.getX()>=p.getX()) && (BR.getY()>=p.getY())){ //Check the cell type of the new movement is a street int type = map[p.x][p.y].getCellType(); if(Cell.STREET==type) possibleMovements.add(p); } } } return possibleMovements; } /** * Get the child cells of the current position * @param currentPos Current position * @return Return the possible movements of the childs of the current position */ private ArrayList<Point> getChilds(Point currentPos){ Point up, right, left, down; double x,y; ArrayList<Point> possibleMovements = new ArrayList<Point>(); x = currentPos.getX(); y = currentPos.getY(); //Move in the 4 possible directions up=new Point((int)currentPos.getX()-1,(int)currentPos.getY()); right=new Point((int)currentPos.getX(),(int)currentPos.getY()+1); left=new Point((int)currentPos.getX(),(int)currentPos.getY()-1); down=new Point((int)currentPos.getX()+1,(int)currentPos.getY()); //Remove the building in the list of no visited buildings. possibleMovements.add(up); possibleMovements.add(left); possibleMovements.add(right); possibleMovements.add(down); return checkBuilding(possibleMovements); } private int mapPosWithDirection(int[] pos, Cell actualPos) { int x = pos[0], y = pos[1], actual_x = actualPos.getRow(), actual_y = actualPos.getColumn(); int x_dif = actual_x - x; int y_dif = actual_y - y; if(actual_x > x && actual_y == y ) return this.NORT; if(actual_x < x && actual_y == y ) return this.SUD; if(actual_x == x && actual_y > y ) return this.WEST; if(actual_x == x && actual_y < y ) return this.EST; /*if (x_dif == 1 && y_dif == 0) return this.NORT; if (x_dif == 0 && y_dif == 1) return this.WEST; if (x_dif == -1 && y_dif == 0) return this.SUD; if ( x_dif == 0 && y_dif == -1) return this.EST; */ System.err.println("Position not correct"); return -1; } private int getOppositeDirection (int direction) { if (direction == this.NORT) return this.SUD; if (direction == this.EST) return this.WEST; if (direction == this.SUD) return this.NORT; if (direction == this.WEST) return this.EST; System.err.println("Direction not correct"); return -1; } /* * Return a Cell to move in order to avoid collitions. Return null when there not exist collisions. */ private Cell checkCollisions(Cell[][] map, Cell actualPosition) { Cell positionToReturn = null; if (!this.has_collision) { ArrayList<int[]> listColisions = detectCollision(map, actualPosition); if ( !listColisions.isEmpty()) { for (int[] col : listColisions) { int xi = col[0], yi = col[1]; InfoAgent other_agent = map[xi][yi].getAgent(); if (other_agent.hasCollision() && other_agent.getAID() != this.preference_over) { this.has_collision = true; this.preference_over = null; int other_direction = mapPosWithDirection(col, actualPosition); this.contrari_colisio = getOppositeDirection(other_direction); } else if (!applyPolitic(col, map) && !this.cantMove) { this.has_collision = true; this.preference_over = null; int other_direction = mapPosWithDirection(col, actualPosition); this.contrari_colisio = getOppositeDirection(other_direction); } else if (applyPolitic(col, map)) { this.preference_over = other_agent.getAID(); if (other_agent.cantMove()) { this.has_collision = true; this.preference_over = null; int other_direction = mapPosWithDirection(col, actualPosition); this.contrari_colisio = getOppositeDirection(other_direction); } } } } else { this.has_collision = false; this.contrari_colisio = -1; this.cantMove = false; } } else { ArrayList<int[]> listColisions = detectCollision(map, actualPosition); if ( listColisions.isEmpty()) { this.has_collision = false; this.contrari_colisio = -1; //this.cantMove = false; ??? } else if (!listColisions.isEmpty() && this.cantMove) { for (int[] col : listColisions) // Aquest for esta be???? { int xi = col[0], yi = col[1]; InfoAgent other_agent = map[xi][yi].getAgent(); this.has_collision = false; this.contrari_colisio = -1; this.preference_over = other_agent.getAID(); } } else if(!listColisions.isEmpty()) // if there is any collision { for (int[] col : listColisions) // for each collisions { int xi = col[0], yi = col[1]; InfoAgent other_agent = map[xi][yi].getAgent(); if (other_agent.cantMove()) // if the other agent can't move, then we have to give him priority { this.has_collision = true; this.preference_over = null; int other_direction = mapPosWithDirection(col, actualPosition); this.contrari_colisio = getOppositeDirection(other_direction); this.cantMove = true; } } } } // Let's decide where to move if (this.has_collision) { if (this.contrari_colisio == this.NORT || this.contrari_colisio == this.SUD) { int directionToMove; // Random movement to contrari direction Random r = new Random(); if ( r.nextInt(1) == 1 ) directionToMove = this.EST; else directionToMove = this.WEST; if (canMoveToCell(actualPosition, directionToMove, map)) { positionToReturn = map[ actualPosition.getRow() + moviment.get(directionToMove)[0] ] [actualPosition.getColumn() + moviment.get(directionToMove)[1]]; } else if ( canMoveToCell(actualPosition, getOppositeDirection(directionToMove), map) ) { directionToMove = getOppositeDirection(directionToMove); positionToReturn = map[ actualPosition.getRow() + moviment.get(directionToMove)[0] ] [actualPosition.getColumn() + moviment.get(directionToMove)[1]]; } // MOVE TO CONTRARI COLISIO else if ( canMoveToCell(actualPosition, contrari_colisio, map) ) { directionToMove = contrari_colisio; positionToReturn = map[ actualPosition.getRow() + moviment.get(directionToMove)[0] ] [actualPosition.getColumn() + moviment.get(directionToMove)[1]]; } // CAS EN QUE HI HA PARETS else if ( isSurroundedByWalls(actualPosition,map) ) { this.cantMove = true; positionToReturn = actualPosition; } } else if (this.contrari_colisio == this.EST || this.contrari_colisio == this.WEST) { int directionToMove; // Random movement to contrari direction Random r = new Random(); if ( r.nextInt(1) == 1 ) directionToMove = this.NORT; else directionToMove = this.SUD; if (canMoveToCell(actualPosition, directionToMove, map)) { positionToReturn = map[ actualPosition.getRow() + moviment.get(directionToMove)[0] ] [actualPosition.getColumn() + moviment.get(directionToMove)[1]]; } else if ( canMoveToCell(actualPosition, getOppositeDirection(directionToMove), map) ) { directionToMove = getOppositeDirection(directionToMove); positionToReturn = map[ actualPosition.getRow() + moviment.get(directionToMove)[0] ] [actualPosition.getColumn() + moviment.get(directionToMove)[1]]; } // MOVE TO CONTRARI COLISIO else if ( canMoveToCell(actualPosition, contrari_colisio, map) ) { directionToMove = contrari_colisio; positionToReturn = map[ actualPosition.getRow() + moviment.get(directionToMove)[0] ] [actualPosition.getColumn() + moviment.get(directionToMove)[1]]; } // CAS EN QUE HI HA PARETS else if ( isSurroundedByWalls(actualPosition,map) ) { this.cantMove = true; positionToReturn = actualPosition; } } // Update info agent in the new cell if (positionToReturn != null && !positionToReturn.equals(actualPosition)) { positionToReturn.removeAgent(this.myAID); try { positionToReturn.addAgent(auxInfo.getInfoAgent(this.getAID())); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } //Save infoagent to the new position } } else // WE ARE GONNA MOVE OPTIMAL WAY { positionToReturn = null; // MEANS THAT THERE IS NO COLLISION } // Update INFOAGENT InfoAgent thisInfoAgent = auxInfo.getInfoAgent(this.myAID); thisInfoAgent.setHasCollision(this.has_collision); thisInfoAgent.setCantMove(this.cantMove); return positionToReturn; } private boolean isSurroundedByWalls (Cell actualPosition, Cell[][] map) { int x=actualPosition.getRow(), y=actualPosition.getColumn(), z = 0, xi=0, yi=0; int maxRows=0, maxColumns=0; maxRows = auxInfo.getMapRows(); maxColumns = auxInfo.getMapColumns(); int [][] nearPlaces = {{x+1,y},{x,y+1},{x-1,y},{x,y-1}}; List<int[]> intList = Arrays.asList(nearPlaces); ArrayList<int[]> arrayList = new ArrayList<int[]>(intList); int valid_position = 0, not_street_cells = 0; int[] list = null; // Search a cell street while (arrayList.size() != 0) { Random a = new Random(); list = arrayList.remove(a.nextInt(arrayList.size())); xi = list[0]; yi = list[1]; if (xi < maxRows && xi >= 0 && yi >= 0 && yi < maxColumns) { Cell position = map[xi][yi]; valid_position++; if (position.getCellType() != Cell.STREET) { not_street_cells++; } } } // If the agent has only 1 factible movement and the other non valid position are street cells, then the agent is surrounded by walls if (valid_position - not_street_cells == 1) return true; else return false; } private boolean canMoveToCell (Cell actualPosition, int DIRECTION, Cell[][] map) { int x=actualPosition.getRow(), y=actualPosition.getColumn(), z = 0, xi=0, yi=0; int maxRows=0, maxColumns=0; maxRows = auxInfo.getMapRows(); maxColumns = auxInfo.getMapColumns(); int[] list = moviment.get(DIRECTION); xi = list[0] + x; yi = list[1] + y; if (xi < maxRows && xi >= 0 && yi >= 0 && yi < maxColumns) { Cell dest = map[xi][yi]; if (dest.getCellType() == Cell.STREET) { if(!dest.isThereAnAgent()) { return true; } } } return false; } private ArrayList<int[]> detectCollision (Cell[][] map, Cell actualPosition) { int x=actualPosition.getRow(), y=actualPosition.getColumn(), z = 0, xi=0, yi=0; int maxRows=0, maxColumns=0; maxRows = auxInfo.getMapRows(); maxColumns = auxInfo.getMapColumns(); ArrayList<int[]> list_colisions = new ArrayList<int[]>(); int [][] nearPlaces = {{x+1,y},{x,y+1},{x-1,y},{x,y-1}}; List<int[]> intList = Arrays.asList(nearPlaces); ArrayList<int[]> arrayList = new ArrayList<int[]>(intList); int[] list = null; // Search a cell street while (arrayList.size() != 0) { Random a = new Random(); list = arrayList.remove(a.nextInt(arrayList.size())); xi = list[0]; yi = list[1]; if (xi < maxRows && xi >= 0 && yi >= 0 && yi < maxColumns) { Cell position = map[xi][yi]; if (position.getCellType() == Cell.STREET) { if(position.isThereAnAgent()) { int[] idx_colision = {xi,yi}; list_colisions.add(idx_colision); } } } } return list_colisions; } private boolean applyPolitic(int[] colision_pos, Cell[][] map) { int xi=0, yi=0; int maxRows=0, maxColumns=0; maxRows = auxInfo.getMapRows(); maxColumns = auxInfo.getMapColumns(); Cell newPosition; xi = colision_pos[0]; yi = colision_pos[1]; if (xi < maxRows && xi >= 0 && yi >= 0 && yi < maxColumns) { newPosition = map[xi][yi]; if(Cell.STREET == newPosition.getCellType() ) //Check the limits of the map { /* If there is a scout agent in front of */ if (newPosition.isThereAnAgent() && newPosition.getAgent().getAgentType() == InfoAgent.SCOUT) { /*Compare the ID's of each scout. The bigger one will be moved to desired position*/ int h1 = auxInfo.getInfoAgent(this.myAID).getAID().hashCode(); int h2 = newPosition.getAgent().getAID().hashCode(); if (h1 > h2) { return true; } else return false; } /*If there is a harvester agent in front of */ else if (newPosition.isThereAnAgent() && newPosition.getAgent().getAgentType() == InfoAgent.HARVESTER) { return false; } /*If there is not an agent*/ else { return true; } } } return false; } }
47,443
0.607178
0.601828
1,388
32.20533
29.305882
154
false
false
0
0
0
0
0
0
3.847983
false
false
7
f913ba0c2f5f6c635a16d85f6a69413d139b4ab9
1,898,375,549,214
c1ef881e6109fe8d5319e051b9ead451eba43362
/java/examples/src/main/java/com/revature/basics/Operators.java
cd638258245b5de2767a3a581c146131146a80d0
[]
no_license
PACE190107/1901_jan07_pe
https://github.com/PACE190107/1901_jan07_pe
31f8404064ddaebd308daf642732cc227ea53da0
e1731d3ef5c70298cc3a1e4058aad89ce38562fd
refs/heads/master
2020-04-14T18:32:30.734000
2019-02-20T17:46:12
2019-02-20T17:46:12
164,022,965
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.revature.basics; import java.util.ArrayList; import java.util.List; // The import below does not work because of a naming collision (which List would the compiler use?) //import java.awt.List; public class Operators { public static void main(String[] args) { /* * Operators * * Types: * - Unary * - Arithmetic * - Relational * - Logical * - Assignment * - Bitwise Shifting * - Ternary */ /* * Unary Operators * * Postfix and Prefix */ // prefix logical NOT boolean bool = true; System.out.println("not bool = " + !bool); // prefix positive int x = +456; System.out.println(x); // prefix negative int y = 78; System.out.println(-y); // prefix increment System.out.println(++x); // prefix decrement System.out.println(--x); // postfix increment System.out.println(y++); //postfix decrement System.out.println(y--); System.out.println(y); /* * Arithmetic Operators * * Addition * Subtraction * Multiplication * Division * Modulus */ // addition int mySum = 4 + 5; System.out.println(mySum); // subtraction int myDifference = mySum - 7; System.out.println(myDifference); // multiplication int myProduct = mySum * myDifference; System.out.println(myProduct); // division double myQuotient = myDifference / mySum; System.out.println(myQuotient); // this doesn't work properly, because our operands are ints! (The compiler is defaulting to integer division) myQuotient = 2 / 9; System.out.println(myQuotient); // this doesn't work myQuotient = 2d / 9d; System.out.println(myQuotient); // explicitly declaring the digits as double literals works! myQuotient = 2. / 9.; // digits are apparently optional after the decimal point System.out.println(myQuotient); // including the decimal places tells the compiler to treat these as floating point numbers myQuotient = 2. / 9; System.out.println(myQuotient); // we really only need to declare one of the operands as a double to get the compiler to do floating point division myQuotient = (double) myDifference / mySum; System.out.println(myQuotient); // to have compiler treat already declared variables differently, cast it as the type you need // REMEMBER TO BEWARE OF TRYING TO CONVERT LARGER DATA TYPES INTO SMALLER ONES!!! int myValue = 0; long myLongValue = 345345348768734345L; myValue = (int) myLongValue; System.out.println(myValue); // modulus operator (remainder) double myRemainder = 12 % 5; System.out.println(myRemainder); /* * Relational Operators */ int a = 0; int b = 1; int c = 2; int d = 2; String myStr = "hello"; ArrayList<String> myArrayList = new ArrayList<>(); // Greater-than, Less-than, Greater-than-or-equal, Less-than-or-equal System.out.println(a > b); System.out.println(a < b); System.out.println(c < d); System.out.println(c <= d); System.out.println(d >= a); System.out.println("------------"); // separator // instanceof returns true if the first operand is a type of the second operand System.out.println(myStr instanceof String); System.out.println(myStr instanceof Object); // since all Java objects directly/indirectly extend Object - this is true! System.out.println(myArrayList instanceof ArrayList); System.out.println(myArrayList instanceof List); // this returns true, even though List is an interface! System.out.println("------------"); // separator // is-equal, not-equal System.out.println(c == d); System.out.println(a != b); System.out.println("------------"); java.awt.List myAwtList; // I can still access non-imported classes using the fully-qualified path name /* * Logical Operators (Short-circuit operators) * * For instance, with AND (&&) - we know that both operands have to be true in order for the result to be true. So, if * the first operand evaluated is false - then we already know that the result is going to be false. * * Likewise, with OR (||) - the operation will return true if at least one of the operands is true. So, if the value of * the first operand is true, then there is no need to check the other. */ boolean value1 = true; boolean value2 = false; boolean value3 = true; // logical AND boolean result = value1 && value2; System.out.println(result); result = value1 && value3; System.out.println(result); // logical OR result = value1 || value2; System.out.println(result); /* * Bitwise Operators (Short-Circuit Operators) * * These are similar to the logical operators, and actually give the same results as their counterparts. But have specific * use cases dealing with binary values. * * XOR is a bit different, it is also known as the Exclusive-OR. This operator returns true if exactly one operand * has a true value. If both are true, then it will return false. Because of its nature, XOR must check both operands. */ // bitwise AND result = value2 & value1; System.out.println(result); // bitwise OR result = value1 | value2; System.out.println(result); // bitwise XOR result = value1 ^ value3; System.out.println(result); // declaring values in different bases int myBinary = 0b0010; // binary (base 2) int myOctal = 010; // octal (base 8) int myHex = 0x3f; // hexadecimal (base 16) System.out.println(myBinary); System.out.println(myOctal); System.out.println(myHex); /* * Assignment Operators * * In addition to the simple assignment that we have been using during variable initialization, we also have the compound * assignment operators at our disposal. These include compound assignment operators for arithmetic and bitwise logical operators. */ // simple assignment int z = 54; // plus-equals z += 5; System.out.println(z); // minus-equals z -= 10; System.out.println(z); // multiply-equals z *= 4; System.out.println(z); // divide-equals z /= 2; System.out.println(z); // mod-equals z %= 6; System.out.println(z); } }
UTF-8
Java
6,198
java
Operators.java
Java
[]
null
[]
package com.revature.basics; import java.util.ArrayList; import java.util.List; // The import below does not work because of a naming collision (which List would the compiler use?) //import java.awt.List; public class Operators { public static void main(String[] args) { /* * Operators * * Types: * - Unary * - Arithmetic * - Relational * - Logical * - Assignment * - Bitwise Shifting * - Ternary */ /* * Unary Operators * * Postfix and Prefix */ // prefix logical NOT boolean bool = true; System.out.println("not bool = " + !bool); // prefix positive int x = +456; System.out.println(x); // prefix negative int y = 78; System.out.println(-y); // prefix increment System.out.println(++x); // prefix decrement System.out.println(--x); // postfix increment System.out.println(y++); //postfix decrement System.out.println(y--); System.out.println(y); /* * Arithmetic Operators * * Addition * Subtraction * Multiplication * Division * Modulus */ // addition int mySum = 4 + 5; System.out.println(mySum); // subtraction int myDifference = mySum - 7; System.out.println(myDifference); // multiplication int myProduct = mySum * myDifference; System.out.println(myProduct); // division double myQuotient = myDifference / mySum; System.out.println(myQuotient); // this doesn't work properly, because our operands are ints! (The compiler is defaulting to integer division) myQuotient = 2 / 9; System.out.println(myQuotient); // this doesn't work myQuotient = 2d / 9d; System.out.println(myQuotient); // explicitly declaring the digits as double literals works! myQuotient = 2. / 9.; // digits are apparently optional after the decimal point System.out.println(myQuotient); // including the decimal places tells the compiler to treat these as floating point numbers myQuotient = 2. / 9; System.out.println(myQuotient); // we really only need to declare one of the operands as a double to get the compiler to do floating point division myQuotient = (double) myDifference / mySum; System.out.println(myQuotient); // to have compiler treat already declared variables differently, cast it as the type you need // REMEMBER TO BEWARE OF TRYING TO CONVERT LARGER DATA TYPES INTO SMALLER ONES!!! int myValue = 0; long myLongValue = 345345348768734345L; myValue = (int) myLongValue; System.out.println(myValue); // modulus operator (remainder) double myRemainder = 12 % 5; System.out.println(myRemainder); /* * Relational Operators */ int a = 0; int b = 1; int c = 2; int d = 2; String myStr = "hello"; ArrayList<String> myArrayList = new ArrayList<>(); // Greater-than, Less-than, Greater-than-or-equal, Less-than-or-equal System.out.println(a > b); System.out.println(a < b); System.out.println(c < d); System.out.println(c <= d); System.out.println(d >= a); System.out.println("------------"); // separator // instanceof returns true if the first operand is a type of the second operand System.out.println(myStr instanceof String); System.out.println(myStr instanceof Object); // since all Java objects directly/indirectly extend Object - this is true! System.out.println(myArrayList instanceof ArrayList); System.out.println(myArrayList instanceof List); // this returns true, even though List is an interface! System.out.println("------------"); // separator // is-equal, not-equal System.out.println(c == d); System.out.println(a != b); System.out.println("------------"); java.awt.List myAwtList; // I can still access non-imported classes using the fully-qualified path name /* * Logical Operators (Short-circuit operators) * * For instance, with AND (&&) - we know that both operands have to be true in order for the result to be true. So, if * the first operand evaluated is false - then we already know that the result is going to be false. * * Likewise, with OR (||) - the operation will return true if at least one of the operands is true. So, if the value of * the first operand is true, then there is no need to check the other. */ boolean value1 = true; boolean value2 = false; boolean value3 = true; // logical AND boolean result = value1 && value2; System.out.println(result); result = value1 && value3; System.out.println(result); // logical OR result = value1 || value2; System.out.println(result); /* * Bitwise Operators (Short-Circuit Operators) * * These are similar to the logical operators, and actually give the same results as their counterparts. But have specific * use cases dealing with binary values. * * XOR is a bit different, it is also known as the Exclusive-OR. This operator returns true if exactly one operand * has a true value. If both are true, then it will return false. Because of its nature, XOR must check both operands. */ // bitwise AND result = value2 & value1; System.out.println(result); // bitwise OR result = value1 | value2; System.out.println(result); // bitwise XOR result = value1 ^ value3; System.out.println(result); // declaring values in different bases int myBinary = 0b0010; // binary (base 2) int myOctal = 010; // octal (base 8) int myHex = 0x3f; // hexadecimal (base 16) System.out.println(myBinary); System.out.println(myOctal); System.out.println(myHex); /* * Assignment Operators * * In addition to the simple assignment that we have been using during variable initialization, we also have the compound * assignment operators at our disposal. These include compound assignment operators for arithmetic and bitwise logical operators. */ // simple assignment int z = 54; // plus-equals z += 5; System.out.println(z); // minus-equals z -= 10; System.out.println(z); // multiply-equals z *= 4; System.out.println(z); // divide-equals z /= 2; System.out.println(z); // mod-equals z %= 6; System.out.println(z); } }
6,198
0.66828
0.655534
225
26.542223
31.250519
149
false
false
0
0
0
0
0
0
2.431111
false
false
7
bef6715ca418a2265b8cde16cf5eccc18065b98a
9,491,877,748,012
b61db8cf613402a751bf4f9e54fbc784e025aa7e
/Better CPT/src/cpt/rewrite/Room1.java
b1b48b032cbff95d0e5752c189af26ab32c5c6b3
[]
no_license
Alexbajenaru/Even-Better-CPT
https://github.com/Alexbajenaru/Even-Better-CPT
506e9be62f09829dedeb7ff85a7cdc9f5f60c4fd
cef76c47fba06868f90d40fb9cca0def6e4eaaf8
refs/heads/master
2020-03-19T10:37:26.561000
2018-06-06T23:12:23
2018-06-06T23:12:23
136,387,024
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package cpt.rewrite; import javafx.scene.Scene; import javafx.scene.paint.Color; import javafx.scene.Group; import javafx.scene.shape.Rectangle; public class Room1 extends Room { public Room1() { super(); wallsColor = Color.DARKRED; doorColor = Color.BISQUE; createDoors(); createWalls(); fillRoom(); int enterX = (int) doors.getChildren().get(0).getTranslateX(); int enterY = (int) doors.getChildren().get(0).getTranslateY(); Room.setSpawnX(enterX + getDOOR_W()); Room.setSpawnY(enterY + getDOOR_H() / 2 - getPLAYER_H() / 2); spawnX = Room.getSpawnX(); spawnY = Room.getSpawnY(); player = new Player(spawnX, spawnY, true, getPLAYER_W(), getPLAYER_H()); root.getChildren().addAll(floor, walls, doors, roomObjects, player); scene = new Scene(root, getSCENE_W(), getSCENE_H()); setKeyHandlers(); } @Override public void createWalls() { walls = new Group(); Rectangle doorEnter = (Rectangle) doors.getChildren().get(0); Rectangle doorExit = (Rectangle) doors.getChildren().get(1); Rectangle rect; // top wall rect = new Rectangle(getROOM_W(), getWALL_W(), wallsColor); rect.setTranslateX(0); rect.setTranslateY(getHEADER_H()); walls.getChildren().add(rect); // bottom wall rect = new Rectangle(getROOM_W(), getWALL_W(), wallsColor); rect.setTranslateX(0); rect.setTranslateY(getROOM_H() - getWALL_W() +getHEADER_H()); walls.getChildren().add(rect); // left wall above door rect = new Rectangle(getWALL_W(), doorEnter.getTranslateY()-getHEADER_H(), wallsColor); rect.setTranslateX(0); rect.setTranslateY(getHEADER_H()); walls.getChildren().add(rect); // left wall under door rect = new Rectangle(getWALL_W(), getROOM_H()+ getHEADER_H() - getDOOR_H() - doorEnter.getTranslateY(), wallsColor); rect.setTranslateX(0); rect.setTranslateY(doorEnter.getTranslateY()+ getDOOR_H()); walls.getChildren().add(rect); // right wall above door rect = new Rectangle(getWALL_W(), doorExit.getTranslateY()- getHEADER_H(), wallsColor); // to find how long the vertical wall has to be, make it the length of the x coordinate of the door rect.setTranslateX(getROOM_W() - getWALL_W()); rect.setTranslateY(getHEADER_H()); walls.getChildren().add(rect); // right wall under door rect = new Rectangle(getWALL_W(), getROOM_H() + getHEADER_H() - doorExit.getTranslateY() - getDOOR_H(), wallsColor); rect.setTranslateX(getROOM_W() - getWALL_W()); rect.setTranslateY(doorExit.getTranslateY() + getDOOR_H()); walls.getChildren().add(rect); floor = new Group(); Rectangle bg = new Rectangle(0, 50, 900, 550); FloorMat mat = new FloorMat(800, 290, 75, 75); bg.setFill(Color.KHAKI); floor.getChildren().addAll(bg, mat); } @Override public void createDoors() { doors = new Group(); Rectangle door; // door enter (0) door = new Rectangle(getDOOR_W(), getDOOR_H(), doorColor); door.setTranslateX(0); door.setTranslateY(getROOM_H() - getDOOR_H() - 50 + getHEADER_H()); doors.getChildren().add(door); // door exit (1) door = new Rectangle(getDOOR_W(), getDOOR_H(), doorColor); door.setTranslateX(getROOM_W() - 10); door.setTranslateY(200 + getHEADER_H()); doors.getChildren().add(door); } @Override public void fillRoom() { roomObjects = new Group(); Crate crate = new Crate(780, 40, 50, 50); Crate crate2 = new Crate(830, 40, 50, 50); Crate crate3 = new Crate(830, 68, 50, 50); Crate crate4 = new Crate(250, 530, 50, 50); Crate crate5 = new Crate(300, 530, 50, 50); Table table = new Table(350, 250, 200, 100); Bookcase bookcase = new Bookcase(100, 20, 110, 75); Bookcase bookcase2 = new Bookcase(175, 20, 110, 75); Bookcase bookcase3 = new Bookcase(250, 20, 110, 75); Bookcase bookcase4 = new Bookcase(325, 20, 110, 75); Desk desk = new Desk(20, 220, 100, 175); DeskChair deskChair = new DeskChair(125, 280, 40, 40); IronBeam ironBeam = new IronBeam(500, 470, 50, 110); IronBeam ironBeam2 = new IronBeam(550, 470, 50, 110); IronBeam ironBeam3 = new IronBeam(600, 470, 50, 110); ComputerDesk computerDesk = new ComputerDesk(600, 20, 100, 75); roomObjects.getChildren().addAll(crate, crate2, crate3, crate4, crate5, table, bookcase, bookcase2, bookcase3, bookcase4, desk, deskChair, ironBeam, ironBeam2, ironBeam3, computerDesk); } }
UTF-8
Java
4,893
java
Room1.java
Java
[]
null
[]
package cpt.rewrite; import javafx.scene.Scene; import javafx.scene.paint.Color; import javafx.scene.Group; import javafx.scene.shape.Rectangle; public class Room1 extends Room { public Room1() { super(); wallsColor = Color.DARKRED; doorColor = Color.BISQUE; createDoors(); createWalls(); fillRoom(); int enterX = (int) doors.getChildren().get(0).getTranslateX(); int enterY = (int) doors.getChildren().get(0).getTranslateY(); Room.setSpawnX(enterX + getDOOR_W()); Room.setSpawnY(enterY + getDOOR_H() / 2 - getPLAYER_H() / 2); spawnX = Room.getSpawnX(); spawnY = Room.getSpawnY(); player = new Player(spawnX, spawnY, true, getPLAYER_W(), getPLAYER_H()); root.getChildren().addAll(floor, walls, doors, roomObjects, player); scene = new Scene(root, getSCENE_W(), getSCENE_H()); setKeyHandlers(); } @Override public void createWalls() { walls = new Group(); Rectangle doorEnter = (Rectangle) doors.getChildren().get(0); Rectangle doorExit = (Rectangle) doors.getChildren().get(1); Rectangle rect; // top wall rect = new Rectangle(getROOM_W(), getWALL_W(), wallsColor); rect.setTranslateX(0); rect.setTranslateY(getHEADER_H()); walls.getChildren().add(rect); // bottom wall rect = new Rectangle(getROOM_W(), getWALL_W(), wallsColor); rect.setTranslateX(0); rect.setTranslateY(getROOM_H() - getWALL_W() +getHEADER_H()); walls.getChildren().add(rect); // left wall above door rect = new Rectangle(getWALL_W(), doorEnter.getTranslateY()-getHEADER_H(), wallsColor); rect.setTranslateX(0); rect.setTranslateY(getHEADER_H()); walls.getChildren().add(rect); // left wall under door rect = new Rectangle(getWALL_W(), getROOM_H()+ getHEADER_H() - getDOOR_H() - doorEnter.getTranslateY(), wallsColor); rect.setTranslateX(0); rect.setTranslateY(doorEnter.getTranslateY()+ getDOOR_H()); walls.getChildren().add(rect); // right wall above door rect = new Rectangle(getWALL_W(), doorExit.getTranslateY()- getHEADER_H(), wallsColor); // to find how long the vertical wall has to be, make it the length of the x coordinate of the door rect.setTranslateX(getROOM_W() - getWALL_W()); rect.setTranslateY(getHEADER_H()); walls.getChildren().add(rect); // right wall under door rect = new Rectangle(getWALL_W(), getROOM_H() + getHEADER_H() - doorExit.getTranslateY() - getDOOR_H(), wallsColor); rect.setTranslateX(getROOM_W() - getWALL_W()); rect.setTranslateY(doorExit.getTranslateY() + getDOOR_H()); walls.getChildren().add(rect); floor = new Group(); Rectangle bg = new Rectangle(0, 50, 900, 550); FloorMat mat = new FloorMat(800, 290, 75, 75); bg.setFill(Color.KHAKI); floor.getChildren().addAll(bg, mat); } @Override public void createDoors() { doors = new Group(); Rectangle door; // door enter (0) door = new Rectangle(getDOOR_W(), getDOOR_H(), doorColor); door.setTranslateX(0); door.setTranslateY(getROOM_H() - getDOOR_H() - 50 + getHEADER_H()); doors.getChildren().add(door); // door exit (1) door = new Rectangle(getDOOR_W(), getDOOR_H(), doorColor); door.setTranslateX(getROOM_W() - 10); door.setTranslateY(200 + getHEADER_H()); doors.getChildren().add(door); } @Override public void fillRoom() { roomObjects = new Group(); Crate crate = new Crate(780, 40, 50, 50); Crate crate2 = new Crate(830, 40, 50, 50); Crate crate3 = new Crate(830, 68, 50, 50); Crate crate4 = new Crate(250, 530, 50, 50); Crate crate5 = new Crate(300, 530, 50, 50); Table table = new Table(350, 250, 200, 100); Bookcase bookcase = new Bookcase(100, 20, 110, 75); Bookcase bookcase2 = new Bookcase(175, 20, 110, 75); Bookcase bookcase3 = new Bookcase(250, 20, 110, 75); Bookcase bookcase4 = new Bookcase(325, 20, 110, 75); Desk desk = new Desk(20, 220, 100, 175); DeskChair deskChair = new DeskChair(125, 280, 40, 40); IronBeam ironBeam = new IronBeam(500, 470, 50, 110); IronBeam ironBeam2 = new IronBeam(550, 470, 50, 110); IronBeam ironBeam3 = new IronBeam(600, 470, 50, 110); ComputerDesk computerDesk = new ComputerDesk(600, 20, 100, 75); roomObjects.getChildren().addAll(crate, crate2, crate3, crate4, crate5, table, bookcase, bookcase2, bookcase3, bookcase4, desk, deskChair, ironBeam, ironBeam2, ironBeam3, computerDesk); } }
4,893
0.603515
0.558144
141
33.702129
33.217262
201
false
false
0
0
0
0
0
0
1.269504
false
false
7
2928571ddd1a2b26ed5d878c2775aaa964da7a3e
25,288,767,500,950
e67781f7f92dc36cd04bbc09b12523b02cad22cc
/src/main/java/com/haalthy/service/controller/Interface/ClinicTrail/GetClinicTrailInfoRequest.java
3c09d67f9d4604c65f616104940862dbd82e8137
[]
no_license
lilyangel/haalthyservice
https://github.com/lilyangel/haalthyservice
5968cc7104ca38ab3392ede92801aa25d4dbddbc
9960a9c6ac158e0f1b6c965261b58ab775783a4e
refs/heads/master
2020-12-14T20:29:05.808000
2016-04-20T22:42:29
2016-04-20T22:42:29
38,935,426
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.haalthy.service.controller.Interface.ClinicTrail; public class GetClinicTrailInfoRequest { private String drugType; private String subGroup; public String getDrugType() { return drugType; } public void setDrugType(String drugType) { this.drugType = drugType; } public String getSubGroup() { return subGroup; } public void setSubGroup(String subGroup) { this.subGroup = subGroup; } }
UTF-8
Java
414
java
GetClinicTrailInfoRequest.java
Java
[]
null
[]
package com.haalthy.service.controller.Interface.ClinicTrail; public class GetClinicTrailInfoRequest { private String drugType; private String subGroup; public String getDrugType() { return drugType; } public void setDrugType(String drugType) { this.drugType = drugType; } public String getSubGroup() { return subGroup; } public void setSubGroup(String subGroup) { this.subGroup = subGroup; } }
414
0.763285
0.763285
18
22
17.448336
61
false
false
0
0
0
0
0
0
1.388889
false
false
7
7123ddd1bf7570b97a848a1f113610319b9f78b1
10,660,108,892,011
826151b79e7a5b051370f0d8f27c1c97f16c24fa
/src/main/java/mis/profile/springprofile/auth/AppSecurityConfigDev.java
fd1f4f84f5af3eb61d68d7d517d7bc6f6fc884c3
[]
no_license
master-microservice/spring-profile
https://github.com/master-microservice/spring-profile
c393b8feb36b3ca0cfce3c80260cf6977d5c0fb4
7171178558dba693351ad6b2c327f190fa34b6d5
refs/heads/master
2023-02-05T12:53:54.797000
2020-12-19T06:04:02
2020-12-19T06:04:02
322,774,120
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package mis.profile.springprofile.auth; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Profile; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; @EnableWebSecurity @EnableConfigurationProperties @Profile("dev") public class AppSecurityConfigDev extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity httpSecurity) throws Exception { httpSecurity.csrf().disable() // Permit all requests without authentication .authorizeRequests().anyRequest().permitAll(); } }
UTF-8
Java
853
java
AppSecurityConfigDev.java
Java
[]
null
[]
package mis.profile.springprofile.auth; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Profile; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; @EnableWebSecurity @EnableConfigurationProperties @Profile("dev") public class AppSecurityConfigDev extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity httpSecurity) throws Exception { httpSecurity.csrf().disable() // Permit all requests without authentication .authorizeRequests().anyRequest().permitAll(); } }
853
0.806565
0.806565
20
41.650002
33.348576
101
false
false
0
0
0
0
0
0
0.35
false
false
7
41fbee0fb44fb5284bbb6ab091e23e2b47205a2d
15,023,795,663,986
c8376fec2cac6b5b044d31e0784cfc7e6530054a
/src/FINAL/Music.java
5189d45e9647ba86b70fc61b188d933534596e69
[]
no_license
RaicLee/JAVA_RhythmGame
https://github.com/RaicLee/JAVA_RhythmGame
f7c1ebf0f30e103ee41184badb7295d0f73ef99e
aa3e95c6f82b4e3c1516e7ad44c47df6cfc50587
refs/heads/main
2023-03-28T12:18:20.373000
2021-03-11T15:07:55
2021-03-11T15:07:55
346,738,279
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package FINAL; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import javazoom.jl.player.Player; public class Music extends Thread { private Player player; // 사용자 private boolean isLoop; // 반복 여부를 위한 변수 private File file; // 음악 파일을 받기 위한 변수 private FileInputStream fis; // 파일을 전달하기 위한 변수 private BufferedInputStream bis; // 플레이어 사용 및 생성을 위한 변수 // 이 클래스는 javazoom을 사용하여 만들어 졌다. public Music(String name, boolean isLoop) { try { file = new File(Main.class.getResource("../music/" + name).toURI()); fis = new FileInputStream(file); bis = new BufferedInputStream(fis); player = new Player(bis); this.isLoop = isLoop; // 파일을 toURI로 받아와서 file변수에 넣고 // fis안에 파일 inputstream으로 파일을 전달해준다. // bis에 fis를 버퍼 인풋스트림으로 전달하고 // 플레이어를 bis를 사용하여 생성한다. // 반복 여부를 받는 isLoop boolean변수에 값을 넣는다 } catch (Exception e) { System.out.println(e.getMessage()); } }// constructor // 하위 디렉토리에 있는 음악 파일에 접근한다 // 3.other functions 구현 // 시간 public int getTime() { if (player == null) return 0; return player.getPosition(); } // 플레이어의 시간과 노트가 내려오는 시간을 비교하여 싱크를 맞추어야 하므로 // 시간을 받아오는 gettime을 구현한다. // 곡 종료 public void close() { isLoop = false; player.close(); this.interrupt();// 곡 종료 } // 루프 거짓으로 초기화 // 플레이어 닫고 // MUSIC을 interrupt시키면서 끝낸다. // start 부분 @Override public void run() { // thread 상속 받으면 무조건 해야함 try { do { player.play(); fis = new FileInputStream(file); bis = new BufferedInputStream(fis); player = new Player(bis); } while (isLoop);// isLoop가 참인동안 계속 플레이어를 실행시키고 똑같은 파일을 받아온다 } catch (Exception e) { System.out.println(e.getMessage()); } } // http://kkckc.tistory.com/70참고 // http://story0111.tistory.com/36 참고 // http://gcyong.tistory.com/53 // 생성자로 노래 이름과 반복여부를 받는다. }
UHC
Java
2,477
java
Music.java
Java
[]
null
[]
package FINAL; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import javazoom.jl.player.Player; public class Music extends Thread { private Player player; // 사용자 private boolean isLoop; // 반복 여부를 위한 변수 private File file; // 음악 파일을 받기 위한 변수 private FileInputStream fis; // 파일을 전달하기 위한 변수 private BufferedInputStream bis; // 플레이어 사용 및 생성을 위한 변수 // 이 클래스는 javazoom을 사용하여 만들어 졌다. public Music(String name, boolean isLoop) { try { file = new File(Main.class.getResource("../music/" + name).toURI()); fis = new FileInputStream(file); bis = new BufferedInputStream(fis); player = new Player(bis); this.isLoop = isLoop; // 파일을 toURI로 받아와서 file변수에 넣고 // fis안에 파일 inputstream으로 파일을 전달해준다. // bis에 fis를 버퍼 인풋스트림으로 전달하고 // 플레이어를 bis를 사용하여 생성한다. // 반복 여부를 받는 isLoop boolean변수에 값을 넣는다 } catch (Exception e) { System.out.println(e.getMessage()); } }// constructor // 하위 디렉토리에 있는 음악 파일에 접근한다 // 3.other functions 구현 // 시간 public int getTime() { if (player == null) return 0; return player.getPosition(); } // 플레이어의 시간과 노트가 내려오는 시간을 비교하여 싱크를 맞추어야 하므로 // 시간을 받아오는 gettime을 구현한다. // 곡 종료 public void close() { isLoop = false; player.close(); this.interrupt();// 곡 종료 } // 루프 거짓으로 초기화 // 플레이어 닫고 // MUSIC을 interrupt시키면서 끝낸다. // start 부분 @Override public void run() { // thread 상속 받으면 무조건 해야함 try { do { player.play(); fis = new FileInputStream(file); bis = new BufferedInputStream(fis); player = new Player(bis); } while (isLoop);// isLoop가 참인동안 계속 플레이어를 실행시키고 똑같은 파일을 받아온다 } catch (Exception e) { System.out.println(e.getMessage()); } } // http://kkckc.tistory.com/70참고 // http://story0111.tistory.com/36 참고 // http://gcyong.tistory.com/53 // 생성자로 노래 이름과 반복여부를 받는다. }
2,477
0.635213
0.628888
79
22.012659
16.371861
71
false
false
0
0
0
0
0
0
1.810127
false
false
7
4edb007bace98cf1b31c2f44d5052bf52c6f6396
9,457,518,048,515
5b5dfbf8ad7f90e8090b29b01f03fe2600e598e4
/src/swimlee/programmers/codechallenge/Pick2AndAdd.java
20ecd8e9415293a2b580ee9b39917debcec3b215
[]
no_license
syleemk/Algorithm
https://github.com/syleemk/Algorithm
a00aea92915771dc50f07322a38037686238039e
21a94fe9a61d005a9e4dab20bdeb2abc619718ca
refs/heads/master
2023-06-17T17:50:24.909000
2021-07-13T14:59:09
2021-07-13T14:59:09
328,723,197
1
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package swimlee.programmers.codechallenge; import java.util.*; import java.util.stream.Collectors; public class Pick2AndAdd { public static void main(String[] args) { int[] numbers = {2,1,3,4,1}; Pick2AndAdd pick2AndAdd = new Pick2AndAdd(); int[] solution = pick2AndAdd.solution(numbers); System.out.println("solution = " + Arrays.toString(solution)); } public int[] solution(int[] numbers) { Set<Integer> set = new TreeSet<>(); for (int i = 0; i < numbers.length-1; i++) { for (int j = i + 1; j < numbers.length; j++) { set.add(numbers[i] + numbers[j]); } } return set.stream().mapToInt(Integer::intValue).toArray(); } }
UTF-8
Java
748
java
Pick2AndAdd.java
Java
[]
null
[]
package swimlee.programmers.codechallenge; import java.util.*; import java.util.stream.Collectors; public class Pick2AndAdd { public static void main(String[] args) { int[] numbers = {2,1,3,4,1}; Pick2AndAdd pick2AndAdd = new Pick2AndAdd(); int[] solution = pick2AndAdd.solution(numbers); System.out.println("solution = " + Arrays.toString(solution)); } public int[] solution(int[] numbers) { Set<Integer> set = new TreeSet<>(); for (int i = 0; i < numbers.length-1; i++) { for (int j = i + 1; j < numbers.length; j++) { set.add(numbers[i] + numbers[j]); } } return set.stream().mapToInt(Integer::intValue).toArray(); } }
748
0.578877
0.561497
26
27.76923
23.677818
70
false
false
0
0
0
0
0
0
0.692308
false
false
7
fbc9d1ca1af07941377f5d17be54a48f3bb613f3
472,446,403,035
5f1b004e3a3fd9b516f4cec77b7973f9cbec4e11
/src/main/java/module-info.java
e5ec6f0df129decc299e4fd251aa6c07a388dd51
[ "Apache-2.0" ]
permissive
mejsla/vassare-jimp
https://github.com/mejsla/vassare-jimp
80168c593f2f10b485b19dd13c14e089fdbd74a0
0d51b85a8fa956df02a0ddfb686e2f5cd3af6f49
refs/heads/master
2022-06-29T15:26:06.203000
2020-05-13T16:49:08
2020-05-13T16:49:08
261,531,149
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
module se.mejsla.jimp { requires javafx.controls; requires javafx.fxml; requires javafx.swing; requires java.desktop; opens se.mejsla.jimp to javafx.fxml; exports se.mejsla.jimp; }
UTF-8
Java
213
java
module-info.java
Java
[]
null
[]
module se.mejsla.jimp { requires javafx.controls; requires javafx.fxml; requires javafx.swing; requires java.desktop; opens se.mejsla.jimp to javafx.fxml; exports se.mejsla.jimp; }
213
0.676056
0.676056
9
21.888889
12.314801
40
false
false
0
0
0
0
0
0
0.666667
false
false
7
a6e1e0bf38601dad6fddaceda159f928171cfb64
25,735,444,106,696
75d3c715dfcd0a05934524994ba66e9b0cd89d4f
/src/com/polymart/service/IChiTietSanPhamService.java
946692710fa155ab6743321d30200ee40f7538fc
[]
no_license
holiday96/Poly-mart
https://github.com/holiday96/Poly-mart
a5bab3faef739b5660f60a586aeb63412a17bf8a
ce8809965617f150935134e226d1fdbcc77be147
refs/heads/master
2023-04-18T02:07:38.174000
2021-04-27T01:02:26
2021-04-27T01:02:26
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.polymart.service; import java.util.List; import com.polymart.model.ChiTietSanPhamModel; import com.polymart.model.UpdatePhotoProduct; public interface IChiTietSanPhamService { List<ChiTietSanPhamModel> findAll(); List<ChiTietSanPhamModel> findByIdOrNameProduct(String input); List<ChiTietSanPhamModel> findAllByHoaDonThanhToan(); int saveProduct(List<ChiTietSanPhamModel> lstChiTietSanPham, List<UpdatePhotoProduct> lstPhoto); Integer getIdProductById(Integer id); void reloadData(); ChiTietSanPhamModel getById(Integer id); boolean updatePrice(int id, Long giaBan, Long giaGiam); boolean checkThemMoiSanPham(ChiTietSanPhamModel chiTietSanPhamModel); }
UTF-8
Java
714
java
IChiTietSanPhamService.java
Java
[]
null
[]
package com.polymart.service; import java.util.List; import com.polymart.model.ChiTietSanPhamModel; import com.polymart.model.UpdatePhotoProduct; public interface IChiTietSanPhamService { List<ChiTietSanPhamModel> findAll(); List<ChiTietSanPhamModel> findByIdOrNameProduct(String input); List<ChiTietSanPhamModel> findAllByHoaDonThanhToan(); int saveProduct(List<ChiTietSanPhamModel> lstChiTietSanPham, List<UpdatePhotoProduct> lstPhoto); Integer getIdProductById(Integer id); void reloadData(); ChiTietSanPhamModel getById(Integer id); boolean updatePrice(int id, Long giaBan, Long giaGiam); boolean checkThemMoiSanPham(ChiTietSanPhamModel chiTietSanPhamModel); }
714
0.792717
0.792717
28
24.5
28.320234
100
false
false
0
0
0
0
0
0
0.571429
false
false
7
d72738503a1e6d281da16f1560f8ae471b5a9ddf
3,736,621,568,514
d4be840f83b9b0c7b496eabba72504941c369b5d
/app/src/main/java/in/nsrinfo/tutorial/SmsListActivity.java
3e81d3db6cda483952bd7467751223c8e9c7a9d0
[]
no_license
nsrinfo/Tutorial
https://github.com/nsrinfo/Tutorial
a6853cd443e09992af744f591e0f10ea2021a012
7468683ddf9e7badec56e720aef7870f919e1923
refs/heads/master
2020-05-29T09:16:45.622000
2016-10-07T16:01:13
2016-10-07T16:01:13
69,447,247
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package in.nsrinfo.tutorial; import android.app.ListActivity; import android.os.Build; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.ArrayAdapter; import android.widget.Toast; import in.nsrinfo.tutorial.sms.Sms; public class SmsListActivity extends ListActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_sms_list); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT){ ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.activity_list_item, android.R.id.text1, Sms.getSmsList(this)); setListAdapter(adapter); }else{ Toast.makeText(this, "Version not supported", Toast.LENGTH_LONG).show(); } } }
UTF-8
Java
862
java
SmsListActivity.java
Java
[]
null
[]
package in.nsrinfo.tutorial; import android.app.ListActivity; import android.os.Build; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.ArrayAdapter; import android.widget.Toast; import in.nsrinfo.tutorial.sms.Sms; public class SmsListActivity extends ListActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_sms_list); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT){ ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.activity_list_item, android.R.id.text1, Sms.getSmsList(this)); setListAdapter(adapter); }else{ Toast.makeText(this, "Version not supported", Toast.LENGTH_LONG).show(); } } }
862
0.718097
0.715777
26
32.153847
32.998474
153
false
false
0
0
0
0
0
0
0.692308
false
false
7
1928be4eabaead112719db67ff708f6a5b4fb448
18,133,351,936,991
67934dd3dfa02e8aac0b76c1043b1935a68ef678
/src/test/java/com/github/lindenb/jvarkit/tools/structvar/SamScanSplitReadsTest.java
b6f7a2336ae1e1a6a5fd730ccf760089392acecd
[ "MIT" ]
permissive
lindenb/jvarkit
https://github.com/lindenb/jvarkit
5dbb37a1eda66b76c4ba495f1f52e9ec023fc37f
3d336e522b2862e7f9490bbdfc80b219e68532e2
refs/heads/master
2023-08-22T13:27:44.758000
2023-05-05T15:32:15
2023-05-05T15:32:15
9,889,013
423
150
NOASSERTION
false
2023-01-27T14:39:22
2013-05-06T14:49:08
2023-01-26T20:37:36
2023-01-27T14:39:22
60,310
393
125
47
Java
false
false
package com.github.lindenb.jvarkit.tools.structvar; import java.nio.file.Path; import org.testng.Assert; import org.testng.annotations.Test; import com.github.lindenb.jvarkit.tests.AlsoTest; import com.github.lindenb.jvarkit.tools.tests.TestSupport; import com.github.lindenb.jvarkit.util.jcommander.LauncherTest; @AlsoTest(LauncherTest.class) public class SamScanSplitReadsTest { @Test public void test01() throws java.io.IOException { final TestSupport support = new TestSupport(); try { final Path out= support.createTmpPath(".vcf"); Assert.assertEquals(new SamScanSplitReads().instanceMain(new String[] { "-o",out.toString(), support.resource("S1.bam"), support.resource("S2.bam"), support.resource("S3.bam") }),0); support.assertIsVcf(out); } finally { support.removeTmpFiles(); } } }
UTF-8
Java
838
java
SamScanSplitReadsTest.java
Java
[]
null
[]
package com.github.lindenb.jvarkit.tools.structvar; import java.nio.file.Path; import org.testng.Assert; import org.testng.annotations.Test; import com.github.lindenb.jvarkit.tests.AlsoTest; import com.github.lindenb.jvarkit.tools.tests.TestSupport; import com.github.lindenb.jvarkit.util.jcommander.LauncherTest; @AlsoTest(LauncherTest.class) public class SamScanSplitReadsTest { @Test public void test01() throws java.io.IOException { final TestSupport support = new TestSupport(); try { final Path out= support.createTmpPath(".vcf"); Assert.assertEquals(new SamScanSplitReads().instanceMain(new String[] { "-o",out.toString(), support.resource("S1.bam"), support.resource("S2.bam"), support.resource("S3.bam") }),0); support.assertIsVcf(out); } finally { support.removeTmpFiles(); } } }
838
0.738663
0.731504
33
24.39394
21.346973
73
false
false
0
0
0
0
0
0
1.787879
false
false
7
3a9a377215c773a4e5b2c6c9314e8ae2a811b251
21,457,656,646,031
0b24685aaf0ab7bb389d476d03ceeaa283618c0a
/Main.java
77b4ce1411c9dfc83e16e1bcc5459779b8807443
[]
no_license
PRAPCS/MathClassExamples19
https://github.com/PRAPCS/MathClassExamples19
e4a813b30ba5ab425eded138109b5a966156b405
c0b7f50bea3a085aebf0c8ab933088cc84ff1690
refs/heads/master
2020-09-11T03:09:10.920000
2019-11-15T12:39:12
2019-11-15T12:39:12
221,921,554
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
public class Main { public static void main (String[] args) { double num1 = 5.2; double num2 = -10.5; int num3 = 2; double num4; num4 = Math.abs(num2); System.out.println(num4); System.out.println(Math.abs(-123456)); num4 = Math.pow(num1,num3); System.out.println(num4); System.out.println(Math.pow(2,8)); System.out.println(Math.sqrt(9)); num4 = Math.random(); // 0.0 to less than 1.0 System.out.println("================Random Number Below========================="); System.out.println(num4); num4 = Math.random()*20;//0.0 to less than 20.0 System.out.println(num4); num3 = (int)(Math.random()*20);//0 to 19 System.out.println(num3); num3 = (int)(Math.random()*20)+1;//1 to 20 System.out.println(num3); } }
UTF-8
Java
866
java
Main.java
Java
[]
null
[]
public class Main { public static void main (String[] args) { double num1 = 5.2; double num2 = -10.5; int num3 = 2; double num4; num4 = Math.abs(num2); System.out.println(num4); System.out.println(Math.abs(-123456)); num4 = Math.pow(num1,num3); System.out.println(num4); System.out.println(Math.pow(2,8)); System.out.println(Math.sqrt(9)); num4 = Math.random(); // 0.0 to less than 1.0 System.out.println("================Random Number Below========================="); System.out.println(num4); num4 = Math.random()*20;//0.0 to less than 20.0 System.out.println(num4); num3 = (int)(Math.random()*20);//0 to 19 System.out.println(num3); num3 = (int)(Math.random()*20)+1;//1 to 20 System.out.println(num3); } }
866
0.533487
0.468822
31
26.903225
20.907408
90
false
false
0
0
0
0
0
0
0.709677
false
false
7
5c0e4b118ef3e9a510ef2d93c5b10a809786101f
2,224,793,090,181
8a5e5849d988cfa785efbf712715e761136a2ab3
/MBank/phase1/actions_classes/AdminAction.java
7bffeb2015d43fa75f3181047a01b93897b65ebe
[]
no_license
noanaaman/MBank
https://github.com/noanaaman/MBank
af73140efb07f6f9a077917a00daf353aec22ef8
1ff483c718ec8f987ca7fee967421da9562058b9
refs/heads/master
2021-01-25T06:36:50.134000
2016-02-18T17:51:18
2016-02-18T17:51:18
22,767,553
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package actions_classes; import java.sql.Connection; import java.sql.SQLException; import java.util.ArrayList; import java.util.Calendar; import enums.ClientType; import bank_beans.Account; import bank_beans.Activity; import bank_beans.Client; import bank_beans.Deposit; import bank_beans.Property; import bank_exceptions.MBankException; public class AdminAction extends Action { public AdminAction(Connection con, long id) { super(con, id); // TODO Auto-generated constructor stub } public long addNewClient(String clientName, String password, String address, String email, String phone, String clientComment, String accountComment, double firstDeposit) throws MBankException, SQLException { double regularDepositRate = Double.parseDouble(propertyManager.query("regular_deposit_rate", con).getProp_value()); double goldDepositRate = Double.parseDouble(propertyManager.query("gold_deposit_rate", con).getProp_value()); double platinumDepositRate = Double.parseDouble(propertyManager.query("platinum_deposit_rate", con).getProp_value()); if ((firstDeposit >= regularDepositRate)&(firstDeposit < goldDepositRate)) { ClientType type = ClientType.REGULAR; String regularCreditLimit = propertyManager.query("regular_credit_limit", con).getProp_value(); Client client = new Client(0, clientName, password, type, address, email, phone, clientComment); long clientId = clientManager.insert(client, con); Account account = new Account(0,clientId,firstDeposit,regularCreditLimit,accountComment); accountsManager.insert(account, con); return clientId; } else if ((firstDeposit >= goldDepositRate)&(firstDeposit < platinumDepositRate)) { ClientType type = ClientType.GOLD; String goldCreditLimit = propertyManager.query("gold_credit_limit", con).getProp_value(); Client client = new Client(0, clientName, password, type, address, email, phone, clientComment); long clientId = clientManager.insert(client, con); Account account = new Account(0,clientId,firstDeposit,goldCreditLimit,accountComment); accountsManager.insert(account, con); return clientId; } else if (firstDeposit >= platinumDepositRate) { ClientType type = ClientType.PLATINUM; String platinumCreditLimit = propertyManager.query("platinum_credit_limit", con).getProp_value(); Client client = new Client(0, clientName, password, type, address, email, phone, clientComment); long clientId = clientManager.insert(client, con); Account account = new Account(0,clientId, firstDeposit, platinumCreditLimit, accountComment); accountsManager.insert(account, con); return clientId; } else throw new MBankException("In order to open an account, client must deposit at least " + regularDepositRate + "."); } public void removeClient(long clientId) throws MBankException { Account account = accountsManager.queryAccountByClient(clientId, con); ArrayList<Deposit> depositsList = depositManager.queryDepositsByClient(clientId, con); if (depositsList == null) { System.out.println("Client had no deposits"); } else { for (int i = 0; i < depositsList.size(); i++) { double comission = Double.parseDouble(propertyManager.query("pre_open_fee", con).getProp_value()) * depositsList.get(i).getBalance(); account.setBalance(account.getBalance() + depositsList.get(i).getBalance() - comission); Activity act = new Activity(0, id, depositsList.get(i).getBalance(), Calendar.getInstance(), comission, "Client " + clientId + " pre-opened deposit " + depositsList.get(i).getDeposit_id() + "."); depositManager.delete(depositsList.get(i), con); activityManager.insert(act, con); } } if (account.getBalance() < 0) { Activity removeAccount = new Activity(0, clientId, account.getBalance(), Calendar.getInstance(), 0, "Client charged due to negative balance account on client removal."); activityManager.insert(removeAccount, con); } accountsManager.delete(account, con); Client c = clientManager.query(clientId, con); clientManager.delete(c, con); } public Account viewAccountByClient (long clientId) throws MBankException { return accountsManager.queryAccountByClient(clientId, con); } public ArrayList<Client> viewAllClientsDetails() throws MBankException { return clientManager.queryAllClients(con); } public ArrayList<Account> viewAllAccountsDetails() throws MBankException { return accountsManager.queryAllAccounts(con); } public ArrayList<Deposit> viewAllDeposits() throws MBankException { return depositManager.queryAllDeposits(con); } public ArrayList<Activity> viewAllActivities() throws MBankException { return activityManager.queryAllActivities(con); } public void updateSystemProperty(Property property) throws MBankException { propertyManager.update(property, con); } public ArrayList<Property> viewAllSystemProperties() throws MBankException { return propertyManager.queryAllProperties(con); } }
UTF-8
Java
5,071
java
AdminAction.java
Java
[]
null
[]
package actions_classes; import java.sql.Connection; import java.sql.SQLException; import java.util.ArrayList; import java.util.Calendar; import enums.ClientType; import bank_beans.Account; import bank_beans.Activity; import bank_beans.Client; import bank_beans.Deposit; import bank_beans.Property; import bank_exceptions.MBankException; public class AdminAction extends Action { public AdminAction(Connection con, long id) { super(con, id); // TODO Auto-generated constructor stub } public long addNewClient(String clientName, String password, String address, String email, String phone, String clientComment, String accountComment, double firstDeposit) throws MBankException, SQLException { double regularDepositRate = Double.parseDouble(propertyManager.query("regular_deposit_rate", con).getProp_value()); double goldDepositRate = Double.parseDouble(propertyManager.query("gold_deposit_rate", con).getProp_value()); double platinumDepositRate = Double.parseDouble(propertyManager.query("platinum_deposit_rate", con).getProp_value()); if ((firstDeposit >= regularDepositRate)&(firstDeposit < goldDepositRate)) { ClientType type = ClientType.REGULAR; String regularCreditLimit = propertyManager.query("regular_credit_limit", con).getProp_value(); Client client = new Client(0, clientName, password, type, address, email, phone, clientComment); long clientId = clientManager.insert(client, con); Account account = new Account(0,clientId,firstDeposit,regularCreditLimit,accountComment); accountsManager.insert(account, con); return clientId; } else if ((firstDeposit >= goldDepositRate)&(firstDeposit < platinumDepositRate)) { ClientType type = ClientType.GOLD; String goldCreditLimit = propertyManager.query("gold_credit_limit", con).getProp_value(); Client client = new Client(0, clientName, password, type, address, email, phone, clientComment); long clientId = clientManager.insert(client, con); Account account = new Account(0,clientId,firstDeposit,goldCreditLimit,accountComment); accountsManager.insert(account, con); return clientId; } else if (firstDeposit >= platinumDepositRate) { ClientType type = ClientType.PLATINUM; String platinumCreditLimit = propertyManager.query("platinum_credit_limit", con).getProp_value(); Client client = new Client(0, clientName, password, type, address, email, phone, clientComment); long clientId = clientManager.insert(client, con); Account account = new Account(0,clientId, firstDeposit, platinumCreditLimit, accountComment); accountsManager.insert(account, con); return clientId; } else throw new MBankException("In order to open an account, client must deposit at least " + regularDepositRate + "."); } public void removeClient(long clientId) throws MBankException { Account account = accountsManager.queryAccountByClient(clientId, con); ArrayList<Deposit> depositsList = depositManager.queryDepositsByClient(clientId, con); if (depositsList == null) { System.out.println("Client had no deposits"); } else { for (int i = 0; i < depositsList.size(); i++) { double comission = Double.parseDouble(propertyManager.query("pre_open_fee", con).getProp_value()) * depositsList.get(i).getBalance(); account.setBalance(account.getBalance() + depositsList.get(i).getBalance() - comission); Activity act = new Activity(0, id, depositsList.get(i).getBalance(), Calendar.getInstance(), comission, "Client " + clientId + " pre-opened deposit " + depositsList.get(i).getDeposit_id() + "."); depositManager.delete(depositsList.get(i), con); activityManager.insert(act, con); } } if (account.getBalance() < 0) { Activity removeAccount = new Activity(0, clientId, account.getBalance(), Calendar.getInstance(), 0, "Client charged due to negative balance account on client removal."); activityManager.insert(removeAccount, con); } accountsManager.delete(account, con); Client c = clientManager.query(clientId, con); clientManager.delete(c, con); } public Account viewAccountByClient (long clientId) throws MBankException { return accountsManager.queryAccountByClient(clientId, con); } public ArrayList<Client> viewAllClientsDetails() throws MBankException { return clientManager.queryAllClients(con); } public ArrayList<Account> viewAllAccountsDetails() throws MBankException { return accountsManager.queryAllAccounts(con); } public ArrayList<Deposit> viewAllDeposits() throws MBankException { return depositManager.queryAllDeposits(con); } public ArrayList<Activity> viewAllActivities() throws MBankException { return activityManager.queryAllActivities(con); } public void updateSystemProperty(Property property) throws MBankException { propertyManager.update(property, con); } public ArrayList<Property> viewAllSystemProperties() throws MBankException { return propertyManager.queryAllProperties(con); } }
5,071
0.743443
0.741274
117
41.341881
42.951206
209
false
false
0
0
0
0
0
0
2.854701
false
false
7
69805b6fcef5d797e459e641038ad2984d5dbb32
26,740,466,398,931
584460f390f654bbf98b720015f05aa80f6ef911
/src/main/java/com/teamtreehouse/instateam/model/Project.java
81728b70460453f26239a935a537846eb0875283
[]
no_license
jamaal729/J-Project-07
https://github.com/jamaal729/J-Project-07
aa45fdff96feda7a85f3430ca54b280c68c93e6c
fc3a7dc6a7311f62d8595a71bfc21591c6ad8f87
refs/heads/master
2021-01-20T05:40:47.544000
2019-12-09T14:47:56
2019-12-09T14:47:56
101,462,303
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.teamtreehouse.instateam.model; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.ManyToMany; import javax.validation.constraints.Size; import java.util.List; @Entity public class Project { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; @Size(min = 3, max = 30) private String name; @Size(min = 3, max = 30) private String description; private String status; @ManyToMany private List<Role> rolesNeeded; @ManyToMany private List<Collaborator> collaborators; public Project() { } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public List<Role> getRolesNeeded() { return rolesNeeded; } public void setRolesNeeded(List<Role> rolesNeeded) { this.rolesNeeded = rolesNeeded; } public List<Collaborator> getCollaborators() { return collaborators; } public void setCollaborators(List<Collaborator> collaborators) { this.collaborators = collaborators; } @Override public String toString() { return "Project{" + "id=" + id + ", name='" + name + '\'' + ", description='" + description + '\'' + ", status='" + status + '\'' + ", rolesNeeded=" + rolesNeeded + ", collaborators=" + collaborators + '}'; } } /*Create the Project model class, which represents a project for which a project manager is seeking collaborators. Each project should contain the following: id: auto-generated numeric identifier to serve as the table’s primary key name: alphanumeric, reader-friendly name to be displayed. This is a required field for data validation. description: longer description of the project. This is a required field for data validation. status: alphanumeric status of the project, for example “recruiting” or “on hold” rolesNeeded: collection of Role objects representing all roles needed for this project, regardless of whether or not they’ve been filled. For proper data association, keep in mind that there could be many projects that contain many Role objects. That is, each project can have many roles that it needs, and each role can be needed by many projects. collaborators: collection of Collaborator objects representing any collaborators that have been assigned to this project. For data association, use the fact that there could be many projects that contain many Collaborator objects. That is, each project can have many collaborators, and each collaborator can work on many projects. Getters and setters for all fields Default constructor*/
UTF-8
Java
3,337
java
Project.java
Java
[]
null
[]
package com.teamtreehouse.instateam.model; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.ManyToMany; import javax.validation.constraints.Size; import java.util.List; @Entity public class Project { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; @Size(min = 3, max = 30) private String name; @Size(min = 3, max = 30) private String description; private String status; @ManyToMany private List<Role> rolesNeeded; @ManyToMany private List<Collaborator> collaborators; public Project() { } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public List<Role> getRolesNeeded() { return rolesNeeded; } public void setRolesNeeded(List<Role> rolesNeeded) { this.rolesNeeded = rolesNeeded; } public List<Collaborator> getCollaborators() { return collaborators; } public void setCollaborators(List<Collaborator> collaborators) { this.collaborators = collaborators; } @Override public String toString() { return "Project{" + "id=" + id + ", name='" + name + '\'' + ", description='" + description + '\'' + ", status='" + status + '\'' + ", rolesNeeded=" + rolesNeeded + ", collaborators=" + collaborators + '}'; } } /*Create the Project model class, which represents a project for which a project manager is seeking collaborators. Each project should contain the following: id: auto-generated numeric identifier to serve as the table’s primary key name: alphanumeric, reader-friendly name to be displayed. This is a required field for data validation. description: longer description of the project. This is a required field for data validation. status: alphanumeric status of the project, for example “recruiting” or “on hold” rolesNeeded: collection of Role objects representing all roles needed for this project, regardless of whether or not they’ve been filled. For proper data association, keep in mind that there could be many projects that contain many Role objects. That is, each project can have many roles that it needs, and each role can be needed by many projects. collaborators: collection of Collaborator objects representing any collaborators that have been assigned to this project. For data association, use the fact that there could be many projects that contain many Collaborator objects. That is, each project can have many collaborators, and each collaborator can work on many projects. Getters and setters for all fields Default constructor*/
3,337
0.670376
0.668571
102
31.59804
51.935341
356
false
false
0
0
0
0
0
0
0.431373
false
false
7
049e4c04b1aa8f28b322ceece3a40a76e460ff0e
17,910,013,653,323
2fb177491e73679f62c4cdf3daf13cfd85d46d05
/app/src/main/java/com/coffeearmy/marvelheroes/base/BaseViewModel.java
8c62693df15bc3b6bb6b36d773d25b2b96532fd0
[ "MIT" ]
permissive
coffeearmy/MarvelHeroes
https://github.com/coffeearmy/MarvelHeroes
22ffae7fc00520f1f9b6799267cd6c25e5d9caf9
994c32e394f3195a86c6bfb0e83b1d643eea5bad
refs/heads/master
2021-01-17T08:25:12.239000
2017-03-11T18:51:43
2017-03-11T18:51:43
83,907,408
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.coffeearmy.marvelheroes.base; /** * */ public interface BaseViewModel { void showLoading(); void hideLoading(); void showError(); }
UTF-8
Java
163
java
BaseViewModel.java
Java
[]
null
[]
package com.coffeearmy.marvelheroes.base; /** * */ public interface BaseViewModel { void showLoading(); void hideLoading(); void showError(); }
163
0.656442
0.656442
14
10.642858
13.735289
41
false
false
0
0
0
0
0
0
0.285714
false
false
7
82227b598f489ea4863bcd4971c5e1293752b81e
6,451,040,915,325
6d1961c9aca3125e6719e80e21eb1f80d24a0cd1
/library/src/main/java/net/adamjak/thomas/graph/library/tests/GraphTest.java
779baf76d06fdeb8d1d497bb194c60e49508b52f
[]
no_license
adamjak/graph
https://github.com/adamjak/graph
4506c42bcaaf52c0c7e9248d63fd5f8880739889
40942e173e55b78147148085f3421a9713680e74
refs/heads/master
2021-01-20T11:47:54.065000
2017-04-21T19:53:27
2017-04-21T19:53:27
48,381,128
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package net.adamjak.thomas.graph.library.tests; import net.adamjak.thomas.graph.library.api.Graph; import java.util.concurrent.Callable; import java.util.concurrent.CancellationException; import java.util.concurrent.ExecutionException; import java.util.concurrent.RecursiveTask; /** * Created by Tomas Adamjak on 9.10.2016. * Copyright 2016, Tomas Adamjak * License: The BSD 3-Clause License */ public abstract class GraphTest<T extends Comparable> extends RecursiveTask<GraphTestResult> implements Callable<GraphTestResult> { protected Graph<T> graph; public abstract void init (Graph<T> graph); /** * Waits if necessary for the computation to complete, and then * retrieves its result. * * @return the computed result * @throws CancellationException if the computation was cancelled * @throws ExecutionException if the computation threw an * exception * @throws InterruptedException if the current thread is not a * member of a ForkJoinPool and was interrupted while waiting */ public final GraphTestResult getResult() throws ExecutionException, InterruptedException { return super.get(); } public Graph<T> getGraph () { return this.graph; } }
UTF-8
Java
1,189
java
GraphTest.java
Java
[ { "context": ".util.concurrent.RecursiveTask;\n\n/**\n * Created by Tomas Adamjak on 9.10.2016.\n * Copyright 2016, Tomas Adamjak\n *", "end": 313, "score": 0.9998381733894348, "start": 300, "tag": "NAME", "value": "Tomas Adamjak" }, { "context": " by Tomas Adamjak on 9.10.2016.\n * Copyright 2016, Tomas Adamjak\n * License: The BSD 3-Clause License\n */\npublic a", "end": 360, "score": 0.9998276829719543, "start": 347, "tag": "NAME", "value": "Tomas Adamjak" } ]
null
[]
package net.adamjak.thomas.graph.library.tests; import net.adamjak.thomas.graph.library.api.Graph; import java.util.concurrent.Callable; import java.util.concurrent.CancellationException; import java.util.concurrent.ExecutionException; import java.util.concurrent.RecursiveTask; /** * Created by <NAME> on 9.10.2016. * Copyright 2016, <NAME> * License: The BSD 3-Clause License */ public abstract class GraphTest<T extends Comparable> extends RecursiveTask<GraphTestResult> implements Callable<GraphTestResult> { protected Graph<T> graph; public abstract void init (Graph<T> graph); /** * Waits if necessary for the computation to complete, and then * retrieves its result. * * @return the computed result * @throws CancellationException if the computation was cancelled * @throws ExecutionException if the computation threw an * exception * @throws InterruptedException if the current thread is not a * member of a ForkJoinPool and was interrupted while waiting */ public final GraphTestResult getResult() throws ExecutionException, InterruptedException { return super.get(); } public Graph<T> getGraph () { return this.graph; } }
1,175
0.771236
0.761144
41
28
29.078531
129
false
false
0
0
0
0
0
0
0.878049
false
false
7
21b8a002ea344474d46591ea8276aceab391f06f
1,159,641,223,194
142c3674e8b7ef5a74ce8559603d72dbc7ce7e7e
/blade-service/blade-bg-admin/src/main/java/org/springblade/bgadmin/modules/sys/entity/AccountRechargeWithUserEntity.java
f08ce4ca213337100213035d7a16c0043b88832e
[]
no_license
linxiumeng/zhonghong
https://github.com/linxiumeng/zhonghong
1be62ad2e365721a872d6e53d2688c10fb166d0a
48a8dfe367a4b6b2c929cc2a94877de375330957
refs/heads/master
2022-07-30T08:46:39.392000
2019-06-04T09:50:12
2019-06-04T09:50:12
190,371,668
0
0
null
false
2022-07-06T20:37:28
2019-06-05T10:03:58
2019-06-05T10:17:47
2022-07-06T20:37:28
2,799
0
0
10
JavaScript
false
false
package org.springblade.bgadmin.modules.sys.entity; import lombok.Data; import java.io.Serializable; @Data public class AccountRechargeWithUserEntity extends AccountRechargeEntity implements Serializable { private static final long serialVersionUID = 1L; private FuserEntity userEntity; }
UTF-8
Java
303
java
AccountRechargeWithUserEntity.java
Java
[]
null
[]
package org.springblade.bgadmin.modules.sys.entity; import lombok.Data; import java.io.Serializable; @Data public class AccountRechargeWithUserEntity extends AccountRechargeEntity implements Serializable { private static final long serialVersionUID = 1L; private FuserEntity userEntity; }
303
0.811881
0.808581
14
20.642857
28.459513
98
false
false
0
0
0
0
0
0
0.357143
false
false
7
0c62e595b9feae3953e087dacb8e6dcecce569db
25,357,486,932,992
8942159d56a57c33a03ca7cc13614a03b62fbf45
/src/customerPage/paymentsettings/PaymentSettingPane.java
52a818b9738238518f2f459560687428dcbf2743
[]
no_license
molleer/iMat
https://github.com/molleer/iMat
3c4ec982dda69a0af14a314daa32b4734a9c79ee
0b152d6f538362b1c6b88e6315d6a13ef87eaab3
refs/heads/master
2020-05-09T22:28:10.768000
2019-06-03T15:20:14
2019-06-03T15:20:14
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package customerPage.paymentsettings; import customerPage.SettingsPane; import customerPage.personaldatapane.PersonalDataPane; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.collections.MapChangeListener; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.scene.control.*; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.input.MouseEvent; import javafx.scene.layout.AnchorPane; import se.chalmers.cse.dat216.project.CreditCard; import se.chalmers.cse.dat216.project.IMatDataHandler; import java.io.IOException; public class PaymentSettingPane extends SettingsPane { IMatDataHandler handler = IMatDataHandler.getInstance(); @FXML RadioButton cardPayRadioButton, deliveryRadioButton, billRadioButton; @FXML TextField entry1, entry2, entry3, entry4; @FXML Label billingAddress; private final TextField entries[]; private static PaymentSettingPane self; private PaymentSettingPane() { FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("paymentsettingpane.fxml")); fxmlLoader.setRoot(this); fxmlLoader.setController(this); try { fxmlLoader.load(); } catch (IOException exception) { throw new RuntimeException(exception); } entries = new TextField[]{entry1, entry2, entry3, entry4}; cardPayRadioButton.setSelected(true); cardPayRadioButton.getToggleGroup().selectedToggleProperty().addListener(new ChangeListener<Toggle>() { @Override public void changed(ObservableValue<? extends Toggle> observable, Toggle oldValue, Toggle newValue) { if(cardPayRadioButton.isSelected()) { for(TextField t: entries) t.setDisable(false); }else { for(TextField t: entries) t.setDisable(true); } } }); CreditCard c = handler.getCreditCard(); entry1.textProperty().addListener(((observable, oldValue, newValue) -> c.setCardNumber(newValue))); entry2.textProperty().addListener(((observable, oldValue, newValue) -> c.setValidMonth(Integer.parseInt(newValue)))); entry3.textProperty().addListener(((observable, oldValue, newValue) -> c.setValidYear(Integer.parseInt(newValue)))); entry4.textProperty().addListener(((observable, oldValue, newValue) -> c.setHoldersName(newValue))); } public static PaymentSettingPane getInstance(){ if(self == null) self= new PaymentSettingPane(); return self; } @Override public void update() { billingAddress.setText(handler.getCustomer().getAddress()); CreditCard c = handler.getCreditCard(); entry1.setText(c.getCardNumber()); entry2.setText(String.valueOf(c.getValidMonth())); entry3.setText(String.valueOf(c.getValidYear())); entry4.setText(c.getHoldersName()); } }
UTF-8
Java
3,081
java
PaymentSettingPane.java
Java
[]
null
[]
package customerPage.paymentsettings; import customerPage.SettingsPane; import customerPage.personaldatapane.PersonalDataPane; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.collections.MapChangeListener; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.scene.control.*; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.input.MouseEvent; import javafx.scene.layout.AnchorPane; import se.chalmers.cse.dat216.project.CreditCard; import se.chalmers.cse.dat216.project.IMatDataHandler; import java.io.IOException; public class PaymentSettingPane extends SettingsPane { IMatDataHandler handler = IMatDataHandler.getInstance(); @FXML RadioButton cardPayRadioButton, deliveryRadioButton, billRadioButton; @FXML TextField entry1, entry2, entry3, entry4; @FXML Label billingAddress; private final TextField entries[]; private static PaymentSettingPane self; private PaymentSettingPane() { FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("paymentsettingpane.fxml")); fxmlLoader.setRoot(this); fxmlLoader.setController(this); try { fxmlLoader.load(); } catch (IOException exception) { throw new RuntimeException(exception); } entries = new TextField[]{entry1, entry2, entry3, entry4}; cardPayRadioButton.setSelected(true); cardPayRadioButton.getToggleGroup().selectedToggleProperty().addListener(new ChangeListener<Toggle>() { @Override public void changed(ObservableValue<? extends Toggle> observable, Toggle oldValue, Toggle newValue) { if(cardPayRadioButton.isSelected()) { for(TextField t: entries) t.setDisable(false); }else { for(TextField t: entries) t.setDisable(true); } } }); CreditCard c = handler.getCreditCard(); entry1.textProperty().addListener(((observable, oldValue, newValue) -> c.setCardNumber(newValue))); entry2.textProperty().addListener(((observable, oldValue, newValue) -> c.setValidMonth(Integer.parseInt(newValue)))); entry3.textProperty().addListener(((observable, oldValue, newValue) -> c.setValidYear(Integer.parseInt(newValue)))); entry4.textProperty().addListener(((observable, oldValue, newValue) -> c.setHoldersName(newValue))); } public static PaymentSettingPane getInstance(){ if(self == null) self= new PaymentSettingPane(); return self; } @Override public void update() { billingAddress.setText(handler.getCustomer().getAddress()); CreditCard c = handler.getCreditCard(); entry1.setText(c.getCardNumber()); entry2.setText(String.valueOf(c.getValidMonth())); entry3.setText(String.valueOf(c.getValidYear())); entry4.setText(c.getHoldersName()); } }
3,081
0.679325
0.672184
87
34.413792
30.896027
125
false
false
0
0
0
0
0
0
0.724138
false
false
7
9ac4a02279ec96aec281457cd7380d9c203edd6f
12,455,405,221,679
3e9cccb713d8135d6a9eaf1b7dde413b4dde33e5
/src/main/java/com/mergen/todolist/ToDoListService.java
a03a30db48d0dce89317238d843624399acb0323
[]
no_license
Mustahsen/is-listesi
https://github.com/Mustahsen/is-listesi
143b738b7199d2f50e245e1d5fa5bbd75c1061cc
2f1657bab96adbd72b4c416fa89b2b5f0430e8b3
refs/heads/master
2020-05-22T17:50:46.116000
2019-05-20T00:26:58
2019-05-20T00:26:58
186,458,740
0
0
null
false
2019-05-19T10:36:57
2019-05-13T16:37:23
2019-05-19T08:41:27
2019-05-19T10:36:57
233
0
0
0
TypeScript
false
false
package com.mergen.todolist; import java.util.ArrayList; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.mergen.user.Users; @Service public class ToDoListService { @Autowired ToDoListRepository toDoListRepository; public List<ToDoList> getToDoListsForUser(Users user){ List<ToDoList> toDoList = new ArrayList<ToDoList>(); toDoListRepository.findByUserOrderByIdAsc(user).forEach(toDoList::add); return toDoList; } public List<ToDoList> getAllToDoLists(){ List<ToDoList> toDoList = new ArrayList<ToDoList>(); toDoListRepository.findAll().forEach(toDoList::add); return toDoList; } public ToDoList getToDoListById(Long id){ return toDoListRepository.findById(id).orElse(null); } public void addToDoList(ToDoList toDoList){ toDoListRepository.save(toDoList); } public void updateToDoList(ToDoList toDoList){ toDoListRepository.save(toDoList); } public void deleteToDoListById(Long id){ toDoListRepository.deleteById(id); } }
UTF-8
Java
1,069
java
ToDoListService.java
Java
[]
null
[]
package com.mergen.todolist; import java.util.ArrayList; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.mergen.user.Users; @Service public class ToDoListService { @Autowired ToDoListRepository toDoListRepository; public List<ToDoList> getToDoListsForUser(Users user){ List<ToDoList> toDoList = new ArrayList<ToDoList>(); toDoListRepository.findByUserOrderByIdAsc(user).forEach(toDoList::add); return toDoList; } public List<ToDoList> getAllToDoLists(){ List<ToDoList> toDoList = new ArrayList<ToDoList>(); toDoListRepository.findAll().forEach(toDoList::add); return toDoList; } public ToDoList getToDoListById(Long id){ return toDoListRepository.findById(id).orElse(null); } public void addToDoList(ToDoList toDoList){ toDoListRepository.save(toDoList); } public void updateToDoList(ToDoList toDoList){ toDoListRepository.save(toDoList); } public void deleteToDoListById(Long id){ toDoListRepository.deleteById(id); } }
1,069
0.781104
0.781104
44
23.295454
22.044973
73
false
false
0
0
0
0
0
0
1.318182
false
false
7
7e7092c787e45b74d57b55dbacecbf16bd8f4b22
22,840,636,080,215
6251e092ef3280f31e1319d2f07010f8528ae701
/src/main/java/be/vdab/dao/VergaderingDAO.java
8c9731da737cb9cbd7fe992f12a949ad2e59b462
[]
no_license
simon-masschelein/planner
https://github.com/simon-masschelein/planner
1a010c8fba759787ca354825bfe240036eea6814
872036cdc51e1d700c467e243c21ccd8307bb1d0
refs/heads/master
2015-08-13T02:00:26.863000
2014-09-01T05:11:39
2014-09-01T05:11:39
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package be.vdab.dao; import org.springframework.data.jpa.repository.JpaRepository; import be.vdab.entities.Vergadering; public interface VergaderingDAO extends JpaRepository<Vergadering, Long> { }
UTF-8
Java
201
java
VergaderingDAO.java
Java
[]
null
[]
package be.vdab.dao; import org.springframework.data.jpa.repository.JpaRepository; import be.vdab.entities.Vergadering; public interface VergaderingDAO extends JpaRepository<Vergadering, Long> { }
201
0.820895
0.820895
9
21.333334
27.483328
74
false
false
0
0
0
0
0
0
0.444444
false
false
7
0c63a7ed708399e1cbff33c04d402f9f17dc65b4
25,400,436,588,793
bd36184f6bb1268cd5ec4193f77ebe6803fe89b6
/jprotobuf-rpc-demo/src/main/java/org/ghy/jprotobuf/rpc/api/EchoService.java
c68197f8b940dc30f3719ecc4d905ab07e248216
[]
no_license
haiyang1985/jprotobuf-demo
https://github.com/haiyang1985/jprotobuf-demo
01639176e2ac724f4f7058955cc1d0bc481442cf
1e311c45c69950772dda61b9f81c6275820ceb9c
refs/heads/master
2022-12-01T07:55:52.156000
2020-08-13T07:59:15
2020-08-13T07:59:15
287,217,540
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.ghy.jprotobuf.rpc.api; import com.baidu.jprotobuf.pbrpc.ProtobufRPC; public interface EchoService { @ProtobufRPC(serviceName = "echoService", onceTalkTimeout = 200) EchoInfo echo(EchoInfo info); }
UTF-8
Java
219
java
EchoService.java
Java
[]
null
[]
package org.ghy.jprotobuf.rpc.api; import com.baidu.jprotobuf.pbrpc.ProtobufRPC; public interface EchoService { @ProtobufRPC(serviceName = "echoService", onceTalkTimeout = 200) EchoInfo echo(EchoInfo info); }
219
0.767123
0.753425
8
26.375
22.994225
68
false
false
0
0
0
0
0
0
0.5
false
false
7
219f9dac8ed8a5023cc3fbe62b6b67ac9182176f
4,655,744,597,365
f2881afa5ed44e3cca38c540b55898030afc1a72
/src/main/java/com/qln/workreserve/tree/dbo/Dictionary.java
b80e17f7bac2dca423c94bc5fac10f218c0158ad
[]
no_license
ywqln/work-reserve
https://github.com/ywqln/work-reserve
f610d2ebd9762a146e5a9e3a8fb94dd56aa1c5f0
bfc0e5ff047268bc65149bca753e146d9621c4ce
refs/heads/master
2022-06-22T07:51:57.698000
2019-07-25T03:24:08
2019-07-25T03:24:08
192,306,171
0
0
null
false
2022-06-17T02:11:28
2019-06-17T08:27:34
2019-07-25T03:26:52
2022-06-17T02:11:27
208
0
0
2
Java
false
false
package com.qln.workreserve.tree.dbo; import lombok.Getter; import lombok.Setter; import org.hibernate.annotations.GenericGenerator; import javax.persistence.*; /** * @Title: $ * @Project: csai-api * @Description: TODO * @Author 秦莉娜 * @Date 2019/7/3$ 9:35$ * @Version V2.0 **/ @Getter @Setter @Entity @Table(name = "qln_dictionary_clc_category") public class Dictionary { @Id @GenericGenerator(name = "id", strategy = "uuid") // @GeneratedValue(strategy = GenerationType.AUTO) private String id; private String code; private String name; private String parentId; private boolean root; }
UTF-8
Java
634
java
Dictionary.java
Java
[ { "context": "roject: csai-api\n * @Description: TODO\n * @Author 秦莉娜\n * @Date 2019/7/3$ 9:35$\n * @Version V2.0\n **/\n@G", "end": 239, "score": 0.9996443390846252, "start": 236, "tag": "NAME", "value": "秦莉娜" } ]
null
[]
package com.qln.workreserve.tree.dbo; import lombok.Getter; import lombok.Setter; import org.hibernate.annotations.GenericGenerator; import javax.persistence.*; /** * @Title: $ * @Project: csai-api * @Description: TODO * @Author 秦莉娜 * @Date 2019/7/3$ 9:35$ * @Version V2.0 **/ @Getter @Setter @Entity @Table(name = "qln_dictionary_clc_category") public class Dictionary { @Id @GenericGenerator(name = "id", strategy = "uuid") // @GeneratedValue(strategy = GenerationType.AUTO) private String id; private String code; private String name; private String parentId; private boolean root; }
634
0.694268
0.676752
30
19.933332
15.340433
53
false
false
0
0
0
0
0
0
0.366667
false
false
7
18ffd0a61428d61b04715720c212b922c37b89de
23,510,650,988,751
750008b731b5f33542c0f3e2c3bdfba27e2be72d
/src/supermarket/TidTest.java
e98f442d55f619e7d39c4a010015d1bb5f4610bf
[]
no_license
kottz/lab5
https://github.com/kottz/lab5
15d33adc81c6e8c14890636c4ffc14006f08d9dc
9fc369869f7365162f542c5b32559719d7f7c9e2
refs/heads/master
2021-01-24T08:37:13.621000
2018-03-12T08:57:59
2018-03-12T08:57:59
122,984,852
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package supermarket; import sim.Event; import sim.SortedSequence; import supermarket.customer.Customer; import random.*; /** * * @author Olof Bourghardt, August Brunnsäter, Oskar Havo , Edward Källstedt * */ public class TidTest { // Proof-of-concept tidräkning public static void main(String[] args) { ExponentialRandomStream eps1 = new ExponentialRandomStream(1.0, 1234); //Håkans parametrar från sim1.txt UniformRandomStream urs1 = new UniformRandomStream(0.5, 1.0, 1234); //Håkans parametrar från sim1.txt double kund0kommerin = eps1.next(); //Kund 0 kommer in double kund1kommerin = kund0kommerin + eps1.next(); //Kund 1 kommer in (triggat av kund0, så dess tid+en ny random) double kund2kommerin = kund1kommerin + eps1.next(); //Kund 2 kommer in(triggat av kund1, så dess tid+en ny random) double kund0betalar = kund0kommerin + urs1.next(); // Kund 0 går till kassan och betalar.(Triggat av arrivalEvent, så tiden kunden //kom in + tiden att plocka. tiden att plocka räknas ut i arrival. System.out.println(kund0kommerin); System.out.println(kund1kommerin); System.out.println(kund2kommerin); System.out.println(kund0betalar); //Samma siffror som i Håkans simulering, måste vara såhär han har gjort. //Eftersom alla events sorteras efter den tid de inträffar så kommer det randomnummer man får från eps.next() alltid komma i rätt //ordning i simuleringen. Det löser sig själv om man bara låter event hålla reda på sin egen tid. } /* Håkans första tider: * * 0,44 Ankomst * 0,49 Ankomst * 0,64 Ankomst * 1,26 Plock * osv. * osv. * Samma som denna kod genererar. */ }
ISO-8859-1
Java
1,718
java
TidTest.java
Java
[ { "context": "mer.Customer;\nimport random.*;\n\n/**\n * \n * @author Olof Bourghardt, August Brunnsäter, Oskar Havo , Edward Källstedt", "end": 157, "score": 0.9998723268508911, "start": 142, "tag": "NAME", "value": "Olof Bourghardt" }, { "context": "ort random.*;\n\n/**\n * \n * @author Olof Bourghardt, August Brunnsäter, Oskar Havo , Edward Källstedt\n *\n */\n\npublic cla", "end": 176, "score": 0.9998583793640137, "start": 159, "tag": "NAME", "value": "August Brunnsäter" }, { "context": " * \n * @author Olof Bourghardt, August Brunnsäter, Oskar Havo , Edward Källstedt\n *\n */\n\npublic class TidTest {", "end": 188, "score": 0.9998621940612793, "start": 178, "tag": "NAME", "value": "Oskar Havo" }, { "context": "r Olof Bourghardt, August Brunnsäter, Oskar Havo , Edward Källstedt\n *\n */\n\npublic class TidTest {\n\n\t// Proof-of-conc", "end": 207, "score": 0.9998626708984375, "start": 191, "tag": "NAME", "value": "Edward Källstedt" } ]
null
[]
package supermarket; import sim.Event; import sim.SortedSequence; import supermarket.customer.Customer; import random.*; /** * * @author <NAME>, <NAME>, <NAME> , <NAME> * */ public class TidTest { // Proof-of-concept tidräkning public static void main(String[] args) { ExponentialRandomStream eps1 = new ExponentialRandomStream(1.0, 1234); //Håkans parametrar från sim1.txt UniformRandomStream urs1 = new UniformRandomStream(0.5, 1.0, 1234); //Håkans parametrar från sim1.txt double kund0kommerin = eps1.next(); //Kund 0 kommer in double kund1kommerin = kund0kommerin + eps1.next(); //Kund 1 kommer in (triggat av kund0, så dess tid+en ny random) double kund2kommerin = kund1kommerin + eps1.next(); //Kund 2 kommer in(triggat av kund1, så dess tid+en ny random) double kund0betalar = kund0kommerin + urs1.next(); // Kund 0 går till kassan och betalar.(Triggat av arrivalEvent, så tiden kunden //kom in + tiden att plocka. tiden att plocka räknas ut i arrival. System.out.println(kund0kommerin); System.out.println(kund1kommerin); System.out.println(kund2kommerin); System.out.println(kund0betalar); //Samma siffror som i Håkans simulering, måste vara såhär han har gjort. //Eftersom alla events sorteras efter den tid de inträffar så kommer det randomnummer man får från eps.next() alltid komma i rätt //ordning i simuleringen. Det löser sig själv om man bara låter event hålla reda på sin egen tid. } /* Håkans första tider: * * 0,44 Ankomst * 0,49 Ankomst * 0,64 Ankomst * 1,26 Plock * osv. * osv. * Samma som denna kod genererar. */ }
1,682
0.708876
0.678698
48
34.208332
39.597431
133
false
false
0
0
0
0
0
0
2.541667
false
false
7
240db3801332eb232e9510a8a2ea58d9e1a8f2ea
27,719,718,929,428
2797413b425a65ce2bd9a149fabebf35044d0ee9
/SessionComparator.java
3b7b126cbff6d044a9f6d24252f86ab903ea190c
[]
no_license
alsyr/Supermarket_Model_With_Express_Lanes
https://github.com/alsyr/Supermarket_Model_With_Express_Lanes
dbc52f77cf824e5fb5329a3dace1a0f4897d6e2c
5959bf80c7d76b01524e7a715c9eec911179389a
refs/heads/master
2021-01-15T10:19:27.846000
2017-02-02T07:00:02
2017-02-02T07:00:02
78,818,288
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.util.Comparator; public class SessionComparator implements Comparator<Object> { public int compare(Object a, Object b) { LaneManager v1 = (LaneManager) a; LaneManager v2 = (LaneManager) b; if (v1.getExpressLimit() < v2.getExpressLimit()) { return -1; } else if (v1.getExpressLimit() == v2.getExpressLimit()) { return 0; } else { return 1; } } }
UTF-8
Java
408
java
SessionComparator.java
Java
[]
null
[]
import java.util.Comparator; public class SessionComparator implements Comparator<Object> { public int compare(Object a, Object b) { LaneManager v1 = (LaneManager) a; LaneManager v2 = (LaneManager) b; if (v1.getExpressLimit() < v2.getExpressLimit()) { return -1; } else if (v1.getExpressLimit() == v2.getExpressLimit()) { return 0; } else { return 1; } } }
408
0.634804
0.612745
18
21.611111
21.56164
62
false
false
0
0
0
0
0
0
0.388889
false
false
7
38fb4a3b8722b1ebca8b74f2203ec4959ed07e33
9,131,100,535,697
dfcd5587682fb6a60a5d4ea8ded3cd3f442f3199
/selenium/src/com/selenium/test/Temp.java
76580867f70848e958fdcdc4881d406971bedd1e
[]
no_license
buzuimoyan/learngit
https://github.com/buzuimoyan/learngit
f8c95e021c01c00810c26f3f326f72b9c40bbc81
3b3fcf887ebdd57c830ee5936e8cfd6551eb6bb6
refs/heads/master
2016-09-14T10:17:06.321000
2016-05-06T09:28:00
2016-05-06T09:28:00
57,937,401
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.selenium.test; import java.awt.Component; import java.awt.Dimension; import java.awt.Toolkit; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JPanel; public class Temp { static JFrame jframe = null; public static void main(String[] args) throws IOException { Component button = frame_init(); button.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { try { copy(); show_dialog(); } catch (FileNotFoundException e1) { System.out.println("文件不存在"); } catch (IOException e1) { System.out.println("写入失败"); } } }); //copy(); } public static Component frame_init() { jframe = new JFrame("Demo1"); Toolkit tool = Toolkit.getDefaultToolkit(); Dimension screen_size= tool.getScreenSize(); jframe.setBounds((screen_size.width-500)/2, (screen_size.height-300)/2, 500, 300); jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JPanel jpanel =new JPanel(); jframe.add(jpanel); JButton button = new JButton("複製"); jpanel.add(button); //frame.setLayout(); jframe.setVisible(true); return button; } public static void show_dialog(){ JDialog dialog = new JDialog(jframe, "复制成功", true); dialog.setVisible(true); } private static void copy() throws FileNotFoundException, IOException { File inputfile = new File("C:\\Users\\Administrator\\OneDrive\\文档\\java基础文档\\day23 GUI.doc"); File outputfile = new File("e:\\123.doc"); FileInputStream fileInputStream = new FileInputStream(inputfile); FileOutputStream fileOutputStream = new FileOutputStream(outputfile); byte[] by = new byte[1024]; int length =0; while ((length=fileInputStream.read(by))!=-1) { fileOutputStream.write(by, 0, length); } fileOutputStream.close(); fileInputStream.close(); } }
GB18030
Java
2,226
java
Temp.java
Java
[]
null
[]
package com.selenium.test; import java.awt.Component; import java.awt.Dimension; import java.awt.Toolkit; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JPanel; public class Temp { static JFrame jframe = null; public static void main(String[] args) throws IOException { Component button = frame_init(); button.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { try { copy(); show_dialog(); } catch (FileNotFoundException e1) { System.out.println("文件不存在"); } catch (IOException e1) { System.out.println("写入失败"); } } }); //copy(); } public static Component frame_init() { jframe = new JFrame("Demo1"); Toolkit tool = Toolkit.getDefaultToolkit(); Dimension screen_size= tool.getScreenSize(); jframe.setBounds((screen_size.width-500)/2, (screen_size.height-300)/2, 500, 300); jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JPanel jpanel =new JPanel(); jframe.add(jpanel); JButton button = new JButton("複製"); jpanel.add(button); //frame.setLayout(); jframe.setVisible(true); return button; } public static void show_dialog(){ JDialog dialog = new JDialog(jframe, "复制成功", true); dialog.setVisible(true); } private static void copy() throws FileNotFoundException, IOException { File inputfile = new File("C:\\Users\\Administrator\\OneDrive\\文档\\java基础文档\\day23 GUI.doc"); File outputfile = new File("e:\\123.doc"); FileInputStream fileInputStream = new FileInputStream(inputfile); FileOutputStream fileOutputStream = new FileOutputStream(outputfile); byte[] by = new byte[1024]; int length =0; while ((length=fileInputStream.read(by))!=-1) { fileOutputStream.write(by, 0, length); } fileOutputStream.close(); fileInputStream.close(); } }
2,226
0.724359
0.711081
76
27.736841
20.166653
95
false
false
0
0
0
0
0
0
2.289474
false
false
7
ab9a5ec1ca909969c8bd19834db4d642c5dd3eb2
38,491,496,928,444
262e597e9361e65922afaa1f07d21195bdf5e30b
/Core/gameserver/src/l2s/gameserver/listener/actor/player/OnPlayerPartyLeaveListener.java
18ec174654b7dbf58185efb02a6567f6e5fb4ee2
[]
no_license
ellitedev/l2ellite
https://github.com/ellitedev/l2ellite
5a7ccac82f2c7b5413913cda8ad13b5bad435f92
cb050cfa96fa7dabe70f0159fa0680878825b9c1
refs/heads/master
2017-12-30T18:44:21.556000
2016-09-28T23:14:59
2016-09-28T23:14:59
68,864,146
1
3
null
null
null
null
null
null
null
null
null
null
null
null
null
package l2s.gameserver.listener.actor.player; import l2s.gameserver.listener.PlayerListener; import l2s.gameserver.model.Player; public interface OnPlayerPartyLeaveListener extends PlayerListener { public void onPartyLeave(Player player); }
UTF-8
Java
244
java
OnPlayerPartyLeaveListener.java
Java
[]
null
[]
package l2s.gameserver.listener.actor.player; import l2s.gameserver.listener.PlayerListener; import l2s.gameserver.model.Player; public interface OnPlayerPartyLeaveListener extends PlayerListener { public void onPartyLeave(Player player); }
244
0.844262
0.831967
9
26.111111
24.195704
66
false
false
0
0
0
0
0
0
0.555556
false
false
7
1e189225f89f2dd5e00ad05e6a9c5049b4844beb
20,349,555,101,368
f8959e30eb7058a1ce2658349a12ee1d91632bb6
/src/main/java/com/king/nowedge/dto/comm/WorkExperienceDTO.java
e58e00a9088f88ff7d69ee2b05509585f0c40c3a
[]
no_license
hq20211124/com.ryx.noeedge
https://github.com/hq20211124/com.ryx.noeedge
190456e908b851cabbe3301eee1802641169ea87
f191be4c119a6f1a2f478e79fd06013c744ca140
refs/heads/master
2023-01-01T19:29:36.834000
2020-10-25T05:03:19
2020-10-25T05:03:19
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.king.nowedge.dto; import java.util.Date; import javax.validation.constraints.NotNull; import org.hibernate.validator.constraints.NotEmpty; import org.springframework.format.annotation.DateTimeFormat; import com.king.nowedge.dto.base.BaseDTO; public class WorkExperienceDTO extends BaseDTO{ private Long userId; /** * 名称 */ @NotEmpty(message="{workExperience.company.not.empty}") private String company ; @NotNull(message="{workExperience.startDate.not.empty}") @DateTimeFormat(pattern = "yyyy-MM") private Date startDate ; @NotNull(message="{workExperience.endDate.not.empty}") @DateTimeFormat(pattern = "yyyy-MM") private Date endDate ; private Long lstart; private long lend; private Integer educationLevel; @NotEmpty(message="{workExperience.descr.not.empty}") private String descr ; @NotEmpty(message="{workExperience.department.not.empty}") private String department; private Integer industry; private Integer companyScale; private Integer specialty; @NotEmpty(message="{workExperience.position.not.empty}") private String position; private Integer companyType ; private Integer type; public Long getUserId() { return userId; } public void setUserId(Long userId) { this.userId = userId; } public Integer getType() { return type; } public void setType(Integer type) { this.type = type; } public String getCompany() { return company; } public void setCompany(String company) { this.company = company; } public Date getStartDate() { return startDate; } public void setStartDate(Date startDate) { this.startDate = startDate; } public Date getEndDate() { return endDate; } public void setEndDate(Date endDate) { this.endDate = endDate; } public Integer getEducationLevel() { return educationLevel; } public void setEducationLevel(Integer educationLevel) { this.educationLevel = educationLevel; } public String getDescr() { return descr; } public void setDescr(String descr) { this.descr = descr; } public Integer getIndustry() { return industry; } public void setIndustry(Integer industry) { this.industry = industry; } public Integer getCompanyScale() { return companyScale; } public void setCompanyScale(Integer companyScale) { this.companyScale = companyScale; } public Integer getSpecialty() { return specialty; } public void setSpecialty(Integer specialty) { this.specialty = specialty; } public String getPosition() { return position; } public void setPosition(String position) { this.position = position; } public String getDepartment() { return department; } public void setDepartment(String department) { this.department = department; } public Integer getCompanyType() { return companyType; } public void setCompanyType(Integer companyType) { this.companyType = companyType; } public Long getLstart() { if(null != startDate){ return startDate.getTime(); } return lstart; } public void setLstart(Long lstart) { this.lstart = lstart; } public long getLend() { if(null != endDate){ return endDate.getTime(); } return lend; } public void setLend(long lend) { this.lend = lend; } }
UTF-8
Java
3,238
java
WorkExperienceDTO.java
Java
[]
null
[]
package com.king.nowedge.dto; import java.util.Date; import javax.validation.constraints.NotNull; import org.hibernate.validator.constraints.NotEmpty; import org.springframework.format.annotation.DateTimeFormat; import com.king.nowedge.dto.base.BaseDTO; public class WorkExperienceDTO extends BaseDTO{ private Long userId; /** * 名称 */ @NotEmpty(message="{workExperience.company.not.empty}") private String company ; @NotNull(message="{workExperience.startDate.not.empty}") @DateTimeFormat(pattern = "yyyy-MM") private Date startDate ; @NotNull(message="{workExperience.endDate.not.empty}") @DateTimeFormat(pattern = "yyyy-MM") private Date endDate ; private Long lstart; private long lend; private Integer educationLevel; @NotEmpty(message="{workExperience.descr.not.empty}") private String descr ; @NotEmpty(message="{workExperience.department.not.empty}") private String department; private Integer industry; private Integer companyScale; private Integer specialty; @NotEmpty(message="{workExperience.position.not.empty}") private String position; private Integer companyType ; private Integer type; public Long getUserId() { return userId; } public void setUserId(Long userId) { this.userId = userId; } public Integer getType() { return type; } public void setType(Integer type) { this.type = type; } public String getCompany() { return company; } public void setCompany(String company) { this.company = company; } public Date getStartDate() { return startDate; } public void setStartDate(Date startDate) { this.startDate = startDate; } public Date getEndDate() { return endDate; } public void setEndDate(Date endDate) { this.endDate = endDate; } public Integer getEducationLevel() { return educationLevel; } public void setEducationLevel(Integer educationLevel) { this.educationLevel = educationLevel; } public String getDescr() { return descr; } public void setDescr(String descr) { this.descr = descr; } public Integer getIndustry() { return industry; } public void setIndustry(Integer industry) { this.industry = industry; } public Integer getCompanyScale() { return companyScale; } public void setCompanyScale(Integer companyScale) { this.companyScale = companyScale; } public Integer getSpecialty() { return specialty; } public void setSpecialty(Integer specialty) { this.specialty = specialty; } public String getPosition() { return position; } public void setPosition(String position) { this.position = position; } public String getDepartment() { return department; } public void setDepartment(String department) { this.department = department; } public Integer getCompanyType() { return companyType; } public void setCompanyType(Integer companyType) { this.companyType = companyType; } public Long getLstart() { if(null != startDate){ return startDate.getTime(); } return lstart; } public void setLstart(Long lstart) { this.lstart = lstart; } public long getLend() { if(null != endDate){ return endDate.getTime(); } return lend; } public void setLend(long lend) { this.lend = lend; } }
3,238
0.721088
0.721088
163
18.84049
17.275085
60
false
false
0
0
0
0
0
0
1.484663
false
false
7
c9f4a864d2ea718bff5c7c34526b553b6ce6648b
37,065,567,795,634
60de13c2877ec032054c0d79ec677cfcd055962e
/app/src/main/java/com/pdm/taskdone/Client_Request_Popup.java
7fbebcedeaf6b34627aab0fb62fb801a839bc68d
[]
no_license
naveenlukefernando/TaskDone-TechieApp
https://github.com/naveenlukefernando/TaskDone-TechieApp
d496c8c58536dbbb68a4a8d2ef6cfbb6845091cf
66c03cf7496d6e2c54cb2ae05c48f61ee1782e18
refs/heads/master
2021-08-16T10:02:52.044000
2019-01-03T18:50:49
2019-01-03T18:50:49
143,540,417
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.pdm.taskdone; import android.animation.ValueAnimator; import android.content.Intent; import android.graphics.Color; import android.media.MediaPlayer; import android.os.Handler; import android.support.annotation.NonNull; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.text.TextUtils; import android.util.Log; import android.view.View; import android.view.animation.LinearInterpolator; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.google.android.gms.maps.CameraUpdate; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.model.BitmapDescriptorFactory; import com.google.android.gms.maps.model.JointType; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.LatLngBounds; import com.google.android.gms.maps.model.MarkerOptions; import com.google.android.gms.maps.model.PolylineOptions; import com.google.android.gms.maps.model.SquareCap; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import com.pdm.taskdone.Common.Common; import com.pdm.taskdone.Model.FCMResponse; import com.pdm.taskdone.Model.Notification; import com.pdm.taskdone.Model.Sender; import com.pdm.taskdone.Model.Token; import com.pdm.taskdone.Model.client_model; import com.pdm.taskdone.Remote.IFCMService; import com.pdm.taskdone.Remote.IGoogleAPI; import com.skyfishjy.library.RippleBackground; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.List; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; // Created by Naveen IT16008892 public class Client_Request_Popup extends AppCompatActivity { TextView txttime,txtAdress,txtDistance; MediaPlayer mediaPlayer ; Button acceptBtn, declineBtn; IGoogleAPI mService; IFCMService miFCMService; double lat,lng; String clientID; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_client__request__popup); final RippleBackground rippleBackground=(RippleBackground)findViewById(R.id.ani_logo); ImageView imageView=(ImageView)findViewById(R.id.taskdone_logo); rippleBackground.startRippleAnimation(); mService = Common.getGoogleAPI(); miFCMService = Common.getIFCMService(); //InitView txtAdress = (TextView)findViewById(R.id.txtAddress); txttime = (TextView)findViewById(R.id.txtTime); txtDistance = (TextView)findViewById(R.id.txt_Distance); acceptBtn = (Button) findViewById(R.id.accept_btn); declineBtn = (Button)findViewById(R.id.decline_btn); declineBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Log.d("clicked","Canceeledd!!!!"); if (!TextUtils.isEmpty(clientID)) cancelRequest (clientID); } }); acceptBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { AcceptNotifyRequest(clientID); Intent intent = new Intent(Client_Request_Popup.this,worker_tracking.class); Log.d("Hey","Accepted"); // send client location to new activity intent.putExtra("lat",lat); intent.putExtra("lng",lng); intent.putExtra("clientID",clientID); startActivity(intent); finish(); } }); mediaPlayer = MediaPlayer.create(this,R.raw.ringtone); mediaPlayer.setLooping(true); mediaPlayer.start(); if (getIntent() != null) { lat = getIntent().getDoubleExtra("lat",-1.0); lng = getIntent().getDoubleExtra("lng",-1.0); clientID = getIntent().getStringExtra("client"); getDirection(lat,lng); } } private void AcceptNotifyRequest(String clientID) { Token token = new Token(clientID); Notification notification = new Notification("Accept","Worker has Accept your request."); Sender sender = new Sender(token.getToken(),notification); miFCMService.sendMessage(sender) .enqueue(new Callback<FCMResponse>() { @Override public void onResponse(Call<FCMResponse> call, Response<FCMResponse> response) { if (response.body().success == 1) { Toast.makeText(Client_Request_Popup.this,"Accepted.",Toast.LENGTH_SHORT).show(); finish(); } } @Override public void onFailure(Call<FCMResponse> call, Throwable t) { } }); } private void cancelRequest(String clientID) { Token token = new Token(clientID); Notification notification = new Notification("Cancel","Worker has cancelled your request."); Sender sender = new Sender(token.getToken(),notification); miFCMService.sendMessage(sender) .enqueue(new Callback<FCMResponse>() { @Override public void onResponse(Call<FCMResponse> call, Response<FCMResponse> response) { if (response.body().success == 1) { Toast.makeText(Client_Request_Popup.this,"Cancelled",Toast.LENGTH_SHORT).show(); finish(); } } @Override public void onFailure(Call<FCMResponse> call, Throwable t) { } }); } private void getDirection(double lat,double lng) { String requestApi = null; try { requestApi = "https://maps.googleapis.com/maps/api/directions/json?" + "mode=driving&" + "transit_routing_preference=less_driving&"+ "origin="+ Common.mLastlocation.getLatitude()+","+Common.mLastlocation.getLongitude()+"&"+ "destination="+lat+","+lng+"&"+ "key="+getResources().getString(R.string.google_direction_api); Log.d("Yeah !!!! ", requestApi); //print URL for debug mService.getPath(requestApi) .enqueue(new Callback<String>() { @Override public void onResponse(Call<String> call, Response<String> response) { try { JSONObject jsonObject = new JSONObject(response.body().toString()); JSONArray routes = jsonObject.getJSONArray("routes"); //getiing the first element JSONObject object = routes.getJSONObject(0); //after getting first element , i named "legs " to an array JSONArray legs = object.getJSONArray("legs"); //and get first element of legs array JSONObject legsObject = legs.getJSONObject(0); //Now getting the distance JSONObject distance = legsObject.getJSONObject("distance"); txtDistance.setText(distance.getString("text")); //get the time JSONObject time = legsObject.getJSONObject("duration"); txttime.setText(time.getString("text")); //get address String address = legsObject.getString("end_address"); txtAdress.setText(address); } catch (JSONException e) { e.printStackTrace(); Log.d("fail",""+e); } } @Override public void onFailure(Call<String> call, Throwable t) { Toast.makeText(Client_Request_Popup.this, "" + t.getMessage(), Toast.LENGTH_SHORT).show(); } }); } catch (Exception e) { e.printStackTrace(); } } @Override protected void onStop() { mediaPlayer.release(); super.onStop(); } @Override protected void onPause() { mediaPlayer.release(); super.onPause(); } @Override protected void onPostResume() { super.onPostResume(); mediaPlayer.start(); } }
UTF-8
Java
9,276
java
Client_Request_Popup.java
Java
[ { "context": "llback;\nimport retrofit2.Response;\n\n\n// Created by Naveen IT16008892\n\npublic class Client_Request_Popup ext", "end": 1905, "score": 0.9995670318603516, "start": 1899, "tag": "NAME", "value": "Naveen" }, { "context": "\nimport retrofit2.Response;\n\n\n// Created by Naveen IT16008892\n\npublic class Client_Request_Popup extends AppCom", "end": 1916, "score": 0.9395422339439392, "start": 1906, "tag": "USERNAME", "value": "IT16008892" } ]
null
[]
package com.pdm.taskdone; import android.animation.ValueAnimator; import android.content.Intent; import android.graphics.Color; import android.media.MediaPlayer; import android.os.Handler; import android.support.annotation.NonNull; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.text.TextUtils; import android.util.Log; import android.view.View; import android.view.animation.LinearInterpolator; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.google.android.gms.maps.CameraUpdate; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.model.BitmapDescriptorFactory; import com.google.android.gms.maps.model.JointType; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.LatLngBounds; import com.google.android.gms.maps.model.MarkerOptions; import com.google.android.gms.maps.model.PolylineOptions; import com.google.android.gms.maps.model.SquareCap; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import com.pdm.taskdone.Common.Common; import com.pdm.taskdone.Model.FCMResponse; import com.pdm.taskdone.Model.Notification; import com.pdm.taskdone.Model.Sender; import com.pdm.taskdone.Model.Token; import com.pdm.taskdone.Model.client_model; import com.pdm.taskdone.Remote.IFCMService; import com.pdm.taskdone.Remote.IGoogleAPI; import com.skyfishjy.library.RippleBackground; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.List; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; // Created by Naveen IT16008892 public class Client_Request_Popup extends AppCompatActivity { TextView txttime,txtAdress,txtDistance; MediaPlayer mediaPlayer ; Button acceptBtn, declineBtn; IGoogleAPI mService; IFCMService miFCMService; double lat,lng; String clientID; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_client__request__popup); final RippleBackground rippleBackground=(RippleBackground)findViewById(R.id.ani_logo); ImageView imageView=(ImageView)findViewById(R.id.taskdone_logo); rippleBackground.startRippleAnimation(); mService = Common.getGoogleAPI(); miFCMService = Common.getIFCMService(); //InitView txtAdress = (TextView)findViewById(R.id.txtAddress); txttime = (TextView)findViewById(R.id.txtTime); txtDistance = (TextView)findViewById(R.id.txt_Distance); acceptBtn = (Button) findViewById(R.id.accept_btn); declineBtn = (Button)findViewById(R.id.decline_btn); declineBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Log.d("clicked","Canceeledd!!!!"); if (!TextUtils.isEmpty(clientID)) cancelRequest (clientID); } }); acceptBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { AcceptNotifyRequest(clientID); Intent intent = new Intent(Client_Request_Popup.this,worker_tracking.class); Log.d("Hey","Accepted"); // send client location to new activity intent.putExtra("lat",lat); intent.putExtra("lng",lng); intent.putExtra("clientID",clientID); startActivity(intent); finish(); } }); mediaPlayer = MediaPlayer.create(this,R.raw.ringtone); mediaPlayer.setLooping(true); mediaPlayer.start(); if (getIntent() != null) { lat = getIntent().getDoubleExtra("lat",-1.0); lng = getIntent().getDoubleExtra("lng",-1.0); clientID = getIntent().getStringExtra("client"); getDirection(lat,lng); } } private void AcceptNotifyRequest(String clientID) { Token token = new Token(clientID); Notification notification = new Notification("Accept","Worker has Accept your request."); Sender sender = new Sender(token.getToken(),notification); miFCMService.sendMessage(sender) .enqueue(new Callback<FCMResponse>() { @Override public void onResponse(Call<FCMResponse> call, Response<FCMResponse> response) { if (response.body().success == 1) { Toast.makeText(Client_Request_Popup.this,"Accepted.",Toast.LENGTH_SHORT).show(); finish(); } } @Override public void onFailure(Call<FCMResponse> call, Throwable t) { } }); } private void cancelRequest(String clientID) { Token token = new Token(clientID); Notification notification = new Notification("Cancel","Worker has cancelled your request."); Sender sender = new Sender(token.getToken(),notification); miFCMService.sendMessage(sender) .enqueue(new Callback<FCMResponse>() { @Override public void onResponse(Call<FCMResponse> call, Response<FCMResponse> response) { if (response.body().success == 1) { Toast.makeText(Client_Request_Popup.this,"Cancelled",Toast.LENGTH_SHORT).show(); finish(); } } @Override public void onFailure(Call<FCMResponse> call, Throwable t) { } }); } private void getDirection(double lat,double lng) { String requestApi = null; try { requestApi = "https://maps.googleapis.com/maps/api/directions/json?" + "mode=driving&" + "transit_routing_preference=less_driving&"+ "origin="+ Common.mLastlocation.getLatitude()+","+Common.mLastlocation.getLongitude()+"&"+ "destination="+lat+","+lng+"&"+ "key="+getResources().getString(R.string.google_direction_api); Log.d("Yeah !!!! ", requestApi); //print URL for debug mService.getPath(requestApi) .enqueue(new Callback<String>() { @Override public void onResponse(Call<String> call, Response<String> response) { try { JSONObject jsonObject = new JSONObject(response.body().toString()); JSONArray routes = jsonObject.getJSONArray("routes"); //getiing the first element JSONObject object = routes.getJSONObject(0); //after getting first element , i named "legs " to an array JSONArray legs = object.getJSONArray("legs"); //and get first element of legs array JSONObject legsObject = legs.getJSONObject(0); //Now getting the distance JSONObject distance = legsObject.getJSONObject("distance"); txtDistance.setText(distance.getString("text")); //get the time JSONObject time = legsObject.getJSONObject("duration"); txttime.setText(time.getString("text")); //get address String address = legsObject.getString("end_address"); txtAdress.setText(address); } catch (JSONException e) { e.printStackTrace(); Log.d("fail",""+e); } } @Override public void onFailure(Call<String> call, Throwable t) { Toast.makeText(Client_Request_Popup.this, "" + t.getMessage(), Toast.LENGTH_SHORT).show(); } }); } catch (Exception e) { e.printStackTrace(); } } @Override protected void onStop() { mediaPlayer.release(); super.onStop(); } @Override protected void onPause() { mediaPlayer.release(); super.onPause(); } @Override protected void onPostResume() { super.onPostResume(); mediaPlayer.start(); } }
9,276
0.578913
0.576757
303
29.613861
28.61903
118
false
false
0
0
0
0
0
0
0.521452
false
false
7
461f12357f2be7248f43cd2a1f0467577a428856
36,807,869,755,604
3243bb38bd8445ac5d6484f91227dec2784047d3
/modules/regularization/regularization-provider/src/main/java/com/bjike/goddess/regularization/dao/ManagementScoreRep.java
45ef3e6a1a34d462705d69ea62c01cf082bfb867
[]
no_license
moutainhigh/goddess-java
https://github.com/moutainhigh/goddess-java
4809935c3c34cd8139e176e08537967ab0504ced
a59cfa5326f01f09e43a69f90161cdc81f7d9fb4
refs/heads/master
2023-03-16T23:52:43.384000
2018-05-18T08:03:42
2018-05-18T08:03:42
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.bjike.goddess.regularization.dao; import com.bjike.goddess.common.jpa.dao.JpaRep; import com.bjike.goddess.regularization.dto.ManagementScoreDTO; import com.bjike.goddess.regularization.entity.ManagementScore; /** * 管理层评分持久化接口, 继承基类可使用jpa命名查询 * * @Author: [ sunfengtao ] * @Date: [ 2017-04-17 11:01 ] * @Description: [ 管理层评分持久化接口, 继承基类可使用jpa命名查询 ] * @Version: [ v1.0.0 ] * @Copy: [ com.bjike ] */ public interface ManagementScoreRep extends JpaRep<ManagementScore, ManagementScoreDTO> { }
UTF-8
Java
607
java
ManagementScoreRep.java
Java
[ { "context": "/**\n * 管理层评分持久化接口, 继承基类可使用jpa命名查询\n *\n * @Author: [ sunfengtao ]\n * @Date: [ 2017-04-17 11:01 ]\n * @Description:", "end": 285, "score": 0.9995914697647095, "start": 275, "tag": "USERNAME", "value": "sunfengtao" } ]
null
[]
package com.bjike.goddess.regularization.dao; import com.bjike.goddess.common.jpa.dao.JpaRep; import com.bjike.goddess.regularization.dto.ManagementScoreDTO; import com.bjike.goddess.regularization.entity.ManagementScore; /** * 管理层评分持久化接口, 继承基类可使用jpa命名查询 * * @Author: [ sunfengtao ] * @Date: [ 2017-04-17 11:01 ] * @Description: [ 管理层评分持久化接口, 继承基类可使用jpa命名查询 ] * @Version: [ v1.0.0 ] * @Copy: [ com.bjike ] */ public interface ManagementScoreRep extends JpaRep<ManagementScore, ManagementScoreDTO> { }
607
0.749511
0.720157
18
27.444445
26.079412
89
false
false
0
0
0
0
0
0
0.388889
false
false
7
2f733f091a703e56e545592a2ba8973e0174d51e
30,142,080,500,949
a4749327ef3cdc7f8fc4f6f5d3f328082cb8bcd2
/src/main/java/com/fh/springboot_shop/service/PinpaiService.java
00969a621aaa5330d5614c58dd591c6b9ed16204
[]
no_license
liuxue525/springbootshopht
https://github.com/liuxue525/springbootshopht
72e2e2c9a40dabfd8931a09e8fe21c0e8e471786
0643ed0417bc9a59c74d76061c05cb6a14e5a289
refs/heads/master
2023-02-24T21:59:34.422000
2021-01-22T11:08:16
2021-01-22T11:08:16
329,582,124
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.fh.springboot_shop.service; import com.fh.springboot_shop.entity.po.Pinpai; import com.fh.springboot_shop.entity.vo.PinpaiParam; import java.util.List; import java.util.Map; public interface PinpaiService { Map selectPinpai(PinpaiParam param); void add(Pinpai pinpai); Pinpai selectPinpaiById(Integer id); void update(Pinpai pinpai); List<Pinpai> selectPinpaiName(); }
UTF-8
Java
408
java
PinpaiService.java
Java
[]
null
[]
package com.fh.springboot_shop.service; import com.fh.springboot_shop.entity.po.Pinpai; import com.fh.springboot_shop.entity.vo.PinpaiParam; import java.util.List; import java.util.Map; public interface PinpaiService { Map selectPinpai(PinpaiParam param); void add(Pinpai pinpai); Pinpai selectPinpaiById(Integer id); void update(Pinpai pinpai); List<Pinpai> selectPinpaiName(); }
408
0.754902
0.754902
19
20.473684
18.723383
52
false
false
0
0
0
0
0
0
0.526316
false
false
7
4c877a5de94b9c85cb530bf44229e5f14e9c4d4c
28,011,776,768,535
ce7cb3b0cbafcb22b016debe39cd1e8cfe91c23c
/app/src/main/java/coder/aihui/manager/DeptLocationManager.java
4f31a4b1c6376d6d0e3fcbd053708b898e082606
[]
no_license
zhougangwei/PrettyGirls-master
https://github.com/zhougangwei/PrettyGirls-master
0812f2da9943b3e893a641be4eb26133e20bb60f
692084b1a5369b149305f999bbbd7dacc84ba03c
refs/heads/master
2021-01-02T08:44:59.913000
2018-03-28T10:03:52
2018-03-28T10:03:52
99,057,688
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package coder.aihui.manager; import android.text.TextUtils; import java.util.ArrayList; import coder.aihui.widget.jdaddressselector.ISelectAble; /** * @ 创建者 zhou * @ 创建时间 2017/8/1 14:05 * @ 描述 ${TODO} * @ 更新者 $AUTHOR$ * @ 更新时间 2017/8/1$ * @ 更新描述 ${TODO} */ public class DeptLocationManager implements ISelectAbleManager{ public ArrayList<ISelectAble> selectAbles; String mDlwzName; String mDlwzIds; String mDeptName; String mDeptIds; String mAllDlwzIds; String mAllDeptIds; String mAllDeptName; String mAllDlwzName; //数据转化分析 public DeptLocationManager() { } public void solveDatas(ArrayList<ISelectAble> selectAbles) { String result = ""; StringBuilder sbids = new StringBuilder(); String arg = ""; sbids.append("("); for (int i = 0; i < selectAbles.size(); i++) { ISelectAble selectAble = selectAbles.get(i); if (i != selectAbles.size() - 1) { arg = selectAble.getArg(); String name = selectAble.getName(); int id = selectAble.getId(); result += name + "-"; sbids.append(id).append(","); } else { arg = selectAble.getArg(); String name = selectAble.getName(); int id = selectAble.getId(); result += name; sbids.append(id); } } sbids.append(")"); if (selectAbles != null && selectAbles.size() > 0) { ISelectAble iSelectAble = selectAbles.get(selectAbles.size() - 1); if ("dept".equals(arg)) { mDeptName = iSelectAble.getName(); mDeptIds = iSelectAble.getId() + ""; } else if ("location".equals(arg)) { mDlwzName = iSelectAble.getName(); mDlwzIds = iSelectAble.getId() + ""; } } if (!TextUtils.isEmpty(result)) { if ("dept".equals(arg)) { mAllDeptName = result.substring(0, result.length() ); } else if ("location".equals(arg)) { mAllDlwzName = result.substring(0, result.length() ); } } String ids = sbids.toString(); if (ids.length() != 2) { //说明只有() if ("dept".equals(arg)) { mAllDeptIds = ids; } else if ("location".equals(arg)) { mAllDlwzIds = ids; } } } public ArrayList<ISelectAble> getSelectAbles() { return selectAbles; } public String getDlwzName() { return mDlwzName; } public String getDlwzIds() { return mDlwzIds; } public String getDeptName() { return mDeptName; } public String getDeptIds() { return mDeptIds; } public String getAllDlwzIds() { return mAllDlwzIds; } public String getAllDeptIds() { return mAllDeptIds; } public String getAllDeptName() { return mAllDeptName; } public String getAllDlwzName() { return mAllDlwzName; } public DeptLocationManager setAllDlwzName(String allDlwzName) { mAllDlwzName = allDlwzName; return this; } }
UTF-8
Java
3,374
java
DeptLocationManager.java
Java
[ { "context": "get.jdaddressselector.ISelectAble;\n\n/**\n * @ 创建者 zhou\n * @ 创建时间 2017/8/1 14:05\n * @ 描述 ${TODO}\n * ", "end": 168, "score": 0.9988453388214111, "start": 164, "tag": "USERNAME", "value": "zhou" } ]
null
[]
package coder.aihui.manager; import android.text.TextUtils; import java.util.ArrayList; import coder.aihui.widget.jdaddressselector.ISelectAble; /** * @ 创建者 zhou * @ 创建时间 2017/8/1 14:05 * @ 描述 ${TODO} * @ 更新者 $AUTHOR$ * @ 更新时间 2017/8/1$ * @ 更新描述 ${TODO} */ public class DeptLocationManager implements ISelectAbleManager{ public ArrayList<ISelectAble> selectAbles; String mDlwzName; String mDlwzIds; String mDeptName; String mDeptIds; String mAllDlwzIds; String mAllDeptIds; String mAllDeptName; String mAllDlwzName; //数据转化分析 public DeptLocationManager() { } public void solveDatas(ArrayList<ISelectAble> selectAbles) { String result = ""; StringBuilder sbids = new StringBuilder(); String arg = ""; sbids.append("("); for (int i = 0; i < selectAbles.size(); i++) { ISelectAble selectAble = selectAbles.get(i); if (i != selectAbles.size() - 1) { arg = selectAble.getArg(); String name = selectAble.getName(); int id = selectAble.getId(); result += name + "-"; sbids.append(id).append(","); } else { arg = selectAble.getArg(); String name = selectAble.getName(); int id = selectAble.getId(); result += name; sbids.append(id); } } sbids.append(")"); if (selectAbles != null && selectAbles.size() > 0) { ISelectAble iSelectAble = selectAbles.get(selectAbles.size() - 1); if ("dept".equals(arg)) { mDeptName = iSelectAble.getName(); mDeptIds = iSelectAble.getId() + ""; } else if ("location".equals(arg)) { mDlwzName = iSelectAble.getName(); mDlwzIds = iSelectAble.getId() + ""; } } if (!TextUtils.isEmpty(result)) { if ("dept".equals(arg)) { mAllDeptName = result.substring(0, result.length() ); } else if ("location".equals(arg)) { mAllDlwzName = result.substring(0, result.length() ); } } String ids = sbids.toString(); if (ids.length() != 2) { //说明只有() if ("dept".equals(arg)) { mAllDeptIds = ids; } else if ("location".equals(arg)) { mAllDlwzIds = ids; } } } public ArrayList<ISelectAble> getSelectAbles() { return selectAbles; } public String getDlwzName() { return mDlwzName; } public String getDlwzIds() { return mDlwzIds; } public String getDeptName() { return mDeptName; } public String getDeptIds() { return mDeptIds; } public String getAllDlwzIds() { return mAllDlwzIds; } public String getAllDeptIds() { return mAllDeptIds; } public String getAllDeptName() { return mAllDeptName; } public String getAllDlwzName() { return mAllDlwzName; } public DeptLocationManager setAllDlwzName(String allDlwzName) { mAllDlwzName = allDlwzName; return this; } }
3,374
0.532287
0.525347
140
22.671429
20.290548
78
false
false
0
0
0
0
0
0
0.392857
false
false
7
619bc5e9d6edb72d024171514b4cbb5783970a03
10,333,691,334,884
67bb19b0e82d6eea16e2b79e67613719038e34f3
/app/src/main/java/com/example/kjjeon/dagger2/class2/di/CafeComponent.java
aab4993d9e7f5b016d27ded555acf67c32a70fa5
[]
no_license
kjjeon/dagger2
https://github.com/kjjeon/dagger2
681bb735f5cdd05fbd5dd2a529868a7799c75aa3
8ed0fd502d9612539e30b9761172001d5798323b
refs/heads/master
2020-07-16T09:10:44.051000
2018-03-19T10:29:19
2018-03-19T10:29:19
205,761,224
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.kjjeon.dagger2.class2.di; import com.example.kjjeon.dagger2.class2.cafe.Cafe; import javax.inject.Singleton; import dagger.Component; /** * Created by kjjeon on 2018-03-19. */ @Singleton //cafeComponent와 연결되는 Module의 에서 scope를 사용 하려면 여기에 정의 해주어야 한다. CafeModule에서 @Singleton을 사용하기 때문에 선언(sample2) @Component(modules = CafeModule.class) public interface CafeComponent { //provison method (sample2) Cafe cafe(); // CafeMoudle 생성자에서 매개변수를 받아서 생성 할 경우 아래와 같이 정의 해서 사용 하면 된다. (sample3) @Component.Builder interface Builder { Builder cafeModule(CafeModule cafeModule); CafeComponent build(); } }
UTF-8
Java
797
java
CafeComponent.java
Java
[ { "context": "eton;\n\nimport dagger.Component;\n\n/**\n * Created by kjjeon on 2018-03-19.\n */\n\n@Singleton //cafeComponent와 연", "end": 182, "score": 0.9982683062553406, "start": 176, "tag": "USERNAME", "value": "kjjeon" } ]
null
[]
package com.example.kjjeon.dagger2.class2.di; import com.example.kjjeon.dagger2.class2.cafe.Cafe; import javax.inject.Singleton; import dagger.Component; /** * Created by kjjeon on 2018-03-19. */ @Singleton //cafeComponent와 연결되는 Module의 에서 scope를 사용 하려면 여기에 정의 해주어야 한다. CafeModule에서 @Singleton을 사용하기 때문에 선언(sample2) @Component(modules = CafeModule.class) public interface CafeComponent { //provison method (sample2) Cafe cafe(); // CafeMoudle 생성자에서 매개변수를 받아서 생성 할 경우 아래와 같이 정의 해서 사용 하면 된다. (sample3) @Component.Builder interface Builder { Builder cafeModule(CafeModule cafeModule); CafeComponent build(); } }
797
0.721461
0.69863
25
25.280001
27.661554
119
false
false
0
0
0
0
0
0
0.28
false
false
7
f064485b5398faabd571483fb9f585275505440f
12,240,656,796,142
892bffc2691f38a853402f3973bf8175bc8716a8
/okr/src/main/java/com/eximbay/okr/model/team/EditTeamOkrModel.java
aa37cedd0cba4c0c78a570c72c0339228b034e90
[]
no_license
JeongWu/okr-system
https://github.com/JeongWu/okr-system
1aab5d440bc4e28daaeafde3d149bf47c562cf64
6ea91309e1c67a04c6aec2333118b96433b6874b
refs/heads/master
2023-04-01T13:58:19.958000
2021-04-01T07:17:13
2021-04-01T07:17:13
351,608,127
0
0
null
false
2021-04-01T07:17:13
2021-03-25T23:51:52
2021-03-31T08:19:33
2021-04-01T07:17:13
6,862
0
0
0
JavaScript
false
false
package com.eximbay.okr.model.team; import com.eximbay.okr.dto.objective.ObjectiveDto; import lombok.Data; @Data public class EditTeamOkrModel extends TeamOkrCommonModel { private ObjectiveDto objectiveDto; }
UTF-8
Java
215
java
EditTeamOkrModel.java
Java
[]
null
[]
package com.eximbay.okr.model.team; import com.eximbay.okr.dto.objective.ObjectiveDto; import lombok.Data; @Data public class EditTeamOkrModel extends TeamOkrCommonModel { private ObjectiveDto objectiveDto; }
215
0.813953
0.813953
9
22.888889
21.615038
58
false
false
0
0
0
0
0
0
0.444444
false
false
7
e687c21e6aac72c63e66b063014ed7a77a3f4a41
25,082,609,024,854
2c912a1f00e74152b665d93830490b4b738b06b7
/app/src/main/java/com/hongyao/hongbao/listener/OnClickRecyclerViewItemListener.java
1474c4242f2f324c5694c3605ef4dec1c9fccf8f
[]
no_license
butlerL/hongyao
https://github.com/butlerL/hongyao
5b1b90c1ec9e360fff60f84019c446a74d37ad26
eea749d76296a5e1bb2e1f1672ede904011e4365
refs/heads/master
2020-04-29T22:57:57.113000
2019-03-19T09:06:33
2019-03-19T09:06:33
176,463,859
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.hongyao.hongbao.listener; /** * Created by liaolan on 16/3/25. */ public interface OnClickRecyclerViewItemListener { void onClick(int position); void onLongClick(int position); }
UTF-8
Java
203
java
OnClickRecyclerViewItemListener.java
Java
[ { "context": "e com.hongyao.hongbao.listener;\n\n/**\n * Created by liaolan on 16/3/25.\n */\npublic interface OnClickRecyclerV", "end": 64, "score": 0.9996063113212585, "start": 57, "tag": "USERNAME", "value": "liaolan" } ]
null
[]
package com.hongyao.hongbao.listener; /** * Created by liaolan on 16/3/25. */ public interface OnClickRecyclerViewItemListener { void onClick(int position); void onLongClick(int position); }
203
0.73399
0.70936
10
19.299999
18.542114
50
false
false
0
0
0
0
0
0
0.3
false
false
7
feb435f06b7c19d05b2326a619aad741a93d9e32
18,511,309,056,643
bcea54a8b45863f4af1c8b6816147450c302157b
/LambdaExpressions/src/main/java/org/punnoose/java8lambda/demo03/LambdaExpressionsDemo3.java
f101596335e9211b85c2afd46a34fd8717545126
[]
no_license
jacobpun/java8-experiments
https://github.com/jacobpun/java8-experiments
2d9943723232a4e30f632d801cb117f3e0c18fb7
9780ad1cc3e926bbeca29ac8830f9e82bb627dd0
refs/heads/master
2021-06-02T11:38:06.487000
2019-10-21T11:54:56
2019-10-21T11:54:56
18,784,886
0
0
null
false
2020-10-13T06:38:11
2014-04-15T02:36:41
2019-10-21T11:55:37
2020-10-13T06:38:10
60
0
0
2
Java
false
false
package org.punnoose.java8lambda.demo03; import java.util.Date; /** * Lambdas and local variables */ public class LambdaExpressionsDemo3 { @SuppressWarnings("unused") public static void main(String[] args) { Date localVariable = new Date(); // Lambdas can access local variables even if not explicitly declared as // final. MyInterface m1 = () -> { return localVariable; }; // However, lambdas cannot modify local variables MyInterface m3 = () -> { // localVariable = new Date(); //ERROR here return localVariable; }; } } /* * Only one method is allowed within a functional interface */ @FunctionalInterface interface MyInterface { Date myMethod(); // Date illegalMethod(); //ERROR here }
UTF-8
Java
729
java
LambdaExpressionsDemo3.java
Java
[]
null
[]
package org.punnoose.java8lambda.demo03; import java.util.Date; /** * Lambdas and local variables */ public class LambdaExpressionsDemo3 { @SuppressWarnings("unused") public static void main(String[] args) { Date localVariable = new Date(); // Lambdas can access local variables even if not explicitly declared as // final. MyInterface m1 = () -> { return localVariable; }; // However, lambdas cannot modify local variables MyInterface m3 = () -> { // localVariable = new Date(); //ERROR here return localVariable; }; } } /* * Only one method is allowed within a functional interface */ @FunctionalInterface interface MyInterface { Date myMethod(); // Date illegalMethod(); //ERROR here }
729
0.696845
0.688615
36
19.277779
19.454521
74
false
false
0
0
0
0
0
0
1.138889
false
false
7
d8cfd54372a0a003d8e5582f88cbe08645a1901c
21,148,418,973,362
58d43961a774dfec3331e955366b48df763b3f71
/mutool-box/src/main/java/com/mutool/box/common/logback/ConsoleLogAppender.java
0a5226719e2c0affce106db647bc6f582dd61198
[ "Apache-2.0" ]
permissive
liershuang/mutool-box
https://github.com/liershuang/mutool-box
e9ddac66fc77c7e7317504dd378a3a5872d7ff75
aba5686f8565e193eda36f952cf9c9433d3d3551
refs/heads/main
2023-02-07T11:13:30.326000
2020-12-30T11:31:58
2020-12-30T11:31:58
309,330,684
4
3
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.mutool.box.common.logback; import ch.qos.logback.classic.Level; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.core.OutputStreamAppender; import com.mutool.javafx.core.util.javafx.TooltipUtil; import javafx.scene.control.TextArea; import lombok.Data; import java.io.IOException; import java.io.OutputStream; import java.util.ArrayList; import java.util.List; /** * @ClassName: ConsoleLogAppender * @Description: 日志打印控制台 * @author: xufeng * @date: 2019/4/25 0025 23:18 */ @Data public class ConsoleLogAppender extends OutputStreamAppender<ILoggingEvent> { public final static List<TextArea> textAreaList = new ArrayList<>(); @Override public void start() { OutputStream targetStream = new OutputStream() { @Override public void write(int b) throws IOException { for (TextArea textArea : textAreaList) { textArea.appendText(b + "\n"); } } @Override public void write(byte[] b) throws IOException { for (TextArea textArea : textAreaList) { textArea.appendText(new String(b) + "\n"); } } }; setOutputStream(targetStream); super.start(); } @Override protected void append(ILoggingEvent eventObject) { if (eventObject.getLevel() == Level.ERROR) { try { TooltipUtil.showToast("发生错误:\n" + eventObject.getFormattedMessage()); } catch (Exception e) { } } super.append(eventObject); } }
UTF-8
Java
1,659
java
ConsoleLogAppender.java
Java
[ { "context": "leLogAppender\n * @Description: 日志打印控制台\n * @author: xufeng\n * @date: 2019/4/25 0025 23:18\n */\n\n@Data\npublic ", "end": 479, "score": 0.9996159076690674, "start": 473, "tag": "USERNAME", "value": "xufeng" } ]
null
[]
package com.mutool.box.common.logback; import ch.qos.logback.classic.Level; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.core.OutputStreamAppender; import com.mutool.javafx.core.util.javafx.TooltipUtil; import javafx.scene.control.TextArea; import lombok.Data; import java.io.IOException; import java.io.OutputStream; import java.util.ArrayList; import java.util.List; /** * @ClassName: ConsoleLogAppender * @Description: 日志打印控制台 * @author: xufeng * @date: 2019/4/25 0025 23:18 */ @Data public class ConsoleLogAppender extends OutputStreamAppender<ILoggingEvent> { public final static List<TextArea> textAreaList = new ArrayList<>(); @Override public void start() { OutputStream targetStream = new OutputStream() { @Override public void write(int b) throws IOException { for (TextArea textArea : textAreaList) { textArea.appendText(b + "\n"); } } @Override public void write(byte[] b) throws IOException { for (TextArea textArea : textAreaList) { textArea.appendText(new String(b) + "\n"); } } }; setOutputStream(targetStream); super.start(); } @Override protected void append(ILoggingEvent eventObject) { if (eventObject.getLevel() == Level.ERROR) { try { TooltipUtil.showToast("发生错误:\n" + eventObject.getFormattedMessage()); } catch (Exception e) { } } super.append(eventObject); } }
1,659
0.613928
0.604765
58
27.224138
22.354544
85
false
false
0
0
0
0
0
0
0.327586
false
false
7
ea28702c851364cb51a730565c24d819d84a42a5
13,666,586,005,096
b61a93c69d4c12c20777cb25ce4581cc0e7ec5a1
/nov30methods/src/Exceptions/ExceptionHandle.java
37ae18f321ed593246c18f62a5d8c4fa2a85b0a4
[]
no_license
divyasri14/MethodsNov30
https://github.com/divyasri14/MethodsNov30
e76239cd27585f1002386d9034d8bf33c189de3f
c177b496003ed9fda577fc8fd127061a4d689252
refs/heads/master
2020-04-09T00:12:25.698000
2018-12-26T10:33:35
2018-12-26T10:33:35
159,857,350
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package Exceptions; public class ExceptionHandle { public static void main(String[] args) { try { for (int i =0 ;i <=5;i++) { int[] arr = new int[5]; arr[0] = 5; arr[1] = 23; arr[2] = 125; arr[3] = 153; arr[4] = 146546; System.out.println(arr[i]); } } catch (ArrayIndexOutOfBoundsException e) { System.out.println("throwing Array exception"); } finally { System.out.println("it will execute irrespective of exception occurs or not"); } System.out.println("after Exception also executing this line"); } }
UTF-8
Java
625
java
ExceptionHandle.java
Java
[]
null
[]
package Exceptions; public class ExceptionHandle { public static void main(String[] args) { try { for (int i =0 ;i <=5;i++) { int[] arr = new int[5]; arr[0] = 5; arr[1] = 23; arr[2] = 125; arr[3] = 153; arr[4] = 146546; System.out.println(arr[i]); } } catch (ArrayIndexOutOfBoundsException e) { System.out.println("throwing Array exception"); } finally { System.out.println("it will execute irrespective of exception occurs or not"); } System.out.println("after Exception also executing this line"); } }
625
0.56
0.5232
33
16.939394
19.939209
81
false
false
0
0
0
0
0
0
2.727273
false
false
7
b529f4bf96e5b0ba25008c83886d02a983662162
13,666,586,004,076
efa72336b8246b53b0469ee338ac8c96901c8e5b
/jdk/src/main/java/com/kaka/jtest/jdk/arithmetic/interview/ArrayRepetition.java
36a916559711282f6cd6bea64641311d2f672dca
[]
no_license
jkaka/jtest
https://github.com/jkaka/jtest
3b31cfc8c6fd170963d07ba72a759c2d76429d1f
07e901b2a7814ed62164f3dd61d398c42c60677d
refs/heads/master
2022-12-22T11:27:41.536000
2020-04-13T06:33:01
2020-04-13T06:33:01
133,806,729
1
0
null
false
2022-12-16T00:42:41
2018-05-17T11:57:15
2020-04-13T06:33:14
2022-12-16T00:42:38
930
1
0
25
Java
false
false
package com.kaka.jtest.jdk.arithmetic.interview; import org.junit.Test; /** * @author jiashuangkai * @version 1.0 * @since 2019-11-19 17:56 */ public class ArrayRepetition { /** * 假设int数组长度为n,其中数组中的每个值都小于n; * 判断这个数组中的值是否有重复,要求空间复杂度小于O(n),时间复杂度小于等于O(n) * 如: * [0,2,1] 不重复 * [0,0,1,3] 重复 */ public static void main(String[] args) { int[] array = {1, 2, 0, 4, 0}; int k = array.length; int index; for (int i = 0; i < k; i++) { if (array[i] >= k) { index = array[i] - k; } else { index = array[i]; } array[index] += k; if (array[index] >= 2 * k) { System.out.println("重复的数据为:" + index); break; } } } @Test public void replete() { int[] array = {1, 2, 0, 2, 4}; for (int i = 0; i < array.length; i++) { while (array[i] != i) { if (array[array[i]] == array[i]) { System.out.println("重复的数据为:" + array[i]); break; } int temp = array[array[i]]; array[array[i]] = array[i]; array[i] = temp; } } } }
UTF-8
Java
1,445
java
ArrayRepetition.java
Java
[ { "context": "interview;\n\nimport org.junit.Test;\n\n/**\n * @author jiashuangkai\n * @version 1.0\n * @since 2019-11-19 17:56\n */\npu", "end": 101, "score": 0.8750932216644287, "start": 89, "tag": "USERNAME", "value": "jiashuangkai" } ]
null
[]
package com.kaka.jtest.jdk.arithmetic.interview; import org.junit.Test; /** * @author jiashuangkai * @version 1.0 * @since 2019-11-19 17:56 */ public class ArrayRepetition { /** * 假设int数组长度为n,其中数组中的每个值都小于n; * 判断这个数组中的值是否有重复,要求空间复杂度小于O(n),时间复杂度小于等于O(n) * 如: * [0,2,1] 不重复 * [0,0,1,3] 重复 */ public static void main(String[] args) { int[] array = {1, 2, 0, 4, 0}; int k = array.length; int index; for (int i = 0; i < k; i++) { if (array[i] >= k) { index = array[i] - k; } else { index = array[i]; } array[index] += k; if (array[index] >= 2 * k) { System.out.println("重复的数据为:" + index); break; } } } @Test public void replete() { int[] array = {1, 2, 0, 2, 4}; for (int i = 0; i < array.length; i++) { while (array[i] != i) { if (array[array[i]] == array[i]) { System.out.println("重复的数据为:" + array[i]); break; } int temp = array[array[i]]; array[array[i]] = array[i]; array[i] = temp; } } } }
1,445
0.413261
0.387047
52
23.942308
16.328848
61
false
false
0
0
0
0
0
0
0.634615
false
false
7
769418ebde38cdaff3a8d53ef06884be27a25ec0
9,500,467,728,285
cba3c1c781e2f8481d62cf7eee01654c383c038a
/trade-core/src/main/java/com/centaline/trans/team/repository/TsTeamScopeGrpMapper.java
26922742fe3f2561fc4f4d885be76d297cbb4f57
[]
no_license
zhouhantong/trade-web
https://github.com/zhouhantong/trade-web
90e5d93e74996271163521405a6fd2d1e92cf794
84f09f27dca2e733a2da24485a19c7bddba23c37
HEAD
2018-12-25T01:07:50.539000
2018-10-18T01:27:15
2018-10-18T01:27:15
110,204,197
1
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.centaline.trans.team.repository; import java.util.List; import com.centaline.trans.common.MyBatisRepository; import com.centaline.trans.team.entity.TsTeamScopeGrp; @MyBatisRepository public interface TsTeamScopeGrpMapper { int deleteByPrimaryKey(Long pkid); int insert(TsTeamScopeGrp record); int insertSelective(TsTeamScopeGrp record); TsTeamScopeGrp selectByPrimaryKey(Long pkid); int updateByPrimaryKeySelective(TsTeamScopeGrp record); int updateByPrimaryKey(TsTeamScopeGrp record); List<TsTeamScopeGrp> getTsTeamScopeGrpListByProperty(TsTeamScopeGrp record); int delTsTeamScopeGrpByProperty(TsTeamScopeGrp record); }
UTF-8
Java
682
java
TsTeamScopeGrpMapper.java
Java
[]
null
[]
package com.centaline.trans.team.repository; import java.util.List; import com.centaline.trans.common.MyBatisRepository; import com.centaline.trans.team.entity.TsTeamScopeGrp; @MyBatisRepository public interface TsTeamScopeGrpMapper { int deleteByPrimaryKey(Long pkid); int insert(TsTeamScopeGrp record); int insertSelective(TsTeamScopeGrp record); TsTeamScopeGrp selectByPrimaryKey(Long pkid); int updateByPrimaryKeySelective(TsTeamScopeGrp record); int updateByPrimaryKey(TsTeamScopeGrp record); List<TsTeamScopeGrp> getTsTeamScopeGrpListByProperty(TsTeamScopeGrp record); int delTsTeamScopeGrpByProperty(TsTeamScopeGrp record); }
682
0.802053
0.802053
25
26.32
25.266136
80
false
false
0
0
0
0
0
0
0.48
false
false
7
56d88bb1ef82b2f0794997b89499b2dd2e76b6ef
9,500,467,727,732
68546b9e13c6402c6762c76d7f8284690db28f77
/MapReduceClientServer/server/src/main/java/ServerMain.java
2d3992a2eeff79f9f7671a6eb35fb6e3e2eefe98
[]
no_license
ed-miller1/Akka
https://github.com/ed-miller1/Akka
41f45ae53def866fbc3d58748ea84fcd28a337bb
3909df3e338066ed6131f03c3eb35060c5591538
refs/heads/master
2019-08-26T18:09:59.381000
2016-04-20T03:35:05
2016-04-20T03:35:05
56,652,292
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import akka.actor.ActorRef; import akka.actor.ActorSystem; import akka.actor.Props; import com.typesafe.config.ConfigFactory; /** * Created by Ed M on 4/18/2016. */ public class ServerMain { public static void main(String[] args) throws InterruptedException { ActorSystem system = ActorSystem.create("MapReduce", ConfigFactory.load().getConfig("server")); System.out.println("server ready"); //create Master but don't start it for here. Simply to handle messages from local Thread.sleep(500000); system.terminate(); } }
UTF-8
Java
573
java
ServerMain.java
Java
[ { "context": ".typesafe.config.ConfigFactory;\n\n/**\n * Created by Ed M on 4/18/2016.\n */\npublic class ServerMain {\n p", "end": 149, "score": 0.9966630339622498, "start": 145, "tag": "NAME", "value": "Ed M" } ]
null
[]
import akka.actor.ActorRef; import akka.actor.ActorSystem; import akka.actor.Props; import com.typesafe.config.ConfigFactory; /** * Created by <NAME> on 4/18/2016. */ public class ServerMain { public static void main(String[] args) throws InterruptedException { ActorSystem system = ActorSystem.create("MapReduce", ConfigFactory.load().getConfig("server")); System.out.println("server ready"); //create Master but don't start it for here. Simply to handle messages from local Thread.sleep(500000); system.terminate(); } }
575
0.699825
0.677138
19
29.157894
29.521202
103
false
false
0
0
0
0
0
0
0.473684
false
false
7
534f015e431c5fe698548124f2d2fc40c4e360c3
11,725,260,755,831
336c99e29a5373746ead4d692eee023cc0be50a8
/java/orientacaoaobjetos/src/lista01ExercicosPOO/Eletronicos.java
ad17ccfc2083bd7077b10b44909a83d54fe2133e
[]
no_license
gildenorjunior/Turma11JavaGeneration
https://github.com/gildenorjunior/Turma11JavaGeneration
164627ce58a836ec757cd6933fa44d6a5d9f5242
389efd29f53d9061361534fa42b54b0b5da406b6
refs/heads/master
2023-01-10T06:44:55.197000
2020-11-10T17:38:16
2020-11-10T17:38:16
298,044,413
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package lista01ExercicosPOO; public class Eletronicos { String tipo; String marca; int preco; String cor; public void liga() { System.out.println("Ligando o eletrônico..."); } }
ISO-8859-1
Java
194
java
Eletronicos.java
Java
[]
null
[]
package lista01ExercicosPOO; public class Eletronicos { String tipo; String marca; int preco; String cor; public void liga() { System.out.println("Ligando o eletrônico..."); } }
194
0.694301
0.683938
14
12.785714
13.507557
48
false
false
0
0
0
0
0
0
1.214286
false
false
7
b5326bec586703d7e80ed0fdd771bfa2353cd534
7,516,192,797,399
be045249ef81382e99467c409427d1d74f3d95d8
/septirahayu-14111200-encapIntegration/MesinMobil.java
9ba832e649259a6738b6484b41869f109581efca
[]
no_license
sepraha/objectorientedprogrammingII
https://github.com/sepraha/objectorientedprogrammingII
052532223744c6788fabf213c017446be4a35af9
34309142e6f675c304c9f59d2b754b9be59decbb
refs/heads/master
2021-01-22T21:38:46.856000
2017-06-12T07:14:12
2017-06-12T07:14:12
85,460,433
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
public class MesinMobil implements Mesin{ public String getMesin(){ return "Ini adalah mesin Mobil" } public String getBahanBakar(){ return "Salah satu bahan bakar Mobil adalah Pertamax" } public String countKapasitasTangki(){ return "Kapasitas tangki bahan bakar pada setiap jenis Mobil berbeda"; } }
UTF-8
Java
316
java
MesinMobil.java
Java
[]
null
[]
public class MesinMobil implements Mesin{ public String getMesin(){ return "Ini adalah mesin Mobil" } public String getBahanBakar(){ return "Salah satu bahan bakar Mobil adalah Pertamax" } public String countKapasitasTangki(){ return "Kapasitas tangki bahan bakar pada setiap jenis Mobil berbeda"; } }
316
0.759494
0.759494
14
21.642857
23.168966
72
false
false
0
0
0
0
0
0
0.928571
false
false
7
4796bd2e3f00766c26081329280fbf227cb20da0
17,420,387,390,276
4b0bf4787e89bcae7e4759bde6d7f3ab2c81f849
/aliyun-java-sdk-cloudphoto/src/main/java/com/aliyuncs/cloudphoto/transform/v20170711/SetAlbumCoverResponseUnmarshaller.java
803a344d68efe79bb65db73c2cbb0e3cd4495c36
[ "Apache-2.0" ]
permissive
aliyun/aliyun-openapi-java-sdk
https://github.com/aliyun/aliyun-openapi-java-sdk
a263fa08e261f12d45586d1b3ad8a6609bba0e91
e19239808ad2298d32dda77db29a6d809e4f7add
refs/heads/master
2023-09-03T12:28:09.765000
2023-09-01T09:03:00
2023-09-01T09:03:00
39,555,898
1,542
1,317
NOASSERTION
false
2023-09-14T07:27:05
2015-07-23T08:41:13
2023-08-31T07:30:44
2023-09-14T07:27:03
72,323
1,375
1,144
12
Java
false
false
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.aliyuncs.cloudphoto.transform.v20170711; import com.aliyuncs.cloudphoto.model.v20170711.SetAlbumCoverResponse; import com.aliyuncs.transform.UnmarshallerContext; public class SetAlbumCoverResponseUnmarshaller { public static SetAlbumCoverResponse unmarshall(SetAlbumCoverResponse setAlbumCoverResponse, UnmarshallerContext context) { setAlbumCoverResponse.setRequestId(context.stringValue("SetAlbumCoverResponse.RequestId")); setAlbumCoverResponse.setCode(context.stringValue("SetAlbumCoverResponse.Code")); setAlbumCoverResponse.setMessage(context.stringValue("SetAlbumCoverResponse.Message")); setAlbumCoverResponse.setAction(context.stringValue("SetAlbumCoverResponse.Action")); return setAlbumCoverResponse; } }
UTF-8
Java
1,314
java
SetAlbumCoverResponseUnmarshaller.java
Java
[]
null
[]
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.aliyuncs.cloudphoto.transform.v20170711; import com.aliyuncs.cloudphoto.model.v20170711.SetAlbumCoverResponse; import com.aliyuncs.transform.UnmarshallerContext; public class SetAlbumCoverResponseUnmarshaller { public static SetAlbumCoverResponse unmarshall(SetAlbumCoverResponse setAlbumCoverResponse, UnmarshallerContext context) { setAlbumCoverResponse.setRequestId(context.stringValue("SetAlbumCoverResponse.RequestId")); setAlbumCoverResponse.setCode(context.stringValue("SetAlbumCoverResponse.Code")); setAlbumCoverResponse.setMessage(context.stringValue("SetAlbumCoverResponse.Message")); setAlbumCoverResponse.setAction(context.stringValue("SetAlbumCoverResponse.Action")); return setAlbumCoverResponse; } }
1,314
0.802892
0.787671
32
39.9375
36.321426
123
false
false
0
0
0
0
0
0
0.90625
false
false
7
8c9a64181d806aafa3871759486c26a649403bd2
8,667,244,061,765
dc3d3cedc6b5e3e1cc1653feaffef0763e3c15ca
/AA-A1-master/src/datageneration/DataGenerator.java
bee2b2d89b3ea9aab56f6cfcb9077cbf3a966d1f
[]
no_license
rhasan1/AlgoTester2019
https://github.com/rhasan1/AlgoTester2019
62caea9dd9f32d63d12e3e9eae247518087fe03e
2e59b568cbcb652ff14676ae4ce118ce5295a135
refs/heads/master
2022-12-18T06:08:44.006000
2020-07-07T16:24:47
2020-07-07T16:24:47
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package datageneration; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.concurrent.ThreadLocalRandom; public class DataGenerator { public static void main(String[] args) { dataGenerator(100, "DEs"); } public static void dataGenerator(int length, String filename) { String fileLine = ""; ArrayList<Integer> values = new ArrayList<Integer>(); // Create a shuffled list of specified range // Each list contains only unique values. // for (int i = 1; i <= length; i++) { // values.add(new Integer(i)); // } // Collections.shuffle(values); //For Testing Values // int randomNum; // for (int i = 1; i <= length; i++) { // randomNum = ThreadLocalRandom.current().nextInt(1, 100000 + 1); // values.add(randomNum); // } // Create output file and FileWriter try { File myFile = new File(filename + ".txt"); if (myFile.createNewFile()) { System.out.println("File created successfully: " + myFile.getName()); } else { System.out.println("File name already exists."); throw new IOException(); } FileWriter output = new FileWriter(myFile); // Write to file for (int i = 0; i < length; i++) { // No new line at end of file. if (i == length - 1) { fileLine += "DE"; //fileLine += "PT " + "P" + values.get(i); output.write(fileLine); } else { fileLine += "DE" + "\n"; //fileLine += "PT " + "P" + values.get(i) + "\n"; output.write(fileLine); fileLine = ""; } } output.close(); } catch (IOException e) { System.out.println("Error: IO Exception."); e.printStackTrace(); } } }
UTF-8
Java
1,710
java
DataGenerator.java
Java
[]
null
[]
package datageneration; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.concurrent.ThreadLocalRandom; public class DataGenerator { public static void main(String[] args) { dataGenerator(100, "DEs"); } public static void dataGenerator(int length, String filename) { String fileLine = ""; ArrayList<Integer> values = new ArrayList<Integer>(); // Create a shuffled list of specified range // Each list contains only unique values. // for (int i = 1; i <= length; i++) { // values.add(new Integer(i)); // } // Collections.shuffle(values); //For Testing Values // int randomNum; // for (int i = 1; i <= length; i++) { // randomNum = ThreadLocalRandom.current().nextInt(1, 100000 + 1); // values.add(randomNum); // } // Create output file and FileWriter try { File myFile = new File(filename + ".txt"); if (myFile.createNewFile()) { System.out.println("File created successfully: " + myFile.getName()); } else { System.out.println("File name already exists."); throw new IOException(); } FileWriter output = new FileWriter(myFile); // Write to file for (int i = 0; i < length; i++) { // No new line at end of file. if (i == length - 1) { fileLine += "DE"; //fileLine += "PT " + "P" + values.get(i); output.write(fileLine); } else { fileLine += "DE" + "\n"; //fileLine += "PT " + "P" + values.get(i) + "\n"; output.write(fileLine); fileLine = ""; } } output.close(); } catch (IOException e) { System.out.println("Error: IO Exception."); e.printStackTrace(); } } }
1,710
0.621637
0.612866
69
23.782608
18.890892
73
false
false
0
0
0
0
0
0
2.695652
false
false
7
c387210b4542a6d466d54a8940d8be7c53e1a3ba
8,959,301,795,793
360a059ae2d13b2317912babad32a5b4da05688f
/projectmain/src/main/java/com/example/puneetgupta/projectmain/Third.java
3ae08f68150c3f6c611c5fcfd88f036a78ce05bf
[]
no_license
puneetgupta4java/Android
https://github.com/puneetgupta4java/Android
52fcffaffa2c1065b380f162f21ce805e27f03d4
1df88caa89531219a80f8966fda669259e0cf35d
refs/heads/master
2021-01-02T08:41:26.440000
2017-08-14T18:13:44
2017-08-14T18:13:44
99,043,355
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.puneetgupta.projectmain; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; public class Third extends AppCompatActivity { TextView t1; Button b1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_third); t1 = (TextView)findViewById(R.id.textView); t1.setText("Welcome User"); b1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent i4 = new Intent(Third.this,MainActivity.class); startActivity(i4); finish(); } }); } }
UTF-8
Java
892
java
Third.java
Java
[ { "context": "package com.example.puneetgupta.projectmain;\r\n\r\nimport android.content.Intent;\r\ni", "end": 31, "score": 0.6156688928604126, "start": 21, "tag": "USERNAME", "value": "uneetgupta" } ]
null
[]
package com.example.puneetgupta.projectmain; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; public class Third extends AppCompatActivity { TextView t1; Button b1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_third); t1 = (TextView)findViewById(R.id.textView); t1.setText("Welcome User"); b1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent i4 = new Intent(Third.this,MainActivity.class); startActivity(i4); finish(); } }); } }
892
0.637892
0.628924
28
29.857143
18.728729
70
false
false
0
0
0
0
0
0
0.642857
false
false
7
f5952b52bbbb925248616abe989728f76df8542d
20,993,800,149,625
77780b12aa5711b1ae93c50af424d4da2b40d03d
/steph/controlflowchallenges/sumFirstAndLastDigit.java
63cb46169f5f73c7a8696e00c13f149dd466d321
[]
no_license
MidKnight92/JavaProgrammingMasterClass
https://github.com/MidKnight92/JavaProgrammingMasterClass
c1dc17892d17eb478820abfe542452ac13025f06
192e886e14ad8a9f85414411dfb7fcc233d6e167
refs/heads/main
2023-02-22T06:05:08.080000
2021-01-28T20:20:32
2021-01-28T20:20:32
333,516,069
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.viveros.steph.controlflowchallenges; public class sumFirstAndLastDigit { public static void main(String[] args) { System.out.println(sumFirstAndLastDigit(252)); System.out.println(sumFirstAndLastDigit(257)); System.out.println(sumFirstAndLastDigit(0)); System.out.println(sumFirstAndLastDigit(5)); System.out.println(sumFirstAndLastDigit(-10)); } public static int sumFirstAndLastDigit(int number){ int sum = 0; if (number < 0){ return -1; } else if (number == 0) { return sum; } else { String numAsString = Integer.toString(number); int numLength = numAsString.length(); sum = Integer.parseInt(String.valueOf(numAsString.charAt(0))) + Integer.parseInt(String.valueOf(numAsString.charAt(numLength - 1))); } return sum; } }
UTF-8
Java
901
java
sumFirstAndLastDigit.java
Java
[]
null
[]
package com.viveros.steph.controlflowchallenges; public class sumFirstAndLastDigit { public static void main(String[] args) { System.out.println(sumFirstAndLastDigit(252)); System.out.println(sumFirstAndLastDigit(257)); System.out.println(sumFirstAndLastDigit(0)); System.out.println(sumFirstAndLastDigit(5)); System.out.println(sumFirstAndLastDigit(-10)); } public static int sumFirstAndLastDigit(int number){ int sum = 0; if (number < 0){ return -1; } else if (number == 0) { return sum; } else { String numAsString = Integer.toString(number); int numLength = numAsString.length(); sum = Integer.parseInt(String.valueOf(numAsString.charAt(0))) + Integer.parseInt(String.valueOf(numAsString.charAt(numLength - 1))); } return sum; } }
901
0.629301
0.611543
25
35.040001
29.852276
144
false
false
0
0
0
0
0
0
0.52
false
false
7
34fd523956503334c8e07b3646a105d1561b93c6
7,997,229,128,391
d98de110431e5124ec7cc70d15906dac05cfa61a
/public/source/core/src/main/java/org/marketcetera/persist/PersistContext.java
0d4300d3a42f11b1f34fbb9ce7d40d3fe5c63869
[]
no_license
dhliu3/marketcetera
https://github.com/dhliu3/marketcetera
367f6df815b09f366eb308481f4f53f928de4c49
4a81e931a044ba19d8f35bdadd4ab081edd02f5f
refs/heads/master
2020-04-06T04:39:55.389000
2012-01-30T06:49:25
2012-01-30T06:49:25
29,947,427
0
1
null
true
2015-01-28T02:54:39
2015-01-28T02:54:39
2013-11-07T00:27:20
2012-01-30T21:57:21
33,324
0
0
0
null
null
null
package org.marketcetera.persist; import org.marketcetera.core.ClassVersion; import java.io.Serializable; /* $License$ */ /** * A context that might be used to send extra information * as a part persist operations from client-side to * server-side. This abstraction is not used by the persistence * infrastructure. And is purely meant to be used by code using * the persistence infrastructure, in case they need to supply * extra data between the client-end and the server-end when * invoking various persistence operations. * * @author anshul@marketcetera.com */ @ClassVersion("$Id: PersistContext.java 9456 2008-07-31 22:28:30Z klim $") //$NON-NLS-1$ public interface PersistContext extends Serializable { }
UTF-8
Java
744
java
PersistContext.java
Java
[ { "context": "ng various persistence operations.\r\n *\r\n * @author anshul@marketcetera.com\r\n */\r\n@ClassVersion(\"$Id: PersistContext.java 945", "end": 588, "score": 0.9999295473098755, "start": 565, "tag": "EMAIL", "value": "anshul@marketcetera.com" } ]
null
[]
package org.marketcetera.persist; import org.marketcetera.core.ClassVersion; import java.io.Serializable; /* $License$ */ /** * A context that might be used to send extra information * as a part persist operations from client-side to * server-side. This abstraction is not used by the persistence * infrastructure. And is purely meant to be used by code using * the persistence infrastructure, in case they need to supply * extra data between the client-end and the server-end when * invoking various persistence operations. * * @author <EMAIL> */ @ClassVersion("$Id: PersistContext.java 9456 2008-07-31 22:28:30Z klim $") //$NON-NLS-1$ public interface PersistContext extends Serializable { }
728
0.740591
0.715054
21
33.42857
27.005417
88
false
false
0
0
0
0
0
0
0.190476
false
false
7
517b8bf0f043db039f745a8aa878a7717b294247
7,456,063,268,480
1272e0af6c6ab10523dfe21f21bd5df85f964116
/bundles/com.zutubi.pulse.core.scm.svn/src/test/com/zutubi/pulse/core/scm/svn/SubversionClientTest.java
a6d496e0ed692601595d420a2e5201e45d64776e
[ "Apache-2.0" ]
permissive
ppsravan/pulse
https://github.com/ppsravan/pulse
083e57932423ea6360e3642f3934e17ea450be75
6a41105ae8438018b055611268c20dac5585f890
refs/heads/master
2022-03-10T23:17:58.540000
2017-04-14T12:00:02
2017-04-14T12:00:02
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* Copyright 2017 Zutubi Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.zutubi.pulse.core.scm.svn; import com.google.common.base.Predicate; import com.zutubi.pulse.core.PulseExecutionContext; import com.zutubi.pulse.core.scm.RecordingScmFeedbackHandler; import com.zutubi.pulse.core.scm.ScmContextImpl; import com.zutubi.pulse.core.scm.api.*; import com.zutubi.pulse.core.test.TestUtils; import com.zutubi.pulse.core.test.api.PulseTestCase; import com.zutubi.util.io.FileSystemUtils; import com.zutubi.util.io.IOUtils; import com.zutubi.util.junit.IOAssertions; import org.tmatesoft.svn.core.SVNCommitInfo; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.SVNURL; import org.tmatesoft.svn.core.wc.*; import java.io.File; import java.io.IOException; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.List; import static com.google.common.collect.Iterables.filter; import static com.google.common.collect.Lists.newArrayList; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.hasItem; public class SubversionClientTest extends PulseTestCase { private static final String REPO = "svn://localhost/test/"; private static final String USER = "jsankey"; private static final String PASSWORD = "password"; private static final String TRUNK_PATH = REPO + "trunk"; private static final String BRANCH_PATH = REPO + "branches/new-branch"; private static final String TAG_PATH = REPO + "tags/test-tag"; private static final int REVISION_TRUNK_LATEST = 4; private SubversionClient client; private File tmpDir; private File gotDir; private File expectedDir; private Process serverProcess; private PulseExecutionContext executionContext; private ScmContext context; private SVNClientManager clientManager; // $ svn log -v svn://localhost/test // ------------------------------------------------------------------------ // r8 | jsankey | 2006-06-20 18:26:41 +1000 (Tue, 20 Jun 2006) | 1 line // Changed paths: // A /test/tags // // Make tags dir // ------------------------------------------------------------------------ // r7 | jsankey | 2006-06-20 17:32:58 +1000 (Tue, 20 Jun 2006) | 1 line // Changed paths: // M /test/branches/dev-it/afolder/f1 // // Edit a branch // ------------------------------------------------------------------------ // r6 | jsankey | 2006-06-20 17:31:51 +1000 (Tue, 20 Jun 2006) | 1 line // Changed paths: // A /test/branches/dev-it (from /test/trunk:5) // // Make a branch // ------------------------------------------------------------------------ // r5 | jsankey | 2006-06-20 17:31:48 +1000 (Tue, 20 Jun 2006) | 1 line // Changed paths: // A /test/branches // // Make a dir // ------------------------------------------------------------------------ // r4 | jsankey | 2006-06-20 17:30:28 +1000 (Tue, 20 Jun 2006) | 1 line // Changed paths: // D /test/trunk/bar // // Delete a file // ------------------------------------------------------------------------ // r3 | jsankey | 2006-06-20 17:30:17 +1000 (Tue, 20 Jun 2006) | 1 line // Changed paths: // A /test/trunk/bar // // Add a file // ------------------------------------------------------------------------ // r2 | jsankey | 2006-06-20 17:30:00 +1000 (Tue, 20 Jun 2006) | 1 line // Changed paths: // M /test/trunk/foo // // Edit a file // ------------------------------------------------------------------------ // r1 | jsankey | 2006-06-20 16:13:29 +1000 (Tue, 20 Jun 2006) | 1 line // Changed paths: // A /test // A /test/trunk // A /test/trunk/afolder // A /test/trunk/afolder/f1 // A /test/trunk/afolder/f2 // A /test/trunk/bfolder // A /test/trunk/bfolder/f1 // A /test/trunk/foo // // Importing test data // ------------------------------------------------------------------------ protected void setUp() throws Exception { super.setUp(); tmpDir = FileSystemUtils.createTempDir(getClass().getName(), ""); File repoDir = new File(tmpDir, "repo"); FileSystemUtils.createDirectory(repoDir); expectedDir = new File(repoDir, "expected"); FileSystemUtils.createDirectory(expectedDir); gotDir = new File(repoDir, "got"); FileSystemUtils.createDirectory(gotDir); executionContext = new PulseExecutionContext(); executionContext.setWorkingDir(gotDir); context = new ScmContextImpl(null, executionContext); unzipInput("data", repoDir); serverProcess = Runtime.getRuntime().exec(new String[]{"svnserve", "--foreground", "--listen-port=3690", "--listen-host=127.0.0.1", "-dr", "."}, null, repoDir); TestUtils.waitForServer(3690); clientManager = SVNClientManager.newInstance(null, SVNWCUtil.createDefaultAuthenticationManager(USER, PASSWORD)); createSubversionClient(TRUNK_PATH); } protected void tearDown() throws Exception { IOUtils.close(client); serverProcess.destroy(); serverProcess.waitFor(); clientManager.dispose(); removeDirectory(tmpDir); super.tearDown(); } public void testGetLatestRevision() throws ScmException { client = createSubversionClient("svn://localhost/"); assertEquals("8", client.getLatestRevision(context).getRevisionString()); } public void testGetLatestRevisionRestrictedToFiles() throws ScmException { assertEquals("4", client.getLatestRevision(context).getRevisionString()); } public void testGetLatestRevisionNewBranch() throws ScmException, SVNException { SVNCopyClient client = clientManager.getCopyClient(); SVNCopySource[] copySource = {new SVNCopySource(SVNRevision.UNDEFINED, SVNRevision.HEAD, SVNURL.parseURIDecoded(TRUNK_PATH))}; SVNCommitInfo info = client.doCopy(copySource, SVNURL.parseURIDecoded(BRANCH_PATH), false, true, true, "Create a branch", null); SubversionClient branchClient = new SubversionClient(BRANCH_PATH, false); assertEquals(Long.toString(info.getNewRevision()), branchClient.getLatestRevision(context).getRevisionString()); } public void testGetLatestRevisionBadRepository() { try { client = createSubversionClient("svn://localhost/no/such/repo"); client.getLatestRevision(context); fail(); } catch (ScmException e) { assertTrue(e.getMessage().contains("no repository found")); } } public void testList() throws ScmException { List<ScmFile> files = client.browse(null, "afolder", null); assertEquals(2, files.size()); assertEquals("f1", files.get(0).getName()); assertEquals("f2", files.get(1).getName()); } public void testListNonExistent() throws ScmException { try { client.browse(null, "nosuchfile", null); fail(); } catch (ScmException e) { assertTrue(e.getMessage().contains("not found")); } } public void testTag() throws ScmException, IOException { client.tag(null, createRevision(1), TAG_PATH, false); SubversionClient confirmServer = null; try { confirmServer = new SubversionClient(TAG_PATH, false, USER, PASSWORD); List<ScmFile> files = getSortedListing(confirmServer); assertEquals(3, files.size()); assertEquals("afolder", files.get(0).getName()); assertEquals("bfolder", files.get(1).getName()); assertEquals("foo", files.get(2).getName()); String foo = ScmUtils.retrieveContent(confirmServer, null, "foo", null); assertEquals("", foo); } finally { IOUtils.close(confirmServer); } } public void testMoveTag() throws ScmException, IOException { client.tag(null, createRevision(1), TAG_PATH, false); client.tag(null, createRevision(8), TAG_PATH, true); assertTaggedRev8(); } public void testMoveTagNonExistant() throws ScmException, IOException { client.tag(null, createRevision(8), TAG_PATH, true); assertTaggedRev8(); } private void assertTaggedRev8() throws ScmException, IOException { SubversionClient confirmServer = null; try { confirmServer = new SubversionClient(TAG_PATH, false, USER, PASSWORD); List<ScmFile> files = getSortedListing(confirmServer); assertEquals(3, files.size()); assertEquals("afolder", files.get(0).getName()); assertEquals("bfolder", files.get(1).getName()); assertEquals("foo", files.get(2).getName()); String foo = ScmUtils.retrieveContent(confirmServer, null, "foo", null); assertEquals("hello\n", foo); } finally { IOUtils.close(confirmServer); } } public void testUnmovableTag() throws ScmException { client.tag(null, createRevision(1), TAG_PATH, false); try { client.tag(null, createRevision(8), TAG_PATH, false); fail(); } catch (ScmException e) { assertEquals("Unable to apply tag: path '" + TAG_PATH + "' already exists in the repository", e.getMessage()); } } public void testChangesSince() throws ScmException { List<Changelist> changes = client.getChanges(context, createRevision(2), null); assertEquals(2, changes.size()); Changelist changelist = changes.get(0); assertEquals("3", changelist.getRevision().getRevisionString()); assertEquals(1, changelist.getChanges().size()); assertEquals("/test/trunk/bar", changelist.getChanges().get(0).getPath()); assertEquals(FileChange.Action.ADD, changelist.getChanges().get(0).getAction()); changelist = changes.get(1); assertEquals("4", changelist.getRevision().getRevisionString()); assertEquals(1, changelist.getChanges().size()); assertEquals("/test/trunk/bar", changelist.getChanges().get(0).getPath()); assertEquals(FileChange.Action.DELETE, changelist.getChanges().get(0).getAction()); } public void testChangesBetweenTwoRevisions() throws ScmException { List<Changelist> changes = client.getChanges(context, createRevision(2), createRevision(3)); assertEquals(1, changes.size()); Changelist changelist = changes.get(0); assertEquals("3", changelist.getRevision().getRevisionString()); assertEquals(1, changelist.getChanges().size()); assertEquals("/test/trunk/bar", changelist.getChanges().get(0).getPath()); assertEquals(FileChange.Action.ADD, changelist.getChanges().get(0).getAction()); } public void testChangesBetweenReversedRange() throws ScmException { List<Changelist> changes = client.getChanges(context, createRevision(3), createRevision(2)); assertEquals(1, changes.size()); Changelist changelist = changes.get(0); assertEquals("3", changelist.getRevision().getRevisionString()); assertEquals(1, changelist.getChanges().size()); assertEquals("/test/trunk/bar", changelist.getChanges().get(0).getPath()); assertEquals(FileChange.Action.ADD, changelist.getChanges().get(0).getAction()); } public void testRevisionsSince() throws ScmException { List<Revision> revisions = client.getRevisions(context, createRevision(2), null); assertEquals(2, revisions.size()); assertEquals("3", revisions.get(0).getRevisionString()); assertEquals("4", revisions.get(1).getRevisionString()); } public void testRevisionsSinceLatestInFiles() throws ScmException { List<Revision> revisions = client.getRevisions(context, createRevision(6), null); assertEquals(0, revisions.size()); } public void testRevisionsSincePastHead() throws ScmException { try { client.getRevisions(context, createRevision(9), null); } catch (ScmException e) { assertThat(e.getMessage(), containsString("No such revision 9")); } } public void testGetRevisionsInRange() throws ScmException { List<Revision> revisions = client.getRevisions(context, createRevision(2), createRevision(4)); assertEquals(2, revisions.size()); assertEquals("3", revisions.get(0).getRevisionString()); assertEquals("4", revisions.get(1).getRevisionString()); } public void testGetRevisionsInReverseRange() throws ScmException { List<Revision> revisions = client.getRevisions(context, createRevision(4), createRevision(2)); assertEquals(2, revisions.size()); assertEquals("4", revisions.get(0).getRevisionString()); assertEquals("3", revisions.get(1).getRevisionString()); } public void testCheckout() throws ScmException, IOException { client.checkout(executionContext, null, null); assertRevision(gotDir, 8); assertTrue(new File(gotDir, ".svn").isDirectory()); } public void testExport() throws ScmException, IOException { client.setUseExport(true); client.checkout(executionContext, null, null); assertRevision(gotDir, 8); assertFalse(new File(gotDir, ".svn").isDirectory()); } public void testUpdate() throws ScmException, IOException { client.checkout(executionContext, createRevision(1), null); assertRevision(gotDir, 1); client.update(executionContext, null, null); assertRevision(gotDir, 8); } public void testMultiUpdate() throws ScmException, IOException { client.checkout(executionContext, createRevision(1), null); client.update(executionContext, createRevision(4), null); client.update(executionContext, createRevision(8), null); assertRevision(gotDir, 8); } public void testUpdateDoesNotPrintUnlabelledLines() throws Exception { RecordingScmFeedbackHandler handler = runRecordedUpdate(); for (String message: handler.getStatusMessages()) { System.out.println("message = " + message); } } public void testUpdateShowsExpectedStatusLabels() throws Exception { RecordingScmFeedbackHandler handler = runRecordedUpdate(); List<String> messages = handler.getStatusMessages(); messages = newArrayList(filter(messages, new Predicate<String>() { public boolean apply(String input) { return !input.startsWith("Updating from"); } })); assertEquals(1, messages.size()); String[] pieces = messages.get(0).split(" +"); assertEquals(2, pieces.length); assertEquals("U", pieces[0]); } private RecordingScmFeedbackHandler runRecordedUpdate() throws ScmException { client.checkout(executionContext, createRevision(1), null); RecordingScmFeedbackHandler handler = new RecordingScmFeedbackHandler(); client.update(executionContext, null, handler); return handler; } public void testUpdateBrokenWorkingCopy() throws Exception { client.setCleanOnUpdateFailure(true); client.checkout(executionContext, createRevision(1), null); File rootSvnDir = new File(gotDir, ".svn"); FileSystemUtils.rmdir(rootSvnDir); RecordingScmFeedbackHandler handler = new RecordingScmFeedbackHandler(); Revision revision = client.update(executionContext, null, handler); assertTrue(rootSvnDir.isDirectory()); assertEquals(Integer.toString(REVISION_TRUNK_LATEST), revision.getRevisionString()); assertRevision(gotDir, REVISION_TRUNK_LATEST); assertThat(handler.getStatusMessages(), hasItem(containsString("Attempting clean checkout"))); } public void testUpdateBrokenWorkingCopyNoRecovery() throws Exception { client.setCleanOnUpdateFailure(false); client.checkout(executionContext, createRevision(1), null); File rootSvnDir = new File(gotDir, ".svn"); FileSystemUtils.rmdir(rootSvnDir); RecordingScmFeedbackHandler handler = new RecordingScmFeedbackHandler(); try { client.update(executionContext, null, handler); fail("Expected update to fail"); } catch (ScmException e) { assertThat(e.getMessage(), containsString("not a working copy")); } } public void testCheckNonExistantPathHTTP() throws Exception { SubversionClient server = null; try { server = new SubversionClient("https://svn.apache.org/repos/asf", false, "anonymous", ""); assertFalse(server.pathExists(SVNURL.parseURIEncoded("https://svn.apache.org/repos/asf/nosuchpath/"))); } finally { IOUtils.close(server); } } // CIB-2322: Svn: Unexpected scm trigger when using filters. public void testChangesOutsideBasePathIgnored() throws ScmException, IOException, SVNException { // Drop into a subdirectory to isolate the two changes. // We use a file:// url so that the url path does not match the // repository path (to catch incorrect use of the url path to filter). client = createSubversionClient("file://" + tmpDir.getAbsolutePath() + "/repo/test/trunk/afolder"); List<Changelist> changelists = client.getChanges(context, createRevision(0), createRevision(1)); assertEquals(1, changelists.size()); Changelist changelist = changelists.get(0); assertEquals(8, changelist.getChanges().size()); // exclude the new changes client.setFilterPaths(Collections.<String>emptyList(), Arrays.asList("**/afolder/**")); changelists = client.getChanges(context, createRevision(0), createRevision(1)); assertEquals(0, changelists.size()); } private SubversionClient createSubversionClient(String path) throws ScmException { if (client != null) { IOUtils.close(client); } client = new SubversionClient(path, false, USER, PASSWORD); return client; } private void assertRevision(File dir, int revision) throws IOException { File expectedTestDir = new File(expectedDir, "test"); if (expectedTestDir.isDirectory()) { removeDirectory(expectedTestDir); } unzipInput(Integer.toString(revision), expectedDir); IOAssertions.assertDirectoriesEqual(new File(expectedTestDir, "trunk"), dir); } private List<ScmFile> getSortedListing(SubversionClient confirmServer) throws ScmException { List<ScmFile> files = confirmServer.browse(null, "", null); Collections.sort(files, new Comparator<ScmFile>() { public int compare(ScmFile o1, ScmFile o2) { return o1.getName().compareTo(o2.getName()); } }); return files; } private static Revision createRevision(long rev) { return new Revision(Long.toString(rev)); } }
UTF-8
Java
20,745
java
SubversionClientTest.java
Java
[ { "context": "/test/\";\r\n private static final String USER = \"jsankey\";\r\n private static final String PASSWORD = \"pa", "end": 1889, "score": 0.9996163249015808, "start": 1882, "tag": "USERNAME", "value": "jsankey" }, { "context": "ey\";\r\n private static final String PASSWORD = \"password\";\r\n\r\n private static final String TRUNK_PATH =", "end": 1945, "score": 0.9992840886116028, "start": 1937, "tag": "PASSWORD", "value": "password" }, { "context": "--------------------------------------\r\n// r8 | jsankey | 2006-06-20 18:26:41 +1000 (Tue, 20 Jun 2006) | ", "end": 2652, "score": 0.9929537773132324, "start": 2645, "tag": "USERNAME", "value": "jsankey" }, { "context": "--------------------------------------\r\n// r7 | jsankey | 2006-06-20 17:32:58 +1000 (Tue, 20 Jun 2006) | ", "end": 2878, "score": 0.9886727333068848, "start": 2871, "tag": "USERNAME", "value": "jsankey" }, { "context": "--------------------------------------\r\n// r6 | jsankey | 2006-06-20 17:31:51 +1000 (Tue, 20 Jun 2006) | ", "end": 3126, "score": 0.9899352192878723, "start": 3119, "tag": "USERNAME", "value": "jsankey" }, { "context": "--------------------------------------\r\n// r5 | jsankey | 2006-06-20 17:31:48 +1000 (Tue, 20 Jun 2006) | ", "end": 3384, "score": 0.9768661856651306, "start": 3377, "tag": "USERNAME", "value": "jsankey" }, { "context": "foreground\", \"--listen-port=3690\", \"--listen-host=127.0.0.1\", \"-dr\", \".\"}, null, repoDir);\r\n\r\n TestUti", "end": 5538, "score": 0.9997471570968628, "start": 5529, "tag": "IP_ADDRESS", "value": "127.0.0.1" } ]
null
[]
/* Copyright 2017 Zutubi Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.zutubi.pulse.core.scm.svn; import com.google.common.base.Predicate; import com.zutubi.pulse.core.PulseExecutionContext; import com.zutubi.pulse.core.scm.RecordingScmFeedbackHandler; import com.zutubi.pulse.core.scm.ScmContextImpl; import com.zutubi.pulse.core.scm.api.*; import com.zutubi.pulse.core.test.TestUtils; import com.zutubi.pulse.core.test.api.PulseTestCase; import com.zutubi.util.io.FileSystemUtils; import com.zutubi.util.io.IOUtils; import com.zutubi.util.junit.IOAssertions; import org.tmatesoft.svn.core.SVNCommitInfo; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.SVNURL; import org.tmatesoft.svn.core.wc.*; import java.io.File; import java.io.IOException; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.List; import static com.google.common.collect.Iterables.filter; import static com.google.common.collect.Lists.newArrayList; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.hasItem; public class SubversionClientTest extends PulseTestCase { private static final String REPO = "svn://localhost/test/"; private static final String USER = "jsankey"; private static final String PASSWORD = "<PASSWORD>"; private static final String TRUNK_PATH = REPO + "trunk"; private static final String BRANCH_PATH = REPO + "branches/new-branch"; private static final String TAG_PATH = REPO + "tags/test-tag"; private static final int REVISION_TRUNK_LATEST = 4; private SubversionClient client; private File tmpDir; private File gotDir; private File expectedDir; private Process serverProcess; private PulseExecutionContext executionContext; private ScmContext context; private SVNClientManager clientManager; // $ svn log -v svn://localhost/test // ------------------------------------------------------------------------ // r8 | jsankey | 2006-06-20 18:26:41 +1000 (Tue, 20 Jun 2006) | 1 line // Changed paths: // A /test/tags // // Make tags dir // ------------------------------------------------------------------------ // r7 | jsankey | 2006-06-20 17:32:58 +1000 (Tue, 20 Jun 2006) | 1 line // Changed paths: // M /test/branches/dev-it/afolder/f1 // // Edit a branch // ------------------------------------------------------------------------ // r6 | jsankey | 2006-06-20 17:31:51 +1000 (Tue, 20 Jun 2006) | 1 line // Changed paths: // A /test/branches/dev-it (from /test/trunk:5) // // Make a branch // ------------------------------------------------------------------------ // r5 | jsankey | 2006-06-20 17:31:48 +1000 (Tue, 20 Jun 2006) | 1 line // Changed paths: // A /test/branches // // Make a dir // ------------------------------------------------------------------------ // r4 | jsankey | 2006-06-20 17:30:28 +1000 (Tue, 20 Jun 2006) | 1 line // Changed paths: // D /test/trunk/bar // // Delete a file // ------------------------------------------------------------------------ // r3 | jsankey | 2006-06-20 17:30:17 +1000 (Tue, 20 Jun 2006) | 1 line // Changed paths: // A /test/trunk/bar // // Add a file // ------------------------------------------------------------------------ // r2 | jsankey | 2006-06-20 17:30:00 +1000 (Tue, 20 Jun 2006) | 1 line // Changed paths: // M /test/trunk/foo // // Edit a file // ------------------------------------------------------------------------ // r1 | jsankey | 2006-06-20 16:13:29 +1000 (Tue, 20 Jun 2006) | 1 line // Changed paths: // A /test // A /test/trunk // A /test/trunk/afolder // A /test/trunk/afolder/f1 // A /test/trunk/afolder/f2 // A /test/trunk/bfolder // A /test/trunk/bfolder/f1 // A /test/trunk/foo // // Importing test data // ------------------------------------------------------------------------ protected void setUp() throws Exception { super.setUp(); tmpDir = FileSystemUtils.createTempDir(getClass().getName(), ""); File repoDir = new File(tmpDir, "repo"); FileSystemUtils.createDirectory(repoDir); expectedDir = new File(repoDir, "expected"); FileSystemUtils.createDirectory(expectedDir); gotDir = new File(repoDir, "got"); FileSystemUtils.createDirectory(gotDir); executionContext = new PulseExecutionContext(); executionContext.setWorkingDir(gotDir); context = new ScmContextImpl(null, executionContext); unzipInput("data", repoDir); serverProcess = Runtime.getRuntime().exec(new String[]{"svnserve", "--foreground", "--listen-port=3690", "--listen-host=127.0.0.1", "-dr", "."}, null, repoDir); TestUtils.waitForServer(3690); clientManager = SVNClientManager.newInstance(null, SVNWCUtil.createDefaultAuthenticationManager(USER, PASSWORD)); createSubversionClient(TRUNK_PATH); } protected void tearDown() throws Exception { IOUtils.close(client); serverProcess.destroy(); serverProcess.waitFor(); clientManager.dispose(); removeDirectory(tmpDir); super.tearDown(); } public void testGetLatestRevision() throws ScmException { client = createSubversionClient("svn://localhost/"); assertEquals("8", client.getLatestRevision(context).getRevisionString()); } public void testGetLatestRevisionRestrictedToFiles() throws ScmException { assertEquals("4", client.getLatestRevision(context).getRevisionString()); } public void testGetLatestRevisionNewBranch() throws ScmException, SVNException { SVNCopyClient client = clientManager.getCopyClient(); SVNCopySource[] copySource = {new SVNCopySource(SVNRevision.UNDEFINED, SVNRevision.HEAD, SVNURL.parseURIDecoded(TRUNK_PATH))}; SVNCommitInfo info = client.doCopy(copySource, SVNURL.parseURIDecoded(BRANCH_PATH), false, true, true, "Create a branch", null); SubversionClient branchClient = new SubversionClient(BRANCH_PATH, false); assertEquals(Long.toString(info.getNewRevision()), branchClient.getLatestRevision(context).getRevisionString()); } public void testGetLatestRevisionBadRepository() { try { client = createSubversionClient("svn://localhost/no/such/repo"); client.getLatestRevision(context); fail(); } catch (ScmException e) { assertTrue(e.getMessage().contains("no repository found")); } } public void testList() throws ScmException { List<ScmFile> files = client.browse(null, "afolder", null); assertEquals(2, files.size()); assertEquals("f1", files.get(0).getName()); assertEquals("f2", files.get(1).getName()); } public void testListNonExistent() throws ScmException { try { client.browse(null, "nosuchfile", null); fail(); } catch (ScmException e) { assertTrue(e.getMessage().contains("not found")); } } public void testTag() throws ScmException, IOException { client.tag(null, createRevision(1), TAG_PATH, false); SubversionClient confirmServer = null; try { confirmServer = new SubversionClient(TAG_PATH, false, USER, PASSWORD); List<ScmFile> files = getSortedListing(confirmServer); assertEquals(3, files.size()); assertEquals("afolder", files.get(0).getName()); assertEquals("bfolder", files.get(1).getName()); assertEquals("foo", files.get(2).getName()); String foo = ScmUtils.retrieveContent(confirmServer, null, "foo", null); assertEquals("", foo); } finally { IOUtils.close(confirmServer); } } public void testMoveTag() throws ScmException, IOException { client.tag(null, createRevision(1), TAG_PATH, false); client.tag(null, createRevision(8), TAG_PATH, true); assertTaggedRev8(); } public void testMoveTagNonExistant() throws ScmException, IOException { client.tag(null, createRevision(8), TAG_PATH, true); assertTaggedRev8(); } private void assertTaggedRev8() throws ScmException, IOException { SubversionClient confirmServer = null; try { confirmServer = new SubversionClient(TAG_PATH, false, USER, PASSWORD); List<ScmFile> files = getSortedListing(confirmServer); assertEquals(3, files.size()); assertEquals("afolder", files.get(0).getName()); assertEquals("bfolder", files.get(1).getName()); assertEquals("foo", files.get(2).getName()); String foo = ScmUtils.retrieveContent(confirmServer, null, "foo", null); assertEquals("hello\n", foo); } finally { IOUtils.close(confirmServer); } } public void testUnmovableTag() throws ScmException { client.tag(null, createRevision(1), TAG_PATH, false); try { client.tag(null, createRevision(8), TAG_PATH, false); fail(); } catch (ScmException e) { assertEquals("Unable to apply tag: path '" + TAG_PATH + "' already exists in the repository", e.getMessage()); } } public void testChangesSince() throws ScmException { List<Changelist> changes = client.getChanges(context, createRevision(2), null); assertEquals(2, changes.size()); Changelist changelist = changes.get(0); assertEquals("3", changelist.getRevision().getRevisionString()); assertEquals(1, changelist.getChanges().size()); assertEquals("/test/trunk/bar", changelist.getChanges().get(0).getPath()); assertEquals(FileChange.Action.ADD, changelist.getChanges().get(0).getAction()); changelist = changes.get(1); assertEquals("4", changelist.getRevision().getRevisionString()); assertEquals(1, changelist.getChanges().size()); assertEquals("/test/trunk/bar", changelist.getChanges().get(0).getPath()); assertEquals(FileChange.Action.DELETE, changelist.getChanges().get(0).getAction()); } public void testChangesBetweenTwoRevisions() throws ScmException { List<Changelist> changes = client.getChanges(context, createRevision(2), createRevision(3)); assertEquals(1, changes.size()); Changelist changelist = changes.get(0); assertEquals("3", changelist.getRevision().getRevisionString()); assertEquals(1, changelist.getChanges().size()); assertEquals("/test/trunk/bar", changelist.getChanges().get(0).getPath()); assertEquals(FileChange.Action.ADD, changelist.getChanges().get(0).getAction()); } public void testChangesBetweenReversedRange() throws ScmException { List<Changelist> changes = client.getChanges(context, createRevision(3), createRevision(2)); assertEquals(1, changes.size()); Changelist changelist = changes.get(0); assertEquals("3", changelist.getRevision().getRevisionString()); assertEquals(1, changelist.getChanges().size()); assertEquals("/test/trunk/bar", changelist.getChanges().get(0).getPath()); assertEquals(FileChange.Action.ADD, changelist.getChanges().get(0).getAction()); } public void testRevisionsSince() throws ScmException { List<Revision> revisions = client.getRevisions(context, createRevision(2), null); assertEquals(2, revisions.size()); assertEquals("3", revisions.get(0).getRevisionString()); assertEquals("4", revisions.get(1).getRevisionString()); } public void testRevisionsSinceLatestInFiles() throws ScmException { List<Revision> revisions = client.getRevisions(context, createRevision(6), null); assertEquals(0, revisions.size()); } public void testRevisionsSincePastHead() throws ScmException { try { client.getRevisions(context, createRevision(9), null); } catch (ScmException e) { assertThat(e.getMessage(), containsString("No such revision 9")); } } public void testGetRevisionsInRange() throws ScmException { List<Revision> revisions = client.getRevisions(context, createRevision(2), createRevision(4)); assertEquals(2, revisions.size()); assertEquals("3", revisions.get(0).getRevisionString()); assertEquals("4", revisions.get(1).getRevisionString()); } public void testGetRevisionsInReverseRange() throws ScmException { List<Revision> revisions = client.getRevisions(context, createRevision(4), createRevision(2)); assertEquals(2, revisions.size()); assertEquals("4", revisions.get(0).getRevisionString()); assertEquals("3", revisions.get(1).getRevisionString()); } public void testCheckout() throws ScmException, IOException { client.checkout(executionContext, null, null); assertRevision(gotDir, 8); assertTrue(new File(gotDir, ".svn").isDirectory()); } public void testExport() throws ScmException, IOException { client.setUseExport(true); client.checkout(executionContext, null, null); assertRevision(gotDir, 8); assertFalse(new File(gotDir, ".svn").isDirectory()); } public void testUpdate() throws ScmException, IOException { client.checkout(executionContext, createRevision(1), null); assertRevision(gotDir, 1); client.update(executionContext, null, null); assertRevision(gotDir, 8); } public void testMultiUpdate() throws ScmException, IOException { client.checkout(executionContext, createRevision(1), null); client.update(executionContext, createRevision(4), null); client.update(executionContext, createRevision(8), null); assertRevision(gotDir, 8); } public void testUpdateDoesNotPrintUnlabelledLines() throws Exception { RecordingScmFeedbackHandler handler = runRecordedUpdate(); for (String message: handler.getStatusMessages()) { System.out.println("message = " + message); } } public void testUpdateShowsExpectedStatusLabels() throws Exception { RecordingScmFeedbackHandler handler = runRecordedUpdate(); List<String> messages = handler.getStatusMessages(); messages = newArrayList(filter(messages, new Predicate<String>() { public boolean apply(String input) { return !input.startsWith("Updating from"); } })); assertEquals(1, messages.size()); String[] pieces = messages.get(0).split(" +"); assertEquals(2, pieces.length); assertEquals("U", pieces[0]); } private RecordingScmFeedbackHandler runRecordedUpdate() throws ScmException { client.checkout(executionContext, createRevision(1), null); RecordingScmFeedbackHandler handler = new RecordingScmFeedbackHandler(); client.update(executionContext, null, handler); return handler; } public void testUpdateBrokenWorkingCopy() throws Exception { client.setCleanOnUpdateFailure(true); client.checkout(executionContext, createRevision(1), null); File rootSvnDir = new File(gotDir, ".svn"); FileSystemUtils.rmdir(rootSvnDir); RecordingScmFeedbackHandler handler = new RecordingScmFeedbackHandler(); Revision revision = client.update(executionContext, null, handler); assertTrue(rootSvnDir.isDirectory()); assertEquals(Integer.toString(REVISION_TRUNK_LATEST), revision.getRevisionString()); assertRevision(gotDir, REVISION_TRUNK_LATEST); assertThat(handler.getStatusMessages(), hasItem(containsString("Attempting clean checkout"))); } public void testUpdateBrokenWorkingCopyNoRecovery() throws Exception { client.setCleanOnUpdateFailure(false); client.checkout(executionContext, createRevision(1), null); File rootSvnDir = new File(gotDir, ".svn"); FileSystemUtils.rmdir(rootSvnDir); RecordingScmFeedbackHandler handler = new RecordingScmFeedbackHandler(); try { client.update(executionContext, null, handler); fail("Expected update to fail"); } catch (ScmException e) { assertThat(e.getMessage(), containsString("not a working copy")); } } public void testCheckNonExistantPathHTTP() throws Exception { SubversionClient server = null; try { server = new SubversionClient("https://svn.apache.org/repos/asf", false, "anonymous", ""); assertFalse(server.pathExists(SVNURL.parseURIEncoded("https://svn.apache.org/repos/asf/nosuchpath/"))); } finally { IOUtils.close(server); } } // CIB-2322: Svn: Unexpected scm trigger when using filters. public void testChangesOutsideBasePathIgnored() throws ScmException, IOException, SVNException { // Drop into a subdirectory to isolate the two changes. // We use a file:// url so that the url path does not match the // repository path (to catch incorrect use of the url path to filter). client = createSubversionClient("file://" + tmpDir.getAbsolutePath() + "/repo/test/trunk/afolder"); List<Changelist> changelists = client.getChanges(context, createRevision(0), createRevision(1)); assertEquals(1, changelists.size()); Changelist changelist = changelists.get(0); assertEquals(8, changelist.getChanges().size()); // exclude the new changes client.setFilterPaths(Collections.<String>emptyList(), Arrays.asList("**/afolder/**")); changelists = client.getChanges(context, createRevision(0), createRevision(1)); assertEquals(0, changelists.size()); } private SubversionClient createSubversionClient(String path) throws ScmException { if (client != null) { IOUtils.close(client); } client = new SubversionClient(path, false, USER, PASSWORD); return client; } private void assertRevision(File dir, int revision) throws IOException { File expectedTestDir = new File(expectedDir, "test"); if (expectedTestDir.isDirectory()) { removeDirectory(expectedTestDir); } unzipInput(Integer.toString(revision), expectedDir); IOAssertions.assertDirectoriesEqual(new File(expectedTestDir, "trunk"), dir); } private List<ScmFile> getSortedListing(SubversionClient confirmServer) throws ScmException { List<ScmFile> files = confirmServer.browse(null, "", null); Collections.sort(files, new Comparator<ScmFile>() { public int compare(ScmFile o1, ScmFile o2) { return o1.getName().compareTo(o2.getName()); } }); return files; } private static Revision createRevision(long rev) { return new Revision(Long.toString(rev)); } }
20,747
0.612003
0.595421
548
35.883213
30.820843
168
false
false
0
0
0
0
0
0
0.839416
false
false
7
097a946120b7ab23f20be60b0e2a53e972666f6d
14,680,198,251,909
0e0577ad494fc5b684d5c94c84365456628f0ba3
/src/Services/EventService.java
75a619573a56856344f1530539f926a4bc874254
[]
no_license
AndrewHillen/FamilyServer
https://github.com/AndrewHillen/FamilyServer
203da7648ede9a13cca2fa9fb5dd5ea91acc85f0
1b4a95628213a08e2305e2849852cddf7b540722
refs/heads/master
2023-02-11T10:38:01.822000
2020-12-05T02:13:23
2020-12-05T02:13:23
281,573,472
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package Services; import DataAccess.*; import Model.AuthToken; import ReqRes.EventRequest; import ReqRes.EventResult; import Model.Event; import ReqRes.PersonResult; import java.sql.Connection; /** * The EventService */ public class EventService { private EventResult result; private Database db; private Connection conn; private EventAccess eventDao; private AuthTokenAccess authDao; /** * Default constructor */ public EventService() throws DBException { db = new Database(); conn = db.getConnection(); eventDao = new EventAccess(conn); authDao = new AuthTokenAccess(conn); result = new EventResult(); } /** * Verifies the token and returns the result using the DAO objects * @param request * @return An EventResult */ public EventResult searchEvents(EventRequest request) throws DBException { AuthToken token = authDao.findAuthTokenByToken(request.getToken()); Event event = eventDao.findEventByID(request.getEventID()); if(token == null || event == null) { result.setSuccess(false); result.setMessage("Error: Invalid AuthToken or ID"); return result; } if(!token.getUserName().equals(event.getUserName())) { result.setSuccess(false); result.setMessage("Error: Event does not belong to this user"); return result; } result.setAssociatedUsername(event.getUserName()); result.setEventID(event.getId()); result.setPersonID(event.getPersonID()); result.setLatitude(event.getLatitude()); result.setLongitude(event.getLongitude()); result.setCountry(event.getCountry()); result.setCity(event.getCity()); result.setEventType(event.getEventType()); result.setYear(event.getYear()); result.setSuccess(true); return result; } //For Testing purposes public Connection getConn() { return conn; } public void commit(boolean commit) throws DBException { db.closeConnection(commit); } }
UTF-8
Java
2,177
java
EventService.java
Java
[]
null
[]
package Services; import DataAccess.*; import Model.AuthToken; import ReqRes.EventRequest; import ReqRes.EventResult; import Model.Event; import ReqRes.PersonResult; import java.sql.Connection; /** * The EventService */ public class EventService { private EventResult result; private Database db; private Connection conn; private EventAccess eventDao; private AuthTokenAccess authDao; /** * Default constructor */ public EventService() throws DBException { db = new Database(); conn = db.getConnection(); eventDao = new EventAccess(conn); authDao = new AuthTokenAccess(conn); result = new EventResult(); } /** * Verifies the token and returns the result using the DAO objects * @param request * @return An EventResult */ public EventResult searchEvents(EventRequest request) throws DBException { AuthToken token = authDao.findAuthTokenByToken(request.getToken()); Event event = eventDao.findEventByID(request.getEventID()); if(token == null || event == null) { result.setSuccess(false); result.setMessage("Error: Invalid AuthToken or ID"); return result; } if(!token.getUserName().equals(event.getUserName())) { result.setSuccess(false); result.setMessage("Error: Event does not belong to this user"); return result; } result.setAssociatedUsername(event.getUserName()); result.setEventID(event.getId()); result.setPersonID(event.getPersonID()); result.setLatitude(event.getLatitude()); result.setLongitude(event.getLongitude()); result.setCountry(event.getCountry()); result.setCity(event.getCity()); result.setEventType(event.getEventType()); result.setYear(event.getYear()); result.setSuccess(true); return result; } //For Testing purposes public Connection getConn() { return conn; } public void commit(boolean commit) throws DBException { db.closeConnection(commit); } }
2,177
0.635278
0.635278
82
25.54878
20.946594
76
false
false
0
0
0
0
0
0
0.5
false
false
7
6ed3b266b30ba46b65b13d2f306008892e8af148
29,454,885,733,351
393ff8313ee0a43a7119b21ce1d50844d8c4e17b
/src/interfaces/IngresoOficinas.java
b320ac375d36d3a79b1f29286f7a8ab1a799e60d
[]
no_license
BrianPaul05/FinalDesarrollo
https://github.com/BrianPaul05/FinalDesarrollo
e7c5f34f6d90f022b4e8566bb19ca8692ebc11bd
9486948d84c0b813daac4c18f7824d325484a925
refs/heads/master
2020-04-13T13:45:43.425000
2019-01-14T14:13:37
2019-01-14T14:13:37
163,241,431
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package interfaces; import Conexion.Conexion; import com.placeholder.PlaceHolder; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JInternalFrame; import javax.swing.JOptionPane; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import javax.swing.table.DefaultTableModel; /** * * @author DELL GAMER */ public class IngresoOficinas extends javax.swing.JInternalFrame { DefaultTableModel model; String codigoOficinaTabla; /** * Creates new form IngresoClientes */ public IngresoOficinas() { initComponents(); // setLocationRelativeTo(this); PlaceHolder holder = new PlaceHolder(txtTelefono, "Teléfono con el codigo de la ciudad"); CargarTablaOficinas(""); Tabla_Oficina.getTableHeader().setReorderingAllowed(false); Tabla_Oficina.getTableHeader().setResizingAllowed(false); cargarModificarTabla(); desactivarTextos(); desactivarBotones(); setFrameIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagenes/oficinas.png"))); this.setTitle("REGISTRO OFICINAS"); } private void guardarOficina() { try { Conexion cc = new Conexion(); Connection cn = cc.conexion(); if (txtNombreOficina.getText().isEmpty()) { JOptionPane.showMessageDialog(null, "Ingrese el nombre de la oficina"); txtNombreOficina.requestFocus(); } else if (txtUbicacion.getText().isEmpty()) { JOptionPane.showMessageDialog(null, "Ingrese la ubicación de la oficina"); txtUbicacion.requestFocus(); } else if (txtTelefono.getText().isEmpty()) { JOptionPane.showMessageDialog(null, "Ingrese el telefono de la oficina"); txtTelefono.requestFocus(); } else if (txtTelefono.getText().length() < 9 || txtTelefono.getText().length() > 10) { JOptionPane.showMessageDialog(null, "El número de cifras del número de teléfono es incorrecto"); txtTelefono.requestFocus(); } else if (txtDireccion.getText().isEmpty()) { JOptionPane.showMessageDialog(null, "Ingrese la dirección de la oficina"); txtDireccion.requestFocus(); } else { String sql = "INSERT INTO OFICINAS (NOM_OFI, UBICACION, TELEFONO, ESTADO, DIRECCION) VALUES(?,?,?,?,?)"; PreparedStatement psd = cn.prepareStatement(sql); psd.setString(1, txtNombreOficina.getText()); psd.setString(2, txtUbicacion.getText()); psd.setString(3, txtTelefono.getText()); psd.setString(4, "S"); psd.setString(5, txtDireccion.getText()); int n = psd.executeUpdate(); if (n > 0) { JOptionPane.showMessageDialog(null, "OFICINA GUARDADA CORRECTAMENTE"); desactivarBotones(); desactivarTextos(); limpiarTextos(); CargarTablaOficinas(""); } } } catch (SQLException ex) { Logger.getLogger(IngresoOficinas.class.getName()).log(Level.SEVERE, null, ex); } } private void limpiarTextos() { txtNombreOficina.setText(null); txtUbicacion.setText(null); txtTelefono.setText(null); txtDireccion.setText(null); } private void activarTextos() { txtNombreOficina.setEnabled(true); txtUbicacion.setEnabled(true); txtTelefono.setEnabled(true); txtDireccion.setEnabled(true); } private void desactivarTextos() { txtNombreOficina.setEnabled(false); txtUbicacion.setEnabled(false); txtTelefono.setEnabled(false); txtDireccion.setEnabled(false); } private void activarBotonesNuevo() { jButton_Nuevo.setEnabled(false); jButton_Guardar.setEnabled(true); jButton_Actualizar.setEnabled(false); jButton_Cancelar.setEnabled(true); jButton_Eliminar.setEnabled(false); jButton_Salir.setEnabled(false); } private void desactivarBotones() { jButton_Nuevo.setEnabled(true); jButton_Guardar.setEnabled(false); jButton_Actualizar.setEnabled(false); jButton_Cancelar.setEnabled(false); jButton_Eliminar.setEnabled(false); jButton_Salir.setEnabled(true); } private void botonesActualizar() { jButton_Nuevo.setEnabled(false); jButton_Guardar.setEnabled(false); jButton_Actualizar.setEnabled(true); jButton_Cancelar.setEnabled(true); jButton_Eliminar.setEnabled(true); jButton_Salir.setEnabled(true); } private void CargarTablaOficinas(String dato) { try { String[] titulos = {"CODIGO", "NOMBRE", "UBICACIÓN", "TELÉFONO", "DIRECCIÓN"}; String[] registros = new String[5]; Conexion cc = new Conexion(); Connection cn = cc.conexion(); String sql = ""; sql = "SELECT COD_OFI, " + "NOM_OFI, " + "UBICACION, " + "TELEFONO, " + "DIRECCION " + "FROM OFICINAS " + "WHERE UBICACION LIKE'%" + dato + "%' " + "AND ESTADO = 'S'"; model = new DefaultTableModel(null, titulos) { @Override public boolean isCellEditable(int filas, int columnas) { if (columnas < 0) { return true; } else { return false; } } }; Statement psd = cn.createStatement(); ResultSet rs = psd.executeQuery(sql); while (rs.next()) { registros[0] = rs.getString("COD_OFI"); registros[1] = rs.getString("NOM_OFI"); registros[2] = rs.getString("UBICACION"); registros[3] = rs.getString("TELEFONO"); registros[4] = rs.getString("DIRECCION"); model.addRow(registros); } Tabla_Oficina.setModel(model); } catch (SQLException ex) { JOptionPane.showMessageDialog(this, ex); } } private void actualizarOficina() { if (txtNombreOficina.getText().isEmpty()) { JOptionPane.showMessageDialog(this, "Ingrese el nombre de la oficina"); txtNombreOficina.requestFocus(); } else if (txtUbicacion.getText().isEmpty()) { JOptionPane.showMessageDialog(this, "Ingrese la ubicación"); txtUbicacion.requestFocus(); } else if (txtTelefono.getText().isEmpty()) { JOptionPane.showMessageDialog(this, "Ingrese el teléfono"); txtTelefono.requestFocus(); } else if (txtTelefono.getText().length() < 9 || txtTelefono.getText().length() > 10) { JOptionPane.showMessageDialog(null, "El número de cifras del número de teléfono es incorrecto"); txtTelefono.requestFocus(); } else if (txtDireccion.getText().isEmpty()) { JOptionPane.showMessageDialog(null, "Ingrese una dirección"); txtDireccion.requestFocus(); } else { try { Conexion cc = new Conexion(); Connection cn = cc.conexion(); String sql = ""; sql = "UPDATE OFICINAS set NOM_OFI ='" + txtNombreOficina.getText() + "' " + ",UBICACION ='" + txtUbicacion.getText() + "' " + ",TELEFONO ='" + txtTelefono.getText() + "' " + ",DIRECCION ='" + txtDireccion.getText() + "' " + " WHERE COD_OFI ='" + codigoOficinaTabla + "'"; PreparedStatement psd = cn.prepareStatement(sql); int n = psd.executeUpdate(); if (n > 0) { JOptionPane.showMessageDialog(this, "SE ACTUALIZO LA OFICINA."); desactivarBotones(); desactivarTextos(); limpiarTextos(); CargarTablaOficinas(""); } } catch (SQLException ex) { JOptionPane.showMessageDialog(null, ex); } } } private boolean condEliOfi1(String codOficina) { /* Metodo que permite verificar si la oficina tiene o no tiene filas hijas , en la tabla PERSONAL_OFICINA sino NO tiene filas hijas elimino el registro DE LA TABLA OFICINA, caso contrario NO. */ int pos = 0; try { String sql = ""; Conexion cc = new Conexion(); Connection cn = cc.conexion(); sql = "SELECT * " + "FROM PERSONAL_OFICINA " + "WHERE COD_OFI_PER = '" + codOficina + "'"; Statement psd = cn.createStatement(); ResultSet rs = psd.executeQuery(sql); while (rs.next()) { pos = pos + 1; } } catch (SQLException ex) { JOptionPane.showMessageDialog(null, ex); } if (pos > 0) { return false; } return true; } private boolean condEliOfi2(String codOficina) { /* Metodo que permite verificar si la oficina tiene o no tiene filas hijas , en la tabla RUTAS sino NO tiene filas hijas elimino el registro DE LA TABLA OFICINA, caso contrario NO. */ int pos = 0; try { String sql = ""; Conexion cc = new Conexion(); Connection cn = cc.conexion(); sql = "SELECT * " + "FROM RUTAS " + "WHERE COD_OFI_ORI = '" + codOficina + "' " + "OR COD_OFI_DES = '" + codOficina + "'"; Statement psd = cn.createStatement(); ResultSet rs = psd.executeQuery(sql); while (rs.next()) { pos = pos + 1; } } catch (SQLException ex) { JOptionPane.showMessageDialog(null, ex); } if (pos > 0) { return false; } return true; } private void cargarModificarTabla() { Tabla_Oficina.getSelectionModel().addListSelectionListener(new ListSelectionListener() { @Override //Override cuando se sobrecarga un metodo o sobrecarga de valores ---- se lo pone con el obejtivo de liberar memoria public void valueChanged(ListSelectionEvent e) { if (Tabla_Oficina.getSelectedRow() != -1) { activarTextos(); botonesActualizar(); int fila = Tabla_Oficina.getSelectedRow(); codigoOficinaTabla = Tabla_Oficina.getValueAt(fila, 0).toString().trim(); //trim para los espacios en blanco txtNombreOficina.setText(Tabla_Oficina.getValueAt(fila, 1).toString().trim()); txtUbicacion.setText(Tabla_Oficina.getValueAt(fila, 2).toString().trim()); txtTelefono.setText(Tabla_Oficina.getValueAt(fila, 3).toString().trim()); txtDireccion.setText(Tabla_Oficina.getValueAt(fila, 4).toString().trim()); } } }); } private void eliminarOficina() { if (JOptionPane.showConfirmDialog(new JInternalFrame(), "¿ ESTA SEGURO DE BORRAR EL REGISTRO DE OFICINA ?", "Ventana Borrar", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) { if (condEliOfi1(codigoOficinaTabla) && condEliOfi2(codigoOficinaTabla)) { try { Conexion cc = new Conexion(); Connection cn = cc.conexion(); String sql = ""; sql = "update OFICINAS set ESTADO = 'N' where COD_OFI='" + codigoOficinaTabla + "'"; PreparedStatement psd = cn.prepareStatement(sql); int n = psd.executeUpdate(); if (n > 0) { JOptionPane.showMessageDialog(this, "REGISTRO ELIMINADO . . . . !"); CargarTablaOficinas(""); limpiarTextos(); desactivarTextos(); desactivarBotones(); } } catch (SQLException ex) { JOptionPane.showMessageDialog(this, ex); } } else { JOptionPane.showMessageDialog(null, "NO SE PUEDE ELIMINAR EL REGISTRO . . . ! " + "PRIMERO DEBE ELIMINAR LAS FILAS DEPENDIENTES DE LA TABLA OFICINA !"); } } } public void soloNumeros(java.awt.event.KeyEvent evt) { char c; c = evt.getKeyChar(); if ((c >= 32 && c <= 47) || (c >= 58 && c <= 255)) { evt.consume(); JOptionPane.showMessageDialog(this, "ERROR Ingrese solo Números"); } } public void soloLetras(java.awt.event.KeyEvent evt) { char c = evt.getKeyChar(); if ((c >= 33 && c <= 64) || (c >= 91 && c <= 96) || (c >= 123 && c <= 255)) { evt.consume(); getToolkit().beep(); JOptionPane.showMessageDialog(this, "Ingrese solo Letras", "Error", JOptionPane.ERROR_MESSAGE); } } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel4 = new javax.swing.JPanel(); jLabel7 = new javax.swing.JLabel(); jPanel3 = new javax.swing.JPanel(); jScrollPane1 = new javax.swing.JScrollPane(); Tabla_Oficina = new javax.swing.JTable(); jLabel5 = new javax.swing.JLabel(); txtBuscar = new javax.swing.JTextField(); jPanel8 = new javax.swing.JPanel(); jPanel1 = new javax.swing.JPanel(); jLabel2 = new javax.swing.JLabel(); txtNombreOficina = new javax.swing.JTextField(); jLabel4 = new javax.swing.JLabel(); txtTelefono = new javax.swing.JTextField(); jLabel3 = new javax.swing.JLabel(); txtUbicacion = new javax.swing.JTextField(); jLabel1 = new javax.swing.JLabel(); txtDireccion = new javax.swing.JTextField(); jButton_Nuevo = new javax.swing.JButton(); jButton_Guardar = new javax.swing.JButton(); jButton_Actualizar = new javax.swing.JButton(); jButton_Eliminar = new javax.swing.JButton(); jButton_Salir = new javax.swing.JButton(); jButton_Cancelar = new javax.swing.JButton(); setBackground(new java.awt.Color(255, 255, 255)); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setIconifiable(true); jPanel4.setBackground(new java.awt.Color(255, 255, 255)); jLabel7.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagenes/oficina.png"))); // NOI18N jPanel3.setBackground(new java.awt.Color(255, 255, 255)); jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder("OFICINAS EXISTENTES")); Tabla_Oficina = new javax.swing.JTable(){ public boolean isCellEditable(int f, int c){ return ((c!=0) && (c!=1) && (c!=2)&&(c!=3) && (c!=4)); } }; Tabla_Oficina.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {}, {}, {}, {} }, new String [] { } )); jScrollPane1.setViewportView(Tabla_Oficina); jLabel5.setFont(new java.awt.Font("Times New Roman", 1, 14)); // NOI18N jLabel5.setText("Buscar por ubicación"); txtBuscar.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { txtBuscarKeyReleased(evt); } public void keyTyped(java.awt.event.KeyEvent evt) { txtBuscarKeyTyped(evt); } }); javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3); jPanel3.setLayout(jPanel3Layout); jPanel3Layout.setHorizontalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 750, Short.MAX_VALUE) .addGroup(jPanel3Layout.createSequentialGroup() .addComponent(jLabel5) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(txtBuscar, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, Short.MAX_VALUE))) .addContainerGap()) ); jPanel3Layout.setVerticalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel5) .addComponent(txtBuscar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 152, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jPanel8.setBackground(new java.awt.Color(0, 153, 255)); javax.swing.GroupLayout jPanel8Layout = new javax.swing.GroupLayout(jPanel8); jPanel8.setLayout(jPanel8Layout); jPanel8Layout.setHorizontalGroup( jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 0, Short.MAX_VALUE) ); jPanel8Layout.setVerticalGroup( jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 29, Short.MAX_VALUE) ); jPanel1.setBackground(new java.awt.Color(255, 255, 255)); jPanel1.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jLabel2.setFont(new java.awt.Font("Times New Roman", 1, 18)); // NOI18N jLabel2.setText("Nombre de la oficina :"); txtNombreOficina.addKeyListener(new java.awt.event.KeyAdapter() { public void keyTyped(java.awt.event.KeyEvent evt) { txtNombreOficinaKeyTyped(evt); } }); jLabel4.setFont(new java.awt.Font("Times New Roman", 1, 18)); // NOI18N jLabel4.setText("Teléfono :"); txtTelefono.addFocusListener(new java.awt.event.FocusAdapter() { public void focusLost(java.awt.event.FocusEvent evt) { txtTelefonoFocusLost(evt); } }); txtTelefono.addKeyListener(new java.awt.event.KeyAdapter() { public void keyTyped(java.awt.event.KeyEvent evt) { txtTelefonoKeyTyped(evt); } }); jLabel3.setFont(new java.awt.Font("Times New Roman", 1, 18)); // NOI18N jLabel3.setText("Ubicación :"); txtUbicacion.addKeyListener(new java.awt.event.KeyAdapter() { public void keyTyped(java.awt.event.KeyEvent evt) { txtUbicacionKeyTyped(evt); } }); jLabel1.setFont(new java.awt.Font("Times New Roman", 1, 18)); // NOI18N jLabel1.setText("Dirección :"); txtDireccion.addKeyListener(new java.awt.event.KeyAdapter() { public void keyTyped(java.awt.event.KeyEvent evt) { txtDireccionKeyTyped(evt); } }); jButton_Nuevo.setFont(new java.awt.Font("Palatino Linotype", 0, 14)); // NOI18N jButton_Nuevo.setText("Nuevo"); jButton_Nuevo.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton_NuevoActionPerformed(evt); } }); jButton_Guardar.setFont(new java.awt.Font("Palatino Linotype", 0, 14)); // NOI18N jButton_Guardar.setText("Guardar"); jButton_Guardar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton_GuardarActionPerformed(evt); } }); jButton_Actualizar.setFont(new java.awt.Font("Palatino Linotype", 0, 14)); // NOI18N jButton_Actualizar.setText("Actualizar"); jButton_Actualizar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton_ActualizarActionPerformed(evt); } }); jButton_Eliminar.setFont(new java.awt.Font("Palatino Linotype", 0, 14)); // NOI18N jButton_Eliminar.setText("Eliminar"); jButton_Eliminar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton_EliminarActionPerformed(evt); } }); jButton_Salir.setFont(new java.awt.Font("Palatino Linotype", 0, 14)); // NOI18N jButton_Salir.setText("Salir"); jButton_Salir.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton_SalirActionPerformed(evt); } }); jButton_Cancelar.setFont(new java.awt.Font("Palatino Linotype", 0, 14)); // NOI18N jButton_Cancelar.setText("Cancelar"); jButton_Cancelar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton_CancelarActionPerformed(evt); } }); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabel2) .addComponent(jLabel3)) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(txtUbicacion) .addComponent(txtNombreOficina, javax.swing.GroupLayout.PREFERRED_SIZE, 214, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(29, 29, 29) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabel4) .addComponent(jLabel1)) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(txtTelefono) .addComponent(txtDireccion, javax.swing.GroupLayout.PREFERRED_SIZE, 214, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jButton_Nuevo, javax.swing.GroupLayout.PREFERRED_SIZE, 99, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jButton_Guardar, javax.swing.GroupLayout.PREFERRED_SIZE, 99, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(28, 28, 28) .addComponent(jButton_Actualizar) .addGap(28, 28, 28) .addComponent(jButton_Cancelar, javax.swing.GroupLayout.PREFERRED_SIZE, 99, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(32, 32, 32) .addComponent(jButton_Eliminar, javax.swing.GroupLayout.PREFERRED_SIZE, 99, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(31, 31, 31) .addComponent(jButton_Salir, javax.swing.GroupLayout.PREFERRED_SIZE, 99, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap(16, Short.MAX_VALUE)) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(35, 35, 35) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel2) .addComponent(txtNombreOficina, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel4) .addComponent(txtTelefono, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(36, 36, 36) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel3) .addComponent(txtUbicacion, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel1) .addComponent(txtDireccion, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 30, Short.MAX_VALUE) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jButton_Nuevo) .addComponent(jButton_Guardar) .addComponent(jButton_Actualizar) .addComponent(jButton_Eliminar) .addComponent(jButton_Salir) .addComponent(jButton_Cancelar)) .addContainerGap()) ); txtTelefono.getAccessibleContext().setAccessibleName(""); txtTelefono.getAccessibleContext().setAccessibleDescription(""); javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4); jPanel4.setLayout(jPanel4Layout); jPanel4Layout.setHorizontalGroup( jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel8, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(jPanel4Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel4Layout.createSequentialGroup() .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, Short.MAX_VALUE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel4Layout.createSequentialGroup() .addGap(0, 0, Short.MAX_VALUE) .addComponent(jLabel7) .addGap(273, 273, 273)) .addGroup(jPanel4Layout.createSequentialGroup() .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))) ); jPanel4Layout.setVerticalGroup( jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel4Layout.createSequentialGroup() .addComponent(jPanel8, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(13, 13, 13) .addComponent(jLabel7) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(13, 13, 13)) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); pack(); }// </editor-fold>//GEN-END:initComponents private void jButton_GuardarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_GuardarActionPerformed guardarOficina(); }//GEN-LAST:event_jButton_GuardarActionPerformed private void txtNombreOficinaKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtNombreOficinaKeyTyped char c = evt.getKeyChar(); if (Character.isLowerCase(c)) { String cad = ("" + c).toUpperCase(); c = cad.charAt(0); evt.setKeyChar(c); } soloLetras(evt); }//GEN-LAST:event_txtNombreOficinaKeyTyped private void txtUbicacionKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtUbicacionKeyTyped char c = evt.getKeyChar(); if (Character.isLowerCase(c)) { String cad = ("" + c).toUpperCase(); c = cad.charAt(0); evt.setKeyChar(c); } soloLetras(evt); }//GEN-LAST:event_txtUbicacionKeyTyped private void txtTelefonoKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtTelefonoKeyTyped char validar = evt.getKeyChar(); if(txtTelefono.getText().length()>=10){ JOptionPane.showMessageDialog(this,"Teléfono Incorrecto"); evt.consume(); } else if (Character.isLetter(validar)) { getToolkit().beep(); evt.consume(); JOptionPane.showMessageDialog(rootPane, "SOLO NÚMEROS POR FAVOR", "Advertencia", JOptionPane.ERROR_MESSAGE); } soloNumeros(evt); }//GEN-LAST:event_txtTelefonoKeyTyped private void txtDireccionKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtDireccionKeyTyped char c = evt.getKeyChar(); if (Character.isLowerCase(c)) { String cad = ("" + c).toUpperCase(); c = cad.charAt(0); evt.setKeyChar(c); } soloLetras(evt); }//GEN-LAST:event_txtDireccionKeyTyped private void txtBuscarKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtBuscarKeyReleased CargarTablaOficinas(txtBuscar.getText()); }//GEN-LAST:event_txtBuscarKeyReleased private void txtBuscarKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtBuscarKeyTyped char c = evt.getKeyChar(); if (Character.isLowerCase(c)) { String cad = ("" + c).toUpperCase(); c = cad.charAt(0); evt.setKeyChar(c); } soloLetras(evt); }//GEN-LAST:event_txtBuscarKeyTyped private void jButton_ActualizarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_ActualizarActionPerformed actualizarOficina(); }//GEN-LAST:event_jButton_ActualizarActionPerformed private void jButton_EliminarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_EliminarActionPerformed eliminarOficina(); }//GEN-LAST:event_jButton_EliminarActionPerformed private void jButton_NuevoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_NuevoActionPerformed activarBotonesNuevo(); activarTextos(); limpiarTextos(); }//GEN-LAST:event_jButton_NuevoActionPerformed private void jButton_CancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_CancelarActionPerformed limpiarTextos(); desactivarTextos(); desactivarBotones(); Tabla_Oficina.clearSelection(); }//GEN-LAST:event_jButton_CancelarActionPerformed private void txtTelefonoFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtTelefonoFocusLost }//GEN-LAST:event_txtTelefonoFocusLost private void jButton_SalirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_SalirActionPerformed this.dispose(); }//GEN-LAST:event_jButton_SalirActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(IngresoOficinas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(IngresoOficinas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(IngresoOficinas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(IngresoOficinas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new IngresoOficinas().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JTable Tabla_Oficina; private javax.swing.JButton jButton_Actualizar; private javax.swing.JButton jButton_Cancelar; private javax.swing.JButton jButton_Eliminar; private javax.swing.JButton jButton_Guardar; private javax.swing.JButton jButton_Nuevo; private javax.swing.JButton jButton_Salir; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel7; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JPanel jPanel3; private javax.swing.JPanel jPanel4; private javax.swing.JPanel jPanel7; private javax.swing.JPanel jPanel8; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JTextField txtBuscar; private javax.swing.JTextField txtDireccion; private javax.swing.JTextField txtNombreOficina; private javax.swing.JTextField txtTelefono; private javax.swing.JTextField txtUbicacion; // End of variables declaration//GEN-END:variables }
UTF-8
Java
38,452
java
IngresoOficinas.java
Java
[ { "context": ".swing.table.DefaultTableModel;\n\n/**\n *\n * @author DELL GAMER\n */\npublic class IngresoOficinas extends javax.sw", "end": 713, "score": 0.9997726678848267, "start": 703, "tag": "NAME", "value": "DELL GAMER" } ]
null
[]
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package interfaces; import Conexion.Conexion; import com.placeholder.PlaceHolder; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JInternalFrame; import javax.swing.JOptionPane; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import javax.swing.table.DefaultTableModel; /** * * @author <NAME> */ public class IngresoOficinas extends javax.swing.JInternalFrame { DefaultTableModel model; String codigoOficinaTabla; /** * Creates new form IngresoClientes */ public IngresoOficinas() { initComponents(); // setLocationRelativeTo(this); PlaceHolder holder = new PlaceHolder(txtTelefono, "Teléfono con el codigo de la ciudad"); CargarTablaOficinas(""); Tabla_Oficina.getTableHeader().setReorderingAllowed(false); Tabla_Oficina.getTableHeader().setResizingAllowed(false); cargarModificarTabla(); desactivarTextos(); desactivarBotones(); setFrameIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagenes/oficinas.png"))); this.setTitle("REGISTRO OFICINAS"); } private void guardarOficina() { try { Conexion cc = new Conexion(); Connection cn = cc.conexion(); if (txtNombreOficina.getText().isEmpty()) { JOptionPane.showMessageDialog(null, "Ingrese el nombre de la oficina"); txtNombreOficina.requestFocus(); } else if (txtUbicacion.getText().isEmpty()) { JOptionPane.showMessageDialog(null, "Ingrese la ubicación de la oficina"); txtUbicacion.requestFocus(); } else if (txtTelefono.getText().isEmpty()) { JOptionPane.showMessageDialog(null, "Ingrese el telefono de la oficina"); txtTelefono.requestFocus(); } else if (txtTelefono.getText().length() < 9 || txtTelefono.getText().length() > 10) { JOptionPane.showMessageDialog(null, "El número de cifras del número de teléfono es incorrecto"); txtTelefono.requestFocus(); } else if (txtDireccion.getText().isEmpty()) { JOptionPane.showMessageDialog(null, "Ingrese la dirección de la oficina"); txtDireccion.requestFocus(); } else { String sql = "INSERT INTO OFICINAS (NOM_OFI, UBICACION, TELEFONO, ESTADO, DIRECCION) VALUES(?,?,?,?,?)"; PreparedStatement psd = cn.prepareStatement(sql); psd.setString(1, txtNombreOficina.getText()); psd.setString(2, txtUbicacion.getText()); psd.setString(3, txtTelefono.getText()); psd.setString(4, "S"); psd.setString(5, txtDireccion.getText()); int n = psd.executeUpdate(); if (n > 0) { JOptionPane.showMessageDialog(null, "OFICINA GUARDADA CORRECTAMENTE"); desactivarBotones(); desactivarTextos(); limpiarTextos(); CargarTablaOficinas(""); } } } catch (SQLException ex) { Logger.getLogger(IngresoOficinas.class.getName()).log(Level.SEVERE, null, ex); } } private void limpiarTextos() { txtNombreOficina.setText(null); txtUbicacion.setText(null); txtTelefono.setText(null); txtDireccion.setText(null); } private void activarTextos() { txtNombreOficina.setEnabled(true); txtUbicacion.setEnabled(true); txtTelefono.setEnabled(true); txtDireccion.setEnabled(true); } private void desactivarTextos() { txtNombreOficina.setEnabled(false); txtUbicacion.setEnabled(false); txtTelefono.setEnabled(false); txtDireccion.setEnabled(false); } private void activarBotonesNuevo() { jButton_Nuevo.setEnabled(false); jButton_Guardar.setEnabled(true); jButton_Actualizar.setEnabled(false); jButton_Cancelar.setEnabled(true); jButton_Eliminar.setEnabled(false); jButton_Salir.setEnabled(false); } private void desactivarBotones() { jButton_Nuevo.setEnabled(true); jButton_Guardar.setEnabled(false); jButton_Actualizar.setEnabled(false); jButton_Cancelar.setEnabled(false); jButton_Eliminar.setEnabled(false); jButton_Salir.setEnabled(true); } private void botonesActualizar() { jButton_Nuevo.setEnabled(false); jButton_Guardar.setEnabled(false); jButton_Actualizar.setEnabled(true); jButton_Cancelar.setEnabled(true); jButton_Eliminar.setEnabled(true); jButton_Salir.setEnabled(true); } private void CargarTablaOficinas(String dato) { try { String[] titulos = {"CODIGO", "NOMBRE", "UBICACIÓN", "TELÉFONO", "DIRECCIÓN"}; String[] registros = new String[5]; Conexion cc = new Conexion(); Connection cn = cc.conexion(); String sql = ""; sql = "SELECT COD_OFI, " + "NOM_OFI, " + "UBICACION, " + "TELEFONO, " + "DIRECCION " + "FROM OFICINAS " + "WHERE UBICACION LIKE'%" + dato + "%' " + "AND ESTADO = 'S'"; model = new DefaultTableModel(null, titulos) { @Override public boolean isCellEditable(int filas, int columnas) { if (columnas < 0) { return true; } else { return false; } } }; Statement psd = cn.createStatement(); ResultSet rs = psd.executeQuery(sql); while (rs.next()) { registros[0] = rs.getString("COD_OFI"); registros[1] = rs.getString("NOM_OFI"); registros[2] = rs.getString("UBICACION"); registros[3] = rs.getString("TELEFONO"); registros[4] = rs.getString("DIRECCION"); model.addRow(registros); } Tabla_Oficina.setModel(model); } catch (SQLException ex) { JOptionPane.showMessageDialog(this, ex); } } private void actualizarOficina() { if (txtNombreOficina.getText().isEmpty()) { JOptionPane.showMessageDialog(this, "Ingrese el nombre de la oficina"); txtNombreOficina.requestFocus(); } else if (txtUbicacion.getText().isEmpty()) { JOptionPane.showMessageDialog(this, "Ingrese la ubicación"); txtUbicacion.requestFocus(); } else if (txtTelefono.getText().isEmpty()) { JOptionPane.showMessageDialog(this, "Ingrese el teléfono"); txtTelefono.requestFocus(); } else if (txtTelefono.getText().length() < 9 || txtTelefono.getText().length() > 10) { JOptionPane.showMessageDialog(null, "El número de cifras del número de teléfono es incorrecto"); txtTelefono.requestFocus(); } else if (txtDireccion.getText().isEmpty()) { JOptionPane.showMessageDialog(null, "Ingrese una dirección"); txtDireccion.requestFocus(); } else { try { Conexion cc = new Conexion(); Connection cn = cc.conexion(); String sql = ""; sql = "UPDATE OFICINAS set NOM_OFI ='" + txtNombreOficina.getText() + "' " + ",UBICACION ='" + txtUbicacion.getText() + "' " + ",TELEFONO ='" + txtTelefono.getText() + "' " + ",DIRECCION ='" + txtDireccion.getText() + "' " + " WHERE COD_OFI ='" + codigoOficinaTabla + "'"; PreparedStatement psd = cn.prepareStatement(sql); int n = psd.executeUpdate(); if (n > 0) { JOptionPane.showMessageDialog(this, "SE ACTUALIZO LA OFICINA."); desactivarBotones(); desactivarTextos(); limpiarTextos(); CargarTablaOficinas(""); } } catch (SQLException ex) { JOptionPane.showMessageDialog(null, ex); } } } private boolean condEliOfi1(String codOficina) { /* Metodo que permite verificar si la oficina tiene o no tiene filas hijas , en la tabla PERSONAL_OFICINA sino NO tiene filas hijas elimino el registro DE LA TABLA OFICINA, caso contrario NO. */ int pos = 0; try { String sql = ""; Conexion cc = new Conexion(); Connection cn = cc.conexion(); sql = "SELECT * " + "FROM PERSONAL_OFICINA " + "WHERE COD_OFI_PER = '" + codOficina + "'"; Statement psd = cn.createStatement(); ResultSet rs = psd.executeQuery(sql); while (rs.next()) { pos = pos + 1; } } catch (SQLException ex) { JOptionPane.showMessageDialog(null, ex); } if (pos > 0) { return false; } return true; } private boolean condEliOfi2(String codOficina) { /* Metodo que permite verificar si la oficina tiene o no tiene filas hijas , en la tabla RUTAS sino NO tiene filas hijas elimino el registro DE LA TABLA OFICINA, caso contrario NO. */ int pos = 0; try { String sql = ""; Conexion cc = new Conexion(); Connection cn = cc.conexion(); sql = "SELECT * " + "FROM RUTAS " + "WHERE COD_OFI_ORI = '" + codOficina + "' " + "OR COD_OFI_DES = '" + codOficina + "'"; Statement psd = cn.createStatement(); ResultSet rs = psd.executeQuery(sql); while (rs.next()) { pos = pos + 1; } } catch (SQLException ex) { JOptionPane.showMessageDialog(null, ex); } if (pos > 0) { return false; } return true; } private void cargarModificarTabla() { Tabla_Oficina.getSelectionModel().addListSelectionListener(new ListSelectionListener() { @Override //Override cuando se sobrecarga un metodo o sobrecarga de valores ---- se lo pone con el obejtivo de liberar memoria public void valueChanged(ListSelectionEvent e) { if (Tabla_Oficina.getSelectedRow() != -1) { activarTextos(); botonesActualizar(); int fila = Tabla_Oficina.getSelectedRow(); codigoOficinaTabla = Tabla_Oficina.getValueAt(fila, 0).toString().trim(); //trim para los espacios en blanco txtNombreOficina.setText(Tabla_Oficina.getValueAt(fila, 1).toString().trim()); txtUbicacion.setText(Tabla_Oficina.getValueAt(fila, 2).toString().trim()); txtTelefono.setText(Tabla_Oficina.getValueAt(fila, 3).toString().trim()); txtDireccion.setText(Tabla_Oficina.getValueAt(fila, 4).toString().trim()); } } }); } private void eliminarOficina() { if (JOptionPane.showConfirmDialog(new JInternalFrame(), "¿ ESTA SEGURO DE BORRAR EL REGISTRO DE OFICINA ?", "Ventana Borrar", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) { if (condEliOfi1(codigoOficinaTabla) && condEliOfi2(codigoOficinaTabla)) { try { Conexion cc = new Conexion(); Connection cn = cc.conexion(); String sql = ""; sql = "update OFICINAS set ESTADO = 'N' where COD_OFI='" + codigoOficinaTabla + "'"; PreparedStatement psd = cn.prepareStatement(sql); int n = psd.executeUpdate(); if (n > 0) { JOptionPane.showMessageDialog(this, "REGISTRO ELIMINADO . . . . !"); CargarTablaOficinas(""); limpiarTextos(); desactivarTextos(); desactivarBotones(); } } catch (SQLException ex) { JOptionPane.showMessageDialog(this, ex); } } else { JOptionPane.showMessageDialog(null, "NO SE PUEDE ELIMINAR EL REGISTRO . . . ! " + "PRIMERO DEBE ELIMINAR LAS FILAS DEPENDIENTES DE LA TABLA OFICINA !"); } } } public void soloNumeros(java.awt.event.KeyEvent evt) { char c; c = evt.getKeyChar(); if ((c >= 32 && c <= 47) || (c >= 58 && c <= 255)) { evt.consume(); JOptionPane.showMessageDialog(this, "ERROR Ingrese solo Números"); } } public void soloLetras(java.awt.event.KeyEvent evt) { char c = evt.getKeyChar(); if ((c >= 33 && c <= 64) || (c >= 91 && c <= 96) || (c >= 123 && c <= 255)) { evt.consume(); getToolkit().beep(); JOptionPane.showMessageDialog(this, "Ingrese solo Letras", "Error", JOptionPane.ERROR_MESSAGE); } } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel4 = new javax.swing.JPanel(); jLabel7 = new javax.swing.JLabel(); jPanel3 = new javax.swing.JPanel(); jScrollPane1 = new javax.swing.JScrollPane(); Tabla_Oficina = new javax.swing.JTable(); jLabel5 = new javax.swing.JLabel(); txtBuscar = new javax.swing.JTextField(); jPanel8 = new javax.swing.JPanel(); jPanel1 = new javax.swing.JPanel(); jLabel2 = new javax.swing.JLabel(); txtNombreOficina = new javax.swing.JTextField(); jLabel4 = new javax.swing.JLabel(); txtTelefono = new javax.swing.JTextField(); jLabel3 = new javax.swing.JLabel(); txtUbicacion = new javax.swing.JTextField(); jLabel1 = new javax.swing.JLabel(); txtDireccion = new javax.swing.JTextField(); jButton_Nuevo = new javax.swing.JButton(); jButton_Guardar = new javax.swing.JButton(); jButton_Actualizar = new javax.swing.JButton(); jButton_Eliminar = new javax.swing.JButton(); jButton_Salir = new javax.swing.JButton(); jButton_Cancelar = new javax.swing.JButton(); setBackground(new java.awt.Color(255, 255, 255)); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setIconifiable(true); jPanel4.setBackground(new java.awt.Color(255, 255, 255)); jLabel7.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagenes/oficina.png"))); // NOI18N jPanel3.setBackground(new java.awt.Color(255, 255, 255)); jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder("OFICINAS EXISTENTES")); Tabla_Oficina = new javax.swing.JTable(){ public boolean isCellEditable(int f, int c){ return ((c!=0) && (c!=1) && (c!=2)&&(c!=3) && (c!=4)); } }; Tabla_Oficina.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {}, {}, {}, {} }, new String [] { } )); jScrollPane1.setViewportView(Tabla_Oficina); jLabel5.setFont(new java.awt.Font("Times New Roman", 1, 14)); // NOI18N jLabel5.setText("Buscar por ubicación"); txtBuscar.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { txtBuscarKeyReleased(evt); } public void keyTyped(java.awt.event.KeyEvent evt) { txtBuscarKeyTyped(evt); } }); javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3); jPanel3.setLayout(jPanel3Layout); jPanel3Layout.setHorizontalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 750, Short.MAX_VALUE) .addGroup(jPanel3Layout.createSequentialGroup() .addComponent(jLabel5) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(txtBuscar, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, Short.MAX_VALUE))) .addContainerGap()) ); jPanel3Layout.setVerticalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel5) .addComponent(txtBuscar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 152, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jPanel8.setBackground(new java.awt.Color(0, 153, 255)); javax.swing.GroupLayout jPanel8Layout = new javax.swing.GroupLayout(jPanel8); jPanel8.setLayout(jPanel8Layout); jPanel8Layout.setHorizontalGroup( jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 0, Short.MAX_VALUE) ); jPanel8Layout.setVerticalGroup( jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 29, Short.MAX_VALUE) ); jPanel1.setBackground(new java.awt.Color(255, 255, 255)); jPanel1.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jLabel2.setFont(new java.awt.Font("Times New Roman", 1, 18)); // NOI18N jLabel2.setText("Nombre de la oficina :"); txtNombreOficina.addKeyListener(new java.awt.event.KeyAdapter() { public void keyTyped(java.awt.event.KeyEvent evt) { txtNombreOficinaKeyTyped(evt); } }); jLabel4.setFont(new java.awt.Font("Times New Roman", 1, 18)); // NOI18N jLabel4.setText("Teléfono :"); txtTelefono.addFocusListener(new java.awt.event.FocusAdapter() { public void focusLost(java.awt.event.FocusEvent evt) { txtTelefonoFocusLost(evt); } }); txtTelefono.addKeyListener(new java.awt.event.KeyAdapter() { public void keyTyped(java.awt.event.KeyEvent evt) { txtTelefonoKeyTyped(evt); } }); jLabel3.setFont(new java.awt.Font("Times New Roman", 1, 18)); // NOI18N jLabel3.setText("Ubicación :"); txtUbicacion.addKeyListener(new java.awt.event.KeyAdapter() { public void keyTyped(java.awt.event.KeyEvent evt) { txtUbicacionKeyTyped(evt); } }); jLabel1.setFont(new java.awt.Font("Times New Roman", 1, 18)); // NOI18N jLabel1.setText("Dirección :"); txtDireccion.addKeyListener(new java.awt.event.KeyAdapter() { public void keyTyped(java.awt.event.KeyEvent evt) { txtDireccionKeyTyped(evt); } }); jButton_Nuevo.setFont(new java.awt.Font("Palatino Linotype", 0, 14)); // NOI18N jButton_Nuevo.setText("Nuevo"); jButton_Nuevo.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton_NuevoActionPerformed(evt); } }); jButton_Guardar.setFont(new java.awt.Font("Palatino Linotype", 0, 14)); // NOI18N jButton_Guardar.setText("Guardar"); jButton_Guardar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton_GuardarActionPerformed(evt); } }); jButton_Actualizar.setFont(new java.awt.Font("Palatino Linotype", 0, 14)); // NOI18N jButton_Actualizar.setText("Actualizar"); jButton_Actualizar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton_ActualizarActionPerformed(evt); } }); jButton_Eliminar.setFont(new java.awt.Font("Palatino Linotype", 0, 14)); // NOI18N jButton_Eliminar.setText("Eliminar"); jButton_Eliminar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton_EliminarActionPerformed(evt); } }); jButton_Salir.setFont(new java.awt.Font("Palatino Linotype", 0, 14)); // NOI18N jButton_Salir.setText("Salir"); jButton_Salir.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton_SalirActionPerformed(evt); } }); jButton_Cancelar.setFont(new java.awt.Font("Palatino Linotype", 0, 14)); // NOI18N jButton_Cancelar.setText("Cancelar"); jButton_Cancelar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton_CancelarActionPerformed(evt); } }); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabel2) .addComponent(jLabel3)) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(txtUbicacion) .addComponent(txtNombreOficina, javax.swing.GroupLayout.PREFERRED_SIZE, 214, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(29, 29, 29) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabel4) .addComponent(jLabel1)) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(txtTelefono) .addComponent(txtDireccion, javax.swing.GroupLayout.PREFERRED_SIZE, 214, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jButton_Nuevo, javax.swing.GroupLayout.PREFERRED_SIZE, 99, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jButton_Guardar, javax.swing.GroupLayout.PREFERRED_SIZE, 99, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(28, 28, 28) .addComponent(jButton_Actualizar) .addGap(28, 28, 28) .addComponent(jButton_Cancelar, javax.swing.GroupLayout.PREFERRED_SIZE, 99, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(32, 32, 32) .addComponent(jButton_Eliminar, javax.swing.GroupLayout.PREFERRED_SIZE, 99, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(31, 31, 31) .addComponent(jButton_Salir, javax.swing.GroupLayout.PREFERRED_SIZE, 99, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap(16, Short.MAX_VALUE)) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(35, 35, 35) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel2) .addComponent(txtNombreOficina, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel4) .addComponent(txtTelefono, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(36, 36, 36) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel3) .addComponent(txtUbicacion, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel1) .addComponent(txtDireccion, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 30, Short.MAX_VALUE) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jButton_Nuevo) .addComponent(jButton_Guardar) .addComponent(jButton_Actualizar) .addComponent(jButton_Eliminar) .addComponent(jButton_Salir) .addComponent(jButton_Cancelar)) .addContainerGap()) ); txtTelefono.getAccessibleContext().setAccessibleName(""); txtTelefono.getAccessibleContext().setAccessibleDescription(""); javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4); jPanel4.setLayout(jPanel4Layout); jPanel4Layout.setHorizontalGroup( jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel8, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(jPanel4Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel4Layout.createSequentialGroup() .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, Short.MAX_VALUE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel4Layout.createSequentialGroup() .addGap(0, 0, Short.MAX_VALUE) .addComponent(jLabel7) .addGap(273, 273, 273)) .addGroup(jPanel4Layout.createSequentialGroup() .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))) ); jPanel4Layout.setVerticalGroup( jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel4Layout.createSequentialGroup() .addComponent(jPanel8, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(13, 13, 13) .addComponent(jLabel7) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(13, 13, 13)) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); pack(); }// </editor-fold>//GEN-END:initComponents private void jButton_GuardarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_GuardarActionPerformed guardarOficina(); }//GEN-LAST:event_jButton_GuardarActionPerformed private void txtNombreOficinaKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtNombreOficinaKeyTyped char c = evt.getKeyChar(); if (Character.isLowerCase(c)) { String cad = ("" + c).toUpperCase(); c = cad.charAt(0); evt.setKeyChar(c); } soloLetras(evt); }//GEN-LAST:event_txtNombreOficinaKeyTyped private void txtUbicacionKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtUbicacionKeyTyped char c = evt.getKeyChar(); if (Character.isLowerCase(c)) { String cad = ("" + c).toUpperCase(); c = cad.charAt(0); evt.setKeyChar(c); } soloLetras(evt); }//GEN-LAST:event_txtUbicacionKeyTyped private void txtTelefonoKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtTelefonoKeyTyped char validar = evt.getKeyChar(); if(txtTelefono.getText().length()>=10){ JOptionPane.showMessageDialog(this,"Teléfono Incorrecto"); evt.consume(); } else if (Character.isLetter(validar)) { getToolkit().beep(); evt.consume(); JOptionPane.showMessageDialog(rootPane, "SOLO NÚMEROS POR FAVOR", "Advertencia", JOptionPane.ERROR_MESSAGE); } soloNumeros(evt); }//GEN-LAST:event_txtTelefonoKeyTyped private void txtDireccionKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtDireccionKeyTyped char c = evt.getKeyChar(); if (Character.isLowerCase(c)) { String cad = ("" + c).toUpperCase(); c = cad.charAt(0); evt.setKeyChar(c); } soloLetras(evt); }//GEN-LAST:event_txtDireccionKeyTyped private void txtBuscarKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtBuscarKeyReleased CargarTablaOficinas(txtBuscar.getText()); }//GEN-LAST:event_txtBuscarKeyReleased private void txtBuscarKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtBuscarKeyTyped char c = evt.getKeyChar(); if (Character.isLowerCase(c)) { String cad = ("" + c).toUpperCase(); c = cad.charAt(0); evt.setKeyChar(c); } soloLetras(evt); }//GEN-LAST:event_txtBuscarKeyTyped private void jButton_ActualizarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_ActualizarActionPerformed actualizarOficina(); }//GEN-LAST:event_jButton_ActualizarActionPerformed private void jButton_EliminarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_EliminarActionPerformed eliminarOficina(); }//GEN-LAST:event_jButton_EliminarActionPerformed private void jButton_NuevoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_NuevoActionPerformed activarBotonesNuevo(); activarTextos(); limpiarTextos(); }//GEN-LAST:event_jButton_NuevoActionPerformed private void jButton_CancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_CancelarActionPerformed limpiarTextos(); desactivarTextos(); desactivarBotones(); Tabla_Oficina.clearSelection(); }//GEN-LAST:event_jButton_CancelarActionPerformed private void txtTelefonoFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtTelefonoFocusLost }//GEN-LAST:event_txtTelefonoFocusLost private void jButton_SalirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_SalirActionPerformed this.dispose(); }//GEN-LAST:event_jButton_SalirActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(IngresoOficinas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(IngresoOficinas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(IngresoOficinas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(IngresoOficinas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new IngresoOficinas().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JTable Tabla_Oficina; private javax.swing.JButton jButton_Actualizar; private javax.swing.JButton jButton_Cancelar; private javax.swing.JButton jButton_Eliminar; private javax.swing.JButton jButton_Guardar; private javax.swing.JButton jButton_Nuevo; private javax.swing.JButton jButton_Salir; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel7; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JPanel jPanel3; private javax.swing.JPanel jPanel4; private javax.swing.JPanel jPanel7; private javax.swing.JPanel jPanel8; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JTextField txtBuscar; private javax.swing.JTextField txtDireccion; private javax.swing.JTextField txtNombreOficina; private javax.swing.JTextField txtTelefono; private javax.swing.JTextField txtUbicacion; // End of variables declaration//GEN-END:variables }
38,448
0.608863
0.598298
835
45.022755
34.604256
169
false
false
0
0
0
0
0
0
0.717365
false
false
7
269e709e1b2a2fe637f295458eef468f01f63aa8
25,829,933,350,637
152c8808a440def7a306aed5d498a8714b5d3527
/bad-words-filter/src/main/java/com/example/badwords/Mask.java
bae389b6aa95d03bb63109f718ee6651d5e6c8a1
[ "LicenseRef-scancode-warranty-disclaimer", "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
ruslan-sverchkov/examples
https://github.com/ruslan-sverchkov/examples
45cba8df5a3ae61ace09238c5472bc67ec248f71
30097482a07ac8eb8bfc4a310e1c965dcf78e58a
refs/heads/master
2019-07-19T01:19:36.553000
2017-12-06T15:20:14
2017-12-06T15:20:14
49,896,074
0
1
null
false
2016-03-10T15:14:48
2016-01-18T18:25:10
2016-01-24T17:23:14
2016-03-10T15:14:48
115
0
1
1
Java
null
null
package com.example.badwords; import org.apache.commons.lang3.Validate; import java.util.BitSet; /** * The class is intended to replace characters in incoming text by mask. * The class is not thread-safe. * * @author Ruslan Sverchkov */ public class Mask { private final BitSet set; /** * Construct an instance of Mask. * * @param set bit set for mask, no defensive copying, so blame yourself if you decide to set bits on result * @throws NullPointerException if set is null */ public Mask(BitSet set) { Validate.notNull(set); this.set = set; } /** * The method is intended to replace characters in the specified array with the specified shadow char. * The input length will stay intact. * For example: * mask = 0100110111 * input = aaaaaaaaaaaaa * shadow = * * result = a*aa**a***aaa * * @param chars input array * @param shadow replacement * @throws NullPointerException if chars is null * @throws IllegalArgumentException if chars is shorter than mask length */ public void apply(char[] chars, char shadow) { Validate.notNull(chars); Validate.isTrue(chars.length >= set.length()); int i = set.nextSetBit(0); while (i != -1) { chars[i] = shadow; i = set.nextSetBit(i + 1); } } /** * Same as {@link Mask#apply(char[], char)}, but the arguments remain intact. * * @param source input string * @param shadow replacement * @return copy of input string with the appropriate characters replaced with shadow according to the mask * @throws NullPointerException if source is null * @throws IllegalArgumentException if source is shorter than mask length */ public String apply(String source, char shadow) { Validate.notNull(source); char[] chars = source.toCharArray(); apply(chars, shadow); return new String(chars); } /** * The method is intended to replace groups of characters in the specified string with the specified shadow string. * The result length may differ from source length because groups of characters of different length will be * replaced with the same shadow string. * For example: * mask = 0100110111 * input = aaaaaaaaaaaaa * shadow = [censored] * result = a[censored]aa[censored]a[censored]aaa * * @param source input string * @param shadow replacement * @return copy of input string with groups of characters replaced with shadow according to the mask * @throws NullPointerException if any of the arguments is null * @throws IllegalArgumentException if source is shorter than mask length */ public String apply(String source, String shadow) { Validate.notNull(source); Validate.notNull(shadow); int sourceLength = source.length(); Validate.isTrue(sourceLength >= set.length()); StringBuilder builder = new StringBuilder(sourceLength); int i = 0; while (i < sourceLength) { if (set.get(i)) { builder.append(shadow); i = set.nextClearBit(i + 1); if (i == -1) { break; } } else { builder.append(source.charAt(i)); i++; } } return builder.toString(); } /** * The method is intended to check if the mask has set bits. * * @return whether the mask has set bits */ public boolean hasSetBits() { return set.nextSetBit(0) != -1; } /** * Returns the number of bits set to {@code true} in this mask. * * @return the number of bits set to {@code true} in this mask */ public int getCardinality() { return set.cardinality(); } /** * Get bit set. No defensive copying, so blame yourself if you decide to set bits on result. * * @return bit set */ public BitSet getSet() { return set; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Mask mask = (Mask) o; return set.equals(mask.set); } @Override public int hashCode() { return set.hashCode(); } @Override public String toString() { return "Mask " + set; } }
UTF-8
Java
4,529
java
Mask.java
Java
[ { "context": "sk.\n * The class is not thread-safe.\n *\n * @author Ruslan Sverchkov\n */\npublic class Mask {\n\n private final BitSet", "end": 240, "score": 0.999860405921936, "start": 224, "tag": "NAME", "value": "Ruslan Sverchkov" } ]
null
[]
package com.example.badwords; import org.apache.commons.lang3.Validate; import java.util.BitSet; /** * The class is intended to replace characters in incoming text by mask. * The class is not thread-safe. * * @author <NAME> */ public class Mask { private final BitSet set; /** * Construct an instance of Mask. * * @param set bit set for mask, no defensive copying, so blame yourself if you decide to set bits on result * @throws NullPointerException if set is null */ public Mask(BitSet set) { Validate.notNull(set); this.set = set; } /** * The method is intended to replace characters in the specified array with the specified shadow char. * The input length will stay intact. * For example: * mask = 0100110111 * input = aaaaaaaaaaaaa * shadow = * * result = a*aa**a***aaa * * @param chars input array * @param shadow replacement * @throws NullPointerException if chars is null * @throws IllegalArgumentException if chars is shorter than mask length */ public void apply(char[] chars, char shadow) { Validate.notNull(chars); Validate.isTrue(chars.length >= set.length()); int i = set.nextSetBit(0); while (i != -1) { chars[i] = shadow; i = set.nextSetBit(i + 1); } } /** * Same as {@link Mask#apply(char[], char)}, but the arguments remain intact. * * @param source input string * @param shadow replacement * @return copy of input string with the appropriate characters replaced with shadow according to the mask * @throws NullPointerException if source is null * @throws IllegalArgumentException if source is shorter than mask length */ public String apply(String source, char shadow) { Validate.notNull(source); char[] chars = source.toCharArray(); apply(chars, shadow); return new String(chars); } /** * The method is intended to replace groups of characters in the specified string with the specified shadow string. * The result length may differ from source length because groups of characters of different length will be * replaced with the same shadow string. * For example: * mask = 0100110111 * input = aaaaaaaaaaaaa * shadow = [censored] * result = a[censored]aa[censored]a[censored]aaa * * @param source input string * @param shadow replacement * @return copy of input string with groups of characters replaced with shadow according to the mask * @throws NullPointerException if any of the arguments is null * @throws IllegalArgumentException if source is shorter than mask length */ public String apply(String source, String shadow) { Validate.notNull(source); Validate.notNull(shadow); int sourceLength = source.length(); Validate.isTrue(sourceLength >= set.length()); StringBuilder builder = new StringBuilder(sourceLength); int i = 0; while (i < sourceLength) { if (set.get(i)) { builder.append(shadow); i = set.nextClearBit(i + 1); if (i == -1) { break; } } else { builder.append(source.charAt(i)); i++; } } return builder.toString(); } /** * The method is intended to check if the mask has set bits. * * @return whether the mask has set bits */ public boolean hasSetBits() { return set.nextSetBit(0) != -1; } /** * Returns the number of bits set to {@code true} in this mask. * * @return the number of bits set to {@code true} in this mask */ public int getCardinality() { return set.cardinality(); } /** * Get bit set. No defensive copying, so blame yourself if you decide to set bits on result. * * @return bit set */ public BitSet getSet() { return set; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Mask mask = (Mask) o; return set.equals(mask.set); } @Override public int hashCode() { return set.hashCode(); } @Override public String toString() { return "Mask " + set; } }
4,519
0.596158
0.589755
157
27.853502
26.650084
119
false
false
0
0
0
0
0
0
0.299363
false
false
7
14acfebf5bf331cec6ec7b5e028331a99d6f9983
9,766,755,681,301
3980e3ce99d00fb9065c114ebed9b9443439df3f
/src/me/ihavenowlan/inmaintenance/cmd/CMD.java
fdde7e82c37357cb1078bee05fd5ff01a3ed916a
[]
no_license
IHaveNoWLAN/InMaintenance
https://github.com/IHaveNoWLAN/InMaintenance
af56878dc15238e9eb0e24414a7ee0168748f89a
7796642fdb0cd7e90807d80085804d032bd7fccf
refs/heads/master
2023-07-02T23:58:40.480000
2021-08-04T07:34:46
2021-08-04T07:34:46
392,126,394
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package me.ihavenowlan.inmaintenance.cmd; import me.ihavenowlan.inmaintenance.Main; import org.bukkit.Bukkit; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerKickEvent; import org.bukkit.event.player.PlayerLoginEvent; import org.bukkit.event.player.PlayerQuitEvent; import org.bukkit.event.server.ServerListPingEvent; import java.util.Iterator; public class CMD implements CommandExecutor, Listener { String exclamation = "\n§c████████\n§c ███§f██§c███ \n§c ███§f██§c███ \n§c ███§f██§c███ \n§c ███§f██§c███ \n§c ████████ \n§c ███§f██§c███ \n§c████████\n\n"; @Override public boolean onCommand(CommandSender commandSender, Command command, String s, String[] args) { String arg; String prefix = Main.getInstance().getConfig().getString("message.prefix"); if (commandSender.hasPermission("maintenance.use")) { if (args.length == 1) { arg = args[0]; if (arg.equalsIgnoreCase("off")) { Bukkit.broadcastMessage(prefix + " " + Main.getInstance().getConfig().getString("message.nowmaintenanceoff")); Main.getInstance().getConfig().set("main.status", false); Main.getInstance().getConfig().set("main.status", false); Main.getInstance().saveConfig(); return false; } if (arg.equalsIgnoreCase("on")) { Bukkit.broadcastMessage(prefix + " " + Main.getInstance().getConfig().getString("message.nowmaintenanceon")); Iterator var8 = Bukkit.getOnlinePlayers().iterator(); while (var8.hasNext()) { Player pp = (Player) var8.next(); if (!pp.hasPermission("maintenance.bypass")) { if (Main.getInstance().getConfig().getBoolean("message.exclamationmark") == true) { String config1 = Main.getInstance().getConfig().getString("message.kick.line1"); config1 = config1; String config2 = Main.getInstance().getConfig().getString("message.kick.line2"); config2 = config2; String config3 = Main.getInstance().getConfig().getString("message.kick.line3"); config3 = config3; String config4 = Main.getInstance().getConfig().getString("message.kick.line4"); config4 = config4; String config5 = Main.getInstance().getConfig().getString("message.kick.line5"); config5 = config5; String config6 = Main.getInstance().getConfig().getString("message.kick.line6"); config6 = config6; pp.kickPlayer(exclamation + config1 + "\n" + config2 + "\n" + config3 + "\n" + config4 + "\n" + config5 + "\n" + config6); } else { String config1 = Main.getInstance().getConfig().getString("message.kick.line1"); config1 = config1; String config2 = Main.getInstance().getConfig().getString("message.kick.line2"); config2 = config2; String config3 = Main.getInstance().getConfig().getString("message.kick.line3"); config3 = config3; String config4 = Main.getInstance().getConfig().getString("message.kick.line4"); config4 = config4; String config5 = Main.getInstance().getConfig().getString("message.kick.line5"); config5 = config5; String config6 = Main.getInstance().getConfig().getString("message.kick.line6"); config6 = config6; pp.kickPlayer(config1 + "\n" + config2 + "\n" + config3 + "\n" + config4 + "\n" + config5 + "\n" + config6); } } } Main.getInstance().getConfig().set("main.status", true); Main.getInstance().getConfig().set("main.status", true); Main.getInstance().saveConfig(); return false; } if (arg.equalsIgnoreCase("reload")) { commandSender.sendMessage(prefix + " " + Main.getInstance().getConfig().getString("message.configreload")); Main.getInstance().reloadConfig(); Main.getInstance().saveConfig(); } } else if (args.length == 0) { if (Main.getInstance().getConfig().getBoolean("main.status") == true) { commandSender.sendMessage(prefix + " " + Main.getInstance().getConfig().getString("message.status").replaceAll("#STATUS#", Main.getInstance().getConfig().getString("message.enabled"))); } else { commandSender.sendMessage(prefix + " " + Main.getInstance().getConfig().getString("message.status").replaceAll("#STATUS#", Main.getInstance().getConfig().getString("message.disabled"))); } } else { commandSender.sendMessage(prefix + " " + Main.getInstance().getConfig().getString("message.error")); } } else { commandSender.sendMessage(prefix + " " + Main.getInstance().getConfig().getString("message.noperm")); } return false; } @EventHandler public void onLogin(PlayerLoginEvent e) { System.out.println(e.getPlayer().getName() + Main.getInstance().getConfig().getBoolean("main.status") + this.exclamation); if (Main.getInstance().getConfig().getBoolean("main.status") == true && !e.getPlayer().hasPermission("maintenance.bypass")) { if (Main.getInstance().getConfig().getBoolean("message.exclamationmark") == true) { String config1 = Main.getInstance().getConfig().getString("message.kick.line1"); config1 = config1; String config2 = Main.getInstance().getConfig().getString("message.kick.line2"); config2 = config2; String config3 = Main.getInstance().getConfig().getString("message.kick.line3"); config3 = config3; String config4 = Main.getInstance().getConfig().getString("message.kick.line4"); config4 = config4; String config5 = Main.getInstance().getConfig().getString("message.kick.line5"); config5 = config5; String config6 = Main.getInstance().getConfig().getString("message.kick.line6"); config6 = config6; e.disallow(null, exclamation + config1 + "\n" + config2 + "\n" + config3 + "\n" + config4 + "\n" + config5 + "\n" + config6); } else { String config1 = Main.getInstance().getConfig().getString("message.kick.line1"); config1 = config1; String config2 = Main.getInstance().getConfig().getString("message.kick.line2"); config2 = config2; String config3 = Main.getInstance().getConfig().getString("message.kick.line3"); config3 = config3; String config4 = Main.getInstance().getConfig().getString("message.kick.line4"); config4 = config4; String config5 = Main.getInstance().getConfig().getString("message.kick.line5"); config5 = config5; String config6 = Main.getInstance().getConfig().getString("message.kick.line6"); config6 = config6; e.disallow(null, config1 + "\n" + config2 + "\n" + config3 + "\n" + config4 + "\n" + config5 + "\n" + config6); } } } @EventHandler public void onKick(PlayerKickEvent e) { if (Main.getInstance().getConfig().getBoolean("main.status") == true) { if (!(e.getPlayer().hasPermission("maintenance.bypass"))) { e.setLeaveMessage(""); } } } @EventHandler public void onLeave(PlayerQuitEvent e) { if (Main.getInstance().getConfig().getBoolean("main.status") == true) { if (!(e.getPlayer().hasPermission("maintenance.bypass"))) { e.setQuitMessage(""); } } } @EventHandler public void onPing(ServerListPingEvent e) { if (Main.getInstance().getConfig().getBoolean("main.status") == true) { int slots = Main.getInstance().getConfig().getInt("main.slots"); e.setMaxPlayers(slots); String MOTD1 = Main.getInstance().getConfig().getString("message.MOTD.line1"); String MOTD2 = Main.getInstance().getConfig().getString("message.MOTD.line2"); e.setMotd(MOTD1 + "\n" + MOTD2); } } }
UTF-8
Java
9,527
java
CMD.java
Java
[]
null
[]
package me.ihavenowlan.inmaintenance.cmd; import me.ihavenowlan.inmaintenance.Main; import org.bukkit.Bukkit; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerKickEvent; import org.bukkit.event.player.PlayerLoginEvent; import org.bukkit.event.player.PlayerQuitEvent; import org.bukkit.event.server.ServerListPingEvent; import java.util.Iterator; public class CMD implements CommandExecutor, Listener { String exclamation = "\n§c████████\n§c ███§f██§c███ \n§c ███§f██§c███ \n§c ███§f██§c███ \n§c ███§f██§c███ \n§c ████████ \n§c ███§f██§c███ \n§c████████\n\n"; @Override public boolean onCommand(CommandSender commandSender, Command command, String s, String[] args) { String arg; String prefix = Main.getInstance().getConfig().getString("message.prefix"); if (commandSender.hasPermission("maintenance.use")) { if (args.length == 1) { arg = args[0]; if (arg.equalsIgnoreCase("off")) { Bukkit.broadcastMessage(prefix + " " + Main.getInstance().getConfig().getString("message.nowmaintenanceoff")); Main.getInstance().getConfig().set("main.status", false); Main.getInstance().getConfig().set("main.status", false); Main.getInstance().saveConfig(); return false; } if (arg.equalsIgnoreCase("on")) { Bukkit.broadcastMessage(prefix + " " + Main.getInstance().getConfig().getString("message.nowmaintenanceon")); Iterator var8 = Bukkit.getOnlinePlayers().iterator(); while (var8.hasNext()) { Player pp = (Player) var8.next(); if (!pp.hasPermission("maintenance.bypass")) { if (Main.getInstance().getConfig().getBoolean("message.exclamationmark") == true) { String config1 = Main.getInstance().getConfig().getString("message.kick.line1"); config1 = config1; String config2 = Main.getInstance().getConfig().getString("message.kick.line2"); config2 = config2; String config3 = Main.getInstance().getConfig().getString("message.kick.line3"); config3 = config3; String config4 = Main.getInstance().getConfig().getString("message.kick.line4"); config4 = config4; String config5 = Main.getInstance().getConfig().getString("message.kick.line5"); config5 = config5; String config6 = Main.getInstance().getConfig().getString("message.kick.line6"); config6 = config6; pp.kickPlayer(exclamation + config1 + "\n" + config2 + "\n" + config3 + "\n" + config4 + "\n" + config5 + "\n" + config6); } else { String config1 = Main.getInstance().getConfig().getString("message.kick.line1"); config1 = config1; String config2 = Main.getInstance().getConfig().getString("message.kick.line2"); config2 = config2; String config3 = Main.getInstance().getConfig().getString("message.kick.line3"); config3 = config3; String config4 = Main.getInstance().getConfig().getString("message.kick.line4"); config4 = config4; String config5 = Main.getInstance().getConfig().getString("message.kick.line5"); config5 = config5; String config6 = Main.getInstance().getConfig().getString("message.kick.line6"); config6 = config6; pp.kickPlayer(config1 + "\n" + config2 + "\n" + config3 + "\n" + config4 + "\n" + config5 + "\n" + config6); } } } Main.getInstance().getConfig().set("main.status", true); Main.getInstance().getConfig().set("main.status", true); Main.getInstance().saveConfig(); return false; } if (arg.equalsIgnoreCase("reload")) { commandSender.sendMessage(prefix + " " + Main.getInstance().getConfig().getString("message.configreload")); Main.getInstance().reloadConfig(); Main.getInstance().saveConfig(); } } else if (args.length == 0) { if (Main.getInstance().getConfig().getBoolean("main.status") == true) { commandSender.sendMessage(prefix + " " + Main.getInstance().getConfig().getString("message.status").replaceAll("#STATUS#", Main.getInstance().getConfig().getString("message.enabled"))); } else { commandSender.sendMessage(prefix + " " + Main.getInstance().getConfig().getString("message.status").replaceAll("#STATUS#", Main.getInstance().getConfig().getString("message.disabled"))); } } else { commandSender.sendMessage(prefix + " " + Main.getInstance().getConfig().getString("message.error")); } } else { commandSender.sendMessage(prefix + " " + Main.getInstance().getConfig().getString("message.noperm")); } return false; } @EventHandler public void onLogin(PlayerLoginEvent e) { System.out.println(e.getPlayer().getName() + Main.getInstance().getConfig().getBoolean("main.status") + this.exclamation); if (Main.getInstance().getConfig().getBoolean("main.status") == true && !e.getPlayer().hasPermission("maintenance.bypass")) { if (Main.getInstance().getConfig().getBoolean("message.exclamationmark") == true) { String config1 = Main.getInstance().getConfig().getString("message.kick.line1"); config1 = config1; String config2 = Main.getInstance().getConfig().getString("message.kick.line2"); config2 = config2; String config3 = Main.getInstance().getConfig().getString("message.kick.line3"); config3 = config3; String config4 = Main.getInstance().getConfig().getString("message.kick.line4"); config4 = config4; String config5 = Main.getInstance().getConfig().getString("message.kick.line5"); config5 = config5; String config6 = Main.getInstance().getConfig().getString("message.kick.line6"); config6 = config6; e.disallow(null, exclamation + config1 + "\n" + config2 + "\n" + config3 + "\n" + config4 + "\n" + config5 + "\n" + config6); } else { String config1 = Main.getInstance().getConfig().getString("message.kick.line1"); config1 = config1; String config2 = Main.getInstance().getConfig().getString("message.kick.line2"); config2 = config2; String config3 = Main.getInstance().getConfig().getString("message.kick.line3"); config3 = config3; String config4 = Main.getInstance().getConfig().getString("message.kick.line4"); config4 = config4; String config5 = Main.getInstance().getConfig().getString("message.kick.line5"); config5 = config5; String config6 = Main.getInstance().getConfig().getString("message.kick.line6"); config6 = config6; e.disallow(null, config1 + "\n" + config2 + "\n" + config3 + "\n" + config4 + "\n" + config5 + "\n" + config6); } } } @EventHandler public void onKick(PlayerKickEvent e) { if (Main.getInstance().getConfig().getBoolean("main.status") == true) { if (!(e.getPlayer().hasPermission("maintenance.bypass"))) { e.setLeaveMessage(""); } } } @EventHandler public void onLeave(PlayerQuitEvent e) { if (Main.getInstance().getConfig().getBoolean("main.status") == true) { if (!(e.getPlayer().hasPermission("maintenance.bypass"))) { e.setQuitMessage(""); } } } @EventHandler public void onPing(ServerListPingEvent e) { if (Main.getInstance().getConfig().getBoolean("main.status") == true) { int slots = Main.getInstance().getConfig().getInt("main.slots"); e.setMaxPlayers(slots); String MOTD1 = Main.getInstance().getConfig().getString("message.MOTD.line1"); String MOTD2 = Main.getInstance().getConfig().getString("message.MOTD.line2"); e.setMotd(MOTD1 + "\n" + MOTD2); } } }
9,527
0.541627
0.527556
173
53.225433
43.491425
206
false
false
0
0
0
0
0
0
0.635838
false
false
7
33d9bfe0cad889b46c4a1f51463cb122d6843149
2,078,764,240,425
bc2bba01cd6c3006512dc47a6c1a64fbff8ece8a
/quali-t-app/app/exceptions/CouldNotConvertException.java
f328d42da264ef70b420e60384053d0d724f078c
[ "Apache-2.0" ]
permissive
team-qualit/quali-t
https://github.com/team-qualit/quali-t
a0530d72d7e9c566652cab3d6d3e48e104ff8242
52890b710d86dbefaa5c07becdc7bdc6109b5261
refs/heads/master
2021-01-19T12:31:38.622000
2015-06-11T17:34:59
2015-06-11T17:34:59
31,060,380
0
2
null
false
2015-05-19T15:01:27
2015-02-20T10:35:10
2015-05-08T17:37:25
2015-05-19T10:58:08
4,908
0
1
1
Java
null
null
package exceptions; /** * Created by corina on 25.05.2015. */ public class CouldNotConvertException extends AbstractException { public CouldNotConvertException(String message) { super(message, 500); } }
UTF-8
Java
222
java
CouldNotConvertException.java
Java
[ { "context": "package exceptions;\n\n/**\n * Created by corina on 25.05.2015.\n */\npublic class CouldNotConvertEx", "end": 45, "score": 0.9984347820281982, "start": 39, "tag": "USERNAME", "value": "corina" } ]
null
[]
package exceptions; /** * Created by corina on 25.05.2015. */ public class CouldNotConvertException extends AbstractException { public CouldNotConvertException(String message) { super(message, 500); } }
222
0.716216
0.666667
10
21.200001
22.256685
65
false
false
0
0
0
0
0
0
0.3
false
false
7
f7a120e00abfd76682f0853363c5184f48abbedb
8,117,488,219,920
76da2d634b8ba5653d32bccde6c2e46c7f5d642e
/test/service/io/NodeTest.java
4e81a58f08ec43fb21bf19e719605709eddffa6b
[]
no_license
Zarazinski/BTREE
https://github.com/Zarazinski/BTREE
dc9fdeae90d30379b0089ee99c4db37367a161fd
d8c7517d8fcf9acb28b4bc6cc911e4fe55c98911
refs/heads/master
2021-10-01T00:13:27.774000
2018-11-26T07:20:49
2018-11-26T07:20:49
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package service.io; import org.junit.Test; import tree.Node; import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.stream.Collectors; import static org.junit.Assert.*; public class NodeTest { @Test public void testWriteReadNode() throws IOException { Node node = new Node(0); node.setKeys(Arrays.asList(5, 10, 15, 20)); node.setDescendants(Arrays.asList(1, 2, 3, 4, 5)); NodeWriter writer = new NodeWriter("testfile", 11 * Integer.BYTES); writer.write(node); NodeReader reader = new NodeReader("testfile", 11 * Integer.BYTES); Node read = reader.read(0); assertArrayEquals(read.getKeys().toArray(new Integer[0]), new Integer[]{5, 10, 15, 20}); assertArrayEquals(read.getDescendants().toArray(new Integer[0]), new Integer[]{1, 2, 3, 4, 5}); } }
UTF-8
Java
918
java
NodeTest.java
Java
[ { "context": "= new Node(0);\n node.setKeys(Arrays.asList(5, 10, 15, 20));\n node.setDescendants(Arrays", "end": 415, "score": 0.9529131650924683, "start": 414, "tag": "KEY", "value": "5" }, { "context": "ew Node(0);\n node.setKeys(Arrays.asList(5, 10, 15, 20));\n node.setDescendants(Arrays.asL", "end": 419, "score": 0.692069411277771, "start": 417, "tag": "KEY", "value": "10" }, { "context": "de(0);\n node.setKeys(Arrays.asList(5, 10, 15, 20));\n node.setDescendants(Arrays.asList(", "end": 423, "score": 0.8974048495292664, "start": 422, "tag": "KEY", "value": "5" }, { "context": ");\n node.setKeys(Arrays.asList(5, 10, 15, 20));\n node.setDescendants(Arrays.asList(1, 2", "end": 427, "score": 0.5114420056343079, "start": 426, "tag": "KEY", "value": "0" } ]
null
[]
package service.io; import org.junit.Test; import tree.Node; import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.stream.Collectors; import static org.junit.Assert.*; public class NodeTest { @Test public void testWriteReadNode() throws IOException { Node node = new Node(0); node.setKeys(Arrays.asList(5, 10, 15, 20)); node.setDescendants(Arrays.asList(1, 2, 3, 4, 5)); NodeWriter writer = new NodeWriter("testfile", 11 * Integer.BYTES); writer.write(node); NodeReader reader = new NodeReader("testfile", 11 * Integer.BYTES); Node read = reader.read(0); assertArrayEquals(read.getKeys().toArray(new Integer[0]), new Integer[]{5, 10, 15, 20}); assertArrayEquals(read.getDescendants().toArray(new Integer[0]), new Integer[]{1, 2, 3, 4, 5}); } }
918
0.673203
0.638344
32
27.71875
28.534227
103
false
false
0
0
0
0
0
0
1.125
false
false
7
49e92d304d7d698ba025064df6bd51dab6765778
22,084,721,870,531
81e308693f2a254af1439f56cc31c71df8d66ed5
/src/main/java/com/aorun/ymgh/util/ImagePathUtil.java
e44d74dacfbd73c07b17c138db2c8ffd11607cdd
[]
no_license
duxihu2014/aorun-ymgh
https://github.com/duxihu2014/aorun-ymgh
f65490a0aab503020ee3536d7f940b64c29902c8
2d17e35ee3d644e71161bbfd0feae8e817d85100
refs/heads/master
2022-07-14T21:35:48.604000
2020-11-08T14:34:08
2020-11-08T14:34:08
177,085,233
0
1
null
false
2022-06-21T01:00:18
2019-03-22T06:38:06
2020-11-08T14:34:12
2022-06-21T01:00:15
270
0
0
3
Java
false
false
/** * */ package com.aorun.ymgh.util; import com.aorun.ymgh.util.biz.ImagePropertiesConfig; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.util.StringUtils; /** * @author mengshaobo * */ public class ImagePathUtil { private static final Log LOGGER = LogFactory.getLog(ImagePathUtil.class); /** * 获取文件系统的相对路径 * @param fileJavaPath 文件java地址 * @return */ public static String getFileName(String fileJavaPath){ String fileName = ""; if(!StringUtils.isEmpty(fileJavaPath)){ fileName = fileJavaPath.substring(fileJavaPath.indexOf("userfiles/")+"userfiles/".length()); } return fileName; } /** * 获取多个图片名称 * @param fileJavaPaths 图片java地址 * @return */ public static String getFileStringName(String fileJavaPaths){ if(null==fileJavaPaths||StringUtils.isEmpty(fileJavaPaths)){ return ""; } StringBuilder stringBuffer = new StringBuilder(); fileJavaPaths.replace("|", ","); String[] gd =StringUtils.split(fileJavaPaths, ","); for(int i = 0 ; i < gd.length;i++){ stringBuffer.append(getFileName(gd[i])+","); } if(stringBuffer.toString().endsWith(",")){ stringBuffer.deleteCharAt(stringBuffer.lastIndexOf(",")); } return stringBuffer.toString(); } /** * 给图片加域名 * * @param pathUrl */ public static String setFileServerName(String pathUrl) { if (!StringUtils.isEmpty(pathUrl) && !pathUrl.startsWith("http")) { return ImagePropertiesConfig.CDN_SERVER_ROOT_PATH + pathUrl; } return pathUrl; } /** * 给多图片加域名 * * @param pathPathString */ public static String setFilePathStringServerName(String pathPathString) { if(null==pathPathString||StringUtils.isEmpty(pathPathString)){ return ""; } String[] split = pathPathString.split(","); StringBuffer stringBuffer = new StringBuffer(); for(int i=0;i<split.length;i++){ stringBuffer.append(setFileServerName(split[i])+","); } if(stringBuffer.toString().endsWith(",")){ stringBuffer.deleteCharAt(stringBuffer.lastIndexOf(",")); } return stringBuffer.toString(); } }
UTF-8
Java
2,177
java
ImagePathUtil.java
Java
[ { "context": ".springframework.util.StringUtils;\n\n/**\n * @author mengshaobo\n *\n */\npublic class ImagePathUtil {\n\t\n\tprivate st", "end": 252, "score": 0.9994950294494629, "start": 242, "tag": "USERNAME", "value": "mengshaobo" } ]
null
[]
/** * */ package com.aorun.ymgh.util; import com.aorun.ymgh.util.biz.ImagePropertiesConfig; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.util.StringUtils; /** * @author mengshaobo * */ public class ImagePathUtil { private static final Log LOGGER = LogFactory.getLog(ImagePathUtil.class); /** * 获取文件系统的相对路径 * @param fileJavaPath 文件java地址 * @return */ public static String getFileName(String fileJavaPath){ String fileName = ""; if(!StringUtils.isEmpty(fileJavaPath)){ fileName = fileJavaPath.substring(fileJavaPath.indexOf("userfiles/")+"userfiles/".length()); } return fileName; } /** * 获取多个图片名称 * @param fileJavaPaths 图片java地址 * @return */ public static String getFileStringName(String fileJavaPaths){ if(null==fileJavaPaths||StringUtils.isEmpty(fileJavaPaths)){ return ""; } StringBuilder stringBuffer = new StringBuilder(); fileJavaPaths.replace("|", ","); String[] gd =StringUtils.split(fileJavaPaths, ","); for(int i = 0 ; i < gd.length;i++){ stringBuffer.append(getFileName(gd[i])+","); } if(stringBuffer.toString().endsWith(",")){ stringBuffer.deleteCharAt(stringBuffer.lastIndexOf(",")); } return stringBuffer.toString(); } /** * 给图片加域名 * * @param pathUrl */ public static String setFileServerName(String pathUrl) { if (!StringUtils.isEmpty(pathUrl) && !pathUrl.startsWith("http")) { return ImagePropertiesConfig.CDN_SERVER_ROOT_PATH + pathUrl; } return pathUrl; } /** * 给多图片加域名 * * @param pathPathString */ public static String setFilePathStringServerName(String pathPathString) { if(null==pathPathString||StringUtils.isEmpty(pathPathString)){ return ""; } String[] split = pathPathString.split(","); StringBuffer stringBuffer = new StringBuffer(); for(int i=0;i<split.length;i++){ stringBuffer.append(setFileServerName(split[i])+","); } if(stringBuffer.toString().endsWith(",")){ stringBuffer.deleteCharAt(stringBuffer.lastIndexOf(",")); } return stringBuffer.toString(); } }
2,177
0.697663
0.69671
87
23.103449
24.023472
96
false
false
0
0
0
0
0
0
1.758621
false
false
7
cb1202b951d924beaa7d59eb658e0825767ff645
566,935,691,557
9d995ab9264754fb567321945d56f339cd97004f
/src/main/java/ru/jooble/inventorysystem/service/impl/EquipmentServiceImpl.java
9d02559263e0c98730e49e34466f694cddf0e006
[]
no_license
jooble/test-task
https://github.com/jooble/test-task
805eb27c13f36f769f319dfb285aedc37d1ba4cb
28572cfaabe58ff8b6449f4f63e4cca816a0365b
refs/heads/master
2020-12-24T21:10:48.167000
2016-05-22T18:16:22
2016-05-22T18:16:38
58,967,969
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ru.jooble.inventorysystem.service.impl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import ru.jooble.inventorysystem.dao.EquipmentDao; import ru.jooble.inventorysystem.domain.Equipment; import ru.jooble.inventorysystem.service.EquipmentService; import java.util.List; @Service public class EquipmentServiceImpl implements EquipmentService { @Autowired EquipmentDao equipmentDao; @Override @Transactional(readOnly = true) public Equipment getById(int id) { return equipmentDao.getById(id); } @Override @Transactional(readOnly = true) public List<Equipment> getAll() { return equipmentDao.getAll(); } @Override @Transactional(readOnly = true) public List getAllCriteriaCupboardId(int id) { return equipmentDao.getAllInCupboardId(id); } @Override @Transactional public void save(Equipment equipment) { equipmentDao.save(equipment); } @Override @Transactional public void update(Equipment equipment) { equipmentDao.update(equipment); } @Override @Transactional public void deleteById(int id) { Equipment equipment = equipmentDao.getById(id); equipmentDao.delete(equipment); } }
UTF-8
Java
1,382
java
EquipmentServiceImpl.java
Java
[]
null
[]
package ru.jooble.inventorysystem.service.impl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import ru.jooble.inventorysystem.dao.EquipmentDao; import ru.jooble.inventorysystem.domain.Equipment; import ru.jooble.inventorysystem.service.EquipmentService; import java.util.List; @Service public class EquipmentServiceImpl implements EquipmentService { @Autowired EquipmentDao equipmentDao; @Override @Transactional(readOnly = true) public Equipment getById(int id) { return equipmentDao.getById(id); } @Override @Transactional(readOnly = true) public List<Equipment> getAll() { return equipmentDao.getAll(); } @Override @Transactional(readOnly = true) public List getAllCriteriaCupboardId(int id) { return equipmentDao.getAllInCupboardId(id); } @Override @Transactional public void save(Equipment equipment) { equipmentDao.save(equipment); } @Override @Transactional public void update(Equipment equipment) { equipmentDao.update(equipment); } @Override @Transactional public void deleteById(int id) { Equipment equipment = equipmentDao.getById(id); equipmentDao.delete(equipment); } }
1,382
0.724313
0.724313
53
25.075472
20.474419
64
false
false
0
0
0
0
0
0
0.301887
false
false
7
09224f74845a0ab959cf9059f1cb1ac0e5c805cc
8,546,984,923,953
d89c40faccf1f0af50e7a1b8e1c790ea3729f1ef
/IDEAprojects/colour_cold/src/InnerClass/InnerClass04Test.java
92250dbd3287465b5ff863d616c5d132fd39d5f9
[]
no_license
colour-cold/repo1
https://github.com/colour-cold/repo1
55e1939711f3720ef8ef3bbdf9cf050cae8d7e4a
b85eb9190d79f630bdeaf2c231542e48c02d116e
refs/heads/master
2022-06-28T12:40:48.563000
2020-03-27T09:50:37
2020-03-27T09:50:37
249,617,363
0
0
null
false
2022-06-21T03:03:12
2020-03-24T05:02:49
2020-03-27T09:50:52
2022-06-21T03:03:11
11,164
0
0
1
Java
false
false
package InnerClass; public class InnerClass04Test { public static void main(String[] args) { InnerClass04Outer test = new InnerClass04Outer(); test.methodOuter(); } }
UTF-8
Java
192
java
InnerClass04Test.java
Java
[]
null
[]
package InnerClass; public class InnerClass04Test { public static void main(String[] args) { InnerClass04Outer test = new InnerClass04Outer(); test.methodOuter(); } }
192
0.677083
0.645833
8
23
19.4615
57
false
false
0
0
0
0
0
0
0.375
false
false
7
d59e0a464bae8c9d2f9fa7a47d47077dc4d6f9f4
18,425,409,708,493
32b72e1dc8b6ee1be2e80bb70a03a021c83db550
/ast_results/daneren2005_Subsonic/app/src/main/java/github/daneren2005/dsub/service/ServerTooOldException.java
e8b3a55ef56424c3ee8678b5aaf65441b320c815
[]
no_license
cmFodWx5YWRhdjEyMTA5/smell-and-machine-learning
https://github.com/cmFodWx5YWRhdjEyMTA5/smell-and-machine-learning
d90c41a17e88fcd99d543124eeb6e93f9133cb4a
0564143d92f8024ff5fa6b659c2baebf827582b1
refs/heads/master
2020-07-13T13:53:40.297000
2019-01-11T11:51:18
2019-01-11T11:51:18
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
// isComment package github.daneren2005.dsub.service; import github.daneren2005.dsub.domain.Version; /** * isComment */ public class isClassOrIsInterface extends Exception { private final String isVariable; private final Version isVariable; private final Version isVariable; public isConstructor(String isParameter, Version isParameter, Version isParameter) { this.isFieldAccessExpr = isNameExpr; this.isFieldAccessExpr = isNameExpr; this.isFieldAccessExpr = isNameExpr; } @Override public String isMethod() { StringBuilder isVariable = new StringBuilder(); if (isNameExpr != null) { isNameExpr.isMethod(isNameExpr).isMethod("isStringConstant"); } isNameExpr.isMethod("isStringConstant"); isNameExpr.isMethod("isStringConstant").isMethod(isNameExpr.isMethod()).isMethod("isStringConstant").isMethod(isNameExpr.isMethod()).isMethod("isStringConstant"); return isNameExpr.isMethod(); } @Override public String isMethod() { return this.isMethod(); } }
UTF-8
Java
1,095
java
ServerTooOldException.java
Java
[ { "context": "// isComment\npackage github.daneren2005.dsub.service;\n\nimport github.daneren2005.dsub.dom", "end": 39, "score": 0.9949913620948792, "start": 28, "tag": "USERNAME", "value": "daneren2005" }, { "context": "e github.daneren2005.dsub.service;\n\nimport github.daneren2005.dsub.domain.Version;\n\n/**\n * isComment\n */\npublic", "end": 80, "score": 0.9977571368217468, "start": 69, "tag": "USERNAME", "value": "daneren2005" } ]
null
[]
// isComment package github.daneren2005.dsub.service; import github.daneren2005.dsub.domain.Version; /** * isComment */ public class isClassOrIsInterface extends Exception { private final String isVariable; private final Version isVariable; private final Version isVariable; public isConstructor(String isParameter, Version isParameter, Version isParameter) { this.isFieldAccessExpr = isNameExpr; this.isFieldAccessExpr = isNameExpr; this.isFieldAccessExpr = isNameExpr; } @Override public String isMethod() { StringBuilder isVariable = new StringBuilder(); if (isNameExpr != null) { isNameExpr.isMethod(isNameExpr).isMethod("isStringConstant"); } isNameExpr.isMethod("isStringConstant"); isNameExpr.isMethod("isStringConstant").isMethod(isNameExpr.isMethod()).isMethod("isStringConstant").isMethod(isNameExpr.isMethod()).isMethod("isStringConstant"); return isNameExpr.isMethod(); } @Override public String isMethod() { return this.isMethod(); } }
1,095
0.697717
0.690411
38
27.81579
32.560757
170
false
false
0
0
0
0
0
0
0.421053
false
false
7
6f1b52c0b42220b2e6f70df18441cd98a9f5a9ae
21,406,117,009,998
c3379122d94b3ec9ae1e232eac199ed189fcdd7b
/dto/src/main/java/com/vivian/kaixiaozao/dto/Content.java
27f8b0b146aea38d2186ba9d99aa8f47459444f6
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
IssacChueng/kaixiaozao
https://github.com/IssacChueng/kaixiaozao
5a926f06a8ff0c17bb976d85044cf4bacd83fd7b
9f08224e655ead1b042d7d194dcb231565d3edd9
refs/heads/master
2018-11-04T04:33:30.310000
2018-08-26T12:28:53
2018-08-26T12:28:53
90,992,562
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.vivian.kaixiaozao.dto; import lombok.Data; @Data public class Content { /** * 内容, 0表示文字,1表示图片,2表示视频 */ private int type; /** * 文字,或者图片地址,或者视频地址 */ private String words; }
UTF-8
Java
281
java
Content.java
Java
[]
null
[]
package com.vivian.kaixiaozao.dto; import lombok.Data; @Data public class Content { /** * 内容, 0表示文字,1表示图片,2表示视频 */ private int type; /** * 文字,或者图片地址,或者视频地址 */ private String words; }
281
0.577778
0.564444
19
10.842105
11.165092
34
false
false
0
0
0
0
0
0
0.473684
false
false
7
2cd3a8dd75b74d049c5359f8110918ad9b0460de
27,247,272,531,422
8f88aa8b80618d4be0fa0b9b87bd6e0ac08d1c17
/Day2/MyCollectionDemoProject/src/com/sujata/setdemos/MyTreeSetDemoForCustomDefinedObjectType2.java
c15e528f611b687ec4d5120a666774d39d075c4e
[]
no_license
Sujatabatra/WileyMThreeC112
https://github.com/Sujatabatra/WileyMThreeC112
0f12a48e5352d80b262a036b705f87232f0f3d0c
65d7e942ad40c10a7ed6eaa6d45054509cb1dfad
refs/heads/main
2023-06-16T23:16:24.632000
2021-07-15T12:27:59
2021-07-15T12:27:59
372,477,462
9
5
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.sujata.setdemos; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.Set; import java.util.TreeSet; public class MyTreeSetDemoForCustomDefinedObjectType2 { public static void main(String[] args) { Set<MyBook> mySet=new TreeSet<MyBook>(new SortByNoOfPages()); mySet.add(new MyBook(101, "Book1", "Author A", 780, 800)); mySet.add(new MyBook(102, "Book2", "Author B", 810, 900)); mySet.add(new MyBook(103, "Book3", "Author C", 7800, 1800)); mySet.add(new MyBook(104, "Book4", "Author D", 1000, 1200)); System.out.println("Size of mySet : "+mySet.size()); System.out.println(mySet); mySet.add(new MyBook(101, "Book1", "Author A", 780, 800)); mySet.add(new MyBook(105, "Book5", "Author E", 900, 8100)); mySet.add(new MyBook(106, "Book6", "Author F", 340, 700)); System.out.println("Size of mySet : "+mySet.size()); System.out.println("Traversal using for each loop"); for(MyBook element: mySet) { System.out.println(element); } System.out.println("Traversal Uaing Iterator"); //Factory Design Pattern : because we are not creating the iterator object with new but iterator() method is creating the object for us Iterator<MyBook> iterator=mySet.iterator(); while(iterator.hasNext()) { System.out.println(iterator.next()); } } }
UTF-8
Java
1,405
java
MyTreeSetDemoForCustomDefinedObjectType2.java
Java
[]
null
[]
package com.sujata.setdemos; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.Set; import java.util.TreeSet; public class MyTreeSetDemoForCustomDefinedObjectType2 { public static void main(String[] args) { Set<MyBook> mySet=new TreeSet<MyBook>(new SortByNoOfPages()); mySet.add(new MyBook(101, "Book1", "Author A", 780, 800)); mySet.add(new MyBook(102, "Book2", "Author B", 810, 900)); mySet.add(new MyBook(103, "Book3", "Author C", 7800, 1800)); mySet.add(new MyBook(104, "Book4", "Author D", 1000, 1200)); System.out.println("Size of mySet : "+mySet.size()); System.out.println(mySet); mySet.add(new MyBook(101, "Book1", "Author A", 780, 800)); mySet.add(new MyBook(105, "Book5", "Author E", 900, 8100)); mySet.add(new MyBook(106, "Book6", "Author F", 340, 700)); System.out.println("Size of mySet : "+mySet.size()); System.out.println("Traversal using for each loop"); for(MyBook element: mySet) { System.out.println(element); } System.out.println("Traversal Uaing Iterator"); //Factory Design Pattern : because we are not creating the iterator object with new but iterator() method is creating the object for us Iterator<MyBook> iterator=mySet.iterator(); while(iterator.hasNext()) { System.out.println(iterator.next()); } } }
1,405
0.668327
0.614235
45
29.222221
28.740904
137
false
false
0
0
0
0
0
0
2.488889
false
false
7
06e7ff7fe1674c5bfdbeb22928ee162bf6cf162b
1,219,770,721,516
389875e4a65b16ed8ffb946223ff08a645e17ef9
/core/src/main/java/hpms/mdm/service/IDiscountProService.java
739b02385bf0b60294607557fac3f2569e1a92d9
[]
no_license
cckmit/hpms
https://github.com/cckmit/hpms
dd59777ee48164f146d7468448d0a791843582cd
d07a5e5d6df29f54f0cb0622aab50f2908ce954f
refs/heads/master
2023-03-16T19:01:00.133000
2017-03-03T07:48:09
2017-03-03T07:48:09
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package hpms.mdm.service; import java.util.List; import com.hand.hap.core.IRequest; import com.hand.hap.core.ProxySelf; import com.hand.hap.system.service.IBaseService; import hpms.mdm.dto.DiscountPro; /** * * @name IDiscountProService * @description 优惠方案Service * @author chengye.hu@hand-china.com 2017年2月24日上午10:33:44 * @version 1.0 */ public interface IDiscountProService extends IBaseService<DiscountPro>,ProxySelf<DiscountPro>{ /** * 根据条件查询discountPro * @author chengye.hu@hand-china.com * @param requestContext 请求 * @param discountPro 封装参数对象 * @param page 查询页 * @param pageSize 页面大小 * @return List<DiscountPro> 所有符合的结果集 */ List<DiscountPro> discountProQuery(IRequest requestContext, DiscountPro discountPro, int page, int pageSize); }
UTF-8
Java
906
java
IDiscountProService.java
Java
[ { "context": "roService\r\n * @description 优惠方案Service\r\n * @author chengye.hu@hand-china.com\t2017年2月24日上午10:33:44\r\n * @version 1.0\r\n */\r\npubli", "end": 319, "score": 0.9999253749847412, "start": 294, "tag": "EMAIL", "value": "chengye.hu@hand-china.com" }, { "context": "{\r\n\t/**\r\n * 根据条件查询discountPro \r\n * @author chengye.hu@hand-china.com\r\n * @param requestContext 请求\r\n * @param ", "end": 533, "score": 0.9999253749847412, "start": 508, "tag": "EMAIL", "value": "chengye.hu@hand-china.com" } ]
null
[]
package hpms.mdm.service; import java.util.List; import com.hand.hap.core.IRequest; import com.hand.hap.core.ProxySelf; import com.hand.hap.system.service.IBaseService; import hpms.mdm.dto.DiscountPro; /** * * @name IDiscountProService * @description 优惠方案Service * @author <EMAIL> 2017年2月24日上午10:33:44 * @version 1.0 */ public interface IDiscountProService extends IBaseService<DiscountPro>,ProxySelf<DiscountPro>{ /** * 根据条件查询discountPro * @author <EMAIL> * @param requestContext 请求 * @param discountPro 封装参数对象 * @param page 查询页 * @param pageSize 页面大小 * @return List<DiscountPro> 所有符合的结果集 */ List<DiscountPro> discountProQuery(IRequest requestContext, DiscountPro discountPro, int page, int pageSize); }
870
0.704819
0.686747
29
26.620689
26.068098
110
false
false
0
0
0
0
0
0
0.482759
false
false
7
91211289cfecd0a21bdb0a89ba70cd7279b9ec9f
1,219,770,724,002
df33522af608c7867cb3d7e08b8895e552a03bb8
/app/src/main/java/com/example/narasim/jm_solution_client/ViewComplaintActivity.java
0ee1d90c9d0468de4c0c463f35eb9258a60c6fdb
[]
no_license
Narasim0406/android_mysql_CRUD_recycleview_client
https://github.com/Narasim0406/android_mysql_CRUD_recycleview_client
37dc7839e999e6acb72a58afe6e3a6abc1759d1a
e07e537a72fd36e85357fc1588573b23f38d94da
refs/heads/master
2020-03-22T23:50:20.439000
2018-07-13T11:17:09
2018-07-13T11:17:09
140,830,967
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.narasim.jm_solution_client; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; public class ViewComplaintActivity extends AppCompatActivity { TextView textViewId, textViewUsername; EditText editTextId, editTextUsername, editTextHint, spinnerTextFeed; String GetId; Button buttonSubmit ; String DataParseUrl = "http://arunraaza.com/android/product/serviceview.php"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_view_complaint); getSupportActionBar().setDisplayHomeAsUpEnabled(true); // // if (!SharedPrefManager.getInstance(this).isLoggedIn()) { // finish(); // startActivity(new Intent(this, LoginActivity.class)); // } // // textViewId = (TextView) findViewById(R.id.textViewId); // editTextId = (EditText)findViewById(R.id.textViewId); // // User user = SharedPrefManager.getInstance(this).getUser(); // // textViewId.setText(String.valueOf(user.getId())); //// // buttonSubmit = (Button)findViewById(R.id.progress); //// // findViewById(R.id.progress).setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View view) { // GetDataFromEditText(); // SendDataToServer(GetId); // } // }); //// // //if user presses on not registered // findViewById(R.id.progress).setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View view) { // //open register screen // finish(); // startActivity(new Intent(getApplicationContext(), ProgressComplaintActivity.class)); // } // }); //// // } //// // public void GetDataFromEditText(){ //// // GetId = (editTextId).getText().toString(); //// // } // // // //sync============================================ //// // public void SendDataToServer(final String id){ // // // class SendPostReqAsyncTask extends AsyncTask<String, Void, String> { // @Override // protected String doInBackground(String... params) { // // String QuickId = id; // // List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); // // nameValuePairs.add(new BasicNameValuePair("id", QuickId)); // // try { // HttpClient httpClient = new DefaultHttpClient(); // // HttpPost httpPost = new HttpPost(DataParseUrl); // // httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); // // HttpResponse response = httpClient.execute(httpPost); // // HttpEntity entity = response.getEntity(); // // // } catch (ClientProtocolException e) { // // } catch (IOException e) { // // } // return "Data Submit Successfully"; // } // // @Override // protected void onPostExecute(String result) { // super.onPostExecute(result); // // // } // } // SendPostReqAsyncTask sendPostReqAsyncTask = new SendPostReqAsyncTask(); // sendPostReqAsyncTask.execute(id); } //=============================================================================== // completed complaints public void ViewCompleted(View view1) { if(view1.getId() == R.id.completed) { Intent i = new Intent(ViewComplaintActivity.this, ViewAllProduct.class); startActivity(i); } } ////progressing Complaints public void ViewProgress(View view2) { if(view2.getId() == R.id.progress) { Intent i = new Intent(ViewComplaintActivity.this, ViewAllService.class); startActivity(i); } } //Cancelled Complaints // public void ViewCancelled(View view3) { // // if(view3.getId() == R.id.cancelled) // { // Intent i = new Intent(ViewComplaintActivity.this, CancelledComplaintActivity.class); // startActivity(i); // } // // } // public void ViewDetail(View view) { // Intent i = new Intent(ViewComplaintActivity.this, FeedBack.class); // startActivity(i); // } }
UTF-8
Java
4,611
java
ViewComplaintActivity.java
Java
[ { "context": "package com.example.narasim.jm_solution_client;\n\nimport android.content.Inten", "end": 27, "score": 0.9956917762756348, "start": 20, "tag": "USERNAME", "value": "narasim" } ]
null
[]
package com.example.narasim.jm_solution_client; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; public class ViewComplaintActivity extends AppCompatActivity { TextView textViewId, textViewUsername; EditText editTextId, editTextUsername, editTextHint, spinnerTextFeed; String GetId; Button buttonSubmit ; String DataParseUrl = "http://arunraaza.com/android/product/serviceview.php"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_view_complaint); getSupportActionBar().setDisplayHomeAsUpEnabled(true); // // if (!SharedPrefManager.getInstance(this).isLoggedIn()) { // finish(); // startActivity(new Intent(this, LoginActivity.class)); // } // // textViewId = (TextView) findViewById(R.id.textViewId); // editTextId = (EditText)findViewById(R.id.textViewId); // // User user = SharedPrefManager.getInstance(this).getUser(); // // textViewId.setText(String.valueOf(user.getId())); //// // buttonSubmit = (Button)findViewById(R.id.progress); //// // findViewById(R.id.progress).setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View view) { // GetDataFromEditText(); // SendDataToServer(GetId); // } // }); //// // //if user presses on not registered // findViewById(R.id.progress).setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View view) { // //open register screen // finish(); // startActivity(new Intent(getApplicationContext(), ProgressComplaintActivity.class)); // } // }); //// // } //// // public void GetDataFromEditText(){ //// // GetId = (editTextId).getText().toString(); //// // } // // // //sync============================================ //// // public void SendDataToServer(final String id){ // // // class SendPostReqAsyncTask extends AsyncTask<String, Void, String> { // @Override // protected String doInBackground(String... params) { // // String QuickId = id; // // List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); // // nameValuePairs.add(new BasicNameValuePair("id", QuickId)); // // try { // HttpClient httpClient = new DefaultHttpClient(); // // HttpPost httpPost = new HttpPost(DataParseUrl); // // httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); // // HttpResponse response = httpClient.execute(httpPost); // // HttpEntity entity = response.getEntity(); // // // } catch (ClientProtocolException e) { // // } catch (IOException e) { // // } // return "Data Submit Successfully"; // } // // @Override // protected void onPostExecute(String result) { // super.onPostExecute(result); // // // } // } // SendPostReqAsyncTask sendPostReqAsyncTask = new SendPostReqAsyncTask(); // sendPostReqAsyncTask.execute(id); } //=============================================================================== // completed complaints public void ViewCompleted(View view1) { if(view1.getId() == R.id.completed) { Intent i = new Intent(ViewComplaintActivity.this, ViewAllProduct.class); startActivity(i); } } ////progressing Complaints public void ViewProgress(View view2) { if(view2.getId() == R.id.progress) { Intent i = new Intent(ViewComplaintActivity.this, ViewAllService.class); startActivity(i); } } //Cancelled Complaints // public void ViewCancelled(View view3) { // // if(view3.getId() == R.id.cancelled) // { // Intent i = new Intent(ViewComplaintActivity.this, CancelledComplaintActivity.class); // startActivity(i); // } // // } // public void ViewDetail(View view) { // Intent i = new Intent(ViewComplaintActivity.this, FeedBack.class); // startActivity(i); // } }
4,611
0.572544
0.571026
163
27.288343
27.950817
102
false
false
0
0
0
0
86
0.018651
0.386503
false
false
7
3455896ea7f04be483e9886169ecac589370e593
6,837,587,945,690
cccc8a6a09916729814f36bc5ca2cff297a44916
/campingszwaenepoel-presentation/src/main/java/be/camping/campingzwaenepoel/presentation/pdf/Fiche.java
92612b72c90b799e595bf5f37568ef7dbc5f294d
[]
no_license
GlWy/campingszwaenepoel
https://github.com/GlWy/campingszwaenepoel
5895b3fcca1f6f49a348d182fd6537b76fd98568
7299322aa04555046aad76fdbccd227e4b591968
refs/heads/master
2022-05-27T19:14:51.012000
2022-05-24T11:58:06
2022-05-24T11:58:06
57,395,110
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package be.camping.campingzwaenepoel.presentation.pdf; import java.awt.Color; import java.awt.print.PrinterException; import java.awt.print.PrinterJob; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import javax.print.PrintService; import javax.print.PrintServiceLookup; import org.apache.commons.lang.StringUtils; import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.printing.PDFPageable; import com.lowagie.text.Document; import com.lowagie.text.DocumentException; import com.lowagie.text.PageSize; import com.lowagie.text.pdf.BaseFont; import com.lowagie.text.pdf.PdfContentByte; import com.lowagie.text.pdf.PdfWriter; import com.lowagie.tools.Executable; import be.camping.campingzwaenepoel.common.enums.GezinsPositieEnum; import be.camping.campingzwaenepoel.common.enums.SoortHuurderEnum; import be.camping.campingzwaenepoel.service.transfer.InschrijvingDTO; import be.camping.campingzwaenepoel.service.transfer.InschrijvingPersoonDTO; import be.camping.campingzwaenepoel.service.transfer.WagenDTO; public class Fiche { // Fiche headers private final String fiche1 = "Karte-Fiche"; private final String fiche2 = "Karte-form"; private String nummer = "N�"; private final String headerNL = "KONTROLE VAN REIZIGERS OP KAMPEERTERREINEN"; private final String headerFR = "CONTROLE DES VOYAGEURS DANS LES CAMPINGS"; private final String headerDU = "AUFSICHT UBER DIE REISENDEN IN CAMPING"; private final String headerEng = "INSPECTION OF TRAVELLERS IN THE CAMPING"; // camping data private final String camping = "N.V. CAMPINGS ZWAENEPOEL"; private final String camping2 = "HOOFDZETEL - BUREAU CENTRALE"; private final String campingAdres = "Vosseslag 20/0005 - 8420 DE HAAN"; private final String campingContact = "TEL: 059/23.32.50 - WACHTDIENST: 059/77.07.07"; private final String campingContact2 = "FAX: 059/23.66.37 - E-mail: camping.zwaenepoel@telenet.be"; // inschrijvingsgegevens private final String aankomst = "Datum van aankomst: "; private final String vertrek = "Werkelijke vertrekdatum (3): "; private String aankomstDatum = ""; private String vertrekDatum = ""; private final String aanwezigen = "Aanwezige mensen:"; private String hoofd = "Gezinshoofd:"; private String naam = ""; private String voornaamHoofd = ""; private String voornaamEcht = ""; private String voornaamKind = ""; private final List<String> namenMedeHuurders = new ArrayList<String>(); private String woonplaats = ""; private String straat = ""; private String huisnummer = ""; private String postcode = ""; private String nrplaat = ""; private String echtgenote = ""; private String aantalOngehKind = ""; private final String uitleg12 = "(1) In drukletters - (2) De juistheid van die inlichting moet door de exploitant niet worden nagegaan"; private final String uitleg3 = "(3) Alleen te vermelden op het dubbel van de kaart"; private final String bevestiging1 = "Ik ben op de hoogte van de campingregels"; private final String bevestiging2 = "en ik teken voor akkoord."; private final String bevestiging1Tr = "Je suis au courant de règles de camping"; private final String bevestiging2Tr = "et je signe pour accord."; private String standplaats = ""; private final String NUMMER_WACHTDIENST = "059/77.07.07"; private final int Y_OFFSET = -5; public Fiche(final SoortHuurderEnum soortHuurderEnum) { if (SoortHuurderEnum.LOS.equals(soortHuurderEnum)) { hoofd = "Verantwoordelijke:"; } } public void createDocument(String standplaats, InschrijvingDTO inschrijving, String printerZwaarNaam, String printerLichtNaam, String computerNamesForPrinting) throws DocumentException, IOException, PrinterException { File tmpDir = new File("/tmp"); if (!tmpDir.exists()) { tmpDir.mkdir(); } String name = "/tmp/fiche" + System.nanoTime() + ".pdf"; Document document = new Document(PageSize.A4.rotate()); PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(name)); document.open(); PdfContentByte cb = writer.getDirectContent(); // set data setData(standplaats, inschrijving); if (inschrijving.getSoorthuurder().equals(SoortHuurderEnum.LOS)) { createDataLos(cb, inschrijving); } else if (inschrijving.getSoorthuurder().equals(SoortHuurderEnum.VAST)) { createDataVast(document, cb, standplaats, inschrijving); } document.close(); if (computerNamesForPrinting != null && computerNamesForPrinting.contains(inschrijving.getComputer()) && !StringUtils.isEmpty(printerZwaarNaam) && !StringUtils.isEmpty(printerLichtNaam)) { PDDocument pdDocument = null; try { pdDocument = PDDocument.load(new File(name)); String printerName = SoortHuurderEnum.LOS.equals(inschrijving.getSoorthuurder()) ? printerLichtNaam : printerZwaarNaam; PrintService myPrintService = findPrintService(printerName); PrinterJob job = PrinterJob.getPrinterJob(); job.setPageable(new PDFPageable(pdDocument)); job.setPrintService(myPrintService); job.print(); } catch (Exception e) { Executable.openDocument(name); } finally { if (pdDocument != null) { pdDocument.close(); } } } else { Executable.openDocument(name); } } private static PrintService findPrintService(String printerName) { PrintService[] printServices = PrintServiceLookup.lookupPrintServices(null, null); for (PrintService printService : printServices) { if (printService.getName().trim().equals(printerName)) { return printService; } } return null; } private void createDataVast(Document document, PdfContentByte cb, String standplaats, InschrijvingDTO inschrijving) throws DocumentException, IOException { int centerOffset = 240; String year = Integer.toString(Calendar.getInstance().get(Calendar.YEAR)); boolean isLeftBoxWriten = false; boolean isFirstPageWritten = false; for (InschrijvingPersoonDTO inschrijvingPersoon : inschrijving.getInschrijvingPersonen()) { if ( inschrijvingPersoon.getPersoon().getWagens() != null && !inschrijvingPersoon.getPersoon().getWagens().isEmpty()) { isLeftBoxWriten = true; for (WagenDTO wagen : inschrijvingPersoon.getPersoon().getWagens()) { if (isFirstPageWritten) { document.newPage(); } else { isFirstPageWritten = true; } // right box insertTextInBox(cb, 517, inschrijving.getSoorthuurder()); // writeLeftBox(cb, inschrijving); cb.beginText(); cb.setColorFill(Color.BLUE); BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); cb.setFontAndSize(bf, 80); cb.showTextAligned(PdfContentByte.ALIGN_CENTER, standplaats, centerOffset, 400, 0); cb.showTextAligned(PdfContentByte.ALIGN_CENTER, year, centerOffset, 200, 0); bf = BaseFont.createFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); cb.setFontAndSize(bf, 70); cb.showTextAligned(PdfContentByte.ALIGN_CENTER, wagen.getNummerplaat(), centerOffset, 300, 0); // draw boxes drawBox(cb, 520, Y_OFFSET); drawBox(cb, 557, Y_OFFSET + 40, 778, Y_OFFSET + 170, Color.RED); drawBox(cb, centerOffset - 200, 360, centerOffset + 237, 270, Color.BLUE); cb.endText(); } } } if (!isLeftBoxWriten) { writeLeftBox(cb, inschrijving); } } private void createDataLos(PdfContentByte cb, InschrijvingDTO inschrijving) throws DocumentException, IOException { // left box writeLeftBox(cb, inschrijving); // right box insertTextInBox(cb, 520, inschrijving.getSoorthuurder()); // center box insertTextInCentre(cb, 320); // draw boxes drawBox(cb, 520, Y_OFFSET - 5); drawBox(cb, 560, Y_OFFSET + 60, 780, Y_OFFSET + 170, Color.RED); } private void writeLeftBox(PdfContentByte cb, InschrijvingDTO inschrijving) throws DocumentException, IOException { // left box drawBox(cb, 10, Y_OFFSET - 5); insertTextInBox(cb, 0, inschrijving.getSoorthuurder()); drawBox(cb, 40, Y_OFFSET + 60, 260, Y_OFFSET + 170, Color.RED); } private void drawBox(PdfContentByte cb, int x1, int y1) { drawBox(cb, x1, y1 + 20, x1 + 310, y1 + 595); } private void drawBox(PdfContentByte cb, int x1, int y1, int x2, int y2) { cb.setLineWidth(1f); cb.setColorStroke(Color.lightGray); cb.moveTo(x1, y1); cb.lineTo(x2, y1); cb.lineTo(x2, y2); cb.lineTo(x1, y2); cb.lineTo(x1, y1); cb.stroke(); } private void drawBox(PdfContentByte cb, int x1, int y1, int x2, int y2, Color color) { cb.setLineWidth(1f); cb.setColorStroke(color); cb.moveTo(x1, y1); cb.lineTo(x2, y1); cb.lineTo(x2, y2); cb.lineTo(x1, y2); cb.lineTo(x1, y1); cb.stroke(); } private void drawLine(PdfContentByte cb, int x1, int y1, int x2, int y2) { cb.setLineWidth(1f); cb.setColorStroke(Color.lightGray); cb.moveTo(x1, y1); cb.lineTo(x2, y2); cb.stroke(); } private void setData(String plaats, InschrijvingDTO inschrijving) { standplaats = plaats; DateFormat formatter; formatter = new SimpleDateFormat("dd-MM-yyyy"); aankomstDatum = formatter.format(inschrijving.getDateVan()); vertrekDatum = formatter.format(inschrijving.getDateTot()); if (inschrijving.getFichenummer() > 0) { nummer += inschrijving.getFichenummer(); } else { nummer = ""; } for (InschrijvingPersoonDTO inschrijvingPersoon : inschrijving.getInschrijvingPersonen()) { if (GezinsPositieEnum.HOOFD.equals(inschrijvingPersoon.getGezinsPositie())) { naam = inschrijvingPersoon.getPersoon().getNaam(); voornaamHoofd = inschrijvingPersoon.getPersoon().getVoornaam(); if (inschrijvingPersoon.getPersoon().getAdresDTO().getStraat() != null) straat = inschrijvingPersoon.getPersoon().getAdresDTO().getStraat(); if (inschrijvingPersoon.getPersoon().getAdresDTO().getHuisnummer() != null) huisnummer = inschrijvingPersoon.getPersoon().getAdresDTO().getHuisnummer(); if (!StringUtils.isEmpty(inschrijvingPersoon.getPersoon().getAdresDTO().getBus())) { huisnummer += " - " + inschrijvingPersoon.getPersoon().getAdresDTO().getBus(); } if (inschrijvingPersoon.getPersoon().getAdresDTO().getPlaats() != null) woonplaats = inschrijvingPersoon.getPersoon().getAdresDTO().getPlaats(); if (inschrijvingPersoon.getPersoon().getAdresDTO().getPostcode() != null) postcode = inschrijvingPersoon.getPersoon().getAdresDTO().getPostcode(); for (WagenDTO wagen : inschrijvingPersoon.getPersoon().getWagens()) { nrplaat = wagen.getNummerplaat(); break; } break; } } if (SoortHuurderEnum.VAST.equals(inschrijving.getSoorthuurder())) { for (InschrijvingPersoonDTO inschrijvingPersoon : inschrijving.getInschrijvingPersonen()) { if (GezinsPositieEnum.ECHTGENOTE.equals(inschrijvingPersoon.getGezinsPositie())) { echtgenote = inschrijvingPersoon.getPersoon().getNaam(); voornaamEcht = inschrijvingPersoon.getPersoon().getVoornaam(); break; } } } int aantalkinderen = 0; List<String> tmpNamen = new ArrayList<>(); for (InschrijvingPersoonDTO inschrijvingPersoon : inschrijving.getInschrijvingPersonen()) { if (GezinsPositieEnum.HOOFD.equals(inschrijvingPersoon.getGezinsPositie()) || (GezinsPositieEnum.ECHTGENOTE.equals(inschrijvingPersoon.getGezinsPositie()) && SoortHuurderEnum.VAST .equals(inschrijving.getSoorthuurder()))) { continue; } if (aantalkinderen > 0) { voornaamKind += ", "; } voornaamKind += inschrijvingPersoon.getPersoon().getVoornaam(); tmpNamen.add(inschrijvingPersoon.getPersoon().getVoornaam() + " " + inschrijvingPersoon.getPersoon().getNaam()); aantalkinderen++; // } } prepareListNamen(tmpNamen); if (aantalkinderen > 0) { aantalOngehKind = Integer.toString(aantalkinderen); } else { aantalOngehKind = "GEEN KINDEREN"; } } private void prepareListNamen(final List<String> tmpNamen) { String line = ""; for (final String naam : tmpNamen) { if (line.length() > 0) { line += ", "; } line += naam; final int index = tmpNamen.indexOf(naam); if (index == 0 || index == tmpNamen.size() - 1 || index % 2 == 0) { namenMedeHuurders.add(line); line = ""; } } } private void insertTextInCentre(PdfContentByte cb, int offset) throws DocumentException, IOException { drawBox(cb, offset + 10, Y_OFFSET + 560, offset + 130, Y_OFFSET + 590); BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); cb.setFontAndSize(bf, 18); cb.beginText(); cb.showTextAligned(PdfContentByte.ALIGN_CENTER, standplaats, 65 + offset, Y_OFFSET + 567, 0); bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); cb.setFontAndSize(bf, 10); offset += 25; cb.setColorFill(Color.RED); cb.showTextAligned(PdfContentByte.ALIGN_CENTER, "LISPANNE", offset + 60, 482, 0); cb.setColorFill(Color.BLACK); cb.showTextAligned(PdfContentByte.ALIGN_LEFT, "VOSSESLAG 20", offset, 458, 0); cb.showTextAligned(PdfContentByte.ALIGN_LEFT, "8420 DE HAAN", offset, 442, 0); cb.showTextAligned(PdfContentByte.ALIGN_LEFT, "059/23.39.75", offset, 428, 0); cb.showTextAligned(PdfContentByte.ALIGN_LEFT, "WACHTDIENST: " + NUMMER_WACHTDIENST, offset, 414, 0); drawLine(cb, offset, 412, offset + 75, 412); cb.setColorFill(Color.RED); cb.showTextAligned(PdfContentByte.ALIGN_CENTER, "CAPRI", offset + 60, 375, 0); cb.setColorFill(Color.BLACK); cb.showTextAligned(PdfContentByte.ALIGN_LEFT, "DRIFTWEG 157", offset, 351, 0); cb.showTextAligned(PdfContentByte.ALIGN_LEFT, "8420 DE HAAN", offset, 335, 0); cb.showTextAligned(PdfContentByte.ALIGN_LEFT, "059/23.45.45.", offset, 319, 0); cb.showTextAligned(PdfContentByte.ALIGN_LEFT, "WACHTDIENST: " + NUMMER_WACHTDIENST, offset, 303, 0); drawLine(cb, offset, 301, offset + 75, 301); cb.setColorFill(Color.RED); cb.showTextAligned(PdfContentByte.ALIGN_CENTER, "HIPPODROOM", offset + 60, 260, 0); cb.setColorFill(Color.BLACK); cb.showTextAligned(PdfContentByte.ALIGN_LEFT, "DUINDOORNSTRAAT 25", offset, 236, 0); cb.showTextAligned(PdfContentByte.ALIGN_LEFT, "8450 BREDENE", offset, 220, 0); cb.showTextAligned(PdfContentByte.ALIGN_LEFT, "059/32.07.91", offset, 204, 0); cb.showTextAligned(PdfContentByte.ALIGN_LEFT, "WACHTDIENST: " + NUMMER_WACHTDIENST, offset, 188, 0); drawLine(cb, offset, 186, offset + 75, 186); cb.endText(); } private void insertTextInBox(PdfContentByte cb, int offset, SoortHuurderEnum soortHuurderEnum) throws DocumentException, IOException { int offsetXUitleg = 25; int offsetXData = 25; int offsetXRightAlign = 280; BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); cb.beginText(); cb.setFontAndSize(bf, 7); // Karte - fiche cb.showTextAligned(PdfContentByte.ALIGN_LEFT, fiche1, 50 + offset, Y_OFFSET + 575, 0); cb.showTextAligned(PdfContentByte.ALIGN_LEFT, fiche2, 50 + offset, Y_OFFSET + 567, 0); // CONTROLE DES VOYAGEURS DAN LES CAMPINGS cb.showTextAligned(PdfContentByte.ALIGN_CENTER, headerFR, 150 + offset, Y_OFFSET + 544, 0); // AUFSICHT UBER DIE REISENDEN IN CAMPING cb.showTextAligned(PdfContentByte.ALIGN_CENTER, headerDU, 150 + offset, Y_OFFSET + 536, 0); // INSPECTION OF TRAVELLERS IN THE CAMPING cb.showTextAligned(PdfContentByte.ALIGN_CENTER, headerEng, 150 + offset, Y_OFFSET + 528, 0); cb.setFontAndSize(bf, 9); bf = BaseFont.createFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); // NV CAMPING ZWAENEPOEL cb.setColorFill(Color.RED); cb.showTextAligned(PdfContentByte.ALIGN_CENTER, camping, 155 + offset, Y_OFFSET + 509, 0); cb.setColorFill(Color.BLACK); cb.showTextAligned(PdfContentByte.ALIGN_CENTER, camping2, 155 + offset, Y_OFFSET + 497, 0); // Vosseslag 20 - 8420 De Haan cb.showTextAligned(PdfContentByte.ALIGN_CENTER, campingAdres, 155 + offset, Y_OFFSET + 485, 0); // Tel: 059/23 39 75 - Wachtdienst: 0477/28 37 96 cb.showTextAligned(PdfContentByte.ALIGN_CENTER, campingContact, 155 + offset, Y_OFFSET + 473, 0); cb.showTextAligned(PdfContentByte.ALIGN_CENTER, campingContact2, 155 + offset, Y_OFFSET + 461, 0); cb.setFontAndSize(bf, 7); cb.setColorFill(Color.RED); cb.showTextAligned(PdfContentByte.ALIGN_CENTER, bevestiging1, 150 + offset, 155, 0); cb.showTextAligned(PdfContentByte.ALIGN_CENTER, bevestiging2, 150 + offset, 145, 0); cb.showTextAligned(PdfContentByte.ALIGN_CENTER, bevestiging1Tr, 150 + offset, 70, 0); cb.showTextAligned(PdfContentByte.ALIGN_CENTER, bevestiging2Tr, 150 + offset, 60, 0); cb.setColorFill(Color.BLACK); drawLine(cb, 20 + offset, Y_OFFSET + 520, 300 + offset, Y_OFFSET + 520); drawLine(cb, 20 + offset, Y_OFFSET + 451, 300 + offset, Y_OFFSET + 451); bf = BaseFont.createFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); cb.setFontAndSize(bf, 9); // KONTROLE VAN REIZIGERS OP KAMPEERTERREINEN cb.showTextAligned(PdfContentByte.ALIGN_CENTER, headerNL, 150 + offset, Y_OFFSET + 552, 0); cb.setFontAndSize(bf, 8); // Aankomst cb.showTextAligned(PdfContentByte.ALIGN_LEFT, aankomst, offsetXData + offset, Y_OFFSET + 438, 0); // aankomst datum cb.showTextAligned(PdfContentByte.ALIGN_RIGHT, aankomstDatum, offsetXData + offset + offsetXRightAlign, Y_OFFSET + 438, 0); // Vertrek cb.showTextAligned(PdfContentByte.ALIGN_LEFT, vertrek, offsetXData + offset, Y_OFFSET + 420, 0); // vertrek datum cb.showTextAligned(PdfContentByte.ALIGN_RIGHT, vertrekDatum, offsetXData + offset + offsetXRightAlign, Y_OFFSET + 420, 0); // Nummerplaat van het voertuig (3): : cb.showTextAligned(PdfContentByte.ALIGN_LEFT, "Nummerplaat van het voertuig (2)", offsetXData + offset, Y_OFFSET + 402, 0); cb.showTextAligned(PdfContentByte.ALIGN_RIGHT, nrplaat, offsetXData + offset + offsetXRightAlign, Y_OFFSET + 402, 0); // Straat cb.showTextAligned(PdfContentByte.ALIGN_LEFT, "Straat: ", offsetXData + offset, Y_OFFSET + 382, 0); cb.showTextAligned(PdfContentByte.ALIGN_RIGHT, straat, offsetXData + offset + offsetXRightAlign, Y_OFFSET + 382, 0); // Nummer cb.showTextAligned(PdfContentByte.ALIGN_LEFT, "Nummer: ", offsetXData + offset, Y_OFFSET + 364, 0); cb.showTextAligned(PdfContentByte.ALIGN_RIGHT, huisnummer, offsetXData + offset + offsetXRightAlign, Y_OFFSET + 364, 0); // postcode cb.showTextAligned(PdfContentByte.ALIGN_LEFT, "Postcode: ", offsetXData + offset, Y_OFFSET + 346, 0); cb.showTextAligned(PdfContentByte.ALIGN_RIGHT, postcode, offsetXData + offset + offsetXRightAlign, Y_OFFSET + 346, 0); // plaats cb.showTextAligned(PdfContentByte.ALIGN_LEFT, "Woonplaats: ", offsetXData + offset, Y_OFFSET + 328, 0); cb.showTextAligned(PdfContentByte.ALIGN_RIGHT, woonplaats, offsetXData + offset + offsetXRightAlign, Y_OFFSET + 328, 0); // Aanwezige mensen cb.showTextAligned(PdfContentByte.ALIGN_LEFT, aanwezigen, offsetXData + offset, Y_OFFSET + 307, 0); // Hoofd: cb.showTextAligned(PdfContentByte.ALIGN_LEFT, hoofd, offsetXData + 10 + offset, Y_OFFSET + 291, 0); // Naam cb.showTextAligned(PdfContentByte.ALIGN_LEFT, "Naam (1): ", offsetXData + 10 + offset, Y_OFFSET + 273, 0); cb.showTextAligned(PdfContentByte.ALIGN_RIGHT, naam, offsetXData + offset + offsetXRightAlign, Y_OFFSET + 273, 0); // Voornaam cb.showTextAligned(PdfContentByte.ALIGN_LEFT, "Voornamen: ", offsetXData + 10 + offset, Y_OFFSET + 255, 0); cb.showTextAligned(PdfContentByte.ALIGN_RIGHT, voornaamHoofd, offsetXData + offset + offsetXRightAlign, Y_OFFSET + 255, 0); if (SoortHuurderEnum.VAST.equals(soortHuurderEnum)) { // Echtgenote - meisjesnaam (1): cb.showTextAligned(PdfContentByte.ALIGN_LEFT, "Echtgenote - meisjesnaam (1): ", offsetXData + 10 + offset, Y_OFFSET + 238, 0); cb.showTextAligned(PdfContentByte.ALIGN_RIGHT, echtgenote, offsetXData + offset + offsetXRightAlign, Y_OFFSET + 238, 0); // Voornamen: cb.showTextAligned(PdfContentByte.ALIGN_LEFT, "Voornaam: ", offsetXData + 10 + offset, Y_OFFSET + 220, 0); cb.showTextAligned(PdfContentByte.ALIGN_RIGHT, voornaamEcht, offsetXData + offset + offsetXRightAlign, Y_OFFSET + 220, 0); // Aantal ongehuwde kinderen: GEEN KINDEREN cb.showTextAligned(PdfContentByte.ALIGN_LEFT, "Aantal ongehuwde kinderen: ", offsetXData + 10 + offset, Y_OFFSET + 202, 0); cb.showTextAligned(PdfContentByte.ALIGN_RIGHT, aantalOngehKind, offsetXData + offset + offsetXRightAlign, Y_OFFSET + 202, 0); // Voornaam cb.showTextAligned(PdfContentByte.ALIGN_LEFT, "Voornamen: ", offsetXData + 10 + offset, Y_OFFSET + 184, 0); cb.showTextAligned(PdfContentByte.ALIGN_RIGHT, voornaamKind, offsetXData + offset + offsetXRightAlign, Y_OFFSET + 184, 0); } else { // Namen mede huurders cb.showTextAligned(PdfContentByte.ALIGN_LEFT, "mede huurders: ", offsetXData + 10 + offset, Y_OFFSET + 238, 0); int yOffset = Y_OFFSET + 238; for (final String naam : namenMedeHuurders) { cb.showTextAligned(PdfContentByte.ALIGN_RIGHT, naam, offsetXData + offset + offsetXRightAlign, yOffset, 0); yOffset -= 18; } } // nummer N�26542 cb.setFontAndSize(bf, 18); cb.showTextAligned(PdfContentByte.ALIGN_LEFT, nummer, 90 + offset, Y_OFFSET + 567, 0); // Standplaats cb.showTextAligned(PdfContentByte.ALIGN_LEFT, standplaats, 190 + offset, Y_OFFSET + 567, 0); cb.setFontAndSize(bf, 6); // (1) In drukletters - (2) De juistheid van die inlichting moet door de // exploitant niet worden nagegaan cb.showTextAligned(PdfContentByte.ALIGN_LEFT, uitleg12, offsetXUitleg + offset, 30, 0); // (3) Alleen te vermelden op het dubbel van de kaart" cb.showTextAligned(PdfContentByte.ALIGN_LEFT, uitleg3, offsetXUitleg + offset, 22, 0); cb.endText(); } }
UTF-8
Java
25,128
java
Fiche.java
Java
[ { "context": " camping data\n private final String camping = \"N.V. CAMPINGS ZWAENEPOEL\";\n private final String ca", "end": 1758, "score": 0.9340417385101318, "start": 1755, "tag": "NAME", "value": "N.V" }, { "context": "ping data\n private final String camping = \"N.V. CAMPINGS ZWAENEPOEL\";\n private final String camping2 = \"HOOFDZETEL", "end": 1779, "score": 0.9311203360557556, "start": 1760, "tag": "NAME", "value": "CAMPINGS ZWAENEPOEL" }, { "context": "ing campingContact2 = \"FAX: 059/23.66.37 - E-mail: camping.zwaenepoel@telenet.be\";\n\n // inschrijvingsgegevens\n private final", "end": 2118, "score": 0.9998518228530884, "start": 2089, "tag": "EMAIL", "value": "camping.zwaenepoel@telenet.be" }, { "context": "252, BaseFont.NOT_EMBEDDED);\n // NV CAMPING ZWAENEPOEL\n cb.setColorFill(Color.RED);\n ", "end": 18008, "score": 0.5704243779182434, "start": 18007, "tag": "NAME", "value": "Z" }, { "context": " BaseFont.NOT_EMBEDDED);\n // NV CAMPING ZWAENEPOEL\n cb.setColorFill(Color.RED);\n c", "end": 18013, "score": 0.5332921147346497, "start": 18010, "tag": "NAME", "value": "ENE" } ]
null
[]
package be.camping.campingzwaenepoel.presentation.pdf; import java.awt.Color; import java.awt.print.PrinterException; import java.awt.print.PrinterJob; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import javax.print.PrintService; import javax.print.PrintServiceLookup; import org.apache.commons.lang.StringUtils; import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.printing.PDFPageable; import com.lowagie.text.Document; import com.lowagie.text.DocumentException; import com.lowagie.text.PageSize; import com.lowagie.text.pdf.BaseFont; import com.lowagie.text.pdf.PdfContentByte; import com.lowagie.text.pdf.PdfWriter; import com.lowagie.tools.Executable; import be.camping.campingzwaenepoel.common.enums.GezinsPositieEnum; import be.camping.campingzwaenepoel.common.enums.SoortHuurderEnum; import be.camping.campingzwaenepoel.service.transfer.InschrijvingDTO; import be.camping.campingzwaenepoel.service.transfer.InschrijvingPersoonDTO; import be.camping.campingzwaenepoel.service.transfer.WagenDTO; public class Fiche { // Fiche headers private final String fiche1 = "Karte-Fiche"; private final String fiche2 = "Karte-form"; private String nummer = "N�"; private final String headerNL = "KONTROLE VAN REIZIGERS OP KAMPEERTERREINEN"; private final String headerFR = "CONTROLE DES VOYAGEURS DANS LES CAMPINGS"; private final String headerDU = "AUFSICHT UBER DIE REISENDEN IN CAMPING"; private final String headerEng = "INSPECTION OF TRAVELLERS IN THE CAMPING"; // camping data private final String camping = "N.V. <NAME>"; private final String camping2 = "HOOFDZETEL - BUREAU CENTRALE"; private final String campingAdres = "Vosseslag 20/0005 - 8420 DE HAAN"; private final String campingContact = "TEL: 059/23.32.50 - WACHTDIENST: 059/77.07.07"; private final String campingContact2 = "FAX: 059/23.66.37 - E-mail: <EMAIL>"; // inschrijvingsgegevens private final String aankomst = "Datum van aankomst: "; private final String vertrek = "Werkelijke vertrekdatum (3): "; private String aankomstDatum = ""; private String vertrekDatum = ""; private final String aanwezigen = "Aanwezige mensen:"; private String hoofd = "Gezinshoofd:"; private String naam = ""; private String voornaamHoofd = ""; private String voornaamEcht = ""; private String voornaamKind = ""; private final List<String> namenMedeHuurders = new ArrayList<String>(); private String woonplaats = ""; private String straat = ""; private String huisnummer = ""; private String postcode = ""; private String nrplaat = ""; private String echtgenote = ""; private String aantalOngehKind = ""; private final String uitleg12 = "(1) In drukletters - (2) De juistheid van die inlichting moet door de exploitant niet worden nagegaan"; private final String uitleg3 = "(3) Alleen te vermelden op het dubbel van de kaart"; private final String bevestiging1 = "Ik ben op de hoogte van de campingregels"; private final String bevestiging2 = "en ik teken voor akkoord."; private final String bevestiging1Tr = "Je suis au courant de règles de camping"; private final String bevestiging2Tr = "et je signe pour accord."; private String standplaats = ""; private final String NUMMER_WACHTDIENST = "059/77.07.07"; private final int Y_OFFSET = -5; public Fiche(final SoortHuurderEnum soortHuurderEnum) { if (SoortHuurderEnum.LOS.equals(soortHuurderEnum)) { hoofd = "Verantwoordelijke:"; } } public void createDocument(String standplaats, InschrijvingDTO inschrijving, String printerZwaarNaam, String printerLichtNaam, String computerNamesForPrinting) throws DocumentException, IOException, PrinterException { File tmpDir = new File("/tmp"); if (!tmpDir.exists()) { tmpDir.mkdir(); } String name = "/tmp/fiche" + System.nanoTime() + ".pdf"; Document document = new Document(PageSize.A4.rotate()); PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(name)); document.open(); PdfContentByte cb = writer.getDirectContent(); // set data setData(standplaats, inschrijving); if (inschrijving.getSoorthuurder().equals(SoortHuurderEnum.LOS)) { createDataLos(cb, inschrijving); } else if (inschrijving.getSoorthuurder().equals(SoortHuurderEnum.VAST)) { createDataVast(document, cb, standplaats, inschrijving); } document.close(); if (computerNamesForPrinting != null && computerNamesForPrinting.contains(inschrijving.getComputer()) && !StringUtils.isEmpty(printerZwaarNaam) && !StringUtils.isEmpty(printerLichtNaam)) { PDDocument pdDocument = null; try { pdDocument = PDDocument.load(new File(name)); String printerName = SoortHuurderEnum.LOS.equals(inschrijving.getSoorthuurder()) ? printerLichtNaam : printerZwaarNaam; PrintService myPrintService = findPrintService(printerName); PrinterJob job = PrinterJob.getPrinterJob(); job.setPageable(new PDFPageable(pdDocument)); job.setPrintService(myPrintService); job.print(); } catch (Exception e) { Executable.openDocument(name); } finally { if (pdDocument != null) { pdDocument.close(); } } } else { Executable.openDocument(name); } } private static PrintService findPrintService(String printerName) { PrintService[] printServices = PrintServiceLookup.lookupPrintServices(null, null); for (PrintService printService : printServices) { if (printService.getName().trim().equals(printerName)) { return printService; } } return null; } private void createDataVast(Document document, PdfContentByte cb, String standplaats, InschrijvingDTO inschrijving) throws DocumentException, IOException { int centerOffset = 240; String year = Integer.toString(Calendar.getInstance().get(Calendar.YEAR)); boolean isLeftBoxWriten = false; boolean isFirstPageWritten = false; for (InschrijvingPersoonDTO inschrijvingPersoon : inschrijving.getInschrijvingPersonen()) { if ( inschrijvingPersoon.getPersoon().getWagens() != null && !inschrijvingPersoon.getPersoon().getWagens().isEmpty()) { isLeftBoxWriten = true; for (WagenDTO wagen : inschrijvingPersoon.getPersoon().getWagens()) { if (isFirstPageWritten) { document.newPage(); } else { isFirstPageWritten = true; } // right box insertTextInBox(cb, 517, inschrijving.getSoorthuurder()); // writeLeftBox(cb, inschrijving); cb.beginText(); cb.setColorFill(Color.BLUE); BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); cb.setFontAndSize(bf, 80); cb.showTextAligned(PdfContentByte.ALIGN_CENTER, standplaats, centerOffset, 400, 0); cb.showTextAligned(PdfContentByte.ALIGN_CENTER, year, centerOffset, 200, 0); bf = BaseFont.createFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); cb.setFontAndSize(bf, 70); cb.showTextAligned(PdfContentByte.ALIGN_CENTER, wagen.getNummerplaat(), centerOffset, 300, 0); // draw boxes drawBox(cb, 520, Y_OFFSET); drawBox(cb, 557, Y_OFFSET + 40, 778, Y_OFFSET + 170, Color.RED); drawBox(cb, centerOffset - 200, 360, centerOffset + 237, 270, Color.BLUE); cb.endText(); } } } if (!isLeftBoxWriten) { writeLeftBox(cb, inschrijving); } } private void createDataLos(PdfContentByte cb, InschrijvingDTO inschrijving) throws DocumentException, IOException { // left box writeLeftBox(cb, inschrijving); // right box insertTextInBox(cb, 520, inschrijving.getSoorthuurder()); // center box insertTextInCentre(cb, 320); // draw boxes drawBox(cb, 520, Y_OFFSET - 5); drawBox(cb, 560, Y_OFFSET + 60, 780, Y_OFFSET + 170, Color.RED); } private void writeLeftBox(PdfContentByte cb, InschrijvingDTO inschrijving) throws DocumentException, IOException { // left box drawBox(cb, 10, Y_OFFSET - 5); insertTextInBox(cb, 0, inschrijving.getSoorthuurder()); drawBox(cb, 40, Y_OFFSET + 60, 260, Y_OFFSET + 170, Color.RED); } private void drawBox(PdfContentByte cb, int x1, int y1) { drawBox(cb, x1, y1 + 20, x1 + 310, y1 + 595); } private void drawBox(PdfContentByte cb, int x1, int y1, int x2, int y2) { cb.setLineWidth(1f); cb.setColorStroke(Color.lightGray); cb.moveTo(x1, y1); cb.lineTo(x2, y1); cb.lineTo(x2, y2); cb.lineTo(x1, y2); cb.lineTo(x1, y1); cb.stroke(); } private void drawBox(PdfContentByte cb, int x1, int y1, int x2, int y2, Color color) { cb.setLineWidth(1f); cb.setColorStroke(color); cb.moveTo(x1, y1); cb.lineTo(x2, y1); cb.lineTo(x2, y2); cb.lineTo(x1, y2); cb.lineTo(x1, y1); cb.stroke(); } private void drawLine(PdfContentByte cb, int x1, int y1, int x2, int y2) { cb.setLineWidth(1f); cb.setColorStroke(Color.lightGray); cb.moveTo(x1, y1); cb.lineTo(x2, y2); cb.stroke(); } private void setData(String plaats, InschrijvingDTO inschrijving) { standplaats = plaats; DateFormat formatter; formatter = new SimpleDateFormat("dd-MM-yyyy"); aankomstDatum = formatter.format(inschrijving.getDateVan()); vertrekDatum = formatter.format(inschrijving.getDateTot()); if (inschrijving.getFichenummer() > 0) { nummer += inschrijving.getFichenummer(); } else { nummer = ""; } for (InschrijvingPersoonDTO inschrijvingPersoon : inschrijving.getInschrijvingPersonen()) { if (GezinsPositieEnum.HOOFD.equals(inschrijvingPersoon.getGezinsPositie())) { naam = inschrijvingPersoon.getPersoon().getNaam(); voornaamHoofd = inschrijvingPersoon.getPersoon().getVoornaam(); if (inschrijvingPersoon.getPersoon().getAdresDTO().getStraat() != null) straat = inschrijvingPersoon.getPersoon().getAdresDTO().getStraat(); if (inschrijvingPersoon.getPersoon().getAdresDTO().getHuisnummer() != null) huisnummer = inschrijvingPersoon.getPersoon().getAdresDTO().getHuisnummer(); if (!StringUtils.isEmpty(inschrijvingPersoon.getPersoon().getAdresDTO().getBus())) { huisnummer += " - " + inschrijvingPersoon.getPersoon().getAdresDTO().getBus(); } if (inschrijvingPersoon.getPersoon().getAdresDTO().getPlaats() != null) woonplaats = inschrijvingPersoon.getPersoon().getAdresDTO().getPlaats(); if (inschrijvingPersoon.getPersoon().getAdresDTO().getPostcode() != null) postcode = inschrijvingPersoon.getPersoon().getAdresDTO().getPostcode(); for (WagenDTO wagen : inschrijvingPersoon.getPersoon().getWagens()) { nrplaat = wagen.getNummerplaat(); break; } break; } } if (SoortHuurderEnum.VAST.equals(inschrijving.getSoorthuurder())) { for (InschrijvingPersoonDTO inschrijvingPersoon : inschrijving.getInschrijvingPersonen()) { if (GezinsPositieEnum.ECHTGENOTE.equals(inschrijvingPersoon.getGezinsPositie())) { echtgenote = inschrijvingPersoon.getPersoon().getNaam(); voornaamEcht = inschrijvingPersoon.getPersoon().getVoornaam(); break; } } } int aantalkinderen = 0; List<String> tmpNamen = new ArrayList<>(); for (InschrijvingPersoonDTO inschrijvingPersoon : inschrijving.getInschrijvingPersonen()) { if (GezinsPositieEnum.HOOFD.equals(inschrijvingPersoon.getGezinsPositie()) || (GezinsPositieEnum.ECHTGENOTE.equals(inschrijvingPersoon.getGezinsPositie()) && SoortHuurderEnum.VAST .equals(inschrijving.getSoorthuurder()))) { continue; } if (aantalkinderen > 0) { voornaamKind += ", "; } voornaamKind += inschrijvingPersoon.getPersoon().getVoornaam(); tmpNamen.add(inschrijvingPersoon.getPersoon().getVoornaam() + " " + inschrijvingPersoon.getPersoon().getNaam()); aantalkinderen++; // } } prepareListNamen(tmpNamen); if (aantalkinderen > 0) { aantalOngehKind = Integer.toString(aantalkinderen); } else { aantalOngehKind = "GEEN KINDEREN"; } } private void prepareListNamen(final List<String> tmpNamen) { String line = ""; for (final String naam : tmpNamen) { if (line.length() > 0) { line += ", "; } line += naam; final int index = tmpNamen.indexOf(naam); if (index == 0 || index == tmpNamen.size() - 1 || index % 2 == 0) { namenMedeHuurders.add(line); line = ""; } } } private void insertTextInCentre(PdfContentByte cb, int offset) throws DocumentException, IOException { drawBox(cb, offset + 10, Y_OFFSET + 560, offset + 130, Y_OFFSET + 590); BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); cb.setFontAndSize(bf, 18); cb.beginText(); cb.showTextAligned(PdfContentByte.ALIGN_CENTER, standplaats, 65 + offset, Y_OFFSET + 567, 0); bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); cb.setFontAndSize(bf, 10); offset += 25; cb.setColorFill(Color.RED); cb.showTextAligned(PdfContentByte.ALIGN_CENTER, "LISPANNE", offset + 60, 482, 0); cb.setColorFill(Color.BLACK); cb.showTextAligned(PdfContentByte.ALIGN_LEFT, "VOSSESLAG 20", offset, 458, 0); cb.showTextAligned(PdfContentByte.ALIGN_LEFT, "8420 DE HAAN", offset, 442, 0); cb.showTextAligned(PdfContentByte.ALIGN_LEFT, "059/23.39.75", offset, 428, 0); cb.showTextAligned(PdfContentByte.ALIGN_LEFT, "WACHTDIENST: " + NUMMER_WACHTDIENST, offset, 414, 0); drawLine(cb, offset, 412, offset + 75, 412); cb.setColorFill(Color.RED); cb.showTextAligned(PdfContentByte.ALIGN_CENTER, "CAPRI", offset + 60, 375, 0); cb.setColorFill(Color.BLACK); cb.showTextAligned(PdfContentByte.ALIGN_LEFT, "DRIFTWEG 157", offset, 351, 0); cb.showTextAligned(PdfContentByte.ALIGN_LEFT, "8420 DE HAAN", offset, 335, 0); cb.showTextAligned(PdfContentByte.ALIGN_LEFT, "059/23.45.45.", offset, 319, 0); cb.showTextAligned(PdfContentByte.ALIGN_LEFT, "WACHTDIENST: " + NUMMER_WACHTDIENST, offset, 303, 0); drawLine(cb, offset, 301, offset + 75, 301); cb.setColorFill(Color.RED); cb.showTextAligned(PdfContentByte.ALIGN_CENTER, "HIPPODROOM", offset + 60, 260, 0); cb.setColorFill(Color.BLACK); cb.showTextAligned(PdfContentByte.ALIGN_LEFT, "DUINDOORNSTRAAT 25", offset, 236, 0); cb.showTextAligned(PdfContentByte.ALIGN_LEFT, "8450 BREDENE", offset, 220, 0); cb.showTextAligned(PdfContentByte.ALIGN_LEFT, "059/32.07.91", offset, 204, 0); cb.showTextAligned(PdfContentByte.ALIGN_LEFT, "WACHTDIENST: " + NUMMER_WACHTDIENST, offset, 188, 0); drawLine(cb, offset, 186, offset + 75, 186); cb.endText(); } private void insertTextInBox(PdfContentByte cb, int offset, SoortHuurderEnum soortHuurderEnum) throws DocumentException, IOException { int offsetXUitleg = 25; int offsetXData = 25; int offsetXRightAlign = 280; BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); cb.beginText(); cb.setFontAndSize(bf, 7); // Karte - fiche cb.showTextAligned(PdfContentByte.ALIGN_LEFT, fiche1, 50 + offset, Y_OFFSET + 575, 0); cb.showTextAligned(PdfContentByte.ALIGN_LEFT, fiche2, 50 + offset, Y_OFFSET + 567, 0); // CONTROLE DES VOYAGEURS DAN LES CAMPINGS cb.showTextAligned(PdfContentByte.ALIGN_CENTER, headerFR, 150 + offset, Y_OFFSET + 544, 0); // AUFSICHT UBER DIE REISENDEN IN CAMPING cb.showTextAligned(PdfContentByte.ALIGN_CENTER, headerDU, 150 + offset, Y_OFFSET + 536, 0); // INSPECTION OF TRAVELLERS IN THE CAMPING cb.showTextAligned(PdfContentByte.ALIGN_CENTER, headerEng, 150 + offset, Y_OFFSET + 528, 0); cb.setFontAndSize(bf, 9); bf = BaseFont.createFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); // NV CAMPING ZWAENEPOEL cb.setColorFill(Color.RED); cb.showTextAligned(PdfContentByte.ALIGN_CENTER, camping, 155 + offset, Y_OFFSET + 509, 0); cb.setColorFill(Color.BLACK); cb.showTextAligned(PdfContentByte.ALIGN_CENTER, camping2, 155 + offset, Y_OFFSET + 497, 0); // Vosseslag 20 - 8420 De Haan cb.showTextAligned(PdfContentByte.ALIGN_CENTER, campingAdres, 155 + offset, Y_OFFSET + 485, 0); // Tel: 059/23 39 75 - Wachtdienst: 0477/28 37 96 cb.showTextAligned(PdfContentByte.ALIGN_CENTER, campingContact, 155 + offset, Y_OFFSET + 473, 0); cb.showTextAligned(PdfContentByte.ALIGN_CENTER, campingContact2, 155 + offset, Y_OFFSET + 461, 0); cb.setFontAndSize(bf, 7); cb.setColorFill(Color.RED); cb.showTextAligned(PdfContentByte.ALIGN_CENTER, bevestiging1, 150 + offset, 155, 0); cb.showTextAligned(PdfContentByte.ALIGN_CENTER, bevestiging2, 150 + offset, 145, 0); cb.showTextAligned(PdfContentByte.ALIGN_CENTER, bevestiging1Tr, 150 + offset, 70, 0); cb.showTextAligned(PdfContentByte.ALIGN_CENTER, bevestiging2Tr, 150 + offset, 60, 0); cb.setColorFill(Color.BLACK); drawLine(cb, 20 + offset, Y_OFFSET + 520, 300 + offset, Y_OFFSET + 520); drawLine(cb, 20 + offset, Y_OFFSET + 451, 300 + offset, Y_OFFSET + 451); bf = BaseFont.createFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); cb.setFontAndSize(bf, 9); // KONTROLE VAN REIZIGERS OP KAMPEERTERREINEN cb.showTextAligned(PdfContentByte.ALIGN_CENTER, headerNL, 150 + offset, Y_OFFSET + 552, 0); cb.setFontAndSize(bf, 8); // Aankomst cb.showTextAligned(PdfContentByte.ALIGN_LEFT, aankomst, offsetXData + offset, Y_OFFSET + 438, 0); // aankomst datum cb.showTextAligned(PdfContentByte.ALIGN_RIGHT, aankomstDatum, offsetXData + offset + offsetXRightAlign, Y_OFFSET + 438, 0); // Vertrek cb.showTextAligned(PdfContentByte.ALIGN_LEFT, vertrek, offsetXData + offset, Y_OFFSET + 420, 0); // vertrek datum cb.showTextAligned(PdfContentByte.ALIGN_RIGHT, vertrekDatum, offsetXData + offset + offsetXRightAlign, Y_OFFSET + 420, 0); // Nummerplaat van het voertuig (3): : cb.showTextAligned(PdfContentByte.ALIGN_LEFT, "Nummerplaat van het voertuig (2)", offsetXData + offset, Y_OFFSET + 402, 0); cb.showTextAligned(PdfContentByte.ALIGN_RIGHT, nrplaat, offsetXData + offset + offsetXRightAlign, Y_OFFSET + 402, 0); // Straat cb.showTextAligned(PdfContentByte.ALIGN_LEFT, "Straat: ", offsetXData + offset, Y_OFFSET + 382, 0); cb.showTextAligned(PdfContentByte.ALIGN_RIGHT, straat, offsetXData + offset + offsetXRightAlign, Y_OFFSET + 382, 0); // Nummer cb.showTextAligned(PdfContentByte.ALIGN_LEFT, "Nummer: ", offsetXData + offset, Y_OFFSET + 364, 0); cb.showTextAligned(PdfContentByte.ALIGN_RIGHT, huisnummer, offsetXData + offset + offsetXRightAlign, Y_OFFSET + 364, 0); // postcode cb.showTextAligned(PdfContentByte.ALIGN_LEFT, "Postcode: ", offsetXData + offset, Y_OFFSET + 346, 0); cb.showTextAligned(PdfContentByte.ALIGN_RIGHT, postcode, offsetXData + offset + offsetXRightAlign, Y_OFFSET + 346, 0); // plaats cb.showTextAligned(PdfContentByte.ALIGN_LEFT, "Woonplaats: ", offsetXData + offset, Y_OFFSET + 328, 0); cb.showTextAligned(PdfContentByte.ALIGN_RIGHT, woonplaats, offsetXData + offset + offsetXRightAlign, Y_OFFSET + 328, 0); // Aanwezige mensen cb.showTextAligned(PdfContentByte.ALIGN_LEFT, aanwezigen, offsetXData + offset, Y_OFFSET + 307, 0); // Hoofd: cb.showTextAligned(PdfContentByte.ALIGN_LEFT, hoofd, offsetXData + 10 + offset, Y_OFFSET + 291, 0); // Naam cb.showTextAligned(PdfContentByte.ALIGN_LEFT, "Naam (1): ", offsetXData + 10 + offset, Y_OFFSET + 273, 0); cb.showTextAligned(PdfContentByte.ALIGN_RIGHT, naam, offsetXData + offset + offsetXRightAlign, Y_OFFSET + 273, 0); // Voornaam cb.showTextAligned(PdfContentByte.ALIGN_LEFT, "Voornamen: ", offsetXData + 10 + offset, Y_OFFSET + 255, 0); cb.showTextAligned(PdfContentByte.ALIGN_RIGHT, voornaamHoofd, offsetXData + offset + offsetXRightAlign, Y_OFFSET + 255, 0); if (SoortHuurderEnum.VAST.equals(soortHuurderEnum)) { // Echtgenote - meisjesnaam (1): cb.showTextAligned(PdfContentByte.ALIGN_LEFT, "Echtgenote - meisjesnaam (1): ", offsetXData + 10 + offset, Y_OFFSET + 238, 0); cb.showTextAligned(PdfContentByte.ALIGN_RIGHT, echtgenote, offsetXData + offset + offsetXRightAlign, Y_OFFSET + 238, 0); // Voornamen: cb.showTextAligned(PdfContentByte.ALIGN_LEFT, "Voornaam: ", offsetXData + 10 + offset, Y_OFFSET + 220, 0); cb.showTextAligned(PdfContentByte.ALIGN_RIGHT, voornaamEcht, offsetXData + offset + offsetXRightAlign, Y_OFFSET + 220, 0); // Aantal ongehuwde kinderen: GEEN KINDEREN cb.showTextAligned(PdfContentByte.ALIGN_LEFT, "Aantal ongehuwde kinderen: ", offsetXData + 10 + offset, Y_OFFSET + 202, 0); cb.showTextAligned(PdfContentByte.ALIGN_RIGHT, aantalOngehKind, offsetXData + offset + offsetXRightAlign, Y_OFFSET + 202, 0); // Voornaam cb.showTextAligned(PdfContentByte.ALIGN_LEFT, "Voornamen: ", offsetXData + 10 + offset, Y_OFFSET + 184, 0); cb.showTextAligned(PdfContentByte.ALIGN_RIGHT, voornaamKind, offsetXData + offset + offsetXRightAlign, Y_OFFSET + 184, 0); } else { // Namen mede huurders cb.showTextAligned(PdfContentByte.ALIGN_LEFT, "mede huurders: ", offsetXData + 10 + offset, Y_OFFSET + 238, 0); int yOffset = Y_OFFSET + 238; for (final String naam : namenMedeHuurders) { cb.showTextAligned(PdfContentByte.ALIGN_RIGHT, naam, offsetXData + offset + offsetXRightAlign, yOffset, 0); yOffset -= 18; } } // nummer N�26542 cb.setFontAndSize(bf, 18); cb.showTextAligned(PdfContentByte.ALIGN_LEFT, nummer, 90 + offset, Y_OFFSET + 567, 0); // Standplaats cb.showTextAligned(PdfContentByte.ALIGN_LEFT, standplaats, 190 + offset, Y_OFFSET + 567, 0); cb.setFontAndSize(bf, 6); // (1) In drukletters - (2) De juistheid van die inlichting moet door de // exploitant niet worden nagegaan cb.showTextAligned(PdfContentByte.ALIGN_LEFT, uitleg12, offsetXUitleg + offset, 30, 0); // (3) Alleen te vermelden op het dubbel van de kaart" cb.showTextAligned(PdfContentByte.ALIGN_LEFT, uitleg3, offsetXUitleg + offset, 22, 0); cb.endText(); } }
25,093
0.634996
0.605581
524
46.946564
35.892345
140
false
false
0
0
0
0
0
0
1.35687
false
false
7
51bcaf815aff9197b6c40d4c23327192146c96f1
5,085,241,289,451
ef4d94d940e4b86b154c7071b429a58873bb4f75
/esup-activ-bo/src/org/esupportail/activbo/domain/beans/ValidationProxyTicketImpl.java
899b0e64eac25b0481b515c42c4301e4243a9cef
[]
no_license
tolobial/esup-activ
https://github.com/tolobial/esup-activ
bf9b73d8d9a00d6d372279c54d21f49e51ea4e7c
725743e87a87cf8af5459f7e2a86248fbcce773f
refs/heads/master
2021-06-21T01:32:51.399000
2017-08-08T09:25:04
2017-08-08T09:25:04
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.esupportail.activbo.domain.beans; import java.util.Arrays; import java.util.List; import org.esupportail.commons.services.logging.Logger; import org.esupportail.commons.services.logging.LoggerImpl; import edu.yale.its.tp.cas.client.ProxyTicketValidator; public class ValidationProxyTicketImpl implements ValidationProxyTicket{ /** * */ private static final long serialVersionUID = 1L; /** * A logger. */ private final Logger logger = new LoggerImpl(getClass()); private String casValidateUrl; private String allowedProxies; private ProxyTicketValidator proxyTicketValidator; public boolean validation(String id,String proxyticket,String targetUrl) { proxyTicketValidator.setCasValidateUrl(casValidateUrl); proxyTicketValidator.setServiceTicket(proxyticket); proxyTicketValidator.setService(targetUrl); try { proxyTicketValidator.validate(); logger.debug("getresponse :"+proxyTicketValidator.getResponse()); logger.debug("getuser :"+proxyTicketValidator.getUser()); logger.debug("service renew :"+proxyTicketValidator.isRenew()); logger.debug("Proxyticket: "+proxyticket); if (proxyTicketValidator.isAuthenticationSuccesful() && proxyTicketValidator.getUser().equals(id) && isProxyAllowed(proxyTicketValidator.getProxyList())) { logger.debug("Authentification réussie"); return true; } } catch (Exception e) { e.printStackTrace(); } logger.debug("Authentification ratée"); logger.debug("isAuthenticationSuccesful: "+proxyTicketValidator.isAuthenticationSuccesful()); return false; } private boolean isProxyAllowed(List<String> proxies) { List<String> allowedProxyList = Arrays.asList(allowedProxies.split(",")); for(String p:proxies) if (allowedProxyList.contains(p)) return true; logger.warn("Les proxies ci-après ne sont pas authorisés à accéder au BO : "+proxies.toString()); logger.warn("Vous pouvez les ajouter sur properties/config.properties, cas.allowedProxies"); logger.warn("Les proxies actuellement autorisés : "+allowedProxyList.toString()); return false; } /** * @return the casValidateUrl */ public String getCasValidateUrl() { return casValidateUrl; } /** * @param casValidateUrl the casValidateUrl to set */ public void setCasValidateUrl(String casValidateUrl) { this.casValidateUrl = casValidateUrl; } /** * @return the proxyTicketValidator */ public ProxyTicketValidator getProxyTicketValidator() { return proxyTicketValidator; } /** * @param proxyTicketValidator the proxyTicketValidator to set */ public void setProxyTicketValidator(ProxyTicketValidator proxyTicketValidator) { this.proxyTicketValidator = proxyTicketValidator; } /** * @return the allowedProxies */ public String getAllowedProxies() { return allowedProxies; } /** * @param allowedProxies the allowedProxies to set */ public void setAllowedProxies(String allowedProxies) { this.allowedProxies = allowedProxies; } }
UTF-8
Java
3,035
java
ValidationProxyTicketImpl.java
Java
[]
null
[]
package org.esupportail.activbo.domain.beans; import java.util.Arrays; import java.util.List; import org.esupportail.commons.services.logging.Logger; import org.esupportail.commons.services.logging.LoggerImpl; import edu.yale.its.tp.cas.client.ProxyTicketValidator; public class ValidationProxyTicketImpl implements ValidationProxyTicket{ /** * */ private static final long serialVersionUID = 1L; /** * A logger. */ private final Logger logger = new LoggerImpl(getClass()); private String casValidateUrl; private String allowedProxies; private ProxyTicketValidator proxyTicketValidator; public boolean validation(String id,String proxyticket,String targetUrl) { proxyTicketValidator.setCasValidateUrl(casValidateUrl); proxyTicketValidator.setServiceTicket(proxyticket); proxyTicketValidator.setService(targetUrl); try { proxyTicketValidator.validate(); logger.debug("getresponse :"+proxyTicketValidator.getResponse()); logger.debug("getuser :"+proxyTicketValidator.getUser()); logger.debug("service renew :"+proxyTicketValidator.isRenew()); logger.debug("Proxyticket: "+proxyticket); if (proxyTicketValidator.isAuthenticationSuccesful() && proxyTicketValidator.getUser().equals(id) && isProxyAllowed(proxyTicketValidator.getProxyList())) { logger.debug("Authentification réussie"); return true; } } catch (Exception e) { e.printStackTrace(); } logger.debug("Authentification ratée"); logger.debug("isAuthenticationSuccesful: "+proxyTicketValidator.isAuthenticationSuccesful()); return false; } private boolean isProxyAllowed(List<String> proxies) { List<String> allowedProxyList = Arrays.asList(allowedProxies.split(",")); for(String p:proxies) if (allowedProxyList.contains(p)) return true; logger.warn("Les proxies ci-après ne sont pas authorisés à accéder au BO : "+proxies.toString()); logger.warn("Vous pouvez les ajouter sur properties/config.properties, cas.allowedProxies"); logger.warn("Les proxies actuellement autorisés : "+allowedProxyList.toString()); return false; } /** * @return the casValidateUrl */ public String getCasValidateUrl() { return casValidateUrl; } /** * @param casValidateUrl the casValidateUrl to set */ public void setCasValidateUrl(String casValidateUrl) { this.casValidateUrl = casValidateUrl; } /** * @return the proxyTicketValidator */ public ProxyTicketValidator getProxyTicketValidator() { return proxyTicketValidator; } /** * @param proxyTicketValidator the proxyTicketValidator to set */ public void setProxyTicketValidator(ProxyTicketValidator proxyTicketValidator) { this.proxyTicketValidator = proxyTicketValidator; } /** * @return the allowedProxies */ public String getAllowedProxies() { return allowedProxies; } /** * @param allowedProxies the allowedProxies to set */ public void setAllowedProxies(String allowedProxies) { this.allowedProxies = allowedProxies; } }
3,035
0.747028
0.746697
111
26.288288
26.977264
99
false
false
0
0
0
0
0
0
1.945946
false
false
7
e2b8167b144d49aa22a3253ce3720b215b67c4cd
11,501,922,479,636
deafb13f36b59f0b2b3e996d1b77a7c191ec5a48
/src/com/jinzht/pro/activity/AboutDetailActivity.java
dbbc83578ca894c50f08df30ca9ca5f304499d07
[]
no_license
zanqging/PE
https://github.com/zanqging/PE
464f7393b295e0f12a0d50d829456ddfca12c911
09b3bfcdf489784dc3a55362b90ce08c1269df66
refs/heads/master
2021-01-01T05:17:17.481000
2016-04-13T09:04:01
2016-04-13T09:04:04
56,134,315
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.jinzht.pro.activity; import android.content.Intent; import android.os.AsyncTask; import android.util.Log; import android.widget.TextView; import com.jinzht.pro.Constant; import com.jinzht.pro.R; import com.jinzht.pro.model.DataBean; import com.jinzht.pro.utils.AsynOkUtils; import com.jinzht.pro.utils.FastJsonTools; import com.jinzht.pro.utils.NetWorkUtils; import com.jinzht.pro.utils.ResourceUtils; import com.jinzht.pro.utils.SuperToastUtils; import java.io.IOException; import butterknife.Bind; import butterknife.OnClick; /** * 世上唯有贫穷可以不劳而获。 * <p> * 隐私政策页,访问网络,获取数据保存到DataBean,再展示出内容 * * @auther Mr.Jobs * @date 2015/6/2 * @time 9:32 */ public class AboutDetailActivity extends BaseActivity { public static final String ENCODING = "UTF-8"; private Intent intent; @Bind(R.id.title) TextView title; @Bind(R.id.context) TextView context; @OnClick(R.id.back) void back() { this.finish(); } @Override protected int getResourcesId() { return R.layout.activity_about_detail; } @Override protected void init() { title.setText(getIntent().getExtras().getString("title")); // 访问网络,获取数据保存到DataBean,再展示出内容 FreeBackTask task = new FreeBackTask(); task.execute(); switch (getIntent().getExtras().getInt("detail")) { case 0://关于路演 context.setText(ResourceUtils.getFromAssets(mContext, "about_roadshow.txt")); break; case 1://关于众筹 // context.setText(ResourceUtils.geFileFromAssets(mContext,"crowdfunding.txt")); context.setText(ResourceUtils.getFromAssets(mContext, "crowdfunding.txt")); break; case 2://领投跟头 // context.setText(ResourceUtils.geFileFromAssets(mContext,"lingtou.txt")); context.setText(ResourceUtils.getFromAssets(mContext, "lingtou.txt")); break; case 3://投资认证时候的 context.setText(ResourceUtils.getFromAssets(mContext, "risk_tips.txt")); break; case 4://设置里的隐私政策 context.setText(ResourceUtils.getFromAssets(mContext, "privacy_policy.txt")); break; case 5://用户协议,注册第二部 context.setText(ResourceUtils.getFromAssets(mContext, "user_agreement.txt")); break; } } // 访问网络,获取数据保存到DataBean,再展示出内容 private class FreeBackTask extends AsyncTask<Void, Void, DataBean> { @Override protected void onPreExecute() { super.onPreExecute(); showLoadingProgressDialog(); } @Override protected DataBean doInBackground(Void... voids) { String body = ""; if (!NetWorkUtils.getNetWorkType(mContext).equals(NetWorkUtils.NETWORK_TYPE_DISCONNECT)) { try { body = AsynOkUtils.doGet(Constant.BASE_URL + Constant.PHONE + Constant.PRINOTICE, mContext); } catch (IOException e) { e.printStackTrace(); } Log.i("协议", body); return FastJsonTools.getBean(body, DataBean.class); } else { return null; } } @Override protected void onPostExecute(DataBean aVoid) { super.onPostExecute(aVoid); dismissProgressDialog(); if (aVoid != null) { if (aVoid.getCode() == -1) { return; } if (aVoid.getCode() == 0) { context.setText(aVoid.getData()); } else { SuperToastUtils.showSuperToast(AboutDetailActivity.this, 1, aVoid.getMsg()); } } } } @Override public void errorPage() { } @Override public void blankPage() { } @Override public void successRefresh() { } }
GB18030
Java
4,221
java
AboutDetailActivity.java
Java
[ { "context": " * 隐私政策页,访问网络,获取数据保存到DataBean,再展示出内容\n *\n * @auther Mr.Jobs\n * @date 2015/6/2\n * @time 9:32\n */\n\npublic class", "end": 631, "score": 0.9906944632530212, "start": 624, "tag": "USERNAME", "value": "Mr.Jobs" } ]
null
[]
package com.jinzht.pro.activity; import android.content.Intent; import android.os.AsyncTask; import android.util.Log; import android.widget.TextView; import com.jinzht.pro.Constant; import com.jinzht.pro.R; import com.jinzht.pro.model.DataBean; import com.jinzht.pro.utils.AsynOkUtils; import com.jinzht.pro.utils.FastJsonTools; import com.jinzht.pro.utils.NetWorkUtils; import com.jinzht.pro.utils.ResourceUtils; import com.jinzht.pro.utils.SuperToastUtils; import java.io.IOException; import butterknife.Bind; import butterknife.OnClick; /** * 世上唯有贫穷可以不劳而获。 * <p> * 隐私政策页,访问网络,获取数据保存到DataBean,再展示出内容 * * @auther Mr.Jobs * @date 2015/6/2 * @time 9:32 */ public class AboutDetailActivity extends BaseActivity { public static final String ENCODING = "UTF-8"; private Intent intent; @Bind(R.id.title) TextView title; @Bind(R.id.context) TextView context; @OnClick(R.id.back) void back() { this.finish(); } @Override protected int getResourcesId() { return R.layout.activity_about_detail; } @Override protected void init() { title.setText(getIntent().getExtras().getString("title")); // 访问网络,获取数据保存到DataBean,再展示出内容 FreeBackTask task = new FreeBackTask(); task.execute(); switch (getIntent().getExtras().getInt("detail")) { case 0://关于路演 context.setText(ResourceUtils.getFromAssets(mContext, "about_roadshow.txt")); break; case 1://关于众筹 // context.setText(ResourceUtils.geFileFromAssets(mContext,"crowdfunding.txt")); context.setText(ResourceUtils.getFromAssets(mContext, "crowdfunding.txt")); break; case 2://领投跟头 // context.setText(ResourceUtils.geFileFromAssets(mContext,"lingtou.txt")); context.setText(ResourceUtils.getFromAssets(mContext, "lingtou.txt")); break; case 3://投资认证时候的 context.setText(ResourceUtils.getFromAssets(mContext, "risk_tips.txt")); break; case 4://设置里的隐私政策 context.setText(ResourceUtils.getFromAssets(mContext, "privacy_policy.txt")); break; case 5://用户协议,注册第二部 context.setText(ResourceUtils.getFromAssets(mContext, "user_agreement.txt")); break; } } // 访问网络,获取数据保存到DataBean,再展示出内容 private class FreeBackTask extends AsyncTask<Void, Void, DataBean> { @Override protected void onPreExecute() { super.onPreExecute(); showLoadingProgressDialog(); } @Override protected DataBean doInBackground(Void... voids) { String body = ""; if (!NetWorkUtils.getNetWorkType(mContext).equals(NetWorkUtils.NETWORK_TYPE_DISCONNECT)) { try { body = AsynOkUtils.doGet(Constant.BASE_URL + Constant.PHONE + Constant.PRINOTICE, mContext); } catch (IOException e) { e.printStackTrace(); } Log.i("协议", body); return FastJsonTools.getBean(body, DataBean.class); } else { return null; } } @Override protected void onPostExecute(DataBean aVoid) { super.onPostExecute(aVoid); dismissProgressDialog(); if (aVoid != null) { if (aVoid.getCode() == -1) { return; } if (aVoid.getCode() == 0) { context.setText(aVoid.getData()); } else { SuperToastUtils.showSuperToast(AboutDetailActivity.this, 1, aVoid.getMsg()); } } } } @Override public void errorPage() { } @Override public void blankPage() { } @Override public void successRefresh() { } }
4,221
0.58231
0.577549
136
28.352942
25.533579
112
false
false
0
0
0
0
0
0
0.492647
false
false
10
4508fa3c2926a8e89ad04d3c937384723515534e
206,158,448,794
dc7c4ae317f46efc24551b68d3bc56f9e9b1f995
/producto/src/main/java/com/uacm/atamarindao/producto/entidad/Producto.java
78cb530896078e139a13bffe7432489caf372293
[]
no_license
armandoRC79/atamarindao
https://github.com/armandoRC79/atamarindao
b592fc995d74d248d75f5b3196ee288fc55a4030
559f276cd73fa8d7a3156d37034c272f6058f4ff
refs/heads/master
2023-03-06T08:18:46.458000
2021-01-25T05:28:56
2021-01-25T05:28:56
332,625,704
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.uacm.atamarindao.producto.entidad; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import javax.validation.constraints.NotEmpty; import javax.validation.constraints.Positive; import javax.validation.constraints.Size; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; @Entity @Table(name = "tbl_productos") @Data @AllArgsConstructor @NoArgsConstructor @Builder public class Producto { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @NotEmpty(message = "El nombre no debe ser vacio") @Size (max = 100) private String nombre; @Size (max = 50) private String imagen; @Size (max = 300) private String descripcion; @Positive(message = "El stock debe ser mayor o igual que cero") private Double stock; @Positive(message = "El precio debe ser mayor o igual que cero") private Double precio; @NotEmpty(message = "Sin estatus asignado") private String status; }
UTF-8
Java
1,178
java
Producto.java
Java
[]
null
[]
package com.uacm.atamarindao.producto.entidad; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import javax.validation.constraints.NotEmpty; import javax.validation.constraints.Positive; import javax.validation.constraints.Size; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; @Entity @Table(name = "tbl_productos") @Data @AllArgsConstructor @NoArgsConstructor @Builder public class Producto { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @NotEmpty(message = "El nombre no debe ser vacio") @Size (max = 100) private String nombre; @Size (max = 50) private String imagen; @Size (max = 300) private String descripcion; @Positive(message = "El stock debe ser mayor o igual que cero") private Double stock; @Positive(message = "El precio debe ser mayor o igual que cero") private Double precio; @NotEmpty(message = "Sin estatus asignado") private String status; }
1,178
0.733447
0.726655
47
24.063829
18.822128
68
false
false
0
0
0
0
0
0
0.425532
false
false
10
377cb1a0ecde664c002879255ac43283f1f30e88
23,175,643,530,254
a3d6eba93e08795db56a80fb6a0747bed845a24d
/src/org/obvial/obvial/Inicializar.java
1930956a604032301dbd57cfe39976d78fc9a3bb
[]
no_license
ProfesorADSI/PracticaADSI
https://github.com/ProfesorADSI/PracticaADSI
c26a3b5fa22b40b1dd372d08bdff42c102a9b23d
b4c8204fb5652b0365f48c9083ba2acb8f71d511
refs/heads/master
2015-08-02T04:19:21.864000
2013-09-12T06:49:15
2013-09-12T06:49:15
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.obvial.obvial; //import java.awt.Toolkit; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.util.StringTokenizer; //En esta clase se encuentran todos los metodos para inicializar el juego public class Inicializar { private static Inicializar miInicio = new Inicializar(); private Inicializar(){ } public static Inicializar getInicializar(){ return miInicio; } public void InicializarCartas(){ try { InputStream archivo = Inicializar.class.getResourceAsStream("datos/Preguntas_de_Curiosidades.txt"); this.recorrerArchivo(archivo, 0); archivo = Inicializar.class.getResourceAsStream("datos/Preguntas_de_Series.txt"); this.recorrerArchivo(archivo, 1); archivo = Inicializar.class.getResourceAsStream("datos/Preguntas_de_Peliculas.txt"); this.recorrerArchivo(archivo, 2); archivo = Inicializar.class.getResourceAsStream("datos/Preguntas_de_Deportes.txt"); this.recorrerArchivo(archivo, 3); archivo = Inicializar.class.getResourceAsStream("datos/Preguntas_de_Videojuegos.txt"); this.recorrerArchivo(archivo, 4); } catch (Exception e) { // TODO: handle exception System.out.println("Error cargando el fichero de preguntas 1."); } } //Este es especifico para cargar las cartas public void recorrerArchivo(InputStream pArchivo, int pTema){ //Recorre el archivo a cargar String pregunta; String respCorrecta; String resp1; String resp2; String resp3; String resp4; Carta carta; ListaCartas listaCartas = new ListaCartas(); int cont = 0; try{ //BufferedReader bufRdr = new BufferedReader(new FileReader(pArchivo)); BufferedReader bufRdr = new BufferedReader(new InputStreamReader(pArchivo)); String linea = null; //Recorrer lineas //Si la linea devuelve null, es que hemos //terminado de recorrer el archivo linea = bufRdr.readLine(); while( linea != null ){ //separamos la linea por los ";" y contamos StringTokenizer lineaActual = new StringTokenizer(linea,";"); cont++; //Debe tener 6 tokens if (lineaActual.countTokens() == 6) { pregunta = lineaActual.nextToken(); //token 1 Pregunta respCorrecta = lineaActual.nextToken(); //token 2 RespuestaCorrecta resp1 = lineaActual.nextToken(); //token 3 RespuestaA resp2 = lineaActual.nextToken(); //token 4 RespuestaB resp3 = lineaActual.nextToken(); //token 5 RespuestaC resp4 = lineaActual.nextToken(); //token 6 RespuestaD //Anadimos la carta carta = new Carta(cont+1, pregunta, respCorrecta, resp1, resp2, resp3, resp4); listaCartas.anadirCarta(carta); //System.out.println("Inserto carta " + Cont); linea = bufRdr.readLine(); } else { System.out.println("La linea preguntas" + cont + " contiene errores."); linea = bufRdr.readLine(); } } Listas.getMisListas().anadirListas(pTema, listaCartas); } catch (Exception e) { // TODO: handle exception System.out.println("Error cargando el fichero de preguntas 2."+pTema); } } public void InicializarCasillas(){ String token1; String token2; String token3; String token4; String token5; int Cont = 0; try { InputStream archivo = Inicializar.class.getResourceAsStream("datos/Datos_Casillas.txt"); //BufferedReader bufRdr = new BufferedReader(new FileReader(archivo)); BufferedReader bufRdr = new BufferedReader(new InputStreamReader(archivo)); String linea = null; //Recorrer lineas //Si la linea devuelve null, es que hemos //terminado de recorrer el archivo while((linea = bufRdr.readLine()) != null) { //Separamos la linea por los ";" y contamos StringTokenizer lineaActual = new StringTokenizer(linea,";"); Cont++; //Debe tener 5 tokens if (lineaActual.countTokens() == 5) { //Con el parseInt pasamos de String a integer cada uno de los tokens token1 = lineaActual.nextToken(); //token 1 Numero de casilla int numCasilla = Integer.parseInt(token1); token2 = lineaActual.nextToken(); //token 2 Tipo de casilla int tipo = Integer.parseInt(token2); token3 = lineaActual.nextToken(); //token 3 Numero de turnos de retencion o casilla a la que desplazarse int opcion = Integer.parseInt(token3); token4 = lineaActual.nextToken(); //token 4 Posicion X en el tablero int posX = Integer.parseInt(token4); token5 = lineaActual.nextToken(); //token 5 Posicion Y en el tablero int posY = Integer.parseInt(token5); //Aniadimos la casilla switch(tipo){ case 1: Casilla casilla = new Casilla(numCasilla, tipo, posX, posY); ListaCasillas.getListaCasillas().anadirCasilla(casilla); break; case 2: CasillaRetencion casilla1 = new CasillaRetencion(numCasilla, opcion, tipo, posX, posY); ListaCasillas.getListaCasillas().anadirCasillaRetencion(casilla1); break; case 3: CasillaTraslado casilla2 = new CasillaTraslado(numCasilla, opcion, tipo, posX, posY); ListaCasillas.getListaCasillas().anadirCasillaTraslado(casilla2); break; } }else{ System.out.println("La linea de casillas " + Cont + " contiene errores."); linea = bufRdr.readLine(); } } } catch (Exception e) { // TODO: handle exception System.out.println("Error cargando el fichero de casillas."); } } }
UTF-8
Java
5,578
java
Inicializar.java
Java
[]
null
[]
package org.obvial.obvial; //import java.awt.Toolkit; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.util.StringTokenizer; //En esta clase se encuentran todos los metodos para inicializar el juego public class Inicializar { private static Inicializar miInicio = new Inicializar(); private Inicializar(){ } public static Inicializar getInicializar(){ return miInicio; } public void InicializarCartas(){ try { InputStream archivo = Inicializar.class.getResourceAsStream("datos/Preguntas_de_Curiosidades.txt"); this.recorrerArchivo(archivo, 0); archivo = Inicializar.class.getResourceAsStream("datos/Preguntas_de_Series.txt"); this.recorrerArchivo(archivo, 1); archivo = Inicializar.class.getResourceAsStream("datos/Preguntas_de_Peliculas.txt"); this.recorrerArchivo(archivo, 2); archivo = Inicializar.class.getResourceAsStream("datos/Preguntas_de_Deportes.txt"); this.recorrerArchivo(archivo, 3); archivo = Inicializar.class.getResourceAsStream("datos/Preguntas_de_Videojuegos.txt"); this.recorrerArchivo(archivo, 4); } catch (Exception e) { // TODO: handle exception System.out.println("Error cargando el fichero de preguntas 1."); } } //Este es especifico para cargar las cartas public void recorrerArchivo(InputStream pArchivo, int pTema){ //Recorre el archivo a cargar String pregunta; String respCorrecta; String resp1; String resp2; String resp3; String resp4; Carta carta; ListaCartas listaCartas = new ListaCartas(); int cont = 0; try{ //BufferedReader bufRdr = new BufferedReader(new FileReader(pArchivo)); BufferedReader bufRdr = new BufferedReader(new InputStreamReader(pArchivo)); String linea = null; //Recorrer lineas //Si la linea devuelve null, es que hemos //terminado de recorrer el archivo linea = bufRdr.readLine(); while( linea != null ){ //separamos la linea por los ";" y contamos StringTokenizer lineaActual = new StringTokenizer(linea,";"); cont++; //Debe tener 6 tokens if (lineaActual.countTokens() == 6) { pregunta = lineaActual.nextToken(); //token 1 Pregunta respCorrecta = lineaActual.nextToken(); //token 2 RespuestaCorrecta resp1 = lineaActual.nextToken(); //token 3 RespuestaA resp2 = lineaActual.nextToken(); //token 4 RespuestaB resp3 = lineaActual.nextToken(); //token 5 RespuestaC resp4 = lineaActual.nextToken(); //token 6 RespuestaD //Anadimos la carta carta = new Carta(cont+1, pregunta, respCorrecta, resp1, resp2, resp3, resp4); listaCartas.anadirCarta(carta); //System.out.println("Inserto carta " + Cont); linea = bufRdr.readLine(); } else { System.out.println("La linea preguntas" + cont + " contiene errores."); linea = bufRdr.readLine(); } } Listas.getMisListas().anadirListas(pTema, listaCartas); } catch (Exception e) { // TODO: handle exception System.out.println("Error cargando el fichero de preguntas 2."+pTema); } } public void InicializarCasillas(){ String token1; String token2; String token3; String token4; String token5; int Cont = 0; try { InputStream archivo = Inicializar.class.getResourceAsStream("datos/Datos_Casillas.txt"); //BufferedReader bufRdr = new BufferedReader(new FileReader(archivo)); BufferedReader bufRdr = new BufferedReader(new InputStreamReader(archivo)); String linea = null; //Recorrer lineas //Si la linea devuelve null, es que hemos //terminado de recorrer el archivo while((linea = bufRdr.readLine()) != null) { //Separamos la linea por los ";" y contamos StringTokenizer lineaActual = new StringTokenizer(linea,";"); Cont++; //Debe tener 5 tokens if (lineaActual.countTokens() == 5) { //Con el parseInt pasamos de String a integer cada uno de los tokens token1 = lineaActual.nextToken(); //token 1 Numero de casilla int numCasilla = Integer.parseInt(token1); token2 = lineaActual.nextToken(); //token 2 Tipo de casilla int tipo = Integer.parseInt(token2); token3 = lineaActual.nextToken(); //token 3 Numero de turnos de retencion o casilla a la que desplazarse int opcion = Integer.parseInt(token3); token4 = lineaActual.nextToken(); //token 4 Posicion X en el tablero int posX = Integer.parseInt(token4); token5 = lineaActual.nextToken(); //token 5 Posicion Y en el tablero int posY = Integer.parseInt(token5); //Aniadimos la casilla switch(tipo){ case 1: Casilla casilla = new Casilla(numCasilla, tipo, posX, posY); ListaCasillas.getListaCasillas().anadirCasilla(casilla); break; case 2: CasillaRetencion casilla1 = new CasillaRetencion(numCasilla, opcion, tipo, posX, posY); ListaCasillas.getListaCasillas().anadirCasillaRetencion(casilla1); break; case 3: CasillaTraslado casilla2 = new CasillaTraslado(numCasilla, opcion, tipo, posX, posY); ListaCasillas.getListaCasillas().anadirCasillaTraslado(casilla2); break; } }else{ System.out.println("La linea de casillas " + Cont + " contiene errores."); linea = bufRdr.readLine(); } } } catch (Exception e) { // TODO: handle exception System.out.println("Error cargando el fichero de casillas."); } } }
5,578
0.676407
0.66583
171
30.619883
28.345642
109
false
false
0
0
0
0
0
0
3.48538
false
false
10