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
ebbabc9b64309b58b3a01c8bb31518cf9183e724
18,562,848,709,774
34487ebb7e1078572da0a2173f9cf9551d70a789
/sabot/kernel/src/main/java/com/dremio/exec/planner/sql/handlers/ConvertJdbcLogicalToJdbcRel.java
ad204191361dae3e165815faf67d592eb19372ec
[ "Apache-2.0" ]
permissive
teratide/dremio-accelerated
https://github.com/teratide/dremio-accelerated
4fe3538b845452de46a260a966811183badae2e4
9b8c9d3f9dc0d71cae0ffb07d397a91012217eb6
refs/heads/master
2023-06-08T20:49:27.347000
2021-01-27T11:02:16
2021-01-27T11:02:16
316,045,445
7
1
Apache-2.0
false
2021-06-01T09:09:16
2020-11-25T20:21:18
2021-03-24T14:08:06
2021-06-01T08:58:19
109,916
1
0
3
Java
false
false
/* * Copyright (C) 2017-2019 Dremio Corporation * * 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.dremio.exec.planner.sql.handlers; import org.apache.calcite.rel.RelNode; import org.apache.calcite.tools.RelBuilderFactory; import com.dremio.exec.calcite.logical.JdbcCrel; import com.dremio.exec.planner.StatelessRelShuttleImpl; import com.dremio.exec.planner.common.JdbcRelImpl; import com.dremio.exec.planner.common.MoreRelOptUtil; import com.dremio.exec.planner.logical.JdbcRel; class ConvertJdbcLogicalToJdbcRel extends StatelessRelShuttleImpl { private RelBuilderFactory factory; public ConvertJdbcLogicalToJdbcRel(RelBuilderFactory factory) { super(); this.factory = factory; } @Override public RelNode visit(RelNode other) { if (other instanceof JdbcCrel) { final JdbcCrel logical = (JdbcCrel) other; // Eliminate subsets to enforce that all nodes in the Jdbc subtree are JdbcRelImpl nodes. final RelNode subsetRemoved = logical.getInput().accept(new MoreRelOptUtil.SubsetRemover()); logical.replaceInput(0, subsetRemoved); if (logical.getPluginId() == null) { // Reverts JdbcRelImpl nodes back to their original Logical rel. This is necessary to handle subtrees that // contain a values operator. We try to pushdown these subtrees if they are joined with another subtree that // is pushed down to a jdbc source. After the HEP planner is finished, if we see that there are isolated // branches that were not joined, we don't want to push them down, so we must revert. return ((JdbcRelImpl) logical.getInput()).revert(factory.create(logical.getCluster(), null)); } return new JdbcRel(logical.getCluster(), logical.getTraitSet(), logical.getInput()); } return super.visit(other); } }
UTF-8
Java
2,335
java
ConvertJdbcLogicalToJdbcRel.java
Java
[]
null
[]
/* * Copyright (C) 2017-2019 Dremio Corporation * * 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.dremio.exec.planner.sql.handlers; import org.apache.calcite.rel.RelNode; import org.apache.calcite.tools.RelBuilderFactory; import com.dremio.exec.calcite.logical.JdbcCrel; import com.dremio.exec.planner.StatelessRelShuttleImpl; import com.dremio.exec.planner.common.JdbcRelImpl; import com.dremio.exec.planner.common.MoreRelOptUtil; import com.dremio.exec.planner.logical.JdbcRel; class ConvertJdbcLogicalToJdbcRel extends StatelessRelShuttleImpl { private RelBuilderFactory factory; public ConvertJdbcLogicalToJdbcRel(RelBuilderFactory factory) { super(); this.factory = factory; } @Override public RelNode visit(RelNode other) { if (other instanceof JdbcCrel) { final JdbcCrel logical = (JdbcCrel) other; // Eliminate subsets to enforce that all nodes in the Jdbc subtree are JdbcRelImpl nodes. final RelNode subsetRemoved = logical.getInput().accept(new MoreRelOptUtil.SubsetRemover()); logical.replaceInput(0, subsetRemoved); if (logical.getPluginId() == null) { // Reverts JdbcRelImpl nodes back to their original Logical rel. This is necessary to handle subtrees that // contain a values operator. We try to pushdown these subtrees if they are joined with another subtree that // is pushed down to a jdbc source. After the HEP planner is finished, if we see that there are isolated // branches that were not joined, we don't want to push them down, so we must revert. return ((JdbcRelImpl) logical.getInput()).revert(factory.create(logical.getCluster(), null)); } return new JdbcRel(logical.getCluster(), logical.getTraitSet(), logical.getInput()); } return super.visit(other); } }
2,335
0.742612
0.737045
57
39.964912
34.907379
116
false
false
0
0
0
0
0
0
0.508772
false
false
1
bab8c6be4449dcb75c0a25c0ece42e402d7fae84
6,682,969,167,015
8529b12787519306e1bc185e765f3bf26421057f
/taotao-manager/taotao-manager-service/src/main/java/com/taotao/service/PictureService.java
d1dd3797a620fe043e27db0b1ae2aa05e8592302
[]
no_license
junjun888/taotaoMall
https://github.com/junjun888/taotaoMall
c657f06bae93508d507290ee286f5fd64960a555
13e57ae083821d50843173d50dd93e922a4d5b29
refs/heads/master
2020-12-02T20:53:51.298000
2017-08-02T14:40:44
2017-08-02T14:40:44
96,226,325
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.taotao.service; import java.util.Map; import org.springframework.web.multipart.MultipartFile; /** * 图片上传接口 * <p>Title: PictureService</p> * <p>Description: </p> * @author 黄文俊 * @date 2017年6月28日下午9:03:33 * @version 1.0 */ public interface PictureService { Map uploadPicture(MultipartFile uploadFile); }
UTF-8
Java
353
java
PictureService.java
Java
[ { "context": "ureService</p>\n * <p>Description: </p>\n * @author\t黄文俊\n * @date\t2017年6月28日下午9:03:33\n * @version 1.0\n */\n", "end": 194, "score": 0.99983811378479, "start": 191, "tag": "NAME", "value": "黄文俊" } ]
null
[]
package com.taotao.service; import java.util.Map; import org.springframework.web.multipart.MultipartFile; /** * 图片上传接口 * <p>Title: PictureService</p> * <p>Description: </p> * @author 黄文俊 * @date 2017年6月28日下午9:03:33 * @version 1.0 */ public interface PictureService { Map uploadPicture(MultipartFile uploadFile); }
353
0.726154
0.683077
18
17.111111
16.387287
55
false
false
0
0
0
0
0
0
0.388889
false
false
1
d324787e83d7274503fc5f0aa5eae6aa66e815f0
8,847,632,694,824
09bc7c4ce5b6d19b6a9b874767dc2e93fb5153e8
/Questao01/Cliente.java
cc5689dccee7f1bbae6e4415ddbe7602eb1ecf5c
[]
no_license
NapoleaoHerculano/ExercicioExtra
https://github.com/NapoleaoHerculano/ExercicioExtra
f1819dd1ef4051b3bc5648a186382150c4ab8d3c
f0a8fb376e4fb1613e69b101b943adca6555ed39
refs/heads/master
2020-03-31T09:47:05.443000
2018-10-08T16:28:21
2018-10-08T16:28:21
152,110,638
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package Questao01; public class Cliente { private int[] numeros; private Ordenador ordenador; public int[] ordenar(){ return ordenador.ordenarNum(numeros); } public void setOrdenadorBubble(){ ordenador = OrdenadorBuble.getInstance(); } public void setOrdenadorInsertion(){ ordenador = OrdenadorInsertion.getInstance(); } public void setOrdenadorMerge(){ ordenador = OrdenadorMerge.getInstance(); } public void setOrdenadorQuick(){ ordenador = OrdenadorQuick.getInstance(); } }
UTF-8
Java
571
java
Cliente.java
Java
[]
null
[]
package Questao01; public class Cliente { private int[] numeros; private Ordenador ordenador; public int[] ordenar(){ return ordenador.ordenarNum(numeros); } public void setOrdenadorBubble(){ ordenador = OrdenadorBuble.getInstance(); } public void setOrdenadorInsertion(){ ordenador = OrdenadorInsertion.getInstance(); } public void setOrdenadorMerge(){ ordenador = OrdenadorMerge.getInstance(); } public void setOrdenadorQuick(){ ordenador = OrdenadorQuick.getInstance(); } }
571
0.660245
0.656743
22
24.954546
18.187101
53
false
false
0
0
0
0
0
0
0.363636
false
false
1
2c41ee135c11e58d39688fd93c602020006cb52e
30,709,016,167,304
a5721d03524d9094f344bdc12746ca3b5579bc04
/hy-lyjc-industrial-operation-monitoring/src/main/java/net/cdsunrise/hy/lyjc/industrialoperationmonitoring/service/impl/EmergencyEventServiceImpl.java
f4507050bb687556f606393b2084cdddd01abacd
[]
no_license
yesewenrou/test
https://github.com/yesewenrou/test
2aeaa0ea09842eeed2b0e589895b4f00319bf13b
992a70bed383f5574e4cc0db539dd764d984e5c6
refs/heads/master
2023-02-16T21:02:59.801000
2021-01-20T02:31:17
2021-01-20T02:31:17
327,574,246
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package net.cdsunrise.hy.lyjc.industrialoperationmonitoring.service.impl; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.core.toolkit.Wrappers; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import net.cdsunrise.common.utility.vo.Result; import net.cdsunrise.hy.lydd.datadictionary.autoconfigure.feign.DataDictionaryFeignClient; import net.cdsunrise.hy.lydd.datadictionary.autoconfigure.feign.vo.DataDictionaryVO; import net.cdsunrise.hy.lyjc.industrialoperationmonitoring.entity.EmergencyEvent; import net.cdsunrise.hy.lyjc.industrialoperationmonitoring.entity.EmergencyEventAttachment; import net.cdsunrise.hy.lyjc.industrialoperationmonitoring.entity.EmergencyPlan; import net.cdsunrise.hy.lyjc.industrialoperationmonitoring.entity.typeenum.EmergencyEventAttachmentTypeEnum; import net.cdsunrise.hy.lyjc.industrialoperationmonitoring.entity.typeenum.EmergencyEventCheckStatusEnum; import net.cdsunrise.hy.lyjc.industrialoperationmonitoring.entity.typeenum.EmergencyEventStatusEnum; import net.cdsunrise.hy.lyjc.industrialoperationmonitoring.exception.ParamErrorException; import net.cdsunrise.hy.lyjc.industrialoperationmonitoring.mapper.EmergencyEventMapper; import net.cdsunrise.hy.lyjc.industrialoperationmonitoring.service.IEmergencyEventAttachmentService; import net.cdsunrise.hy.lyjc.industrialoperationmonitoring.service.IEmergencyEventKeywordService; import net.cdsunrise.hy.lyjc.industrialoperationmonitoring.service.IEmergencyEventService; import net.cdsunrise.hy.lyjc.industrialoperationmonitoring.service.IEmergencyPlanService; import net.cdsunrise.hy.lyjc.industrialoperationmonitoring.usermanage.domain.vo.resp.UserVO; import net.cdsunrise.hy.lyjc.industrialoperationmonitoring.usermanage.service.MenuService; import net.cdsunrise.hy.lyjc.industrialoperationmonitoring.usermanage.service.UserService; import net.cdsunrise.hy.lyjc.industrialoperationmonitoring.usermanage.service.feign.SsoFeignService; import net.cdsunrise.hy.lyjc.industrialoperationmonitoring.util.PageUtil; import net.cdsunrise.hy.lyjc.industrialoperationmonitoring.vo.*; import net.cdsunrise.hy.sso.starter.common.CustomContext; import net.cdsunrise.hy.sso.starter.domain.UserResp; import org.springframework.beans.BeanUtils; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.CollectionUtils; import org.springframework.util.StringUtils; import java.math.BigDecimal; import java.math.RoundingMode; import java.util.*; import java.util.stream.Collectors; /** * @author lijiafeng * @date 2019/11/27 17:22 */ @Service public class EmergencyEventServiceImpl extends ServiceImpl<EmergencyEventMapper, EmergencyEvent> implements IEmergencyEventService { /** * 反馈事件情况的接口的权限标识 */ private static final String PERMISSION_EMERGENCY_EVENT_FEEDBACK = "emergency-event:feedback"; private static final String EVENT_TYPE_PARENT_CODE = "EMERGENCY_EVENT_TYPE"; private static final String EVENT_LEVEL_PARENT_CODE = "EMERGENCY_EVENT_LEVEL"; private static final List<String> DISALLOW_EVENT_TYPE = Arrays.asList("014006", "014007"); private static final List<String> ORDER_COLUMNS = Arrays.asList("event_type", "event_level", "event_time", "event_status", "gmt_create"); private final IEmergencyEventAttachmentService emergencyEventAttachmentService; private final IEmergencyEventKeywordService emergencyEventKeywordService; private final IEmergencyPlanService emergencyPlanService; private final DataDictionaryFeignClient dataDictionaryFeignClient; private final UserService userService; private final MenuService menuService; private final SsoFeignService ssoFeignService; public EmergencyEventServiceImpl(IEmergencyEventAttachmentService emergencyEventAttachmentService, IEmergencyEventKeywordService emergencyEventKeywordService, IEmergencyPlanService emergencyPlanService, DataDictionaryFeignClient dataDictionaryFeignClient, UserService userService, MenuService menuService, SsoFeignService ssoFeignService) { this.emergencyEventAttachmentService = emergencyEventAttachmentService; this.emergencyEventKeywordService = emergencyEventKeywordService; this.emergencyPlanService = emergencyPlanService; this.dataDictionaryFeignClient = dataDictionaryFeignClient; this.userService = userService; this.menuService = menuService; this.ssoFeignService = ssoFeignService; } @Override @Transactional(rollbackFor = Exception.class) public Long saveEmergencyEvent(EmergencyEventAddVO emergencyEventAddVO) { return saveEmergencyEvent(Boolean.FALSE, EmergencyEventStatusEnum.WAIT_CHECK, emergencyEventAddVO); } @Override @Transactional(rollbackFor = Exception.class) public Long saveSystemEmergencyEvent(EmergencyEventAddVO emergencyEventAddVO) { if (!DISALLOW_EVENT_TYPE.contains(emergencyEventAddVO.getEventType())) { throw new ParamErrorException("只能新增交通拥堵事件或客流预警事件"); } return saveEmergencyEvent(Boolean.TRUE, EmergencyEventStatusEnum.CLOSED, emergencyEventAddVO); } private Long saveEmergencyEvent(Boolean isAutoCreated, EmergencyEventStatusEnum emergencyEventStatusEnum, EmergencyEventAddVO emergencyEventAddVO) { // 基础信息 Map<String, Map<String, DataDictionaryVO>> allEmergencyEventTypeAndLevel = getAllEmergencyEventTypeAndLevel(); checkEventTypeAndLevel(allEmergencyEventTypeAndLevel, emergencyEventAddVO.getEventType(), emergencyEventAddVO.getEventLevel()); EmergencyEvent emergencyEvent = new EmergencyEvent(); BeanUtils.copyProperties(emergencyEventAddVO, emergencyEvent); // 事件状态 emergencyEvent.setEventStatus(emergencyEventStatusEnum); emergencyEvent.setAutoCreated(isAutoCreated); // 存储 super.save(emergencyEvent); // 关键词 emergencyEventKeywordService.save(emergencyEvent.getId(), emergencyEventAddVO.getKeywords()); // 附件 List<EmergencyEventAttachment> scenePhotos = getAttachments(emergencyEvent.getId(), emergencyEventAddVO.getScenePhotos(), EmergencyEventAttachmentTypeEnum.EVENT_IMAGE); List<EmergencyEventAttachment> attachments = getAttachments(emergencyEvent.getId(), emergencyEventAddVO.getAttachments(), EmergencyEventAttachmentTypeEnum.EVENT_FILE); if (!CollectionUtils.isEmpty(scenePhotos)) { emergencyEventAttachmentService.saveBatch(scenePhotos); } if (!CollectionUtils.isEmpty(attachments)) { emergencyEventAttachmentService.saveBatch(attachments); } return emergencyEvent.getId(); } @Override @Transactional(rollbackFor = Exception.class) public void editEmergencyEvent(EmergencyEventEditVO emergencyEventEditVO) { EmergencyEvent emergencyEvent = super.getById(emergencyEventEditVO.getId()); if (Objects.isNull(emergencyEvent)) { throw new ParamErrorException("指定ID事件不存在"); } // 只能编辑状态为待审核的事件 if (!EmergencyEventStatusEnum.WAIT_CHECK.equals(emergencyEvent.getEventStatus())) { throw new ParamErrorException("只能编辑待审批事件"); } // 基础信息 Map<String, Map<String, DataDictionaryVO>> allEmergencyEventTypeAndLevel = getAllEmergencyEventTypeAndLevel(); checkEventTypeAndLevel(allEmergencyEventTypeAndLevel, emergencyEventEditVO.getEventType(), emergencyEventEditVO.getEventLevel()); BeanUtils.copyProperties(emergencyEventEditVO, emergencyEvent); // 更新 super.updateById(emergencyEvent); // 删除旧关键词 emergencyEventKeywordService.delete(emergencyEvent.getId()); // 重新存入关键词 emergencyEventKeywordService.save(emergencyEvent.getId(), emergencyEventEditVO.getKeywords()); // 附件 // 删除所有旧附件 QueryWrapper<EmergencyEventAttachment> queryWrapper = Wrappers.query(); queryWrapper.lambda() .eq(EmergencyEventAttachment::getEventId, emergencyEvent.getId()); emergencyEventAttachmentService.remove(queryWrapper); // 插入新附件 List<EmergencyEventAttachment> scenePhotos = getAttachments(emergencyEvent.getId(), emergencyEventEditVO.getScenePhotos(), EmergencyEventAttachmentTypeEnum.EVENT_IMAGE); List<EmergencyEventAttachment> attachments = getAttachments(emergencyEvent.getId(), emergencyEventEditVO.getAttachments(), EmergencyEventAttachmentTypeEnum.EVENT_FILE); if (!CollectionUtils.isEmpty(scenePhotos)) { emergencyEventAttachmentService.saveBatch(scenePhotos); } if (!CollectionUtils.isEmpty(attachments)) { emergencyEventAttachmentService.saveBatch(attachments); } } @Override public boolean checkEmergencyEvent(EmergencyEventCheckVO emergencyEventCheckVO) { EmergencyEvent emergencyEvent = super.getById(emergencyEventCheckVO.getId()); if (emergencyEvent == null) { throw new ParamErrorException("指定ID事件不存在"); } EmergencyEventStatusEnum eventStatus = emergencyEvent.getEventStatus(); if (eventStatus != EmergencyEventStatusEnum.WAIT_CHECK) { throw new ParamErrorException("事件不是待审核状态"); } Boolean checkFlag = emergencyEventCheckVO.getCheckFlag(); emergencyEvent.setCheckUserId(CustomContext.getTokenInfo().getUser().getId()); emergencyEvent.setCheckTime(new Date()); // 待处理或未通过 emergencyEvent.setEventStatus(checkFlag ? EmergencyEventStatusEnum.WAIT_DEAL : EmergencyEventStatusEnum.NO_PASS); emergencyEvent.setCheckStatus(checkFlag ? EmergencyEventCheckStatusEnum.PASS : EmergencyEventCheckStatusEnum.NO_PASS); emergencyEvent.setCheckContent(emergencyEventCheckVO.getCheckContent()); return super.updateById(emergencyEvent); } @Override public List<UserVO> listAllCanAssignUser() { return userService.findByPermission(PERMISSION_EMERGENCY_EVENT_FEEDBACK); } @Override public boolean assignEmergencyEvent(EmergencyEventAssignVO emergencyEventAssignVO) { EmergencyEvent emergencyEvent = super.getById(emergencyEventAssignVO.getId()); if (emergencyEvent == null) { throw new ParamErrorException("指定ID事件不存在"); } EmergencyEventStatusEnum eventStatus = emergencyEvent.getEventStatus(); if (eventStatus != EmergencyEventStatusEnum.WAIT_DEAL) { throw new ParamErrorException("事件不是待处理状态"); } Long assignedUserId = emergencyEventAssignVO.getAssignedUserId(); if (!menuService.userHasPermission(assignedUserId, PERMISSION_EMERGENCY_EVENT_FEEDBACK)) { throw new ParamErrorException("被指派人员无对应处理权限"); } // 待结案 emergencyEvent.setEventStatus(EmergencyEventStatusEnum.WAIT_CLOSE); emergencyEvent.setAssignedUserId(assignedUserId); emergencyEvent.setAssignerUserId(CustomContext.getTokenInfo().getUser().getId()); emergencyEvent.setAssignTime(new Date()); return super.updateById(emergencyEvent); } @Override @Transactional(rollbackFor = Exception.class) public boolean feedbackEmergencyEvent(EmergencyEventFeedbackVO emergencyEventFeedbackVO) { EmergencyEvent emergencyEvent = super.getById(emergencyEventFeedbackVO.getId()); if (emergencyEvent == null) { throw new ParamErrorException("指定ID事件不存在"); } EmergencyEventStatusEnum eventStatus = emergencyEvent.getEventStatus(); if (eventStatus != EmergencyEventStatusEnum.WAIT_CLOSE) { throw new ParamErrorException("事件不是待结案状态"); } Long currentUserId = CustomContext.getTokenInfo().getUser().getId(); if (!emergencyEvent.getAssignedUserId().equals(currentUserId)) { throw new ParamErrorException("只能由被指派人员反馈"); } emergencyEvent.setFeedbackContent(emergencyEventFeedbackVO.getFeedbackContent()); emergencyEvent.setFeedbackTime(new Date()); boolean success = super.updateById(emergencyEvent); // 附件 List<EmergencyEventAttachment> feedbackPhotos = getAttachments(emergencyEvent.getId(), emergencyEventFeedbackVO.getFeedbackPhotos(), EmergencyEventAttachmentTypeEnum.FEEDBACK_IMAGE); // 删除旧附件,多次反馈视为编辑 QueryWrapper<EmergencyEventAttachment> queryWrapper = Wrappers.query(); queryWrapper.lambda() .eq(EmergencyEventAttachment::getEventId, emergencyEventFeedbackVO.getId()) .eq(EmergencyEventAttachment::getType, EmergencyEventAttachmentTypeEnum.FEEDBACK_IMAGE); emergencyEventAttachmentService.remove(queryWrapper); if (!CollectionUtils.isEmpty(feedbackPhotos)) { emergencyEventAttachmentService.saveBatch(feedbackPhotos); } return success; } @Override @Transactional(rollbackFor = Exception.class) public boolean closeEmergencyEvent(EmergencyEventCloseVO emergencyEventCloseVO) { EmergencyEvent emergencyEvent = super.getById(emergencyEventCloseVO.getId()); if (emergencyEvent == null) { throw new ParamErrorException("指定ID事件不存在"); } EmergencyEventStatusEnum eventStatus = emergencyEvent.getEventStatus(); if (eventStatus != EmergencyEventStatusEnum.WAIT_DEAL && eventStatus != EmergencyEventStatusEnum.WAIT_CLOSE) { throw new ParamErrorException("事件不是待处理或待结案状态"); } // 已结案 emergencyEvent.setEventStatus(EmergencyEventStatusEnum.CLOSED); emergencyEvent.setCloseContent(emergencyEventCloseVO.getCloseContent()); emergencyEvent.setCloseTime(new Date()); emergencyEvent.setCloseUserId(CustomContext.getTokenInfo().getUser().getId()); boolean success = super.updateById(emergencyEvent); // 附件 List<EmergencyEventAttachment> closeAttachment = getAttachments(emergencyEvent.getId(), emergencyEventCloseVO.getCloseAttachments(), EmergencyEventAttachmentTypeEnum.CLOSE_FILE); if (!CollectionUtils.isEmpty(closeAttachment)) { emergencyEventAttachmentService.saveBatch(closeAttachment); } // 结案图片 List<EmergencyEventAttachment> closeImages = getAttachments(emergencyEvent.getId(), emergencyEventCloseVO.getCloseImages(), EmergencyEventAttachmentTypeEnum.CLOSE_IMAGE); if (!CollectionUtils.isEmpty(closeImages)) { emergencyEventAttachmentService.saveBatch(closeImages); } return success; } @Override public EmergencyEventVO getEmergencyEvent(Long id) { if (id == null) { throw new ParamErrorException("事件ID不能为空"); } // 基础信息 EmergencyEvent emergencyEvent = super.getById(id); if (emergencyEvent == null) { throw new ParamErrorException("事件不存在"); } // 关键词 Set<String> keywords = emergencyEventKeywordService.get(emergencyEvent.getId()); // 数据字典 Map<String, Map<String, DataDictionaryVO>> allEmergencyEventTypeAndLevel = getAllEmergencyEventTypeAndLevel(); return convertToVO(allEmergencyEventTypeAndLevel, emergencyEvent, keywords); } @Override public IPage<EmergencyEventVO> listEmergencyEvent(PageRequest<EmergencyEventCondition> pageRequest) { // 分页 Page<EmergencyEvent> page = new Page<>(pageRequest.getCurrent(), pageRequest.getSize()); QueryWrapper<EmergencyEvent> queryWrapper = Wrappers.query(); EmergencyEventCondition condition = pageRequest.getCondition(); //筛选 if (condition != null) { queryWrapper.lambda() .like(StringUtils.hasText(condition.getEventName()), EmergencyEvent::getEventName, condition.getEventName()) .eq(StringUtils.hasText(condition.getEventType()), EmergencyEvent::getEventType, condition.getEventType()) .eq(StringUtils.hasText(condition.getEventLevel()), EmergencyEvent::getEventLevel, condition.getEventLevel()) .eq(condition.getEventStatus() != null, EmergencyEvent::getEventStatus, condition.getEventStatus()) .eq(condition.getAssignedUserId() != null, EmergencyEvent::getAssignedUserId, condition.getAssignedUserId()); } //排序 List<PageRequest.OrderItem> orderItemList = pageRequest.getOrderItemList(); if (!CollectionUtils.isEmpty(orderItemList)) { PageUtil.setOrders(queryWrapper, ORDER_COLUMNS, orderItemList); } else { // 默认事件状态排序 queryWrapper.lambda().orderByAsc(EmergencyEvent::getEventStatus); } super.page(page, queryWrapper); // 关键词 Set<Long> ids = page.getRecords().stream().map(EmergencyEvent::getId).collect(Collectors.toSet()); Map<Long, Set<String>> keywordMap = emergencyEventKeywordService.getMap(ids); // 数据字典 Map<String, Map<String, DataDictionaryVO>> allEmergencyEventTypeAndLevel = getAllEmergencyEventTypeAndLevel(); return page.convert(emergencyEvent -> convertToVO(allEmergencyEventTypeAndLevel, emergencyEvent, keywordMap.getOrDefault(emergencyEvent.getId(), new HashSet<>(0)))); } @Override public void deleteEmergencyEvent(Long id) { // 删除基础信息 super.removeById(id); // 删除附件 QueryWrapper<EmergencyEventAttachment> queryWrapper = Wrappers.query(); queryWrapper.lambda() .eq(EmergencyEventAttachment::getEventId, id); emergencyEventAttachmentService.remove(queryWrapper); } @Override public List<EmergencyEventEvaluationVO> evaluate(Long id) { // 查询事件 LambdaQueryWrapper<EmergencyEvent> queryWrapper = Wrappers.lambdaQuery(); queryWrapper.select(EmergencyEvent::getEventType, EmergencyEvent::getEventLevel) .eq(EmergencyEvent::getId, id); EmergencyEvent emergencyEvent = getOne(queryWrapper); if (Objects.isNull(emergencyEvent)) { throw new ParamErrorException("指定ID的应急事件不存在"); } // 查询对应事件类型的应急预案 List<EmergencyPlan> emergencyPlans = emergencyPlanService.listForEvaluate(emergencyEvent.getEventType()); if (CollectionUtils.isEmpty(emergencyPlans)) { return new ArrayList<>(); } // 查询事件关键词 Set<String> eventKeywords = emergencyEventKeywordService.get(id); // 查询预案关键词 Set<Long> emergencyPlanIds = emergencyPlans.stream().map(EmergencyPlan::getId).collect(Collectors.toSet()); Map<Long, Set<String>> planKeywordMap = emergencyPlanService.getKeywordMap(emergencyPlanIds); // 开始评估 return emergencyPlans.stream().map(emergencyPlan -> { // 事件类型匹配,则占比20% BigDecimal fitRate = new BigDecimal("0.2").setScale(4, RoundingMode.HALF_UP); // 事件等级匹配,则占比20% if (emergencyEvent.getEventLevel().equals(emergencyPlan.getEventLevel())) { fitRate = fitRate.add(new BigDecimal("0.2")); } // 计算关键词定义占比=预案匹配的关键词/事件关键词总数*60% // 关键词匹配是指文本内容一致;若均不一致,则为0 Set<String> planKeywords = planKeywordMap.get(emergencyPlan.getId()); if (!CollectionUtils.isEmpty(eventKeywords) && !CollectionUtils.isEmpty(planKeywords)) { long keywordsFitCount = planKeywords.stream().filter(eventKeywords::contains).count(); BigDecimal keywordsFitRate = BigDecimal.valueOf(keywordsFitCount).divide(BigDecimal.valueOf(eventKeywords.size()), 4, RoundingMode.HALF_UP); fitRate = fitRate.add(keywordsFitRate.multiply(new BigDecimal("0.6"))); } EmergencyEventEvaluationVO emergencyEventEvaluationVO = new EmergencyEventEvaluationVO(); emergencyEventEvaluationVO.setEmergencyPlanId(emergencyPlan.getId()); emergencyEventEvaluationVO.setEmergencyPlanName(emergencyPlan.getPlanName()); emergencyEventEvaluationVO.setFitRate(fitRate); return emergencyEventEvaluationVO; }).sorted(Comparator.comparing(EmergencyEventEvaluationVO::getFitRate).reversed()).collect(Collectors.toList()); } private String getUserName(Long userId) { if (userId == null) { return null; } // 获取修改人名称 UserResp userResp = userService.getUserById(userId); if (userResp != null) { return userResp.getUserName(); } return null; } private EmergencyEventVO convertToVO(Map<String, Map<String, DataDictionaryVO>> allEmergencyEventTypeAndLevel, EmergencyEvent emergencyEvent, Set<String> keywords) { EmergencyEventVO emergencyEventVO = new EmergencyEventVO(); BeanUtils.copyProperties(emergencyEvent, emergencyEventVO); DataDictionaryVO eventType = getEventType(allEmergencyEventTypeAndLevel, emergencyEvent.getEventType()); if (eventType != null) { emergencyEventVO.setEventTypeDesc(eventType.getName()); } DataDictionaryVO eventLevel = getEventLevel(allEmergencyEventTypeAndLevel, emergencyEvent.getEventLevel()); if (eventLevel != null) { emergencyEventVO.setEventLevelDesc(eventLevel.getName()); } // 关键词 emergencyEventVO.setKeywords(keywords); // 现场照片 List<EmergencyEventVO.Attachment> scenePhotos = getAttachmentVos(emergencyEvent, EmergencyEventAttachmentTypeEnum.EVENT_IMAGE); emergencyEventVO.setScenePhotos(scenePhotos); // 资料附件 List<EmergencyEventVO.Attachment> attachments = getAttachmentVos(emergencyEvent, EmergencyEventAttachmentTypeEnum.EVENT_FILE); emergencyEventVO.setAttachments(attachments); // 事件状态 emergencyEventVO.setEventStatusDesc(emergencyEventVO.getEventStatus().getDesc()); // 审核状态 EmergencyEventCheckStatusEnum checkStatus = emergencyEventVO.getCheckStatus(); if (checkStatus != null) { emergencyEventVO.setCheckStatusDesc(checkStatus.getDesc()); } // 获取用户名 Long checkUserId = emergencyEventVO.getCheckUserId() == null ? 0 : emergencyEventVO.getCheckUserId(); Long assignedUserId = emergencyEventVO.getAssignedUserId() == null ? 0 : emergencyEventVO.getAssignedUserId(); Long assignerUserId = emergencyEventVO.getAssignerUserId() == null ? 0 : emergencyEventVO.getAssignerUserId(); Long closeUserId = emergencyEventVO.getCloseUserId() == null ? 0 : emergencyEventVO.getCloseUserId(); List<Long> ids = Arrays.asList(checkUserId, assignedUserId, assignerUserId, closeUserId); List<UserVO> userInfoList = userList(ids); // 审核人员名称 emergencyEventVO.setCheckUserName(getUserNameByIdInList(userInfoList, checkUserId)); // 被指派人员名称 emergencyEventVO.setAssignedUserName(getUserNameByIdInList(userInfoList, assignedUserId)); // 指派人名称 emergencyEventVO.setAssignerUserName(getUserNameByIdInList(userInfoList, assignerUserId)); // 结案人名称 emergencyEventVO.setCloseUserName(getUserNameByIdInList(userInfoList, closeUserId)); // 反馈现场照片 List<EmergencyEventVO.Attachment> feedbackPhotos = getAttachmentVos(emergencyEvent, EmergencyEventAttachmentTypeEnum.FEEDBACK_IMAGE); emergencyEventVO.setFeedbackPhotos(feedbackPhotos); // 结案附件 List<EmergencyEventVO.Attachment> closeAttachments = getAttachmentVos(emergencyEvent, EmergencyEventAttachmentTypeEnum.CLOSE_FILE); emergencyEventVO.setCloseAttachments(closeAttachments); // 结案图片 List<EmergencyEventVO.Attachment> closeImages = getAttachmentVos(emergencyEvent, EmergencyEventAttachmentTypeEnum.CLOSE_IMAGE); emergencyEventVO.setCloseImages(closeImages); return emergencyEventVO; } private List<UserVO> userList(List<Long> ids) { net.cdsunrise.hy.lyjc.industrialoperationmonitoring.usermanage.domain.vo.req.PageRequest pageRequest = new net.cdsunrise.hy.lyjc.industrialoperationmonitoring.usermanage.domain.vo.req.PageRequest(); pageRequest.setPage(1); pageRequest.setSize(ids.size()); pageRequest.setUserIds(ids); Result<Page<UserVO>> result = ssoFeignService.userList(pageRequest); if (result.getSuccess()) { return result.getData().getRecords(); } else { return new ArrayList<UserVO>(); } } private String getUserNameByIdInList(List<UserVO> userList, long id) { if (CollectionUtils.isEmpty(userList)) { return ""; } return userList.stream().filter(userVO -> userVO.getId().equals(id)).findFirst().map(UserVO::getUserName).orElse(""); } private Map<String, Map<String, DataDictionaryVO>> getAllEmergencyEventTypeAndLevel() { Result<Map<String, DataDictionaryVO>> result = dataDictionaryFeignClient.getByCodes(new String[]{EVENT_TYPE_PARENT_CODE, EVENT_LEVEL_PARENT_CODE}); Map<String, DataDictionaryVO> data = result.getData(); if (data == null || data.isEmpty()) { throw new RuntimeException("事件类型及事件等级未在数据字典定义"); } Map<String, Map<String, DataDictionaryVO>> map = new HashMap<>(2); DataDictionaryVO eventTypeDataDictionaryVO = data.get(EVENT_TYPE_PARENT_CODE); if (eventTypeDataDictionaryVO == null) { throw new RuntimeException("事件类型未在数据字典定义"); } DataDictionaryVO eventLevelDataDictionaryVO = data.get(EVENT_LEVEL_PARENT_CODE); if (eventLevelDataDictionaryVO == null) { throw new RuntimeException("事件等级未在数据字典定义"); } map.put(EVENT_LEVEL_PARENT_CODE, eventLevelDataDictionaryVO.getChildren().stream().collect(Collectors.toMap(DataDictionaryVO::getCode, item -> item))); map.put(EVENT_TYPE_PARENT_CODE, eventTypeDataDictionaryVO.getChildren().stream().collect(Collectors.toMap(DataDictionaryVO::getCode, item -> item))); return map; } private DataDictionaryVO getDictionary(Map<String, DataDictionaryVO> allTypes, String type) { if (allTypes == null || allTypes.isEmpty()) { return null; } return allTypes.get(type); } private DataDictionaryVO getEventType(Map<String, Map<String, DataDictionaryVO>> map, String type) { Map<String, DataDictionaryVO> allTypes = map.get(EVENT_TYPE_PARENT_CODE); return getDictionary(allTypes, type); } private DataDictionaryVO getEventLevel(Map<String, Map<String, DataDictionaryVO>> map, String type) { Map<String, DataDictionaryVO> allTypes = map.get(EVENT_LEVEL_PARENT_CODE); return getDictionary(allTypes, type); } private void checkEventType(Map<String, Map<String, DataDictionaryVO>> map, String type) { DataDictionaryVO dataDictionaryVO = getEventType(map, type); if (dataDictionaryVO == null) { throw new ParamErrorException("未知的事件类型编码: " + type); } } private void checkEventLevel(Map<String, Map<String, DataDictionaryVO>> map, String type) { DataDictionaryVO dataDictionaryVO = getEventLevel(map, type); if (dataDictionaryVO == null) { throw new ParamErrorException("未知的事件等级编码: " + type); } } private void checkEventTypeAndLevel(Map<String, Map<String, DataDictionaryVO>> map, String eventType, String eventLevel) { checkEventType(map, eventType); checkEventLevel(map, eventLevel); } private List<EmergencyEventAttachment> getAttachments(Long eventId, List<EmergencyEventVO.Attachment> attachments, EmergencyEventAttachmentTypeEnum type) { if (CollectionUtils.isEmpty(attachments)) { return null; } return attachments.stream().map(attachment -> { EmergencyEventAttachment emergencyEventAttachment = new EmergencyEventAttachment(); BeanUtils.copyProperties(attachment, emergencyEventAttachment, "id"); emergencyEventAttachment.setEventId(eventId); emergencyEventAttachment.setType(type); return emergencyEventAttachment; }).collect(Collectors.toList()); } private List<EmergencyEventVO.Attachment> getAttachmentVos(EmergencyEvent emergencyEvent, EmergencyEventAttachmentTypeEnum type) { QueryWrapper<EmergencyEventAttachment> queryWrapper = Wrappers.query(); queryWrapper.lambda() .eq(EmergencyEventAttachment::getEventId, emergencyEvent.getId()) .eq(EmergencyEventAttachment::getType, type); List<EmergencyEventAttachment> emergencyEventAttachments = emergencyEventAttachmentService.list(queryWrapper); if (CollectionUtils.isEmpty(emergencyEventAttachments)) { return null; } return emergencyEventAttachments.stream().map(emergencyEventAttachment -> { EmergencyEventVO.Attachment attachment = new EmergencyEventVO.Attachment(); BeanUtils.copyProperties(emergencyEventAttachment, attachment); return attachment; }).collect(Collectors.toList()); } }
UTF-8
Java
30,404
java
EmergencyEventServiceImpl.java
Java
[ { "context": "mport java.util.stream.Collectors;\n\n/**\n * @author lijiafeng\n * @date 2019/11/27 17:22\n */\n@Service\npublic cla", "end": 2830, "score": 0.9972355961799622, "start": 2821, "tag": "USERNAME", "value": "lijiafeng" } ]
null
[]
package net.cdsunrise.hy.lyjc.industrialoperationmonitoring.service.impl; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.core.toolkit.Wrappers; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import net.cdsunrise.common.utility.vo.Result; import net.cdsunrise.hy.lydd.datadictionary.autoconfigure.feign.DataDictionaryFeignClient; import net.cdsunrise.hy.lydd.datadictionary.autoconfigure.feign.vo.DataDictionaryVO; import net.cdsunrise.hy.lyjc.industrialoperationmonitoring.entity.EmergencyEvent; import net.cdsunrise.hy.lyjc.industrialoperationmonitoring.entity.EmergencyEventAttachment; import net.cdsunrise.hy.lyjc.industrialoperationmonitoring.entity.EmergencyPlan; import net.cdsunrise.hy.lyjc.industrialoperationmonitoring.entity.typeenum.EmergencyEventAttachmentTypeEnum; import net.cdsunrise.hy.lyjc.industrialoperationmonitoring.entity.typeenum.EmergencyEventCheckStatusEnum; import net.cdsunrise.hy.lyjc.industrialoperationmonitoring.entity.typeenum.EmergencyEventStatusEnum; import net.cdsunrise.hy.lyjc.industrialoperationmonitoring.exception.ParamErrorException; import net.cdsunrise.hy.lyjc.industrialoperationmonitoring.mapper.EmergencyEventMapper; import net.cdsunrise.hy.lyjc.industrialoperationmonitoring.service.IEmergencyEventAttachmentService; import net.cdsunrise.hy.lyjc.industrialoperationmonitoring.service.IEmergencyEventKeywordService; import net.cdsunrise.hy.lyjc.industrialoperationmonitoring.service.IEmergencyEventService; import net.cdsunrise.hy.lyjc.industrialoperationmonitoring.service.IEmergencyPlanService; import net.cdsunrise.hy.lyjc.industrialoperationmonitoring.usermanage.domain.vo.resp.UserVO; import net.cdsunrise.hy.lyjc.industrialoperationmonitoring.usermanage.service.MenuService; import net.cdsunrise.hy.lyjc.industrialoperationmonitoring.usermanage.service.UserService; import net.cdsunrise.hy.lyjc.industrialoperationmonitoring.usermanage.service.feign.SsoFeignService; import net.cdsunrise.hy.lyjc.industrialoperationmonitoring.util.PageUtil; import net.cdsunrise.hy.lyjc.industrialoperationmonitoring.vo.*; import net.cdsunrise.hy.sso.starter.common.CustomContext; import net.cdsunrise.hy.sso.starter.domain.UserResp; import org.springframework.beans.BeanUtils; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.CollectionUtils; import org.springframework.util.StringUtils; import java.math.BigDecimal; import java.math.RoundingMode; import java.util.*; import java.util.stream.Collectors; /** * @author lijiafeng * @date 2019/11/27 17:22 */ @Service public class EmergencyEventServiceImpl extends ServiceImpl<EmergencyEventMapper, EmergencyEvent> implements IEmergencyEventService { /** * 反馈事件情况的接口的权限标识 */ private static final String PERMISSION_EMERGENCY_EVENT_FEEDBACK = "emergency-event:feedback"; private static final String EVENT_TYPE_PARENT_CODE = "EMERGENCY_EVENT_TYPE"; private static final String EVENT_LEVEL_PARENT_CODE = "EMERGENCY_EVENT_LEVEL"; private static final List<String> DISALLOW_EVENT_TYPE = Arrays.asList("014006", "014007"); private static final List<String> ORDER_COLUMNS = Arrays.asList("event_type", "event_level", "event_time", "event_status", "gmt_create"); private final IEmergencyEventAttachmentService emergencyEventAttachmentService; private final IEmergencyEventKeywordService emergencyEventKeywordService; private final IEmergencyPlanService emergencyPlanService; private final DataDictionaryFeignClient dataDictionaryFeignClient; private final UserService userService; private final MenuService menuService; private final SsoFeignService ssoFeignService; public EmergencyEventServiceImpl(IEmergencyEventAttachmentService emergencyEventAttachmentService, IEmergencyEventKeywordService emergencyEventKeywordService, IEmergencyPlanService emergencyPlanService, DataDictionaryFeignClient dataDictionaryFeignClient, UserService userService, MenuService menuService, SsoFeignService ssoFeignService) { this.emergencyEventAttachmentService = emergencyEventAttachmentService; this.emergencyEventKeywordService = emergencyEventKeywordService; this.emergencyPlanService = emergencyPlanService; this.dataDictionaryFeignClient = dataDictionaryFeignClient; this.userService = userService; this.menuService = menuService; this.ssoFeignService = ssoFeignService; } @Override @Transactional(rollbackFor = Exception.class) public Long saveEmergencyEvent(EmergencyEventAddVO emergencyEventAddVO) { return saveEmergencyEvent(Boolean.FALSE, EmergencyEventStatusEnum.WAIT_CHECK, emergencyEventAddVO); } @Override @Transactional(rollbackFor = Exception.class) public Long saveSystemEmergencyEvent(EmergencyEventAddVO emergencyEventAddVO) { if (!DISALLOW_EVENT_TYPE.contains(emergencyEventAddVO.getEventType())) { throw new ParamErrorException("只能新增交通拥堵事件或客流预警事件"); } return saveEmergencyEvent(Boolean.TRUE, EmergencyEventStatusEnum.CLOSED, emergencyEventAddVO); } private Long saveEmergencyEvent(Boolean isAutoCreated, EmergencyEventStatusEnum emergencyEventStatusEnum, EmergencyEventAddVO emergencyEventAddVO) { // 基础信息 Map<String, Map<String, DataDictionaryVO>> allEmergencyEventTypeAndLevel = getAllEmergencyEventTypeAndLevel(); checkEventTypeAndLevel(allEmergencyEventTypeAndLevel, emergencyEventAddVO.getEventType(), emergencyEventAddVO.getEventLevel()); EmergencyEvent emergencyEvent = new EmergencyEvent(); BeanUtils.copyProperties(emergencyEventAddVO, emergencyEvent); // 事件状态 emergencyEvent.setEventStatus(emergencyEventStatusEnum); emergencyEvent.setAutoCreated(isAutoCreated); // 存储 super.save(emergencyEvent); // 关键词 emergencyEventKeywordService.save(emergencyEvent.getId(), emergencyEventAddVO.getKeywords()); // 附件 List<EmergencyEventAttachment> scenePhotos = getAttachments(emergencyEvent.getId(), emergencyEventAddVO.getScenePhotos(), EmergencyEventAttachmentTypeEnum.EVENT_IMAGE); List<EmergencyEventAttachment> attachments = getAttachments(emergencyEvent.getId(), emergencyEventAddVO.getAttachments(), EmergencyEventAttachmentTypeEnum.EVENT_FILE); if (!CollectionUtils.isEmpty(scenePhotos)) { emergencyEventAttachmentService.saveBatch(scenePhotos); } if (!CollectionUtils.isEmpty(attachments)) { emergencyEventAttachmentService.saveBatch(attachments); } return emergencyEvent.getId(); } @Override @Transactional(rollbackFor = Exception.class) public void editEmergencyEvent(EmergencyEventEditVO emergencyEventEditVO) { EmergencyEvent emergencyEvent = super.getById(emergencyEventEditVO.getId()); if (Objects.isNull(emergencyEvent)) { throw new ParamErrorException("指定ID事件不存在"); } // 只能编辑状态为待审核的事件 if (!EmergencyEventStatusEnum.WAIT_CHECK.equals(emergencyEvent.getEventStatus())) { throw new ParamErrorException("只能编辑待审批事件"); } // 基础信息 Map<String, Map<String, DataDictionaryVO>> allEmergencyEventTypeAndLevel = getAllEmergencyEventTypeAndLevel(); checkEventTypeAndLevel(allEmergencyEventTypeAndLevel, emergencyEventEditVO.getEventType(), emergencyEventEditVO.getEventLevel()); BeanUtils.copyProperties(emergencyEventEditVO, emergencyEvent); // 更新 super.updateById(emergencyEvent); // 删除旧关键词 emergencyEventKeywordService.delete(emergencyEvent.getId()); // 重新存入关键词 emergencyEventKeywordService.save(emergencyEvent.getId(), emergencyEventEditVO.getKeywords()); // 附件 // 删除所有旧附件 QueryWrapper<EmergencyEventAttachment> queryWrapper = Wrappers.query(); queryWrapper.lambda() .eq(EmergencyEventAttachment::getEventId, emergencyEvent.getId()); emergencyEventAttachmentService.remove(queryWrapper); // 插入新附件 List<EmergencyEventAttachment> scenePhotos = getAttachments(emergencyEvent.getId(), emergencyEventEditVO.getScenePhotos(), EmergencyEventAttachmentTypeEnum.EVENT_IMAGE); List<EmergencyEventAttachment> attachments = getAttachments(emergencyEvent.getId(), emergencyEventEditVO.getAttachments(), EmergencyEventAttachmentTypeEnum.EVENT_FILE); if (!CollectionUtils.isEmpty(scenePhotos)) { emergencyEventAttachmentService.saveBatch(scenePhotos); } if (!CollectionUtils.isEmpty(attachments)) { emergencyEventAttachmentService.saveBatch(attachments); } } @Override public boolean checkEmergencyEvent(EmergencyEventCheckVO emergencyEventCheckVO) { EmergencyEvent emergencyEvent = super.getById(emergencyEventCheckVO.getId()); if (emergencyEvent == null) { throw new ParamErrorException("指定ID事件不存在"); } EmergencyEventStatusEnum eventStatus = emergencyEvent.getEventStatus(); if (eventStatus != EmergencyEventStatusEnum.WAIT_CHECK) { throw new ParamErrorException("事件不是待审核状态"); } Boolean checkFlag = emergencyEventCheckVO.getCheckFlag(); emergencyEvent.setCheckUserId(CustomContext.getTokenInfo().getUser().getId()); emergencyEvent.setCheckTime(new Date()); // 待处理或未通过 emergencyEvent.setEventStatus(checkFlag ? EmergencyEventStatusEnum.WAIT_DEAL : EmergencyEventStatusEnum.NO_PASS); emergencyEvent.setCheckStatus(checkFlag ? EmergencyEventCheckStatusEnum.PASS : EmergencyEventCheckStatusEnum.NO_PASS); emergencyEvent.setCheckContent(emergencyEventCheckVO.getCheckContent()); return super.updateById(emergencyEvent); } @Override public List<UserVO> listAllCanAssignUser() { return userService.findByPermission(PERMISSION_EMERGENCY_EVENT_FEEDBACK); } @Override public boolean assignEmergencyEvent(EmergencyEventAssignVO emergencyEventAssignVO) { EmergencyEvent emergencyEvent = super.getById(emergencyEventAssignVO.getId()); if (emergencyEvent == null) { throw new ParamErrorException("指定ID事件不存在"); } EmergencyEventStatusEnum eventStatus = emergencyEvent.getEventStatus(); if (eventStatus != EmergencyEventStatusEnum.WAIT_DEAL) { throw new ParamErrorException("事件不是待处理状态"); } Long assignedUserId = emergencyEventAssignVO.getAssignedUserId(); if (!menuService.userHasPermission(assignedUserId, PERMISSION_EMERGENCY_EVENT_FEEDBACK)) { throw new ParamErrorException("被指派人员无对应处理权限"); } // 待结案 emergencyEvent.setEventStatus(EmergencyEventStatusEnum.WAIT_CLOSE); emergencyEvent.setAssignedUserId(assignedUserId); emergencyEvent.setAssignerUserId(CustomContext.getTokenInfo().getUser().getId()); emergencyEvent.setAssignTime(new Date()); return super.updateById(emergencyEvent); } @Override @Transactional(rollbackFor = Exception.class) public boolean feedbackEmergencyEvent(EmergencyEventFeedbackVO emergencyEventFeedbackVO) { EmergencyEvent emergencyEvent = super.getById(emergencyEventFeedbackVO.getId()); if (emergencyEvent == null) { throw new ParamErrorException("指定ID事件不存在"); } EmergencyEventStatusEnum eventStatus = emergencyEvent.getEventStatus(); if (eventStatus != EmergencyEventStatusEnum.WAIT_CLOSE) { throw new ParamErrorException("事件不是待结案状态"); } Long currentUserId = CustomContext.getTokenInfo().getUser().getId(); if (!emergencyEvent.getAssignedUserId().equals(currentUserId)) { throw new ParamErrorException("只能由被指派人员反馈"); } emergencyEvent.setFeedbackContent(emergencyEventFeedbackVO.getFeedbackContent()); emergencyEvent.setFeedbackTime(new Date()); boolean success = super.updateById(emergencyEvent); // 附件 List<EmergencyEventAttachment> feedbackPhotos = getAttachments(emergencyEvent.getId(), emergencyEventFeedbackVO.getFeedbackPhotos(), EmergencyEventAttachmentTypeEnum.FEEDBACK_IMAGE); // 删除旧附件,多次反馈视为编辑 QueryWrapper<EmergencyEventAttachment> queryWrapper = Wrappers.query(); queryWrapper.lambda() .eq(EmergencyEventAttachment::getEventId, emergencyEventFeedbackVO.getId()) .eq(EmergencyEventAttachment::getType, EmergencyEventAttachmentTypeEnum.FEEDBACK_IMAGE); emergencyEventAttachmentService.remove(queryWrapper); if (!CollectionUtils.isEmpty(feedbackPhotos)) { emergencyEventAttachmentService.saveBatch(feedbackPhotos); } return success; } @Override @Transactional(rollbackFor = Exception.class) public boolean closeEmergencyEvent(EmergencyEventCloseVO emergencyEventCloseVO) { EmergencyEvent emergencyEvent = super.getById(emergencyEventCloseVO.getId()); if (emergencyEvent == null) { throw new ParamErrorException("指定ID事件不存在"); } EmergencyEventStatusEnum eventStatus = emergencyEvent.getEventStatus(); if (eventStatus != EmergencyEventStatusEnum.WAIT_DEAL && eventStatus != EmergencyEventStatusEnum.WAIT_CLOSE) { throw new ParamErrorException("事件不是待处理或待结案状态"); } // 已结案 emergencyEvent.setEventStatus(EmergencyEventStatusEnum.CLOSED); emergencyEvent.setCloseContent(emergencyEventCloseVO.getCloseContent()); emergencyEvent.setCloseTime(new Date()); emergencyEvent.setCloseUserId(CustomContext.getTokenInfo().getUser().getId()); boolean success = super.updateById(emergencyEvent); // 附件 List<EmergencyEventAttachment> closeAttachment = getAttachments(emergencyEvent.getId(), emergencyEventCloseVO.getCloseAttachments(), EmergencyEventAttachmentTypeEnum.CLOSE_FILE); if (!CollectionUtils.isEmpty(closeAttachment)) { emergencyEventAttachmentService.saveBatch(closeAttachment); } // 结案图片 List<EmergencyEventAttachment> closeImages = getAttachments(emergencyEvent.getId(), emergencyEventCloseVO.getCloseImages(), EmergencyEventAttachmentTypeEnum.CLOSE_IMAGE); if (!CollectionUtils.isEmpty(closeImages)) { emergencyEventAttachmentService.saveBatch(closeImages); } return success; } @Override public EmergencyEventVO getEmergencyEvent(Long id) { if (id == null) { throw new ParamErrorException("事件ID不能为空"); } // 基础信息 EmergencyEvent emergencyEvent = super.getById(id); if (emergencyEvent == null) { throw new ParamErrorException("事件不存在"); } // 关键词 Set<String> keywords = emergencyEventKeywordService.get(emergencyEvent.getId()); // 数据字典 Map<String, Map<String, DataDictionaryVO>> allEmergencyEventTypeAndLevel = getAllEmergencyEventTypeAndLevel(); return convertToVO(allEmergencyEventTypeAndLevel, emergencyEvent, keywords); } @Override public IPage<EmergencyEventVO> listEmergencyEvent(PageRequest<EmergencyEventCondition> pageRequest) { // 分页 Page<EmergencyEvent> page = new Page<>(pageRequest.getCurrent(), pageRequest.getSize()); QueryWrapper<EmergencyEvent> queryWrapper = Wrappers.query(); EmergencyEventCondition condition = pageRequest.getCondition(); //筛选 if (condition != null) { queryWrapper.lambda() .like(StringUtils.hasText(condition.getEventName()), EmergencyEvent::getEventName, condition.getEventName()) .eq(StringUtils.hasText(condition.getEventType()), EmergencyEvent::getEventType, condition.getEventType()) .eq(StringUtils.hasText(condition.getEventLevel()), EmergencyEvent::getEventLevel, condition.getEventLevel()) .eq(condition.getEventStatus() != null, EmergencyEvent::getEventStatus, condition.getEventStatus()) .eq(condition.getAssignedUserId() != null, EmergencyEvent::getAssignedUserId, condition.getAssignedUserId()); } //排序 List<PageRequest.OrderItem> orderItemList = pageRequest.getOrderItemList(); if (!CollectionUtils.isEmpty(orderItemList)) { PageUtil.setOrders(queryWrapper, ORDER_COLUMNS, orderItemList); } else { // 默认事件状态排序 queryWrapper.lambda().orderByAsc(EmergencyEvent::getEventStatus); } super.page(page, queryWrapper); // 关键词 Set<Long> ids = page.getRecords().stream().map(EmergencyEvent::getId).collect(Collectors.toSet()); Map<Long, Set<String>> keywordMap = emergencyEventKeywordService.getMap(ids); // 数据字典 Map<String, Map<String, DataDictionaryVO>> allEmergencyEventTypeAndLevel = getAllEmergencyEventTypeAndLevel(); return page.convert(emergencyEvent -> convertToVO(allEmergencyEventTypeAndLevel, emergencyEvent, keywordMap.getOrDefault(emergencyEvent.getId(), new HashSet<>(0)))); } @Override public void deleteEmergencyEvent(Long id) { // 删除基础信息 super.removeById(id); // 删除附件 QueryWrapper<EmergencyEventAttachment> queryWrapper = Wrappers.query(); queryWrapper.lambda() .eq(EmergencyEventAttachment::getEventId, id); emergencyEventAttachmentService.remove(queryWrapper); } @Override public List<EmergencyEventEvaluationVO> evaluate(Long id) { // 查询事件 LambdaQueryWrapper<EmergencyEvent> queryWrapper = Wrappers.lambdaQuery(); queryWrapper.select(EmergencyEvent::getEventType, EmergencyEvent::getEventLevel) .eq(EmergencyEvent::getId, id); EmergencyEvent emergencyEvent = getOne(queryWrapper); if (Objects.isNull(emergencyEvent)) { throw new ParamErrorException("指定ID的应急事件不存在"); } // 查询对应事件类型的应急预案 List<EmergencyPlan> emergencyPlans = emergencyPlanService.listForEvaluate(emergencyEvent.getEventType()); if (CollectionUtils.isEmpty(emergencyPlans)) { return new ArrayList<>(); } // 查询事件关键词 Set<String> eventKeywords = emergencyEventKeywordService.get(id); // 查询预案关键词 Set<Long> emergencyPlanIds = emergencyPlans.stream().map(EmergencyPlan::getId).collect(Collectors.toSet()); Map<Long, Set<String>> planKeywordMap = emergencyPlanService.getKeywordMap(emergencyPlanIds); // 开始评估 return emergencyPlans.stream().map(emergencyPlan -> { // 事件类型匹配,则占比20% BigDecimal fitRate = new BigDecimal("0.2").setScale(4, RoundingMode.HALF_UP); // 事件等级匹配,则占比20% if (emergencyEvent.getEventLevel().equals(emergencyPlan.getEventLevel())) { fitRate = fitRate.add(new BigDecimal("0.2")); } // 计算关键词定义占比=预案匹配的关键词/事件关键词总数*60% // 关键词匹配是指文本内容一致;若均不一致,则为0 Set<String> planKeywords = planKeywordMap.get(emergencyPlan.getId()); if (!CollectionUtils.isEmpty(eventKeywords) && !CollectionUtils.isEmpty(planKeywords)) { long keywordsFitCount = planKeywords.stream().filter(eventKeywords::contains).count(); BigDecimal keywordsFitRate = BigDecimal.valueOf(keywordsFitCount).divide(BigDecimal.valueOf(eventKeywords.size()), 4, RoundingMode.HALF_UP); fitRate = fitRate.add(keywordsFitRate.multiply(new BigDecimal("0.6"))); } EmergencyEventEvaluationVO emergencyEventEvaluationVO = new EmergencyEventEvaluationVO(); emergencyEventEvaluationVO.setEmergencyPlanId(emergencyPlan.getId()); emergencyEventEvaluationVO.setEmergencyPlanName(emergencyPlan.getPlanName()); emergencyEventEvaluationVO.setFitRate(fitRate); return emergencyEventEvaluationVO; }).sorted(Comparator.comparing(EmergencyEventEvaluationVO::getFitRate).reversed()).collect(Collectors.toList()); } private String getUserName(Long userId) { if (userId == null) { return null; } // 获取修改人名称 UserResp userResp = userService.getUserById(userId); if (userResp != null) { return userResp.getUserName(); } return null; } private EmergencyEventVO convertToVO(Map<String, Map<String, DataDictionaryVO>> allEmergencyEventTypeAndLevel, EmergencyEvent emergencyEvent, Set<String> keywords) { EmergencyEventVO emergencyEventVO = new EmergencyEventVO(); BeanUtils.copyProperties(emergencyEvent, emergencyEventVO); DataDictionaryVO eventType = getEventType(allEmergencyEventTypeAndLevel, emergencyEvent.getEventType()); if (eventType != null) { emergencyEventVO.setEventTypeDesc(eventType.getName()); } DataDictionaryVO eventLevel = getEventLevel(allEmergencyEventTypeAndLevel, emergencyEvent.getEventLevel()); if (eventLevel != null) { emergencyEventVO.setEventLevelDesc(eventLevel.getName()); } // 关键词 emergencyEventVO.setKeywords(keywords); // 现场照片 List<EmergencyEventVO.Attachment> scenePhotos = getAttachmentVos(emergencyEvent, EmergencyEventAttachmentTypeEnum.EVENT_IMAGE); emergencyEventVO.setScenePhotos(scenePhotos); // 资料附件 List<EmergencyEventVO.Attachment> attachments = getAttachmentVos(emergencyEvent, EmergencyEventAttachmentTypeEnum.EVENT_FILE); emergencyEventVO.setAttachments(attachments); // 事件状态 emergencyEventVO.setEventStatusDesc(emergencyEventVO.getEventStatus().getDesc()); // 审核状态 EmergencyEventCheckStatusEnum checkStatus = emergencyEventVO.getCheckStatus(); if (checkStatus != null) { emergencyEventVO.setCheckStatusDesc(checkStatus.getDesc()); } // 获取用户名 Long checkUserId = emergencyEventVO.getCheckUserId() == null ? 0 : emergencyEventVO.getCheckUserId(); Long assignedUserId = emergencyEventVO.getAssignedUserId() == null ? 0 : emergencyEventVO.getAssignedUserId(); Long assignerUserId = emergencyEventVO.getAssignerUserId() == null ? 0 : emergencyEventVO.getAssignerUserId(); Long closeUserId = emergencyEventVO.getCloseUserId() == null ? 0 : emergencyEventVO.getCloseUserId(); List<Long> ids = Arrays.asList(checkUserId, assignedUserId, assignerUserId, closeUserId); List<UserVO> userInfoList = userList(ids); // 审核人员名称 emergencyEventVO.setCheckUserName(getUserNameByIdInList(userInfoList, checkUserId)); // 被指派人员名称 emergencyEventVO.setAssignedUserName(getUserNameByIdInList(userInfoList, assignedUserId)); // 指派人名称 emergencyEventVO.setAssignerUserName(getUserNameByIdInList(userInfoList, assignerUserId)); // 结案人名称 emergencyEventVO.setCloseUserName(getUserNameByIdInList(userInfoList, closeUserId)); // 反馈现场照片 List<EmergencyEventVO.Attachment> feedbackPhotos = getAttachmentVos(emergencyEvent, EmergencyEventAttachmentTypeEnum.FEEDBACK_IMAGE); emergencyEventVO.setFeedbackPhotos(feedbackPhotos); // 结案附件 List<EmergencyEventVO.Attachment> closeAttachments = getAttachmentVos(emergencyEvent, EmergencyEventAttachmentTypeEnum.CLOSE_FILE); emergencyEventVO.setCloseAttachments(closeAttachments); // 结案图片 List<EmergencyEventVO.Attachment> closeImages = getAttachmentVos(emergencyEvent, EmergencyEventAttachmentTypeEnum.CLOSE_IMAGE); emergencyEventVO.setCloseImages(closeImages); return emergencyEventVO; } private List<UserVO> userList(List<Long> ids) { net.cdsunrise.hy.lyjc.industrialoperationmonitoring.usermanage.domain.vo.req.PageRequest pageRequest = new net.cdsunrise.hy.lyjc.industrialoperationmonitoring.usermanage.domain.vo.req.PageRequest(); pageRequest.setPage(1); pageRequest.setSize(ids.size()); pageRequest.setUserIds(ids); Result<Page<UserVO>> result = ssoFeignService.userList(pageRequest); if (result.getSuccess()) { return result.getData().getRecords(); } else { return new ArrayList<UserVO>(); } } private String getUserNameByIdInList(List<UserVO> userList, long id) { if (CollectionUtils.isEmpty(userList)) { return ""; } return userList.stream().filter(userVO -> userVO.getId().equals(id)).findFirst().map(UserVO::getUserName).orElse(""); } private Map<String, Map<String, DataDictionaryVO>> getAllEmergencyEventTypeAndLevel() { Result<Map<String, DataDictionaryVO>> result = dataDictionaryFeignClient.getByCodes(new String[]{EVENT_TYPE_PARENT_CODE, EVENT_LEVEL_PARENT_CODE}); Map<String, DataDictionaryVO> data = result.getData(); if (data == null || data.isEmpty()) { throw new RuntimeException("事件类型及事件等级未在数据字典定义"); } Map<String, Map<String, DataDictionaryVO>> map = new HashMap<>(2); DataDictionaryVO eventTypeDataDictionaryVO = data.get(EVENT_TYPE_PARENT_CODE); if (eventTypeDataDictionaryVO == null) { throw new RuntimeException("事件类型未在数据字典定义"); } DataDictionaryVO eventLevelDataDictionaryVO = data.get(EVENT_LEVEL_PARENT_CODE); if (eventLevelDataDictionaryVO == null) { throw new RuntimeException("事件等级未在数据字典定义"); } map.put(EVENT_LEVEL_PARENT_CODE, eventLevelDataDictionaryVO.getChildren().stream().collect(Collectors.toMap(DataDictionaryVO::getCode, item -> item))); map.put(EVENT_TYPE_PARENT_CODE, eventTypeDataDictionaryVO.getChildren().stream().collect(Collectors.toMap(DataDictionaryVO::getCode, item -> item))); return map; } private DataDictionaryVO getDictionary(Map<String, DataDictionaryVO> allTypes, String type) { if (allTypes == null || allTypes.isEmpty()) { return null; } return allTypes.get(type); } private DataDictionaryVO getEventType(Map<String, Map<String, DataDictionaryVO>> map, String type) { Map<String, DataDictionaryVO> allTypes = map.get(EVENT_TYPE_PARENT_CODE); return getDictionary(allTypes, type); } private DataDictionaryVO getEventLevel(Map<String, Map<String, DataDictionaryVO>> map, String type) { Map<String, DataDictionaryVO> allTypes = map.get(EVENT_LEVEL_PARENT_CODE); return getDictionary(allTypes, type); } private void checkEventType(Map<String, Map<String, DataDictionaryVO>> map, String type) { DataDictionaryVO dataDictionaryVO = getEventType(map, type); if (dataDictionaryVO == null) { throw new ParamErrorException("未知的事件类型编码: " + type); } } private void checkEventLevel(Map<String, Map<String, DataDictionaryVO>> map, String type) { DataDictionaryVO dataDictionaryVO = getEventLevel(map, type); if (dataDictionaryVO == null) { throw new ParamErrorException("未知的事件等级编码: " + type); } } private void checkEventTypeAndLevel(Map<String, Map<String, DataDictionaryVO>> map, String eventType, String eventLevel) { checkEventType(map, eventType); checkEventLevel(map, eventLevel); } private List<EmergencyEventAttachment> getAttachments(Long eventId, List<EmergencyEventVO.Attachment> attachments, EmergencyEventAttachmentTypeEnum type) { if (CollectionUtils.isEmpty(attachments)) { return null; } return attachments.stream().map(attachment -> { EmergencyEventAttachment emergencyEventAttachment = new EmergencyEventAttachment(); BeanUtils.copyProperties(attachment, emergencyEventAttachment, "id"); emergencyEventAttachment.setEventId(eventId); emergencyEventAttachment.setType(type); return emergencyEventAttachment; }).collect(Collectors.toList()); } private List<EmergencyEventVO.Attachment> getAttachmentVos(EmergencyEvent emergencyEvent, EmergencyEventAttachmentTypeEnum type) { QueryWrapper<EmergencyEventAttachment> queryWrapper = Wrappers.query(); queryWrapper.lambda() .eq(EmergencyEventAttachment::getEventId, emergencyEvent.getId()) .eq(EmergencyEventAttachment::getType, type); List<EmergencyEventAttachment> emergencyEventAttachments = emergencyEventAttachmentService.list(queryWrapper); if (CollectionUtils.isEmpty(emergencyEventAttachments)) { return null; } return emergencyEventAttachments.stream().map(emergencyEventAttachment -> { EmergencyEventVO.Attachment attachment = new EmergencyEventVO.Attachment(); BeanUtils.copyProperties(emergencyEventAttachment, attachment); return attachment; }).collect(Collectors.toList()); } }
30,404
0.72486
0.723293
550
52.374546
43.355461
344
false
false
0
0
0
0
0
0
0.754545
false
false
1
564506ea2faa88a84e4dac054196a2f9c5bd25af
31,181,462,622,564
da6e725c6b2e76450fb6854cd7cf70219ef7e8c7
/mylibrary/src/main/java/com/sepideh/mylibrary/utils/RestHandler.java
70625810ae808692d8bab16ed3c606e980c58335
[]
no_license
sepideh69/SepidehLiberary
https://github.com/sepideh69/SepidehLiberary
fcf4e3b8c53b2829b56dd203e9db1d51055e76fa
f679c1783c518084cc712bdea606facd31a3820e
refs/heads/master
2020-03-28T17:19:45.310000
2018-09-18T15:29:30
2018-09-18T15:29:30
148,778,834
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.sepideh.mylibrary.utils; import okhttp3.OkHttpClient; import okhttp3.logging.HttpLoggingInterceptor; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; /** * Created by pc on 9/14/2018. */ public class RestHandler { public static <S> S createService(Class<S> serviceClass) { HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(); interceptor.setLevel(HttpLoggingInterceptor.Level.BODY); OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build(); Retrofit retrofit = new Retrofit.Builder() .baseUrl(Constant.BASE_URL) .client(client) .addConverterFactory(GsonConverterFactory.create()) .build(); return retrofit.create(serviceClass); } }
UTF-8
Java
835
java
RestHandler.java
Java
[ { "context": "rter.gson.GsonConverterFactory;\n\n/**\n * Created by pc on 9/14/2018.\n */\n\npublic class RestHandler {\n ", "end": 216, "score": 0.9779072999954224, "start": 214, "tag": "USERNAME", "value": "pc" } ]
null
[]
package com.sepideh.mylibrary.utils; import okhttp3.OkHttpClient; import okhttp3.logging.HttpLoggingInterceptor; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; /** * Created by pc on 9/14/2018. */ public class RestHandler { public static <S> S createService(Class<S> serviceClass) { HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(); interceptor.setLevel(HttpLoggingInterceptor.Level.BODY); OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build(); Retrofit retrofit = new Retrofit.Builder() .baseUrl(Constant.BASE_URL) .client(client) .addConverterFactory(GsonConverterFactory.create()) .build(); return retrofit.create(serviceClass); } }
835
0.699401
0.686228
24
33.791668
26.148581
93
false
false
0
0
0
0
0
0
0.416667
false
false
1
e735b568934856360dde7d5104c24fae8a34f9fb
6,846,177,936,541
837cf87e27fab251d5fe07df25a01dd2d563039b
/src/main/java/adf/launcher/AgentLauncher.java
3fab5f4574593f95d489ea6a1f4884d464363b3a
[ "BSD-2-Clause" ]
permissive
RCRS-ADF/core
https://github.com/RCRS-ADF/core
a4ae32f4027ffcef38535f768a9b4d500af97e10
13e53ca4be2777782be7455b1f524fb7d9ab9a8e
refs/heads/master
2021-01-24T08:33:02.865000
2017-09-30T05:25:16
2017-09-30T05:25:16
46,782,738
4
1
null
false
2016-12-08T17:50:00
2015-11-24T09:58:47
2016-12-08T07:57:51
2016-12-08T17:50:00
25,531
0
0
0
Java
null
null
package adf.launcher; import adf.component.AbstractLoader; import adf.launcher.connect.*; import rescuecore2.Constants; import rescuecore2.components.ComponentConnectionException; import rescuecore2.components.ComponentLauncher; import rescuecore2.components.TCPComponentLauncher; import rescuecore2.config.Config; import rescuecore2.registry.Registry; import rescuecore2.standard.entities.StandardEntityFactory; import rescuecore2.standard.entities.StandardPropertyFactory; import rescuecore2.standard.messages.StandardMessageFactory; import java.net.URLClassLoader; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; public class AgentLauncher { private Config config; private AbstractLoader loader; private List<Connector> connectors; public AgentLauncher(String... args) throws ClassNotFoundException, ClassCastException, InstantiationException, IllegalAccessException { this.init(args); } private void init(String... args) throws ClassNotFoundException, ClassCastException, InstantiationException, IllegalAccessException { this.initSystem(); this.config = ConfigInitializer.getConfig(args); this.initConnector(); if (this.config.getBooleanValue(ConfigKey.KEY_DEBUG_FLAG, false)) { ConsoleOutput.info("*** DEBUG MODE ***"); } if (this.config.getBooleanValue(ConfigKey.KEY_DEVELOP_FLAG, false)) { ConsoleOutput.info("*** DEVELOP MODE ***"); } } private void initSystem() { //register rescue system Registry.SYSTEM_REGISTRY.registerEntityFactory(StandardEntityFactory.INSTANCE); Registry.SYSTEM_REGISTRY.registerMessageFactory(StandardMessageFactory.INSTANCE); Registry.SYSTEM_REGISTRY.registerPropertyFactory(StandardPropertyFactory.INSTANCE); } private void initConnector() throws ClassNotFoundException, ClassCastException, InstantiationException, IllegalAccessException { //load AbstractLoader URLClassLoader classLoader = (URLClassLoader) this.getClass().getClassLoader(); Class c = classLoader.loadClass(this.config.getValue(ConfigKey.KEY_LOADER_CLASS)); this.loader = (AbstractLoader) c.newInstance(); // set connectors this.connectors = new ArrayList<>(); //platoon this.registerConnector(new ConnectorAmbulanceTeam()); this.registerConnector(new ConnectorFireBrigade()); this.registerConnector(new ConnectorPoliceForce()); //office this.registerConnector(new ConnectorAmbulanceCentre()); this.registerConnector(new ConnectorFireStation()); this.registerConnector(new ConnectorPoliceOffice()); } private void registerConnector(Connector connector) { this.connectors.add(connector); } public void start() { String host = this.config.getValue(Constants.KERNEL_HOST_NAME_KEY, Constants.DEFAULT_KERNEL_HOST_NAME); int port = this.config.getIntValue(Constants.KERNEL_PORT_NUMBER_KEY, Constants.DEFAULT_KERNEL_PORT_NUMBER); ComponentLauncher launcher = new TCPComponentLauncher(host, port, this.config); ConsoleOutput.out(ConsoleOutput.State.START, "Connect to server (host:" + host + ", port:" + port + ")"); List<Thread> threadList = this.connectors.stream().map( connector -> new Thread(() -> { connector.connect(launcher, this.config, loader); })) .collect(Collectors.toList()); threadList.forEach(Thread::start); try { for (Thread thread : threadList) { thread.join(); } } catch (InterruptedException e) { e.printStackTrace(); } int connectedCount = this.connectors.stream().mapToInt(Connector::getCountConnected).sum(); ConsoleOutput.finish("Done connecting to server (" + connectedCount + " agent" + (connectedCount > 1 ? 's' : "") + ")"); if (this.config.getBooleanValue(ConfigKey.KEY_PRECOMPUTE, false)) { // Because Precompute phase is only use postConnect. System.exit(0); } } }
UTF-8
Java
4,213
java
AgentLauncher.java
Java
[]
null
[]
package adf.launcher; import adf.component.AbstractLoader; import adf.launcher.connect.*; import rescuecore2.Constants; import rescuecore2.components.ComponentConnectionException; import rescuecore2.components.ComponentLauncher; import rescuecore2.components.TCPComponentLauncher; import rescuecore2.config.Config; import rescuecore2.registry.Registry; import rescuecore2.standard.entities.StandardEntityFactory; import rescuecore2.standard.entities.StandardPropertyFactory; import rescuecore2.standard.messages.StandardMessageFactory; import java.net.URLClassLoader; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; public class AgentLauncher { private Config config; private AbstractLoader loader; private List<Connector> connectors; public AgentLauncher(String... args) throws ClassNotFoundException, ClassCastException, InstantiationException, IllegalAccessException { this.init(args); } private void init(String... args) throws ClassNotFoundException, ClassCastException, InstantiationException, IllegalAccessException { this.initSystem(); this.config = ConfigInitializer.getConfig(args); this.initConnector(); if (this.config.getBooleanValue(ConfigKey.KEY_DEBUG_FLAG, false)) { ConsoleOutput.info("*** DEBUG MODE ***"); } if (this.config.getBooleanValue(ConfigKey.KEY_DEVELOP_FLAG, false)) { ConsoleOutput.info("*** DEVELOP MODE ***"); } } private void initSystem() { //register rescue system Registry.SYSTEM_REGISTRY.registerEntityFactory(StandardEntityFactory.INSTANCE); Registry.SYSTEM_REGISTRY.registerMessageFactory(StandardMessageFactory.INSTANCE); Registry.SYSTEM_REGISTRY.registerPropertyFactory(StandardPropertyFactory.INSTANCE); } private void initConnector() throws ClassNotFoundException, ClassCastException, InstantiationException, IllegalAccessException { //load AbstractLoader URLClassLoader classLoader = (URLClassLoader) this.getClass().getClassLoader(); Class c = classLoader.loadClass(this.config.getValue(ConfigKey.KEY_LOADER_CLASS)); this.loader = (AbstractLoader) c.newInstance(); // set connectors this.connectors = new ArrayList<>(); //platoon this.registerConnector(new ConnectorAmbulanceTeam()); this.registerConnector(new ConnectorFireBrigade()); this.registerConnector(new ConnectorPoliceForce()); //office this.registerConnector(new ConnectorAmbulanceCentre()); this.registerConnector(new ConnectorFireStation()); this.registerConnector(new ConnectorPoliceOffice()); } private void registerConnector(Connector connector) { this.connectors.add(connector); } public void start() { String host = this.config.getValue(Constants.KERNEL_HOST_NAME_KEY, Constants.DEFAULT_KERNEL_HOST_NAME); int port = this.config.getIntValue(Constants.KERNEL_PORT_NUMBER_KEY, Constants.DEFAULT_KERNEL_PORT_NUMBER); ComponentLauncher launcher = new TCPComponentLauncher(host, port, this.config); ConsoleOutput.out(ConsoleOutput.State.START, "Connect to server (host:" + host + ", port:" + port + ")"); List<Thread> threadList = this.connectors.stream().map( connector -> new Thread(() -> { connector.connect(launcher, this.config, loader); })) .collect(Collectors.toList()); threadList.forEach(Thread::start); try { for (Thread thread : threadList) { thread.join(); } } catch (InterruptedException e) { e.printStackTrace(); } int connectedCount = this.connectors.stream().mapToInt(Connector::getCountConnected).sum(); ConsoleOutput.finish("Done connecting to server (" + connectedCount + " agent" + (connectedCount > 1 ? 's' : "") + ")"); if (this.config.getBooleanValue(ConfigKey.KEY_PRECOMPUTE, false)) { // Because Precompute phase is only use postConnect. System.exit(0); } } }
4,213
0.693093
0.690482
113
36.283184
34.566204
138
false
false
0
0
0
0
0
0
0.628319
false
false
1
cf39b0a022eacb1b69cff6c8a4feb6eed51ba38f
8,254,927,209,498
c25d012a09f6544007cb360c9b8cb7dd4042f375
/src/main/java/com/woowa/conatuseus/configuration/AppConfig.java
a99835888f18ca1b453a487c6678c0e179d8d355
[]
no_license
Conatuseus/racingcar-web
https://github.com/Conatuseus/racingcar-web
35882c6059b4561d9f3c19fc57c29a717d41d8e7
e2989e6f02574da33acaa8c18cfff6d3096686bb
refs/heads/master
2020-06-13T21:23:23.439000
2019-07-02T13:05:13
2019-07-02T13:05:13
194,791,114
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.woowa.conatuseus.configuration; import com.woowa.conatuseus.domain.Car; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class AppConfig { }
UTF-8
Java
244
java
AppConfig.java
Java
[]
null
[]
package com.woowa.conatuseus.configuration; import com.woowa.conatuseus.domain.Car; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class AppConfig { }
244
0.831967
0.831967
12
19.333334
22.095751
60
false
false
0
0
0
0
0
0
0.333333
false
false
1
f19e5bb2865ceb0beb3700b9c13c3b943ae1e9b8
12,979,391,237,689
1ba95c2a96b098078c4a1cb973b160fae196b54e
/src/main/java/com/tigerknows/proxy/web/answer/StringAnswer.java
ac6e17898f6ce1ba7e9b6921cd9997b5a6f3be7c
[]
no_license
liuweikx/proxy
https://github.com/liuweikx/proxy
b2bfd317b6e30d76e03e38d60b84218f7170ee70
47eed41f17122b7d9c84a4f2603c237f79181d31
refs/heads/master
2020-05-16T01:35:07.227000
2014-05-09T08:36:42
2014-05-09T08:36:42
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.tigerknows.proxy.web.answer; import java.io.IOException; import java.io.OutputStream; import com.tigerknows.proxy.web.io.ByteWriter; public class StringAnswer implements Answer { private String result; public StringAnswer(String result){ this.result = result; } public void writeTo(OutputStream os, String charset) throws IOException { writeBinary(new ByteWriter(charset, os)); } protected void writeBinary(ByteWriter writer) throws IOException { writer.writeString(this.result); } public void writeToBrowser(OutputStream os, String charset) throws IOException { // TODO Auto-generated method stub } public boolean isEmpty() { // TODO Auto-generated method stub return false; } public String getLogInfo() { // TODO Auto-generated method stub return this.result; } public String getStringResut(){ return this.result; } public static void main(String[] argv) { StringAnswer la = new StringAnswer(""); try { la.writeTo(System.out, "UTF8"); } catch (IOException e) { e.printStackTrace(); } return; } public String toJSONString() { // TODO Auto-generated method stub return null; } }
UTF-8
Java
1,190
java
StringAnswer.java
Java
[]
null
[]
package com.tigerknows.proxy.web.answer; import java.io.IOException; import java.io.OutputStream; import com.tigerknows.proxy.web.io.ByteWriter; public class StringAnswer implements Answer { private String result; public StringAnswer(String result){ this.result = result; } public void writeTo(OutputStream os, String charset) throws IOException { writeBinary(new ByteWriter(charset, os)); } protected void writeBinary(ByteWriter writer) throws IOException { writer.writeString(this.result); } public void writeToBrowser(OutputStream os, String charset) throws IOException { // TODO Auto-generated method stub } public boolean isEmpty() { // TODO Auto-generated method stub return false; } public String getLogInfo() { // TODO Auto-generated method stub return this.result; } public String getStringResut(){ return this.result; } public static void main(String[] argv) { StringAnswer la = new StringAnswer(""); try { la.writeTo(System.out, "UTF8"); } catch (IOException e) { e.printStackTrace(); } return; } public String toJSONString() { // TODO Auto-generated method stub return null; } }
1,190
0.710924
0.710084
67
16.761194
18.725901
74
false
false
0
0
0
0
0
0
1.462687
false
false
1
ec4ea329d78469299a8457bb74ff49c38b464c3d
20,469,814,198,207
f04c8f419830f481ab960e6dafe623b49099af19
/housebay/src/main/java/br/senac/tads/housebay/model/TabelaDB.java
ffa1d5b9ad47a92f51532f384c7ba7d3132272b4
[]
no_license
VFata/PI
https://github.com/VFata/PI
513f7b86fbb90cbbadc6e45e6ae030d6aa36616b
32f51bf2a5704857f837f60aefc6e3e4eb5e164a
refs/heads/master
2021-08-24T08:30:35.972000
2017-12-08T21:35:43
2017-12-08T21:35:43
103,710,393
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 br.senac.tads.housebay.model; import java.util.GregorianCalendar; /** * * @author Diego */ public abstract class TabelaDB { public static final String ID = "id"; public final static String ATIVO = "ativo"; private Long _id; private boolean ativo; private GregorianCalendar criado; private GregorianCalendar modificado; public TabelaDB() { this._id = -1l; this.ativo = true; } public TabelaDB(Long _id, boolean ativo) { this._id = _id; this.ativo = ativo; } public Long getId() { return _id; } public void setId(Long _id) { this._id = _id; } public boolean isAtivo() { return ativo; } public void setAtivo(boolean ativo) { this.ativo = ativo; } public GregorianCalendar getCriado() { return criado; } public void setCriado(GregorianCalendar criado) { this.criado = criado; } public void setCriado(long timeInMillis) { this.criado = new GregorianCalendar(); this.criado.setTimeInMillis(timeInMillis); } public GregorianCalendar getModificado() { return modificado; } public void setModificado(GregorianCalendar modificado) { this.modificado = modificado; } public void setModificado(long timeInMillis) { this.modificado = new GregorianCalendar(); this.modificado.setTimeInMillis(timeInMillis); } }
UTF-8
Java
1,731
java
TabelaDB.java
Java
[ { "context": "ava.util.GregorianCalendar;\r\n\r\n/**\r\n *\r\n * @author Diego\r\n */\r\npublic abstract class TabelaDB {\r\n publi", "end": 295, "score": 0.9993607997894287, "start": 290, "tag": "NAME", "value": "Diego" } ]
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 br.senac.tads.housebay.model; import java.util.GregorianCalendar; /** * * @author Diego */ public abstract class TabelaDB { public static final String ID = "id"; public final static String ATIVO = "ativo"; private Long _id; private boolean ativo; private GregorianCalendar criado; private GregorianCalendar modificado; public TabelaDB() { this._id = -1l; this.ativo = true; } public TabelaDB(Long _id, boolean ativo) { this._id = _id; this.ativo = ativo; } public Long getId() { return _id; } public void setId(Long _id) { this._id = _id; } public boolean isAtivo() { return ativo; } public void setAtivo(boolean ativo) { this.ativo = ativo; } public GregorianCalendar getCriado() { return criado; } public void setCriado(GregorianCalendar criado) { this.criado = criado; } public void setCriado(long timeInMillis) { this.criado = new GregorianCalendar(); this.criado.setTimeInMillis(timeInMillis); } public GregorianCalendar getModificado() { return modificado; } public void setModificado(GregorianCalendar modificado) { this.modificado = modificado; } public void setModificado(long timeInMillis) { this.modificado = new GregorianCalendar(); this.modificado.setTimeInMillis(timeInMillis); } }
1,731
0.608319
0.607741
69
23.086956
19.575006
79
false
false
0
0
0
0
0
0
0.405797
false
false
1
9a93188e4f6473afd554780eac98f504d5226017
23,467,701,374,250
7629e176b523e9edc6386b435bdb87c3a23c4f97
/Direct/src/test/java/com/dimas/direct/DirectFunctionalTest.java
33764904d22b1612ceb6bceaf8da1356ab84ce0d
[]
no_license
recvezitor/DBAccessTutorial
https://github.com/recvezitor/DBAccessTutorial
53c0b646a51aabf674a8436951eb10418544c19b
b838372f36683e231531a459e514a5fb5f59a2f9
refs/heads/master
2021-01-13T01:44:03.725000
2014-03-21T10:37:26
2014-03-21T10:37:26
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.dimas.direct; import com.dimas.direct.dao.ContactService; import com.dimas.direct.domain.Contact; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import java.util.List; import static org.junit.Assert.assertNotNull; /** * Copyright 2009-2014. NxSystems Inc. * PROPRIETARY/CONFIDENTIAL. * <p/> * Created: 08.02.14 19:16 * * @author Dmitry Borovoy */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = {"classpath:/spring-config.xml"}) public class DirectFunctionalTest { protected final Logger l = LoggerFactory.getLogger(getClass()); @Autowired @Qualifier("directContactService") ContactService contactService; @Before public void setUp() throws Exception { l.info("Started"); assertNotNull(contactService); } @Test public void testName() throws Exception { List<Contact> contactList = contactService.findAll(); assertNotNull(contactList); l.info("size={}", contactList.size()); } }
UTF-8
Java
1,364
java
DirectFunctionalTest.java
Java
[ { "context": ".\n * <p/>\n * Created: 08.02.14 19:16\n *\n * @author Dmitry Borovoy\n */\n\n@RunWith(SpringJUnit4ClassRunner.class)\n@Con", "end": 716, "score": 0.9998593926429749, "start": 702, "tag": "NAME", "value": "Dmitry Borovoy" } ]
null
[]
package com.dimas.direct; import com.dimas.direct.dao.ContactService; import com.dimas.direct.domain.Contact; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import java.util.List; import static org.junit.Assert.assertNotNull; /** * Copyright 2009-2014. NxSystems Inc. * PROPRIETARY/CONFIDENTIAL. * <p/> * Created: 08.02.14 19:16 * * @author <NAME> */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = {"classpath:/spring-config.xml"}) public class DirectFunctionalTest { protected final Logger l = LoggerFactory.getLogger(getClass()); @Autowired @Qualifier("directContactService") ContactService contactService; @Before public void setUp() throws Exception { l.info("Started"); assertNotNull(contactService); } @Test public void testName() throws Exception { List<Contact> contactList = contactService.findAll(); assertNotNull(contactList); l.info("size={}", contactList.size()); } }
1,356
0.745601
0.728739
51
25.745098
21.745266
71
false
false
0
0
0
0
0
0
0.431373
false
false
1
769ae94d33abdc6f9631dbb09dfe4eacd2730c79
21,449,066,684,016
931574f845931019dc36173e44a59746ebf76da6
/Project1/src/ChessPanel.java
6b31ee1262d5cd9df7b6b6f3bc9e6334a8736897
[]
no_license
luoyan1216/SoftwareDesignTask-1
https://github.com/luoyan1216/SoftwareDesignTask-1
3271fc78d5d4cc1a880f37365c4b0691c85f2263
bfecc87250d5aabb59021daf94e345343de215f1
refs/heads/master
2022-11-15T04:54:09.558000
2020-07-05T09:41:57
2020-07-05T09:41:57
277,268,416
1
0
null
true
2020-07-05T09:19:35
2020-07-05T09:19:34
2020-07-05T09:19:29
2020-07-05T09:17:28
0
0
0
0
null
false
false
import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.Image; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import javax.swing.ImageIcon; import javax.swing.JOptionPane; import javax.swing.JPanel; public class ChessPanel extends JPanel implements MouseListener ,Runnable{ //棋子数组 //chesses[0][0]->chesses[18][18],默认是0,表示没有棋子,白色-1,黑色1 int[][] chesses = new int[19][19]; int currentColor = 1;//初始颜色:黑色,标志最近下的棋子颜色 String blackMessage = "时间无限制";//就写个字 String whiteMessage = "时间无限制"; int blackTime = 0;//剩余落子时间 int whiteTime = 0; Thread t = new Thread(this);//new一个线程 int undoTimeX;//撤销时间 int undoTimeY; @Override public void paint(Graphics g) {//画面板 } public void drawBackground(Graphics g) {//画背景 } public void drawGameInfo(Graphics g) {//写游戏信息 } public void drawTime(Graphics g) {//计时器,需要游戏里设置计时才倒计时 } public void drawChessBoard(Graphics g) {//画棋盘 } boolean gameOver = false;//游戏结束标志 @Override public void mouseClicked(MouseEvent e) {//鼠标点击事件 } public String currentColorStringfy() {//判断最近一次落子的颜色 } public void playChess(int mouseX,int mouseY) {//落子 } public boolean checkWin() { //判断输赢 } public boolean checkOneDirection() {//检查是否已经五子连 } public void run() {//运行 } //下面都是检查某个功能点的范围 public boolean isChessBoardRange (int mouseX, int mouseY) { } public boolean isStartGameRange (int mouseX, int mouseY) { } public boolean isSettingRange (int mouseX, int mouseY) { } public boolean isGameBriefRge (int mouseX, int mouseY) { } public boolean isDefeat (int mouseX, int mouseY) { } public boolean isGiveUpRange (int mouseX, int mouseY) { } public boolean isAboutRange (int mouseX, int mouseY) { } public boolean isExitRange (int mouseX, int mouseY) { } public void mousePressed(MouseEvent e) {} public void mouseReleased(MouseEvent e) {} public void mouseEntered(MouseEvent e) {} public void mouseExited(MouseEvent e) {} }
GB18030
Java
2,407
java
ChessPanel.java
Java
[]
null
[]
import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.Image; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import javax.swing.ImageIcon; import javax.swing.JOptionPane; import javax.swing.JPanel; public class ChessPanel extends JPanel implements MouseListener ,Runnable{ //棋子数组 //chesses[0][0]->chesses[18][18],默认是0,表示没有棋子,白色-1,黑色1 int[][] chesses = new int[19][19]; int currentColor = 1;//初始颜色:黑色,标志最近下的棋子颜色 String blackMessage = "时间无限制";//就写个字 String whiteMessage = "时间无限制"; int blackTime = 0;//剩余落子时间 int whiteTime = 0; Thread t = new Thread(this);//new一个线程 int undoTimeX;//撤销时间 int undoTimeY; @Override public void paint(Graphics g) {//画面板 } public void drawBackground(Graphics g) {//画背景 } public void drawGameInfo(Graphics g) {//写游戏信息 } public void drawTime(Graphics g) {//计时器,需要游戏里设置计时才倒计时 } public void drawChessBoard(Graphics g) {//画棋盘 } boolean gameOver = false;//游戏结束标志 @Override public void mouseClicked(MouseEvent e) {//鼠标点击事件 } public String currentColorStringfy() {//判断最近一次落子的颜色 } public void playChess(int mouseX,int mouseY) {//落子 } public boolean checkWin() { //判断输赢 } public boolean checkOneDirection() {//检查是否已经五子连 } public void run() {//运行 } //下面都是检查某个功能点的范围 public boolean isChessBoardRange (int mouseX, int mouseY) { } public boolean isStartGameRange (int mouseX, int mouseY) { } public boolean isSettingRange (int mouseX, int mouseY) { } public boolean isGameBriefRge (int mouseX, int mouseY) { } public boolean isDefeat (int mouseX, int mouseY) { } public boolean isGiveUpRange (int mouseX, int mouseY) { } public boolean isAboutRange (int mouseX, int mouseY) { } public boolean isExitRange (int mouseX, int mouseY) { } public void mousePressed(MouseEvent e) {} public void mouseReleased(MouseEvent e) {} public void mouseEntered(MouseEvent e) {} public void mouseExited(MouseEvent e) {} }
2,407
0.674584
0.666983
108
17.472221
20.952971
74
false
false
0
0
0
0
0
0
1.055556
false
false
1
16486da5d02d3dff009c16e851c07c4aa67899f8
17,867,063,961,284
b01b2e204c61b01744f0a2cd8ebd32600a755647
/src/main/java/jee/projet/ecom/Repository/UserRepository.java
eda366f8f4b71b5af1ab3aecad188db053ff2d5d
[]
no_license
Rawaatrad/ecomJEE
https://github.com/Rawaatrad/ecomJEE
4007eb5d0f511528f75cec82847135148801798d
6e24fe494fbf3f3b007d118bddebb8c97772953e
refs/heads/master
2023-06-01T00:10:29.733000
2021-06-26T17:04:03
2021-06-26T17:04:03
380,554,935
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package jee.projet.ecom.Repository; import jee.projet.ecom.entity.User; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import java.util.Optional; @Repository public interface UserRepository extends JpaRepository<User, Long> { Optional<User> findByEmailAndPassword(String email,String password); }
UTF-8
Java
370
java
UserRepository.java
Java
[]
null
[]
package jee.projet.ecom.Repository; import jee.projet.ecom.entity.User; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import java.util.Optional; @Repository public interface UserRepository extends JpaRepository<User, Long> { Optional<User> findByEmailAndPassword(String email,String password); }
370
0.824324
0.824324
13
27.461538
26.659145
72
false
false
0
0
0
0
0
0
0.615385
false
false
1
ffeb7e74a1f2f07bbe06a6d4fa4432260ce20b9a
6,545,530,163,771
b9b371fe8da7f2726f0c80e7ed26eec387734f8b
/src/com/guoguocai/observer/demo3/observer/StockObserver.java
b4135ff67d4da4329bae85c7c4e0c7ffb2ec2232
[]
no_license
guoguocai/Design-Pattern
https://github.com/guoguocai/Design-Pattern
699f6d21571faf3cd0ece368c81eecdbaed20217
01b6eff174345d6210db6ae6827aca8bf310d7f2
refs/heads/master
2021-07-11T04:05:01.903000
2020-06-27T13:58:51
2020-06-27T13:58:51
160,521,286
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.guoguocai.observer.demo3.observer; import com.guoguocai.observer.demo3.interfaces.Subject; /** * 看股票的同事 * * @auther guoguocai * @date 2019/1/19 15:19 */ public class StockObserver { private String name; private Subject sub; public StockObserver(String name, Subject sub) { this.name = name; this.sub = sub; } // 去掉了父类“抽象观察类”,所以此处的方法名也改变了。 public void closeStockMarket() { System.out.println(sub.getAction() + ", " + name + "关闭股票行情,继续工作!"); } }
UTF-8
Java
631
java
StockObserver.java
Java
[ { "context": "erfaces.Subject;\r\n\r\n/**\r\n * 看股票的同事\r\n *\r\n * @auther guoguocai\r\n * @date 2019/1/19 15:19\r\n */\r\npublic class Stoc", "end": 149, "score": 0.9994409680366516, "start": 140, "tag": "USERNAME", "value": "guoguocai" } ]
null
[]
package com.guoguocai.observer.demo3.observer; import com.guoguocai.observer.demo3.interfaces.Subject; /** * 看股票的同事 * * @auther guoguocai * @date 2019/1/19 15:19 */ public class StockObserver { private String name; private Subject sub; public StockObserver(String name, Subject sub) { this.name = name; this.sub = sub; } // 去掉了父类“抽象观察类”,所以此处的方法名也改变了。 public void closeStockMarket() { System.out.println(sub.getAction() + ", " + name + "关闭股票行情,继续工作!"); } }
631
0.61326
0.589319
25
19.719999
20.349977
75
false
false
0
0
0
0
0
0
0.36
false
false
1
1b3ee540cd20b17dd69c37351494d68a2c84b6c7
5,497,558,157,395
ba96a55f06b376cb6426265110b447c78fffb629
/src/main/java/zzk/project/dms/domain/entities/TenementContactMethod.java
ae03781eee5d031fa66c419c6a818d34e249d55b
[]
no_license
zzk0803/dms
https://github.com/zzk0803/dms
f31e383715182200d78c97dab5dd9d80bc1fc1d9
47974e237ccd080b072ae64c16f9263aca33024e
refs/heads/master
2023-06-22T12:50:30.613000
2023-03-16T13:01:01
2023-03-16T13:01:01
173,445,981
10
1
null
false
2023-06-14T22:23:07
2019-03-02T12:35:26
2023-05-26T06:54:54
2023-06-14T22:23:03
600
10
0
2
Java
false
false
package zzk.project.dms.domain.entities; import javax.persistence.Embeddable; @Embeddable public class TenementContactMethod { private String houseTelephone = ""; private String mobilePhone = ""; private String primaryEmail = ""; public String getHouseTelephone() { return houseTelephone; } public void setHouseTelephone(String houseTelephone) { this.houseTelephone = houseTelephone; } public String getMobilePhone() { return mobilePhone; } public void setMobilePhone(String mobilePhone) { this.mobilePhone = mobilePhone; } public String getPrimaryEmail() { return primaryEmail; } public void setPrimaryEmail(String primaryEmail) { this.primaryEmail = primaryEmail; } }
UTF-8
Java
786
java
TenementContactMethod.java
Java
[]
null
[]
package zzk.project.dms.domain.entities; import javax.persistence.Embeddable; @Embeddable public class TenementContactMethod { private String houseTelephone = ""; private String mobilePhone = ""; private String primaryEmail = ""; public String getHouseTelephone() { return houseTelephone; } public void setHouseTelephone(String houseTelephone) { this.houseTelephone = houseTelephone; } public String getMobilePhone() { return mobilePhone; } public void setMobilePhone(String mobilePhone) { this.mobilePhone = mobilePhone; } public String getPrimaryEmail() { return primaryEmail; } public void setPrimaryEmail(String primaryEmail) { this.primaryEmail = primaryEmail; } }
786
0.684478
0.684478
34
22.117647
19.423704
58
false
false
0
0
0
0
0
0
0.323529
false
false
1
1a746addfabcb6155e702dc8582cffd8844bd185
34,617,436,452,858
55d53303c265be8cb018962aed870acad46a6927
/src/main/java/com/teles/havel/batch/select/BulkSelect.java
26ee79254bc6dd0bc1362add1f0b32e22eca1962
[]
no_license
hugoltsp/havel
https://github.com/hugoltsp/havel
62a2049a2289cc2fbf28fee1937d36b6a2e007ec
646ab8b00388a99edb5d4bbd77b95a9f465ef899
refs/heads/master
2022-01-28T00:45:05.772000
2019-11-23T18:44:44
2019-11-23T18:44:44
60,037,088
0
0
null
false
2022-01-21T23:20:00
2016-05-30T20:26:58
2019-11-23T18:44:46
2022-01-21T23:19:58
114
0
0
2
Java
false
false
package com.teles.havel.batch.select; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Spliterator; import java.util.Spliterators; import java.util.Spliterators.AbstractSpliterator; import java.util.function.Consumer; import java.util.stream.Stream; import java.util.stream.StreamSupport; import org.slf4j.Logger; import com.teles.havel.batch.BatchOperation; import com.teles.havel.batch.enums.LogLevel; import com.teles.havel.batch.exception.BatchException; import com.teles.havel.batch.select.function.OutputMapperFunction; import com.teles.havel.batch.select.utils.Row; public class BulkSelect<T> extends BatchOperation { private final OutputMapperFunction<T> outputMapper; private int rowCount; BulkSelect(Logger logger, LogLevel logLevel, Connection connection, String sqlStatement, PreparedStatement preparedStatement, OutputMapperFunction<T> outputMapper) { super(logger, logLevel, connection, sqlStatement, preparedStatement); this.outputMapper = outputMapper; validateOutputMapper(); } public Stream<T> select() throws BatchException, IllegalStateException { logIfAvailable("Fetching rows from database..."); ResultSet resultSet = fetchResultSet(); return StreamSupport.stream(spliterator(resultSet), false).onClose(() -> { try { this.close(); } catch (SQLException e) { logIfAvailable("An error occurred while trying to close this resource", e); } }); } private AbstractSpliterator<T> spliterator(ResultSet resultSet) { return new Spliterators.AbstractSpliterator<T>(Long.MAX_VALUE, Spliterator.ORDERED) { @Override public boolean tryAdvance(Consumer<? super T> action) { try { if (!resultSet.next()) { logIfAvailable("{} rows selected from database", rowCount); return false; } action.accept(outputMapper.apply(new Row(resultSet))); rowCount++; return true; } catch (SQLException ex) { throw new BatchException(ex); } } }; } private void validateOutputMapper() { if (this.outputMapper == null) { throw new IllegalStateException("OutputMapper can't be null"); } } private ResultSet fetchResultSet() throws BatchException { try { ResultSet resultSet = this.preparedStatement.executeQuery(); return resultSet; } catch (SQLException e) { throw new BatchException("Could not fetch result set", e); } } }
UTF-8
Java
2,443
java
BulkSelect.java
Java
[]
null
[]
package com.teles.havel.batch.select; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Spliterator; import java.util.Spliterators; import java.util.Spliterators.AbstractSpliterator; import java.util.function.Consumer; import java.util.stream.Stream; import java.util.stream.StreamSupport; import org.slf4j.Logger; import com.teles.havel.batch.BatchOperation; import com.teles.havel.batch.enums.LogLevel; import com.teles.havel.batch.exception.BatchException; import com.teles.havel.batch.select.function.OutputMapperFunction; import com.teles.havel.batch.select.utils.Row; public class BulkSelect<T> extends BatchOperation { private final OutputMapperFunction<T> outputMapper; private int rowCount; BulkSelect(Logger logger, LogLevel logLevel, Connection connection, String sqlStatement, PreparedStatement preparedStatement, OutputMapperFunction<T> outputMapper) { super(logger, logLevel, connection, sqlStatement, preparedStatement); this.outputMapper = outputMapper; validateOutputMapper(); } public Stream<T> select() throws BatchException, IllegalStateException { logIfAvailable("Fetching rows from database..."); ResultSet resultSet = fetchResultSet(); return StreamSupport.stream(spliterator(resultSet), false).onClose(() -> { try { this.close(); } catch (SQLException e) { logIfAvailable("An error occurred while trying to close this resource", e); } }); } private AbstractSpliterator<T> spliterator(ResultSet resultSet) { return new Spliterators.AbstractSpliterator<T>(Long.MAX_VALUE, Spliterator.ORDERED) { @Override public boolean tryAdvance(Consumer<? super T> action) { try { if (!resultSet.next()) { logIfAvailable("{} rows selected from database", rowCount); return false; } action.accept(outputMapper.apply(new Row(resultSet))); rowCount++; return true; } catch (SQLException ex) { throw new BatchException(ex); } } }; } private void validateOutputMapper() { if (this.outputMapper == null) { throw new IllegalStateException("OutputMapper can't be null"); } } private ResultSet fetchResultSet() throws BatchException { try { ResultSet resultSet = this.preparedStatement.executeQuery(); return resultSet; } catch (SQLException e) { throw new BatchException("Could not fetch result set", e); } } }
2,443
0.749079
0.74867
80
29.549999
25.683603
89
false
false
0
0
0
0
0
0
2.35
false
false
1
bf568d5934a5d2194ab4c183add76a7aeca1a246
34,540,127,041,920
56aec8cc2d2245d1806fda14658f81b66e97c231
/design patterns/factory.java
80df33eb34aee7712f676f3909eed503066ad7cc
[]
no_license
a1101101/Java
https://github.com/a1101101/Java
7f927afcbbc4e48b0f813f13906647dca132d5aa
05f8ef188e33a351de963729bdb34a9ceb7bdde4
refs/heads/master
2021-04-18T17:24:53.830000
2021-02-04T09:24:52
2021-02-04T09:24:52
249,566,556
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
//design pattern "Factory" interface Item{ public void f(); } class J implements Item{ public void f(){ System.out.println("J.f() is called."); } } class K implements Item{ public void f(){ System.out.println("K.f() is called."); } } class Factory{ public Item getItem(String itype){ if(itype==null){ return null; } if(itype.equalsIgnoreCase("J")){ return new J(); }else if(itype.equalsIgnoreCase("K")){ return new K(); } return null; } } class M{ public static void main(String args[]){ Factory factory = new Factory(); Item j = factory.getItem("J"); j.f(); Item k = factory.getItem("K"); k.f(); } }
UTF-8
Java
697
java
factory.java
Java
[]
null
[]
//design pattern "Factory" interface Item{ public void f(); } class J implements Item{ public void f(){ System.out.println("J.f() is called."); } } class K implements Item{ public void f(){ System.out.println("K.f() is called."); } } class Factory{ public Item getItem(String itype){ if(itype==null){ return null; } if(itype.equalsIgnoreCase("J")){ return new J(); }else if(itype.equalsIgnoreCase("K")){ return new K(); } return null; } } class M{ public static void main(String args[]){ Factory factory = new Factory(); Item j = factory.getItem("J"); j.f(); Item k = factory.getItem("K"); k.f(); } }
697
0.581062
0.581062
42
14.595238
13.756487
41
false
false
0
0
0
0
0
0
1.428571
false
false
1
b0da7f2231a78d2eb2b7f86fa2016ad7ccd2a7dc
36,137,854,866,061
ba9f6527e7199e30d605776080bda362d6e523f0
/app/src/main/java/space/codejun/hedwigapp/ui/activity/AddWordActivity.java
81fd7e3c17c6e8f00f20a2fab8d85643fa5d6b8b
[]
no_license
Sumida-melonhot/android-app
https://github.com/Sumida-melonhot/android-app
ddfad659370b7d8e9d32146fe51df4ed01ea5475
5c6825d8ff7061781f2f9a02ada5fb6835d2f7ad
refs/heads/master
2020-04-11T14:48:39.467000
2018-12-16T02:04:08
2018-12-16T02:04:08
161,868,994
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package space.codejun.hedwigapp.ui.activity; import android.os.Bundle; import com.google.firebase.firestore.FirebaseFirestore; import java.util.HashMap; import java.util.Map; import java.util.Objects; import androidx.appcompat.app.AppCompatActivity; import androidx.databinding.DataBindingUtil; import space.codejun.hedwigapp.R; import space.codejun.hedwigapp.databinding.ActivityAddWordBinding; public class AddWordActivity extends AppCompatActivity { private ActivityAddWordBinding binding; private FirebaseFirestore db; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); binding = DataBindingUtil.setContentView(this, R.layout.activity_add_word); db = FirebaseFirestore.getInstance(); binding.backButton.setOnClickListener(view -> finish()); //TODO 태일이는 여기다 파베스토어 이니셜라이징 하시오. binding.addButton.setOnClickListener(view -> { if (Objects.requireNonNull(binding.addWordInputText.getText()).length() == 0) { binding.addWordInputLayout.setErrorEnabled(true); binding.addWordInputLayout.setError("この項目を満たしてください。"); } else { binding.addWordInputLayout.setErrorEnabled(false); //TODO 파베 추가 ㄱ //binding.addWordInputText.getText().toString(); Map<String, Object> data = new HashMap<>(); data.put("count", 1); db.collection("word").document(binding.addWordInputText.getText().toString()).set(data); } }); } }
UTF-8
Java
1,681
java
AddWordActivity.java
Java
[]
null
[]
package space.codejun.hedwigapp.ui.activity; import android.os.Bundle; import com.google.firebase.firestore.FirebaseFirestore; import java.util.HashMap; import java.util.Map; import java.util.Objects; import androidx.appcompat.app.AppCompatActivity; import androidx.databinding.DataBindingUtil; import space.codejun.hedwigapp.R; import space.codejun.hedwigapp.databinding.ActivityAddWordBinding; public class AddWordActivity extends AppCompatActivity { private ActivityAddWordBinding binding; private FirebaseFirestore db; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); binding = DataBindingUtil.setContentView(this, R.layout.activity_add_word); db = FirebaseFirestore.getInstance(); binding.backButton.setOnClickListener(view -> finish()); //TODO 태일이는 여기다 파베스토어 이니셜라이징 하시오. binding.addButton.setOnClickListener(view -> { if (Objects.requireNonNull(binding.addWordInputText.getText()).length() == 0) { binding.addWordInputLayout.setErrorEnabled(true); binding.addWordInputLayout.setError("この項目を満たしてください。"); } else { binding.addWordInputLayout.setErrorEnabled(false); //TODO 파베 추가 ㄱ //binding.addWordInputText.getText().toString(); Map<String, Object> data = new HashMap<>(); data.put("count", 1); db.collection("word").document(binding.addWordInputText.getText().toString()).set(data); } }); } }
1,681
0.681449
0.6802
48
32.354168
28.391232
104
false
false
0
0
0
0
0
0
0.5625
false
false
1
a823d4712a9372823fb4c13e95279b85bbfc071f
36,301,063,627,638
c5d1d4103eac759d227f35c51463d0cb7a6b87cf
/src/main/java/ec/edu/ctrlsolutions/repository/UsuarioRepository.java
4e9877d3103ec45ef9ea4ee14c99fa57ff06c5e0
[]
no_license
LuisFrnkMorocho/ProyectoWeb-Tesis
https://github.com/LuisFrnkMorocho/ProyectoWeb-Tesis
8c757869444ef7b7384b3ccc9da3afd3a882b51f
c7c402d13f00ae22ae4645aa6d20fe24cc562a88
refs/heads/master
2023-06-28T01:40:52.677000
2021-08-06T22:09:08
2021-08-06T22:09:08
393,514,669
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ec.edu.ctrlsolutions.repository; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import ec.edu.ctrlsolutions.model.Usuario; public interface UsuarioRepository extends JpaRepository<Usuario, Integer> { @Query("SELECT u FROM Usuario u WHERE u.username = ?1 AND u.password = ?2") Usuario findUsuarioByCredenciales(String username, String password); }
UTF-8
Java
442
java
UsuarioRepository.java
Java
[ { "context": "M Usuario u WHERE u.username = ?1 AND u.password = ?2\")\r\n\tUsuario findUsuarioByCredenciales(String user", "end": 364, "score": 0.8957043886184692, "start": 362, "tag": "PASSWORD", "value": "?2" } ]
null
[]
package ec.edu.ctrlsolutions.repository; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import ec.edu.ctrlsolutions.model.Usuario; public interface UsuarioRepository extends JpaRepository<Usuario, Integer> { @Query("SELECT u FROM Usuario u WHERE u.username = ?1 AND u.password = ?2") Usuario findUsuarioByCredenciales(String username, String password); }
442
0.789593
0.785068
12
34.833332
31.155079
76
false
false
0
0
0
0
0
0
0.75
false
false
1
8eb7c0ef0ac88f1ec6141e12b44fe27f1bb5a00e
18,511,309,054,569
a7e31218b1a29e62be405a5b34ae9f45472791c9
/java/com/raadz/program/raadzandroid/_TestActivity.java
a8e961950d8b6016e28114927c9c814192dcc508
[]
no_license
LoganRichardson/Projects
https://github.com/LoganRichardson/Projects
c4cab77b3749f76ebf2532f3098f5d77025ad6a4
609e6ba8f913c714477453b9a3760f7f6292e093
refs/heads/master
2021-09-27T00:13:10.353000
2021-09-21T07:55:41
2021-09-21T07:55:41
152,376,267
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.raadz.program.raadzandroid; import android.content.ContentResolver; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.content.res.Configuration; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Color; import android.media.MediaPlayer; import android.media.session.MediaController; import android.net.Uri; import android.os.AsyncTask; import android.os.Environment; import android.preference.PreferenceManager; import android.provider.MediaStore; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.DialogFragment; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.text.Html; import android.util.Log; import android.view.View; import android.webkit.WebChromeClient; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.Button; import android.widget.EditText; import android.widget.ExpandableListView; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import android.widget.VideoView; import com.facebook.share.model.ShareLinkContent; import com.facebook.share.widget.ShareDialog; import com.google.android.gms.auth.api.Auth; import com.google.android.gms.auth.api.signin.GoogleSignInAccount; import com.google.android.gms.auth.api.signin.GoogleSignInOptions; import com.google.android.gms.auth.api.signin.GoogleSignInResult; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.SignInButton; import com.google.android.gms.common.api.ApiException; import com.google.android.gms.common.api.CommonStatusCodes; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.common.api.ResultCallback; import com.google.android.gms.common.api.Status; import com.google.android.gms.safetynet.SafetyNet; import com.google.android.gms.safetynet.SafetyNetApi; import com.google.android.gms.tasks.OnFailureListener; import com.google.android.gms.tasks.OnSuccessListener; import com.google.android.youtube.player.YouTubeBaseActivity; import com.google.android.youtube.player.YouTubeInitializationResult; import com.google.android.youtube.player.YouTubePlayer; import com.google.android.youtube.player.YouTubePlayerFragment; import com.google.android.youtube.player.YouTubePlayerSupportFragment; import com.google.android.youtube.player.YouTubePlayerView; import com.google.android.youtube.player.YouTubeStandalonePlayer; import com.kosalgeek.asynctask.AsyncResponse; import com.stripe.android.view.CardMultilineWidget; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.NameValuePair; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.concurrent.Executor; import static android.R.attr.tag; import static android.provider.MediaStore.Video.Thumbnails.VIDEO_ID; import static com.raadz.program.raadzandroid.PubSubmitActivity.getFileNameByUri; import static com.raadz.program.raadzandroid.R.id.LLMain; import static com.raadz.program.raadzandroid.R.id.bYTPlay; import static com.raadz.program.raadzandroid.R.id.etVideoID; import static com.raadz.program.raadzandroid.R.id.newYTPlayer; import static com.raadz.program.raadzandroid.R.id.videoView; import static com.raadz.program.raadzandroid.R.id.wvLoad; public class _TestActivity extends YouTubeBaseActivity implements AsyncResponse, View.OnClickListener, DialogInterface, GoogleApiClient.OnConnectionFailedListener, GoogleApiClient.ConnectionCallbacks { private static final String TAG = "_TestActivity"; private Button mOpenDialog; BufferedReader bufferedReader; OutputStream outputStream; java.lang.StringBuffer stringBuffer = new java.lang.StringBuffer(); String httpRequest; GoogleApiClient googleApiClient; View view; YouTubePlayerView mYouTubePlayerView; YouTubePlayerView NewYouTubePlayerView; YouTubePlayer player; YouTubePlayer.OnInitializedListener mOnInitializedListener; YouTubePlayerFragment myYouTubePlayerFragment; WebView wvWeb; VideoView vvVideo; private ExpandableListView listView; private ExpandableListAdapter listAdapter; private List<String> listDataHeader; private HashMap<String,List<String>> listHash; ImageView ivImage; LinearLayout LLButtons; LinearLayout LLLogout; LinearLayout LLShare; Button bPlay; Button bTest; Button bLogout; Button bShare; SignInButton bGoogleSignIn; SignInButton bGoogleSignUp; String ServerLoginURL = "https://raadz.com/mobilelogin.php"; String RaddzIDURL = "https://raadz.com/getRaadzIDs.php"; String GoogleUserSignUpURL = "https://raadz.com/googusersignup.php"; String buttonPlaceholder; String userResponseToken; String UID; String PID; String UserToken; String PubToken; String fName; String lName; String email; String username; String id; String token; String InOut; String str; int PICK_VIDEO = 100; int PICK_IMAGE = 100; int PICK_AUDIO = 100; boolean updateUI; public static final String data = "{\"user_id\":{\"put_id\":\"token\",\"salary\":56000}}"; public static final String SITE_KEY = "6LcVrUwUAAAAAL2J1zasONEiiru3Lgg4z9bMxxLJ"; public static final String SECRET_KEY = "6LcVrUwUAAAAADmA4tnNYUmPu8rcOcOBF1IxTt0d"; private static final int REQ_CODE = 9001; private static final String REQ_TOKEN = "1088961401873-969414qur5dh7ied7ailbajgcst9t5ou.apps.googleusercontent.com"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity___test); mYouTubePlayerView = (YouTubePlayerView) findViewById(newYTPlayer); ivImage = (ImageView) findViewById(R.id.ivImage); LLButtons = (LinearLayout) findViewById(R.id.LLButtons); LLLogout = (LinearLayout) findViewById(R.id.LLLogout); LLShare = (LinearLayout) findViewById(R.id.LLShare); bTest = (Button) findViewById(R.id.bTest); bPlay = (Button) findViewById(R.id.bPlay); bLogout = (Button) findViewById(R.id.bLogout); bShare = (Button) findViewById(R.id.bShare); bGoogleSignIn = (SignInButton) findViewById(R.id.bGoogleSignIn); bGoogleSignUp = (SignInButton) findViewById(R.id.bGoogleSignUp); mOpenDialog = findViewById(R.id.bShare); GoogleSignInOptions signInOption = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN).requestEmail().requestIdToken(REQ_TOKEN).build(); ImageView img = (ImageView) findViewById(R.id.ivImage); Bitmap bitmap = BitmapFactory.decodeFile("/sdcard/sample-1.jpg"); img.setImageBitmap(bitmap); mOpenDialog.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { MyCustomDialog dialog = new MyCustomDialog(); dialog.show(getFragmentManager(), "LeaderboardActivityUser"); } }); // bShare.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View view) { // Intent intent = YouTubeStandalonePlayer.createVideoIntent(_TestActivity.this, YouTubeConfig.getApiKey(), "yVqFow3sNOY"); // startActivity(intent); // } // }); bShare.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { AlertDialog.Builder mBuilder = new AlertDialog.Builder(_TestActivity.this); View mView = getLayoutInflater().inflate(R.layout.terms_layout, null); Button mCancel = (Button) mView.findViewById(R.id.bCancel); WebView wvLoad = (WebView) mView.findViewById(R.id.wvLoad); wvLoad.loadUrl("https://raadz.com/privacy.html"); mBuilder.setView(mView); final AlertDialog dialog = mBuilder.create(); dialog.show(); } }); bGoogleSignIn.setOnClickListener(this); bGoogleSignUp.setOnClickListener(this); bLogout.setOnClickListener(this); bTest.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.google.com")); startActivity(browserIntent); } }); // bPlay.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View view) { // Intent intent = new Intent(); // intent.setAction(android.content.Intent.ACTION_PICK); // intent.setData(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI); // startActivityForResult(intent, PICK_AUDIO); // } // }); } public void playVideo(String url) { if (player != null) { player.cueVideo(url); Log.d("url ", url); //player.play(); } } public String fetchContent(String http) { try { HttpClient client = new DefaultHttpClient(); HttpPost postalcall = new HttpPost(http); HttpResponse response = client.execute(postalcall); if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { str = EntityUtils.toString(response.getEntity()); } }catch(IOException e){ e.printStackTrace(); } return str; } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); // Checks the orientation of the screen if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) { Log.d("Log ", "Landscape"); } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) { Log.d("Log ", "Portrait"); } } public void signOut() { Auth.GoogleSignInApi.signOut(googleApiClient).setResultCallback( new ResultCallback<Status>() { @Override public void onResult(Status status) { Toast.makeText(_TestActivity.this, "We've signed out", Toast.LENGTH_SHORT).show(); updateUI(false); } }); } public void signIn() { Intent in = Auth.GoogleSignInApi.getSignInIntent(googleApiClient); startActivityForResult(in, REQ_CODE); } public void updateUI(boolean SI) { if (SI == true) { Log.d("updateUI ", String.valueOf(SI)); LLButtons.setVisibility(View.GONE); LLLogout.setVisibility(View.VISIBLE); } if (SI == false) { Log.d("updateUI ", String.valueOf(SI)); LLLogout.setVisibility(View.GONE); LLButtons.setVisibility(View.VISIBLE); } } @Override public void onConnectionFailed(@NonNull ConnectionResult connectionResult) { } @Override public void onPointerCaptureChanged(boolean hasCapture) { } @Override public void onConnected(@Nullable Bundle bundle) { } @Override public void onConnectionSuspended(int i) { } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode == RESULT_OK) { GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data); handleResult(result); } super.onActivityResult(requestCode, resultCode, data); } public void handleResult(final GoogleSignInResult handleResult) { if (InOut.equals("in")) { if (handleResult.isSuccess()) { Log.d("InHandleResult ", "1"); SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); SharedPreferences.Editor edit = preferences.edit(); final GoogleSignInAccount account = handleResult.getSignInAccount(); fName = account.getGivenName(); lName = account.getFamilyName(); email = account.getEmail(); username = account.getDisplayName(); id = account.getId(); token = handleResult.getSignInAccount().getIdToken(); Log.d("Googlefname ", fName); Log.d("Googlelname ", lName); Log.d("Googleemail ", email); Log.d("Googlefusername ", username); Log.d("Googleid ", id); Log.d("Googletoken ", token); updateUI(true); Log.d("Login" + " - ", "Success"); GoogleFunction(id, token); } else { updateUI(false); Toast.makeText(this, "Google Login Failed", Toast.LENGTH_SHORT).show(); } } if (InOut.equals("out")) { if (handleResult.isSuccess()) { Log.d("InHandleResult ", "1"); SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); SharedPreferences.Editor edit = preferences.edit(); final GoogleSignInAccount account = handleResult.getSignInAccount(); fName = account.getGivenName(); lName = account.getFamilyName(); email = account.getEmail(); username = account.getDisplayName(); id = account.getId(); token = handleResult.getSignInAccount().getIdToken(); Log.d("Googlefname ", fName); Log.d("Googlelname ", lName); Log.d("Googleemail ", email); Log.d("Googlefusername ", username); Log.d("Googleid ", id); Log.d("Googletoken ", token); updateUI(true); Log.d("Login" + " - ", "Success"); GoogleSignUp(fName, lName, email, "", id, token); } else { updateUI(false); Toast.makeText(this, "Google Login Failed", Toast.LENGTH_SHORT).show(); } } } @Override public void cancel() { } @Override public void dismiss() { } @Override public void onClick(View view) { if (view == bGoogleSignIn) { InOut = "in"; buttonPlaceholder = "bGoogleSignIn"; signIn(); } if (view == bGoogleSignUp) { InOut = "out"; buttonPlaceholder = "bGoogleSignUp"; signIn(); } if (view == bLogout) { signOut(); } } @Override public void processFinish(String s) { Log.d("GoogleOutput ", s); } public void GoogleSignUp(final String first, final String last, final String email, final String referrer, final String google_id, final String google_token) { class SendPostReqAsyncTask extends AsyncTask<String, Void, String> { @Override protected void onPreExecute() { super.onPreExecute(); } @Override protected String doInBackground(String... params) { List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); nameValuePairs.add(new BasicNameValuePair("first_name", first)); nameValuePairs.add(new BasicNameValuePair("last_name", last)); nameValuePairs.add(new BasicNameValuePair("email", email)); nameValuePairs.add(new BasicNameValuePair("referrer", referrer)); nameValuePairs.add(new BasicNameValuePair("user_id", google_id)); nameValuePairs.add(new BasicNameValuePair("goog_access_token", google_token)); try { httpRequest = ""; bufferedReader = null; stringBuffer = new java.lang.StringBuffer(); HttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(RaddzIDURL); httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse response = httpClient.execute(httpPost); HttpPost request = new HttpPost(RaddzIDURL); UrlEncodedFormEntity entity = new UrlEncodedFormEntity(nameValuePairs); request.setEntity(entity); bufferedReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); String line = ""; String LineSeparator = System.getProperty("line.separator"); while ((line = bufferedReader.readLine()) != null) { stringBuffer.append(line + LineSeparator); //Log.d("stringBuffer: ", stringBuffer.toString()); } httpRequest = stringBuffer.toString(); bufferedReader.close(); } catch (ClientProtocolException e) { } catch (IOException e) { } Log.d("httpRequest Google ", httpRequest); runOnUiThread(new Runnable() { public void run() { SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); SharedPreferences.Editor edit = preferences.edit(); edit.putString("google_information", httpRequest); edit.commit(); } }); SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); SharedPreferences.Editor edit = preferences.edit(); edit.remove("user_data").apply(); edit.putString("user_data", httpRequest); edit.commit(); return httpRequest; } @Override protected void onPostExecute(final String result) { super.onPostExecute(result); Log.d("PostResult ", result); } } SendPostReqAsyncTask sendPostReqAsyncTask = new SendPostReqAsyncTask(); sendPostReqAsyncTask.execute(google_id, google_token); } public void GoogleFunction(final String google_id, final String google_token) { class SendPostReqAsyncTask extends AsyncTask<String, Void, String> { @Override protected void onPreExecute() { super.onPreExecute(); } @Override protected String doInBackground(String... params) { List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); nameValuePairs.add(new BasicNameValuePair("google_user_id", google_id)); nameValuePairs.add(new BasicNameValuePair("google_access_token", google_token)); try { httpRequest = ""; bufferedReader = null; stringBuffer = new java.lang.StringBuffer(); HttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(RaddzIDURL); httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse response = httpClient.execute(httpPost); HttpPost request = new HttpPost(RaddzIDURL); UrlEncodedFormEntity entity = new UrlEncodedFormEntity(nameValuePairs); request.setEntity(entity); bufferedReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); String line = ""; String LineSeparator = System.getProperty("line.separator"); while ((line = bufferedReader.readLine()) != null) { stringBuffer.append(line + LineSeparator); //Log.d("stringBuffer: ", stringBuffer.toString()); } httpRequest = stringBuffer.toString(); bufferedReader.close(); } catch (ClientProtocolException e) { } catch (IOException e) { } Log.d("httpRequest Google ", httpRequest); runOnUiThread(new Runnable() { public void run() { SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); SharedPreferences.Editor edit = preferences.edit(); edit.putString("google_information", httpRequest); edit.commit(); } }); SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); SharedPreferences.Editor edit = preferences.edit(); edit.remove("user_data").apply(); edit.putString("user_data", httpRequest); edit.commit(); return httpRequest; } @Override protected void onPostExecute(final String result) { super.onPostExecute(result); SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); SharedPreferences.Editor edit = preferences.edit(); if (!result.equals("invalid access token") && !result.equals("invalid data")) { Log.d("GoogleResult ", result); Log.d("GoogleID ", preferences.getString("google_id", "")); Log.d("GoogleToken ", preferences.getString("google_token", "")); String[] parts = result.split(":"); for (int i = 0; i < parts.length; i++) { Log.d("-", "-"); Log.d("parts ", parts[i]); Log.d("count ", String.valueOf(i)); Log.d("-", "-"); if (i == 0 && parts[0].length() > 1) { UID = parts[0]; } else if (i == 0 && parts[0].length() < 8) { UID = "x"; } if (i == 1 && parts[1].length() > 1) { PID = parts[1]; } else if (i == 1 && parts[1].length() < 8) { PID = "x"; } if (i == 2 && parts[2].length() > 1) { UserToken = parts[2]; } else if (i == 2 && parts[2].length() < 8) { UserToken = "x"; } if (i == 3 && parts[3].length() > 8) { PubToken = parts[3]; } else if (i == 3 && parts[3].length() < 8) { PubToken = "x"; } } Log.d("-", "-"); Log.d("UID", UID); Log.d("PID", PID); Log.d("UserToken", UserToken); Log.d("PubToken", PubToken); Log.d("FullResult ", result); Log.d("-", "-"); } } } SendPostReqAsyncTask sendPostReqAsyncTask = new SendPostReqAsyncTask(); sendPostReqAsyncTask.execute(google_id, google_token); } public void HTMLFunction(final String http) { class SendPostReqAsyncTask extends AsyncTask<String, Void, String> { @Override protected String doInBackground(String... params) { try { HttpClient client = new DefaultHttpClient(); HttpPost postalcall = new HttpPost(http); HttpResponse response = client.execute(postalcall); if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { str = EntityUtils.toString(response.getEntity()); } }catch(IOException e){ e.printStackTrace(); } return httpRequest; } @Override protected void onPostExecute(String result) { super.onPostExecute(result); Log.d("ActiveAds ", result); } } SendPostReqAsyncTask sendPostReqAsyncTask = new SendPostReqAsyncTask(); sendPostReqAsyncTask.execute(http); } // // public String getRealPathFromURI(Context context, Uri contentUri) { // Cursor cursor = null; // try { // String[] proj = { MediaStore.Images.Media.DATA }; // cursor = context.getContentResolver().query(contentUri, proj, null, null, null); // int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); // cursor.moveToFirst(); // return cursor.getString(column_index); // } finally { // if (cursor != null) { // cursor.close(); // } // } // } // // public static String getFileNameByUri(Context context, Uri uri) // { // String fileName="unknown";//default fileName // Uri filePathUri = uri; // if (uri.getScheme().toString().compareTo("content")==0) // { // Cursor cursor = context.getContentResolver().query(uri, null, null, null, null); // if (cursor.moveToFirst()) // { // int column_index = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA);//Instead of "MediaStore.Images.Media.DATA" can be used "_data" // filePathUri = Uri.parse(cursor.getString(column_index)); // fileName = filePathUri.getLastPathSegment().toString(); // Log.d("fileName ", fileName); // } // } // else if (uri.getScheme().compareTo("file")==0) // { // fileName = filePathUri.getLastPathSegment().toString(); // Log.d("fileName ", fileName); // } // else // { // fileName = fileName+"_"+filePathUri.getLastPathSegment(); // Log.d("fileName ", fileName); // } // return fileName; // } // public String getRealPathFromURI(Uri uri) { // String[] projection = {MediaStore.Video.Media.DATA}; // @SuppressWarnings("deprecation") // Cursor cursor = managedQuery(uri, projection, null, null, null); // int column_index = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATA); // cursor.moveToFirst(); // return cursor.getString(column_index); // } // // private String getVideoIdFromFilePath(String filePath, // ContentResolver contentResolver) { // long videoId; // Log.d(TAG, "Loading file " + filePath); // Uri videosUri = MediaStore.Audio.Media.getContentUri("external"); // Log.d(TAG, "videosUri = " + videosUri.toString()); // String[] projection = {MediaStore.Video.VideoColumns._ID}; // // TODO This will break if we have no matching item in the MediaStore. // String newID = videosUri.getPath(); // Log.d(TAG, "Video ID is " + newID); // return newID; // } }
UTF-8
Java
29,543
java
_TestActivity.java
Java
[ { "context": "0}}\";\r\n public static final String SITE_KEY = \"6LcVrUwUAAAAAL2J1zasONEiiru3Lgg4z9bMxxLJ\";\r\n public static final String SECRET_KEY = \"6", "end": 6273, "score": 0.999744713306427, "start": 6233, "tag": "KEY", "value": "6LcVrUwUAAAAAL2J1zasONEiiru3Lgg4z9bMxxLJ" }, { "context": "J\";\r\n public static final String SECRET_KEY = \"6LcVrUwUAAAAADmA4tnNYUmPu8rcOcOBF1IxTt0d\";\r\n private static final int REQ_CODE = 9001;\r", "end": 6362, "score": 0.9997687339782715, "start": 6322, "tag": "KEY", "value": "6LcVrUwUAAAAADmA4tnNYUmPu8rcOcOBF1IxTt0d" }, { "context": "01;\r\n private static final String REQ_TOKEN = \"1088961401873-969414qur5dh7ied7ailbajgcst9t5ou.apps.googleusercontent.com\";\r\n\r\n @Override\r\n protected void onCreate(B", "end": 6531, "score": 0.794736385345459, "start": 6458, "tag": "KEY", "value": "1088961401873-969414qur5dh7ied7ailbajgcst9t5ou.apps.googleusercontent.com" }, { "context": "t(_TestActivity.this, YouTubeConfig.getApiKey(), \"yVqFow3sNOY\");\r\n// startActivity(intent);\r\n// ", "end": 8390, "score": 0.9949530959129333, "start": 8379, "tag": "KEY", "value": "yVqFow3sNOY" } ]
null
[]
package com.raadz.program.raadzandroid; import android.content.ContentResolver; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.content.res.Configuration; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Color; import android.media.MediaPlayer; import android.media.session.MediaController; import android.net.Uri; import android.os.AsyncTask; import android.os.Environment; import android.preference.PreferenceManager; import android.provider.MediaStore; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.DialogFragment; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.text.Html; import android.util.Log; import android.view.View; import android.webkit.WebChromeClient; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.Button; import android.widget.EditText; import android.widget.ExpandableListView; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import android.widget.VideoView; import com.facebook.share.model.ShareLinkContent; import com.facebook.share.widget.ShareDialog; import com.google.android.gms.auth.api.Auth; import com.google.android.gms.auth.api.signin.GoogleSignInAccount; import com.google.android.gms.auth.api.signin.GoogleSignInOptions; import com.google.android.gms.auth.api.signin.GoogleSignInResult; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.SignInButton; import com.google.android.gms.common.api.ApiException; import com.google.android.gms.common.api.CommonStatusCodes; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.common.api.ResultCallback; import com.google.android.gms.common.api.Status; import com.google.android.gms.safetynet.SafetyNet; import com.google.android.gms.safetynet.SafetyNetApi; import com.google.android.gms.tasks.OnFailureListener; import com.google.android.gms.tasks.OnSuccessListener; import com.google.android.youtube.player.YouTubeBaseActivity; import com.google.android.youtube.player.YouTubeInitializationResult; import com.google.android.youtube.player.YouTubePlayer; import com.google.android.youtube.player.YouTubePlayerFragment; import com.google.android.youtube.player.YouTubePlayerSupportFragment; import com.google.android.youtube.player.YouTubePlayerView; import com.google.android.youtube.player.YouTubeStandalonePlayer; import com.kosalgeek.asynctask.AsyncResponse; import com.stripe.android.view.CardMultilineWidget; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.NameValuePair; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.concurrent.Executor; import static android.R.attr.tag; import static android.provider.MediaStore.Video.Thumbnails.VIDEO_ID; import static com.raadz.program.raadzandroid.PubSubmitActivity.getFileNameByUri; import static com.raadz.program.raadzandroid.R.id.LLMain; import static com.raadz.program.raadzandroid.R.id.bYTPlay; import static com.raadz.program.raadzandroid.R.id.etVideoID; import static com.raadz.program.raadzandroid.R.id.newYTPlayer; import static com.raadz.program.raadzandroid.R.id.videoView; import static com.raadz.program.raadzandroid.R.id.wvLoad; public class _TestActivity extends YouTubeBaseActivity implements AsyncResponse, View.OnClickListener, DialogInterface, GoogleApiClient.OnConnectionFailedListener, GoogleApiClient.ConnectionCallbacks { private static final String TAG = "_TestActivity"; private Button mOpenDialog; BufferedReader bufferedReader; OutputStream outputStream; java.lang.StringBuffer stringBuffer = new java.lang.StringBuffer(); String httpRequest; GoogleApiClient googleApiClient; View view; YouTubePlayerView mYouTubePlayerView; YouTubePlayerView NewYouTubePlayerView; YouTubePlayer player; YouTubePlayer.OnInitializedListener mOnInitializedListener; YouTubePlayerFragment myYouTubePlayerFragment; WebView wvWeb; VideoView vvVideo; private ExpandableListView listView; private ExpandableListAdapter listAdapter; private List<String> listDataHeader; private HashMap<String,List<String>> listHash; ImageView ivImage; LinearLayout LLButtons; LinearLayout LLLogout; LinearLayout LLShare; Button bPlay; Button bTest; Button bLogout; Button bShare; SignInButton bGoogleSignIn; SignInButton bGoogleSignUp; String ServerLoginURL = "https://raadz.com/mobilelogin.php"; String RaddzIDURL = "https://raadz.com/getRaadzIDs.php"; String GoogleUserSignUpURL = "https://raadz.com/googusersignup.php"; String buttonPlaceholder; String userResponseToken; String UID; String PID; String UserToken; String PubToken; String fName; String lName; String email; String username; String id; String token; String InOut; String str; int PICK_VIDEO = 100; int PICK_IMAGE = 100; int PICK_AUDIO = 100; boolean updateUI; public static final String data = "{\"user_id\":{\"put_id\":\"token\",\"salary\":56000}}"; public static final String SITE_KEY = "<KEY>"; public static final String SECRET_KEY = "<KEY>"; private static final int REQ_CODE = 9001; private static final String REQ_TOKEN = "1088961401873-969414qur5dh7ied7ailbajgcst9t5ou.apps.googleusercontent.com"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity___test); mYouTubePlayerView = (YouTubePlayerView) findViewById(newYTPlayer); ivImage = (ImageView) findViewById(R.id.ivImage); LLButtons = (LinearLayout) findViewById(R.id.LLButtons); LLLogout = (LinearLayout) findViewById(R.id.LLLogout); LLShare = (LinearLayout) findViewById(R.id.LLShare); bTest = (Button) findViewById(R.id.bTest); bPlay = (Button) findViewById(R.id.bPlay); bLogout = (Button) findViewById(R.id.bLogout); bShare = (Button) findViewById(R.id.bShare); bGoogleSignIn = (SignInButton) findViewById(R.id.bGoogleSignIn); bGoogleSignUp = (SignInButton) findViewById(R.id.bGoogleSignUp); mOpenDialog = findViewById(R.id.bShare); GoogleSignInOptions signInOption = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN).requestEmail().requestIdToken(REQ_TOKEN).build(); ImageView img = (ImageView) findViewById(R.id.ivImage); Bitmap bitmap = BitmapFactory.decodeFile("/sdcard/sample-1.jpg"); img.setImageBitmap(bitmap); mOpenDialog.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { MyCustomDialog dialog = new MyCustomDialog(); dialog.show(getFragmentManager(), "LeaderboardActivityUser"); } }); // bShare.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View view) { // Intent intent = YouTubeStandalonePlayer.createVideoIntent(_TestActivity.this, YouTubeConfig.getApiKey(), "<KEY>"); // startActivity(intent); // } // }); bShare.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { AlertDialog.Builder mBuilder = new AlertDialog.Builder(_TestActivity.this); View mView = getLayoutInflater().inflate(R.layout.terms_layout, null); Button mCancel = (Button) mView.findViewById(R.id.bCancel); WebView wvLoad = (WebView) mView.findViewById(R.id.wvLoad); wvLoad.loadUrl("https://raadz.com/privacy.html"); mBuilder.setView(mView); final AlertDialog dialog = mBuilder.create(); dialog.show(); } }); bGoogleSignIn.setOnClickListener(this); bGoogleSignUp.setOnClickListener(this); bLogout.setOnClickListener(this); bTest.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.google.com")); startActivity(browserIntent); } }); // bPlay.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View view) { // Intent intent = new Intent(); // intent.setAction(android.content.Intent.ACTION_PICK); // intent.setData(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI); // startActivityForResult(intent, PICK_AUDIO); // } // }); } public void playVideo(String url) { if (player != null) { player.cueVideo(url); Log.d("url ", url); //player.play(); } } public String fetchContent(String http) { try { HttpClient client = new DefaultHttpClient(); HttpPost postalcall = new HttpPost(http); HttpResponse response = client.execute(postalcall); if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { str = EntityUtils.toString(response.getEntity()); } }catch(IOException e){ e.printStackTrace(); } return str; } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); // Checks the orientation of the screen if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) { Log.d("Log ", "Landscape"); } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) { Log.d("Log ", "Portrait"); } } public void signOut() { Auth.GoogleSignInApi.signOut(googleApiClient).setResultCallback( new ResultCallback<Status>() { @Override public void onResult(Status status) { Toast.makeText(_TestActivity.this, "We've signed out", Toast.LENGTH_SHORT).show(); updateUI(false); } }); } public void signIn() { Intent in = Auth.GoogleSignInApi.getSignInIntent(googleApiClient); startActivityForResult(in, REQ_CODE); } public void updateUI(boolean SI) { if (SI == true) { Log.d("updateUI ", String.valueOf(SI)); LLButtons.setVisibility(View.GONE); LLLogout.setVisibility(View.VISIBLE); } if (SI == false) { Log.d("updateUI ", String.valueOf(SI)); LLLogout.setVisibility(View.GONE); LLButtons.setVisibility(View.VISIBLE); } } @Override public void onConnectionFailed(@NonNull ConnectionResult connectionResult) { } @Override public void onPointerCaptureChanged(boolean hasCapture) { } @Override public void onConnected(@Nullable Bundle bundle) { } @Override public void onConnectionSuspended(int i) { } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode == RESULT_OK) { GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data); handleResult(result); } super.onActivityResult(requestCode, resultCode, data); } public void handleResult(final GoogleSignInResult handleResult) { if (InOut.equals("in")) { if (handleResult.isSuccess()) { Log.d("InHandleResult ", "1"); SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); SharedPreferences.Editor edit = preferences.edit(); final GoogleSignInAccount account = handleResult.getSignInAccount(); fName = account.getGivenName(); lName = account.getFamilyName(); email = account.getEmail(); username = account.getDisplayName(); id = account.getId(); token = handleResult.getSignInAccount().getIdToken(); Log.d("Googlefname ", fName); Log.d("Googlelname ", lName); Log.d("Googleemail ", email); Log.d("Googlefusername ", username); Log.d("Googleid ", id); Log.d("Googletoken ", token); updateUI(true); Log.d("Login" + " - ", "Success"); GoogleFunction(id, token); } else { updateUI(false); Toast.makeText(this, "Google Login Failed", Toast.LENGTH_SHORT).show(); } } if (InOut.equals("out")) { if (handleResult.isSuccess()) { Log.d("InHandleResult ", "1"); SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); SharedPreferences.Editor edit = preferences.edit(); final GoogleSignInAccount account = handleResult.getSignInAccount(); fName = account.getGivenName(); lName = account.getFamilyName(); email = account.getEmail(); username = account.getDisplayName(); id = account.getId(); token = handleResult.getSignInAccount().getIdToken(); Log.d("Googlefname ", fName); Log.d("Googlelname ", lName); Log.d("Googleemail ", email); Log.d("Googlefusername ", username); Log.d("Googleid ", id); Log.d("Googletoken ", token); updateUI(true); Log.d("Login" + " - ", "Success"); GoogleSignUp(fName, lName, email, "", id, token); } else { updateUI(false); Toast.makeText(this, "Google Login Failed", Toast.LENGTH_SHORT).show(); } } } @Override public void cancel() { } @Override public void dismiss() { } @Override public void onClick(View view) { if (view == bGoogleSignIn) { InOut = "in"; buttonPlaceholder = "bGoogleSignIn"; signIn(); } if (view == bGoogleSignUp) { InOut = "out"; buttonPlaceholder = "bGoogleSignUp"; signIn(); } if (view == bLogout) { signOut(); } } @Override public void processFinish(String s) { Log.d("GoogleOutput ", s); } public void GoogleSignUp(final String first, final String last, final String email, final String referrer, final String google_id, final String google_token) { class SendPostReqAsyncTask extends AsyncTask<String, Void, String> { @Override protected void onPreExecute() { super.onPreExecute(); } @Override protected String doInBackground(String... params) { List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); nameValuePairs.add(new BasicNameValuePair("first_name", first)); nameValuePairs.add(new BasicNameValuePair("last_name", last)); nameValuePairs.add(new BasicNameValuePair("email", email)); nameValuePairs.add(new BasicNameValuePair("referrer", referrer)); nameValuePairs.add(new BasicNameValuePair("user_id", google_id)); nameValuePairs.add(new BasicNameValuePair("goog_access_token", google_token)); try { httpRequest = ""; bufferedReader = null; stringBuffer = new java.lang.StringBuffer(); HttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(RaddzIDURL); httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse response = httpClient.execute(httpPost); HttpPost request = new HttpPost(RaddzIDURL); UrlEncodedFormEntity entity = new UrlEncodedFormEntity(nameValuePairs); request.setEntity(entity); bufferedReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); String line = ""; String LineSeparator = System.getProperty("line.separator"); while ((line = bufferedReader.readLine()) != null) { stringBuffer.append(line + LineSeparator); //Log.d("stringBuffer: ", stringBuffer.toString()); } httpRequest = stringBuffer.toString(); bufferedReader.close(); } catch (ClientProtocolException e) { } catch (IOException e) { } Log.d("httpRequest Google ", httpRequest); runOnUiThread(new Runnable() { public void run() { SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); SharedPreferences.Editor edit = preferences.edit(); edit.putString("google_information", httpRequest); edit.commit(); } }); SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); SharedPreferences.Editor edit = preferences.edit(); edit.remove("user_data").apply(); edit.putString("user_data", httpRequest); edit.commit(); return httpRequest; } @Override protected void onPostExecute(final String result) { super.onPostExecute(result); Log.d("PostResult ", result); } } SendPostReqAsyncTask sendPostReqAsyncTask = new SendPostReqAsyncTask(); sendPostReqAsyncTask.execute(google_id, google_token); } public void GoogleFunction(final String google_id, final String google_token) { class SendPostReqAsyncTask extends AsyncTask<String, Void, String> { @Override protected void onPreExecute() { super.onPreExecute(); } @Override protected String doInBackground(String... params) { List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); nameValuePairs.add(new BasicNameValuePair("google_user_id", google_id)); nameValuePairs.add(new BasicNameValuePair("google_access_token", google_token)); try { httpRequest = ""; bufferedReader = null; stringBuffer = new java.lang.StringBuffer(); HttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(RaddzIDURL); httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse response = httpClient.execute(httpPost); HttpPost request = new HttpPost(RaddzIDURL); UrlEncodedFormEntity entity = new UrlEncodedFormEntity(nameValuePairs); request.setEntity(entity); bufferedReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); String line = ""; String LineSeparator = System.getProperty("line.separator"); while ((line = bufferedReader.readLine()) != null) { stringBuffer.append(line + LineSeparator); //Log.d("stringBuffer: ", stringBuffer.toString()); } httpRequest = stringBuffer.toString(); bufferedReader.close(); } catch (ClientProtocolException e) { } catch (IOException e) { } Log.d("httpRequest Google ", httpRequest); runOnUiThread(new Runnable() { public void run() { SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); SharedPreferences.Editor edit = preferences.edit(); edit.putString("google_information", httpRequest); edit.commit(); } }); SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); SharedPreferences.Editor edit = preferences.edit(); edit.remove("user_data").apply(); edit.putString("user_data", httpRequest); edit.commit(); return httpRequest; } @Override protected void onPostExecute(final String result) { super.onPostExecute(result); SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); SharedPreferences.Editor edit = preferences.edit(); if (!result.equals("invalid access token") && !result.equals("invalid data")) { Log.d("GoogleResult ", result); Log.d("GoogleID ", preferences.getString("google_id", "")); Log.d("GoogleToken ", preferences.getString("google_token", "")); String[] parts = result.split(":"); for (int i = 0; i < parts.length; i++) { Log.d("-", "-"); Log.d("parts ", parts[i]); Log.d("count ", String.valueOf(i)); Log.d("-", "-"); if (i == 0 && parts[0].length() > 1) { UID = parts[0]; } else if (i == 0 && parts[0].length() < 8) { UID = "x"; } if (i == 1 && parts[1].length() > 1) { PID = parts[1]; } else if (i == 1 && parts[1].length() < 8) { PID = "x"; } if (i == 2 && parts[2].length() > 1) { UserToken = parts[2]; } else if (i == 2 && parts[2].length() < 8) { UserToken = "x"; } if (i == 3 && parts[3].length() > 8) { PubToken = parts[3]; } else if (i == 3 && parts[3].length() < 8) { PubToken = "x"; } } Log.d("-", "-"); Log.d("UID", UID); Log.d("PID", PID); Log.d("UserToken", UserToken); Log.d("PubToken", PubToken); Log.d("FullResult ", result); Log.d("-", "-"); } } } SendPostReqAsyncTask sendPostReqAsyncTask = new SendPostReqAsyncTask(); sendPostReqAsyncTask.execute(google_id, google_token); } public void HTMLFunction(final String http) { class SendPostReqAsyncTask extends AsyncTask<String, Void, String> { @Override protected String doInBackground(String... params) { try { HttpClient client = new DefaultHttpClient(); HttpPost postalcall = new HttpPost(http); HttpResponse response = client.execute(postalcall); if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { str = EntityUtils.toString(response.getEntity()); } }catch(IOException e){ e.printStackTrace(); } return httpRequest; } @Override protected void onPostExecute(String result) { super.onPostExecute(result); Log.d("ActiveAds ", result); } } SendPostReqAsyncTask sendPostReqAsyncTask = new SendPostReqAsyncTask(); sendPostReqAsyncTask.execute(http); } // // public String getRealPathFromURI(Context context, Uri contentUri) { // Cursor cursor = null; // try { // String[] proj = { MediaStore.Images.Media.DATA }; // cursor = context.getContentResolver().query(contentUri, proj, null, null, null); // int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); // cursor.moveToFirst(); // return cursor.getString(column_index); // } finally { // if (cursor != null) { // cursor.close(); // } // } // } // // public static String getFileNameByUri(Context context, Uri uri) // { // String fileName="unknown";//default fileName // Uri filePathUri = uri; // if (uri.getScheme().toString().compareTo("content")==0) // { // Cursor cursor = context.getContentResolver().query(uri, null, null, null, null); // if (cursor.moveToFirst()) // { // int column_index = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA);//Instead of "MediaStore.Images.Media.DATA" can be used "_data" // filePathUri = Uri.parse(cursor.getString(column_index)); // fileName = filePathUri.getLastPathSegment().toString(); // Log.d("fileName ", fileName); // } // } // else if (uri.getScheme().compareTo("file")==0) // { // fileName = filePathUri.getLastPathSegment().toString(); // Log.d("fileName ", fileName); // } // else // { // fileName = fileName+"_"+filePathUri.getLastPathSegment(); // Log.d("fileName ", fileName); // } // return fileName; // } // public String getRealPathFromURI(Uri uri) { // String[] projection = {MediaStore.Video.Media.DATA}; // @SuppressWarnings("deprecation") // Cursor cursor = managedQuery(uri, projection, null, null, null); // int column_index = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATA); // cursor.moveToFirst(); // return cursor.getString(column_index); // } // // private String getVideoIdFromFilePath(String filePath, // ContentResolver contentResolver) { // long videoId; // Log.d(TAG, "Loading file " + filePath); // Uri videosUri = MediaStore.Audio.Media.getContentUri("external"); // Log.d(TAG, "videosUri = " + videosUri.toString()); // String[] projection = {MediaStore.Video.VideoColumns._ID}; // // TODO This will break if we have no matching item in the MediaStore. // String newID = videosUri.getPath(); // Log.d(TAG, "Video ID is " + newID); // return newID; // } }
29,467
0.582541
0.57946
751
37.335552
29.6213
201
false
false
0
0
0
0
0
0
0.711052
false
false
1
f43a0388f7d075b613ec82da4b2c060416003e31
24,575,802,876,049
61a622eab52cbea805e9ccd5ffe92278cab04877
/concurrent-programming/java-concurrent-test/src/test/java/me/josephzhu/javaconcurrenttest/concurrent/executors/ForkJoinPoolBenchmark.java
644e3e38f2db99e71d43ee7fe4249de672873c80
[ "Apache-2.0" ]
permissive
renyiwei-xinyi/jmh-and-javanew
https://github.com/renyiwei-xinyi/jmh-and-javanew
edbbd611c5365211fe2718cdddf3de5e3ffd6487
c70d5043420a2f7f8e500de076ad82f5df801756
refs/heads/master
2023-03-09T06:15:56.504000
2021-02-28T12:40:55
2021-02-28T12:40:55
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package me.josephzhu.javaconcurrenttest.concurrent.executors; import lombok.extern.slf4j.Slf4j; import org.junit.Test; import org.springframework.util.StopWatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; import java.util.stream.LongStream; @Slf4j public class ForkJoinPoolBenchmark { @Test public void test() throws InterruptedException { AtomicLong atomicLong = new AtomicLong(); StopWatch stopWatch = new StopWatch(); ExecutorService normal = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()); ExecutorService forkjoin = Executors.newWorkStealingPool(Runtime.getRuntime().availableProcessors()); stopWatch.start("normal"); LongStream.rangeClosed(1, 10000000).forEach(__->normal.submit(atomicLong::incrementAndGet)); normal.shutdown(); normal.awaitTermination(1, TimeUnit.HOURS); stopWatch.stop(); long r = atomicLong.get(); stopWatch.start("forkjoin"); LongStream.rangeClosed(1, 10000000).forEach(__->forkjoin.submit(atomicLong::incrementAndGet)); forkjoin.shutdown(); forkjoin.awaitTermination(1, TimeUnit.HOURS); stopWatch.stop(); log.info(stopWatch.prettyPrint()); log.info("result:{},{}", r, atomicLong.get()); } }
UTF-8
Java
1,423
java
ForkJoinPoolBenchmark.java
Java
[ { "context": "package me.josephzhu.javaconcurrenttest.concurrent.executors;\n\nimport ", "end": 20, "score": 0.9370718002319336, "start": 11, "tag": "USERNAME", "value": "josephzhu" } ]
null
[]
package me.josephzhu.javaconcurrenttest.concurrent.executors; import lombok.extern.slf4j.Slf4j; import org.junit.Test; import org.springframework.util.StopWatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; import java.util.stream.LongStream; @Slf4j public class ForkJoinPoolBenchmark { @Test public void test() throws InterruptedException { AtomicLong atomicLong = new AtomicLong(); StopWatch stopWatch = new StopWatch(); ExecutorService normal = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()); ExecutorService forkjoin = Executors.newWorkStealingPool(Runtime.getRuntime().availableProcessors()); stopWatch.start("normal"); LongStream.rangeClosed(1, 10000000).forEach(__->normal.submit(atomicLong::incrementAndGet)); normal.shutdown(); normal.awaitTermination(1, TimeUnit.HOURS); stopWatch.stop(); long r = atomicLong.get(); stopWatch.start("forkjoin"); LongStream.rangeClosed(1, 10000000).forEach(__->forkjoin.submit(atomicLong::incrementAndGet)); forkjoin.shutdown(); forkjoin.awaitTermination(1, TimeUnit.HOURS); stopWatch.stop(); log.info(stopWatch.prettyPrint()); log.info("result:{},{}", r, atomicLong.get()); } }
1,423
0.717498
0.701335
36
38.527779
29.011
109
false
false
0
0
0
0
0
0
0.916667
false
false
1
620a432a7433366c04dd7458a64313d4c00e5f6a
31,877,247,282,226
ef5118800e99643c894ac85cd90a72563feaad60
/src/test/java/com/leetcode/easy/TwoSumTest.java
0ce59e9c705489e1ae2136db5eeb245ef574a409
[]
no_license
kamikhaylov/leetcode
https://github.com/kamikhaylov/leetcode
40541510b4586cd9ba1a73355e18f446a00a4416
5a80f6d735d6c480e152b247ee76659ef1b01648
refs/heads/master
2023-04-09T09:30:48.887000
2021-04-18T11:25:55
2021-04-18T11:25:55
358,970,543
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.leetcode.easy; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import org.junit.Test; public class TwoSumTest { @Test public void whenArrAndTargetThenNewArr1() { TwoSum twoSum = new TwoSum(); int[] rsl = twoSum.twoSum(new int[] {2, 7, 11, 15}, 9); int[] expected = new int[] {0, 1}; assertThat(rsl, is(expected)); } @Test public void whenArrAndTargetThenNewArr2() { TwoSum twoSum = new TwoSum(); int[] rsl = twoSum.twoSum(new int[] {3, 2, 4}, 6); int[] expected = new int[] {1, 2}; assertThat(rsl, is(expected)); } @Test public void whenArrAndTargetThenNewArr3() { TwoSum twoSum = new TwoSum(); int[] rsl = twoSum.twoSum(new int[] {3, 3}, 6); int[] expected = new int[] {0, 1}; assertThat(rsl, is(expected)); } @Test public void whenArrAndTargetThenNewArr4() { TwoSum twoSum = new TwoSum(); int[] rsl = twoSum.twoSum(new int[] {-1, -2, -3, -4, -5}, -8); int[] expected = new int[] {2, 4}; assertThat(rsl, is(expected)); } }
UTF-8
Java
1,161
java
TwoSumTest.java
Java
[]
null
[]
package com.leetcode.easy; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import org.junit.Test; public class TwoSumTest { @Test public void whenArrAndTargetThenNewArr1() { TwoSum twoSum = new TwoSum(); int[] rsl = twoSum.twoSum(new int[] {2, 7, 11, 15}, 9); int[] expected = new int[] {0, 1}; assertThat(rsl, is(expected)); } @Test public void whenArrAndTargetThenNewArr2() { TwoSum twoSum = new TwoSum(); int[] rsl = twoSum.twoSum(new int[] {3, 2, 4}, 6); int[] expected = new int[] {1, 2}; assertThat(rsl, is(expected)); } @Test public void whenArrAndTargetThenNewArr3() { TwoSum twoSum = new TwoSum(); int[] rsl = twoSum.twoSum(new int[] {3, 3}, 6); int[] expected = new int[] {0, 1}; assertThat(rsl, is(expected)); } @Test public void whenArrAndTargetThenNewArr4() { TwoSum twoSum = new TwoSum(); int[] rsl = twoSum.twoSum(new int[] {-1, -2, -3, -4, -5}, -8); int[] expected = new int[] {2, 4}; assertThat(rsl, is(expected)); } }
1,161
0.578811
0.551249
39
28.794872
20.569057
70
false
false
0
0
0
0
0
0
1.076923
false
false
1
e5864d17e2fea4e92b986d689717f7e6a0cba930
12,867,722,021,982
a2f7d6a312c048d9fa9aed24c0cce58433e454b3
/beautiful-api/src/main/java/com/beautiful/api/block/DataBlock.java
dbf0c46310e7edec83ef09c25e2c7887978b2d41
[ "Apache-2.0" ]
permissive
xlzwhboy/flowml
https://github.com/xlzwhboy/flowml
72b25e55e8ce54f08c4294ab4479278438b31bd3
2181bf1ae01b09a2fa90a204421a33d34c8c41f0
refs/heads/master
2020-03-13T22:19:34.371000
2018-06-03T07:44:50
2018-06-03T07:44:50
131,313,999
0
0
Apache-2.0
true
2018-06-03T07:44:51
2018-04-27T15:27:50
2018-05-11T09:37:29
2018-06-03T07:44:51
2,535
0
0
0
Java
false
null
package com.beautiful.api.block; import com.beautiful.api.writable.WritableValue; import com.google.common.collect.Lists; import java.io.Serializable; import java.util.List; /** * @Description:抽象 可以 扩展 这是行列形式 * @Author: zhuyuping * @CreateDate: 2018/4/10 13:46 **/ public class DataBlock<T extends WritableValue> implements Serializable { private List<List<T>> blocks = Lists.newArrayList(); public List<List<T>> getBlocks() { return blocks; } public void setBlocks(List<List<T>> blocks) { this.blocks = blocks; } public T get(final int row, final int col) { return blocks.get(row).get(col); } public void set(final T value, final int row, final int col) { blocks.get(row).set(col, value); } //public void addHorizontal() public void addVertical(List<WritableValue> values) { for (List<T> block : blocks) { } } /** * 行 * * @return */ public int rows() { return blocks.size(); } /** * 列 * * @return */ public int cols() { return blocks.isEmpty() ? 0 : blocks.get(0).size(); } }
UTF-8
Java
1,200
java
DataBlock.java
Java
[ { "context": ";\n\n/**\n * @Description:抽象 可以 扩展 这是行列形式\n * @Author: zhuyuping\n * @CreateDate: 2018/4/10 13:46\n **/\npublic class", "end": 234, "score": 0.999494194984436, "start": 225, "tag": "USERNAME", "value": "zhuyuping" } ]
null
[]
package com.beautiful.api.block; import com.beautiful.api.writable.WritableValue; import com.google.common.collect.Lists; import java.io.Serializable; import java.util.List; /** * @Description:抽象 可以 扩展 这是行列形式 * @Author: zhuyuping * @CreateDate: 2018/4/10 13:46 **/ public class DataBlock<T extends WritableValue> implements Serializable { private List<List<T>> blocks = Lists.newArrayList(); public List<List<T>> getBlocks() { return blocks; } public void setBlocks(List<List<T>> blocks) { this.blocks = blocks; } public T get(final int row, final int col) { return blocks.get(row).get(col); } public void set(final T value, final int row, final int col) { blocks.get(row).set(col, value); } //public void addHorizontal() public void addVertical(List<WritableValue> values) { for (List<T> block : blocks) { } } /** * 行 * * @return */ public int rows() { return blocks.size(); } /** * 列 * * @return */ public int cols() { return blocks.isEmpty() ? 0 : blocks.get(0).size(); } }
1,200
0.590444
0.579352
61
18.213116
19.82391
73
false
false
0
0
0
0
0
0
0.262295
false
false
1
0d9714b501351c455c76d7e48ae0c44852d39398
790,274,001,856
c48111fc243c11ec6198a5d859078844a7571b0a
/homework_00_4/src/task_7/Main.java
41aab32cce4d652b2ff1834677632f649bd6bf2c
[]
no_license
oleksiuk-petro/homework_java_core
https://github.com/oleksiuk-petro/homework_java_core
9c88e021627789db9260f02e914704d0990626cd
f8cdd7829e9db62990b99c7816512528a83c556c
refs/heads/master
2023-08-25T11:51:19.640000
2021-09-19T21:27:01
2021-09-19T21:27:01
360,096,516
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* Користувач вводить розмірність масиву. Масив повинен містити рядкові величини. Користувач вводить або "bad" або "good". Якщо масив не містить значення "good, то виводиться повідомлення "Fail!". Якщо масив містить одне або два значення "good", то виводиться повідомлення "Publish!". Якщо масив містить більше двох значень "good", то виводиться повідомлення "I smell a series!". */ package task_7; import java.util.Scanner; public class Main { public static void main(String[] args) { //вводимо розмірність масиву int size; System.out.print("Enter size of array: size="); Scanner scan_size = new Scanner(System.in); size = scan_size.nextInt(); System.out.println("--------------------"); //оголощуємо масив рядків String[] array = new String[size]; //вводимо масив рядків System.out.println("Please, enter words \"good\" or \"bad"); for (int i = 0; i < array.length; i++) { System.out.print("array [" + i + "]="); Scanner scan_array = new Scanner(System.in); array[i] = scan_array.nextLine(); } System.out.println("--------------------"); //виводимо масив рядків for (int i = 0; i < array.length; i++) { System.out.println("array [" + i + "]=" + array[i]); } //викликаємо метод, який виводить повідомлення String welcome = well(array); System.out.println(welcome); } public static String well(String[] array) { //тимчасова змінна, яку повертатиме метод "well" String text = null; //в циклі рахуємо кількість слів "good" int k = 0; String a = "good"; for (int i = 0; i < array.length; i++) { if (array[i].equals(a)) { k++; } } System.out.println(k); //визначаємо текст повідомлення, яке буде виводитись if (k <= 0) { text = "Fail!"; } else if ((k > 0) && (k < 3)) { text = "Publish!"; } else { text = "I smell a series!"; } return text; } }
UTF-8
Java
2,659
java
Main.java
Java
[]
null
[]
/* Користувач вводить розмірність масиву. Масив повинен містити рядкові величини. Користувач вводить або "bad" або "good". Якщо масив не містить значення "good, то виводиться повідомлення "Fail!". Якщо масив містить одне або два значення "good", то виводиться повідомлення "Publish!". Якщо масив містить більше двох значень "good", то виводиться повідомлення "I smell a series!". */ package task_7; import java.util.Scanner; public class Main { public static void main(String[] args) { //вводимо розмірність масиву int size; System.out.print("Enter size of array: size="); Scanner scan_size = new Scanner(System.in); size = scan_size.nextInt(); System.out.println("--------------------"); //оголощуємо масив рядків String[] array = new String[size]; //вводимо масив рядків System.out.println("Please, enter words \"good\" or \"bad"); for (int i = 0; i < array.length; i++) { System.out.print("array [" + i + "]="); Scanner scan_array = new Scanner(System.in); array[i] = scan_array.nextLine(); } System.out.println("--------------------"); //виводимо масив рядків for (int i = 0; i < array.length; i++) { System.out.println("array [" + i + "]=" + array[i]); } //викликаємо метод, який виводить повідомлення String welcome = well(array); System.out.println(welcome); } public static String well(String[] array) { //тимчасова змінна, яку повертатиме метод "well" String text = null; //в циклі рахуємо кількість слів "good" int k = 0; String a = "good"; for (int i = 0; i < array.length; i++) { if (array[i].equals(a)) { k++; } } System.out.println(k); //визначаємо текст повідомлення, яке буде виводитись if (k <= 0) { text = "Fail!"; } else if ((k > 0) && (k < 3)) { text = "Publish!"; } else { text = "I smell a series!"; } return text; } }
2,659
0.538567
0.534894
68
31.029411
23.109694
98
false
false
0
0
0
0
0
0
0.558824
false
false
1
d3ebe252e662cfc4c8e8b822c995d71aa94c848d
8,598,524,544,619
0427bfb55c6e29d1e8ec1ea1f405f2fdf1bad063
/app/src/main/java/com/example/victorkeinander/testapplication/BorrowingsJSONAdapter.java
9bbfd4e1b395e71d672c1366ecbaf7e4bc88d2cd
[]
no_license
keinander/Doelibs
https://github.com/keinander/Doelibs
3676eaa1272a3e81ef567c04c3415c374d8b6249
9d35fb41137b9628b10b17417eccd277eaba09e2
refs/heads/master
2015-07-14T18:38:29
2014-12-11T13:11:28
2014-12-11T13:11:28
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.victorkeinander.testapplication; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import org.json.JSONArray; import org.json.JSONObject; /** * Created by victorkeinander on 2014-12-04. */ public class BorrowingsJSONAdapter extends JSONAdapter { public BorrowingsJSONAdapter(Context context, LayoutInflater i){ super(context,i); context = context; inflater = i; jsonArray = new JSONArray(); } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder; if(convertView == null){ convertView = inflater.inflate(R.layout.borrowing_row,null); holder = new ViewHolder(); holder.borrowingTitle = (TextView) convertView.findViewById(R.id.borrowing_title); holder.borrowingDate = (TextView) convertView.findViewById(R.id.borrowing_date); convertView.setTag(holder); }else{ holder = (ViewHolder) convertView.getTag(); } JSONObject jsonObject = (JSONObject) getItem(position); String titleName = jsonObject.optString("Title"); String date = jsonObject.optString("Expires"); String tag = jsonObject.optString("Tag"); holder.borrowingTitle.setText(titleName); holder.borrowingDate.setText(date); return convertView; } private static class ViewHolder{ public TextView borrowingTitle; public TextView borrowingDate; } }
UTF-8
Java
1,626
java
BorrowingsJSONAdapter.java
Java
[ { "context": "package com.example.victorkeinander.testapplication;\n\nimport android.content.Context;", "end": 35, "score": 0.9293924570083618, "start": 20, "tag": "USERNAME", "value": "victorkeinander" }, { "context": "ay;\nimport org.json.JSONObject;\n\n/**\n * Created by victorkeinander on 2014-12-04.\n */\npublic class BorrowingsJSONAda", "end": 301, "score": 0.9996750950813293, "start": 286, "tag": "USERNAME", "value": "victorkeinander" } ]
null
[]
package com.example.victorkeinander.testapplication; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import org.json.JSONArray; import org.json.JSONObject; /** * Created by victorkeinander on 2014-12-04. */ public class BorrowingsJSONAdapter extends JSONAdapter { public BorrowingsJSONAdapter(Context context, LayoutInflater i){ super(context,i); context = context; inflater = i; jsonArray = new JSONArray(); } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder; if(convertView == null){ convertView = inflater.inflate(R.layout.borrowing_row,null); holder = new ViewHolder(); holder.borrowingTitle = (TextView) convertView.findViewById(R.id.borrowing_title); holder.borrowingDate = (TextView) convertView.findViewById(R.id.borrowing_date); convertView.setTag(holder); }else{ holder = (ViewHolder) convertView.getTag(); } JSONObject jsonObject = (JSONObject) getItem(position); String titleName = jsonObject.optString("Title"); String date = jsonObject.optString("Expires"); String tag = jsonObject.optString("Tag"); holder.borrowingTitle.setText(titleName); holder.borrowingDate.setText(date); return convertView; } private static class ViewHolder{ public TextView borrowingTitle; public TextView borrowingDate; } }
1,626
0.675892
0.670972
57
27.526316
25.28442
94
false
false
0
0
0
0
0
0
0.578947
false
false
1
b5b2d0774abda21aeb6ab79df3b59379062f4047
22,557,168,303,600
afd1ab6c34142f5ec6ecbfd8414e0d0ae8adeffd
/app/src/main/java/com/example/xcomputers/testassignment/viewHolders/AbstractViewHolder.java
59449f455b50438bafdcfb730015ba9990e1ca78
[]
no_license
georgi-nikolov/TestAssignment
https://github.com/georgi-nikolov/TestAssignment
bc032b00c40c505d5f3cc0371a64d0412630c409
593952d880a2cc4dc99a94897c561350a74037d4
refs/heads/master
2021-01-18T17:24:12.841000
2017-04-20T15:26:30
2017-04-20T15:26:30
86,794,577
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.xcomputers.testassignment.viewHolders; import android.support.v7.widget.RecyclerView; import android.view.View; import com.example.xcomputers.testassignment.adapters.BrowsingAdapter; import com.pcloud.sdk.RemoteEntry; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; /** * Created by Georgi on 4/18/2017. */ /** * An abstraction of a RecyclerView.ViewHolder to house the logic for the OnClickListener and the Date formatting */ public abstract class AbstractViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener { private BrowsingAdapter.OnResultClickListener resultsItemClickListener; AbstractViewHolder(View itemView) { super(itemView); } public abstract void bind(RemoteEntry entry); @Override public void onClick(View v) { if (getAdapterPosition() == RecyclerView.NO_POSITION) { return; } resultsItemClickListener.onResultClicked(v, getAdapterPosition()); } String formatDate(Date date) { SimpleDateFormat formatter = new SimpleDateFormat("dd.MM.yyyy HH:mm", Locale.getDefault()); return formatter.format(date); } public void setOnClickListener(BrowsingAdapter.OnResultClickListener listener) { this.resultsItemClickListener = listener; } }
UTF-8
Java
1,350
java
AbstractViewHolder.java
Java
[ { "context": ".Date;\nimport java.util.Locale;\n\n/**\n * Created by Georgi on 4/18/2017.\n */\n\n/**\n * An abstraction of a Rec", "end": 349, "score": 0.9085189700126648, "start": 343, "tag": "USERNAME", "value": "Georgi" } ]
null
[]
package com.example.xcomputers.testassignment.viewHolders; import android.support.v7.widget.RecyclerView; import android.view.View; import com.example.xcomputers.testassignment.adapters.BrowsingAdapter; import com.pcloud.sdk.RemoteEntry; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; /** * Created by Georgi on 4/18/2017. */ /** * An abstraction of a RecyclerView.ViewHolder to house the logic for the OnClickListener and the Date formatting */ public abstract class AbstractViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener { private BrowsingAdapter.OnResultClickListener resultsItemClickListener; AbstractViewHolder(View itemView) { super(itemView); } public abstract void bind(RemoteEntry entry); @Override public void onClick(View v) { if (getAdapterPosition() == RecyclerView.NO_POSITION) { return; } resultsItemClickListener.onResultClicked(v, getAdapterPosition()); } String formatDate(Date date) { SimpleDateFormat formatter = new SimpleDateFormat("dd.MM.yyyy HH:mm", Locale.getDefault()); return formatter.format(date); } public void setOnClickListener(BrowsingAdapter.OnResultClickListener listener) { this.resultsItemClickListener = listener; } }
1,350
0.74
0.734074
49
26.55102
31.382473
113
false
false
0
0
0
0
0
0
0.367347
false
false
1
2680d35756fa9c802852fdd3d582f5df5bc0f201
33,243,046,922,683
1c999e8f8e5948b968989f217dcf669d84b2cc08
/src/main/java/com/github/izerui/form/validator/UrlValidator.java
6be9fc568e8b3d5e938252c1e2d3cd35734d6c5f
[]
no_license
izerui/validator
https://github.com/izerui/validator
1b0d87ac9494803f1bfc2a26779947291472600a
5974f9c29e3886bbffeec3cc5f7566fe40a26857
refs/heads/master
2020-04-15T04:21:46.479000
2019-01-07T04:56:28
2019-01-07T04:56:28
164,380,130
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.github.izerui.form.validator; import com.github.izerui.form.ValidatorException; import static org.apache.commons.validator.GenericValidator.isUrl; /** * url验证器 * Created by serv on 2016/12/5. */ public class UrlValidator implements Validator<String> { @Override public boolean isValid(Object obj, Property<String> property) throws ValidatorException { return isUrl(property.getValue()); } @Override public String name() { return "url"; } @Override public Class<String> pType() { return String.class; } }
UTF-8
Java
592
java
UrlValidator.java
Java
[ { "context": "nericValidator.isUrl;\n\n/**\n * url验证器\n * Created by serv on 2016/12/5.\n */\npublic class UrlValidator imple", "end": 194, "score": 0.9436717629432678, "start": 190, "tag": "USERNAME", "value": "serv" } ]
null
[]
package com.github.izerui.form.validator; import com.github.izerui.form.ValidatorException; import static org.apache.commons.validator.GenericValidator.isUrl; /** * url验证器 * Created by serv on 2016/12/5. */ public class UrlValidator implements Validator<String> { @Override public boolean isValid(Object obj, Property<String> property) throws ValidatorException { return isUrl(property.getValue()); } @Override public String name() { return "url"; } @Override public Class<String> pType() { return String.class; } }
592
0.686007
0.674061
28
19.928572
23.626451
93
false
false
0
0
0
0
0
0
0.25
false
false
1
a1a7ee4b68f26ffa04cecb5659029c61a595eb3c
25,821,343,442,977
4f219dd01e17dd23edfba31be7da1b6a15759340
/src/executor/commandable/turtle/StandardTurtle.java
6f7ed6cb0d39bf225ad0af9d06a272358d8b417e
[ "MIT" ]
permissive
ramilmsh-archive/cs308_slogo
https://github.com/ramilmsh-archive/cs308_slogo
063ed589e5c21ba9d986a7826bd510d0157abcf3
a3dd2ea7d7dd67ff9826c921347fa6af934c6db9
refs/heads/master
2020-07-01T15:02:26.006000
2019-08-08T07:34:03
2019-08-08T07:34:03
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package executor.commandable.turtle; import java.util.HashMap; import java.util.Observable; import executor.commandable.Commandable; import java.util.Map; /** * Observable code found here: * http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/util/Observable.java#Observable.notifyObservers%28java.lang.Object%29 * * Also used: https://docs.oracle.com/javase/7/docs/api/java/util/Observer.html * * Implementation of the Turtle API Controls turtle movement and visibility * * @author Natalie * */ public class StandardTurtle extends Observable implements Turtle, Commandable { private static final int HALF_CIRCLE = 180; public static final int FULL_CIRCLE = 360; public static final int ANGLE_ADJUST = 90; public static final double STARTING_ANGLE = 0; public static final int STARTING_TVIS = 1; public static final int STARTING_SHAPE = 0; public static final int STARTING_ACTIVE = 1; public static final int OFFSET = 80; private int max_x; private int max_y; private int id; private TurtlePoint coords = new TurtlePoint(0, 0); private double angle = STARTING_ANGLE; private int turtleVis = STARTING_TVIS; private int turtleShape = STARTING_SHAPE; private int active = STARTING_ACTIVE; private Map<String, Double> changes = new HashMap<String, Double>(); public StandardTurtle(int X, int Y, int id) { max_x = X; max_y = Y-OFFSET; this.id = id; } @Override public double interpretQuery(String query){ switch(query){ case "XCoordinate": return coords.getX(); case "YCoordinate": return coords.getY(); case "Heading": return angle; case "Showing": return turtleVis; case "Shape": return turtleShape; } return 0; } private void checkValid(String s, double val) { if ((!(turtleVis == 0) && !(turtleVis == 1)) || (!(active==0) && !(active==1))) { changes.put("bad input", 0.0); setChanged(); return; } if (s.equals("coords")) { changes.put("x coord", coords.getX()); changes.put("y coord", coords.getY()); } else { changes.put(s, val); } setChanged(); } @Override public double move(Double dist) { double x = dist * Math.cos(Math.toRadians(angle + ANGLE_ADJUST)); double y = -dist * Math.sin(Math.toRadians(angle + ANGLE_ADJUST)); coords.translate(x, y); fixCoords(); checkValid("coords", 0.0); return dist; } @Override public double move(Double d1, Double d2) { TurtlePoint p = new TurtlePoint(d1, d2); double moved = coords.distance(p); coords.setLocation(p); fixCoords(); checkValid("coords", 0.0); return moved; } @Override public double turn(Double degrees) { angle += degrees; fixAngle(); checkValid("angle", angle); return degrees; } @Override public double absTurn(Double degrees) { double turned = degrees - angle; angle = degrees; fixAngle(); checkValid("angle", angle); return turned; } @Override public double absTurn(Double d1, Double d2) { TurtlePoint p = new TurtlePoint(d1, d2); double angle = Math.toDegrees(Math.asin(-(p.getY() - coords.getY()) / (coords.distance(p)))); if (p.getX() < coords.getX()) angle = HALF_CIRCLE - angle; if (angle < 0) angle = FULL_CIRCLE + angle; return absTurn(angle-90); } private void fixAngle() { if (angle < 0) angle = FULL_CIRCLE + angle; if (angle >= FULL_CIRCLE) angle = angle - FULL_CIRCLE; } private void fixCoords(){ if (coords.getX()>max_x) coords.setLocation(max_x, coords.getY()); if (coords.getX()<-max_x) coords.setLocation(-max_x, coords.getY()); if (coords.getY()>max_y) coords.setLocation(coords.getX(), max_y); if (coords.getY()<-max_y) coords.setLocation(coords.getX(), -max_y); } @Override public double turtleVis(Double vis) { turtleVis = vis.intValue(); checkValid("tVis", turtleVis); return turtleVis; } @Override public double reset() { angle = STARTING_ANGLE; turtleVis = STARTING_TVIS; changes.put("reset", 0.0); setChanged(); return move(0.0,0.0); } @Override public double getID() { return (double) id; } @Override public double turtleShape(Double index){ turtleShape = index.intValue(); checkValid("shape", turtleShape); return turtleShape; } @Override public double palette(Double index, Double r, Double g, Double b){ checkValid("palette", index*Math.pow(256, 3) + r*256*256 + g*256 + b); return index; } @Override public double background(Double index){ checkValid("background", index); return index; } @Override public double active(Double a){ active = a.intValue(); checkValid("active", active); return active; } @Override public void notifyObservers() { notifyObservers(new HashMap<String, Double>(changes)); } @Override protected synchronized void clearChanged() { super.clearChanged(); changes.clear(); } }
UTF-8
Java
4,848
java
StandardTurtle.java
Java
[ { "context": "rols turtle movement and visibility\n * \n * @author Natalie\n *\n */\npublic class StandardTurtle extends Observ", "end": 535, "score": 0.9998393058776855, "start": 528, "tag": "NAME", "value": "Natalie" } ]
null
[]
package executor.commandable.turtle; import java.util.HashMap; import java.util.Observable; import executor.commandable.Commandable; import java.util.Map; /** * Observable code found here: * http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/util/Observable.java#Observable.notifyObservers%28java.lang.Object%29 * * Also used: https://docs.oracle.com/javase/7/docs/api/java/util/Observer.html * * Implementation of the Turtle API Controls turtle movement and visibility * * @author Natalie * */ public class StandardTurtle extends Observable implements Turtle, Commandable { private static final int HALF_CIRCLE = 180; public static final int FULL_CIRCLE = 360; public static final int ANGLE_ADJUST = 90; public static final double STARTING_ANGLE = 0; public static final int STARTING_TVIS = 1; public static final int STARTING_SHAPE = 0; public static final int STARTING_ACTIVE = 1; public static final int OFFSET = 80; private int max_x; private int max_y; private int id; private TurtlePoint coords = new TurtlePoint(0, 0); private double angle = STARTING_ANGLE; private int turtleVis = STARTING_TVIS; private int turtleShape = STARTING_SHAPE; private int active = STARTING_ACTIVE; private Map<String, Double> changes = new HashMap<String, Double>(); public StandardTurtle(int X, int Y, int id) { max_x = X; max_y = Y-OFFSET; this.id = id; } @Override public double interpretQuery(String query){ switch(query){ case "XCoordinate": return coords.getX(); case "YCoordinate": return coords.getY(); case "Heading": return angle; case "Showing": return turtleVis; case "Shape": return turtleShape; } return 0; } private void checkValid(String s, double val) { if ((!(turtleVis == 0) && !(turtleVis == 1)) || (!(active==0) && !(active==1))) { changes.put("bad input", 0.0); setChanged(); return; } if (s.equals("coords")) { changes.put("x coord", coords.getX()); changes.put("y coord", coords.getY()); } else { changes.put(s, val); } setChanged(); } @Override public double move(Double dist) { double x = dist * Math.cos(Math.toRadians(angle + ANGLE_ADJUST)); double y = -dist * Math.sin(Math.toRadians(angle + ANGLE_ADJUST)); coords.translate(x, y); fixCoords(); checkValid("coords", 0.0); return dist; } @Override public double move(Double d1, Double d2) { TurtlePoint p = new TurtlePoint(d1, d2); double moved = coords.distance(p); coords.setLocation(p); fixCoords(); checkValid("coords", 0.0); return moved; } @Override public double turn(Double degrees) { angle += degrees; fixAngle(); checkValid("angle", angle); return degrees; } @Override public double absTurn(Double degrees) { double turned = degrees - angle; angle = degrees; fixAngle(); checkValid("angle", angle); return turned; } @Override public double absTurn(Double d1, Double d2) { TurtlePoint p = new TurtlePoint(d1, d2); double angle = Math.toDegrees(Math.asin(-(p.getY() - coords.getY()) / (coords.distance(p)))); if (p.getX() < coords.getX()) angle = HALF_CIRCLE - angle; if (angle < 0) angle = FULL_CIRCLE + angle; return absTurn(angle-90); } private void fixAngle() { if (angle < 0) angle = FULL_CIRCLE + angle; if (angle >= FULL_CIRCLE) angle = angle - FULL_CIRCLE; } private void fixCoords(){ if (coords.getX()>max_x) coords.setLocation(max_x, coords.getY()); if (coords.getX()<-max_x) coords.setLocation(-max_x, coords.getY()); if (coords.getY()>max_y) coords.setLocation(coords.getX(), max_y); if (coords.getY()<-max_y) coords.setLocation(coords.getX(), -max_y); } @Override public double turtleVis(Double vis) { turtleVis = vis.intValue(); checkValid("tVis", turtleVis); return turtleVis; } @Override public double reset() { angle = STARTING_ANGLE; turtleVis = STARTING_TVIS; changes.put("reset", 0.0); setChanged(); return move(0.0,0.0); } @Override public double getID() { return (double) id; } @Override public double turtleShape(Double index){ turtleShape = index.intValue(); checkValid("shape", turtleShape); return turtleShape; } @Override public double palette(Double index, Double r, Double g, Double b){ checkValid("palette", index*Math.pow(256, 3) + r*256*256 + g*256 + b); return index; } @Override public double background(Double index){ checkValid("background", index); return index; } @Override public double active(Double a){ active = a.intValue(); checkValid("active", active); return active; } @Override public void notifyObservers() { notifyObservers(new HashMap<String, Double>(changes)); } @Override protected synchronized void clearChanged() { super.clearChanged(); changes.clear(); } }
4,848
0.679662
0.666048
214
21.654205
20.926039
154
false
false
0
0
0
0
0
0
1.939252
false
false
1
76e168034fea5e58eb657179e58b81755c4bf8b9
584,115,602,578
65f6867b6413b4201dd8113a46d9f9e5e6930e38
/src/com/bjpowernoed/test03.java
52b4d4de616a5ec4662c05f0c58eccb94a889936
[]
no_license
wangmingzhi1234/sh2006
https://github.com/wangmingzhi1234/sh2006
40c360a209a69b23a706efc742b77f51a74e8e5f
ae1bc8a9da0e48e0c24406f3359d3a3ab58cb495
refs/heads/master
2023-02-21T13:12:08.132000
2021-01-22T08:59:44
2021-01-22T08:59:44
331,853,744
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.bjpowernoed; public class test03 { public static void main(String[] args) { System.out.println("你是傻逼吗?"); } }
UTF-8
Java
151
java
test03.java
Java
[]
null
[]
package com.bjpowernoed; public class test03 { public static void main(String[] args) { System.out.println("你是傻逼吗?"); } }
151
0.640288
0.625899
7
18.857143
16.295736
44
false
false
0
0
0
0
0
0
0.285714
false
false
1
167bad701fbd43415fad13d5f11f3c687413c45c
3,083,786,533,546
b39ad1e8ba7e6b11faa654f4328af5b532b762d3
/outland-feature-server/src/main/java/outland/feature/server/tasks/DynamoCreateGroupsTableTask.java
88d3cb83ff7679fb38f5d74a8ba5793e34a19d04
[ "Apache-2.0" ]
permissive
retnuh/outland
https://github.com/retnuh/outland
2e0062a75c11eea731c6f9704e19097d041661bb
8f719248af7a7cda1012250892e2702991b8a369
refs/heads/master
2021-01-19T17:48:21.060000
2017-07-13T18:53:14
2017-07-13T19:03:26
88,342,042
0
0
null
true
2017-04-15T11:11:38
2017-04-15T11:11:38
2017-03-15T23:49:57
2017-04-14T23:46:48
828
0
0
0
null
null
null
package outland.feature.server.tasks; import com.amazonaws.services.dynamodbv2.AmazonDynamoDB; import com.amazonaws.services.dynamodbv2.model.AttributeDefinition; import com.amazonaws.services.dynamodbv2.model.CreateTableRequest; import com.amazonaws.services.dynamodbv2.model.DescribeTableRequest; import com.amazonaws.services.dynamodbv2.model.KeySchemaElement; import com.amazonaws.services.dynamodbv2.model.KeyType; import com.amazonaws.services.dynamodbv2.model.ProvisionedThroughput; import com.amazonaws.services.dynamodbv2.model.ScalarAttributeType; import com.amazonaws.services.dynamodbv2.model.TableDescription; import com.google.common.collect.ImmutableMultimap; import com.google.common.collect.Lists; import io.dropwizard.servlets.tasks.Task; import java.io.PrintWriter; import java.util.ArrayList; import javax.inject.Inject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import outland.feature.server.features.TableConfiguration; import outland.feature.server.groups.DefaultGroupStorage; public class DynamoCreateGroupsTableTask extends Task { public static final String HASH_KEY = DefaultGroupStorage.HASH_KEY; private static final Logger logger = LoggerFactory.getLogger(DynamoCreateGroupsTableTask.class); private final AmazonDynamoDB amazonDynamoDB; private final TableConfiguration tableConfiguration; @Inject public DynamoCreateGroupsTableTask( AmazonDynamoDB amazonDynamoDB, TableConfiguration tableConfiguration ) { super("DynamoCreateGroupsTableTask"); this.amazonDynamoDB = amazonDynamoDB; this.tableConfiguration = tableConfiguration; } @Override public void execute(ImmutableMultimap<String, String> parameters, PrintWriter output) throws Exception { createAppsTable(tableConfiguration.outlandGroupsTable); } private void createAppsTable(String tableName) { final AttributeDefinition appKey = new AttributeDefinition().withAttributeName(HASH_KEY).withAttributeType( ScalarAttributeType.S); final ArrayList<AttributeDefinition> tableAttributeDefinitions = Lists.newArrayList(appKey); final ArrayList<KeySchemaElement> tableKeySchema = Lists.newArrayList(); tableKeySchema.add( new KeySchemaElement().withAttributeName(HASH_KEY).withKeyType(KeyType.HASH)); final ProvisionedThroughput tableProvisionedThroughput = new ProvisionedThroughput() .withReadCapacityUnits(10L) .withWriteCapacityUnits(10L); final CreateTableRequest createTableRequest = new CreateTableRequest() .withTableName(tableName) .withKeySchema(tableKeySchema) .withAttributeDefinitions(tableAttributeDefinitions) .withProvisionedThroughput(tableProvisionedThroughput); final TableDescription tableDescription = amazonDynamoDB.createTable(createTableRequest).getTableDescription(); logger.info("created_table {}", tableDescription); final DescribeTableRequest describeTableRequest = new DescribeTableRequest().withTableName(tableName); final TableDescription description = amazonDynamoDB.describeTable(describeTableRequest).getTable(); logger.info("table_description: " + description); } }
UTF-8
Java
3,259
java
DynamoCreateGroupsTableTask.java
Java
[]
null
[]
package outland.feature.server.tasks; import com.amazonaws.services.dynamodbv2.AmazonDynamoDB; import com.amazonaws.services.dynamodbv2.model.AttributeDefinition; import com.amazonaws.services.dynamodbv2.model.CreateTableRequest; import com.amazonaws.services.dynamodbv2.model.DescribeTableRequest; import com.amazonaws.services.dynamodbv2.model.KeySchemaElement; import com.amazonaws.services.dynamodbv2.model.KeyType; import com.amazonaws.services.dynamodbv2.model.ProvisionedThroughput; import com.amazonaws.services.dynamodbv2.model.ScalarAttributeType; import com.amazonaws.services.dynamodbv2.model.TableDescription; import com.google.common.collect.ImmutableMultimap; import com.google.common.collect.Lists; import io.dropwizard.servlets.tasks.Task; import java.io.PrintWriter; import java.util.ArrayList; import javax.inject.Inject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import outland.feature.server.features.TableConfiguration; import outland.feature.server.groups.DefaultGroupStorage; public class DynamoCreateGroupsTableTask extends Task { public static final String HASH_KEY = DefaultGroupStorage.HASH_KEY; private static final Logger logger = LoggerFactory.getLogger(DynamoCreateGroupsTableTask.class); private final AmazonDynamoDB amazonDynamoDB; private final TableConfiguration tableConfiguration; @Inject public DynamoCreateGroupsTableTask( AmazonDynamoDB amazonDynamoDB, TableConfiguration tableConfiguration ) { super("DynamoCreateGroupsTableTask"); this.amazonDynamoDB = amazonDynamoDB; this.tableConfiguration = tableConfiguration; } @Override public void execute(ImmutableMultimap<String, String> parameters, PrintWriter output) throws Exception { createAppsTable(tableConfiguration.outlandGroupsTable); } private void createAppsTable(String tableName) { final AttributeDefinition appKey = new AttributeDefinition().withAttributeName(HASH_KEY).withAttributeType( ScalarAttributeType.S); final ArrayList<AttributeDefinition> tableAttributeDefinitions = Lists.newArrayList(appKey); final ArrayList<KeySchemaElement> tableKeySchema = Lists.newArrayList(); tableKeySchema.add( new KeySchemaElement().withAttributeName(HASH_KEY).withKeyType(KeyType.HASH)); final ProvisionedThroughput tableProvisionedThroughput = new ProvisionedThroughput() .withReadCapacityUnits(10L) .withWriteCapacityUnits(10L); final CreateTableRequest createTableRequest = new CreateTableRequest() .withTableName(tableName) .withKeySchema(tableKeySchema) .withAttributeDefinitions(tableAttributeDefinitions) .withProvisionedThroughput(tableProvisionedThroughput); final TableDescription tableDescription = amazonDynamoDB.createTable(createTableRequest).getTableDescription(); logger.info("created_table {}", tableDescription); final DescribeTableRequest describeTableRequest = new DescribeTableRequest().withTableName(tableName); final TableDescription description = amazonDynamoDB.describeTable(describeTableRequest).getTable(); logger.info("table_description: " + description); } }
3,259
0.789813
0.78521
82
38.743904
26.684156
98
false
false
0
0
0
0
0
0
0.52439
false
false
1
1a17a5cbf115287f5b1c9f33c688190b07d0daff
20,023,137,601,169
87795bc7ef697a810bf8155ba0f51fa26b00ca1d
/projects/previousProjects/eCarStreet/src/main/java/eCarStreet/ECarStreetTopology.java
0ac1aca6f33871b049dbbca92254f025bb103ec8
[ "Apache-2.0" ]
permissive
SES-fortiss/SmartGridCoSimulation
https://github.com/SES-fortiss/SmartGridCoSimulation
6885de28472faefe054a6f8956235c4952172104
909761bb54c332b77292af169137758683457b08
refs/heads/development
2023-07-02T02:00:02.241000
2022-01-27T10:35:39
2022-01-27T10:35:39
37,121,821
15
7
Apache-2.0
false
2023-06-13T22:57:35
2015-06-09T09:06:38
2023-02-10T16:06:11
2023-06-13T22:57:30
57,540
17
7
65
Java
false
false
/* * Copyright (c) 2011-2015, fortiss GmbH. * Licensed under the Apache License, Version 2.0. * * Use, modification and distribution are subject to the terms specified * in the accompanying license file LICENSE.txt located at the root directory * of this software distribution. */ package eCarStreet; import java.util.HashSet; import powerflowApi.PowerflowTopology; import topology.ActorTopology; import eCarStreet.eCar.helper.configurations.*; import eCarStreet.eCar.helper.decisions.*; public class ECarStreetTopology{ /** * ACHTUNG Simulations Name muss ohne Leerzeichen sein! (wg. AKKA) */ public static String simulationName = "ECAR-Simulation"; public static DecisionType modus = DecisionType.SIMPLE; public static int houseWithoutCars = 135; public static boolean coordinatorControl = false; public static ActorTopology createTopology() { ActorTopology top = new ActorTopology(simulationName); top.addActor("Coordinator", ECarStreetActorFactory.createCoordinator()); top.addActor("Market", ECarStreetActorFactory.createMarket()); //modus = DecisionType.TIMETRIGGERED; //modus = DecisionType.OPTIMAL; coordinatorControl = true; top.addActorAsChild("Coordinator/HouseA1", ECarStreetActorFactory.createHouse(4940 , new CarConfiguration1(), modus)); top.addActorAsChild("Coordinator/HouseB1", ECarStreetActorFactory.createHouse(4940 , new CarConfiguration2(), modus)); top.addActorAsChild("Coordinator/HouseC1", ECarStreetActorFactory.createHouse(4940 , new CarConfiguration3(), modus)); top.addActorAsChild("Coordinator/HouseD1", ECarStreetActorFactory.createHouse(4940 , new CarConfiguration4(), modus)); top.addActorAsChild("Coordinator/HouseE1", ECarStreetActorFactory.createHouse(4940 , new CarConfiguration5(), modus)); top.addActorAsChild("Coordinator/HouseA2", ECarStreetActorFactory.createHouse(4940 , new CarConfiguration1(), modus)); top.addActorAsChild("Coordinator/HouseB2", ECarStreetActorFactory.createHouse(4940 , new CarConfiguration2(), modus)); top.addActorAsChild("Coordinator/HouseC2", ECarStreetActorFactory.createHouse(4940 , new CarConfiguration3(), modus)); top.addActorAsChild("Coordinator/HouseD2", ECarStreetActorFactory.createHouse(4940 , new CarConfiguration4(), modus)); top.addActorAsChild("Coordinator/HouseE2", ECarStreetActorFactory.createHouse(4940 , new CarConfiguration5(), modus)); top.addActorAsChild("Coordinator/HouseA3", ECarStreetActorFactory.createHouse(4940 , new CarConfiguration1(), modus)); top.addActorAsChild("Coordinator/HouseB3", ECarStreetActorFactory.createHouse(4940 , new CarConfiguration2(), modus)); top.addActorAsChild("Coordinator/HouseC3", ECarStreetActorFactory.createHouse(4940 , new CarConfiguration3(), modus)); top.addActorAsChild("Coordinator/HouseD3", ECarStreetActorFactory.createHouse(4940 , new CarConfiguration4(), modus)); top.addActorAsChild("Coordinator/HouseE3", ECarStreetActorFactory.createHouse(4940 , new CarConfiguration5(), modus)); /* * Notizen zum Modell: * * 14,1% 4 Personen Haushalt mit 4940kwh --> also 7*3 Häuser * 13,4% 3 Personen Haushalt mit 4050kwh --> also 7*3 Häuser * 34,8% 2 Personen Haushalt mit 3440kwh --> also 17*3 Häuser * 37,8% 1 Personen Haushalt mit 2050kwh --> also 19*3 Häuser * */ String name = ""; double verbrauch = 0; int _1Person = 19*3; int _2Person = 17*3; int _3Person = 7*3; //int _4Person = 7*3; for (int i = 1; i <= houseWithoutCars; i++) { name = "Coordinator/h" + i; verbrauch = 2050; if (i > _1Person) verbrauch = 3440; if (i > _1Person + _2Person) verbrauch = 4050; if (i > _1Person + _2Person + _3Person) verbrauch = 4950; top.addActorAsChild(name, ECarStreetActorFactory.createHouse(verbrauch)); } //createPowerFlow(top); return top; } /** * @param top */ @SuppressWarnings("unused") private static void createPowerFlow(ActorTopology top) { HashSet<String> children = top.getActorOptions("Coordinator").childrenPathList; System.out.println(children.size()); PowerflowTopology model = new PowerflowTopology(); model.setStandardVoltage(1000); for (String childName : children) { model.addNodeBelow(childName); } model.autoMap(top); } }
UTF-8
Java
4,263
java
ECarStreetTopology.java
Java
[ { "context": "t i = 1; i <= houseWithoutCars; i++) {\n\t\t\tname = \"Coordinator/h\" + i;\n\t\t\tverbrauch = 2050;\n\t\t\tif (i > _1Person)", "end": 3520, "score": 0.7739053964614868, "start": 3509, "tag": "NAME", "value": "Coordinator" } ]
null
[]
/* * Copyright (c) 2011-2015, fortiss GmbH. * Licensed under the Apache License, Version 2.0. * * Use, modification and distribution are subject to the terms specified * in the accompanying license file LICENSE.txt located at the root directory * of this software distribution. */ package eCarStreet; import java.util.HashSet; import powerflowApi.PowerflowTopology; import topology.ActorTopology; import eCarStreet.eCar.helper.configurations.*; import eCarStreet.eCar.helper.decisions.*; public class ECarStreetTopology{ /** * ACHTUNG Simulations Name muss ohne Leerzeichen sein! (wg. AKKA) */ public static String simulationName = "ECAR-Simulation"; public static DecisionType modus = DecisionType.SIMPLE; public static int houseWithoutCars = 135; public static boolean coordinatorControl = false; public static ActorTopology createTopology() { ActorTopology top = new ActorTopology(simulationName); top.addActor("Coordinator", ECarStreetActorFactory.createCoordinator()); top.addActor("Market", ECarStreetActorFactory.createMarket()); //modus = DecisionType.TIMETRIGGERED; //modus = DecisionType.OPTIMAL; coordinatorControl = true; top.addActorAsChild("Coordinator/HouseA1", ECarStreetActorFactory.createHouse(4940 , new CarConfiguration1(), modus)); top.addActorAsChild("Coordinator/HouseB1", ECarStreetActorFactory.createHouse(4940 , new CarConfiguration2(), modus)); top.addActorAsChild("Coordinator/HouseC1", ECarStreetActorFactory.createHouse(4940 , new CarConfiguration3(), modus)); top.addActorAsChild("Coordinator/HouseD1", ECarStreetActorFactory.createHouse(4940 , new CarConfiguration4(), modus)); top.addActorAsChild("Coordinator/HouseE1", ECarStreetActorFactory.createHouse(4940 , new CarConfiguration5(), modus)); top.addActorAsChild("Coordinator/HouseA2", ECarStreetActorFactory.createHouse(4940 , new CarConfiguration1(), modus)); top.addActorAsChild("Coordinator/HouseB2", ECarStreetActorFactory.createHouse(4940 , new CarConfiguration2(), modus)); top.addActorAsChild("Coordinator/HouseC2", ECarStreetActorFactory.createHouse(4940 , new CarConfiguration3(), modus)); top.addActorAsChild("Coordinator/HouseD2", ECarStreetActorFactory.createHouse(4940 , new CarConfiguration4(), modus)); top.addActorAsChild("Coordinator/HouseE2", ECarStreetActorFactory.createHouse(4940 , new CarConfiguration5(), modus)); top.addActorAsChild("Coordinator/HouseA3", ECarStreetActorFactory.createHouse(4940 , new CarConfiguration1(), modus)); top.addActorAsChild("Coordinator/HouseB3", ECarStreetActorFactory.createHouse(4940 , new CarConfiguration2(), modus)); top.addActorAsChild("Coordinator/HouseC3", ECarStreetActorFactory.createHouse(4940 , new CarConfiguration3(), modus)); top.addActorAsChild("Coordinator/HouseD3", ECarStreetActorFactory.createHouse(4940 , new CarConfiguration4(), modus)); top.addActorAsChild("Coordinator/HouseE3", ECarStreetActorFactory.createHouse(4940 , new CarConfiguration5(), modus)); /* * Notizen zum Modell: * * 14,1% 4 Personen Haushalt mit 4940kwh --> also 7*3 Häuser * 13,4% 3 Personen Haushalt mit 4050kwh --> also 7*3 Häuser * 34,8% 2 Personen Haushalt mit 3440kwh --> also 17*3 Häuser * 37,8% 1 Personen Haushalt mit 2050kwh --> also 19*3 Häuser * */ String name = ""; double verbrauch = 0; int _1Person = 19*3; int _2Person = 17*3; int _3Person = 7*3; //int _4Person = 7*3; for (int i = 1; i <= houseWithoutCars; i++) { name = "Coordinator/h" + i; verbrauch = 2050; if (i > _1Person) verbrauch = 3440; if (i > _1Person + _2Person) verbrauch = 4050; if (i > _1Person + _2Person + _3Person) verbrauch = 4950; top.addActorAsChild(name, ECarStreetActorFactory.createHouse(verbrauch)); } //createPowerFlow(top); return top; } /** * @param top */ @SuppressWarnings("unused") private static void createPowerFlow(ActorTopology top) { HashSet<String> children = top.getActorOptions("Coordinator").childrenPathList; System.out.println(children.size()); PowerflowTopology model = new PowerflowTopology(); model.setStandardVoltage(1000); for (String childName : children) { model.addNodeBelow(childName); } model.autoMap(top); } }
4,263
0.748767
0.70486
103
40.349514
39.753784
120
false
false
0
0
0
0
0
0
2.543689
false
false
1
2ef2f7c6fc6187d8ea5b632be0a11107b2ae3260
26,121,991,151,805
cb88a02fa2ef4092a150b229b5b3779dc89b1586
/Android/MyApplication/weixinLoginView/src/main/java/com/hqf/weixinloginview/LoginView.java
421ed540988c08f37be62ed236df2ccf0a859985
[]
no_license
1765155167/C-Java-Python
https://github.com/1765155167/C-Java-Python
f083ed7de36936ff4b20ddcf865b593c353d3abd
aa31d765d3e895dc65bbb770a32c7bc07a64b4bd
refs/heads/master
2022-06-26T19:55:45.171000
2020-04-13T15:20:39
2020-04-13T15:20:39
205,353,222
0
0
null
false
2022-06-21T04:12:40
2019-08-30T09:45:46
2020-04-13T15:29:11
2022-06-21T04:12:40
1,128,600
0
0
1
Python
false
false
package com.hqf.weixinloginview; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import org.w3c.dom.Text; public class LoginView extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login_view); final Button login_button = (Button)findViewById(R.id.login_button); login_button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { EditText login_id = (EditText)findViewById(R.id.login_id); String id = login_id.getText().toString(); Toast.makeText(LoginView.this, id, Toast.LENGTH_SHORT).show(); } }); } }
UTF-8
Java
932
java
LoginView.java
Java
[]
null
[]
package com.hqf.weixinloginview; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import org.w3c.dom.Text; public class LoginView extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login_view); final Button login_button = (Button)findViewById(R.id.login_button); login_button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { EditText login_id = (EditText)findViewById(R.id.login_id); String id = login_id.getText().toString(); Toast.makeText(LoginView.this, id, Toast.LENGTH_SHORT).show(); } }); } }
932
0.678112
0.677039
29
31.137932
24.807846
78
false
false
0
0
0
0
0
0
0.586207
false
false
1
b36c27a53eea0fa77dc34042b39e35554f7d5f04
858,993,503,462
19ce14328948284f80d194dd13b9331fcc61da22
/src/main/java/com/xxg/jdk/executor/CallableAndFuture.java
7f8e5b05eb2beeb96dee96e35d96d236be306d89
[]
no_license
xiexingguang/JDK_XXG
https://github.com/xiexingguang/JDK_XXG
a8990902da6ac8121c63cf265926efb4f6b0d0e9
3155e2a2258b53401c216c767d284b5fb253d730
refs/heads/master
2016-09-11T02:23:04.649000
2015-10-21T02:06:56
2015-10-21T02:06:56
42,419,593
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * Project Name:JDK_XXG * File Name:CallableAndFuture.java * Package Name:com.xxg.jdk.executor * Date:2015年8月7日上午10:39:36 * Copyright (c) 2015, 深圳市六度人和 All Rights Reserved. * */ package com.xxg.jdk.executor; import java.util.Random; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; /** * ClassName:CallableAndFuture <br/> * Function: TODO ADD FUNCTION. <br/> * Reason: TODO ADD REASON. <br/> * Date: 2015年8月7日 上午10:39:36 <br/> * @author ecuser * @version * @since JDK 1.7 * @see */ public class CallableAndFuture { public static void main(String[] args) throws InterruptedException, ExecutionException { ExecutorService threadPool = Executors.newSingleThreadExecutor(); Future<Integer> future = threadPool.submit(new Callable<Integer>() { @Override public Integer call() throws Exception { Thread.sleep(10000); return new Random().nextInt(100); } }); if(future.isDone()) System.out.println(future.get()); System.out.println("not get the date"); } }
UTF-8
Java
1,223
java
CallableAndFuture.java
Java
[ { "context": " Date: 2015年8月7日 上午10:39:36 <br/>\n * @author ecuser\n * @version \n * @since JDK 1.7\n * @see \t \n */", "end": 624, "score": 0.9996685981750488, "start": 618, "tag": "USERNAME", "value": "ecuser" } ]
null
[]
/** * Project Name:JDK_XXG * File Name:CallableAndFuture.java * Package Name:com.xxg.jdk.executor * Date:2015年8月7日上午10:39:36 * Copyright (c) 2015, 深圳市六度人和 All Rights Reserved. * */ package com.xxg.jdk.executor; import java.util.Random; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; /** * ClassName:CallableAndFuture <br/> * Function: TODO ADD FUNCTION. <br/> * Reason: TODO ADD REASON. <br/> * Date: 2015年8月7日 上午10:39:36 <br/> * @author ecuser * @version * @since JDK 1.7 * @see */ public class CallableAndFuture { public static void main(String[] args) throws InterruptedException, ExecutionException { ExecutorService threadPool = Executors.newSingleThreadExecutor(); Future<Integer> future = threadPool.submit(new Callable<Integer>() { @Override public Integer call() throws Exception { Thread.sleep(10000); return new Random().nextInt(100); } }); if(future.isDone()) System.out.println(future.get()); System.out.println("not get the date"); } }
1,223
0.708999
0.67704
46
24.826086
20.979601
89
false
false
0
0
0
0
0
0
1.086957
false
false
1
d818b859df269d10814d0fcb18dba66b96249bf6
20,306,605,441,476
165723ae1a81719f4de9a7b2f839256897818bd7
/src/main/java/de/sebastianhesse/pbf/routing/BaseDijkstra.java
a142f0a01197918174bb126164cf78f38043cc10
[ "MIT" ]
permissive
seeebiii/osm-routing-examples
https://github.com/seeebiii/osm-routing-examples
bcdff3641856d425839cded60b03d9da773ac1f7
631729019c72f35393520506020ce0edb3e7f6a9
refs/heads/master
2021-05-03T21:54:42.106000
2017-03-31T07:49:02
2017-03-31T07:49:02
71,562,909
4
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package de.sebastianhesse.pbf.routing; import de.sebastianhesse.pbf.reader.Accessor; import de.sebastianhesse.pbf.routing.accessors.CarAccessor; import de.sebastianhesse.pbf.routing.accessors.PedestrianAccessor; import de.sebastianhesse.pbf.routing.accessors.WayAccessor; import de.sebastianhesse.pbf.routing.calculators.FastestPathCalculator; import de.sebastianhesse.pbf.routing.calculators.PathCalculator; import de.sebastianhesse.pbf.routing.calculators.ShortestPathCalculator; import de.sebastianhesse.pbf.storage.Graph; import de.sebastianhesse.pbf.storage.Node; import gnu.trove.map.TIntDoubleMap; import gnu.trove.map.TIntIntMap; import gnu.trove.map.hash.TIntDoubleHashMap; import gnu.trove.map.hash.TIntIntHashMap; /** * */ public abstract class BaseDijkstra extends Thread { protected Graph graph; protected Node source; protected Node[] nodes; protected DijkstraOptions options = DijkstraOptions.shortestWithCar(); protected PathCalculator pathCalculator; // store costs protected TIntDoubleMap weights; // store nodes of shortest path protected TIntIntMap predecessors; public BaseDijkstra(Graph graph, Node source, DijkstraOptions options) { this.graph = graph; this.source = source; this.nodes = this.graph.getNodes(); this.weights = new TIntDoubleHashMap(this.nodes.length / 2); this.predecessors = new TIntIntHashMap(this.nodes.length / 2); this.options = options; this.pathCalculator = getPathCalculator(); } protected Node getPredecessor(Node routeNode) { return graph.getNodes()[predecessors.get((int) routeNode.getId())]; } protected boolean isPredecessor(Node routeNode) { return predecessors.containsKey((int) routeNode.getId()) && predecessors.get((int) routeNode.getId()) != -1; } private PathCalculator getPathCalculator() { WayAccessor accessor; if (options.getAccessor().equals(Accessor.CAR)) { accessor = new CarAccessor(); } else { accessor = new PedestrianAccessor(); } switch (options.getCalculationType()) { case FASTEST: return new FastestPathCalculator(this.weights, accessor); case SHORTEST: return new ShortestPathCalculator(this.weights, accessor); default: throw new IllegalStateException("Dijkstra options have a mismatching state: neither fastest nor shortest type was selected."); } } }
UTF-8
Java
2,541
java
BaseDijkstra.java
Java
[]
null
[]
package de.sebastianhesse.pbf.routing; import de.sebastianhesse.pbf.reader.Accessor; import de.sebastianhesse.pbf.routing.accessors.CarAccessor; import de.sebastianhesse.pbf.routing.accessors.PedestrianAccessor; import de.sebastianhesse.pbf.routing.accessors.WayAccessor; import de.sebastianhesse.pbf.routing.calculators.FastestPathCalculator; import de.sebastianhesse.pbf.routing.calculators.PathCalculator; import de.sebastianhesse.pbf.routing.calculators.ShortestPathCalculator; import de.sebastianhesse.pbf.storage.Graph; import de.sebastianhesse.pbf.storage.Node; import gnu.trove.map.TIntDoubleMap; import gnu.trove.map.TIntIntMap; import gnu.trove.map.hash.TIntDoubleHashMap; import gnu.trove.map.hash.TIntIntHashMap; /** * */ public abstract class BaseDijkstra extends Thread { protected Graph graph; protected Node source; protected Node[] nodes; protected DijkstraOptions options = DijkstraOptions.shortestWithCar(); protected PathCalculator pathCalculator; // store costs protected TIntDoubleMap weights; // store nodes of shortest path protected TIntIntMap predecessors; public BaseDijkstra(Graph graph, Node source, DijkstraOptions options) { this.graph = graph; this.source = source; this.nodes = this.graph.getNodes(); this.weights = new TIntDoubleHashMap(this.nodes.length / 2); this.predecessors = new TIntIntHashMap(this.nodes.length / 2); this.options = options; this.pathCalculator = getPathCalculator(); } protected Node getPredecessor(Node routeNode) { return graph.getNodes()[predecessors.get((int) routeNode.getId())]; } protected boolean isPredecessor(Node routeNode) { return predecessors.containsKey((int) routeNode.getId()) && predecessors.get((int) routeNode.getId()) != -1; } private PathCalculator getPathCalculator() { WayAccessor accessor; if (options.getAccessor().equals(Accessor.CAR)) { accessor = new CarAccessor(); } else { accessor = new PedestrianAccessor(); } switch (options.getCalculationType()) { case FASTEST: return new FastestPathCalculator(this.weights, accessor); case SHORTEST: return new ShortestPathCalculator(this.weights, accessor); default: throw new IllegalStateException("Dijkstra options have a mismatching state: neither fastest nor shortest type was selected."); } } }
2,541
0.711137
0.709957
73
33.80822
29.609632
142
false
false
0
0
0
0
0
0
0.547945
false
false
1
ea65498b32ba120f7b77742349ca0a7bcbb3929d
8,117,488,229,094
1575b765686e727377617ba4223091a732f6092a
/basic Security/csrf/src/main/java/com/sripiranavan/spring/security/basic/csrf/security/CustomCsrfTokenRepository.java
dd9ed925c7a991982afd988ce845530c18bc1e54
[]
no_license
sripiranavan8/Spring-Security-with-OAuth2
https://github.com/sripiranavan8/Spring-Security-with-OAuth2
bab3ca20a6a856113b345f91795875c9ed4af4b8
bf96b9892ed45819a6f11c878a440cfd583ba63f
refs/heads/main
2023-04-02T11:25:50.831000
2021-12-22T16:39:46
2021-12-22T16:39:46
347,045,601
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.sripiranavan.spring.security.basic.csrf.security; import org.springframework.security.web.csrf.CsrfToken; import org.springframework.security.web.csrf.CsrfTokenRepository; import org.springframework.security.web.csrf.DefaultCsrfToken; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class CustomCsrfTokenRepository implements CsrfTokenRepository { @Override public CsrfToken generateToken(HttpServletRequest httpServletRequest) { CsrfToken t = new DefaultCsrfToken("X-CSRF-TOKEN","_csrf","123456789"); return t; } @Override public void saveToken(CsrfToken csrfToken, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) { } @Override public CsrfToken loadToken(HttpServletRequest httpServletRequest) { return null; } }
UTF-8
Java
876
java
CustomCsrfTokenRepository.java
Java
[ { "context": " t = new DefaultCsrfToken(\"X-CSRF-TOKEN\",\"_csrf\",\"123456789\");\n return t;\n }\n\n @Override\n pub", "end": 581, "score": 0.9801142811775208, "start": 572, "tag": "PASSWORD", "value": "123456789" } ]
null
[]
package com.sripiranavan.spring.security.basic.csrf.security; import org.springframework.security.web.csrf.CsrfToken; import org.springframework.security.web.csrf.CsrfTokenRepository; import org.springframework.security.web.csrf.DefaultCsrfToken; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class CustomCsrfTokenRepository implements CsrfTokenRepository { @Override public CsrfToken generateToken(HttpServletRequest httpServletRequest) { CsrfToken t = new DefaultCsrfToken("X-CSRF-TOKEN","_csrf","<PASSWORD>"); return t; } @Override public void saveToken(CsrfToken csrfToken, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) { } @Override public CsrfToken loadToken(HttpServletRequest httpServletRequest) { return null; } }
877
0.785388
0.775114
26
32.692307
34.402336
128
false
false
0
0
0
0
0
0
0.5
false
false
1
61ff9c15170f2d49307256fd75ffe3c83fae69a3
33,045,478,444,069
9d50c30f24781cbab1952c93286cacb917f0df43
/src/main/java/jpabook/jpashop/repository/OrderSearch.java
acdd89f62299367fb892682da1bd071164219fcf
[]
no_license
Fly-Eugene/JPA_uses2
https://github.com/Fly-Eugene/JPA_uses2
b3665543470fbcc8a0b14707dd3e64903d45d4ed
e997d0075d7df6d04815aeae8e81a463f62f261e
refs/heads/master
2023-07-30T03:39:46.285000
2021-09-21T19:09:17
2021-09-21T19:09:17
407,947,545
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package jpabook.jpashop.repository; import jpabook.jpashop.domain.OrderStatus; import lombok.Getter; import lombok.Setter; @Getter @Setter public class OrderSearch { private String memberName; private OrderStatus orderStatus; // 주문 상태[ORDER, CANCEL]\ public OrderSearch() { } public OrderSearch(String memberName, OrderStatus orderStatus) { this.memberName = memberName; this.orderStatus = orderStatus; } }
UTF-8
Java
460
java
OrderSearch.java
Java
[]
null
[]
package jpabook.jpashop.repository; import jpabook.jpashop.domain.OrderStatus; import lombok.Getter; import lombok.Setter; @Getter @Setter public class OrderSearch { private String memberName; private OrderStatus orderStatus; // 주문 상태[ORDER, CANCEL]\ public OrderSearch() { } public OrderSearch(String memberName, OrderStatus orderStatus) { this.memberName = memberName; this.orderStatus = orderStatus; } }
460
0.723451
0.723451
21
20.523809
20.308617
68
false
false
0
0
0
0
0
0
0.47619
false
false
1
e74278862f194e712161f70c7ab48f7a96dfaa4a
35,493,609,776,586
a3b54a8e0048cb0b50e38c954e74d6d9d66eb2fd
/src/test/java/as/leap/rpc/example/spi/SampleFutureSPI.java
892f454a04472124eb0d2f67ad861c2eb7c11f45
[]
no_license
chenyanjin/vertx-rpc
https://github.com/chenyanjin/vertx-rpc
c847ca4d28e02561838620bc0f13b2fb9118e358
380aeca7c92f8278182ed5c39747421e19c9cc9a
refs/heads/master
2021-01-19T13:44:03.895000
2017-01-06T06:42:00
2017-01-06T06:42:00
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package as.leap.rpc.example.spi; import io.vertx.core.Future; import java.util.List; import java.util.Map; /** * Created by stream. */ public interface SampleFutureSPI { //complex object Future<Department> getDepartment(User user); //primitive Future<Integer> getDepartment(int userId, Integer anotherId); //array Future<byte[]> getBytes(byte[] args); //Collection Future<List<Department>> getDepartList(List<User> users); //HashMap Future<Map<String, Department>> getDepartMap(Map<String, User> userMap); //enum Future<Weeks> getDayOfWeek(Weeks day); //exception and non-argument Future<User> someException(); //both arg and the result is null; Future<User> nullInvoke(User user); }
UTF-8
Java
730
java
SampleFutureSPI.java
Java
[ { "context": "til.List;\nimport java.util.Map;\n\n/**\n * Created by stream.\n */\npublic interface SampleFutureSPI {\n\n //comp", "end": 134, "score": 0.7910347580909729, "start": 128, "tag": "USERNAME", "value": "stream" } ]
null
[]
package as.leap.rpc.example.spi; import io.vertx.core.Future; import java.util.List; import java.util.Map; /** * Created by stream. */ public interface SampleFutureSPI { //complex object Future<Department> getDepartment(User user); //primitive Future<Integer> getDepartment(int userId, Integer anotherId); //array Future<byte[]> getBytes(byte[] args); //Collection Future<List<Department>> getDepartList(List<User> users); //HashMap Future<Map<String, Department>> getDepartMap(Map<String, User> userMap); //enum Future<Weeks> getDayOfWeek(Weeks day); //exception and non-argument Future<User> someException(); //both arg and the result is null; Future<User> nullInvoke(User user); }
730
0.717808
0.717808
37
18.729731
20.143604
74
false
false
0
0
0
0
0
0
0.432432
false
false
1
24475bac8f7434cb431707b65fada38390c7982a
36,979,668,444,164
f36c09b6299eda58d1465bb5aacf1a12edc35407
/app/src/main/java/com/qs/qswlw/bean/UserIDSearchBean.java
9a12ce3f50bac9da7d4a38eda652e10def4aa23e
[]
no_license
xiaoyuanxiao/QSWLW
https://github.com/xiaoyuanxiao/QSWLW
6cd8e51fe9aed50490ac9f7d1d5e73cbd8d8c42e
7534e54e90611d13913729960e5754e36310869c
refs/heads/master
2021-01-18T15:52:39.402000
2017-12-28T09:33:39
2017-12-28T09:33:39
86,685,025
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.qs.qswlw.bean; /** * Created by xiaoyu on 2017/12/22. */ public class UserIDSearchBean { /** * data : 998 */ private String data; public String getData() { return data; } public void setData(String data) { this.data = data; } }
UTF-8
Java
299
java
UserIDSearchBean.java
Java
[ { "context": "package com.qs.qswlw.bean;\n\n/**\n * Created by xiaoyu on 2017/12/22.\n */\n\npublic class UserIDSearchBean", "end": 52, "score": 0.9991404414176941, "start": 46, "tag": "USERNAME", "value": "xiaoyu" } ]
null
[]
package com.qs.qswlw.bean; /** * Created by xiaoyu on 2017/12/22. */ public class UserIDSearchBean { /** * data : 998 */ private String data; public String getData() { return data; } public void setData(String data) { this.data = data; } }
299
0.551839
0.51505
23
12
13.008359
38
false
false
0
0
0
0
0
0
0.173913
false
false
1
fe53513cc547123393b309710efa5f133382ef00
35,253,091,605,658
b97db9a877ffc0f1ca0ae73d7d311b588b83478b
/QualSerie/app/src/main/java/aula/com/qualserie/MainActivity.java
ce8ebd9b06a50f9cbbf7a9704b168b9f750c7c01
[]
no_license
renanidc/android_portifolio
https://github.com/renanidc/android_portifolio
ff494e64a24e57f34de1980b41e4456195cd43f7
43b2a92300ff5c32d2a5aaf410344f577ae2ce2c
refs/heads/master
2021-01-24T17:03:17.711000
2018-02-28T03:19:03
2018-02-28T03:19:03
123,223,523
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package aula.com.qualserie; import android.content.Intent; import android.media.MediaPlayer; import android.support.v4.content.ContextCompat; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.ImageView; import android.widget.SeekBar; import android.widget.Switch; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends AppCompatActivity { private SeekBar seekbar; private ImageView imagemResposta; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); seekbar = (SeekBar) findViewById(R.id.seekBarId); imagemResposta = (ImageView) findViewById(R.id.imageViewId); seekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { if(progress==0){ imagemResposta.setImageResource(R.drawable.pouco); } if(progress==1){ imagemResposta.setImageResource(R.drawable.medio); } if(progress==2){ imagemResposta.setImageResource(R.drawable.medio); } if(progress==3){ imagemResposta.setImageResource(R.drawable.muito); } if(progress==4){ startActivity(new Intent(MainActivity.this,AchouActivity.class)); } } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } }); } }
UTF-8
Java
1,854
java
MainActivity.java
Java
[]
null
[]
package aula.com.qualserie; import android.content.Intent; import android.media.MediaPlayer; import android.support.v4.content.ContextCompat; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.ImageView; import android.widget.SeekBar; import android.widget.Switch; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends AppCompatActivity { private SeekBar seekbar; private ImageView imagemResposta; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); seekbar = (SeekBar) findViewById(R.id.seekBarId); imagemResposta = (ImageView) findViewById(R.id.imageViewId); seekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { if(progress==0){ imagemResposta.setImageResource(R.drawable.pouco); } if(progress==1){ imagemResposta.setImageResource(R.drawable.medio); } if(progress==2){ imagemResposta.setImageResource(R.drawable.medio); } if(progress==3){ imagemResposta.setImageResource(R.drawable.muito); } if(progress==4){ startActivity(new Intent(MainActivity.this,AchouActivity.class)); } } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } }); } }
1,854
0.618123
0.614347
63
28.428572
25.232704
92
false
false
0
0
0
0
0
0
0.412698
false
false
1
50f113556e5eb3f22a87a8325aca5980a8488874
38,585,986,211,069
9f30fbae8035c2fc1cb681855db1bc32964ffbd4
/Java/yuexiaopeng/jnshuTask/task9/tuscanyDemo/src/main/java/tuscanyTest/StartService3.java
87293f83082a9eaf0cdc1d1c571f3917e21ab2bd
[]
no_license
IT-xzy/Task
https://github.com/IT-xzy/Task
f2d309cbea962bec628df7be967ac335fd358b15
4f72d55b8c9247064b7c15db172fd68415492c48
refs/heads/master
2022-12-23T04:53:59.410000
2019-06-20T21:14:15
2019-06-20T21:14:15
126,955,174
18
395
null
false
2022-12-16T12:17:21
2018-03-27T08:34:32
2022-12-09T22:30:57
2022-12-16T12:17:20
1,957,915
8
84
11,015
null
false
false
package tuscanyTest; import org.apache.tuscany.sca.Node; import org.apache.tuscany.sca.TuscanyRuntime; import org.oasisopen.sca.NoSuchServiceException; public class StartService3 { public static void main(String[] args) throws NoSuchServiceException { Node node = TuscanyRuntime.runComposite("Calculator.composite", "target/classes"); // try { System.out.println("service启动"); } }
UTF-8
Java
429
java
StartService3.java
Java
[]
null
[]
package tuscanyTest; import org.apache.tuscany.sca.Node; import org.apache.tuscany.sca.TuscanyRuntime; import org.oasisopen.sca.NoSuchServiceException; public class StartService3 { public static void main(String[] args) throws NoSuchServiceException { Node node = TuscanyRuntime.runComposite("Calculator.composite", "target/classes"); // try { System.out.println("service启动"); } }
429
0.717647
0.715294
13
30.846153
27.450224
90
false
false
0
0
0
0
0
0
0.538462
false
false
1
659dacc68e5a3247132985c4ce9895f47bc83f4c
3,796,751,137,578
f754cb550ac67ea0eb009708bb03f7445b0d4318
/src/test/java/Pages/TarifaPage.java
f6e40cc127a67ff33f30987d49e7a3dbedee817a
[]
no_license
helderfpaula/PassagemGOL
https://github.com/helderfpaula/PassagemGOL
ba4fcd83b9c5f55ac4ef04eaa465711e5bd48d72
ecb31f35c2042aa3a1f43b3df8e9604c12446d9d
refs/heads/master
2021-05-08T11:08:03.115000
2018-07-31T21:15:52
2018-07-31T21:15:52
119,881,190
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package Pages; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; public class TarifaPage { private WebDriver navegador; public TarifaPage(WebDriver navegador) { this.navegador = navegador; } public TarifaPage EscolherTarifaIda() { navegador.findElement(By.xpath("//*[@id=\"ida\"]/div[2]/div[5]/table[1]/tbody/tr/td[2]")).click(); return this; } public TarifaPage EscolherTarifaRetorno() { navegador.findElement(By.xpath("//*[@id=\"volta\"]/div[2]/div[5]/table[1]/tbody/tr/td[2]")).click(); return this; } public TarifaPage AceitarTermos() { navegador.findElement(By.id("agree")).click(); return this; } public PageLogin Continuar() { navegador.findElement(By.id("ControlGroupSelect2View_AvailabilityInputSelect2View_ButtonSubmit")).click(); return new PageLogin(navegador); } }
UTF-8
Java
923
java
TarifaPage.java
Java
[]
null
[]
package Pages; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; public class TarifaPage { private WebDriver navegador; public TarifaPage(WebDriver navegador) { this.navegador = navegador; } public TarifaPage EscolherTarifaIda() { navegador.findElement(By.xpath("//*[@id=\"ida\"]/div[2]/div[5]/table[1]/tbody/tr/td[2]")).click(); return this; } public TarifaPage EscolherTarifaRetorno() { navegador.findElement(By.xpath("//*[@id=\"volta\"]/div[2]/div[5]/table[1]/tbody/tr/td[2]")).click(); return this; } public TarifaPage AceitarTermos() { navegador.findElement(By.id("agree")).click(); return this; } public PageLogin Continuar() { navegador.findElement(By.id("ControlGroupSelect2View_AvailabilityInputSelect2View_ButtonSubmit")).click(); return new PageLogin(navegador); } }
923
0.651138
0.640303
35
25.371429
30.807314
114
false
false
0
0
0
0
0
0
0.371429
false
false
1
16a10a55f005471076c8bd4ea459f6d19f371cb3
5,274,219,873,340
62abf13797a8fc990347d9fd4376c933853430dc
/src/main/java/com/shanzha/moduls/sys/service/UserFollowService.java
6afd71a32641636de6a10c7d7048a8e4584f1987
[]
no_license
jiajia-Hu/graduation-peoject
https://github.com/jiajia-Hu/graduation-peoject
5491725c6b7b1220c86215a6af8071cc82c1c3f9
19f22a90238313eb04c621d0d673155674d23e80
refs/heads/master
2021-01-19T13:44:01.386000
2017-08-20T12:22:36
2017-08-20T12:22:36
100,859,489
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.shanzha.moduls.sys.service; import java.util.Date; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.shanzha.moduls.sys.entity.UserFollow; import com.shanzha.moduls.sys.entity.UserFollowExample; import com.shanzha.moduls.sys.mapper.UserFollowMapper; import com.shanzha.moduls.sys.utils.UserUtils; @Service public class UserFollowService { @Autowired UserFollowMapper userFollowMapper; public List<UserFollow> selectByExample(UserFollowExample example) { return userFollowMapper.selectByExample(example); } public int insert(UserFollow record) { record.setFollowDate(new Date()); record.setUserId(UserUtils.getCurrentUserId()); return userFollowMapper.insert(record); } }
UTF-8
Java
800
java
UserFollowService.java
Java
[]
null
[]
package com.shanzha.moduls.sys.service; import java.util.Date; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.shanzha.moduls.sys.entity.UserFollow; import com.shanzha.moduls.sys.entity.UserFollowExample; import com.shanzha.moduls.sys.mapper.UserFollowMapper; import com.shanzha.moduls.sys.utils.UserUtils; @Service public class UserFollowService { @Autowired UserFollowMapper userFollowMapper; public List<UserFollow> selectByExample(UserFollowExample example) { return userFollowMapper.selectByExample(example); } public int insert(UserFollow record) { record.setFollowDate(new Date()); record.setUserId(UserUtils.getCurrentUserId()); return userFollowMapper.insert(record); } }
800
0.8125
0.8125
30
25.666666
22.862391
69
false
false
0
0
0
0
0
0
0.966667
false
false
1
a7e70826b37eacda179692ac016c282c3fc1828f
12,541,304,574,416
f064e06445cad9ebd61d17737e4ddae67259d7a4
/goldeasy-user-service/src/main/java/com/goldeasy/user/service/impl/UserInvoiceInfoServiceImpl.java
562a3341cd0a4bc5d43ebd0fd76996d6e3368eea
[]
no_license
t629715/goldeasy-user-service
https://github.com/t629715/goldeasy-user-service
3e69bf55d9c80702ab81951c569a8ad6028bc67a
f5274f6f680176e6c13b22b731665338311c19ce
refs/heads/master
2020-04-03T14:10:31.885000
2018-11-20T06:30:08
2018-11-20T06:30:08
155,313,456
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.goldeasy.user.service.impl; import com.alibaba.dubbo.config.annotation.Service; import com.goldeasy.common.exception.UserModuleException; import com.goldeasy.user.entity.UserInvoiceInfo; import com.goldeasy.user.mapper.UserInvoiceInfoMapper; import com.goldeasy.user.mapper.UserMessageMapper; import com.goldeasy.user.service.UserInvoiceInfoService; import com.goldeasy.user.service.UserMessageService; import com.goldeasy.user.service.UserService; import com.goldeasy.user.vo.UserInvoiceInfoVO; import com.goldeasy.user.vo.UserMessageInfoVO; import com.goldeasy.user.vo.UserMessageVO; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; import javax.annotation.Resource; import javax.xml.crypto.Data; import java.util.Date; import java.util.List; /** * @author:tianliya * @CreateTime:2018-10-15 16:50 * @Description:用户业务实现类 **/ @Component @Service(interfaceClass = UserService.class, version = "${dubbo.service.version}") public class UserInvoiceInfoServiceImpl implements UserInvoiceInfoService { private final Logger logger = LoggerFactory.getLogger(UserInvoiceInfoServiceImpl.class); @Resource private UserInvoiceInfoMapper userInvoiceInfoMapper; @Override @Transactional(rollbackFor = Exception.class) public Boolean addUserInvoice(UserInvoiceInfo userInvoiceInfo, Long userId) { this.logger.info("添加用户发票信息-业务层"); try{ userInvoiceInfo.setGmtCreate(new Date()); userInvoiceInfo.setUserId(userId); int flag = this.userInvoiceInfoMapper.insertSelective(userInvoiceInfo); if (flag > 0){ return true; }else { return false; } }catch (Exception e){ this.logger.error("添加用户发票信息异常-业务层,添加信息:{}",userInvoiceInfo.toString()); e.printStackTrace(); throw new UserModuleException("添加用户发票信息异常",e.getCause()); } } @Override @Transactional(rollbackFor = Exception.class) public Boolean modifyUserInvoice(UserInvoiceInfo userInvoiceInfo) { this.logger.info("修改用户发票信息-业务层"); try{ userInvoiceInfo.setGmtModified(new Date()); int flag =this.userInvoiceInfoMapper.updateByPrimaryKeySelective(userInvoiceInfo); if (flag > 0){ return true; }else { return false; } }catch (Exception e){ this.logger.error("修改用户发票信息异常-业务层,添加信息:{}",userInvoiceInfo.toString()); e.printStackTrace(); throw new UserModuleException("修改用户发票信息异常",e.getCause()); } } @Override public UserInvoiceInfoVO selectUserInvoiceInfo(Long userId) { this.logger.info("获取用户发票信息-业务层"); try{ List<UserInvoiceInfoVO> userInvoiceInfos = this.userInvoiceInfoMapper.listUserInvoiceInfo(userId); if (userInvoiceInfos != null && userInvoiceInfos.size() != 0){ return userInvoiceInfos.get(0); } return null; }catch (Exception e){ this.logger.error("获取用户发票信息异常-业务层}"); e.printStackTrace(); throw new UserModuleException("获取用户发票信息异常",e.getCause()); } } @Override public List<UserInvoiceInfoVO> listUserInvoiceInfo(Long userId) { this.logger.info("获取用户所有发票信息-业务层"); try{ }catch (Exception e){ this.logger.error("获取用户所有发票信息异常-业务层,添加信息:{}"); e.printStackTrace(); throw new UserModuleException("获取用户所有发票信息异常",e.getCause()); } return null; } }
UTF-8
Java
4,057
java
UserInvoiceInfoServiceImpl.java
Java
[ { "context": "util.Date;\nimport java.util.List;\n\n/**\n * @author:tianliya\n * @CreateTime:2018-10-15 16:50\n * @Description:用", "end": 905, "score": 0.9996020197868347, "start": 897, "tag": "USERNAME", "value": "tianliya" } ]
null
[]
package com.goldeasy.user.service.impl; import com.alibaba.dubbo.config.annotation.Service; import com.goldeasy.common.exception.UserModuleException; import com.goldeasy.user.entity.UserInvoiceInfo; import com.goldeasy.user.mapper.UserInvoiceInfoMapper; import com.goldeasy.user.mapper.UserMessageMapper; import com.goldeasy.user.service.UserInvoiceInfoService; import com.goldeasy.user.service.UserMessageService; import com.goldeasy.user.service.UserService; import com.goldeasy.user.vo.UserInvoiceInfoVO; import com.goldeasy.user.vo.UserMessageInfoVO; import com.goldeasy.user.vo.UserMessageVO; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; import javax.annotation.Resource; import javax.xml.crypto.Data; import java.util.Date; import java.util.List; /** * @author:tianliya * @CreateTime:2018-10-15 16:50 * @Description:用户业务实现类 **/ @Component @Service(interfaceClass = UserService.class, version = "${dubbo.service.version}") public class UserInvoiceInfoServiceImpl implements UserInvoiceInfoService { private final Logger logger = LoggerFactory.getLogger(UserInvoiceInfoServiceImpl.class); @Resource private UserInvoiceInfoMapper userInvoiceInfoMapper; @Override @Transactional(rollbackFor = Exception.class) public Boolean addUserInvoice(UserInvoiceInfo userInvoiceInfo, Long userId) { this.logger.info("添加用户发票信息-业务层"); try{ userInvoiceInfo.setGmtCreate(new Date()); userInvoiceInfo.setUserId(userId); int flag = this.userInvoiceInfoMapper.insertSelective(userInvoiceInfo); if (flag > 0){ return true; }else { return false; } }catch (Exception e){ this.logger.error("添加用户发票信息异常-业务层,添加信息:{}",userInvoiceInfo.toString()); e.printStackTrace(); throw new UserModuleException("添加用户发票信息异常",e.getCause()); } } @Override @Transactional(rollbackFor = Exception.class) public Boolean modifyUserInvoice(UserInvoiceInfo userInvoiceInfo) { this.logger.info("修改用户发票信息-业务层"); try{ userInvoiceInfo.setGmtModified(new Date()); int flag =this.userInvoiceInfoMapper.updateByPrimaryKeySelective(userInvoiceInfo); if (flag > 0){ return true; }else { return false; } }catch (Exception e){ this.logger.error("修改用户发票信息异常-业务层,添加信息:{}",userInvoiceInfo.toString()); e.printStackTrace(); throw new UserModuleException("修改用户发票信息异常",e.getCause()); } } @Override public UserInvoiceInfoVO selectUserInvoiceInfo(Long userId) { this.logger.info("获取用户发票信息-业务层"); try{ List<UserInvoiceInfoVO> userInvoiceInfos = this.userInvoiceInfoMapper.listUserInvoiceInfo(userId); if (userInvoiceInfos != null && userInvoiceInfos.size() != 0){ return userInvoiceInfos.get(0); } return null; }catch (Exception e){ this.logger.error("获取用户发票信息异常-业务层}"); e.printStackTrace(); throw new UserModuleException("获取用户发票信息异常",e.getCause()); } } @Override public List<UserInvoiceInfoVO> listUserInvoiceInfo(Long userId) { this.logger.info("获取用户所有发票信息-业务层"); try{ }catch (Exception e){ this.logger.error("获取用户所有发票信息异常-业务层,添加信息:{}"); e.printStackTrace(); throw new UserModuleException("获取用户所有发票信息异常",e.getCause()); } return null; } }
4,057
0.670427
0.665592
104
34.798077
26.071049
110
false
false
0
0
0
0
0
0
0.567308
false
false
1
bd43d7f9e00c7194979225aa18f8c90179dfe689
26,319,559,632,287
79e9d250d428f733f04293e8a512ec04dc68195b
/app/src/main/java/com/hyrc/lrs/xunsi/receiver/SealNotificationReceiver.java
d84e393afa44faba8270d8225753e7ea9bf0e113
[]
no_license
lurongshuang/LRS_IM
https://github.com/lurongshuang/LRS_IM
97dc0d62ea37239f381a8a0eb57058dbfc92b576
66ba9b150576c62f38de4db92fa37af2a6409a63
refs/heads/master
2021-05-24T18:48:25.327000
2020-04-07T07:46:57
2020-04-07T07:46:57
253,704,879
3
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.hyrc.lrs.xunsi.receiver; import android.content.Context; import io.rong.push.PushType; import io.rong.push.notification.PushMessageReceiver; import io.rong.push.notification.PushNotificationMessage; /** * @description 作用: * @date: 2020/3/27 * @author: 卢融霜 */ public class SealNotificationReceiver extends PushMessageReceiver { @Override public boolean onNotificationMessageArrived(Context context, PushType pushType, PushNotificationMessage pushNotificationMessage) { return false; // 返回 false, 会弹出融云 SDK 默认通知; 返回 true, 融云 SDK 不会弹通知, 通知需要由您自定义。 } @Override public boolean onNotificationMessageClicked(Context context, PushType pushType, PushNotificationMessage pushNotificationMessage) { return false; // 返回 false, 会走融云 SDK 默认处理逻辑, 即点击该通知会打开会话列表或会话界面; 返回 true, 则由您自定义处理逻辑。 } }
UTF-8
Java
1,035
java
SealNotificationReceiver.java
Java
[ { "context": "description 作用:\r\n * @date: 2020/3/27\r\n * @author: 卢融霜\r\n */\r\npublic class SealNotificationReceiver exten", "end": 284, "score": 0.9995655417442322, "start": 281, "tag": "NAME", "value": "卢融霜" } ]
null
[]
package com.hyrc.lrs.xunsi.receiver; import android.content.Context; import io.rong.push.PushType; import io.rong.push.notification.PushMessageReceiver; import io.rong.push.notification.PushNotificationMessage; /** * @description 作用: * @date: 2020/3/27 * @author: 卢融霜 */ public class SealNotificationReceiver extends PushMessageReceiver { @Override public boolean onNotificationMessageArrived(Context context, PushType pushType, PushNotificationMessage pushNotificationMessage) { return false; // 返回 false, 会弹出融云 SDK 默认通知; 返回 true, 融云 SDK 不会弹通知, 通知需要由您自定义。 } @Override public boolean onNotificationMessageClicked(Context context, PushType pushType, PushNotificationMessage pushNotificationMessage) { return false; // 返回 false, 会走融云 SDK 默认处理逻辑, 即点击该通知会打开会话列表或会话界面; 返回 true, 则由您自定义处理逻辑。 } }
1,035
0.731513
0.723549
26
31.807692
37.453579
134
false
false
0
0
0
0
0
0
0.730769
false
false
1
9f898c4da27bc303a67d99d9fa3bb05e02ff6b5f
6,167,573,082,610
031a05381d8bcbff196cd7c8edeb2a099d76a4f3
/src/models/PedidoProduto.java
30ebc796a5078db0aa5d639f6517523a37cc9281
[]
no_license
olivmarcos/projeto-vendas
https://github.com/olivmarcos/projeto-vendas
1bedcf2982f4f1e12a445ecade46d22557e95d95
1d894ab99196f4384f9a420dfa6f5ad33c459ef6
refs/heads/master
2022-04-14T20:18:39.843000
2020-04-12T17:40:52
2020-04-12T17:40:52
254,146,543
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package models; public class PedidoProduto { private int pedp_codigo; private int pedp_quantidade; private Double pedp_valor; private Double pedp_valor_total; private int pedp_cod_produto; private int pedp_cod_pedido; public int getPedp_codigo() { return this.pedp_codigo; } public void setPedp_codigo(int pedp_codigo) { this.pedp_codigo = pedp_codigo; } public int getPedp_quantidade() { return this.pedp_quantidade; } public void setPedp_quantidade(int pedp_quantidade) { this.pedp_quantidade = pedp_quantidade; } public Double getPedp_valor() { return this.pedp_valor; } public void setPedp_valor(Double pedp_valor) { this.pedp_valor = pedp_valor; } public Double getPedp_valor_total() { return this.pedp_valor_total; } public void setPedp_valor_total(Double pedp_valor_total) { this.pedp_valor_total = pedp_valor_total; } public int getPedp_cod_produto() { return this.pedp_cod_produto; } public void setPedp_cod_produto(int pedp_cod_produto) { this.pedp_cod_produto = pedp_cod_produto; } public int getPedp_cod_pedido() { return this.pedp_cod_pedido; } public void setPedp_cod_pedido(int pedp_cod_pedido) { this.pedp_cod_pedido = pedp_cod_pedido; } @Override public String toString() { return "{" + " pedp_codigo='" + getPedp_codigo() + "'" + ", pedp_quantidade='" + getPedp_quantidade() + "'" + ", pedp_valor='" + getPedp_valor() + "'" + ", pedp_valor_total='" + getPedp_valor_total() + "'" + ", pedp_cod_produto='" + getPedp_cod_produto() + "'" + ", pedp_cod_pedido='" + getPedp_cod_pedido() + "'" + "}"; } public String[] toVetor() { String vetor[] = new String[6]; vetor[0] = String.valueOf(getPedp_codigo()); vetor[1] = String.valueOf(getPedp_quantidade()); vetor[2] = String.valueOf(getPedp_valor()); vetor[3] = String.valueOf(getPedp_valor_total()); vetor[4] = String.valueOf(getPedp_cod_produto()); vetor[5] = String.valueOf(getPedp_cod_pedido()); return vetor; } public void vetorTo(String[] dados) { this.setPedp_codigo(Integer.parseInt(dados[0])); this.setPedp_quantidade(Integer.parseInt(dados[1])); this.setPedp_valor(Double.parseDouble(dados[2])); this.setPedp_valor_total(Double.parseDouble(dados[3])); this.setPedp_cod_produto(Integer.parseInt(dados[4])); this.setPedp_cod_pedido(Integer.parseInt(dados[5])); } }
UTF-8
Java
2,790
java
PedidoProduto.java
Java
[]
null
[]
package models; public class PedidoProduto { private int pedp_codigo; private int pedp_quantidade; private Double pedp_valor; private Double pedp_valor_total; private int pedp_cod_produto; private int pedp_cod_pedido; public int getPedp_codigo() { return this.pedp_codigo; } public void setPedp_codigo(int pedp_codigo) { this.pedp_codigo = pedp_codigo; } public int getPedp_quantidade() { return this.pedp_quantidade; } public void setPedp_quantidade(int pedp_quantidade) { this.pedp_quantidade = pedp_quantidade; } public Double getPedp_valor() { return this.pedp_valor; } public void setPedp_valor(Double pedp_valor) { this.pedp_valor = pedp_valor; } public Double getPedp_valor_total() { return this.pedp_valor_total; } public void setPedp_valor_total(Double pedp_valor_total) { this.pedp_valor_total = pedp_valor_total; } public int getPedp_cod_produto() { return this.pedp_cod_produto; } public void setPedp_cod_produto(int pedp_cod_produto) { this.pedp_cod_produto = pedp_cod_produto; } public int getPedp_cod_pedido() { return this.pedp_cod_pedido; } public void setPedp_cod_pedido(int pedp_cod_pedido) { this.pedp_cod_pedido = pedp_cod_pedido; } @Override public String toString() { return "{" + " pedp_codigo='" + getPedp_codigo() + "'" + ", pedp_quantidade='" + getPedp_quantidade() + "'" + ", pedp_valor='" + getPedp_valor() + "'" + ", pedp_valor_total='" + getPedp_valor_total() + "'" + ", pedp_cod_produto='" + getPedp_cod_produto() + "'" + ", pedp_cod_pedido='" + getPedp_cod_pedido() + "'" + "}"; } public String[] toVetor() { String vetor[] = new String[6]; vetor[0] = String.valueOf(getPedp_codigo()); vetor[1] = String.valueOf(getPedp_quantidade()); vetor[2] = String.valueOf(getPedp_valor()); vetor[3] = String.valueOf(getPedp_valor_total()); vetor[4] = String.valueOf(getPedp_cod_produto()); vetor[5] = String.valueOf(getPedp_cod_pedido()); return vetor; } public void vetorTo(String[] dados) { this.setPedp_codigo(Integer.parseInt(dados[0])); this.setPedp_quantidade(Integer.parseInt(dados[1])); this.setPedp_valor(Double.parseDouble(dados[2])); this.setPedp_valor_total(Double.parseDouble(dados[3])); this.setPedp_cod_produto(Integer.parseInt(dados[4])); this.setPedp_cod_pedido(Integer.parseInt(dados[5])); } }
2,790
0.579211
0.574552
92
28.347826
22.94153
66
false
false
0
0
0
0
0
0
0.423913
false
false
1
217a3d9466cd2b3785ff0830caf5c2981f30a678
1,099,511,681,509
0872b601284f65364241a9a5be0b72495cd2ab6b
/pidevSafa/src/com/mycompany/gui/ListParentForm.java
d5b61d45be45ccb325b63bd22249465afacab06a
[]
no_license
safaaa1/SprintMobile
https://github.com/safaaa1/SprintMobile
a05a1bbbf22e17955911028fb909a09b354638a0
c70ca4caa28b5ee2e5426d5f1d6e09c505a78ec7
refs/heads/master
2022-08-30T02:16:23.452000
2020-05-21T00:36:16
2020-05-21T00:36:16
259,757,899
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.mycompany.gui; import com.codename1.ui.Container; import com.codename1.ui.Form; import com.codename1.ui.layouts.BoxLayout; import com.mycompany.entites.Parent; import com.mycompany.services.ServiceParent; /** * * @author safa */ public class ListParentForm extends Form{ Form current; Form f; public ListParentForm() { current = this; f = new Form(); Container liste = new Container(BoxLayout.y()); for (Parent parentt : ServiceParent.getInstance().getAllParents()) { CelluleParent celluleProduit = new CelluleParent(parentt); liste.add(celluleProduit); } add(liste); } ListParentForm(Form current) { } public Form getCurrent() { return current; } public void setCurrent(Form current) { this.current = current; } public Form getF() { return f; } public void setF(Form f) { this.f = f; } }
UTF-8
Java
1,176
java
ListParentForm.java
Java
[ { "context": "company.services.ServiceParent;\n\n/**\n *\n * @author safa\n */\npublic class ListParentForm extends Form{\n ", "end": 426, "score": 0.9966363906860352, "start": 422, "tag": "USERNAME", "value": "safa" } ]
null
[]
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.mycompany.gui; import com.codename1.ui.Container; import com.codename1.ui.Form; import com.codename1.ui.layouts.BoxLayout; import com.mycompany.entites.Parent; import com.mycompany.services.ServiceParent; /** * * @author safa */ public class ListParentForm extends Form{ Form current; Form f; public ListParentForm() { current = this; f = new Form(); Container liste = new Container(BoxLayout.y()); for (Parent parentt : ServiceParent.getInstance().getAllParents()) { CelluleParent celluleProduit = new CelluleParent(parentt); liste.add(celluleProduit); } add(liste); } ListParentForm(Form current) { } public Form getCurrent() { return current; } public void setCurrent(Form current) { this.current = current; } public Form getF() { return f; } public void setF(Form f) { this.f = f; } }
1,176
0.630102
0.627551
54
20.777779
20.589161
79
false
false
0
0
0
0
0
0
0.388889
false
false
1
e8bb026baea86ebec974c17e7777066712a5f04c
17,695,265,300,011
7022f7fdf258cc91143366b6b19c0958982722e3
/src/com/sucho/fun/RandomNumberGenerator.java
487285abf8b2a58ed1ba07c6d74620cc6fe69383
[]
no_license
irapohlf/Fun
https://github.com/irapohlf/Fun
d83828f62d7ac9f7f5f1c95286e701e8da4c334b
bef6005292535fb2f454e2f91089b49060797147
refs/heads/master
2021-01-23T12:47:26.538000
2018-10-28T21:55:06
2018-10-28T21:55:06
93,200,483
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.sucho.fun; import java.util.Scanner; /** * @author sucho * @since 7/17/17. */ public class RandomNumberGenerator { private static void print(int nominator, int denominator) { // BigInteger nom = BigInteger.valueOf(nominator); // BigInteger den = BigInteger.valueOf(denominator); // BigInteger gcd = nom.gcd(den); // System.out.println(nom.divide(gcd).intValue() + "/" + den.divide(gcd).intValue()); int gcd = gcd(nominator, denominator); System.out.println(nominator/gcd + "/" + denominator/gcd); } private static int gcd(int a, int b) { if (a > b) { int tmp = a; a = b; b = tmp; } int remainder = b % a; if (remainder == 0) { return a; } return gcd(a, remainder); } private static void prob(int A, int B, int C) { if (C >= A + B) { System.out.println("1/1"); return; } if (A > B) { int tmp = A; A = B; B = tmp; } int nomi = 0; int deno = 0; if (C <= A) { nomi = C * C; deno = 2 * A * B; } else if (C <= B) { nomi = (C + C - A) * A; deno = 2 * A * B; } else if (C <= A + B) { nomi = 2*C*(A+B)-A*A-B*B-C*C; deno = 2 * A * B; } print(nomi, deno); } public static void main(String[] args) { Scanner sc = new Scanner(System.in); int N = sc.nextInt(); for (int n = 0; n < N; n++) { int A = sc.nextInt(); int B = sc.nextInt(); int C = sc.nextInt(); prob(A, B, C); } sc.close(); } }
UTF-8
Java
1,782
java
RandomNumberGenerator.java
Java
[ { "context": "ho.fun;\n\nimport java.util.Scanner;\n\n/**\n * @author sucho\n * @since 7/17/17.\n */\npublic class RandomNumberG", "end": 71, "score": 0.9995896816253662, "start": 66, "tag": "USERNAME", "value": "sucho" } ]
null
[]
package com.sucho.fun; import java.util.Scanner; /** * @author sucho * @since 7/17/17. */ public class RandomNumberGenerator { private static void print(int nominator, int denominator) { // BigInteger nom = BigInteger.valueOf(nominator); // BigInteger den = BigInteger.valueOf(denominator); // BigInteger gcd = nom.gcd(den); // System.out.println(nom.divide(gcd).intValue() + "/" + den.divide(gcd).intValue()); int gcd = gcd(nominator, denominator); System.out.println(nominator/gcd + "/" + denominator/gcd); } private static int gcd(int a, int b) { if (a > b) { int tmp = a; a = b; b = tmp; } int remainder = b % a; if (remainder == 0) { return a; } return gcd(a, remainder); } private static void prob(int A, int B, int C) { if (C >= A + B) { System.out.println("1/1"); return; } if (A > B) { int tmp = A; A = B; B = tmp; } int nomi = 0; int deno = 0; if (C <= A) { nomi = C * C; deno = 2 * A * B; } else if (C <= B) { nomi = (C + C - A) * A; deno = 2 * A * B; } else if (C <= A + B) { nomi = 2*C*(A+B)-A*A-B*B-C*C; deno = 2 * A * B; } print(nomi, deno); } public static void main(String[] args) { Scanner sc = new Scanner(System.in); int N = sc.nextInt(); for (int n = 0; n < N; n++) { int A = sc.nextInt(); int B = sc.nextInt(); int C = sc.nextInt(); prob(A, B, C); } sc.close(); } }
1,782
0.436027
0.427609
74
23.081081
18.422781
92
false
false
0
0
0
0
0
0
0.621622
false
false
1
8c45b2f32085af5fc1714378cacce54e2bf114c5
28,965,259,458,888
f155614e535853f031b3add7fc571ce3cde57a14
/src/main/java/com/jjsd/options/controller/UsersController.java
9a4a841dd26f92f8fabcb14167baec8a50185668
[]
no_license
NJUjjsd/options-web
https://github.com/NJUjjsd/options-web
640ffdab657b6345653eb5a15c55bdd51843ba6d
f72625628f4e2c8452d9281678f57085010f987f
refs/heads/master
2021-01-01T17:55:05.797000
2017-09-22T05:58:02
2017-09-22T05:58:02
98,199,227
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.jjsd.options.controller; import com.jjsd.options.entity.user.Cost; import com.jjsd.options.entity.user.Property; import com.jjsd.options.entity.user.User; import com.jjsd.options.entity.vo.Account; import com.jjsd.options.entity.vo.Password; import com.jjsd.options.entity.vo.UserInfo; import com.jjsd.options.service.UserService; import com.jjsd.options.util.AesEncryptUtil; import com.jjsd.options.util.EmailUtil; import com.jjsd.options.util.JSONResult; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import javax.mail.MessagingException; import java.io.IOException; import java.security.NoSuchAlgorithmException; /** * Created by john on 2017/9/10. */ @Controller @RequestMapping(value="/api/users", produces = "application/json;charset=UTF-8") public class UsersController { @Autowired private UserService userService; private static final String register = "http://localhost: 8000/users/register"; @RequestMapping(value = "/getUserInfo", method = RequestMethod.POST) public @ResponseBody String getUserInfo(@RequestBody Account account){ String email = account.getEmail(); try{ email = AesEncryptUtil.desEncrypt(email); }catch (Exception e){ e.printStackTrace(); } System.out.println(email); User user = userService.loadUserByEmail(email); UserInfo userInfo = new UserInfo(email, user.getUserName(),user.isSetCost(),user.isSetProperty()); if(user.isSetCost()){ Cost cost = userService.loadCostByEmail(email); userInfo.setCost(cost); } if(user.isSetProperty()){ Property property = userService.loadPropertyByEmail(email); userInfo.setProperty(property); } // 0全都填写,1未写 int status = 0; String message = ""; if(!(user.isSetProperty()&&user.isSetCost())){ status = 1; message = "请将交易成本和目前持有补充完整,否则您将无法投资"; } return JSONResult.fillResultString(status,message,userInfo); } @RequestMapping(value = "/modifyUserInfo", method = RequestMethod.POST) public @ResponseBody String modifyUserInfo(@RequestBody UserInfo userInfo){ System.out.println(userInfo.getEmail()); String email = userInfo.getEmail(); try{ email = AesEncryptUtil.desEncrypt(email); }catch (Exception e){ e.printStackTrace(); } System.out.println(email); Cost cost = new Cost(); cost.setEmail(email); cost.setC1(userInfo.getBuyPut()); cost.setC2(userInfo.getBuySubscribe()); cost.setC3(userInfo.getBuyETF()); cost.setC4(userInfo.getSellPut()); cost.setC5(userInfo.getSellSubscribe()); cost.setC6(userInfo.getSellETF()); boolean flagCost = userService.fillInCost(cost); System.out.println(userInfo.getRiskRate()+" "+userInfo.getCapital()); boolean flagPro = userService.fillInProperty(email,userInfo.getRiskRate(),userInfo.getCapital()); System.out.println(flagCost); System.out.println(flagPro); int status = 0; String message = "信息修改成功"; if(!(flagCost&&flagPro)){ status = 1; message = "woops ~~>,<~~ 修改信息失败"; } return JSONResult.fillResultString(status,message,flagCost&&flagPro); } @RequestMapping(value = "/changePassword",method = RequestMethod.POST) public @ResponseBody String changePassword(@RequestBody Password password){ String email = password.getEmail(); String prePassword = password.getPrePassword(); String newPassword = password.getNewPassword(); try{ email = AesEncryptUtil.desEncrypt(email); prePassword = AesEncryptUtil.desEncrypt(prePassword); newPassword = AesEncryptUtil.desEncrypt(newPassword); }catch (Exception e){ e.printStackTrace(); } System.out.println(email+" "+prePassword+" "+newPassword); boolean result = userService.modify(email,prePassword,newPassword); int status = result?0:1; String message = result?"密码修改成功":"woops ~~>,<~~ 密码修改失败"; System.out.println(message); return JSONResult.fillResultString(status,message,result); } @RequestMapping(value = "/signUp", method = RequestMethod.POST) public @ResponseBody String signUp(@RequestBody Account account){ System.out.println(account); String email = account.getEmail(); String password = account.getPassword(); String userName = account.getUserName(); try{ email = AesEncryptUtil.desEncrypt(email); password = AesEncryptUtil.desEncrypt(password); userName = AesEncryptUtil.desEncrypt(userName); }catch (Exception e){ e.printStackTrace(); } System.out.println(email+" "+password+" "+userName+" "); boolean result = false; try { result = userService.signUp(email,userName,password); }catch (MessagingException e){ e.printStackTrace(); return JSONResult.fillResultString(1,"激活链接发送失败,请稍后再试",result); } System.out.println("注册结果"+result); if (result){ return JSONResult.fillResultString(0,"激活链接已成功发送到您的邮箱,请在24小时内激活您的账号",result); } else { return JSONResult.fillResultString(1,"woops ~~>,<~~ 该账号已被注册",result); } } @RequestMapping(value = "/login", method = RequestMethod.POST) public @ResponseBody String login(@RequestBody Account account){ String email = account.getEmail(); String password = account.getPassword(); try{ email = AesEncryptUtil.desEncrypt(email); password = AesEncryptUtil.desEncrypt(password); }catch (Exception e){ e.printStackTrace(); } System.out.println(email+" "+password+" "); boolean result = userService.login(email,password); if (result){ return JSONResult.fillResultString(0,"登录成功",result); } else { return JSONResult.fillResultString(1,"用户名或密码错误",result); } } @RequestMapping(value = "/activatemail", method = RequestMethod.GET) public @ResponseBody String activatemail(String token,String email) throws IOException, MessagingException, NoSuchAlgorithmException { //获取激活参数 // String email = account.getEmail(); // String token = account.getToken(); System.out.println("========================"); System.out.println(email+" "+token); Long time = System.currentTimeMillis(); User u = userService.loadUserByEmail(email); if (u != null) { if (!u.isStatus() && u.getActivateTime() != 1) { if (u.getActivateTime() < time) { //过期--激活失败 u.setActivateTime(Long.parseLong("-1")); //重新发送激活邮件 u = EmailUtil.activateMail(u); //重新设置了有效时间和token激活码 userService.update(u); return "woops ~~>,<~~ 激活链接已过期"; // return JSONResult.fillResultString(3,"woops ~~>,<~~ 激活链接已过期",false); } else if (u.getActivateTime()>time){ //在时间内 u.setActivateTime(Long.parseLong("1")); if (u.getToken().equals(token)) { //在时间内且激活码通过,激活成功 u.setStatus(true); //重新设置token防止被禁用的用户利用激活 u.setToken(token.replace("1", "c")); userService.update(u); return "恭喜您成功激活账号"; // return JSONResult.fillResultString(0,"恭喜您成功激活账号",true); } else { System.out.println("++++++++++++++++++++++++++"); System.out.println(u.getToken()); return "woops ~~>,<~~ 激活码验证不通过"; // return JSONResult.fillResultString(1,"woops ~~>,<~~ 激活码验证不通过",false); } } } } else if (u == null) { return "woops ~~>,<~~ 无此用户"; // return JSONResult.fillResultString(2,"woops ~~>,<~~ 无此用户",false); } return "恭喜您成功激活账号"; // return JSONResult.fillResultString(0,"恭喜您成功激活账号","恭喜您成功激活账号"); } }
UTF-8
Java
9,340
java
UsersController.java
Java
[ { "context": "urity.NoSuchAlgorithmException;\n\n/**\n * Created by john on 2017/9/10.\n */\n@Controller\n@RequestMapping(val", "end": 966, "score": 0.9848712682723999, "start": 962, "tag": "USERNAME", "value": "john" }, { "context": "tUtil.desEncrypt(email);\n prePassword = AesEncryptUtil.desEncrypt(prePassword);\n n", "end": 4098, "score": 0.9425274133682251, "start": 4095, "tag": "PASSWORD", "value": "Aes" }, { "context": "ryptUtil.desEncrypt(email);\n password = AesEncryptUtil.desEncrypt(password);\n userName = AesEncryptUtil.", "end": 5058, "score": 0.986286461353302, "start": 5033, "tag": "PASSWORD", "value": "AesEncryptUtil.desEncrypt" }, { "context": "unt.getEmail();\n String password = account.getPassword();\n try{\n email = AesEncryptUti", "end": 6028, "score": 0.6410337090492249, "start": 6017, "tag": "PASSWORD", "value": "getPassword" } ]
null
[]
package com.jjsd.options.controller; import com.jjsd.options.entity.user.Cost; import com.jjsd.options.entity.user.Property; import com.jjsd.options.entity.user.User; import com.jjsd.options.entity.vo.Account; import com.jjsd.options.entity.vo.Password; import com.jjsd.options.entity.vo.UserInfo; import com.jjsd.options.service.UserService; import com.jjsd.options.util.AesEncryptUtil; import com.jjsd.options.util.EmailUtil; import com.jjsd.options.util.JSONResult; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import javax.mail.MessagingException; import java.io.IOException; import java.security.NoSuchAlgorithmException; /** * Created by john on 2017/9/10. */ @Controller @RequestMapping(value="/api/users", produces = "application/json;charset=UTF-8") public class UsersController { @Autowired private UserService userService; private static final String register = "http://localhost: 8000/users/register"; @RequestMapping(value = "/getUserInfo", method = RequestMethod.POST) public @ResponseBody String getUserInfo(@RequestBody Account account){ String email = account.getEmail(); try{ email = AesEncryptUtil.desEncrypt(email); }catch (Exception e){ e.printStackTrace(); } System.out.println(email); User user = userService.loadUserByEmail(email); UserInfo userInfo = new UserInfo(email, user.getUserName(),user.isSetCost(),user.isSetProperty()); if(user.isSetCost()){ Cost cost = userService.loadCostByEmail(email); userInfo.setCost(cost); } if(user.isSetProperty()){ Property property = userService.loadPropertyByEmail(email); userInfo.setProperty(property); } // 0全都填写,1未写 int status = 0; String message = ""; if(!(user.isSetProperty()&&user.isSetCost())){ status = 1; message = "请将交易成本和目前持有补充完整,否则您将无法投资"; } return JSONResult.fillResultString(status,message,userInfo); } @RequestMapping(value = "/modifyUserInfo", method = RequestMethod.POST) public @ResponseBody String modifyUserInfo(@RequestBody UserInfo userInfo){ System.out.println(userInfo.getEmail()); String email = userInfo.getEmail(); try{ email = AesEncryptUtil.desEncrypt(email); }catch (Exception e){ e.printStackTrace(); } System.out.println(email); Cost cost = new Cost(); cost.setEmail(email); cost.setC1(userInfo.getBuyPut()); cost.setC2(userInfo.getBuySubscribe()); cost.setC3(userInfo.getBuyETF()); cost.setC4(userInfo.getSellPut()); cost.setC5(userInfo.getSellSubscribe()); cost.setC6(userInfo.getSellETF()); boolean flagCost = userService.fillInCost(cost); System.out.println(userInfo.getRiskRate()+" "+userInfo.getCapital()); boolean flagPro = userService.fillInProperty(email,userInfo.getRiskRate(),userInfo.getCapital()); System.out.println(flagCost); System.out.println(flagPro); int status = 0; String message = "信息修改成功"; if(!(flagCost&&flagPro)){ status = 1; message = "woops ~~>,<~~ 修改信息失败"; } return JSONResult.fillResultString(status,message,flagCost&&flagPro); } @RequestMapping(value = "/changePassword",method = RequestMethod.POST) public @ResponseBody String changePassword(@RequestBody Password password){ String email = password.getEmail(); String prePassword = password.getPrePassword(); String newPassword = password.getNewPassword(); try{ email = AesEncryptUtil.desEncrypt(email); prePassword = AesEncryptUtil.desEncrypt(prePassword); newPassword = AesEncryptUtil.desEncrypt(newPassword); }catch (Exception e){ e.printStackTrace(); } System.out.println(email+" "+prePassword+" "+newPassword); boolean result = userService.modify(email,prePassword,newPassword); int status = result?0:1; String message = result?"密码修改成功":"woops ~~>,<~~ 密码修改失败"; System.out.println(message); return JSONResult.fillResultString(status,message,result); } @RequestMapping(value = "/signUp", method = RequestMethod.POST) public @ResponseBody String signUp(@RequestBody Account account){ System.out.println(account); String email = account.getEmail(); String password = account.getPassword(); String userName = account.getUserName(); try{ email = AesEncryptUtil.desEncrypt(email); password = <PASSWORD>(password); userName = AesEncryptUtil.desEncrypt(userName); }catch (Exception e){ e.printStackTrace(); } System.out.println(email+" "+password+" "+userName+" "); boolean result = false; try { result = userService.signUp(email,userName,password); }catch (MessagingException e){ e.printStackTrace(); return JSONResult.fillResultString(1,"激活链接发送失败,请稍后再试",result); } System.out.println("注册结果"+result); if (result){ return JSONResult.fillResultString(0,"激活链接已成功发送到您的邮箱,请在24小时内激活您的账号",result); } else { return JSONResult.fillResultString(1,"woops ~~>,<~~ 该账号已被注册",result); } } @RequestMapping(value = "/login", method = RequestMethod.POST) public @ResponseBody String login(@RequestBody Account account){ String email = account.getEmail(); String password = account.<PASSWORD>(); try{ email = AesEncryptUtil.desEncrypt(email); password = AesEncryptUtil.desEncrypt(password); }catch (Exception e){ e.printStackTrace(); } System.out.println(email+" "+password+" "); boolean result = userService.login(email,password); if (result){ return JSONResult.fillResultString(0,"登录成功",result); } else { return JSONResult.fillResultString(1,"用户名或密码错误",result); } } @RequestMapping(value = "/activatemail", method = RequestMethod.GET) public @ResponseBody String activatemail(String token,String email) throws IOException, MessagingException, NoSuchAlgorithmException { //获取激活参数 // String email = account.getEmail(); // String token = account.getToken(); System.out.println("========================"); System.out.println(email+" "+token); Long time = System.currentTimeMillis(); User u = userService.loadUserByEmail(email); if (u != null) { if (!u.isStatus() && u.getActivateTime() != 1) { if (u.getActivateTime() < time) { //过期--激活失败 u.setActivateTime(Long.parseLong("-1")); //重新发送激活邮件 u = EmailUtil.activateMail(u); //重新设置了有效时间和token激活码 userService.update(u); return "woops ~~>,<~~ 激活链接已过期"; // return JSONResult.fillResultString(3,"woops ~~>,<~~ 激活链接已过期",false); } else if (u.getActivateTime()>time){ //在时间内 u.setActivateTime(Long.parseLong("1")); if (u.getToken().equals(token)) { //在时间内且激活码通过,激活成功 u.setStatus(true); //重新设置token防止被禁用的用户利用激活 u.setToken(token.replace("1", "c")); userService.update(u); return "恭喜您成功激活账号"; // return JSONResult.fillResultString(0,"恭喜您成功激活账号",true); } else { System.out.println("++++++++++++++++++++++++++"); System.out.println(u.getToken()); return "woops ~~>,<~~ 激活码验证不通过"; // return JSONResult.fillResultString(1,"woops ~~>,<~~ 激活码验证不通过",false); } } } } else if (u == null) { return "woops ~~>,<~~ 无此用户"; // return JSONResult.fillResultString(2,"woops ~~>,<~~ 无此用户",false); } return "恭喜您成功激活账号"; // return JSONResult.fillResultString(0,"恭喜您成功激活账号","恭喜您成功激活账号"); } }
9,324
0.60509
0.600318
215
39.939533
25.040453
138
false
false
0
0
0
0
0
0
0.837209
false
false
1
0034d82df0d0776e4d6a01b709dc59bb31d86866
29,901,562,329,476
2808d4af07ac7608534cc576f1c11efa1bd9c03c
/app/src/main/java/com/hawk/util/PreferenceUtil.java
7c5fbc714280397c016312df2e704bc4079102ea
[]
no_license
BlackYHawk/Hawk
https://github.com/BlackYHawk/Hawk
13407fa56874769d1750745162304022b15dcb82
438f8d67938c5025de29e6acf6c781df66eaf7c8
refs/heads/master
2021-01-17T13:13:55.889000
2016-06-20T16:43:26
2016-06-20T16:43:28
40,252,414
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.hawk.util; import android.content.Context; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; public class PreferenceUtil { private static final String PREFERENCE_NAME = "hawk"; //首选项名 private static final String SUDOKU_ON = "sudoku_on"; private static final String SUDOKU_PASSWD = "activity_sudoku"; public static boolean get_sudoku_on(Context context) { if(context == null){ return false; } SharedPreferences pref = context.getSharedPreferences(PREFERENCE_NAME, 0); if(pref == null) return false; return pref.getBoolean(SUDOKU_ON, false); } public static boolean set_sudoku_on(Context context, boolean on) { if(context == null){ return false; } SharedPreferences pref = context.getSharedPreferences(PREFERENCE_NAME, 0); Editor editor = pref.edit(); if(editor == null) return false; editor.putBoolean(SUDOKU_ON, on); return editor.commit(); } public static String get_sudoku_passwd(Context context) { if(context == null){ return null; } SharedPreferences pref = context.getSharedPreferences(PREFERENCE_NAME, 0); if(pref == null) return null; return pref.getString(SUDOKU_PASSWD, null); } public static boolean set_sudoku_passwd(Context context, String passwd) { if(context == null){ return false; } SharedPreferences pref = context.getSharedPreferences(PREFERENCE_NAME, 0); Editor editor = pref.edit(); if(editor == null) return false; editor.putString(SUDOKU_PASSWD, passwd); return editor.commit(); } }
UTF-8
Java
1,595
java
PreferenceUtil.java
Java
[ { "context": "n\";\n\tprivate static final String SUDOKU_PASSWD = \"activity_sudoku\";\n\n\tpublic static boolean get_sudoku_on(Context c", "end": 362, "score": 0.9993594884872437, "start": 347, "tag": "PASSWORD", "value": "activity_sudoku" } ]
null
[]
package com.hawk.util; import android.content.Context; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; public class PreferenceUtil { private static final String PREFERENCE_NAME = "hawk"; //首选项名 private static final String SUDOKU_ON = "sudoku_on"; private static final String SUDOKU_PASSWD = "<PASSWORD>"; public static boolean get_sudoku_on(Context context) { if(context == null){ return false; } SharedPreferences pref = context.getSharedPreferences(PREFERENCE_NAME, 0); if(pref == null) return false; return pref.getBoolean(SUDOKU_ON, false); } public static boolean set_sudoku_on(Context context, boolean on) { if(context == null){ return false; } SharedPreferences pref = context.getSharedPreferences(PREFERENCE_NAME, 0); Editor editor = pref.edit(); if(editor == null) return false; editor.putBoolean(SUDOKU_ON, on); return editor.commit(); } public static String get_sudoku_passwd(Context context) { if(context == null){ return null; } SharedPreferences pref = context.getSharedPreferences(PREFERENCE_NAME, 0); if(pref == null) return null; return pref.getString(SUDOKU_PASSWD, null); } public static boolean set_sudoku_passwd(Context context, String passwd) { if(context == null){ return false; } SharedPreferences pref = context.getSharedPreferences(PREFERENCE_NAME, 0); Editor editor = pref.edit(); if(editor == null) return false; editor.putString(SUDOKU_PASSWD, passwd); return editor.commit(); } }
1,590
0.710145
0.707624
69
22
23.423016
76
false
false
0
0
0
0
0
0
2.101449
false
false
1
5fb317d6693dcc6a7af43f51115db9222bebf8e6
20,512,763,849,196
b2efee20516a3e58e083a7376b78b8a46ce302c1
/app/src/main/java/com/jaekapps/expensetracker/model/BEIAmount.java
60ab496577eb12ceab048cd9ba698daa42c37221
[]
no_license
expensetracker015/expense_tracker
https://github.com/expensetracker015/expense_tracker
0bfb78f9d9a08f51ab1544429c94656b27c57650
b0a73bf556b43f250a380ca932a03f4e6188f2b7
refs/heads/master
2023-04-16T21:10:59.808000
2021-04-27T09:09:10
2021-04-27T09:09:10
354,219,847
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.jaekapps.expensetracker.model; public class BEIAmount { private String balance, expense, income; public BEIAmount() {} public String getBalance() { return balance; } public void setBalance(String balance) { this.balance = balance; } public String getExpense() { return expense; } public void setExpense(String expense) { this.expense = expense; } public String getIncome() { return income; } public void setIncome(String income) { this.income = income; } }
UTF-8
Java
585
java
BEIAmount.java
Java
[]
null
[]
package com.jaekapps.expensetracker.model; public class BEIAmount { private String balance, expense, income; public BEIAmount() {} public String getBalance() { return balance; } public void setBalance(String balance) { this.balance = balance; } public String getExpense() { return expense; } public void setExpense(String expense) { this.expense = expense; } public String getIncome() { return income; } public void setIncome(String income) { this.income = income; } }
585
0.610256
0.610256
35
15.714286
16.352495
44
false
false
0
0
0
0
0
0
0.285714
false
false
1
855f00debf04cee1aa90628977764173db131800
9,861,244,944,904
76852b1b29410436817bafa34c6dedaedd0786cd
/sources-2020-11-04-tempmail/sources/com/google/firebase/f/c.java
36098c4d51de92242310f2a6e4ee6e2a69f1a305
[]
no_license
zteeed/tempmail-apks
https://github.com/zteeed/tempmail-apks
040e64e07beadd8f5e48cd7bea8b47233e99611c
19f8da1993c2f783b8847234afb52d94b9d1aa4c
refs/heads/master
2023-01-09T06:43:40.830000
2020-11-04T18:55:05
2020-11-04T18:55:05
310,075,224
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.google.firebase.f; /* compiled from: com.google.firebase:firebase-components@@16.0.0 */ public interface c { }
UTF-8
Java
124
java
c.java
Java
[]
null
[]
package com.google.firebase.f; /* compiled from: com.google.firebase:firebase-components@@16.0.0 */ public interface c { }
124
0.741935
0.709677
5
23.799999
24.870867
68
false
false
0
0
0
0
0
0
0.2
false
false
1
09bdf779c118126fe44f31dc3320c8cdcc4373c9
10,969,346,498,764
30c5cbfe2d1aa8409ef5d14c37b8a867945727d5
/HotelMngt/src/com/hospitality/controller/RoomController.java
4bd250e9bb918a286a20ecd14fb95e1151f9e21b
[]
no_license
kishore888/kts
https://github.com/kishore888/kts
da76d9dc095b751d1aab5bedf85af7450257e210
0e8919ff97f997100d80148bf33c4b3a80f9a0b3
refs/heads/master
2021-07-13T04:16:58.180000
2020-08-12T03:53:37
2020-08-12T03:53:37
190,324,837
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.hospitality.controller; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpSession; import org.apache.commons.lang.StringUtils; import org.json.JSONObject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import com.hospitality.bo.HotelPaymentGatewayBO; import com.hospitality.bo.HotelPlanMasterBO; import com.hospitality.bo.PaymentAccountBO; import com.hospitality.bo.RoomBO; import com.hospitality.bo.RoomTypeBO; import com.hospitality.core.Hotel; import com.hospitality.core.HotelPaymentGateway; import com.hospitality.core.HotelPlanMaster; import com.hospitality.core.PaymentAccount; import com.hospitality.core.Room; import com.hospitality.core.RoomType; import com.hospitality.dto.DataTableDTO; @Controller @RequestMapping("/room/") public class RoomController { @Autowired private RoomBO roomBO; @Autowired private RoomTypeBO roomTypeBO; @Autowired private HotelPlanMasterBO hotelPlanMasterBO; @Autowired private HotelPaymentGatewayBO hotelPaymentGatewayBO; @Autowired private PaymentAccountBO paymentAccountBO; @RequestMapping(value="create",method = RequestMethod.GET) public ModelAndView showCreateRoom(String roomId, HttpSession session){ Room room = null; Hotel hotel = null; List<RoomType> roomTypeList = null; List<HotelPlanMaster> hotelPlanMasterList = new ArrayList<>(); List<PaymentAccount> paymentAccountList = new ArrayList<>(); try{ hotel = (Hotel)session.getAttribute("hotelObj"); if(StringUtils.isNotBlank(roomId)) { room = roomBO.retrieveByRoomId(roomId); } roomTypeList = roomTypeBO.retrieveListByYear(); hotelPlanMasterList = hotelPlanMasterBO.retrieveListByYear(); paymentAccountList = paymentAccountBO.retrieveListByHotel(hotel); }catch(Exception e){ e.printStackTrace(); } return new ModelAndView("CreateRoom", "roomTypeList", roomTypeList).addObject("room", room).addObject("hotelPlanMasterList", hotelPlanMasterList).addObject("paymentAccountList", paymentAccountList); } @RequestMapping(value="create",method = RequestMethod.POST) public ModelAndView create(Room room){ try{ roomBO.create(room); }catch(Exception e){ e.printStackTrace(); } return new ModelAndView("redirect:create?roomId="+room.getRoomId()); } @RequestMapping(value="retrieveRoomList",method = RequestMethod.GET) public ModelAndView retrieveList(Hotel hotel, HttpSession session){ List<Room> roomList = new ArrayList<>(); List<HotelPaymentGateway> hotelPaymentGatewayList = new ArrayList<>(); try{ if(hotel == null) { hotel = (Hotel)session.getAttribute("hotelObj"); }else if(StringUtils.isBlank(hotel.getHotelId())) { hotel = (Hotel)session.getAttribute("hotelObj"); } roomList = roomBO.retrieveRoomList(hotel); hotelPaymentGatewayList = hotelPaymentGatewayBO.retrieveActiveGatewayListByHotel(hotel); }catch(Exception e){ e.printStackTrace(); } return new ModelAndView("RoomList", "roomList", roomList).addObject("hotelPaymentGatewayList", hotelPaymentGatewayList); } @RequestMapping(value="retrieveRoomListServersideDatatable",method = RequestMethod.GET) public ModelAndView retrieveRoomListServersideDatatable(DataTableDTO dataTable, HttpSession session){ List<Room> roomList = new ArrayList<>(); Hotel hotel = null; try{ hotel = (Hotel)session.getAttribute("hotelObj"); roomList = roomBO.retrieveRoomList(hotel); // roomList = roomBO.retrieveRoomListServersideDatatable(); }catch(Exception e){ e.printStackTrace(); } return new ModelAndView("ServersideRoomList").addObject("roomList", roomList); } @RequestMapping(value="retrieveRoomListServersideDatatableAjax",method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE) @ResponseBody public Map<String, Object> retrieveRoomsServersideDatatableAjax(@RequestBody DataTableDTO dataTable, HttpSession httpSession){ List<Room> roomList = null; Map<String, Object> roomMap = new HashMap<>(); Hotel hotel = null; try{ hotel = (Hotel) httpSession.getAttribute("hotel"); // roomList = roomBO.retrieveRoomList(); roomMap = roomBO.retrieveRoomsServersideDatatable(dataTable, hotel); }catch(Exception e){ e.printStackTrace(); } return roomMap; } }
UTF-8
Java
4,830
java
RoomController.java
Java
[]
null
[]
package com.hospitality.controller; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpSession; import org.apache.commons.lang.StringUtils; import org.json.JSONObject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import com.hospitality.bo.HotelPaymentGatewayBO; import com.hospitality.bo.HotelPlanMasterBO; import com.hospitality.bo.PaymentAccountBO; import com.hospitality.bo.RoomBO; import com.hospitality.bo.RoomTypeBO; import com.hospitality.core.Hotel; import com.hospitality.core.HotelPaymentGateway; import com.hospitality.core.HotelPlanMaster; import com.hospitality.core.PaymentAccount; import com.hospitality.core.Room; import com.hospitality.core.RoomType; import com.hospitality.dto.DataTableDTO; @Controller @RequestMapping("/room/") public class RoomController { @Autowired private RoomBO roomBO; @Autowired private RoomTypeBO roomTypeBO; @Autowired private HotelPlanMasterBO hotelPlanMasterBO; @Autowired private HotelPaymentGatewayBO hotelPaymentGatewayBO; @Autowired private PaymentAccountBO paymentAccountBO; @RequestMapping(value="create",method = RequestMethod.GET) public ModelAndView showCreateRoom(String roomId, HttpSession session){ Room room = null; Hotel hotel = null; List<RoomType> roomTypeList = null; List<HotelPlanMaster> hotelPlanMasterList = new ArrayList<>(); List<PaymentAccount> paymentAccountList = new ArrayList<>(); try{ hotel = (Hotel)session.getAttribute("hotelObj"); if(StringUtils.isNotBlank(roomId)) { room = roomBO.retrieveByRoomId(roomId); } roomTypeList = roomTypeBO.retrieveListByYear(); hotelPlanMasterList = hotelPlanMasterBO.retrieveListByYear(); paymentAccountList = paymentAccountBO.retrieveListByHotel(hotel); }catch(Exception e){ e.printStackTrace(); } return new ModelAndView("CreateRoom", "roomTypeList", roomTypeList).addObject("room", room).addObject("hotelPlanMasterList", hotelPlanMasterList).addObject("paymentAccountList", paymentAccountList); } @RequestMapping(value="create",method = RequestMethod.POST) public ModelAndView create(Room room){ try{ roomBO.create(room); }catch(Exception e){ e.printStackTrace(); } return new ModelAndView("redirect:create?roomId="+room.getRoomId()); } @RequestMapping(value="retrieveRoomList",method = RequestMethod.GET) public ModelAndView retrieveList(Hotel hotel, HttpSession session){ List<Room> roomList = new ArrayList<>(); List<HotelPaymentGateway> hotelPaymentGatewayList = new ArrayList<>(); try{ if(hotel == null) { hotel = (Hotel)session.getAttribute("hotelObj"); }else if(StringUtils.isBlank(hotel.getHotelId())) { hotel = (Hotel)session.getAttribute("hotelObj"); } roomList = roomBO.retrieveRoomList(hotel); hotelPaymentGatewayList = hotelPaymentGatewayBO.retrieveActiveGatewayListByHotel(hotel); }catch(Exception e){ e.printStackTrace(); } return new ModelAndView("RoomList", "roomList", roomList).addObject("hotelPaymentGatewayList", hotelPaymentGatewayList); } @RequestMapping(value="retrieveRoomListServersideDatatable",method = RequestMethod.GET) public ModelAndView retrieveRoomListServersideDatatable(DataTableDTO dataTable, HttpSession session){ List<Room> roomList = new ArrayList<>(); Hotel hotel = null; try{ hotel = (Hotel)session.getAttribute("hotelObj"); roomList = roomBO.retrieveRoomList(hotel); // roomList = roomBO.retrieveRoomListServersideDatatable(); }catch(Exception e){ e.printStackTrace(); } return new ModelAndView("ServersideRoomList").addObject("roomList", roomList); } @RequestMapping(value="retrieveRoomListServersideDatatableAjax",method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE) @ResponseBody public Map<String, Object> retrieveRoomsServersideDatatableAjax(@RequestBody DataTableDTO dataTable, HttpSession httpSession){ List<Room> roomList = null; Map<String, Object> roomMap = new HashMap<>(); Hotel hotel = null; try{ hotel = (Hotel) httpSession.getAttribute("hotel"); // roomList = roomBO.retrieveRoomList(); roomMap = roomBO.retrieveRoomsServersideDatatable(dataTable, hotel); }catch(Exception e){ e.printStackTrace(); } return roomMap; } }
4,830
0.760662
0.760662
133
34.315788
31.580276
200
false
false
0
0
0
0
0
0
2.067669
false
false
1
099b2944c85e94e52683a03d40da23f3c28bca83
17,420,387,398,555
481bd1dd64b60a98a750a9b9e366051c958e3ce0
/hacker-rank/Practice/medium/Play_with_words.java
ab96bc24f2bc2ba3e2c2e93dcc5f58bf091496c6
[]
no_license
trungdovan87/hacker
https://github.com/trungdovan87/hacker
6cb55c0632b087983187eb5cbaa8b279dc60eb53
2de025d5c73eef2fcdf031466bdaa0f8553211de
refs/heads/master
2021-01-13T16:44:44.484000
2019-11-04T09:33:11
2019-11-04T09:33:11
77,213,690
4
4
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * Play with words * link: https://www.hackerrank.com/challenges/strplay * point: 15/15 */ import java.util.Scanner; public class Main { static int solution(String seq) { int n = seq.length(); int i, j, cl; int L[][] = new int[n][n]; for (i = 0; i < n; i++) L[i][i] = 1; for (cl=2; cl<=n; cl++) { for (i=0; i<n-cl+1; i++) { j = i+cl-1; if (seq.charAt(i) == seq.charAt(j) && cl == 2) L[i][j] = 2; else if (seq.charAt(i) == seq.charAt(j)) L[i][j] = L[i+1][j-1] + 2; else L[i][j] = Math.max(L[i][j-1], L[i+1][j]); } } int max = 0; for (int tmp = 1; tmp < n; tmp++) { int lt = L[0][tmp - 1] * L[tmp][n - 1]; if (max < lt) max = lt; } return max; } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String s = scanner.next(); System.out.println(solution(s)); } }
UTF-8
Java
890
java
Play_with_words.java
Java
[]
null
[]
/** * Play with words * link: https://www.hackerrank.com/challenges/strplay * point: 15/15 */ import java.util.Scanner; public class Main { static int solution(String seq) { int n = seq.length(); int i, j, cl; int L[][] = new int[n][n]; for (i = 0; i < n; i++) L[i][i] = 1; for (cl=2; cl<=n; cl++) { for (i=0; i<n-cl+1; i++) { j = i+cl-1; if (seq.charAt(i) == seq.charAt(j) && cl == 2) L[i][j] = 2; else if (seq.charAt(i) == seq.charAt(j)) L[i][j] = L[i+1][j-1] + 2; else L[i][j] = Math.max(L[i][j-1], L[i+1][j]); } } int max = 0; for (int tmp = 1; tmp < n; tmp++) { int lt = L[0][tmp - 1] * L[tmp][n - 1]; if (max < lt) max = lt; } return max; } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String s = scanner.next(); System.out.println(solution(s)); } }
890
0.505618
0.480899
46
18.347826
15.695772
54
false
false
0
0
0
0
0
0
2.456522
false
false
1
23fedac32aec9354ce2a70af43a698375c534174
6,828,998,023,699
5a01dad8ce2ff5998ab445dc0fd3075ad5db1b60
/air/southwest/src/main/java/xsscd/monitor/air/southwest/modules/core/entitys/mybatis/dto/SupersetDashboardsAssembly.java
ee805651cd7c37dcb730dd9b1987adbf30f54cdd
[]
no_license
yanghuan1987/monitor_bak
https://github.com/yanghuan1987/monitor_bak
2d794c08fd0c5681667d5730bd1ba7a055f4ae28
5cfd8c3dda29445d999b7a9f7b4760d00cb8485a
refs/heads/master
2020-03-18T06:23:43.894000
2018-05-22T09:33:33
2018-05-22T09:33:33
134,386,320
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package xsscd.monitor.air.southwest.modules.core.entitys.mybatis.dto; import java.util.List; public class SupersetDashboardsAssembly { private static final long serialVersionUID = 1L; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column superset_dashboards_assembly.id * * @mbggenerated */ private Long id; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column superset_dashboards_assembly.dashboards_id * * @mbggenerated */ private Long dashboardsId; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column superset_dashboards_assembly.name * * @mbggenerated */ private String name; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column superset_dashboards_assembly.type * * @mbggenerated */ private String type; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column superset_dashboards_assembly.position * * @mbggenerated */ private String position; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column superset_dashboards_assembly.slices_id * * @mbggenerated */ private String slicesId; private List<SupersetDashboardsAssemblyItem> supersetDashboardsAssemblyItems; /** * This method was generated by MyBatis Generator. * This method returns the value of the database column superset_dashboards_assembly.id * * @return the value of superset_dashboards_assembly.id * * @mbggenerated */ public Long getId() { return id; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column superset_dashboards_assembly.id * * @param id the value for superset_dashboards_assembly.id * * @mbggenerated */ public void setId(Long id) { this.id = id; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column superset_dashboards_assembly.dashboards_id * * @return the value of superset_dashboards_assembly.dashboards_id * * @mbggenerated */ public Long getDashboardsId() { return dashboardsId; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column superset_dashboards_assembly.dashboards_id * * @param dashboardsId the value for superset_dashboards_assembly.dashboards_id * * @mbggenerated */ public void setDashboardsId(Long dashboardsId) { this.dashboardsId = dashboardsId; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column superset_dashboards_assembly.name * * @return the value of superset_dashboards_assembly.name * * @mbggenerated */ public String getName() { return name; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column superset_dashboards_assembly.name * * @param name the value for superset_dashboards_assembly.name * * @mbggenerated */ public void setName(String name) { this.name = name == null ? null : name.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column superset_dashboards_assembly.type * * @return the value of superset_dashboards_assembly.type * * @mbggenerated */ public String getType() { return type; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column superset_dashboards_assembly.type * * @param type the value for superset_dashboards_assembly.type * * @mbggenerated */ public void setType(String type) { this.type = type == null ? null : type.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column superset_dashboards_assembly.position * * @return the value of superset_dashboards_assembly.position * * @mbggenerated */ public String getPosition() { return position; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column superset_dashboards_assembly.position * * @param position the value for superset_dashboards_assembly.position * * @mbggenerated */ public void setPosition(String position) { this.position = position == null ? null : position.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column superset_dashboards_assembly.slices_id * * @return the value of superset_dashboards_assembly.slices_id * * @mbggenerated */ public String getSlicesId() { return slicesId; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column superset_dashboards_assembly.slices_id * * @param slicesId the value for superset_dashboards_assembly.slices_id * * @mbggenerated */ public void setSlicesId(String slicesId) { this.slicesId = slicesId == null ? null : slicesId.trim(); } public List<SupersetDashboardsAssemblyItem> getSupersetDashboardsAssemblyItems() { return supersetDashboardsAssemblyItems; } public void setSupersetDashboardsAssemblyItems(List<SupersetDashboardsAssemblyItem> supersetDashboardsAssemblyItems) { this.supersetDashboardsAssemblyItems = supersetDashboardsAssemblyItems; } }
UTF-8
Java
6,127
java
SupersetDashboardsAssembly.java
Java
[]
null
[]
package xsscd.monitor.air.southwest.modules.core.entitys.mybatis.dto; import java.util.List; public class SupersetDashboardsAssembly { private static final long serialVersionUID = 1L; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column superset_dashboards_assembly.id * * @mbggenerated */ private Long id; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column superset_dashboards_assembly.dashboards_id * * @mbggenerated */ private Long dashboardsId; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column superset_dashboards_assembly.name * * @mbggenerated */ private String name; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column superset_dashboards_assembly.type * * @mbggenerated */ private String type; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column superset_dashboards_assembly.position * * @mbggenerated */ private String position; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column superset_dashboards_assembly.slices_id * * @mbggenerated */ private String slicesId; private List<SupersetDashboardsAssemblyItem> supersetDashboardsAssemblyItems; /** * This method was generated by MyBatis Generator. * This method returns the value of the database column superset_dashboards_assembly.id * * @return the value of superset_dashboards_assembly.id * * @mbggenerated */ public Long getId() { return id; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column superset_dashboards_assembly.id * * @param id the value for superset_dashboards_assembly.id * * @mbggenerated */ public void setId(Long id) { this.id = id; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column superset_dashboards_assembly.dashboards_id * * @return the value of superset_dashboards_assembly.dashboards_id * * @mbggenerated */ public Long getDashboardsId() { return dashboardsId; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column superset_dashboards_assembly.dashboards_id * * @param dashboardsId the value for superset_dashboards_assembly.dashboards_id * * @mbggenerated */ public void setDashboardsId(Long dashboardsId) { this.dashboardsId = dashboardsId; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column superset_dashboards_assembly.name * * @return the value of superset_dashboards_assembly.name * * @mbggenerated */ public String getName() { return name; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column superset_dashboards_assembly.name * * @param name the value for superset_dashboards_assembly.name * * @mbggenerated */ public void setName(String name) { this.name = name == null ? null : name.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column superset_dashboards_assembly.type * * @return the value of superset_dashboards_assembly.type * * @mbggenerated */ public String getType() { return type; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column superset_dashboards_assembly.type * * @param type the value for superset_dashboards_assembly.type * * @mbggenerated */ public void setType(String type) { this.type = type == null ? null : type.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column superset_dashboards_assembly.position * * @return the value of superset_dashboards_assembly.position * * @mbggenerated */ public String getPosition() { return position; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column superset_dashboards_assembly.position * * @param position the value for superset_dashboards_assembly.position * * @mbggenerated */ public void setPosition(String position) { this.position = position == null ? null : position.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column superset_dashboards_assembly.slices_id * * @return the value of superset_dashboards_assembly.slices_id * * @mbggenerated */ public String getSlicesId() { return slicesId; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column superset_dashboards_assembly.slices_id * * @param slicesId the value for superset_dashboards_assembly.slices_id * * @mbggenerated */ public void setSlicesId(String slicesId) { this.slicesId = slicesId == null ? null : slicesId.trim(); } public List<SupersetDashboardsAssemblyItem> getSupersetDashboardsAssemblyItems() { return supersetDashboardsAssemblyItems; } public void setSupersetDashboardsAssemblyItems(List<SupersetDashboardsAssemblyItem> supersetDashboardsAssemblyItems) { this.supersetDashboardsAssemblyItems = supersetDashboardsAssemblyItems; } }
6,127
0.661662
0.661498
207
28.603865
30.185059
122
false
false
0
0
0
0
0
0
0.120773
false
false
1
0a5cbba7ff5bdb6f13b003d4ff612406ba31882e
24,730,421,756,878
5ce2aa33e1f76dac0bed1225a14430153ce0f42a
/src/main/java/com/schwifty/gardenator/zone/service/ZoneService.java
0aa9d9244679e9fd62380d232d822fbcda60b4d1
[]
no_license
ldlharper/gardenator
https://github.com/ldlharper/gardenator
dcc5203bf057cb620b990dddbf934214a4158557
54848322e17cf6e15b2242cc5dc436044423ee40
refs/heads/master
2020-03-16T22:13:58.303000
2018-05-29T20:42:19
2018-05-29T20:42:19
133,031,390
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.schwifty.gardenator.zone.service; import com.fasterxml.jackson.databind.ObjectMapper; import com.schwifty.gardenator.zone.json.ZonesJson; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import java.io.File; import java.io.IOException; @Service public class ZoneService { @Value("${files.zone.path}") private String zonePath; @Autowired private ObjectMapper objectMapper; public ZonesJson getZones() throws IOException { return objectMapper.readValue(new File(zonePath), ZonesJson.class); } public void saveZones(ZonesJson zones) throws IOException { objectMapper.writeValue(new File(zonePath), zones); } }
UTF-8
Java
795
java
ZoneService.java
Java
[]
null
[]
package com.schwifty.gardenator.zone.service; import com.fasterxml.jackson.databind.ObjectMapper; import com.schwifty.gardenator.zone.json.ZonesJson; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import java.io.File; import java.io.IOException; @Service public class ZoneService { @Value("${files.zone.path}") private String zonePath; @Autowired private ObjectMapper objectMapper; public ZonesJson getZones() throws IOException { return objectMapper.readValue(new File(zonePath), ZonesJson.class); } public void saveZones(ZonesJson zones) throws IOException { objectMapper.writeValue(new File(zonePath), zones); } }
795
0.767296
0.767296
29
26.413794
24.54063
75
false
false
0
0
0
0
0
0
0.482759
false
false
1
14b4377da2c58011494461e86d915313ab081500
12,541,304,529,255
6bf9565ddcc68a46a1f6349cb73bdb8b9a2f3089
/modules/rsl-util/src/main/java/rsl/util/StackTrace.java
d765d1825c3fd5e893eb37ea30c59ba55fe61a39
[]
no_license
asanctor/rsl-master
https://github.com/asanctor/rsl-master
cefa70c1d77d0ed8b0cfff9ba61378278f1ebb7a
5151457123d9d55a70d9cebdfce9d638204d674d
refs/heads/main
2023-05-03T22:35:48.893000
2021-05-21T15:51:49
2021-05-21T15:51:49
369,582,688
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package rsl.util; import java.io.PrintWriter; import java.io.StringWriter; public class StackTrace { public static void printStackTrace() { StringWriter sw = new StringWriter(); new Throwable("").printStackTrace(new PrintWriter(sw)); System.out.println(sw.toString()); } }
UTF-8
Java
312
java
StackTrace.java
Java
[]
null
[]
package rsl.util; import java.io.PrintWriter; import java.io.StringWriter; public class StackTrace { public static void printStackTrace() { StringWriter sw = new StringWriter(); new Throwable("").printStackTrace(new PrintWriter(sw)); System.out.println(sw.toString()); } }
312
0.676282
0.676282
14
21.285715
19.807749
63
false
false
0
0
0
0
0
0
0.428571
false
false
1
7c2230d0a2163286a05a0fee969267aee0fbccbb
5,995,774,347,495
46febff8e41aa710e22359e848fb9547b555f781
/src/test/Java/com/neuedu/test/ProductTest.java
dd37ef4c157f23db1db78e246fd2ee09fe0eff7c
[]
no_license
yw888/BusinessProject
https://github.com/yw888/BusinessProject
153becf1802239325e46c8d42cfe64df6e94360f
0b8ad06b2393f0ccd3d31cac8b950e013928a0d0
refs/heads/master
2020-03-24T02:32:36.697000
2018-08-02T10:41:20
2018-08-02T10:41:20
142,380,417
5
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.neuedu.test; import com.neuedu.dao.ProductDao; import com.neuedu.dao.impl.jdbc.mybatis.ProductMybatisImpl; import com.neuedu.entity.PageMo; import com.neuedu.entity.Product; import org.junit.jupiter.api.Test; public class ProductTest { ProductDao productDao=new ProductMybatisImpl(); @Test public void testfindProductByPage(){ PageMo<Product> pageMo=productDao.findProductByPage(1,4); System.out.println(pageMo); } @Test public void testaddProduct(){ Product product=new Product(); product.setName("荣耀10"); product.setDesc("极光色"); product.setPrice(3200); product.setRule("kkkk"); product.setImage("sssss"); product.setStock(20); boolean result=productDao.addProduct(product); System.out.println(result); } @Test public void testUpdateProduct(){ Product product=new Product(); product.setName("iphone"); product.setDesc("极光色"); product.setPrice(8000); product.setRule("kkkk"); product.setImage("sssss"); product.setStock(20); product.setId(20); productDao.updateProduct(product); } @Test public void testdeleteProduct(){ productDao.deleteProduct(20); } @Test public void testfindById(){ Product product=productDao.findById(3); System.out.println(product); } }
UTF-8
Java
1,438
java
ProductTest.java
Java
[]
null
[]
package com.neuedu.test; import com.neuedu.dao.ProductDao; import com.neuedu.dao.impl.jdbc.mybatis.ProductMybatisImpl; import com.neuedu.entity.PageMo; import com.neuedu.entity.Product; import org.junit.jupiter.api.Test; public class ProductTest { ProductDao productDao=new ProductMybatisImpl(); @Test public void testfindProductByPage(){ PageMo<Product> pageMo=productDao.findProductByPage(1,4); System.out.println(pageMo); } @Test public void testaddProduct(){ Product product=new Product(); product.setName("荣耀10"); product.setDesc("极光色"); product.setPrice(3200); product.setRule("kkkk"); product.setImage("sssss"); product.setStock(20); boolean result=productDao.addProduct(product); System.out.println(result); } @Test public void testUpdateProduct(){ Product product=new Product(); product.setName("iphone"); product.setDesc("极光色"); product.setPrice(8000); product.setRule("kkkk"); product.setImage("sssss"); product.setStock(20); product.setId(20); productDao.updateProduct(product); } @Test public void testdeleteProduct(){ productDao.deleteProduct(20); } @Test public void testfindById(){ Product product=productDao.findById(3); System.out.println(product); } }
1,438
0.647679
0.632911
50
27.440001
15.922512
65
false
false
0
0
0
0
0
0
0.62
false
false
1
3648c6164c321959dd6ae226fbe7967897172b88
25,288,767,506,029
9fde4f4bbdf06dd4d95aeba9412332f7df81497d
/app/src/main/java/org/sluman/movies/FetchReviewsTask.java
6d4ce59c32e652c9e14b7146e1d9243325374a15
[]
no_license
brycesluman/nanodegree-movies
https://github.com/brycesluman/nanodegree-movies
96e2f629c13a4ecb90c7f277c51fe4a52bc4c7dc
2a2185ab3894e6bd7c0b629f3ba8c429f7e44f21
refs/heads/master
2021-01-10T14:23:56.214000
2016-05-03T00:20:46
2016-05-03T00:20:46
55,573,453
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.sluman.movies; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.net.Uri; import android.os.AsyncTask; import android.text.format.Time; import android.util.Log; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.sluman.movies.data.MoviesContract; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.util.Vector; /** * Created by bryce on 4/8/16. */ public class FetchReviewsTask extends AsyncTask<Integer, Void, Void> { private final String LOG_TAG = FetchVideosTask.class.getSimpleName(); private final Context mContext; public FetchReviewsTask(Context context) { mContext = context; } private boolean DEBUG = true; private long getMovieDbId(int id) { long videoId = 0; // First, check if the location with this city name exists in the db Cursor reviewCursor = mContext.getContentResolver().query( MoviesContract.MovieEntry.buildMoviesUri(id), new String[]{MoviesContract.MovieEntry.COLUMN_ID}, null, null, null); if (reviewCursor.moveToFirst()) { int videoIdIndex = reviewCursor.getColumnIndex(MoviesContract.MovieEntry.COLUMN_ID); videoId = reviewCursor.getLong(videoIdIndex); } reviewCursor.close(); return videoId; } /** * Take the String representing the complete forecast in JSON Format and * pull out the data we need to construct the Strings needed for the wireframes. * <p/> * Fortunately parsing is easy: constructor takes the JSON string and converts it * into an Object hierarchy for us. */ public Void getVideosDataFromJson(String videosJsonStr, int id) throws JSONException { Log.d("FetchVideosTask", "MovieId: " + id); // Now we have a String representing the complete forecast in JSON Format. // Fortunately parsing is easy: constructor takes the JSON string and converts it // into an Object hierarchy for us. // { // "id": 209112, // "page": 1, // "results": [ // { // "id":"56f4f0bd9251417a440017bd", // "author":"Rahul Gupta", // "content": // "Awesome moview. Best Action sequence.\r\n\r\n**Slow in the first half**", // "url":"https://www.themoviedb.org/review/56f4f0bd9251417a440017bd" // } // } // These are the names of the JSON objects that need to be extracted. final String OWM_MDB_ID = "id"; final String OWM_LIST = "results"; final String OWM_ID = "id"; final String OWM_AUTHOR = "author"; final String OWM_CONTENT = "content"; final String OWM_URL = "url"; try { int moviedb_id; JSONObject reviewsJson = new JSONObject(videosJsonStr); JSONArray reviewsArray = reviewsJson.getJSONArray(OWM_LIST); moviedb_id = reviewsJson.getInt(OWM_MDB_ID); // Insert the new weather information into the database Vector<ContentValues> cVVector = new Vector<ContentValues>(reviewsArray.length()); Time dayTime = new Time(); dayTime.setToNow(); // we start at the day returned by local time. Otherwise this is a mess. int julianStartDay = Time.getJulianDay(System.currentTimeMillis(), dayTime.gmtoff); // now we work exclusively in UTC dayTime = new Time(); for (int i = 0; i < reviewsArray.length(); i++) { // These are the values that will be collected. long dateTime; String review_id; String author; String content; String url; // Get the JSON object representing the day JSONObject reviewObject = reviewsArray.getJSONObject(i); // Cheating to convert this to UTC time, which is what we want anyhow dateTime = dayTime.setJulianDay(julianStartDay + i); review_id = reviewObject.getString(OWM_ID); author = reviewObject.getString(OWM_AUTHOR); content = reviewObject.getString(OWM_CONTENT); url = reviewObject.getString(OWM_URL); ContentValues reviewValues = new ContentValues(); reviewValues.put(MoviesContract.ReviewEntry.COLUMN_FOREIGN_KEY, id); reviewValues.put(MoviesContract.ReviewEntry.COLUMN_MOVIEDB_ID, moviedb_id); reviewValues.put(MoviesContract.ReviewEntry.COLUMN_REVIEW_ID, review_id); reviewValues.put(MoviesContract.ReviewEntry.COLUMN_AUTHOR, author); reviewValues.put(MoviesContract.ReviewEntry.COLUMN_CONTENT, content); reviewValues.put(MoviesContract.ReviewEntry.COLUMN_URL, url); cVVector.add(reviewValues); } int inserted = 0; // add to database if (cVVector.size() > 0) { ContentValues[] cvArray = new ContentValues[cVVector.size()]; cVVector.toArray(cvArray); inserted = mContext.getContentResolver().bulkInsert(MoviesContract.ReviewEntry.CONTENT_URI, cvArray); } Log.d(LOG_TAG, "FetchReviewsTask Complete. " + inserted + " Inserted"); } catch (JSONException e) { Log.e(LOG_TAG, e.getMessage(), e); e.printStackTrace(); } return null; } @Override protected Void doInBackground(Integer... params) { // If there's no zip code, there's nothing to look up. Verify size of params. if (params.length == 0) { return null; } int MOVIE_ID = params[0]; long MOVIEDB_ID = getMovieDbId(MOVIE_ID); Log.d("FetchReviewsTask", "MovieDbId: " + MOVIEDB_ID); // These two need to be declared outside the try/catch // so that they can be closed in the finally block. HttpURLConnection urlConnection = null; BufferedReader reader = null; // Will contain the raw JSON response as a string. String reviewsJsonStr = null; try { // Construct the URL for the OpenWeatherMap query // Possible parameters are avaiable at OWM's forecast API page, at // http://openweathermap.org/API#forecast final String BASE_URL = "https://api.themoviedb.org/3/movie/"; final String APPID_PARAM = "api_key"; Uri builtUri = Uri.parse(BASE_URL).buildUpon() .appendPath(String.valueOf(MOVIEDB_ID)) .appendPath("reviews") .appendQueryParameter(APPID_PARAM, BuildConfig.MOVIE_DB_API_KEY) .build(); Log.d(LOG_TAG, builtUri.toString()); URL url = new URL(builtUri.toString()); // Create the request to OpenWeatherMap, and open the connection urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestMethod("GET"); urlConnection.connect(); // Read the input stream into a String InputStream inputStream = urlConnection.getInputStream(); StringBuffer buffer = new StringBuffer(); if (inputStream == null) { // Nothing to do. return null; } reader = new BufferedReader(new InputStreamReader(inputStream)); String line; while ((line = reader.readLine()) != null) { // Since it's JSON, adding a newline isn't necessary (it won't affect parsing) // But it does make debugging a *lot* easier if you print out the completed // buffer for debugging. buffer.append(line + "\n"); } if (buffer.length() == 0) { // Stream was empty. No point in parsing. return null; } reviewsJsonStr = buffer.toString(); } catch (IOException e) { Log.e(LOG_TAG, "Error ", e); // If the code didn't successfully get the weather data, there's no point in attemping // to parse it. return null; } finally { if (urlConnection != null) { urlConnection.disconnect(); } if (reader != null) { try { reader.close(); } catch (final IOException e) { Log.e(LOG_TAG, "Error closing stream", e); } } } try { return getVideosDataFromJson(reviewsJsonStr, MOVIE_ID); } catch (JSONException e) { Log.e(LOG_TAG, e.getMessage(), e); e.printStackTrace(); } // This will only happen if there was an error getting or parsing the forecast. return null; } }
UTF-8
Java
9,397
java
FetchReviewsTask.java
Java
[ { "context": "t.URL;\nimport java.util.Vector;\n\n/**\n * Created by bryce on 4/8/16.\n */\npublic class FetchReviewsTask exte", "end": 602, "score": 0.999678909778595, "start": 597, "tag": "USERNAME", "value": "bryce" }, { "context": "251417a440017bd\",\n// \"author\":\"Rahul Gupta\",\n// \"content\":\n// ", "end": 2535, "score": 0.999873161315918, "start": 2524, "tag": "NAME", "value": "Rahul Gupta" } ]
null
[]
package org.sluman.movies; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.net.Uri; import android.os.AsyncTask; import android.text.format.Time; import android.util.Log; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.sluman.movies.data.MoviesContract; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.util.Vector; /** * Created by bryce on 4/8/16. */ public class FetchReviewsTask extends AsyncTask<Integer, Void, Void> { private final String LOG_TAG = FetchVideosTask.class.getSimpleName(); private final Context mContext; public FetchReviewsTask(Context context) { mContext = context; } private boolean DEBUG = true; private long getMovieDbId(int id) { long videoId = 0; // First, check if the location with this city name exists in the db Cursor reviewCursor = mContext.getContentResolver().query( MoviesContract.MovieEntry.buildMoviesUri(id), new String[]{MoviesContract.MovieEntry.COLUMN_ID}, null, null, null); if (reviewCursor.moveToFirst()) { int videoIdIndex = reviewCursor.getColumnIndex(MoviesContract.MovieEntry.COLUMN_ID); videoId = reviewCursor.getLong(videoIdIndex); } reviewCursor.close(); return videoId; } /** * Take the String representing the complete forecast in JSON Format and * pull out the data we need to construct the Strings needed for the wireframes. * <p/> * Fortunately parsing is easy: constructor takes the JSON string and converts it * into an Object hierarchy for us. */ public Void getVideosDataFromJson(String videosJsonStr, int id) throws JSONException { Log.d("FetchVideosTask", "MovieId: " + id); // Now we have a String representing the complete forecast in JSON Format. // Fortunately parsing is easy: constructor takes the JSON string and converts it // into an Object hierarchy for us. // { // "id": 209112, // "page": 1, // "results": [ // { // "id":"56f4f0bd9251417a440017bd", // "author":"<NAME>", // "content": // "Awesome moview. Best Action sequence.\r\n\r\n**Slow in the first half**", // "url":"https://www.themoviedb.org/review/56f4f0bd9251417a440017bd" // } // } // These are the names of the JSON objects that need to be extracted. final String OWM_MDB_ID = "id"; final String OWM_LIST = "results"; final String OWM_ID = "id"; final String OWM_AUTHOR = "author"; final String OWM_CONTENT = "content"; final String OWM_URL = "url"; try { int moviedb_id; JSONObject reviewsJson = new JSONObject(videosJsonStr); JSONArray reviewsArray = reviewsJson.getJSONArray(OWM_LIST); moviedb_id = reviewsJson.getInt(OWM_MDB_ID); // Insert the new weather information into the database Vector<ContentValues> cVVector = new Vector<ContentValues>(reviewsArray.length()); Time dayTime = new Time(); dayTime.setToNow(); // we start at the day returned by local time. Otherwise this is a mess. int julianStartDay = Time.getJulianDay(System.currentTimeMillis(), dayTime.gmtoff); // now we work exclusively in UTC dayTime = new Time(); for (int i = 0; i < reviewsArray.length(); i++) { // These are the values that will be collected. long dateTime; String review_id; String author; String content; String url; // Get the JSON object representing the day JSONObject reviewObject = reviewsArray.getJSONObject(i); // Cheating to convert this to UTC time, which is what we want anyhow dateTime = dayTime.setJulianDay(julianStartDay + i); review_id = reviewObject.getString(OWM_ID); author = reviewObject.getString(OWM_AUTHOR); content = reviewObject.getString(OWM_CONTENT); url = reviewObject.getString(OWM_URL); ContentValues reviewValues = new ContentValues(); reviewValues.put(MoviesContract.ReviewEntry.COLUMN_FOREIGN_KEY, id); reviewValues.put(MoviesContract.ReviewEntry.COLUMN_MOVIEDB_ID, moviedb_id); reviewValues.put(MoviesContract.ReviewEntry.COLUMN_REVIEW_ID, review_id); reviewValues.put(MoviesContract.ReviewEntry.COLUMN_AUTHOR, author); reviewValues.put(MoviesContract.ReviewEntry.COLUMN_CONTENT, content); reviewValues.put(MoviesContract.ReviewEntry.COLUMN_URL, url); cVVector.add(reviewValues); } int inserted = 0; // add to database if (cVVector.size() > 0) { ContentValues[] cvArray = new ContentValues[cVVector.size()]; cVVector.toArray(cvArray); inserted = mContext.getContentResolver().bulkInsert(MoviesContract.ReviewEntry.CONTENT_URI, cvArray); } Log.d(LOG_TAG, "FetchReviewsTask Complete. " + inserted + " Inserted"); } catch (JSONException e) { Log.e(LOG_TAG, e.getMessage(), e); e.printStackTrace(); } return null; } @Override protected Void doInBackground(Integer... params) { // If there's no zip code, there's nothing to look up. Verify size of params. if (params.length == 0) { return null; } int MOVIE_ID = params[0]; long MOVIEDB_ID = getMovieDbId(MOVIE_ID); Log.d("FetchReviewsTask", "MovieDbId: " + MOVIEDB_ID); // These two need to be declared outside the try/catch // so that they can be closed in the finally block. HttpURLConnection urlConnection = null; BufferedReader reader = null; // Will contain the raw JSON response as a string. String reviewsJsonStr = null; try { // Construct the URL for the OpenWeatherMap query // Possible parameters are avaiable at OWM's forecast API page, at // http://openweathermap.org/API#forecast final String BASE_URL = "https://api.themoviedb.org/3/movie/"; final String APPID_PARAM = "api_key"; Uri builtUri = Uri.parse(BASE_URL).buildUpon() .appendPath(String.valueOf(MOVIEDB_ID)) .appendPath("reviews") .appendQueryParameter(APPID_PARAM, BuildConfig.MOVIE_DB_API_KEY) .build(); Log.d(LOG_TAG, builtUri.toString()); URL url = new URL(builtUri.toString()); // Create the request to OpenWeatherMap, and open the connection urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestMethod("GET"); urlConnection.connect(); // Read the input stream into a String InputStream inputStream = urlConnection.getInputStream(); StringBuffer buffer = new StringBuffer(); if (inputStream == null) { // Nothing to do. return null; } reader = new BufferedReader(new InputStreamReader(inputStream)); String line; while ((line = reader.readLine()) != null) { // Since it's JSON, adding a newline isn't necessary (it won't affect parsing) // But it does make debugging a *lot* easier if you print out the completed // buffer for debugging. buffer.append(line + "\n"); } if (buffer.length() == 0) { // Stream was empty. No point in parsing. return null; } reviewsJsonStr = buffer.toString(); } catch (IOException e) { Log.e(LOG_TAG, "Error ", e); // If the code didn't successfully get the weather data, there's no point in attemping // to parse it. return null; } finally { if (urlConnection != null) { urlConnection.disconnect(); } if (reader != null) { try { reader.close(); } catch (final IOException e) { Log.e(LOG_TAG, "Error closing stream", e); } } } try { return getVideosDataFromJson(reviewsJsonStr, MOVIE_ID); } catch (JSONException e) { Log.e(LOG_TAG, e.getMessage(), e); e.printStackTrace(); } // This will only happen if there was an error getting or parsing the forecast. return null; } }
9,392
0.578057
0.572417
251
36.438248
27.817404
117
false
false
0
0
0
0
0
0
0.585657
false
false
1
e62fc3649dd31d4c8230d96dca7200d12a89edd4
20,194,936,245,241
6db5b2d1606982289e8259e3f97be9cd9c56cfe0
/hdf5iolib/src/main/java/app/keve/hdf5io/fileformat/level2datatype/FixedPointNumberBB.java
7e524942532bf47f50c139d2924a3b64075bdcee
[ "Apache-2.0" ]
permissive
kevemueller/hdf5io
https://github.com/kevemueller/hdf5io
2105f2c1c58402652f0011c5d98f837363933897
3a2a52eea9754d491e360501f1e4036c6b1b32de
refs/heads/main
2023-01-07T16:17:56.887000
2020-11-03T11:08:05
2020-11-03T11:08:05
303,676,940
5
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * Copyright 2020 Keve Müller * * 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 app.keve.hdf5io.fileformat.level2datatype; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.util.OptionalInt; import app.keve.hdf5io.api.datatype.HDF5FixedPointNumber; import app.keve.hdf5io.fileformat.H5Context; public final class FixedPointNumberBB extends AbstractDatatypeBB implements HDF5FixedPointNumber { private static final int BF_BYTEORDER_MASK = 0x01; private static final int BF_LOPAD_MASK = 0x02; private static final int BF_HIPAD_MASK = 0x04; private static final int BF_SIGNED_MASK = 0x08; public FixedPointNumberBB(final ByteBuffer buf, final H5Context context) { super(buf, context); } @Override public long size() { return 8 + 4; } @Override public HDF5ByteOrder getByteOrder() { return 0 == (getClassBitField() & BF_BYTEORDER_MASK) ? HDF5ByteOrder.LITTLE_ENDIAN : HDF5ByteOrder.BIG_ENDIAN; } @Override public int getLoPadBit() { return 0 == (getClassBitField() & BF_LOPAD_MASK) ? 0 : 1; } @Override public int getHiPadBit() { return 0 == (getClassBitField() & BF_HIPAD_MASK) ? 0 : 1; } @Override public boolean isSigned() { return (getClassBitField() & BF_SIGNED_MASK) > 0; } @Override public int getBitOffset() { return getUnsignedShort(8); } protected void setBitOffset(final int value) { assert value >= 0 && value <= 0xFFFF; setUnsignedShort(8, value); } @Override public int getBitPrecision() { return getUnsignedShort(10); } protected void setBitPrecision(final int value) { assert value >= 0 && value <= 0xFFFF; setUnsignedShort(10, value); } private static int encodeClassBits(final HDF5ByteOrder hdf5ByteOrder, final int loPadBit, final int hiPadBit, final boolean signed) { int classBits = 0; switch (hdf5ByteOrder) { case LITTLE_ENDIAN: classBits |= 0b0; break; case BIG_ENDIAN: classBits |= 0b1; break; default: throw new IllegalArgumentException(); } switch (loPadBit) { case 0: classBits |= 0b00; break; case 1: classBits |= 0b10; break; default: throw new IllegalArgumentException(); } switch (hiPadBit) { case 0: classBits |= 0b000; break; case 1: classBits |= 0b100; break; default: throw new IllegalArgumentException(); } if (signed) { classBits |= 0b1000; } return classBits; } @Override public String toString() { return String.format( "%s, FixedPointNumberBB [size()=%s, getByteOrder()=%s, getLoPadBit()=%s, getHiPadBit()=%s, isSigned()=%s, " + "getBitOffset()=%s, getBitPrecision()=%s]", super.toString(), size(), getByteOrder(), getLoPadBit(), getHiPadBit(), isSigned(), getBitOffset(), getBitPrecision()); } @SuppressWarnings("checkstyle:hiddenfield") public static final class BuilderBB implements FixedPointNumberBuilder { private final H5Context context; private OptionalInt elementSize = OptionalInt.empty(); private HDF5ByteOrder hdf5ByteOrder = HDF5ByteOrder.BIG_ENDIAN; private OptionalInt loPadBit = OptionalInt.empty(); private OptionalInt bitOffset = OptionalInt.empty(); private Boolean signed = true; private OptionalInt hiPadBit = OptionalInt.empty(); private OptionalInt bitPrecision = OptionalInt.empty(); public BuilderBB(final H5Context context) { this.context = context; } @Override public HDF5FixedPointNumber build() { final ByteBuffer buf = ByteBuffer.allocate(8 + 4).order(ByteOrder.LITTLE_ENDIAN); final FixedPointNumberBB fixedPointNumber = new FixedPointNumberBB(buf, context); fixedPointNumber.setDatatypeClass(TypeClass.FIXED_POINT); fixedPointNumber.setVersion(1); fixedPointNumber .setClassBitField(encodeClassBits(hdf5ByteOrder, loPadBit.orElse(0), hiPadBit.orElse(0), signed)); final int precision = bitPrecision.orElseGet(() -> elementSize.orElseThrow() * 8); fixedPointNumber.setElementSize(elementSize.orElse((precision + 7) / 8)); fixedPointNumber.setBitOffset(bitOffset.orElse(0)); fixedPointNumber.setBitPrecision(precision); return fixedPointNumber; } @Override public FixedPointNumberBuilder withElementSize(final int elementSize) { this.elementSize = OptionalInt.of(elementSize); return this; } @Override public FixedPointNumberBuilder withByteOrder(final HDF5ByteOrder hdf5ByteOrder) { this.hdf5ByteOrder = hdf5ByteOrder; return this; } @Override public FixedPointNumberBuilder withLoPadBit(final int loPadBit) { this.loPadBit = OptionalInt.of(loPadBit); return this; } @Override public FixedPointNumberBuilder withHiPadBit(final int hiPadBit) { this.hiPadBit = OptionalInt.of(hiPadBit); return this; } @Override public FixedPointNumberBuilder signed() { this.signed = true; return this; } @Override public FixedPointNumberBuilder unsigned() { this.signed = false; return this; } @Override public FixedPointNumberBuilder withBitOffset(final int bitOffset) { this.bitOffset = OptionalInt.of(bitOffset); return this; } @Override public FixedPointNumberBuilder withBitPrecision(final int bitPrecision) { this.bitPrecision = OptionalInt.of(bitPrecision); return this; } } }
UTF-8
Java
6,735
java
FixedPointNumberBB.java
Java
[ { "context": "/*\n * Copyright 2020 Keve Müller\n *\n * Licensed under the Apache License, Version ", "end": 32, "score": 0.9998167157173157, "start": 21, "tag": "NAME", "value": "Keve Müller" } ]
null
[]
/* * Copyright 2020 <NAME> * * 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 app.keve.hdf5io.fileformat.level2datatype; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.util.OptionalInt; import app.keve.hdf5io.api.datatype.HDF5FixedPointNumber; import app.keve.hdf5io.fileformat.H5Context; public final class FixedPointNumberBB extends AbstractDatatypeBB implements HDF5FixedPointNumber { private static final int BF_BYTEORDER_MASK = 0x01; private static final int BF_LOPAD_MASK = 0x02; private static final int BF_HIPAD_MASK = 0x04; private static final int BF_SIGNED_MASK = 0x08; public FixedPointNumberBB(final ByteBuffer buf, final H5Context context) { super(buf, context); } @Override public long size() { return 8 + 4; } @Override public HDF5ByteOrder getByteOrder() { return 0 == (getClassBitField() & BF_BYTEORDER_MASK) ? HDF5ByteOrder.LITTLE_ENDIAN : HDF5ByteOrder.BIG_ENDIAN; } @Override public int getLoPadBit() { return 0 == (getClassBitField() & BF_LOPAD_MASK) ? 0 : 1; } @Override public int getHiPadBit() { return 0 == (getClassBitField() & BF_HIPAD_MASK) ? 0 : 1; } @Override public boolean isSigned() { return (getClassBitField() & BF_SIGNED_MASK) > 0; } @Override public int getBitOffset() { return getUnsignedShort(8); } protected void setBitOffset(final int value) { assert value >= 0 && value <= 0xFFFF; setUnsignedShort(8, value); } @Override public int getBitPrecision() { return getUnsignedShort(10); } protected void setBitPrecision(final int value) { assert value >= 0 && value <= 0xFFFF; setUnsignedShort(10, value); } private static int encodeClassBits(final HDF5ByteOrder hdf5ByteOrder, final int loPadBit, final int hiPadBit, final boolean signed) { int classBits = 0; switch (hdf5ByteOrder) { case LITTLE_ENDIAN: classBits |= 0b0; break; case BIG_ENDIAN: classBits |= 0b1; break; default: throw new IllegalArgumentException(); } switch (loPadBit) { case 0: classBits |= 0b00; break; case 1: classBits |= 0b10; break; default: throw new IllegalArgumentException(); } switch (hiPadBit) { case 0: classBits |= 0b000; break; case 1: classBits |= 0b100; break; default: throw new IllegalArgumentException(); } if (signed) { classBits |= 0b1000; } return classBits; } @Override public String toString() { return String.format( "%s, FixedPointNumberBB [size()=%s, getByteOrder()=%s, getLoPadBit()=%s, getHiPadBit()=%s, isSigned()=%s, " + "getBitOffset()=%s, getBitPrecision()=%s]", super.toString(), size(), getByteOrder(), getLoPadBit(), getHiPadBit(), isSigned(), getBitOffset(), getBitPrecision()); } @SuppressWarnings("checkstyle:hiddenfield") public static final class BuilderBB implements FixedPointNumberBuilder { private final H5Context context; private OptionalInt elementSize = OptionalInt.empty(); private HDF5ByteOrder hdf5ByteOrder = HDF5ByteOrder.BIG_ENDIAN; private OptionalInt loPadBit = OptionalInt.empty(); private OptionalInt bitOffset = OptionalInt.empty(); private Boolean signed = true; private OptionalInt hiPadBit = OptionalInt.empty(); private OptionalInt bitPrecision = OptionalInt.empty(); public BuilderBB(final H5Context context) { this.context = context; } @Override public HDF5FixedPointNumber build() { final ByteBuffer buf = ByteBuffer.allocate(8 + 4).order(ByteOrder.LITTLE_ENDIAN); final FixedPointNumberBB fixedPointNumber = new FixedPointNumberBB(buf, context); fixedPointNumber.setDatatypeClass(TypeClass.FIXED_POINT); fixedPointNumber.setVersion(1); fixedPointNumber .setClassBitField(encodeClassBits(hdf5ByteOrder, loPadBit.orElse(0), hiPadBit.orElse(0), signed)); final int precision = bitPrecision.orElseGet(() -> elementSize.orElseThrow() * 8); fixedPointNumber.setElementSize(elementSize.orElse((precision + 7) / 8)); fixedPointNumber.setBitOffset(bitOffset.orElse(0)); fixedPointNumber.setBitPrecision(precision); return fixedPointNumber; } @Override public FixedPointNumberBuilder withElementSize(final int elementSize) { this.elementSize = OptionalInt.of(elementSize); return this; } @Override public FixedPointNumberBuilder withByteOrder(final HDF5ByteOrder hdf5ByteOrder) { this.hdf5ByteOrder = hdf5ByteOrder; return this; } @Override public FixedPointNumberBuilder withLoPadBit(final int loPadBit) { this.loPadBit = OptionalInt.of(loPadBit); return this; } @Override public FixedPointNumberBuilder withHiPadBit(final int hiPadBit) { this.hiPadBit = OptionalInt.of(hiPadBit); return this; } @Override public FixedPointNumberBuilder signed() { this.signed = true; return this; } @Override public FixedPointNumberBuilder unsigned() { this.signed = false; return this; } @Override public FixedPointNumberBuilder withBitOffset(final int bitOffset) { this.bitOffset = OptionalInt.of(bitOffset); return this; } @Override public FixedPointNumberBuilder withBitPrecision(final int bitPrecision) { this.bitPrecision = OptionalInt.of(bitPrecision); return this; } } }
6,729
0.620434
0.605287
209
31.220097
28.022707
123
false
false
0
0
0
0
0
0
0.545455
false
false
1
5dfb2908b6800b6f8d1e3a7df5f7fc9b294113a5
26,723,286,583,526
26ce52ac325b6266e0c3a3ba059c569d5a1f5460
/src/test/java/com/sachin/collaborationbackendsach/C_BlogDAOTestCase.java
07478821275b43a7a203e24d3ab8892e5602c6c6
[]
no_license
sachindhillon/CollaborationProject
https://github.com/sachindhillon/CollaborationProject
647d5934709afdc9f9808e7ced4c23b85c5dd826
87d3ff0eac74cb8bd408ee559305ffb136729e46
refs/heads/master
2020-03-17T18:47:02.332000
2018-07-06T10:26:33
2018-07-06T10:26:33
133,833,275
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.sachin.collaborationbackendsach; import static org.junit.Assert.*; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import com.sachin.project2.dao.C_BlogDAO; import com.sachin.project2.dao.C_JobDAO; import com.sachin.project2.domain.C_Blog; import com.sachin.project2.domain.C_Blog_Comment; import com.sachin.project2.domain.C_Job; import com.sachin.project2.domain.C_Job_Application; public class C_BlogDAOTestCase { private static AnnotationConfigApplicationContext context; @Autowired private static C_BlogDAO c_blogDAO; @Autowired private static C_Blog c_blog; @Autowired private static C_Blog_Comment c_blog_comment; @BeforeClass public static void init() { context = new AnnotationConfigApplicationContext(); context.scan("com.sachin.project2"); context.refresh(); c_blogDAO=(C_BlogDAO) context.getBean("c_blogDAO"); c_blog = (C_Blog) context.getBean("c_blog"); c_blog_comment = (C_Blog_Comment) context.getBean("c_blog_comment"); } @Test public void saveBlogTestCase() { c_blog.setBlog_title("java"); c_blog.setLogin_name("sachin@gmail.com"); c_blog.setBlog_description("javva is a programming language used to develop applications and do many more."); Assert.assertEquals("saveBlogTestCase", true,c_blogDAO.save(c_blog)); } @Test public void updateBlogTestCase() { c_blog=c_blogDAO.get(101); c_blog.setBlog_likes(1); Assert.assertEquals("updateBlogTestCase", true,c_blogDAO.update(c_blog)); } @Test public void getBlogSuccessTestCase() { Assert.assertNotNull(c_blogDAO.get(101)); } @Test public void getBlogFailureTestCase() { C_Blog c_blog=c_blogDAO.get(101); System.out.println(c_blog.getBlog_id()); System.out.println(c_blog.getBlog_description()); Assert.assertNotNull(c_blogDAO.get(102)); } @Test public void getAllBlogs() { Assert.assertEquals(4,c_blogDAO.list().size()); } //to comment on a particular blog @Test public void commentOnBlogTestCase() { c_blog_comment.setLogin_name("sachin@gmail.com"); c_blog_comment.setBlog_id(101); c_blog_comment.setComments("you can do it better"); Assert.assertEquals("commentOnBlogtestCase",true,c_blogDAO.save(c_blog_comment)); } @Test public void commentListOnParticularBlog() { Assert.assertEquals(3,c_blogDAO.list(101).size()); } }
UTF-8
Java
2,483
java
C_BlogDAOTestCase.java
Java
[ { "context": "og.setBlog_title(\"java\");\n\t\tc_blog.setLogin_name(\"sachin@gmail.com\");\n\t\tc_blog.setBlog_description(\"javva is a progr", "end": 1271, "score": 0.999920666217804, "start": 1255, "tag": "EMAIL", "value": "sachin@gmail.com" }, { "context": "BlogTestCase()\n\t{\n\t\tc_blog_comment.setLogin_name(\"sachin@gmail.com\");\n\t\tc_blog_comment.setBlog_id(101);\n\t\tc_blog_com", "end": 2191, "score": 0.9999227523803711, "start": 2175, "tag": "EMAIL", "value": "sachin@gmail.com" } ]
null
[]
package com.sachin.collaborationbackendsach; import static org.junit.Assert.*; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import com.sachin.project2.dao.C_BlogDAO; import com.sachin.project2.dao.C_JobDAO; import com.sachin.project2.domain.C_Blog; import com.sachin.project2.domain.C_Blog_Comment; import com.sachin.project2.domain.C_Job; import com.sachin.project2.domain.C_Job_Application; public class C_BlogDAOTestCase { private static AnnotationConfigApplicationContext context; @Autowired private static C_BlogDAO c_blogDAO; @Autowired private static C_Blog c_blog; @Autowired private static C_Blog_Comment c_blog_comment; @BeforeClass public static void init() { context = new AnnotationConfigApplicationContext(); context.scan("com.sachin.project2"); context.refresh(); c_blogDAO=(C_BlogDAO) context.getBean("c_blogDAO"); c_blog = (C_Blog) context.getBean("c_blog"); c_blog_comment = (C_Blog_Comment) context.getBean("c_blog_comment"); } @Test public void saveBlogTestCase() { c_blog.setBlog_title("java"); c_blog.setLogin_name("<EMAIL>"); c_blog.setBlog_description("javva is a programming language used to develop applications and do many more."); Assert.assertEquals("saveBlogTestCase", true,c_blogDAO.save(c_blog)); } @Test public void updateBlogTestCase() { c_blog=c_blogDAO.get(101); c_blog.setBlog_likes(1); Assert.assertEquals("updateBlogTestCase", true,c_blogDAO.update(c_blog)); } @Test public void getBlogSuccessTestCase() { Assert.assertNotNull(c_blogDAO.get(101)); } @Test public void getBlogFailureTestCase() { C_Blog c_blog=c_blogDAO.get(101); System.out.println(c_blog.getBlog_id()); System.out.println(c_blog.getBlog_description()); Assert.assertNotNull(c_blogDAO.get(102)); } @Test public void getAllBlogs() { Assert.assertEquals(4,c_blogDAO.list().size()); } //to comment on a particular blog @Test public void commentOnBlogTestCase() { c_blog_comment.setLogin_name("<EMAIL>"); c_blog_comment.setBlog_id(101); c_blog_comment.setComments("you can do it better"); Assert.assertEquals("commentOnBlogtestCase",true,c_blogDAO.save(c_blog_comment)); } @Test public void commentListOnParticularBlog() { Assert.assertEquals(3,c_blogDAO.list(101).size()); } }
2,465
0.749497
0.73822
93
25.698925
24.36849
111
false
false
0
0
0
0
0
0
1.526882
false
false
1
97c83338f818434334fdf2415954604c7a2feebf
5,239,860,118,337
af3d37446edeae389d441aecbde2dc552a72aaa2
/src/main/java/es/loyola/iitv/pdm/classes/MessageImpl.java
4410270b07b98ec89502b1d67003f552a615700e
[]
no_license
amorenotalero/BlueFinder
https://github.com/amorenotalero/BlueFinder
f0778ecb2de4a8d1c926bda230803bee5aba37de
3cb97b2bc904fd0eba16c206ce4c4014266e75ad
refs/heads/main
2023-04-11T09:45:29.818000
2021-04-19T16:08:14
2021-04-19T16:08:14
359,518,968
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package es.loyola.iitv.pdm.classes; import java.util.Date; public class MessageImpl implements Message{ private String text; private Date sendDate; private Chat chat; public MessageImpl(String text, Date sendDate, Chat chat) { super(); this.text = text; this.sendDate = sendDate; this.chat = chat; } public String getText() { return text; } public void setText(String text) { this.text = text; } public Date getSendDate() { return sendDate; } public Chat getChat() { return chat; } }
UTF-8
Java
524
java
MessageImpl.java
Java
[]
null
[]
package es.loyola.iitv.pdm.classes; import java.util.Date; public class MessageImpl implements Message{ private String text; private Date sendDate; private Chat chat; public MessageImpl(String text, Date sendDate, Chat chat) { super(); this.text = text; this.sendDate = sendDate; this.chat = chat; } public String getText() { return text; } public void setText(String text) { this.text = text; } public Date getSendDate() { return sendDate; } public Chat getChat() { return chat; } }
524
0.692748
0.692748
32
15.375
14.711284
60
false
false
0
0
0
0
0
0
1.5
false
false
1
eec4d7f7dc7b6dcbfd84d84a6ac0aac21a8782d1
15,908,558,869,853
1098d8ca29f1f094f78458bf75294edc6f784c1e
/generator/src/main/java/com/wildbeeslabs/sensiblemetrics/diffy/generator/service/function/ToIntFunctionGenerator.java
89c6aa494c9561111e29948f9302f786f5a15eb8
[ "MIT" ]
permissive
AlexRogalskiy/Diffy
https://github.com/AlexRogalskiy/Diffy
8e8879a89dbd18ff58ebfbf7e5e663bf5bc0f849
42a03c14d639663387e7b796dca41cb1300ad36b
refs/heads/master
2022-12-08T13:35:07.874000
2019-12-24T19:58:16
2019-12-24T19:58:16
168,051,241
1
2
MIT
false
2022-11-16T12:21:54
2019-01-28T22:52:50
2022-09-06T15:41:14
2022-11-16T12:21:51
2,491
2
2
10
Java
false
false
package com.wildbeeslabs.sensiblemetrics.diffy.generator.service.function; import com.wildbeeslabs.sensiblemetrics.diffy.generator.interfaces.GenerationStatus; import com.wildbeeslabs.sensiblemetrics.diffy.generator.service.ComponentizedGenerator; import com.wildbeeslabs.sensiblemetrics.diffy.generator.service.SourceOfRandomness; import java.util.function.ToIntFunction; import static com.wildbeeslabs.sensiblemetrics.diffy.generator.utils.Lambdas.makeLambda; /** * Produces values of type {@link ToIntFunction}. * * @param <T> type of parameter of produced function */ public class ToIntFunctionGenerator<T> extends ComponentizedGenerator<ToIntFunction> { public ToIntFunctionGenerator() { super(ToIntFunction.class); } @SuppressWarnings("unchecked") @Override public ToIntFunction<T> generate(SourceOfRandomness random, GenerationStatus status) { return makeLambda(ToIntFunction.class, gen().type(int.class), status); } @Override public int numberOfNeededComponents() { return 1; } }
UTF-8
Java
1,058
java
ToIntFunctionGenerator.java
Java
[]
null
[]
package com.wildbeeslabs.sensiblemetrics.diffy.generator.service.function; import com.wildbeeslabs.sensiblemetrics.diffy.generator.interfaces.GenerationStatus; import com.wildbeeslabs.sensiblemetrics.diffy.generator.service.ComponentizedGenerator; import com.wildbeeslabs.sensiblemetrics.diffy.generator.service.SourceOfRandomness; import java.util.function.ToIntFunction; import static com.wildbeeslabs.sensiblemetrics.diffy.generator.utils.Lambdas.makeLambda; /** * Produces values of type {@link ToIntFunction}. * * @param <T> type of parameter of produced function */ public class ToIntFunctionGenerator<T> extends ComponentizedGenerator<ToIntFunction> { public ToIntFunctionGenerator() { super(ToIntFunction.class); } @SuppressWarnings("unchecked") @Override public ToIntFunction<T> generate(SourceOfRandomness random, GenerationStatus status) { return makeLambda(ToIntFunction.class, gen().type(int.class), status); } @Override public int numberOfNeededComponents() { return 1; } }
1,058
0.776938
0.775992
31
33.129032
33.754086
90
false
false
0
0
0
0
0
0
0.387097
false
false
1
60f80a86ce40d9e5fd8800065eeef9dd654743e2
14,757,507,696,661
bbd101601a2539c6dbb45824c7fde1be77313fa3
/app/src/main/java/com/playground/renan/playground/pojo/MenuItem.java
3a1fd7257accfe5347bb6b088ab49272191c78fd
[]
no_license
soulnanx/Playground
https://github.com/soulnanx/Playground
ca6d44778d5bc4e1ef6c8e5b15b1ec5ca49e1125
7a050e31d0ed9cdf1b4e82ac639f6879b3d1f087
refs/heads/master
2020-07-02T00:46:27.628000
2015-03-17T13:21:51
2015-03-17T13:21:51
30,617,763
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.playground.renan.playground.pojo; import com.playground.renan.playground.R; import com.playground.renan.playground.ui.fragment.CallbackFragment; import com.playground.renan.playground.ui.fragment.NotificationFragment; import java.util.ArrayList; public class MenuItem { private String fragmentName; private int label; private int icon; private MenuItem(Class fragment) { this.fragmentName = fragment.getName(); try { this.label = fragment.getDeclaredField("NAME_ITEM").getInt(Integer.class); this.icon = fragment.getDeclaredField("ICON_ITEM").getInt(Integer.class); } catch (Exception e) { this.label = R.string.default_item_menu; this.icon = android.R.drawable.ic_media_play; } } public static ArrayList<MenuItem> getItemsMenu(){ ArrayList<MenuItem> list = new ArrayList<MenuItem>(); list.add(new MenuItem(CallbackFragment.class)); list.add(new MenuItem(NotificationFragment.class)); list.add(new MenuItem(CallbackFragment.class)); return list; } public String getFragmentName() { return fragmentName; } public int getLabel() { return label; } public int getIcon() { return icon; } }
UTF-8
Java
1,307
java
MenuItem.java
Java
[]
null
[]
package com.playground.renan.playground.pojo; import com.playground.renan.playground.R; import com.playground.renan.playground.ui.fragment.CallbackFragment; import com.playground.renan.playground.ui.fragment.NotificationFragment; import java.util.ArrayList; public class MenuItem { private String fragmentName; private int label; private int icon; private MenuItem(Class fragment) { this.fragmentName = fragment.getName(); try { this.label = fragment.getDeclaredField("NAME_ITEM").getInt(Integer.class); this.icon = fragment.getDeclaredField("ICON_ITEM").getInt(Integer.class); } catch (Exception e) { this.label = R.string.default_item_menu; this.icon = android.R.drawable.ic_media_play; } } public static ArrayList<MenuItem> getItemsMenu(){ ArrayList<MenuItem> list = new ArrayList<MenuItem>(); list.add(new MenuItem(CallbackFragment.class)); list.add(new MenuItem(NotificationFragment.class)); list.add(new MenuItem(CallbackFragment.class)); return list; } public String getFragmentName() { return fragmentName; } public int getLabel() { return label; } public int getIcon() { return icon; } }
1,307
0.662586
0.662586
49
25.67347
25.12937
86
false
false
0
0
0
0
0
0
0.428571
false
false
1
eb31c6e65bbe947ebd1bf38b4d31f87a26801d8f
21,835,613,733,082
692bb6e62b92508b8d97a165fa20d47aace485ce
/Coding_Challenge/src/ScrollingDemonstration.java
deab22636eafd8fa6f2ce4eb6342240924f8369d
[]
no_license
bladerjam7/Coding-Challenge
https://github.com/bladerjam7/Coding-Challenge
70f2f5e9544b4a86c77b79ecaebb84be291ae851
0b93488ae716738f08e708dae035c13168a4f985
refs/heads/master
2020-06-26T20:04:39.144000
2019-07-31T14:00:29
2019-07-31T14:00:29
199,742,074
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.util.concurrent.TimeUnit; import org.junit.Test; import org.openqa.selenium.By; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; public class ScrollingDemonstration { WebDriver driver; @Test public void ScrollingTest() throws InterruptedException { driver = new FirefoxDriver(); JavascriptExecutor js = (JavascriptExecutor) driver; // Launch the application driver.get("http://www.biochem.emory.edu/seyfried/people/index.html"); driver.manage().timeouts().implicitlyWait(100, TimeUnit.SECONDS); // scroll down till the element is found //js.executeScript("scroll(0, 2000)"); for (int second = 0;; second++) { if(second >=500){ break; } ((JavascriptExecutor) driver).executeScript("window.scrollBy(0,3)"); //y value '400' can be altered Thread.sleep(1); } for (int second = 0;; second++) { if(second >=500){ break; } ((JavascriptExecutor) driver).executeScript("window.scrollBy(0,-3)"); //y value '400' can be altered Thread.sleep(1); } /**********************************************************************************/ /***** ******/ /***** My picture is all the way at the bottom of the page ******/ /***** ******/ /**********************************************************************************/ for (int second = 0;; second++) { if(second >=350){ break; } ((JavascriptExecutor) driver).executeScript("window.scrollBy(0,10)"); //y value '400' can be altered Thread.sleep(1); } } }
UTF-8
Java
1,914
java
ScrollingDemonstration.java
Java
[ { "context": "ation\r\n\t\tdriver.get(\"http://www.biochem.emory.edu/seyfried/people/index.html\");\t\t\t\r\n\t\t\r\n\t\tdriver.manage().ti", "end": 590, "score": 0.8941786885261536, "start": 582, "tag": "USERNAME", "value": "seyfried" } ]
null
[]
import java.util.concurrent.TimeUnit; import org.junit.Test; import org.openqa.selenium.By; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; public class ScrollingDemonstration { WebDriver driver; @Test public void ScrollingTest() throws InterruptedException { driver = new FirefoxDriver(); JavascriptExecutor js = (JavascriptExecutor) driver; // Launch the application driver.get("http://www.biochem.emory.edu/seyfried/people/index.html"); driver.manage().timeouts().implicitlyWait(100, TimeUnit.SECONDS); // scroll down till the element is found //js.executeScript("scroll(0, 2000)"); for (int second = 0;; second++) { if(second >=500){ break; } ((JavascriptExecutor) driver).executeScript("window.scrollBy(0,3)"); //y value '400' can be altered Thread.sleep(1); } for (int second = 0;; second++) { if(second >=500){ break; } ((JavascriptExecutor) driver).executeScript("window.scrollBy(0,-3)"); //y value '400' can be altered Thread.sleep(1); } /**********************************************************************************/ /***** ******/ /***** My picture is all the way at the bottom of the page ******/ /***** ******/ /**********************************************************************************/ for (int second = 0;; second++) { if(second >=350){ break; } ((JavascriptExecutor) driver).executeScript("window.scrollBy(0,10)"); //y value '400' can be altered Thread.sleep(1); } } }
1,914
0.510972
0.490596
67
26.567163
29.355883
113
false
false
0
0
0
0
0
0
2.432836
false
false
1
60ab165946f397665ab2e12b69a9ab991ca98b90
14,663,018,364,678
b0c33dc40789de5495f0fe9e81b8f4e3d38388bf
/src/main/java/ru/opensolutions/fortune/configuration/validation/ValidationConfig.java
8342777128d5d252e7e12114215bb4f75849ba26
[]
no_license
vladislav-chunikhin/waves
https://github.com/vladislav-chunikhin/waves
b260556a9cf94a4d15184e4058f5b7287764c8b4
21e5aa8363405dcec9b8c2aa17af0db7473f4117
refs/heads/master
2023-03-14T14:23:48.630000
2019-08-20T15:49:41
2019-08-20T15:49:41
344,703,973
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ru.opensolutions.fortune.configuration.validation; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import ru.opensolutions.fortune.util.MessageUtils; import ru.opensolutions.fortune.util.enums.AuthOptionType; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; /** * Валидация настроек приложения. */ @Configuration public class ValidationConfig { /** * Настройка по включению | выключению авторизации в проекте. */ @Value("${auth.switch}") private String authSwitcher; /** * Проверка значений для файл свойств. */ @Bean public void checkAppProperties() { final List<String> allOptions = Arrays .stream(AuthOptionType.values()) .map(AuthOptionType::getName) .collect(Collectors.toList()); final boolean isValidOption = allOptions.contains(authSwitcher); if (!isValidOption) { throw new IllegalArgumentException( MessageUtils.getMessage("auth.switch.exception", allOptions, authSwitcher)); } } }
UTF-8
Java
1,321
java
ValidationConfig.java
Java
[]
null
[]
package ru.opensolutions.fortune.configuration.validation; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import ru.opensolutions.fortune.util.MessageUtils; import ru.opensolutions.fortune.util.enums.AuthOptionType; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; /** * Валидация настроек приложения. */ @Configuration public class ValidationConfig { /** * Настройка по включению | выключению авторизации в проекте. */ @Value("${auth.switch}") private String authSwitcher; /** * Проверка значений для файл свойств. */ @Bean public void checkAppProperties() { final List<String> allOptions = Arrays .stream(AuthOptionType.values()) .map(AuthOptionType::getName) .collect(Collectors.toList()); final boolean isValidOption = allOptions.contains(authSwitcher); if (!isValidOption) { throw new IllegalArgumentException( MessageUtils.getMessage("auth.switch.exception", allOptions, authSwitcher)); } } }
1,321
0.701235
0.701235
37
31.837837
24.513111
96
false
false
0
0
0
0
0
0
0.432432
false
false
1
6774da34fd3d8ef6398b3d83230870035553b7f6
21,930,103,050,419
c54205f630588a9cb782858f738b535518050de5
/Práctica 3/Prim.java
bb2dc1efc20dba8c25330d4751273e9947112123
[]
no_license
JessHG04/EDA
https://github.com/JessHG04/EDA
26efaffe7b34d274e6b1c289653fd40d918d486b
313382c6562b6f1f0c943b642e7f715450c66e8f
refs/heads/master
2022-11-12T00:44:09.027000
2020-07-01T14:31:25
2020-07-01T14:31:25
243,062,088
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
//23900715N HERNANDEZ GOMEZ, JESSICA import java.util.*; public class Prim { public static void main(String[] args) { Coleccion colec = new Coleccion(); if(args.length == 2){ if(args[0]!= null){ colec.lectura(args[0]); } } } }
UTF-8
Java
311
java
Prim.java
Java
[ { "context": "//23900715N HERNANDEZ GOMEZ, JESSICA\r\nimport java.util.*;\r\npublic class Prim ", "end": 27, "score": 0.9998184442520142, "start": 12, "tag": "NAME", "value": "HERNANDEZ GOMEZ" }, { "context": "//23900715N HERNANDEZ GOMEZ, JESSICA\r\nimport java.util.*;\r\npublic class Prim {\r\n pu", "end": 36, "score": 0.8064616322517395, "start": 29, "tag": "NAME", "value": "JESSICA" } ]
null
[]
//23900715N <NAME>, JESSICA import java.util.*; public class Prim { public static void main(String[] args) { Coleccion colec = new Coleccion(); if(args.length == 2){ if(args[0]!= null){ colec.lectura(args[0]); } } } }
302
0.501608
0.466238
12
23.916666
14.297193
44
false
false
0
0
0
0
0
0
0.333333
false
false
1
4b28aa4e5b542a374623d59f23c01af8e0d2adcf
1,511,828,533,751
bd04f3680f533e727a99f2c02d030419558b0ea6
/plugin/it.polimi.dice.verification.uml2json/src/it/polimi/dice/verification/uml/diagrams/classdiagram/Spout.java
da2fe7b80cbb9b2d22cbfc488186c6e1ac8f810f
[ "Apache-2.0" ]
permissive
dice-project/DICE-Verification
https://github.com/dice-project/DICE-Verification
487becf66d477c0e1c0fde25d9dd442ddc942c04
bd180043b9a0f75d2dbe32fe5106f1975704fec7
refs/heads/master
2021-04-22T12:12:05.886000
2017-10-03T12:00:29
2017-10-03T12:00:29
49,935,312
0
1
null
false
2017-04-02T05:34:47
2016-01-19T07:40:31
2017-03-03T12:35:29
2017-04-02T05:34:47
7,133
0
0
0
Common Lisp
null
null
package it.polimi.dice.verification.uml.diagrams.classdiagram; import org.eclipse.uml2.uml.Classifier; import org.eclipse.uml2.uml.InstanceSpecification; import it.polimi.dice.verification.uml.helpers.UML2ModelHelper; public class Spout { private InstanceSpecification umlSpout; public Spout(org.eclipse.uml2.uml.InstanceSpecification c) { this.umlSpout=c; } public String getName() { return umlSpout.getName(); } /** Do not use if you do not know what are you doing **/ public InstanceSpecification getUMLSpout(){ return umlSpout; } public int getParallelism() { Classifier umlSpoutType=umlSpout.getClassifiers().get(0); int parallelism= (Integer)umlSpout.getClassifiers().get(0).getValue(UML2ModelHelper.getStereotype(umlSpoutType, "Spout"), "parallelism"); return parallelism; } public int getAverageEmitRate() { Classifier umlSpoutType=umlSpout.getClassifiers().get(0); int avgEmitRate= (Integer)umlSpout.getClassifiers().get(0).getValue(UML2ModelHelper.getStereotype(umlSpoutType, "Spout"), "avg_emit_rate"); return avgEmitRate; } }
UTF-8
Java
1,083
java
Spout.java
Java
[]
null
[]
package it.polimi.dice.verification.uml.diagrams.classdiagram; import org.eclipse.uml2.uml.Classifier; import org.eclipse.uml2.uml.InstanceSpecification; import it.polimi.dice.verification.uml.helpers.UML2ModelHelper; public class Spout { private InstanceSpecification umlSpout; public Spout(org.eclipse.uml2.uml.InstanceSpecification c) { this.umlSpout=c; } public String getName() { return umlSpout.getName(); } /** Do not use if you do not know what are you doing **/ public InstanceSpecification getUMLSpout(){ return umlSpout; } public int getParallelism() { Classifier umlSpoutType=umlSpout.getClassifiers().get(0); int parallelism= (Integer)umlSpout.getClassifiers().get(0).getValue(UML2ModelHelper.getStereotype(umlSpoutType, "Spout"), "parallelism"); return parallelism; } public int getAverageEmitRate() { Classifier umlSpoutType=umlSpout.getClassifiers().get(0); int avgEmitRate= (Integer)umlSpout.getClassifiers().get(0).getValue(UML2ModelHelper.getStereotype(umlSpoutType, "Spout"), "avg_emit_rate"); return avgEmitRate; } }
1,083
0.768236
0.759003
39
26.76923
34.35371
141
false
false
0
0
0
0
0
0
1.307692
false
false
1
aee126c29ae8fe5e1c314699ae2ff1d592334298
9,397,388,461,731
fd414b72fa69b666b669ad1f4c357795ef7ce27c
/src/main/java/com/forecasting/models/utils/AccuracyIndicators.java
93ac66edc9e10403dc95f021ef3b1b1fb74a95dd
[]
no_license
skalva404/forecasting
https://github.com/skalva404/forecasting
707eb6ec516b6d46643eee466f753e39d6cabd5f
75bc15b12c4b36b12a3972213842b8311821cd48
refs/heads/master
2020-08-30T19:17:18.370000
2019-10-30T07:25:06
2019-10-30T07:25:06
218,466,941
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package com.forecasting.models.utils; /** * A simple Java Bean that gathers together in one class all current "accuracy * indicators" for a given forecasting model. Currently, the supported * measurements of accuracy of a forecasting model supported by this class * include: * <ul> * <li>AIC - or the Akaike Information Criteria value</li> * <li>bias - or the mean error</li> * <li>MAD - or the Mean Absolute Deviation</li> * <li>MAPE - or the Mean Absolute Percentage Error</li> * <li>MSE - or the Mean Square of the Error</li> * <li>SAE - or the Sum of the Absolute Errors</li> * </ul> * * @author Steven R. Gould * @since 0.3 */ public class AccuracyIndicators { /** * Kullback–Leibler Information Criteria measure. */ private double klic; /** * Akaike Information Criteria measure. */ private double bic; /** * Bayesian Information Criteria measure. */ private double aic; /** * Arithmetic mean of the errors. */ private double bias; /** * Mean Absolute Deviation. */ private double mad; /** * Mean Absolute Percentage Error. */ private double mape; /** * Mean Square of the Error. */ private double mse; /** * Sum of the Absolute Errors. */ private double sae; /** * array of errors on validaiton points */ private double[] validationErrors; /** * directionalError */ private double directionalError; /** * directionalError Matrix */ private double[] directionalErrorMatrix; /** * Default constructor. Initializes all accuracy indicators to their * "worst" possible values - generally this means some large number, * indicating "very" inaccurate. */ public AccuracyIndicators() { aic = bias = mad = mape = mse = sae = Double.MAX_VALUE; } /** * Returns the AIC for the associated forecasting model. * * @return the AIC. */ public double getAIC() { return aic; } /** * Sets the AIC for the associated forecasting model to the given value. * * @param aic the new value for the AIC. */ public void setAIC(double aic) { this.aic = aic; } /** * Returns the bias for the associated forecasting model. * * @return the bias. */ public double getBias() { return bias; } /** * Sets the bias for the associated forecasting model to the given value. * * @param bias the new value for the bias. */ public void setBias(double bias) { this.bias = bias; } public double[] getDirectionalErrorMatrix() { return directionalErrorMatrix; } public void setDirectionalErrorMatrix(double[] directionalErrorMatrix) { this.directionalErrorMatrix = directionalErrorMatrix; } /** * Returns the Mean Absolute Deviation (MAD) for the associated * forecasting model to the given value. * * @return the Mean Absolute Deviation. */ public double getMAD() { return mad; } /** * Sets the Mean Absolute Deviation (MAD) for the associated forecasting * model. That is, the <code>SUM( abs(actual-forecast) ) / n</code> for * the initial data set. * * @param mad the new value for the Mean Absolute Deviation. */ public void setMAD(double mad) { this.mad = mad; } /** * Returns the Mean Absolute Percentage Error (MAPE) for the associated * forecasting model. That is, the * <code>SUM( 100% . abs(actual-forecast)/actual ) / n</code> for the * initial data set. * * @return the Mean Absolute Percentage Error. */ public double getMAPE() { return mape; } /** * Sets the Mean Absolute Percentage Error (MAPE) for the associated * forecasting model to the given value. * * @param mape the new value for the Mean Absolute Percentage Error. */ public void setMAPE(double mape) { this.mape = mape; } /** * Returns the Mean Square of the Errors (MSE) for the associated * forecasting model. That is, the * <code>SUM( (actual-forecast)^2 ) / n</code> for the initial data set. * * @return the Mean Square of the Errors. */ public double getMSE() { return mse; } /** * Sets the Mean Square of the Errors (MSE) for the associated * forecasting model to the new value. * * @param mse the new value for the Mean Square of the Errors. */ public void setMSE(double mse) { this.mse = mse; } /** * Returns the Sum of the Absolute Errors (SAE) for the associated * forecasting model. That is, the * <code>SUM( abs(actual-forecast) )</code> for the initial data set. * * @return the Mean Absolute Deviation. */ public double getSAE() { return sae; } /** * Sets the Sum of the Absolute Errors (SAE) for the associated * forecasting model to the new value. * * @return the new value for the Mean Absolute Deviation. */ public void setSAE(double sae) { this.sae = sae; } /** * Returns a string containing the accuracy indicators and their values. * Overridden to provide some useful output for debugging. * * @return a string containing the accuracy indicators and their values. */ public String toString() { return " MAPE = " + mape + " , MSE = " + mse + " , AIC = " + aic + " , BIC = " + bic + " , Directional Error = " + directionalError + " , Biasness = " + bias; } public double getKlic() { return klic; } public void setKlic(double klic) { this.klic = klic; } public double[] getValidationErrors() { return validationErrors; } public void setValidationErrors(double[] validationErrors) { this.validationErrors = validationErrors; } public double getDirectionalError() { return directionalError; } public void setDirectionalError(double directionalError) { this.directionalError = directionalError; } public double getBic() { return bic; } public void setBic(double bic) { this.bic = bic; } }
UTF-8
Java
7,271
java
AccuracyIndicators.java
Java
[ { "context": "of the Absolute Errors</li>\n * </ul>\n *\n * @author Steven R. Gould\n * @since 0.3\n */\npublic class AccuracyIndicators", "end": 1436, "score": 0.9998686909675598, "start": 1421, "tag": "NAME", "value": "Steven R. Gould" } ]
null
[]
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package com.forecasting.models.utils; /** * A simple Java Bean that gathers together in one class all current "accuracy * indicators" for a given forecasting model. Currently, the supported * measurements of accuracy of a forecasting model supported by this class * include: * <ul> * <li>AIC - or the Akaike Information Criteria value</li> * <li>bias - or the mean error</li> * <li>MAD - or the Mean Absolute Deviation</li> * <li>MAPE - or the Mean Absolute Percentage Error</li> * <li>MSE - or the Mean Square of the Error</li> * <li>SAE - or the Sum of the Absolute Errors</li> * </ul> * * @author <NAME> * @since 0.3 */ public class AccuracyIndicators { /** * Kullback–Leibler Information Criteria measure. */ private double klic; /** * Akaike Information Criteria measure. */ private double bic; /** * Bayesian Information Criteria measure. */ private double aic; /** * Arithmetic mean of the errors. */ private double bias; /** * Mean Absolute Deviation. */ private double mad; /** * Mean Absolute Percentage Error. */ private double mape; /** * Mean Square of the Error. */ private double mse; /** * Sum of the Absolute Errors. */ private double sae; /** * array of errors on validaiton points */ private double[] validationErrors; /** * directionalError */ private double directionalError; /** * directionalError Matrix */ private double[] directionalErrorMatrix; /** * Default constructor. Initializes all accuracy indicators to their * "worst" possible values - generally this means some large number, * indicating "very" inaccurate. */ public AccuracyIndicators() { aic = bias = mad = mape = mse = sae = Double.MAX_VALUE; } /** * Returns the AIC for the associated forecasting model. * * @return the AIC. */ public double getAIC() { return aic; } /** * Sets the AIC for the associated forecasting model to the given value. * * @param aic the new value for the AIC. */ public void setAIC(double aic) { this.aic = aic; } /** * Returns the bias for the associated forecasting model. * * @return the bias. */ public double getBias() { return bias; } /** * Sets the bias for the associated forecasting model to the given value. * * @param bias the new value for the bias. */ public void setBias(double bias) { this.bias = bias; } public double[] getDirectionalErrorMatrix() { return directionalErrorMatrix; } public void setDirectionalErrorMatrix(double[] directionalErrorMatrix) { this.directionalErrorMatrix = directionalErrorMatrix; } /** * Returns the Mean Absolute Deviation (MAD) for the associated * forecasting model to the given value. * * @return the Mean Absolute Deviation. */ public double getMAD() { return mad; } /** * Sets the Mean Absolute Deviation (MAD) for the associated forecasting * model. That is, the <code>SUM( abs(actual-forecast) ) / n</code> for * the initial data set. * * @param mad the new value for the Mean Absolute Deviation. */ public void setMAD(double mad) { this.mad = mad; } /** * Returns the Mean Absolute Percentage Error (MAPE) for the associated * forecasting model. That is, the * <code>SUM( 100% . abs(actual-forecast)/actual ) / n</code> for the * initial data set. * * @return the Mean Absolute Percentage Error. */ public double getMAPE() { return mape; } /** * Sets the Mean Absolute Percentage Error (MAPE) for the associated * forecasting model to the given value. * * @param mape the new value for the Mean Absolute Percentage Error. */ public void setMAPE(double mape) { this.mape = mape; } /** * Returns the Mean Square of the Errors (MSE) for the associated * forecasting model. That is, the * <code>SUM( (actual-forecast)^2 ) / n</code> for the initial data set. * * @return the Mean Square of the Errors. */ public double getMSE() { return mse; } /** * Sets the Mean Square of the Errors (MSE) for the associated * forecasting model to the new value. * * @param mse the new value for the Mean Square of the Errors. */ public void setMSE(double mse) { this.mse = mse; } /** * Returns the Sum of the Absolute Errors (SAE) for the associated * forecasting model. That is, the * <code>SUM( abs(actual-forecast) )</code> for the initial data set. * * @return the Mean Absolute Deviation. */ public double getSAE() { return sae; } /** * Sets the Sum of the Absolute Errors (SAE) for the associated * forecasting model to the new value. * * @return the new value for the Mean Absolute Deviation. */ public void setSAE(double sae) { this.sae = sae; } /** * Returns a string containing the accuracy indicators and their values. * Overridden to provide some useful output for debugging. * * @return a string containing the accuracy indicators and their values. */ public String toString() { return " MAPE = " + mape + " , MSE = " + mse + " , AIC = " + aic + " , BIC = " + bic + " , Directional Error = " + directionalError + " , Biasness = " + bias; } public double getKlic() { return klic; } public void setKlic(double klic) { this.klic = klic; } public double[] getValidationErrors() { return validationErrors; } public void setValidationErrors(double[] validationErrors) { this.validationErrors = validationErrors; } public double getDirectionalError() { return directionalError; } public void setDirectionalError(double directionalError) { this.directionalError = directionalError; } public double getBic() { return bic; } public void setBic(double bic) { this.bic = bic; } }
7,262
0.612464
0.611088
280
24.964285
23.783821
78
false
false
0
0
0
0
0
0
0.185714
false
false
1
5e5aba0b19924dd702130d667b1173c327198519
18,571,438,598,973
1d489a68c4f7fada86dff1693ce4a373e8739f7c
/JavaVituralMachine/src/main/java/com/li/chapter12/InstructionReordering.java
55f6b17619281ea440a54d99971cb091a193772b
[]
no_license
1367356/GradleTestUseSubModule
https://github.com/1367356/GradleTestUseSubModule
730b9fe2f76c90697ef62cc9e001b4c8e0b35801
287bdd2df30788d95b925450a4475dda61ceaf69
refs/heads/master
2021-04-26T23:05:31.885000
2018-10-01T08:38:37
2018-10-01T08:38:37
123,929,145
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.li.chapter12; import java.util.Map; /** * 指令重排序 */ public class InstructionReordering { Map configOptions; char[] configText; //此变量必须定义为volatile volatile boolean initialized=false; //假设以下代码在线程A中执行 //模拟读取配置信息,当读取完成后将initialized 设置为true以通知其它线程配置可用 public static void main(String[] args){ } }
UTF-8
Java
450
java
InstructionReordering.java
Java
[]
null
[]
package com.li.chapter12; import java.util.Map; /** * 指令重排序 */ public class InstructionReordering { Map configOptions; char[] configText; //此变量必须定义为volatile volatile boolean initialized=false; //假设以下代码在线程A中执行 //模拟读取配置信息,当读取完成后将initialized 设置为true以通知其它线程配置可用 public static void main(String[] args){ } }
450
0.702941
0.697059
19
16.894737
16.114376
52
false
false
0
0
0
0
0
0
0.263158
false
false
1
a771a77579ef392e55a9dfb2bf4365768ad15dc6
23,313,082,494,599
b146143fc14ddf0e4d3436326c70b6e0bc2707ec
/JavaEE/JDK8/src/com/jorge/jdk8/Test7_Consumer.java
ed17405a4733cbfcc64f5dad8957366a4af68a89
[]
no_license
string-jorge/Java
https://github.com/string-jorge/Java
ed4444b9f089fec500fee0d03ec89e46be4a30b3
f3fe14de95a523ed1f164730e43beea08ffa4152
refs/heads/master
2021-07-02T18:59:19.153000
2019-05-29T11:30:29
2019-05-29T11:30:29
182,716,806
3
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.jorge.jdk8; //Consumer接口是消费型接口,泛型指定什么类型,使用accept方法消费(使用)什么类型的数据 // accept方法 import java.util.function.Consumer; public class Test7_Consumer { public static void method(String name, Consumer<String> con) { con.accept(name); } //消费方式,直接输出 public static void main(String[] args) { method("张三",(String name) -> { //直接输出 System.out.println("我的名字是:" + name); //反转姓名 String rename = new StringBuilder(name).reverse().toString(); System.out.println("反转后的名字是:" + rename); }); } }
UTF-8
Java
722
java
Test7_Consumer.java
Java
[]
null
[]
package com.jorge.jdk8; //Consumer接口是消费型接口,泛型指定什么类型,使用accept方法消费(使用)什么类型的数据 // accept方法 import java.util.function.Consumer; public class Test7_Consumer { public static void method(String name, Consumer<String> con) { con.accept(name); } //消费方式,直接输出 public static void main(String[] args) { method("张三",(String name) -> { //直接输出 System.out.println("我的名字是:" + name); //反转姓名 String rename = new StringBuilder(name).reverse().toString(); System.out.println("反转后的名字是:" + rename); }); } }
722
0.592282
0.588926
25
22.84
21.993963
73
false
false
0
0
0
0
0
0
0.48
false
false
1
190c2cec2d1f5a6efe5a83740713a382041e25be
1,099,511,653,127
47980146e4c365b387cd23c209d03baac592c2ea
/kr.co.pk.0702Class/src/method1/job.java
5a9dfca43f058c14e6949bfd5c21c240043c5bd8
[]
no_license
JOAL0818/javaFirst
https://github.com/JOAL0818/javaFirst
d2d81df00220e9bf643ec063d9fc7727ae35a51b
48d93d5307fd826d62d6a9affddd09efd174d7d0
refs/heads/master
2020-03-22T05:14:04.317000
2018-10-23T09:37:00
2018-10-23T09:37:00
139,551,533
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package method1; public class job { // 메소드의 결과형 앞에 static을 붙이면 클래스가 호출가능한 메소드가 됩니다. public static void display() { System.out.println("static 메소드"); } // 매개변수가 value형인경우 -call by valuse // 원본데이터 변경불가 public static void incValue(int n) { n = n + 1; } // 매개변수가 reference형인경우-call by reference // 원본데이터 변경가능 public static void incReference(int[] n) { n[0] = n[0] + 1; } // 재귀함수 만들기 // if(중단조건) return 중단햇을 때의 값 // else 재귀함수를 호출 // 예) 1-n까지의 합을 재귀를 이용해서 리턴해주는 함수 public int sum(int n) { if (n == 1) { return 1; } else { return n + sum(n - 1); } } // 1) 재귀함수 사용x public int fiboNoRecursion(int n) { int n1 = 1; int n2 = 1; int result = 1; for (int i = 3; i < n + 1; i = i + 1) { result = n1 + n2; n1 = n2; n2 = result; } return result; } // 2) 재귀함수 사용 public int fiboRecusion(int n) { if (n == 1 || n == 2) { return 1; } else { return fiboRecusion(n - 1) + fiboRecusion(n - 2); } } }
UTF-8
Java
1,276
java
job.java
Java
[]
null
[]
package method1; public class job { // 메소드의 결과형 앞에 static을 붙이면 클래스가 호출가능한 메소드가 됩니다. public static void display() { System.out.println("static 메소드"); } // 매개변수가 value형인경우 -call by valuse // 원본데이터 변경불가 public static void incValue(int n) { n = n + 1; } // 매개변수가 reference형인경우-call by reference // 원본데이터 변경가능 public static void incReference(int[] n) { n[0] = n[0] + 1; } // 재귀함수 만들기 // if(중단조건) return 중단햇을 때의 값 // else 재귀함수를 호출 // 예) 1-n까지의 합을 재귀를 이용해서 리턴해주는 함수 public int sum(int n) { if (n == 1) { return 1; } else { return n + sum(n - 1); } } // 1) 재귀함수 사용x public int fiboNoRecursion(int n) { int n1 = 1; int n2 = 1; int result = 1; for (int i = 3; i < n + 1; i = i + 1) { result = n1 + n2; n1 = n2; n2 = result; } return result; } // 2) 재귀함수 사용 public int fiboRecusion(int n) { if (n == 1 || n == 2) { return 1; } else { return fiboRecusion(n - 1) + fiboRecusion(n - 2); } } }
1,276
0.533138
0.504873
59
15.389831
14.216268
52
false
false
0
0
0
0
0
0
1.627119
false
false
1
4e2e6ae9c8c88989f75345fe1d66d1e09e2942a7
1,099,511,654,068
f90b64c1d043b1a246edecdaba81929a4fe39171
/backend/JavaWebService/src/main/java/com/kainos/ea/controllers/CapabilitiesController.java
f29234ad689b370589c03bf0313981acebd2e897
[]
no_license
AmamMcMam/Team-A-Agile
https://github.com/AmamMcMam/Team-A-Agile
0e2b737e6083f923ed7a3668911d2b14c753c959
d59069488f0948109a5650d7e016bf74481836cc
refs/heads/main
2023-07-29T02:26:30.185000
2021-09-09T14:48:03
2021-09-09T14:48:03
399,105,725
0
0
null
false
2021-09-09T14:48:04
2021-08-23T13:03:19
2021-09-03T16:01:05
2021-09-09T14:48:03
876
0
0
0
Java
false
false
package com.kainos.ea.controllers; import com.kainos.ea.models.Capability; import com.kainos.ea.models.Role; import com.kainos.ea.services.CapabilitiesService; import io.swagger.annotations.Api; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import java.util.List; @Api @Path("/api") public class CapabilitiesController { private CapabilitiesService service; public CapabilitiesController(CapabilitiesService service){ this.service = service; } @GET @Path("/capabilities") @Produces(MediaType.APPLICATION_JSON) public List<Capability> getCapabilities(){ return service.getCapabilities(); } @GET @Path("/capabilities/{capabilityId}") @Produces(MediaType.APPLICATION_JSON) public List<Role> getRolesForCapability(@PathParam("capabilityId") int capabilityId){ return service.rolesPerCapability(capabilityId); } @GET @Path("/capabilities/{capabilityId}/lead") @Produces(MediaType.APPLICATION_JSON) public Capability getLeadPerCapability(@PathParam("capabilityId") int capabilityId){ return service.getLeadPerCapability(capabilityId); } }
UTF-8
Java
1,241
java
CapabilitiesController.java
Java
[]
null
[]
package com.kainos.ea.controllers; import com.kainos.ea.models.Capability; import com.kainos.ea.models.Role; import com.kainos.ea.services.CapabilitiesService; import io.swagger.annotations.Api; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import java.util.List; @Api @Path("/api") public class CapabilitiesController { private CapabilitiesService service; public CapabilitiesController(CapabilitiesService service){ this.service = service; } @GET @Path("/capabilities") @Produces(MediaType.APPLICATION_JSON) public List<Capability> getCapabilities(){ return service.getCapabilities(); } @GET @Path("/capabilities/{capabilityId}") @Produces(MediaType.APPLICATION_JSON) public List<Role> getRolesForCapability(@PathParam("capabilityId") int capabilityId){ return service.rolesPerCapability(capabilityId); } @GET @Path("/capabilities/{capabilityId}/lead") @Produces(MediaType.APPLICATION_JSON) public Capability getLeadPerCapability(@PathParam("capabilityId") int capabilityId){ return service.getLeadPerCapability(capabilityId); } }
1,241
0.737309
0.737309
44
27.204546
22.904524
89
false
false
0
0
0
0
0
0
0.363636
false
false
1
d0a48c044ea9d8d938919f0acaf82c7e636e5762
36,086,315,229,940
677bc3ca4b177afb6f9da6a12f999c7fff9984fb
/ochko/src/main/java/com/alegerd/Ochko/Interfaces/Observable.java
5e686dd41a9b5890be0b76879edc718651d6896d
[]
no_license
Alegerd/Ochko
https://github.com/Alegerd/Ochko
2fc61e4fda028a68feed9178ad6059ea6574e788
7a88a24aaf529510a5279e62b2232c238f6c888d
refs/heads/master
2020-05-22T19:48:58.427000
2017-03-12T15:39:00
2017-03-12T15:39:00
84,719,707
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.alegerd.Ochko.Interfaces; /** * Created by alegerd on 12.03.17. */ public interface Observable<T> { void addObserver(Observer<T> observer); void removeObserver(Observer<T> observer); void notifyObserver(int whatToDo); }
UTF-8
Java
247
java
Observable.java
Java
[ { "context": "e com.alegerd.Ochko.Interfaces;\n\n/**\n * Created by alegerd on 12.03.17.\n */\npublic interface Observable<T> {", "end": 64, "score": 0.9995965361595154, "start": 57, "tag": "USERNAME", "value": "alegerd" } ]
null
[]
package com.alegerd.Ochko.Interfaces; /** * Created by alegerd on 12.03.17. */ public interface Observable<T> { void addObserver(Observer<T> observer); void removeObserver(Observer<T> observer); void notifyObserver(int whatToDo); }
247
0.720648
0.696356
10
23.700001
18.330576
46
false
false
0
0
0
0
0
0
0.4
false
false
1
ce0001d1d091e0988acc88c4cc64b92bac5dcc8e
38,714,835,211,075
8106d9490bd26126308b17e84ab3f69bbcaa154f
/src/prjlista/ListaV.java
5e6c06232392dc4b6419a2bf68a1fc12de30fd4f
[]
no_license
Jos3Luis/appListasReproduccion
https://github.com/Jos3Luis/appListasReproduccion
ff8a27337a0110e95ee5241aa0f6de2807136719
75861e8c3b3d519b2779c72e471a46acc0e38739
refs/heads/master
2021-01-01T05:18:16.503000
2016-05-02T00:06:59
2016-05-02T00:06:59
57,856,869
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * Creado por Jose Luis * Quispe Aracayo */ package prjlista; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.Transferable; import java.awt.dnd.DnDConstants; import java.awt.dnd.DropTarget; import java.awt.dnd.DropTargetDragEvent; import java.awt.dnd.DropTargetDropEvent; import java.awt.dnd.DropTargetEvent; import java.awt.dnd.DropTargetListener; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.Reader; import java.io.Writer; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.StringTokenizer; import javax.swing.DefaultListModel; import javax.swing.JFileChooser; import javax.swing.JOptionPane; /** * * @author JOSE */ public class ListaV extends javax.swing.JFrame { private DefaultListModel mlist; private ArrayList<String> archivos; //private ArrayList<String> xOrden; private ArrayList<String> xNombre; private ArrayList<String> xAleatorio; private static final int XACTUAL = 0; private static final int XNOMBRE = 1; private static final int XALEATORIO = 2; private int opc = 0; public ListaV() { initComponents(); mlist = new DefaultListModel(); jlista.setModel(mlist); archivos = new ArrayList<>(); xNombre = new ArrayList<>(); xAleatorio = new ArrayList<>(); new DropTarget(jlista, new DropTargetListener() { @Override public void dragEnter(DropTargetDragEvent dtde) { } @Override public void dragOver(DropTargetDragEvent dtde) { } @Override public void dropActionChanged(DropTargetDragEvent dtde) { } @Override public void dragExit(DropTargetEvent dte) { } @Override public void drop(DropTargetDropEvent event) { event.acceptDrop(DnDConstants.ACTION_COPY); Transferable transferable = event.getTransferable(); DataFlavor[] flavors = transferable.getTransferDataFlavors(); for (DataFlavor flavor : flavors) { try { if (flavor.isFlavorJavaFileListType()) { mlist.clear(); //guardo en el objeto archivos List<File> files = (List) transferable.getTransferData(flavor); for (File file : files) { archivos.add(file.getAbsolutePath()); } //actualizo el jlist actualizar(); } } catch (Exception e) { e.printStackTrace(); } } event.dropComplete(true); } }); } private void generarxActual() { mlist.clear(); for (int i = 0; i < archivos.size(); i++) { mlist.addElement(new File(archivos.get(i)).getName()); } } private void actualizar() { if (jrbtnActual.isSelected()) { generarxActual(); } else if (jrbtnAleatorio.isSelected()) { generarxAleatorio(); } else if (jrbtnNombre.isSelected()) { generarxNombre(); } } private void generarxNombre() { mlist.clear(); xNombre.clear(); for (String f : archivos) { xNombre.add(f); } Collections.sort(xNombre); for (int i = 0; i < xNombre.size(); i++) { mlist.addElement(new File(xNombre.get(i)).getName()); } } private void generarxAleatorio() { mlist.clear(); xAleatorio.clear(); for (String f : archivos) { xAleatorio.add(f); } Collections.shuffle(xAleatorio); for (int i = 0; i < xAleatorio.size(); i++) { mlist.addElement(new File(xAleatorio.get(i)).getName()); } } /** * 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() { buttonGroup1 = new javax.swing.ButtonGroup(); jPanel1 = new javax.swing.JPanel(); jrbtnActual = new javax.swing.JRadioButton(); jrbtnNombre = new javax.swing.JRadioButton(); jrbtnAleatorio = new javax.swing.JRadioButton(); jScrollPane1 = new javax.swing.JScrollPane(); jlista = new javax.swing.JList<>(); jPanel2 = new javax.swing.JPanel(); jcbReproductor = new javax.swing.JComboBox<>(); jSeparator1 = new javax.swing.JSeparator(); jPanel3 = new javax.swing.JPanel(); btnExportar = new javax.swing.JButton(); jbtnCarpeta = new javax.swing.JButton(); jbtnRecuperar = new javax.swing.JButton(); jPanel4 = new javax.swing.JPanel(); jbtnUp = new javax.swing.JButton(); jbtnDown = new javax.swing.JButton(); jbtnQuitar = new javax.swing.JButton(); jbtnLimpiar = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("Generador de Lista MPlayer"); jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Orden")); buttonGroup1.add(jrbtnActual); jrbtnActual.setSelected(true); jrbtnActual.setText("Orden"); jrbtnActual.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jrbtnActualActionPerformed(evt); } }); buttonGroup1.add(jrbtnNombre); jrbtnNombre.setText("Nombre"); jrbtnNombre.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jrbtnNombreActionPerformed(evt); } }); buttonGroup1.add(jrbtnAleatorio); jrbtnAleatorio.setText("Aleatorio"); jrbtnAleatorio.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jrbtnAleatorioActionPerformed(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() .addComponent(jrbtnActual, javax.swing.GroupLayout.PREFERRED_SIZE, 78, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(11, 11, 11) .addComponent(jrbtnNombre, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGap(18, 18, 18) .addComponent(jrbtnAleatorio, javax.swing.GroupLayout.PREFERRED_SIZE, 81, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jrbtnActual) .addComponent(jrbtnNombre) .addComponent(jrbtnAleatorio)) .addGap(0, 8, Short.MAX_VALUE)) ); jlista.setDragEnabled(true); jScrollPane1.setViewportView(jlista); jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Reproductor")); jcbReproductor.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Player Clasic [PC]", "Windows Media Player[PC]", "PlayerPro Music Player[Android]" })); jcbReproductor.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jcbReproductorActionPerformed(evt); } }); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addComponent(jcbReproductor, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addContainerGap()) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jcbReproductor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) ); jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder("Acciones")); btnExportar.setText("Guardar"); btnExportar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnExportarActionPerformed(evt); } }); jbtnCarpeta.setText("A Carpeta"); jbtnCarpeta.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jbtnCarpetaActionPerformed(evt); } }); jbtnRecuperar.setText("Recuperar"); jbtnRecuperar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jbtnRecuperarActionPerformed(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, false) .addComponent(btnExportar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jbtnRecuperar, javax.swing.GroupLayout.DEFAULT_SIZE, 93, Short.MAX_VALUE) .addComponent(jbtnCarpeta, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addContainerGap(19, Short.MAX_VALUE)) ); jPanel3Layout.setVerticalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addComponent(btnExportar) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jbtnRecuperar) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jbtnCarpeta) .addContainerGap(12, Short.MAX_VALUE)) ); jbtnUp.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imgs/up_s.png"))); // NOI18N jbtnUp.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jbtnUpActionPerformed(evt); } }); jbtnDown.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imgs/down_s.png"))); // NOI18N jbtnDown.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jbtnDownActionPerformed(evt); } }); jbtnQuitar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imgs/delete.png"))); // NOI18N jbtnQuitar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jbtnQuitarActionPerformed(evt); } }); jbtnLimpiar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imgs/limpiar.png"))); // NOI18N jbtnLimpiar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jbtnLimpiarActionPerformed(evt); } }); javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4); jPanel4.setLayout(jPanel4Layout); jPanel4Layout.setHorizontalGroup( jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel4Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jbtnQuitar, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jbtnDown, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jbtnUp, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jbtnLimpiar, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addContainerGap()) ); jPanel4Layout.setVerticalGroup( jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel4Layout.createSequentialGroup() .addContainerGap(92, Short.MAX_VALUE) .addComponent(jbtnUp) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jbtnDown) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jbtnLimpiar) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jbtnQuitar) .addGap(40, 40, 40)) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 360, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGap(18, 18, 18) .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 455, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(12, 12, 12) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 415, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap()) ); pack(); }// </editor-fold>//GEN-END:initComponents private void jrbtnNombreActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jrbtnNombreActionPerformed generarxNombre(); opc = XNOMBRE; }//GEN-LAST:event_jrbtnNombreActionPerformed private void jrbtnActualActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jrbtnActualActionPerformed generarxActual(); opc = XACTUAL; }//GEN-LAST:event_jrbtnActualActionPerformed private void btnExportarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnExportarActionPerformed String contenido = ""; switch (opc) { case XNOMBRE: { if (jcbReproductor.getSelectedIndex() == 0) {//Player Classic contenido = getContenidoPlayerClassic(xNombre); } else if (jcbReproductor.getSelectedIndex() == 1) { contenido = getContenidoWMPlayer(xNombre); } } break; case XALEATORIO: { if (jcbReproductor.getSelectedIndex() == 0) {//Player Classic contenido = getContenidoPlayerClassic(xAleatorio); } else if (jcbReproductor.getSelectedIndex() == 1) { contenido = getContenidoWMPlayer(xAleatorio); } } break; case XACTUAL: { if (jcbReproductor.getSelectedIndex() == 0) {//Player Classic contenido = getContenidoPlayerClassic(archivos);//xOrden ya no se usa ya que todo esta en archivos } else if (jcbReproductor.getSelectedIndex() == 1) { contenido = getContenidoWMPlayer(archivos); } } break; } JFileChooser jfc = new JFileChooser(); int retorno = jfc.showSaveDialog(null); if (retorno == JFileChooser.APPROVE_OPTION) { File f = jfc.getSelectedFile(); String ruta = f.getAbsolutePath() + getExtension(); Writer salida = null; try { salida = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(ruta)), "utf-8")); salida.write(contenido); } catch (Exception e) { JOptionPane.showMessageDialog(null, "Error: " + e.toString()); } finally { try { salida.close(); } catch (Exception ex) {/*ignore*/ } } } }//GEN-LAST:event_btnExportarActionPerformed private void jbtnLimpiarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnLimpiarActionPerformed mlist.clear(); archivos.clear(); xAleatorio.clear(); xNombre.clear(); }//GEN-LAST:event_jbtnLimpiarActionPerformed private void jrbtnAleatorioActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jrbtnAleatorioActionPerformed generarxAleatorio(); opc = XALEATORIO; }//GEN-LAST:event_jrbtnAleatorioActionPerformed private void jcbReproductorActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jcbReproductorActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jcbReproductorActionPerformed private void jbtnQuitarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnQuitarActionPerformed if (jlista.getSelectedIndex() > 0) { int i = 0; String cadena = jlista.getSelectedValue(); for (i = 0; i < archivos.size(); i++) { if (archivos.get(i).contains(cadena)) { archivos.remove(i); break; } } actualizar(); } }//GEN-LAST:event_jbtnQuitarActionPerformed private void jbtnUpActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnUpActionPerformed if (jlista.getSelectedIndex() > 0) { String cadena = jlista.getSelectedValue(); for (int i = 0; i < archivos.size(); i++) { if (archivos.get(i).contains(cadena)) { if (i > 0) { String aux = archivos.get(i - 1); archivos.set(i - 1, archivos.get(i)); archivos.set(i, aux); break; } } } actualizar(); } }//GEN-LAST:event_jbtnUpActionPerformed private void jbtnDownActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnDownActionPerformed if (jlista.getSelectedIndex() > 0) { String cadena = jlista.getSelectedValue(); for (int i = 0; i < archivos.size(); i++) { if (archivos.get(i).contains(cadena)) { if (i < archivos.size() - 1) { String aux = archivos.get(i + 1); archivos.set(i + 1, archivos.get(i)); archivos.set(i, aux); break; } } } actualizar(); } }//GEN-LAST:event_jbtnDownActionPerformed private void jbtnCarpetaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnCarpetaActionPerformed JFileChooser jfc = new JFileChooser(); jfc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); int retorno = jfc.showSaveDialog(null); if (retorno == JFileChooser.APPROVE_OPTION) { File ruta = jfc.getSelectedFile(); if (ruta.mkdir()) { try { for (int i = 0; i < archivos.size(); i++) { copyFile(new File(archivos.get(i)), new File(ruta.getAbsolutePath() + "/" + new File(archivos.get(i)).getName())); } } catch (Exception e) { } } } }//GEN-LAST:event_jbtnCarpetaActionPerformed private void jbtnRecuperarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnRecuperarActionPerformed JFileChooser jfc = new JFileChooser(); int retorno = jfc.showOpenDialog(null); if (retorno == JFileChooser.APPROVE_OPTION) { File f = jfc.getSelectedFile(); String ruta = f.getAbsolutePath(); BufferedReader entrada = null; jbtnLimpiar.doClick(); try { String readLinea = null; entrada = new BufferedReader(new InputStreamReader(new FileInputStream(new File(ruta)), "utf8"), 8192); String ext = getExtensionFile(f.getName()); while ((readLinea = entrada.readLine()) != null) { if (ext.toLowerCase().equals("mpcpl")) { //mpc String buscar = ",filename,"; int ini = readLinea.indexOf(buscar); if (ini > 0) { ini += buscar.length(); archivos.add(readLinea.substring(ini)); } } else if (ext.toLowerCase().equals("wpl")) { //microsoft String buscar = "<media src=\""; int ini = readLinea.indexOf(buscar); int posfinal=readLinea.indexOf("\"/>"); if (ini > 0 && posfinal>0) { ini += buscar.length(); archivos.add(readLinea.substring(ini,posfinal)); } } } actualizar(); } catch (Exception e) { JOptionPane.showMessageDialog(null, "Error: " + e.toString()); } finally { try { entrada.close(); } catch (Exception ex) {/*ignore*/ } } } }//GEN-LAST:event_jbtnRecuperarActionPerformed /** * @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(ListaV.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(ListaV.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(ListaV.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(ListaV.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new ListaV().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton btnExportar; private javax.swing.ButtonGroup buttonGroup1; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JPanel jPanel3; private javax.swing.JPanel jPanel4; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JSeparator jSeparator1; private javax.swing.JButton jbtnCarpeta; private javax.swing.JButton jbtnDown; private javax.swing.JButton jbtnLimpiar; private javax.swing.JButton jbtnQuitar; private javax.swing.JButton jbtnRecuperar; private javax.swing.JButton jbtnUp; private javax.swing.JComboBox<String> jcbReproductor; private javax.swing.JList<String> jlista; private javax.swing.JRadioButton jrbtnActual; private javax.swing.JRadioButton jrbtnAleatorio; private javax.swing.JRadioButton jrbtnNombre; // End of variables declaration//GEN-END:variables public String getExtension() { if (jcbReproductor.getSelectedIndex() == 0) {//Media Player Clasicc return ".mpcpl"; } else if (jcbReproductor.getSelectedIndex() == 1) { //WMP return ".wpl"; } return ""; } public String getContenidoPlayerClassic(ArrayList<String> l) { String str = "MPCPLAYLIST\n"; for (int i = 0; i < l.size(); i++) { str += (1 + i) + ",type,0\n" + (1 + i) + ",filename," + l.get(i) + "\n"; } return str; } public String getContenidoWMPlayer(ArrayList<String> l) { String str = "<?wpl version=\"1.0\"?>\n" + "<smil>\n" + " <head>\n" + " <meta name=\"Generator\" content=\"Microsoft Windows Media Player -- 12.0.10586.162\"/>\n" + " <meta name=\"ItemCount\" content=\"" + l.size() + "\"/>\n" + " <title>mi lista</title>\n" + " </head>\n" + " <body>\n" + " <seq>\n"; for (int i = 0; i < l.size(); i++) { str += " <media src=\"" + l.get(i) + "\" />\n"; } str += " </seq>\n" + " </body>\n" + "</smil>"; return str; } private static void copyFile(File source, File dest) throws IOException { InputStream is = null; OutputStream os = null; try { is = new FileInputStream(source); os = new FileOutputStream(dest); byte[] buffer = new byte[1024]; int length; while ((length = is.read(buffer)) > 0) { os.write(buffer, 0, length); } } finally { is.close(); os.close(); } } private String getExtensionFile(String f) { int i = f.lastIndexOf('.'); if (i > 0) { return f.substring(i + 1); } return ""; } }
UTF-8
Java
31,999
java
ListaV.java
Java
[ { "context": "/*\n * Creado por Jose Luis\n * Quispe Aracayo\n */\npackage prjlista;\n\nimport j", "end": 26, "score": 0.9998762011528015, "start": 17, "tag": "NAME", "value": "Jose Luis" }, { "context": "/*\n * Creado por Jose Luis\n * Quispe Aracayo\n */\npackage prjlista;\n\nimport java.awt.datatransf", "end": 44, "score": 0.9998806118965149, "start": 30, "tag": "NAME", "value": "Quispe Aracayo" }, { "context": "import javax.swing.JOptionPane;\n\n/**\n *\n * @author JOSE\n */\npublic class ListaV extends javax.swing.JFram", "end": 965, "score": 0.7184839248657227, "start": 961, "tag": "NAME", "value": "JOSE" } ]
null
[]
/* * Creado por <NAME> * <NAME> */ package prjlista; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.Transferable; import java.awt.dnd.DnDConstants; import java.awt.dnd.DropTarget; import java.awt.dnd.DropTargetDragEvent; import java.awt.dnd.DropTargetDropEvent; import java.awt.dnd.DropTargetEvent; import java.awt.dnd.DropTargetListener; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.Reader; import java.io.Writer; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.StringTokenizer; import javax.swing.DefaultListModel; import javax.swing.JFileChooser; import javax.swing.JOptionPane; /** * * @author JOSE */ public class ListaV extends javax.swing.JFrame { private DefaultListModel mlist; private ArrayList<String> archivos; //private ArrayList<String> xOrden; private ArrayList<String> xNombre; private ArrayList<String> xAleatorio; private static final int XACTUAL = 0; private static final int XNOMBRE = 1; private static final int XALEATORIO = 2; private int opc = 0; public ListaV() { initComponents(); mlist = new DefaultListModel(); jlista.setModel(mlist); archivos = new ArrayList<>(); xNombre = new ArrayList<>(); xAleatorio = new ArrayList<>(); new DropTarget(jlista, new DropTargetListener() { @Override public void dragEnter(DropTargetDragEvent dtde) { } @Override public void dragOver(DropTargetDragEvent dtde) { } @Override public void dropActionChanged(DropTargetDragEvent dtde) { } @Override public void dragExit(DropTargetEvent dte) { } @Override public void drop(DropTargetDropEvent event) { event.acceptDrop(DnDConstants.ACTION_COPY); Transferable transferable = event.getTransferable(); DataFlavor[] flavors = transferable.getTransferDataFlavors(); for (DataFlavor flavor : flavors) { try { if (flavor.isFlavorJavaFileListType()) { mlist.clear(); //guardo en el objeto archivos List<File> files = (List) transferable.getTransferData(flavor); for (File file : files) { archivos.add(file.getAbsolutePath()); } //actualizo el jlist actualizar(); } } catch (Exception e) { e.printStackTrace(); } } event.dropComplete(true); } }); } private void generarxActual() { mlist.clear(); for (int i = 0; i < archivos.size(); i++) { mlist.addElement(new File(archivos.get(i)).getName()); } } private void actualizar() { if (jrbtnActual.isSelected()) { generarxActual(); } else if (jrbtnAleatorio.isSelected()) { generarxAleatorio(); } else if (jrbtnNombre.isSelected()) { generarxNombre(); } } private void generarxNombre() { mlist.clear(); xNombre.clear(); for (String f : archivos) { xNombre.add(f); } Collections.sort(xNombre); for (int i = 0; i < xNombre.size(); i++) { mlist.addElement(new File(xNombre.get(i)).getName()); } } private void generarxAleatorio() { mlist.clear(); xAleatorio.clear(); for (String f : archivos) { xAleatorio.add(f); } Collections.shuffle(xAleatorio); for (int i = 0; i < xAleatorio.size(); i++) { mlist.addElement(new File(xAleatorio.get(i)).getName()); } } /** * 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() { buttonGroup1 = new javax.swing.ButtonGroup(); jPanel1 = new javax.swing.JPanel(); jrbtnActual = new javax.swing.JRadioButton(); jrbtnNombre = new javax.swing.JRadioButton(); jrbtnAleatorio = new javax.swing.JRadioButton(); jScrollPane1 = new javax.swing.JScrollPane(); jlista = new javax.swing.JList<>(); jPanel2 = new javax.swing.JPanel(); jcbReproductor = new javax.swing.JComboBox<>(); jSeparator1 = new javax.swing.JSeparator(); jPanel3 = new javax.swing.JPanel(); btnExportar = new javax.swing.JButton(); jbtnCarpeta = new javax.swing.JButton(); jbtnRecuperar = new javax.swing.JButton(); jPanel4 = new javax.swing.JPanel(); jbtnUp = new javax.swing.JButton(); jbtnDown = new javax.swing.JButton(); jbtnQuitar = new javax.swing.JButton(); jbtnLimpiar = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("Generador de Lista MPlayer"); jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Orden")); buttonGroup1.add(jrbtnActual); jrbtnActual.setSelected(true); jrbtnActual.setText("Orden"); jrbtnActual.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jrbtnActualActionPerformed(evt); } }); buttonGroup1.add(jrbtnNombre); jrbtnNombre.setText("Nombre"); jrbtnNombre.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jrbtnNombreActionPerformed(evt); } }); buttonGroup1.add(jrbtnAleatorio); jrbtnAleatorio.setText("Aleatorio"); jrbtnAleatorio.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jrbtnAleatorioActionPerformed(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() .addComponent(jrbtnActual, javax.swing.GroupLayout.PREFERRED_SIZE, 78, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(11, 11, 11) .addComponent(jrbtnNombre, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGap(18, 18, 18) .addComponent(jrbtnAleatorio, javax.swing.GroupLayout.PREFERRED_SIZE, 81, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jrbtnActual) .addComponent(jrbtnNombre) .addComponent(jrbtnAleatorio)) .addGap(0, 8, Short.MAX_VALUE)) ); jlista.setDragEnabled(true); jScrollPane1.setViewportView(jlista); jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Reproductor")); jcbReproductor.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Player Clasic [PC]", "Windows Media Player[PC]", "PlayerPro Music Player[Android]" })); jcbReproductor.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jcbReproductorActionPerformed(evt); } }); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addComponent(jcbReproductor, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addContainerGap()) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jcbReproductor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) ); jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder("Acciones")); btnExportar.setText("Guardar"); btnExportar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnExportarActionPerformed(evt); } }); jbtnCarpeta.setText("A Carpeta"); jbtnCarpeta.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jbtnCarpetaActionPerformed(evt); } }); jbtnRecuperar.setText("Recuperar"); jbtnRecuperar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jbtnRecuperarActionPerformed(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, false) .addComponent(btnExportar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jbtnRecuperar, javax.swing.GroupLayout.DEFAULT_SIZE, 93, Short.MAX_VALUE) .addComponent(jbtnCarpeta, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addContainerGap(19, Short.MAX_VALUE)) ); jPanel3Layout.setVerticalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addComponent(btnExportar) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jbtnRecuperar) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jbtnCarpeta) .addContainerGap(12, Short.MAX_VALUE)) ); jbtnUp.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imgs/up_s.png"))); // NOI18N jbtnUp.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jbtnUpActionPerformed(evt); } }); jbtnDown.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imgs/down_s.png"))); // NOI18N jbtnDown.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jbtnDownActionPerformed(evt); } }); jbtnQuitar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imgs/delete.png"))); // NOI18N jbtnQuitar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jbtnQuitarActionPerformed(evt); } }); jbtnLimpiar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imgs/limpiar.png"))); // NOI18N jbtnLimpiar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jbtnLimpiarActionPerformed(evt); } }); javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4); jPanel4.setLayout(jPanel4Layout); jPanel4Layout.setHorizontalGroup( jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel4Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jbtnQuitar, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jbtnDown, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jbtnUp, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jbtnLimpiar, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addContainerGap()) ); jPanel4Layout.setVerticalGroup( jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel4Layout.createSequentialGroup() .addContainerGap(92, Short.MAX_VALUE) .addComponent(jbtnUp) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jbtnDown) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jbtnLimpiar) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jbtnQuitar) .addGap(40, 40, 40)) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 360, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGap(18, 18, 18) .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 455, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(12, 12, 12) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 415, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap()) ); pack(); }// </editor-fold>//GEN-END:initComponents private void jrbtnNombreActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jrbtnNombreActionPerformed generarxNombre(); opc = XNOMBRE; }//GEN-LAST:event_jrbtnNombreActionPerformed private void jrbtnActualActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jrbtnActualActionPerformed generarxActual(); opc = XACTUAL; }//GEN-LAST:event_jrbtnActualActionPerformed private void btnExportarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnExportarActionPerformed String contenido = ""; switch (opc) { case XNOMBRE: { if (jcbReproductor.getSelectedIndex() == 0) {//Player Classic contenido = getContenidoPlayerClassic(xNombre); } else if (jcbReproductor.getSelectedIndex() == 1) { contenido = getContenidoWMPlayer(xNombre); } } break; case XALEATORIO: { if (jcbReproductor.getSelectedIndex() == 0) {//Player Classic contenido = getContenidoPlayerClassic(xAleatorio); } else if (jcbReproductor.getSelectedIndex() == 1) { contenido = getContenidoWMPlayer(xAleatorio); } } break; case XACTUAL: { if (jcbReproductor.getSelectedIndex() == 0) {//Player Classic contenido = getContenidoPlayerClassic(archivos);//xOrden ya no se usa ya que todo esta en archivos } else if (jcbReproductor.getSelectedIndex() == 1) { contenido = getContenidoWMPlayer(archivos); } } break; } JFileChooser jfc = new JFileChooser(); int retorno = jfc.showSaveDialog(null); if (retorno == JFileChooser.APPROVE_OPTION) { File f = jfc.getSelectedFile(); String ruta = f.getAbsolutePath() + getExtension(); Writer salida = null; try { salida = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(ruta)), "utf-8")); salida.write(contenido); } catch (Exception e) { JOptionPane.showMessageDialog(null, "Error: " + e.toString()); } finally { try { salida.close(); } catch (Exception ex) {/*ignore*/ } } } }//GEN-LAST:event_btnExportarActionPerformed private void jbtnLimpiarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnLimpiarActionPerformed mlist.clear(); archivos.clear(); xAleatorio.clear(); xNombre.clear(); }//GEN-LAST:event_jbtnLimpiarActionPerformed private void jrbtnAleatorioActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jrbtnAleatorioActionPerformed generarxAleatorio(); opc = XALEATORIO; }//GEN-LAST:event_jrbtnAleatorioActionPerformed private void jcbReproductorActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jcbReproductorActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jcbReproductorActionPerformed private void jbtnQuitarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnQuitarActionPerformed if (jlista.getSelectedIndex() > 0) { int i = 0; String cadena = jlista.getSelectedValue(); for (i = 0; i < archivos.size(); i++) { if (archivos.get(i).contains(cadena)) { archivos.remove(i); break; } } actualizar(); } }//GEN-LAST:event_jbtnQuitarActionPerformed private void jbtnUpActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnUpActionPerformed if (jlista.getSelectedIndex() > 0) { String cadena = jlista.getSelectedValue(); for (int i = 0; i < archivos.size(); i++) { if (archivos.get(i).contains(cadena)) { if (i > 0) { String aux = archivos.get(i - 1); archivos.set(i - 1, archivos.get(i)); archivos.set(i, aux); break; } } } actualizar(); } }//GEN-LAST:event_jbtnUpActionPerformed private void jbtnDownActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnDownActionPerformed if (jlista.getSelectedIndex() > 0) { String cadena = jlista.getSelectedValue(); for (int i = 0; i < archivos.size(); i++) { if (archivos.get(i).contains(cadena)) { if (i < archivos.size() - 1) { String aux = archivos.get(i + 1); archivos.set(i + 1, archivos.get(i)); archivos.set(i, aux); break; } } } actualizar(); } }//GEN-LAST:event_jbtnDownActionPerformed private void jbtnCarpetaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnCarpetaActionPerformed JFileChooser jfc = new JFileChooser(); jfc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); int retorno = jfc.showSaveDialog(null); if (retorno == JFileChooser.APPROVE_OPTION) { File ruta = jfc.getSelectedFile(); if (ruta.mkdir()) { try { for (int i = 0; i < archivos.size(); i++) { copyFile(new File(archivos.get(i)), new File(ruta.getAbsolutePath() + "/" + new File(archivos.get(i)).getName())); } } catch (Exception e) { } } } }//GEN-LAST:event_jbtnCarpetaActionPerformed private void jbtnRecuperarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnRecuperarActionPerformed JFileChooser jfc = new JFileChooser(); int retorno = jfc.showOpenDialog(null); if (retorno == JFileChooser.APPROVE_OPTION) { File f = jfc.getSelectedFile(); String ruta = f.getAbsolutePath(); BufferedReader entrada = null; jbtnLimpiar.doClick(); try { String readLinea = null; entrada = new BufferedReader(new InputStreamReader(new FileInputStream(new File(ruta)), "utf8"), 8192); String ext = getExtensionFile(f.getName()); while ((readLinea = entrada.readLine()) != null) { if (ext.toLowerCase().equals("mpcpl")) { //mpc String buscar = ",filename,"; int ini = readLinea.indexOf(buscar); if (ini > 0) { ini += buscar.length(); archivos.add(readLinea.substring(ini)); } } else if (ext.toLowerCase().equals("wpl")) { //microsoft String buscar = "<media src=\""; int ini = readLinea.indexOf(buscar); int posfinal=readLinea.indexOf("\"/>"); if (ini > 0 && posfinal>0) { ini += buscar.length(); archivos.add(readLinea.substring(ini,posfinal)); } } } actualizar(); } catch (Exception e) { JOptionPane.showMessageDialog(null, "Error: " + e.toString()); } finally { try { entrada.close(); } catch (Exception ex) {/*ignore*/ } } } }//GEN-LAST:event_jbtnRecuperarActionPerformed /** * @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(ListaV.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(ListaV.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(ListaV.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(ListaV.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new ListaV().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton btnExportar; private javax.swing.ButtonGroup buttonGroup1; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JPanel jPanel3; private javax.swing.JPanel jPanel4; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JSeparator jSeparator1; private javax.swing.JButton jbtnCarpeta; private javax.swing.JButton jbtnDown; private javax.swing.JButton jbtnLimpiar; private javax.swing.JButton jbtnQuitar; private javax.swing.JButton jbtnRecuperar; private javax.swing.JButton jbtnUp; private javax.swing.JComboBox<String> jcbReproductor; private javax.swing.JList<String> jlista; private javax.swing.JRadioButton jrbtnActual; private javax.swing.JRadioButton jrbtnAleatorio; private javax.swing.JRadioButton jrbtnNombre; // End of variables declaration//GEN-END:variables public String getExtension() { if (jcbReproductor.getSelectedIndex() == 0) {//Media Player Clasicc return ".mpcpl"; } else if (jcbReproductor.getSelectedIndex() == 1) { //WMP return ".wpl"; } return ""; } public String getContenidoPlayerClassic(ArrayList<String> l) { String str = "MPCPLAYLIST\n"; for (int i = 0; i < l.size(); i++) { str += (1 + i) + ",type,0\n" + (1 + i) + ",filename," + l.get(i) + "\n"; } return str; } public String getContenidoWMPlayer(ArrayList<String> l) { String str = "<?wpl version=\"1.0\"?>\n" + "<smil>\n" + " <head>\n" + " <meta name=\"Generator\" content=\"Microsoft Windows Media Player -- 12.0.10586.162\"/>\n" + " <meta name=\"ItemCount\" content=\"" + l.size() + "\"/>\n" + " <title>mi lista</title>\n" + " </head>\n" + " <body>\n" + " <seq>\n"; for (int i = 0; i < l.size(); i++) { str += " <media src=\"" + l.get(i) + "\" />\n"; } str += " </seq>\n" + " </body>\n" + "</smil>"; return str; } private static void copyFile(File source, File dest) throws IOException { InputStream is = null; OutputStream os = null; try { is = new FileInputStream(source); os = new FileOutputStream(dest); byte[] buffer = new byte[1024]; int length; while ((length = is.read(buffer)) > 0) { os.write(buffer, 0, length); } } finally { is.close(); os.close(); } } private String getExtensionFile(String f) { int i = f.lastIndexOf('.'); if (i > 0) { return f.substring(i + 1); } return ""; } }
31,988
0.601706
0.5953
716
43.691341
35.362465
184
false
false
0
0
0
0
0
0
0.586592
false
false
1
b9c1e9767d5216c76b6354209d42aafe977fbe39
25,795,573,635,058
fb413d9851c176146540ae59e2954d00d5513cd3
/seckill_uniqueid/server/src/main/java/com/seckill/uniqueid/server/controller/UniqueIdController.java
ead1f904f5fa43b70724277b7d7c2f08140e699d
[]
no_license
randy1568/SpringCloudSeckill
https://github.com/randy1568/SpringCloudSeckill
aef8e47d801077ece4092cd75600b7864829410b
1e785bf41eca1c88586199f97f1cd1662402e2e5
refs/heads/master
2022-11-10T13:50:10.002000
2020-06-14T12:41:09
2020-06-14T12:41:09
271,553,995
0
1
null
false
2020-06-14T12:41:11
2020-06-11T13:31:23
2020-06-14T07:40:44
2020-06-14T12:41:10
1,531
0
1
2
JavaScript
false
false
package com.seckill.uniqueid.server.controller; import com.seckill.uniqueid.server.IdGenerator; import com.seckill.uniqueid.server.common.Result; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class UniqueIdController { @GetMapping("/getuniqueid") public String getUniqueId(){ return String.valueOf(new IdGenerator().nextId()); } }
UTF-8
Java
453
java
UniqueIdController.java
Java
[]
null
[]
package com.seckill.uniqueid.server.controller; import com.seckill.uniqueid.server.IdGenerator; import com.seckill.uniqueid.server.common.Result; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class UniqueIdController { @GetMapping("/getuniqueid") public String getUniqueId(){ return String.valueOf(new IdGenerator().nextId()); } }
453
0.785872
0.785872
15
29.200001
22.987534
62
false
false
0
0
0
0
0
0
0.4
false
false
1
085488d4188e7e68063f0f93759b130d37962fc0
12,086,038,018,378
dbed862acee93bdc572ae8c2cac49dfbf14700eb
/app/src/main/java/vsu/ru/homecrime/MainActivity.java
0cd44be3693646856c49cbf14ceb2af5c937a56b
[]
no_license
endovitskayaV/HomeCrime
https://github.com/endovitskayaV/HomeCrime
77a16f72562dc22f6b2b94525dceb5e5265f5ff5
5f3815a2068d489a2f049ddec6bfb079e7977d9c
refs/heads/master
2020-03-06T23:30:49.224000
2018-04-21T09:46:41
2018-04-21T09:46:41
127,133,598
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package vsu.ru.homecrime; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentManager; import android.os.Bundle; import android.support.v4.app.FragmentStatePagerAdapter; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import vsu.ru.homecrime.model.DataKeeper; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); FragmentManager fragmentManager = getSupportFragmentManager(); Fragment fragment = fragmentManager.findFragmentById(R.id.frame_layout); if (fragment == null) { fragment = new MainFragment(); fragmentManager.beginTransaction().add(R.id.frame_layout, fragment).commit(); } } }
UTF-8
Java
1,067
java
MainActivity.java
Java
[]
null
[]
package vsu.ru.homecrime; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentManager; import android.os.Bundle; import android.support.v4.app.FragmentStatePagerAdapter; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import vsu.ru.homecrime.model.DataKeeper; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); FragmentManager fragmentManager = getSupportFragmentManager(); Fragment fragment = fragmentManager.findFragmentById(R.id.frame_layout); if (fragment == null) { fragment = new MainFragment(); fragmentManager.beginTransaction().add(R.id.frame_layout, fragment).commit(); } } }
1,067
0.744142
0.737582
30
34.599998
24.540579
89
false
false
0
0
0
0
0
0
0.633333
false
false
1
b60479973640e0dcc866d7440bd6b64678e98397
23,562,190,589,154
21de9b9c405f63dd8b7bf8a50c5906d8b21960bb
/src/mgplugin/template/DefaultCodeResolver.java
99acd8c9d64af0c3355ab783effdaa67f41b9386
[]
no_license
bresting/MgPlugin
https://github.com/bresting/MgPlugin
24868c0b550f7a6d6af2e7533aef4ee5069de4c8
355eea89f5120f6a6839474c695c51ad673dc13e
refs/heads/master
2021-07-13T14:37:07.489000
2020-11-27T06:44:48
2020-11-27T06:44:48
226,097,091
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package mgplugin.template; import java.util.ArrayList; import java.util.List; import org.eclipse.jface.text.templates.TemplateContext; import org.eclipse.jface.text.templates.TemplateVariable; import org.eclipse.jface.text.templates.TemplateVariableResolver; /** * 패키지 구조에 따라 class component annotation 템플릿을 설정한다. * @author jakekim84 * @since 2019.11.26 */ public class DefaultCodeResolver extends TemplateVariableResolver { public DefaultCodeResolver() { super("MG_defaultCode", "패키지 구조에 따라 기본코드 설정"); } public void resolve(TemplateVariable variable, TemplateContext context) { String package_name = context.getVariable("package_name"); String type_name = context.getVariable("type_name"); List<String> textList = new ArrayList<String>(); if ( package_name.contains("controller") ) { textList.add("private static final Logger logger = LoggerFactory.getLogger(" + type_name + ".class);"); } else if ( package_name.contains("service") ) { textList.add("private static final Logger logger = LoggerFactory.getLogger(" + type_name + ".class);"); } variable.setValue(String.join(System.getProperty("line.separator"), textList)); } }
UTF-8
Java
1,381
java
DefaultCodeResolver.java
Java
[ { "context": " class component annotation 템플릿을 설정한다.\r\n * @author jakekim84\r\n * @since 2019.11.26\r\n */\r\npublic class Default", "end": 349, "score": 0.9995555877685547, "start": 340, "tag": "USERNAME", "value": "jakekim84" } ]
null
[]
package mgplugin.template; import java.util.ArrayList; import java.util.List; import org.eclipse.jface.text.templates.TemplateContext; import org.eclipse.jface.text.templates.TemplateVariable; import org.eclipse.jface.text.templates.TemplateVariableResolver; /** * 패키지 구조에 따라 class component annotation 템플릿을 설정한다. * @author jakekim84 * @since 2019.11.26 */ public class DefaultCodeResolver extends TemplateVariableResolver { public DefaultCodeResolver() { super("MG_defaultCode", "패키지 구조에 따라 기본코드 설정"); } public void resolve(TemplateVariable variable, TemplateContext context) { String package_name = context.getVariable("package_name"); String type_name = context.getVariable("type_name"); List<String> textList = new ArrayList<String>(); if ( package_name.contains("controller") ) { textList.add("private static final Logger logger = LoggerFactory.getLogger(" + type_name + ".class);"); } else if ( package_name.contains("service") ) { textList.add("private static final Logger logger = LoggerFactory.getLogger(" + type_name + ".class);"); } variable.setValue(String.join(System.getProperty("line.separator"), textList)); } }
1,381
0.659349
0.651779
34
36.85294
33.431347
115
false
false
0
0
0
0
0
0
0.529412
false
false
1
50a90763e40bbf4ba06db1ba8913861d677e7ac7
23,330,262,395,815
50a52f2d7baaa9890e9ef4ff906feef7414d40fb
/JulianDateInterface.java
8078a0a627edd58d657f625f550c3396b805f91b
[]
no_license
nikigawlik/info_2_ex_8
https://github.com/nikigawlik/info_2_ex_8
5adb64e484063bb371be933e2ac13ae660eeddec
48f360a63c0f67cc169382472089c9e3b05aa9e5
refs/heads/master
2023-01-28T02:05:31.243000
2016-06-12T17:22:14
2016-06-12T17:22:14
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package info_2_ex_8; public interface JulianDateInterface { /* (non-Javadoc) * @see JulianDateInterfaces#getDays() */ long getDays(); int getGregDay(); int getGregMonth(); int getGregYear(); /* (non-Javadoc) * @see JulianDateInterfaces#getWeekday() */ String getWeekday(); String getGregDate(); }
UTF-8
Java
321
java
JulianDateInterface.java
Java
[]
null
[]
package info_2_ex_8; public interface JulianDateInterface { /* (non-Javadoc) * @see JulianDateInterfaces#getDays() */ long getDays(); int getGregDay(); int getGregMonth(); int getGregYear(); /* (non-Javadoc) * @see JulianDateInterfaces#getWeekday() */ String getWeekday(); String getGregDate(); }
321
0.679128
0.672897
24
12.416667
13.394391
42
false
false
0
0
0
0
0
0
0.791667
false
false
1
da9895e36779d62af0f5c4dbb0dab58e0cffc3bd
31,129,922,981,616
4e79ce67667002f65ead3c83db0970937d0e903f
/FAST-WebService-Mysql/src/main/java/com/ppu/fast/ws/service/impl/HelloServiceImpl.java
e54381dad38d3d49d17d54aa8239b2a01b7e7899
[]
no_license
elkana911/FAST-WebService-Mysql
https://github.com/elkana911/FAST-WebService-Mysql
976b3582d368af5a74161e4233344bda49cb7bdf
987fa2490d0ddc9169d9a437f95c7d86dbdf5c8d
refs/heads/master
2020-04-18T05:42:42.376000
2016-09-30T08:46:52
2016-09-30T08:46:52
66,820,889
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.ppu.fast.ws.service.impl; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.ppu.fast.ws.service.IHelloService; import com.ppu.fast.ws.service.response.HelloWebResponse; import com.ppu.fast.ws.util.Utils; @Service("helloService") @Transactional public class HelloServiceImpl implements IHelloService { private static Logger log = LoggerFactory.getLogger(HelloServiceImpl.class); @Override public HelloWebResponse hello(String name) { HelloWebResponse helloWebResponse = new HelloWebResponse(); helloWebResponse.setData("Hello " + name); helloWebResponse.setError(null); helloWebResponse.setIp(Utils.getClientIP()); return helloWebResponse; } @Override public HelloWebResponse hello() { HelloWebResponse helloWebResponse = new HelloWebResponse(); helloWebResponse.setData("Hello World"); helloWebResponse.setError(null); helloWebResponse.setIp(Utils.getClientIP()); return helloWebResponse; } }
UTF-8
Java
1,122
java
HelloServiceImpl.java
Java
[]
null
[]
package com.ppu.fast.ws.service.impl; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.ppu.fast.ws.service.IHelloService; import com.ppu.fast.ws.service.response.HelloWebResponse; import com.ppu.fast.ws.util.Utils; @Service("helloService") @Transactional public class HelloServiceImpl implements IHelloService { private static Logger log = LoggerFactory.getLogger(HelloServiceImpl.class); @Override public HelloWebResponse hello(String name) { HelloWebResponse helloWebResponse = new HelloWebResponse(); helloWebResponse.setData("Hello " + name); helloWebResponse.setError(null); helloWebResponse.setIp(Utils.getClientIP()); return helloWebResponse; } @Override public HelloWebResponse hello() { HelloWebResponse helloWebResponse = new HelloWebResponse(); helloWebResponse.setData("Hello World"); helloWebResponse.setError(null); helloWebResponse.setIp(Utils.getClientIP()); return helloWebResponse; } }
1,122
0.764706
0.762923
39
26.76923
22.844471
80
false
false
0
0
0
0
0
0
1.358974
false
false
1
29fde70d5b698ee36ec0796add9a3baef0975112
22,351,009,835,036
e818977ec3385aff17892a64bd8ed473f1e66aae
/fly-leadnews-apis/src/main/java/com/fly/apis/admin/AdSensitiveControllerApi.java
1ffe50b744b2ba6acd590ceca5b7d20c342290e5
[]
no_license
Adairlizi/fly-leadnews
https://github.com/Adairlizi/fly-leadnews
e5f06e278f79b5f56832ea33e4a380901464d194
71c6af31490bf92f045834bdf279117629715dfe
refs/heads/master
2023-06-24T23:23:18.395000
2021-08-01T10:45:35
2021-08-01T10:45:35
385,942,163
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.fly.apis.admin; import com.fly.model.admin.dtos.SensitiveDto; import com.fly.model.admin.pojos.AdSensitive; import com.fly.model.common.dtos.ResponseResult; public interface AdSensitiveControllerApi { /** * 根据名称分页查询 * @param sensitiveDto * @return */ public ResponseResult findByNameAndPage(SensitiveDto sensitiveDto); /** * 频道查询 * @param adSensitive * @return */ public ResponseResult addAdSensitive(AdSensitive adSensitive); /** * 频道修改 * @param adSensitive * @return */ public ResponseResult updateAdSensitive(AdSensitive adSensitive); /** * 通过ID删除 * @param id 删除 * @return */ public ResponseResult deleteSAdSensitiveById(Integer id); }
UTF-8
Java
813
java
AdSensitiveControllerApi.java
Java
[]
null
[]
package com.fly.apis.admin; import com.fly.model.admin.dtos.SensitiveDto; import com.fly.model.admin.pojos.AdSensitive; import com.fly.model.common.dtos.ResponseResult; public interface AdSensitiveControllerApi { /** * 根据名称分页查询 * @param sensitiveDto * @return */ public ResponseResult findByNameAndPage(SensitiveDto sensitiveDto); /** * 频道查询 * @param adSensitive * @return */ public ResponseResult addAdSensitive(AdSensitive adSensitive); /** * 频道修改 * @param adSensitive * @return */ public ResponseResult updateAdSensitive(AdSensitive adSensitive); /** * 通过ID删除 * @param id 删除 * @return */ public ResponseResult deleteSAdSensitiveById(Integer id); }
813
0.661899
0.661899
36
20.361111
21.072826
71
false
false
0
0
0
0
0
0
0.222222
false
false
1
e71ab139e05c946e83592df730f7fa874d2e690e
20,684,562,561,075
a80343191fe5c90c61ddde0057ec2fd0be203dac
/JavaLab/src/javalab2/studentinfo.java
e441cea997d4a3f9de508022fba07373c1e69442
[]
no_license
bappi2097/java-code
https://github.com/bappi2097/java-code
784e930b40d1e95bc6fada911c77eb64b4aeb8c4
886e14f157cf9c3ede6853c02cc5676c2cef15d6
refs/heads/master
2023-04-30T17:40:42.962000
2021-05-09T14:14:06
2021-05-09T14:14:06
364,961,693
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package javalab2; public class studentinfo { String Id; String Name; String Department; float Cgpa = 0; double payment = 0.0; public void info(String i,String n,String d,float c , double p){ Id = i; Name = n; Department = d; Cgpa = c; payment = p; } public void paymentSubmit(double d){ payment += d; } public void cgpa(float f , float s , float t){ Cgpa = (f+s+t)/3; } public void showInfo(){ System.out.print("\nID: "+Id+"\nName: "+Name+"\nDepartment: "+Department); System.out.print("\nCgpa: "+Cgpa+"\nPayment: "+payment); } }
UTF-8
Java
672
java
studentinfo.java
Java
[ { "context": "loat c , double p){\n Id = i;\n Name = n;\n Department = d;\n Cgpa = c;\n ", "end": 247, "score": 0.9183987379074097, "start": 246, "tag": "NAME", "value": "n" } ]
null
[]
package javalab2; public class studentinfo { String Id; String Name; String Department; float Cgpa = 0; double payment = 0.0; public void info(String i,String n,String d,float c , double p){ Id = i; Name = n; Department = d; Cgpa = c; payment = p; } public void paymentSubmit(double d){ payment += d; } public void cgpa(float f , float s , float t){ Cgpa = (f+s+t)/3; } public void showInfo(){ System.out.print("\nID: "+Id+"\nName: "+Name+"\nDepartment: "+Department); System.out.print("\nCgpa: "+Cgpa+"\nPayment: "+payment); } }
672
0.534226
0.526786
27
23.888889
20.009874
82
false
false
0
0
0
0
0
0
0.777778
false
false
1
689032e783533c6209cda18c114ed4147ac65505
8,443,905,727,329
3d44d46f2a9b4ffb86a347c580cce53d21a34889
/Assignment3/Breakout.java
79cbc19f1522f8c1d6dbaf950079da3ddc190e03
[]
no_license
tomtom28/SEE-CS106A
https://github.com/tomtom28/SEE-CS106A
b441081cd1a1cbdc839702f432c3fefee934d169
8405680ce7472d6b77d6ac0dcf80cac89f7a64d7
refs/heads/master
2021-06-22T07:30:27.887000
2017-08-27T02:25:48
2017-08-27T02:25:48
100,323,614
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * File: Breakout.java * ------------------- * Name: Thomas Thompson * * This file will eventually implement the game of Breakout. */ import acm.graphics.*; import acm.program.*; import acm.util.*; import java.applet.*; import java.awt.*; import java.awt.event.*; public class Breakout extends GraphicsProgram { /** Width and height of application window in pixels */ public static final int APPLICATION_WIDTH = 400; public static final int APPLICATION_HEIGHT = 600; /** Dimensions of game board (usually the same) */ private static final int WIDTH = APPLICATION_WIDTH; private static final int HEIGHT = APPLICATION_HEIGHT; /** Dimensions of the paddle */ private static final int PADDLE_WIDTH = 60; private static final int PADDLE_HEIGHT = 10; /** Offset of the paddle up from the bottom */ private static final int PADDLE_Y_OFFSET = 30; /** Number of bricks per row */ private static final int NBRICKS_PER_ROW = 10; /** Number of rows of bricks */ private static final int NBRICK_ROWS = 10; /** Separation between bricks */ private static final int BRICK_SEP = 4; /** Width of a brick */ private static final int BRICK_WIDTH = (WIDTH - (NBRICKS_PER_ROW - 1) * BRICK_SEP) / NBRICKS_PER_ROW; /** Height of a brick */ private static final int BRICK_HEIGHT = 8; /** Radius of the ball in pixels */ private static final int BALL_RADIUS = 10; /** Offset of the top brick row from the top */ private static final int BRICK_Y_OFFSET = 70; /** Number of turns */ private static final int NTURNS = 3; // Game Delay for animation private static final int DELAY = 10; // Globally Scope the Paddle and Ball private GRect paddle; private GOval ball; // Global Scope for Ball Velocities private double vx, vy; // Global Scope for current Turns private int currTurns = NTURNS; /* Method: run() */ /** Runs the Breakout program. */ public void run() { // Add Mouse Listeners addMouseListeners(); // Initialize Game (build boxes) initGame(); // Play Game play(); } /** Builds the Game Board & Paddle. */ private void initGame(){ // Draw Bricks buildBricks(); // Draw Paddle drawPaddle(); // Draw Ball createBall(); } // Builds the Bricks (rainbow colored) private void buildBricks() { // Iterate over each row of bricks for (int i=0; i<NBRICK_ROWS; i++) { // Determine color of row Color rowColor; if (i==0 || i==1) { rowColor = Color.red; } else if (i==2 || i==3) { rowColor = Color.orange; } else if (i==4 || i==5) { rowColor = Color.yellow; } else if (i==6 || i==7) { rowColor = Color.green; } else if (i==8 || i==9) { rowColor = Color.cyan; } else { rowColor = Color.pink; } // Iterate within each row to draw bricks for (int j=0; j<NBRICKS_PER_ROW; j++) { // Determine Current Brick Position double x = BRICK_SEP/2 + j*(BRICK_WIDTH + BRICK_SEP); double y = BRICK_Y_OFFSET + i*(BRICK_HEIGHT + BRICK_SEP); // Create & Append Current Brick GRect brick = new GRect(x, y, BRICK_WIDTH, BRICK_HEIGHT); brick.setFilled(true); brick.setColor(rowColor); add(brick); } } } // Draws the paddle (black color) private void drawPaddle() { // Determine Paddle Position double x = WIDTH/2 - PADDLE_WIDTH/2; double y = HEIGHT - PADDLE_Y_OFFSET - PADDLE_HEIGHT; // Create & Append Paddle paddle = new GRect(x, y, PADDLE_WIDTH, PADDLE_HEIGHT); paddle.setFilled(true); paddle.setColor(Color.black); add(paddle); } // Moves the paddle in response to the mouse movements public void mouseMoved(MouseEvent e) { // Determine limitations to move int leftX = 0; int rightX = WIDTH - PADDLE_WIDTH; // Get current X (and static y) double x = e.getX(); double y = HEIGHT - PADDLE_Y_OFFSET - PADDLE_HEIGHT; // Move Paddle if within game region if (leftX >= 0 && x <= rightX) { paddle.setLocation(x, y); } } // Create the ball private void createBall() { // Determine start location of ball double x = WIDTH/2 - BALL_RADIUS/2; double y = HEIGHT/2 - BALL_RADIUS/2; // Create & Append Ball ball = new GOval(x, y, BALL_RADIUS, BALL_RADIUS); ball.setFilled(true); ball.setColor(Color.black); add(ball); // Initialize Ball Velocities RandomGenerator rgen = RandomGenerator.getInstance(); vx = rgen.nextDouble(1.0, 3.0); if (rgen.nextBoolean(0.5)) { vx = -vx; } vy = 3; } /** Plays the Game */ private void play(){ // Keeps running while turns available while(currTurns > 0) { // Moves Ball animateBall(); } } // Animate the Ball (move it) private void animateBall() { // Move Ball ball.move(vx, vy); // Check Collision checkCollision(); // Delay few milliseconds pause(DELAY); } private void checkCollision() { // Get ball position GPoint ballPosition = ball.getLocation(); double ballX = ballPosition.getX(); double ballY = ballPosition.getY(); // Ball touches left wall if (ballX <= 0) { vx = -vx; } // Ball touches right wall (account for the x,y of ball as top left of square) if(ballX >= WIDTH - BALL_RADIUS*2) { vx = -vx; } // Ball touches top wall if(ballY <= 0) { vy = -vy; } // Ball touches bottom wall (account for the x,y of ball as top left of square) if(ballY >= HEIGHT - BALL_RADIUS*2) { resetBall(); } } // Reset Ball if hits bottom private void resetBall() { // Decrement Turns left currTurns = currTurns - 1; // Check for game loss if (currTurns == 0) { System.out.println("Game Over"); } else { System.out.println(currTurns + " Turn(s) Left!"); // Move ball back to starting position double x = WIDTH/2 - BALL_RADIUS/2; double y = HEIGHT/2 - BALL_RADIUS/2; ball.setLocation(x, y); // Reset Ball Velocities RandomGenerator rgen = RandomGenerator.getInstance(); vx = rgen.nextDouble(1.0, 3.0); if (rgen.nextBoolean(0.5)) { vx = -vx; } vy = 3; } } }
UTF-8
Java
6,147
java
Breakout.java
Java
[ { "context": "ile: Breakout.java\n * -------------------\n * Name: Thomas Thompson\n * \n * This file will eventually implement the ga", "end": 73, "score": 0.9997708201408386, "start": 58, "tag": "NAME", "value": "Thomas Thompson" } ]
null
[]
/* * File: Breakout.java * ------------------- * Name: <NAME> * * This file will eventually implement the game of Breakout. */ import acm.graphics.*; import acm.program.*; import acm.util.*; import java.applet.*; import java.awt.*; import java.awt.event.*; public class Breakout extends GraphicsProgram { /** Width and height of application window in pixels */ public static final int APPLICATION_WIDTH = 400; public static final int APPLICATION_HEIGHT = 600; /** Dimensions of game board (usually the same) */ private static final int WIDTH = APPLICATION_WIDTH; private static final int HEIGHT = APPLICATION_HEIGHT; /** Dimensions of the paddle */ private static final int PADDLE_WIDTH = 60; private static final int PADDLE_HEIGHT = 10; /** Offset of the paddle up from the bottom */ private static final int PADDLE_Y_OFFSET = 30; /** Number of bricks per row */ private static final int NBRICKS_PER_ROW = 10; /** Number of rows of bricks */ private static final int NBRICK_ROWS = 10; /** Separation between bricks */ private static final int BRICK_SEP = 4; /** Width of a brick */ private static final int BRICK_WIDTH = (WIDTH - (NBRICKS_PER_ROW - 1) * BRICK_SEP) / NBRICKS_PER_ROW; /** Height of a brick */ private static final int BRICK_HEIGHT = 8; /** Radius of the ball in pixels */ private static final int BALL_RADIUS = 10; /** Offset of the top brick row from the top */ private static final int BRICK_Y_OFFSET = 70; /** Number of turns */ private static final int NTURNS = 3; // Game Delay for animation private static final int DELAY = 10; // Globally Scope the Paddle and Ball private GRect paddle; private GOval ball; // Global Scope for Ball Velocities private double vx, vy; // Global Scope for current Turns private int currTurns = NTURNS; /* Method: run() */ /** Runs the Breakout program. */ public void run() { // Add Mouse Listeners addMouseListeners(); // Initialize Game (build boxes) initGame(); // Play Game play(); } /** Builds the Game Board & Paddle. */ private void initGame(){ // Draw Bricks buildBricks(); // Draw Paddle drawPaddle(); // Draw Ball createBall(); } // Builds the Bricks (rainbow colored) private void buildBricks() { // Iterate over each row of bricks for (int i=0; i<NBRICK_ROWS; i++) { // Determine color of row Color rowColor; if (i==0 || i==1) { rowColor = Color.red; } else if (i==2 || i==3) { rowColor = Color.orange; } else if (i==4 || i==5) { rowColor = Color.yellow; } else if (i==6 || i==7) { rowColor = Color.green; } else if (i==8 || i==9) { rowColor = Color.cyan; } else { rowColor = Color.pink; } // Iterate within each row to draw bricks for (int j=0; j<NBRICKS_PER_ROW; j++) { // Determine Current Brick Position double x = BRICK_SEP/2 + j*(BRICK_WIDTH + BRICK_SEP); double y = BRICK_Y_OFFSET + i*(BRICK_HEIGHT + BRICK_SEP); // Create & Append Current Brick GRect brick = new GRect(x, y, BRICK_WIDTH, BRICK_HEIGHT); brick.setFilled(true); brick.setColor(rowColor); add(brick); } } } // Draws the paddle (black color) private void drawPaddle() { // Determine Paddle Position double x = WIDTH/2 - PADDLE_WIDTH/2; double y = HEIGHT - PADDLE_Y_OFFSET - PADDLE_HEIGHT; // Create & Append Paddle paddle = new GRect(x, y, PADDLE_WIDTH, PADDLE_HEIGHT); paddle.setFilled(true); paddle.setColor(Color.black); add(paddle); } // Moves the paddle in response to the mouse movements public void mouseMoved(MouseEvent e) { // Determine limitations to move int leftX = 0; int rightX = WIDTH - PADDLE_WIDTH; // Get current X (and static y) double x = e.getX(); double y = HEIGHT - PADDLE_Y_OFFSET - PADDLE_HEIGHT; // Move Paddle if within game region if (leftX >= 0 && x <= rightX) { paddle.setLocation(x, y); } } // Create the ball private void createBall() { // Determine start location of ball double x = WIDTH/2 - BALL_RADIUS/2; double y = HEIGHT/2 - BALL_RADIUS/2; // Create & Append Ball ball = new GOval(x, y, BALL_RADIUS, BALL_RADIUS); ball.setFilled(true); ball.setColor(Color.black); add(ball); // Initialize Ball Velocities RandomGenerator rgen = RandomGenerator.getInstance(); vx = rgen.nextDouble(1.0, 3.0); if (rgen.nextBoolean(0.5)) { vx = -vx; } vy = 3; } /** Plays the Game */ private void play(){ // Keeps running while turns available while(currTurns > 0) { // Moves Ball animateBall(); } } // Animate the Ball (move it) private void animateBall() { // Move Ball ball.move(vx, vy); // Check Collision checkCollision(); // Delay few milliseconds pause(DELAY); } private void checkCollision() { // Get ball position GPoint ballPosition = ball.getLocation(); double ballX = ballPosition.getX(); double ballY = ballPosition.getY(); // Ball touches left wall if (ballX <= 0) { vx = -vx; } // Ball touches right wall (account for the x,y of ball as top left of square) if(ballX >= WIDTH - BALL_RADIUS*2) { vx = -vx; } // Ball touches top wall if(ballY <= 0) { vy = -vy; } // Ball touches bottom wall (account for the x,y of ball as top left of square) if(ballY >= HEIGHT - BALL_RADIUS*2) { resetBall(); } } // Reset Ball if hits bottom private void resetBall() { // Decrement Turns left currTurns = currTurns - 1; // Check for game loss if (currTurns == 0) { System.out.println("Game Over"); } else { System.out.println(currTurns + " Turn(s) Left!"); // Move ball back to starting position double x = WIDTH/2 - BALL_RADIUS/2; double y = HEIGHT/2 - BALL_RADIUS/2; ball.setLocation(x, y); // Reset Ball Velocities RandomGenerator rgen = RandomGenerator.getInstance(); vx = rgen.nextDouble(1.0, 3.0); if (rgen.nextBoolean(0.5)) { vx = -vx; } vy = 3; } } }
6,138
0.624695
0.612982
302
19.354305
17.801805
81
false
false
0
0
0
0
0
0
2.139073
false
false
1
2c2e109a0908715cd2e386aa5ccd28adb0c203b7
8,443,905,726,183
28725543f66badc90563a29f7cfe4879816e1ca9
/src/com/jacamars/dsp/rtb/probe/CreativeProbe.java
d017e1c9978cb203c670194eddd8ad603ad1db0c
[ "Apache-2.0" ]
permissive
zorrofox/Newbidder
https://github.com/zorrofox/Newbidder
06e0f9c99a84c4173e260257528399c89b8bb5af
da7a61ba22c3985c7c72c4d1ddf617ca3be9c380
refs/heads/master
2023-08-15T22:23:16.590000
2021-09-17T17:14:55
2021-09-17T17:14:55
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.jacamars.dsp.rtb.probe; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.LongAdder; /** * A class that keeps up with the creative probes (why the creative didn't bid). * * @author Ben M. Faul */ public class CreativeProbe { String creative; Map<String, LongAdder> probes; LongAdder total = new LongAdder(); LongAdder bid = new LongAdder(); public static ObjectMapper mapper = new ObjectMapper(); static { mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); } public CreativeProbe() { } public CreativeProbe(String creative) { this.creative = creative; probes = new ConcurrentHashMap<>(); } public void reset() { probes = new ConcurrentHashMap(); total = new LongAdder(); bid = new LongAdder(); } public void process(String key) { LongAdder ad = probes.get(key); if (ad == null) { ad = new LongAdder(); probes.put(key, ad); } ad.increment(); total.increment(); } public void process() { total.increment(); bid.increment(); } public String report() { StringBuilder report = new StringBuilder(); report.append("\t\t\ttotal = "); report.append(total.sum()); report.append(", bids = "); report.append("\n"); for (Map.Entry<String, LongAdder> entry : probes.entrySet()) { String key = entry.getKey(); report.append("\t\t\t"); report.append(key); report.append(" = "); LongAdder ad = entry.getValue(); report.append(ad.sum()); report.append(", ("); double v = total.sum(); double vx = ad.sum(); report.append(100 * vx / v); report.append(")\n"); } return report.toString(); } public void reportCsv(StringBuilder sb, String pre) { pre = pre + creative + "," + total.sum() + ", " + bid.sum(); // Sort the list List<EntryField> values = new ArrayList<EntryField>(); for (Map.Entry<String, LongAdder> entry : probes.entrySet()) { EntryField ef = new EntryField(entry.getKey(), entry.getValue().sum()); values.add(ef); } Collections.sort(values, Collections.reverseOrder()); for (EntryField ef : values) { String key = "\"" + ef.key.trim() + "\""; sb.append(pre + "," + key + "," + total.sum() + "," + ef.value + "\n"); } } public void reportJson(StringBuilder sb, long grandtotal, String exchange, long bidstotal, String campaign) throws Exception { for (Map.Entry<String, LongAdder> entry : probes.entrySet()) { EntryField ef = new EntryField(entry.getKey(), entry.getValue().sum()); Map report = new HashMap(); report.put("timestamp",System.currentTimeMillis()); report.put("exchange",exchange); report.put("campaign",campaign); report.put("creative",creative); report.put("reason",ef.key.replaceAll("\n","")); report.put("reasoncount",ef.value); String content = mapper.writer().writeValueAsString(report); sb.append(content); sb.append("\n"); } } public long getSumBids() { return bid.sum(); } public long getSumTotal() { return total.sum(); } public List getMap() { Map x = new HashMap(); List list = new ArrayList(); /** * Sort the list first */ List<EntryField> values = new ArrayList<EntryField>(); for (Map.Entry<String, LongAdder> entry : probes.entrySet()) { EntryField ef = new EntryField(entry.getKey(), entry.getValue().sum()); values.add(ef); } Collections.sort(values, Collections.reverseOrder()); // Now create the map for (EntryField e : values) { x = new HashMap(); x.put("name", e.key); x.put("count", e.value); list.add(x); } return list; } public List<Reason> getReasons() { List<Reason> list = new ArrayList(); /** * Sort the list first */ List<EntryField> values = new ArrayList<EntryField>(); for (Map.Entry<String, LongAdder> entry : probes.entrySet()) { EntryField ef = new EntryField(entry.getKey(), entry.getValue().sum()); values.add(ef); } Collections.sort(values, Collections.reverseOrder()); // Now create the map for (EntryField e : values) { Reason x = new Reason(); x.name = e.key; x.count = e.value; list.add(x); } return list; } public String getTable() { double nobids = total.sum() - bid.sum(); StringBuilder table = new StringBuilder("<table border='1'>"); table.append("<tr><td>total</td><td>"); table.append(total.sum()); table.append("</td></tr>"); table.append("<tr><td>bids</td><td>"); table.append(bid.sum()); table.append("</td></tr>"); table.append("<tr><td>no bids:</td><td>"); table.append((total.sum() - bid.sum())); table.append("</td></tr>"); if (probes.entrySet().size() > 0) { table.append("<table>"); table.append("<tr><td>Reasons</td><td><table border='1'><th>Reason</th><th>Count</th><th>Percent</th>"); List<EntryField> values = new ArrayList<EntryField>(); for (Map.Entry<String, LongAdder> entry : probes.entrySet()) { EntryField ef = new EntryField(entry.getKey(), entry.getValue().sum()); values.add(ef); } Collections.sort(values, Collections.reverseOrder()); for (EntryField e : values) { table.append("<tr><td>"); table.append(e.key); table.append("</td><td>"); table.append(e.value); table.append("</td><td>"); table.append((e.value / nobids * 100)); table.append("</td></tr>"); } table.append("</table></td></tr></td></tr>"); } else { table.append("</td></tr></td></tr>"); } table.append("</table>"); return table.toString(); } }
UTF-8
Java
6,843
java
CreativeProbe.java
Java
[ { "context": "robes (why the creative didn't bid).\n *\n * @author Ben M. Faul\n */\npublic class CreativeProbe {\n\n String crea", "end": 429, "score": 0.9998348355293274, "start": 418, "tag": "NAME", "value": "Ben M. Faul" }, { "context": " values) {\n String key = \"\\\"\" + ef.key.trim() + \"\\\"\";\n sb.append(pre + \",\" + key + \"", "end": 2775, "score": 0.6809245347976685, "start": 2769, "tag": "KEY", "value": "trim()" } ]
null
[]
package com.jacamars.dsp.rtb.probe; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.LongAdder; /** * A class that keeps up with the creative probes (why the creative didn't bid). * * @author <NAME> */ public class CreativeProbe { String creative; Map<String, LongAdder> probes; LongAdder total = new LongAdder(); LongAdder bid = new LongAdder(); public static ObjectMapper mapper = new ObjectMapper(); static { mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); } public CreativeProbe() { } public CreativeProbe(String creative) { this.creative = creative; probes = new ConcurrentHashMap<>(); } public void reset() { probes = new ConcurrentHashMap(); total = new LongAdder(); bid = new LongAdder(); } public void process(String key) { LongAdder ad = probes.get(key); if (ad == null) { ad = new LongAdder(); probes.put(key, ad); } ad.increment(); total.increment(); } public void process() { total.increment(); bid.increment(); } public String report() { StringBuilder report = new StringBuilder(); report.append("\t\t\ttotal = "); report.append(total.sum()); report.append(", bids = "); report.append("\n"); for (Map.Entry<String, LongAdder> entry : probes.entrySet()) { String key = entry.getKey(); report.append("\t\t\t"); report.append(key); report.append(" = "); LongAdder ad = entry.getValue(); report.append(ad.sum()); report.append(", ("); double v = total.sum(); double vx = ad.sum(); report.append(100 * vx / v); report.append(")\n"); } return report.toString(); } public void reportCsv(StringBuilder sb, String pre) { pre = pre + creative + "," + total.sum() + ", " + bid.sum(); // Sort the list List<EntryField> values = new ArrayList<EntryField>(); for (Map.Entry<String, LongAdder> entry : probes.entrySet()) { EntryField ef = new EntryField(entry.getKey(), entry.getValue().sum()); values.add(ef); } Collections.sort(values, Collections.reverseOrder()); for (EntryField ef : values) { String key = "\"" + ef.key.trim() + "\""; sb.append(pre + "," + key + "," + total.sum() + "," + ef.value + "\n"); } } public void reportJson(StringBuilder sb, long grandtotal, String exchange, long bidstotal, String campaign) throws Exception { for (Map.Entry<String, LongAdder> entry : probes.entrySet()) { EntryField ef = new EntryField(entry.getKey(), entry.getValue().sum()); Map report = new HashMap(); report.put("timestamp",System.currentTimeMillis()); report.put("exchange",exchange); report.put("campaign",campaign); report.put("creative",creative); report.put("reason",ef.key.replaceAll("\n","")); report.put("reasoncount",ef.value); String content = mapper.writer().writeValueAsString(report); sb.append(content); sb.append("\n"); } } public long getSumBids() { return bid.sum(); } public long getSumTotal() { return total.sum(); } public List getMap() { Map x = new HashMap(); List list = new ArrayList(); /** * Sort the list first */ List<EntryField> values = new ArrayList<EntryField>(); for (Map.Entry<String, LongAdder> entry : probes.entrySet()) { EntryField ef = new EntryField(entry.getKey(), entry.getValue().sum()); values.add(ef); } Collections.sort(values, Collections.reverseOrder()); // Now create the map for (EntryField e : values) { x = new HashMap(); x.put("name", e.key); x.put("count", e.value); list.add(x); } return list; } public List<Reason> getReasons() { List<Reason> list = new ArrayList(); /** * Sort the list first */ List<EntryField> values = new ArrayList<EntryField>(); for (Map.Entry<String, LongAdder> entry : probes.entrySet()) { EntryField ef = new EntryField(entry.getKey(), entry.getValue().sum()); values.add(ef); } Collections.sort(values, Collections.reverseOrder()); // Now create the map for (EntryField e : values) { Reason x = new Reason(); x.name = e.key; x.count = e.value; list.add(x); } return list; } public String getTable() { double nobids = total.sum() - bid.sum(); StringBuilder table = new StringBuilder("<table border='1'>"); table.append("<tr><td>total</td><td>"); table.append(total.sum()); table.append("</td></tr>"); table.append("<tr><td>bids</td><td>"); table.append(bid.sum()); table.append("</td></tr>"); table.append("<tr><td>no bids:</td><td>"); table.append((total.sum() - bid.sum())); table.append("</td></tr>"); if (probes.entrySet().size() > 0) { table.append("<table>"); table.append("<tr><td>Reasons</td><td><table border='1'><th>Reason</th><th>Count</th><th>Percent</th>"); List<EntryField> values = new ArrayList<EntryField>(); for (Map.Entry<String, LongAdder> entry : probes.entrySet()) { EntryField ef = new EntryField(entry.getKey(), entry.getValue().sum()); values.add(ef); } Collections.sort(values, Collections.reverseOrder()); for (EntryField e : values) { table.append("<tr><td>"); table.append(e.key); table.append("</td><td>"); table.append(e.value); table.append("</td><td>"); table.append((e.value / nobids * 100)); table.append("</td></tr>"); } table.append("</table></td></tr></td></tr>"); } else { table.append("</td></tr></td></tr>"); } table.append("</table>"); return table.toString(); } }
6,838
0.53836
0.537045
222
29.824324
24.685787
130
false
false
0
0
0
0
0
0
0.68018
false
false
1
47f32e1c9a763ac5f7baeceecc384bab3e005094
19,301,583,046,808
5e878ee2dd2f3752f7373cc790846497e2ea9bc3
/13.Serializable/src/p1/Person.java
34428b1a4c8294b7491bf4e02714efa78f39b823
[ "Apache-2.0" ]
permissive
RGU5Android/JavaDemoCDAC
https://github.com/RGU5Android/JavaDemoCDAC
486f11ebeb5bc02f6d0417192dfaa77896588324
20d44c74dacd9b055353075e07323af72bc84c4d
refs/heads/master
2021-01-17T11:51:46.497000
2014-06-03T07:37:05
2014-06-03T07:37:05
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package p1; import java.io.Serializable; public class Person implements Serializable { private static final long serialVersionUID = 1L; int age; String name; public Person(int age, String name) { this.age = age; this.name = name; } public Person() { this(23, "Rahul G. Uppalwar"); } @Override public String toString() { return "Person : AGE = " + age + " NAME = " + name + "\n"; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
UTF-8
Java
649
java
Person.java
Java
[ { "context": "me = name;\r\n\t}\r\n\r\n\tpublic Person() {\r\n\t\tthis(23, \"Rahul G. Uppalwar\");\r\n\t}\r\n\r\n\t@Override\r\n\tpublic String toString() {", "end": 310, "score": 0.9998859763145447, "start": 293, "tag": "NAME", "value": "Rahul G. Uppalwar" } ]
null
[]
package p1; import java.io.Serializable; public class Person implements Serializable { private static final long serialVersionUID = 1L; int age; String name; public Person(int age, String name) { this.age = age; this.name = name; } public Person() { this(23, "<NAME>"); } @Override public String toString() { return "Person : AGE = " + age + " NAME = " + name + "\n"; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
638
0.599384
0.59322
41
13.829268
15.570301
60
false
false
0
0
0
0
0
0
1.195122
false
false
1
8104826948dff3c6ea98c161ba1876f81b134463
3,083,786,577,600
ed7f6813ee91ff4340d0a97b88bc680513da4877
/src/main/java/com/ohdoking/kstreemap/model/Company.java
212d85a28880ffbcf755fa0fa6046c61c9bfcf24
[]
no_license
ohdoking/ks-treemap-backend-spring
https://github.com/ohdoking/ks-treemap-backend-spring
b03c5b2da49ca8aec769fbfe48cf89d3dac02f8a
db97bf968d56daee6acc3ff617b30ac809ccab04
refs/heads/master
2022-12-10T17:54:23.619000
2020-08-26T16:52:30
2020-08-26T16:52:30
289,972,994
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.ohdoking.kstreemap.model; import com.fasterxml.jackson.annotation.JsonInclude; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import javax.persistence.Entity; import javax.persistence.Id; import java.sql.Timestamp; import java.util.UUID; @Entity(name = "company") @Data @AllArgsConstructor @NoArgsConstructor @JsonInclude(JsonInclude.Include.NON_NULL) public class Company { @Id private UUID id; private String ticker; private String name; private Float marketCap; private UUID stockMarketId; private boolean isUse; private Timestamp createdDate; private Timestamp updatedDate; }
UTF-8
Java
671
java
Company.java
Java
[]
null
[]
package com.ohdoking.kstreemap.model; import com.fasterxml.jackson.annotation.JsonInclude; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import javax.persistence.Entity; import javax.persistence.Id; import java.sql.Timestamp; import java.util.UUID; @Entity(name = "company") @Data @AllArgsConstructor @NoArgsConstructor @JsonInclude(JsonInclude.Include.NON_NULL) public class Company { @Id private UUID id; private String ticker; private String name; private Float marketCap; private UUID stockMarketId; private boolean isUse; private Timestamp createdDate; private Timestamp updatedDate; }
671
0.780924
0.780924
28
22.964285
13.047939
52
false
false
0
0
0
0
0
0
0.607143
false
false
1
c636ef6cda83115a573f78093b2a7b19e9ef0fa0
14,551,349,258,457
9f93a6b0a9a3e5dd860d07afd3af81cf7ae21ee0
/src/main/src/com/highershine/dna/warning/pojo/OffenderGroup.java
32cf80f2966a558d3daf5c8f344caab8240f8952
[]
no_license
cuiqiusheng/dna_warning
https://github.com/cuiqiusheng/dna_warning
b5af0aeb5a8fd3394bcb71701090388900d21b38
e1855323567ce4a7bd3a304e2760a104d05de80d
refs/heads/master
2016-09-18T23:50:42.640000
2016-08-18T08:15:19
2016-08-18T08:15:19
65,969,099
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.highershine.dna.warning.pojo; import java.util.Date; /** * 重点人员实体类 */ public class OffenderGroup { private static final long serialVersionUID = 1L; private String id; private String personName;// 人员名称 private String idCodeNo;// 证件号码 private String personProperty;// 人员类别 private String dataSource;// 数据来源 private String personLevel;// 人员级别 private String gzyy;// 关注原因 private String contactInfo;// 联系人信息,姓名、电话、地址,可以有多个 private String status = "0";// 处理状态,0、初始状态 1、待处理2、处理中3、已办结 private String deleteFlag;// 删除状态0,1 private Date createDatetime;// 录入时间 private String createUser;// 录入人 private Date updateDatetime;// 修改时间 private String updateUser;// 修改人 public OffenderGroup() { super(); } public OffenderGroup(String id, String personName, String idCodeNo, String personProperty, String dataSource, String personLevel, String gzyy, String contactInfo, String status, String deleteFlag, Date createDatetime, String createUser, Date updateDatetime, String updateUser) { super(); this.id = id; this.personName = personName; this.idCodeNo = idCodeNo; this.personProperty = personProperty; this.dataSource = dataSource; this.personLevel = personLevel; this.gzyy = gzyy; this.contactInfo = contactInfo; this.status = status; this.deleteFlag = deleteFlag; this.createDatetime = createDatetime; this.createUser = createUser; this.updateDatetime = updateDatetime; this.updateUser = updateUser; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getPersonName() { return personName; } public void setPersonName(String personName) { this.personName = personName; } public String getIdCodeNo() { return idCodeNo; } public void setIdCodeNo(String idCodeNo) { this.idCodeNo = idCodeNo; } public String getPersonProperty() { return personProperty; } public void setPersonProperty(String personProperty) { this.personProperty = personProperty; } public String getDataSource() { return dataSource; } public void setDataSource(String dataSource) { this.dataSource = dataSource; } public String getPersonLevel() { return personLevel; } public void setPersonLevel(String personLevel) { this.personLevel = personLevel; } public String getGzyy() { return gzyy; } public void setGzyy(String gzyy) { this.gzyy = gzyy; } public String getContactInfo() { return contactInfo; } public void setContactInfo(String contactInfo) { this.contactInfo = contactInfo; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getDeleteFlag() { return deleteFlag; } public void setDeleteFlag(String deleteFlag) { this.deleteFlag = deleteFlag; } public Date getCreateDatetime() { return createDatetime; } public void setCreateDatetime(Date createDatetime) { this.createDatetime = createDatetime; } public String getCreateUser() { return createUser; } public void setCreateUser(String createUser) { this.createUser = createUser; } public Date getUpdateDatetime() { return updateDatetime; } public void setUpdateDatetime(Date updateDatetime) { this.updateDatetime = updateDatetime; } public String getUpdateUser() { return updateUser; } public void setUpdateUser(String updateUser) { this.updateUser = updateUser; } }
UTF-8
Java
3,600
java
OffenderGroup.java
Java
[ { "context": ") {\n\t\tsuper();\n\t\tthis.id = id;\n\t\tthis.personName = personName;\n\t\tthis.idCodeNo = idCodeNo;\n\t\tthis.personPro", "end": 1076, "score": 0.9947037100791931, "start": 1070, "tag": "NAME", "value": "person" }, { "context": "uper();\n\t\tthis.id = id;\n\t\tthis.personName = personName;\n\t\tthis.idCodeNo = idCodeNo;\n\t\tthis.personPropert", "end": 1080, "score": 0.6587139964103699, "start": 1076, "tag": "NAME", "value": "Name" } ]
null
[]
package com.highershine.dna.warning.pojo; import java.util.Date; /** * 重点人员实体类 */ public class OffenderGroup { private static final long serialVersionUID = 1L; private String id; private String personName;// 人员名称 private String idCodeNo;// 证件号码 private String personProperty;// 人员类别 private String dataSource;// 数据来源 private String personLevel;// 人员级别 private String gzyy;// 关注原因 private String contactInfo;// 联系人信息,姓名、电话、地址,可以有多个 private String status = "0";// 处理状态,0、初始状态 1、待处理2、处理中3、已办结 private String deleteFlag;// 删除状态0,1 private Date createDatetime;// 录入时间 private String createUser;// 录入人 private Date updateDatetime;// 修改时间 private String updateUser;// 修改人 public OffenderGroup() { super(); } public OffenderGroup(String id, String personName, String idCodeNo, String personProperty, String dataSource, String personLevel, String gzyy, String contactInfo, String status, String deleteFlag, Date createDatetime, String createUser, Date updateDatetime, String updateUser) { super(); this.id = id; this.personName = personName; this.idCodeNo = idCodeNo; this.personProperty = personProperty; this.dataSource = dataSource; this.personLevel = personLevel; this.gzyy = gzyy; this.contactInfo = contactInfo; this.status = status; this.deleteFlag = deleteFlag; this.createDatetime = createDatetime; this.createUser = createUser; this.updateDatetime = updateDatetime; this.updateUser = updateUser; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getPersonName() { return personName; } public void setPersonName(String personName) { this.personName = personName; } public String getIdCodeNo() { return idCodeNo; } public void setIdCodeNo(String idCodeNo) { this.idCodeNo = idCodeNo; } public String getPersonProperty() { return personProperty; } public void setPersonProperty(String personProperty) { this.personProperty = personProperty; } public String getDataSource() { return dataSource; } public void setDataSource(String dataSource) { this.dataSource = dataSource; } public String getPersonLevel() { return personLevel; } public void setPersonLevel(String personLevel) { this.personLevel = personLevel; } public String getGzyy() { return gzyy; } public void setGzyy(String gzyy) { this.gzyy = gzyy; } public String getContactInfo() { return contactInfo; } public void setContactInfo(String contactInfo) { this.contactInfo = contactInfo; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getDeleteFlag() { return deleteFlag; } public void setDeleteFlag(String deleteFlag) { this.deleteFlag = deleteFlag; } public Date getCreateDatetime() { return createDatetime; } public void setCreateDatetime(Date createDatetime) { this.createDatetime = createDatetime; } public String getCreateUser() { return createUser; } public void setCreateUser(String createUser) { this.createUser = createUser; } public Date getUpdateDatetime() { return updateDatetime; } public void setUpdateDatetime(Date updateDatetime) { this.updateDatetime = updateDatetime; } public String getUpdateUser() { return updateUser; } public void setUpdateUser(String updateUser) { this.updateUser = updateUser; } }
3,600
0.735673
0.733333
167
19.479042
18.418566
69
false
false
0
0
0
0
0
0
1.502994
false
false
1
39b5bb4abefec1724e6bd529aab30a935a2b65b0
16,681,652,997,263
292dd944f69b3c2a5ce66837fd165c1a1854d246
/src/main/java/ru/sbtqa/tag/stepdefs/ru/ApiStepDefs.java
ca9caa5d586060376c61b8eaecd823a322b0aa3b
[ "Apache-2.0" ]
permissive
sbtqa/api-factory
https://github.com/sbtqa/api-factory
da974cab7c8d157391612674977d7dea89921d1f
f727124b5c1e83c7f0ca5c2e68dcb21a594cfef8
refs/heads/master
2021-07-05T03:18:04.772000
2020-11-15T10:32:50
2020-11-15T10:32:50
73,985,461
9
3
null
false
2018-07-24T04:53:01
2016-11-17T03:13:02
2018-06-15T12:23:19
2018-07-24T04:52:07
165
10
3
4
Java
false
null
package ru.sbtqa.tag.stepdefs.ru; import cucumber.api.DataTable; import cucumber.api.java.Before; import cucumber.api.java.bg.И; import ru.sbtqa.tag.apifactory.exception.ApiException; import ru.sbtqa.tag.stepdefs.ApiGenericStepDefs; public class ApiStepDefs extends ApiGenericStepDefs { @Before public void iniApi() { super.initApi(); } /** * {@inheritDoc} */ @Override @И("^(?:пользователь |он )?отправляет запрос \"([^\"]*)\"$") public void userSendRequestNoParams(String action) throws ApiException { super.userSendRequestNoParams(action); } /** * {@inheritDoc} */ @Override @И("^(?:пользователь |он )?отправляет запрос \"([^\"]*)\" с параметрами:?$") public void userSendRequestTableParam(String action, DataTable dataTable) throws ApiException { super.userSendRequestTableParam(action, dataTable); } /** * {@inheritDoc} */ @Override @И("^система возвращает ответ \"([^\"]*)\"$") public void userValidate(String rule) throws ApiException { super.userValidate(rule); } /** * {@inheritDoc} */ @Override @И("^система возвращает ответ \"([^\"]*)\" с параметрами:?$") public void userValidateTable(String rule, DataTable dataTable) throws ApiException { super.userValidateTable(rule, dataTable); } }
UTF-8
Java
1,512
java
ApiStepDefs.java
Java
[]
null
[]
package ru.sbtqa.tag.stepdefs.ru; import cucumber.api.DataTable; import cucumber.api.java.Before; import cucumber.api.java.bg.И; import ru.sbtqa.tag.apifactory.exception.ApiException; import ru.sbtqa.tag.stepdefs.ApiGenericStepDefs; public class ApiStepDefs extends ApiGenericStepDefs { @Before public void iniApi() { super.initApi(); } /** * {@inheritDoc} */ @Override @И("^(?:пользователь |он )?отправляет запрос \"([^\"]*)\"$") public void userSendRequestNoParams(String action) throws ApiException { super.userSendRequestNoParams(action); } /** * {@inheritDoc} */ @Override @И("^(?:пользователь |он )?отправляет запрос \"([^\"]*)\" с параметрами:?$") public void userSendRequestTableParam(String action, DataTable dataTable) throws ApiException { super.userSendRequestTableParam(action, dataTable); } /** * {@inheritDoc} */ @Override @И("^система возвращает ответ \"([^\"]*)\"$") public void userValidate(String rule) throws ApiException { super.userValidate(rule); } /** * {@inheritDoc} */ @Override @И("^система возвращает ответ \"([^\"]*)\" с параметрами:?$") public void userValidateTable(String rule, DataTable dataTable) throws ApiException { super.userValidateTable(rule, dataTable); } }
1,512
0.639594
0.639594
52
25.51923
26.282848
99
false
false
0
0
0
0
0
0
0.326923
false
false
1
691da65b6511e2b1999925193dd5af87144b6d0c
30,726,196,077,827
d0afcfa22dabbd457dc556c671ac833b31c919c2
/Maze.java
768052d76f53d0c1bc9a7f840a750fafed29143e
[]
no_license
IQ01660/MazeGenerator
https://github.com/IQ01660/MazeGenerator
9acfdf44ece0f9de5595d5b97994264cdb834344
e3fb08f03467013ac45cce87e7598684ceb6d6f7
refs/heads/master
2020-04-13T06:48:13.499000
2018-12-25T00:25:49
2018-12-25T00:25:49
163,031,226
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.awt.Color; import java.awt.Graphics; import java.util.ArrayList; import java.util.Random; public class Maze { public static Cell sampleCell = new Cell(100, 100); public static final int COLS = Animation.WIDTH / sampleCell.width; public static final int ROWS = Animation.HEIGHT / sampleCell.height; public static Cell currentCell; public static Cell[][] cellsMatrix = new Cell[ROWS][COLS]; public static Random rand = new Random(); public static ArrayList<Cell> visitedCells = new ArrayList<Cell>(); public static void positionCells() { for(int r = 0; r < ROWS; r++) { for(int c = 0; c < COLS; c++) { Maze.cellsMatrix[r][c] = new Cell(r, c); //the top left cell is currentCell initially if (r == 0 && c == 0) { Maze.currentCell = Maze.cellsMatrix[r][c]; Maze.currentCell.isVisited = true; } } } } public static void showAll(Graphics g) { for(int r = 0; r < ROWS; r++) { for(int c = 0; c < COLS; c++) { Maze.cellsMatrix[r][c].show(g); } } } public static boolean areAllVisited() { boolean status = true; for(int r = 0; r < ROWS; r++) { for(int c = 0; c < COLS; c++) { //System.out.println(Maze.cellsMatrix[r][c].isVisited); if(Maze.cellsMatrix[r][c].isVisited == false) { status = false; break; } } } return status; } /** * checks whether a coordinate is inside the matrix * @param cur */ public static boolean isIn(int _row, int _col) { boolean status = false; if (_row >= 0 && _row < ROWS && _col >= 0 && _col < COLS) { status = true; } return status; } public static Cell unvisitedNeighbor(Cell cur) { ArrayList<Cell> neighbors = new ArrayList<Cell>(); int topRow = cur.row - 1; int topCol = cur.col; if (Maze.isIn(topRow, topCol) && Maze.cellsMatrix[topRow][topCol].isVisited == false) { neighbors.add(Maze.cellsMatrix[topRow][topCol]); } int rightRow = cur.row; int rightCol = cur.col + 1; if (Maze.isIn(rightRow, rightCol) && Maze.cellsMatrix[rightRow][rightCol].isVisited == false) { neighbors.add(Maze.cellsMatrix[rightRow][rightCol]); } int bottomRow = cur.row + 1; int bottomCol = cur.col; if (Maze.isIn(bottomRow, bottomCol) && Maze.cellsMatrix[bottomRow][bottomCol].isVisited == false) { neighbors.add(Maze.cellsMatrix[bottomRow][bottomCol]); } int leftRow = cur.row; int leftCol = cur.col - 1; if (Maze.isIn(leftRow, leftCol) && Maze.cellsMatrix[leftRow][leftCol].isVisited == false) { neighbors.add(Maze.cellsMatrix[leftRow][leftCol]); } //picking a random cell Cell chosen = neighbors.get(rand.nextInt(neighbors.size())); //System.out.println(currentCell.col + " " + currentCell.row + " ; " + chosen.col + " " + chosen.row); return chosen; } public static boolean hasUnvisitedNeighbor(Cell cur) { boolean status = false; int topRow = cur.row - 1; int topCol = cur.col; if (Maze.isIn(topRow, topCol) && Maze.cellsMatrix[topRow][topCol].isVisited == false) { status = true; } int rightRow = cur.row; int rightCol = cur.col + 1; if (Maze.isIn(rightRow, rightCol) && Maze.cellsMatrix[rightRow][rightCol].isVisited == false) { status = true; } int bottomRow = cur.row + 1; int bottomCol = cur.col; if (Maze.isIn(bottomRow, bottomCol) && Maze.cellsMatrix[bottomRow][bottomCol].isVisited == false) { status = true; } int leftRow = cur.row; int leftCol = cur.col - 1; if (Maze.isIn(leftRow, leftCol) && Maze.cellsMatrix[leftRow][leftCol].isVisited == false) { status = true; } //picking a random cell return status; } public static void removeWall() { Cell chosen = Maze.visitedCells.get(visitedCells.size() - 1); if(chosen.col - currentCell.col < 0) { chosen.sidesStatus[1] = false; currentCell.sidesStatus[3] = false; } else if(chosen.col - currentCell.col > 0) { chosen.sidesStatus[3] = false; currentCell.sidesStatus[1] = false; } else if(chosen.row - currentCell.row < 0) { chosen.sidesStatus[2] = false; currentCell.sidesStatus[0] = false; } else if(chosen.row - currentCell.row > 0) { chosen.sidesStatus[0] = false; currentCell.sidesStatus[2] = false; } chosen.isVisited = true; //change the current cell currentCell = chosen; //System.out.println(currentCell.col + " " + currentCell.row); } public static void buildMaze() { if (Maze.hasUnvisitedNeighbor(Maze.currentCell)) { Maze.visitedCells.add(Maze.unvisitedNeighbor(currentCell)); Maze.removeWall(); } else if (Maze.visitedCells.size() > 0) { Maze.currentCell = Maze.visitedCells.remove(visitedCells.size() - 1); } } }
UTF-8
Java
4,613
java
Maze.java
Java
[]
null
[]
import java.awt.Color; import java.awt.Graphics; import java.util.ArrayList; import java.util.Random; public class Maze { public static Cell sampleCell = new Cell(100, 100); public static final int COLS = Animation.WIDTH / sampleCell.width; public static final int ROWS = Animation.HEIGHT / sampleCell.height; public static Cell currentCell; public static Cell[][] cellsMatrix = new Cell[ROWS][COLS]; public static Random rand = new Random(); public static ArrayList<Cell> visitedCells = new ArrayList<Cell>(); public static void positionCells() { for(int r = 0; r < ROWS; r++) { for(int c = 0; c < COLS; c++) { Maze.cellsMatrix[r][c] = new Cell(r, c); //the top left cell is currentCell initially if (r == 0 && c == 0) { Maze.currentCell = Maze.cellsMatrix[r][c]; Maze.currentCell.isVisited = true; } } } } public static void showAll(Graphics g) { for(int r = 0; r < ROWS; r++) { for(int c = 0; c < COLS; c++) { Maze.cellsMatrix[r][c].show(g); } } } public static boolean areAllVisited() { boolean status = true; for(int r = 0; r < ROWS; r++) { for(int c = 0; c < COLS; c++) { //System.out.println(Maze.cellsMatrix[r][c].isVisited); if(Maze.cellsMatrix[r][c].isVisited == false) { status = false; break; } } } return status; } /** * checks whether a coordinate is inside the matrix * @param cur */ public static boolean isIn(int _row, int _col) { boolean status = false; if (_row >= 0 && _row < ROWS && _col >= 0 && _col < COLS) { status = true; } return status; } public static Cell unvisitedNeighbor(Cell cur) { ArrayList<Cell> neighbors = new ArrayList<Cell>(); int topRow = cur.row - 1; int topCol = cur.col; if (Maze.isIn(topRow, topCol) && Maze.cellsMatrix[topRow][topCol].isVisited == false) { neighbors.add(Maze.cellsMatrix[topRow][topCol]); } int rightRow = cur.row; int rightCol = cur.col + 1; if (Maze.isIn(rightRow, rightCol) && Maze.cellsMatrix[rightRow][rightCol].isVisited == false) { neighbors.add(Maze.cellsMatrix[rightRow][rightCol]); } int bottomRow = cur.row + 1; int bottomCol = cur.col; if (Maze.isIn(bottomRow, bottomCol) && Maze.cellsMatrix[bottomRow][bottomCol].isVisited == false) { neighbors.add(Maze.cellsMatrix[bottomRow][bottomCol]); } int leftRow = cur.row; int leftCol = cur.col - 1; if (Maze.isIn(leftRow, leftCol) && Maze.cellsMatrix[leftRow][leftCol].isVisited == false) { neighbors.add(Maze.cellsMatrix[leftRow][leftCol]); } //picking a random cell Cell chosen = neighbors.get(rand.nextInt(neighbors.size())); //System.out.println(currentCell.col + " " + currentCell.row + " ; " + chosen.col + " " + chosen.row); return chosen; } public static boolean hasUnvisitedNeighbor(Cell cur) { boolean status = false; int topRow = cur.row - 1; int topCol = cur.col; if (Maze.isIn(topRow, topCol) && Maze.cellsMatrix[topRow][topCol].isVisited == false) { status = true; } int rightRow = cur.row; int rightCol = cur.col + 1; if (Maze.isIn(rightRow, rightCol) && Maze.cellsMatrix[rightRow][rightCol].isVisited == false) { status = true; } int bottomRow = cur.row + 1; int bottomCol = cur.col; if (Maze.isIn(bottomRow, bottomCol) && Maze.cellsMatrix[bottomRow][bottomCol].isVisited == false) { status = true; } int leftRow = cur.row; int leftCol = cur.col - 1; if (Maze.isIn(leftRow, leftCol) && Maze.cellsMatrix[leftRow][leftCol].isVisited == false) { status = true; } //picking a random cell return status; } public static void removeWall() { Cell chosen = Maze.visitedCells.get(visitedCells.size() - 1); if(chosen.col - currentCell.col < 0) { chosen.sidesStatus[1] = false; currentCell.sidesStatus[3] = false; } else if(chosen.col - currentCell.col > 0) { chosen.sidesStatus[3] = false; currentCell.sidesStatus[1] = false; } else if(chosen.row - currentCell.row < 0) { chosen.sidesStatus[2] = false; currentCell.sidesStatus[0] = false; } else if(chosen.row - currentCell.row > 0) { chosen.sidesStatus[0] = false; currentCell.sidesStatus[2] = false; } chosen.isVisited = true; //change the current cell currentCell = chosen; //System.out.println(currentCell.col + " " + currentCell.row); } public static void buildMaze() { if (Maze.hasUnvisitedNeighbor(Maze.currentCell)) { Maze.visitedCells.add(Maze.unvisitedNeighbor(currentCell)); Maze.removeWall(); } else if (Maze.visitedCells.size() > 0) { Maze.currentCell = Maze.visitedCells.remove(visitedCells.size() - 1); } } }
4,613
0.658574
0.650119
146
30.602739
25.422318
104
false
false
0
0
0
0
0
0
2.732877
false
false
1
7ab06e111a2ce66e2678bd2d98433eb30fa6f32a
33,981,781,290,942
dfdfc95fbd7f5d63a369e1d55f5bf867e62d6766
/CS110/src/assignments/chap4/Pe425.java
1d2112bd3d8bbac1ec26cb3002bd6f790011dcc2
[]
no_license
SaronYifru/CS110
https://github.com/SaronYifru/CS110
d2b91ef06cf51d1027d34cd5a0bd0531f5d5c910
2ac4be262e5c4a931438eeb24ba39454d6d1d968
refs/heads/master
2016-09-08T01:41:54.315000
2013-05-06T02:53:01
2013-05-06T02:53:01
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package assignments.chap4; public class Pe425 { public static void main(String[] args) { final int MAXIMUMI = 100000; double piValue = 0; for (int i = 1; i <= MAXIMUMI;i++) { piValue = piValue + 4 * (Math.pow(-1, i + 1))/(2 * i - 1); if (i%10000 == 0) { System.out.println("The pi value at i = " + i + " is " + piValue); } } } }
UTF-8
Java
422
java
Pe425.java
Java
[]
null
[]
package assignments.chap4; public class Pe425 { public static void main(String[] args) { final int MAXIMUMI = 100000; double piValue = 0; for (int i = 1; i <= MAXIMUMI;i++) { piValue = piValue + 4 * (Math.pow(-1, i + 1))/(2 * i - 1); if (i%10000 == 0) { System.out.println("The pi value at i = " + i + " is " + piValue); } } } }
422
0.471564
0.417062
20
18.9
21.304695
74
false
false
0
0
0
0
0
0
1.7
false
false
1
f11a9799b11f5ba8a7195c5b78f48d79a3b8a6fd
39,307,540,724,210
bb30c5514b8310390e3ff3c113e5ba03fc23cff5
/src/fp/daw/examen/Ejercicio3.java
7258405f02fe7c6a5a003f80ff8588dfab45fb91
[]
no_license
LuciaGitHub88/20191203
https://github.com/LuciaGitHub88/20191203
27f538ab2052d9dac7d6f096631a5e6775f0f859
1acea7ee0dcfcff05344109818f1e6e82e321599
refs/heads/master
2020-09-24T02:51:55.120000
2019-12-03T17:12:17
2019-12-03T17:12:17
225,644,491
0
0
null
true
2019-12-03T14:49:10
2019-12-03T14:49:09
2019-12-03T14:44:02
2019-12-03T14:44:00
0
0
0
0
null
false
false
package fp.daw.examen; import java.util.Scanner; public class Ejercicio3 { /* * 3 puntos * * Decimos que un número entero positivo es guay si puede obtenerse como suma de * dos o más números enteros consecutivos. Por ejemplo, 3 (=1+2), 5 (=2+3), * 6(=1+2+3), son números guays. * * Escribir en el método main un programa que lea un número entero positivo e * indique si éste es guay. * * */ public static void main(String[] args) { Scanner teclado = new Scanner(System.in); int div; int num = 0; int suma = 0; System.out.println("Introduce un número entero:"); num = teclado.nextInt(); for (div = 1; div < num; div++) { if (num % div == 0) { suma = suma + div; } } if (suma == num) { System.out.println("Es un número guay"); } else { System.out.println("Lo siento, tu número no mola"); } teclado.close(); } }
UTF-8
Java
896
java
Ejercicio3.java
Java
[]
null
[]
package fp.daw.examen; import java.util.Scanner; public class Ejercicio3 { /* * 3 puntos * * Decimos que un número entero positivo es guay si puede obtenerse como suma de * dos o más números enteros consecutivos. Por ejemplo, 3 (=1+2), 5 (=2+3), * 6(=1+2+3), son números guays. * * Escribir en el método main un programa que lea un número entero positivo e * indique si éste es guay. * * */ public static void main(String[] args) { Scanner teclado = new Scanner(System.in); int div; int num = 0; int suma = 0; System.out.println("Introduce un número entero:"); num = teclado.nextInt(); for (div = 1; div < num; div++) { if (num % div == 0) { suma = suma + div; } } if (suma == num) { System.out.println("Es un número guay"); } else { System.out.println("Lo siento, tu número no mola"); } teclado.close(); } }
896
0.617382
0.599323
43
19.60465
22.140291
81
false
false
0
0
0
0
0
0
1.697674
false
false
1
7f53a6f2f54140a372b95682420e097b584339cf
21,466,246,616,023
40a43ac74ca84cdd927a973e5d1b5e445f07a801
/src/gui/GUIMainView.java
9fb41c94cbc16810bb085e21c13d0252d288d384
[]
no_license
Iam-YJ/1st_MiniProject_Kosta
https://github.com/Iam-YJ/1st_MiniProject_Kosta
ea541fa1ad3c0e5247c0cd1e76b31e9dc01a80c1
ee3598e74b0f54d61b38fcd72f30f7a09c0c239d
refs/heads/master
2022-12-25T20:20:53.264000
2020-10-07T00:11:28
2020-10-07T00:11:28
299,145,786
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package gui; import java.util.ArrayList; import java.util.List; import java.util.Random; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.StyledText; import org.eclipse.swt.events.FocusEvent; import org.eclipse.swt.events.FocusListener; import org.eclipse.swt.events.MouseAdapter; import org.eclipse.swt.events.MouseEvent; import org.eclipse.swt.events.VerifyEvent; import org.eclipse.swt.events.VerifyListener; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.Font; import org.eclipse.swt.graphics.FontData; import org.eclipse.swt.graphics.GC; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.layout.RowLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.MessageBox; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; import controller.MemberController; import controller.UserWordController; import controller.WordController; import dto.Admin; import dto.Member; import dto.UserWord; import dto.Word; import view.MenuView; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.layout.RowData; import org.eclipse.swt.graphics.Point; public class GUIMainView { // Title Height static private final int programWidth = 800; static private final int programHeight = 1000; // Word Test Variables static private int count = 0; static private int score = 0; static private int run = 0; static private int life = 0; static private int bonus = 0; static Random rand = new Random(); static boolean bSecondLayout = false; static Member loginMember; static Button buttonLogin; private static String passwordText; private static String useridText; static List<Integer> numList = new ArrayList<Integer>(); static List<Integer> orderList = new ArrayList<Integer>(); // Main Display and Shell private static Display mainDisplay = new Display(); private static Shell mainShell = new Shell(mainDisplay, SWT.CLOSE|SWT.TITLE|SWT.MIN|SWT.NO_REDRAW_RESIZE); private static StyledText ConsoleField = new StyledText(mainShell, SWT.BORDER | SWT.WRAP | SWT.V_SCROLL); private static void initConsoleField(){ ConsoleField.setLayoutData(new RowData(programWidth-37, programHeight-150)); ConsoleField.setEditable(false); } public static void ConsoleFieldVisible(boolean visible) { getConsoleField().setVisible(visible); } public static Display getMainDisplay() { return mainDisplay; } public static Shell getMainShell() { return mainShell; } public static String getPasswordText() { return passwordText; } public static void setPasswordText(String password) { passwordText = password; } public static String getUseridText() { return useridText; } public static void setUseridText(String userid) { useridText = userid; } public static StyledText getConsoleField() { return ConsoleField; } public static void main(String[] string) { ConsoleFieldVisible(false); // Background Color // Color colorBackground = new Color(display, 242, 242, 242); Color colorTitle = new Color (mainDisplay, 102, 153, 255); // System Font Data FontData systemFontData = mainDisplay.getSystemFont().getFontData()[0]; // Font Bold Font fontTitle = new Font(mainDisplay, systemFontData.getName(), 22, SWT.BOLD); Font fontButton = new Font(mainDisplay, systemFontData.getName(), 12, SWT.BOLD); // Icon Random Image Random rand = new Random(); int randNum = rand.nextInt(2)+1; Image imageIcon = resize(new Image(mainDisplay, "./src/img/icon." + randNum + ".png"), 128, 128); // Main Shell mainShell.setText("잊혀질 단어장"); mainShell.setBounds(40, 40, programWidth, programHeight); mainShell.setMinimumSize(new Point(programWidth, programHeight)); mainShell.setImage(imageIcon); // mainShell.setBackground(colorBackground); int x = (mainDisplay.getBounds().width - mainShell.getSize().x) / 2; int y = (mainDisplay.getBounds().height - mainShell.getSize().y) / 2; mainShell.setLocation(x, y); // Dialog MessageBox dialogInfo = new MessageBox(mainShell, SWT.ICON_QUESTION | SWT.OK); MessageBox dialogQuestion = new MessageBox(mainShell, SWT.ICON_WARNING | SWT.OK | SWT.CANCEL); RowLayout rowLayout = new RowLayout(SWT.VERTICAL); rowLayout.wrap = false; rowLayout.fill = false; rowLayout.justify = false; rowLayout.center = true; mainShell.setLayout(rowLayout); final Label labelTitleImage = new Label(mainShell, SWT.CENTER); labelTitleImage.setLayoutData(new RowData(programWidth, (mainShell.getSize().y+mainShell.getSize().y/3) - mainDisplay.getBounds().height)); labelTitleImage.setImage(imageIcon); final Label labelTitleText = new Label(mainShell, SWT.CENTER); labelTitleText.setLayoutData(new RowData(programWidth, (mainShell.getSize().y+mainShell.getSize().y/3) - mainDisplay.getBounds().height)); labelTitleText.setFont(fontTitle); labelTitleText.setForeground(colorTitle); labelTitleText.setImage(imageIcon); labelTitleText.setText("Welcome back :)"); /* * TEXT FIELD - USERID */ Text useridField = new Text(mainShell, SWT.BORDER | SWT.CENTER | SWT.SINGLE); useridField.setTextLimit(16); useridField.setLayoutData(new RowData(352, 32)); useridField.setText("ID / E-mail"); useridField.addFocusListener(new FocusListener() { @Override public void focusGained(FocusEvent e) { } @Override public void focusLost(FocusEvent e) { if (useridField.getText().isEmpty()) { useridField.setText("ID / E-mail"); } } }); useridField.addListener(SWT.Traverse, new Listener() { @Override public void handleEvent(Event event) { if (event.detail == SWT.TRAVERSE_RETURN){ loginCheck(); } } }); useridField.addMouseListener(new MouseAdapter() { @Override public void mouseDown(MouseEvent e) { String str = useridField.getText(); if (str.equals("ID / E-mail")) useridField.setText(""); } }); useridField.addVerifyListener(new VerifyListener() { @Override public void verifyText(VerifyEvent e) { if (e.text.length() > 0) { String str = useridField.getText(); if (str.contains("ID / E-mail")) useridField.setText(""); } for (int i = 0; i < e.text.length(); i++) { if (Character.isWhitespace(e.text.charAt(i))) { if (e.text.equals("ID / E-mail")) break; dialogInfo.setText("Login Information"); dialogInfo.setMessage("아이디는 공백을 포함할 수 없습니다 :("); dialogInfo.open(); e.doit = false; return; } } setUseridText(useridField.getText() + e.text); } }); /* * TEXT FIELD - PASSWORD */ Text passwordField = new Text(mainShell, SWT.BORDER | SWT.PASSWORD | SWT.CENTER | SWT.SINGLE); passwordField.setTextLimit(16); passwordField.setLayoutData(new RowData(352, 32)); passwordField.setText("PASSWORD"); passwordField.addVerifyListener(new VerifyListener() { @Override public void verifyText(VerifyEvent e) { setPasswordText(passwordField.getText() + e.text); } }); passwordField.addFocusListener(new FocusListener() { @Override public void focusGained(FocusEvent e) { String str = passwordField.getText(); if (str.equals("PASSWORD")) passwordField.setText(""); } public void focusLost(FocusEvent e) { if (passwordField.getText().isEmpty()) { passwordField.setText("PASSWORD"); } } }); passwordField.addListener(SWT.Traverse, new Listener() { @Override public void handleEvent(Event event){ if (event.detail == SWT.TRAVERSE_RETURN){ loginCheck(); } } }); /* * Button - Login */ buttonLogin = new Button(mainShell, SWT.PUSH); buttonLogin.setText("Login"); buttonLogin.setFont(fontButton); buttonLogin.setForeground(colorTitle); buttonLogin.setLayoutData(new RowData(200, 64)); buttonLogin.addListener(SWT.Selection, new Listener() { public void handleEvent(Event e) { loginCheck(); } } ); /* * Button - Guest */ Button buttonGuest = new Button(mainShell, SWT.PUSH); buttonGuest.setText("Guest"); buttonGuest.setLayoutData(new RowData(200, 40)); buttonGuest.addListener(SWT.Selection, new Listener() { public void handleEvent(Event e) { bSecondLayout = true; dialogInfo.setText("Login Information"); dialogInfo.setMessage("Guest Login"); dialogInfo.open(); MenuView.printNonUserMenu(); } }); /* * Button - Guest */ Button buttonRegister = new Button(mainShell, SWT.PUSH); buttonRegister.setText("Register"); buttonRegister.setLayoutData(new RowData(200, 40)); buttonRegister.addListener(SWT.Selection, new Listener() { public void handleEvent(Event e) { registerCheck(); } }); // Open Shell mainShell.open(); while (! mainShell.isDisposed() && ! mainDisplay.isDisposed()) { if (! mainDisplay.readAndDispatch()) { if (bSecondLayout) { bSecondLayout = false; buttonRegister.dispose(); buttonGuest.dispose(); buttonLogin.dispose(); labelTitleText.dispose(); labelTitleImage.dispose(); useridField.dispose(); passwordField.dispose(); initConsoleField(); Button buttonReturn = new Button(mainShell, SWT.PUSH); buttonReturn.moveAbove(ConsoleField); buttonReturn.setText("Main"); buttonReturn.setLayoutData(new RowData(160, 36)); buttonReturn.addListener(SWT.Selection, new Listener() { public void handleEvent(Event e) { if (MenuView.CurrentMenu > 2 && MenuView.CurrentMenu != 80 && MenuView.CurrentMenu != 90) { dialogQuestion.setText(":<"); dialogQuestion.setMessage("메인 메뉴로 돌아가시겠습니까?"); int result = dialogQuestion.open(); if (result == SWT.OK) { if (loginMember == null) MenuView.printNonUserMenu(); else if (Admin.getUserNo() == loginMember.getUserNo()) MenuView.printAdminMenu(); else MenuView.printUserMenu(loginMember.getUserId(), loginMember.getUserNo()); } } } }); ConsoleFieldVisible(true); Text InputField = new Text(mainShell, SWT.BORDER | SWT.FILL); InputField.setLayoutData(new RowData(300, 30)); InputField.setTextLimit(48); InputField.setFocus(); InputField.addListener(SWT.Traverse, new Listener() { @Override public void handleEvent(Event event) { if (event.detail == SWT.TRAVERSE_RETURN && InputField.getText().length() > 0){ if (MenuView.CurrentMenu > 0 && MenuView.CurrentMenu != 20) appendConsoleField("\"" + InputField.getText() + "\""); else { } String text = InputField.getText(); InputField.setText(""); checkEvent(text); } } }); mainShell.requestLayout(); } mainDisplay.sleep(); } } mainDisplay.dispose(); } private static void registerCheck() { MessageBox dialogInfo = new MessageBox(mainShell, SWT.ICON_QUESTION | SWT.OK); if (useridText == null || passwordText == null || useridText.equals("ID / E-mail") || passwordText.equals("PASSWORD")) { dialogInfo.setText("Login Information"); dialogInfo.setMessage("아이디와 비밀번호를 입력해주세요."); dialogInfo.open(); return; } // User ID Length Check if (useridText.length() < 3) { dialogInfo.setText("Login Information"); dialogInfo.setMessage("아이디는 3자리 이상이어야 합니다."); dialogInfo.open(); return; } // User Password Length Check if (passwordText.length() < 4){ dialogInfo.setText("Login Information"); dialogInfo.setMessage("비밀번호는 4자리 이상이어야 합니다."); dialogInfo.open(); return; } // User ID & Password Check if (registerUser(useridText, passwordText)) { dialogInfo.setText("Registration Successful"); dialogInfo.setMessage("User: " + useridText + "\n등록하신 아이디로 로그인하실 수 있습니다."); dialogInfo.open(); return; } else { dialogInfo.setText("Registration Failed"); dialogInfo.setMessage("User: " + useridText + "\n이미 존재하는 아이디 입니다."); dialogInfo.open(); return; } } private static void loginCheck() { MessageBox dialogInfo = new MessageBox(mainShell, SWT.ICON_QUESTION | SWT.OK); if (useridText == null || passwordText == null || useridText.equals("ID / E-mail") || passwordText.equals("PASSWORD")) { dialogInfo.setText("Login Information"); dialogInfo.setMessage("아이디와 비밀번호를 입력해주세요."); dialogInfo.open(); return; } // User ID Length Check if (useridText.length() < 3) { dialogInfo.setText("Login Information"); dialogInfo.setMessage("아이디는 3자리 이상이어야 합니다."); dialogInfo.open(); return; } // User Password Length Check if (passwordText.length() < 4){ dialogInfo.setText("Login Information"); dialogInfo.setMessage("비밀번호는 4자리 이상이어야 합니다."); dialogInfo.open(); return; } // User ID & Password Check loginUser(useridText, passwordText); if (loginMember != null) { dialogInfo.setText("Login Information"); dialogInfo.setMessage("User: " + useridText + "\n로그인 되었습니다."); dialogInfo.open(); bSecondLayout = true; return; } else { dialogInfo.setText("Login Information"); dialogInfo.setMessage("아이디 또는 비밀번호가 틀렸습니다"); dialogInfo.open(); return; } } private static void checkEvent(String text) { if (MenuView.CurrentMenu == 1) { // MenuView.printUserMenu - 일반 유저 메뉴 try { int SelectedMenu = Integer.parseInt(text); switch(SelectedMenu) { case 1: // 전체 검색 MenuView.CurrentMenu = 10; MenuView.printAllWord(); break; case 2: // 단어 시험 count = 1; score = 0; run = 0; MenuView.CurrentMenu = 20; MenuView.wordTest(loginMember.getUserNo()); break; case 3: // 단어 게임 count = 0; score = 0; run = 0; life = 5; bonus = 0; MenuView.CurrentMenu = 21; MenuView.wordGame(loginMember.getUserNo()); break; case 4: // 랭킹 MenuView.CurrentMenu = 70; MemberController.rank(); break; case 5: // 단어 추가 MenuView.CurrentMenu = 30; MenuView.printInputWord(loginMember.getUserNo()); break; case 6: // 단어 삭제 MenuView.CurrentMenu = 40; MenuView.printDeleteWord(loginMember.getUserNo()); break; case 7: // 오답 노트 MenuView.CurrentMenu = 50; WordController.wordSelectByWordNo(loginMember.getUserNo()); break; case 8: // 오답 노트 초기화 MenuView.CurrentMenu = 60; setConsoleField("===== 오답 노트 초기화 ====="); WordController.resetTestNote(loginMember.getUserNo()); break; default: appendConsoleField("일치하는 메뉴가 없습니다."); } } catch (NumberFormatException e) { appendConsoleField("숫자만 입력 가능합니다."); } } else if (MenuView.CurrentMenu == 10) { // MenuView.printAllWord - 전체 출력 선택지 메뉴 try { int SelectedMenu = Integer.parseInt(text); switch(SelectedMenu) { case 1: MenuView.CurrentMenu = 11; setConsoleField("===== 전체 검색 ====="); WordController.wordSelect(); return; case 2: MenuView.CurrentMenu = 12; appendConsoleField("검색할 영단어를 입력하세요 "); return; case 3: MenuView.CurrentMenu = 13; appendConsoleField("검색할 알파벳을 입력하세요 "); return; case 4: MenuView.CurrentMenu = 14; appendConsoleField("검색할 한글을 입력하세요 "); return; case 5: MenuView.CurrentMenu = 15; setConsoleField("===== 개인 단어 검색 ====="); WordController.wordSelectByUser(loginMember.getUserNo()); return; default: appendConsoleField("일치하는 메뉴가 없습니다."); break; } } catch (NumberFormatException e) { appendConsoleField("숫자만 입력 가능합니다."); } } else if (MenuView.CurrentMenu == 12) { // WordController.wordSelectByWord - 영단어 검색 if (text.matches("^[a-zA-Z]*$")) { setConsoleField("===== \"" + text + "\" 에 대한 영단어 검색 ====="); WordController.wordSelectByWord(text.toLowerCase()); } else { appendConsoleField("영문만 입력 가능합니다"); } } else if (MenuView.CurrentMenu == 13) { // WordController.wordSelectByAlphabet - 알파벳 검색 if (text.length() == 1 && text.matches("^[a-zA-Z]*$")) { setConsoleField("===== \"" + text + "\" 에 대한 알파벳 검색 ====="); WordController.wordSelectByAlphabet(text); } else { appendConsoleField("한 글자의 알파벳만 입력 가능합니다"); } } else if (MenuView.CurrentMenu == 14) { // WordController.wordSelectByWordKor - 한글 검색 if (!text.matches("^[a-zA-Z0-9]*$")) { setConsoleField("===== \"" + text + "\" 에 대한 한글 검색 ====="); WordController.wordSelectByWordKor(text); } else { appendConsoleField("영문과 숫자는 입력할 수 없습니다"); } } else if (MenuView.CurrentMenu == 80) { // MenuView.printNonUserMenu - Guest 메뉴 try { int SelectedMenu = Integer.parseInt(text); switch(SelectedMenu) { case 1: // 전체 검색 MenuView.CurrentMenu = 81; MenuView.printAllWordGuest(); break; case 2: // 단어 시험 count = 1; score = 0; run = 0; MenuView.CurrentMenu = 20; MenuView.wordTest(0); break; case 3: // 단어 게임 count = 0; score = 0; run = 0; life = 5; bonus = 0; MenuView.CurrentMenu = 21; MenuView.wordGame(0); break; default: appendConsoleField("일치하는 메뉴가 없습니다."); } } catch (NumberFormatException e) { appendConsoleField("숫자만 입력 가능합니다."); } } else if (MenuView.CurrentMenu == 81) { // MenuView.printAllWordGuest - Guest 전체 출력 선택지 메뉴 try { int SelectedMenu = Integer.parseInt(text); switch(SelectedMenu) { case 1: MenuView.CurrentMenu = 11; setConsoleField("===== 전체 검색 ====="); WordController.wordSelect(); return; case 2: MenuView.CurrentMenu = 12; appendConsoleField("검색할 영단어를 입력하세요 "); return; case 3: MenuView.CurrentMenu = 13; appendConsoleField("검색할 알파벳을 입력하세요 "); return; case 4: MenuView.CurrentMenu = 14; appendConsoleField("검색할 한글을 입력하세요 "); return; case 5: MenuView.CurrentMenu = 15; setConsoleField("===== 개인 단어 검색 ====="); WordController.wordSelectByUser(loginMember.getUserNo()); return; default: appendConsoleField("일치하는 메뉴가 없습니다."); break; } } catch (NumberFormatException e) { appendConsoleField("숫자만 입력 가능합니다."); } } else if (MenuView.CurrentMenu == 90) { // MenuView.printAdminMenu - Administrator 메뉴 try { int SelectedMenu = Integer.parseInt(text); switch(SelectedMenu) { case 1: MenuView.CurrentMenu = 81; MenuView.printInputAdminWord(); break; case 2: MenuView.CurrentMenu = 82; MenuView.printDeleteAdminWord(); break; case 3: MenuView.CurrentMenu = 83; MemberController.rank(); break; case 4: MenuView.CurrentMenu = 84; MenuView.printUpdateAdminMember(); break; case 5: MenuView.CurrentMenu = 85; MenuView.printDeleteAdminMember(); break; default: appendConsoleField("일치하는 메뉴가 없습니다."); } } catch (NumberFormatException e) { appendConsoleField("숫자만 입력 가능합니다."); } } } public static void resetConsoleField() { ConsoleField.setText(""); } public static void appendConsoleField(String text) { text = "\n" + text; ConsoleField.append(text); ConsoleField.setTopIndex(ConsoleField.getLineCount() - 1); ConsoleField.setLineAlignment(0, ConsoleField.getLineCount(), SWT.CENTER); } public static void setConsoleField(String text) { ConsoleField.setText(text); ConsoleField.setLineAlignment(0, ConsoleField.getLineCount(), SWT.CENTER); } public static boolean registerUser(String userid, String password) { return MemberController.register(userid, password, userid); } public static void loginUser(String userid, String password) { loginMember = MemberController.login(userid, password); } /** 이미지 리사이징 * * @param image * @param width * @param height * @return */ static Image resize(Image image, int width, int height) { Image scaled = new Image(Display.getDefault(), width, height); GC gc = new GC(scaled); gc.setAntialias(SWT.ON); gc.setInterpolation(SWT.HIGH); gc.drawImage(image, 0, 0, image.getBounds().width, image.getBounds().height, 0, 0, width, height); gc.dispose(); image.dispose(); // don't forget about me! return scaled; } public static String getInputDialog(String title, String desc) { String result = ""; final Shell shell = new Shell(mainDisplay, SWT.TITLE | SWT.BORDER | SWT.APPLICATION_MODAL | SWT.CENTER); shell.setText(title); shell.setLocation(800, 400); shell.setLayout(new GridLayout(2, true)); shell.setLayoutData(new GridData(300, 300)); Label label = new Label(shell, SWT.NULL); label.setText(desc); final Text text = new Text(shell, SWT.SINGLE | SWT.BORDER | SWT.CENTER); text.setTextLimit(16); text.setLayoutData(new GridData(200, 30)); text.addListener(SWT.Traverse, new Listener() { @Override public void handleEvent(Event event) { if (event.detail == SWT.TRAVERSE_RETURN && text.getText().length() > 0){ appendConsoleField("\"" + text.getText() + "\""); shell.dispose(); } } }); shell.pack(); shell.open(); while (!shell.isDisposed()) { if (!mainDisplay.readAndDispatch()) { result = text.getText(); mainDisplay.sleep(); } } shell.dispose(); return result; } /** * 단어 시험 (전체 DB 참조) * @param list * @param userNo */ public static void wordTest(List<Word> list, int userNo) { List<Integer> orderList = GUIMainView.makeRandom(10-run, list.size()); for (Integer i : orderList) { GUIMainView.appendConsoleField("문제 " + count + "번"); GUIMainView.appendConsoleField(list.get(i).getWordEng() + "의 뜻은?"); System.out.println("[DEBUG] 정답 >> " + list.get(i).getWordKor()); if (WordController.getAnswer(list.get(i).getWordNo(), getInputDialog("전체 단어 [" + count + " / 10]", list.get(i).getWordEng() + "의 뜻은?"))) { GUIMainView.appendConsoleField("\n정답입니다\n____________________________________________________________________________________\n\n"); score++; } else { MemberController.insertTest(userNo, null, list.get(i).getWordLevel(), score, 10 - score, Integer.toString(list.get(i).getWordNo())); GUIMainView.appendConsoleField("\n틀렸습니다\n____________________________________________________________________________________\n\n"); } count++; } if (userNo > 0) { MemberController.updatePoint(userNo, score); loginMember.setPoints(loginMember.getPoints() + score); GUIMainView.appendConsoleField("고생하셨습니다.\n총 " + score + " 문제 맞추셨으며 누적 점수는 " + loginMember.getPoints() + " 포인트 입니다"); } else GUIMainView.appendConsoleField("고생하셨습니다.\n총 " + score + " 문제 맞추셨습니다"); } /** * 단어 시험 (개인DB 참조) * @param list */ public static void userWordTest(List<UserWord> list) { if (list.size() < 1) return; while (true) { run = rand.nextInt(10) + 1; if (run <= list.size() && run > 0) { break; } } List<Integer> orderList = GUIMainView.makeRandom(run, list.size()); for (Integer i : orderList) { GUIMainView.appendConsoleField("(개인 단어) 문제 " + count + "번"); GUIMainView.appendConsoleField(list.get(i).getUserEng() + "의 뜻은?"); System.out.println("[DEBUG] 정답 >> " + list.get(i).getUserKor()); if (UserWordController.getAnswer(list.get(i).getUserWordNo(), getInputDialog("개인 단어 [" + count + " / 10]", list.get(i).getUserEng() + "의 뜻은?"))) { GUIMainView.appendConsoleField("\n정답입니다\n____________________________________________________________________________________\n\n"); score++; } else { MemberController.insertTest(list.get(i).getUserNo(), null, list.get(i).getUserLevel(), score, 10 - score, Integer.toString(list.get(i).getUserWordNo())); GUIMainView.appendConsoleField("\n틀렸습니다\n____________________________________________________________________________________\n\n"); } count++; } } /** * 단어 게임 (전체 DB 참조) * @param list * @param userNo */ public static int wordGame(List<Word> list, int userNo) { List<Integer> orderList = GUIMainView.makeRandom(1, list.size()); for (Integer i : orderList) { count++; GUIMainView.appendConsoleField("문제 " + count + "번 [라이프 " + life + " / 5]"); GUIMainView.appendConsoleField(list.get(i).getWordEng() + "의 뜻은?"); System.out.println("[DEBUG] 정답 >> " + list.get(i).getWordKor()); if (WordController.getAnswer(list.get(i).getWordNo(), getInputDialog("전체 단어 [" + count + "]", list.get(i).getWordEng() + "의 뜻은?"))) { GUIMainView.appendConsoleField("\n정답입니다\n____________________________________________________________________________________\n\n"); score++; bonus++; if (bonus >= 5) { bonus = 0; if (life < 5) GUIMainView.appendConsoleField("5문제 라이프 보너스 !\n" + "[라이프 " + ++life + " / 5]\n\n____________________________________________________________________________________\n\n"); } } else { life--; if (userNo > 0) MemberController.insertTest(userNo, null, list.get(i).getWordLevel(), score, count - score, Integer.toString(list.get(i).getWordNo())); GUIMainView.appendConsoleField("\n틀렸습니다\n____________________________________________________________________________________\n\n"); } break; } if (life == 0) { if (userNo > 0) { loginMember.setPoints(loginMember.getPoints() + score); MemberController.updatePoint(loginMember.getUserNo(), score); GUIMainView.appendConsoleField("고생하셨습니다.\n총 " + score + " 문제 맞추셨으며 누적 점수는 " + loginMember.getPoints() + " 포인트 입니다"); } else GUIMainView.appendConsoleField("고생하셨습니다.\n총 " + score + " 문제 맞추셨습니다"); } return life; } /** * 단어 게임 (개인DB 참조) * @param list */ public static int userWordGame(List<UserWord> list) { if (list.size() < 1) return 0; List<Integer> orderList = GUIMainView.makeRandom(1, list.size()); for (Integer i : orderList) { count++; GUIMainView.appendConsoleField("(개인 단어) 문제 " + count + "번 [라이프 " + life + " / 5]"); GUIMainView.appendConsoleField(list.get(i).getUserEng() + "의 뜻은?"); System.out.println("[DEBUG] 정답 >> " + list.get(i).getUserKor()); if (UserWordController.getAnswer(list.get(i).getUserWordNo(), getInputDialog("개인 단어 [" + count + "]", list.get(i).getUserEng() + "의 뜻은?"))) { GUIMainView.appendConsoleField("\n정답입니다\n____________________________________________________________________________________\n\n"); score++; bonus++; if (bonus >= 5) { bonus = 0; if (life < 5) GUIMainView.appendConsoleField("5문제 라이프 보너스 !\n" + "[라이프 " + ++life + " / 5]\n\n____________________________________________________________________________________\n\n"); } } else { life--; MemberController.insertTest(list.get(i).getUserNo(), null, list.get(i).getUserLevel(), score, count - score, Integer.toString(list.get(i).getUserWordNo())); GUIMainView.appendConsoleField("\n틀렸습니다\n____________________________________________________________________________________\n\n"); } if (life == 0) { loginMember.setPoints(loginMember.getPoints() + score); MemberController.updatePoint(loginMember.getUserNo(), score); GUIMainView.appendConsoleField("고생하셨습니다.\n총 " + score + " 문제 맞추셨으며 누적 점수는 " + loginMember.getPoints() + " 포인트 입니다"); } break; } return life; } /** * 단어시험용 랜덤 10개 뽑기 * @param run * @param size * @return */ public static List<Integer> makeRandom(int run, int size) { numList.clear(); for (int i = 0; i < run; i++) { int number = rand.nextInt(size); if (!numList.contains(number)) { numList.add(number); } else { i--; } } return numList; } }
UHC
Java
31,328
java
GUIMainView.java
Java
[ { "context": "a(new RowData(352, 32));\n\t\tpasswordField.setText(\"PASSWORD\");\n\t\tpasswordField.addVerifyListener(new VerifyLi", "end": 7238, "score": 0.994563639163971, "start": 7230, "tag": "PASSWORD", "value": "PASSWORD" }, { "context": "etText().isEmpty()) {\n\t\t\t\t\tpasswordField.setText(\"PASSWORD\");\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t\tpasswordField.addListener(S", "end": 7786, "score": 0.9883247017860413, "start": 7778, "tag": "PASSWORD", "value": "PASSWORD" }, { "context": "ext.equals(\"ID / E-mail\") || passwordText.equals(\"PASSWORD\")) {\n \tdialogInfo.setText(\"Login Informati", "end": 12480, "score": 0.9991795420646667, "start": 12472, "tag": "PASSWORD", "value": "PASSWORD" }, { "context": "ext.equals(\"ID / E-mail\") || passwordText.equals(\"PASSWORD\")) {\n \tdialogInfo.setText(\"Login Informati", "end": 13776, "score": 0.9603611826896667, "start": 13768, "tag": "PASSWORD", "value": "PASSWORD" } ]
null
[]
package gui; import java.util.ArrayList; import java.util.List; import java.util.Random; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.StyledText; import org.eclipse.swt.events.FocusEvent; import org.eclipse.swt.events.FocusListener; import org.eclipse.swt.events.MouseAdapter; import org.eclipse.swt.events.MouseEvent; import org.eclipse.swt.events.VerifyEvent; import org.eclipse.swt.events.VerifyListener; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.Font; import org.eclipse.swt.graphics.FontData; import org.eclipse.swt.graphics.GC; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.layout.RowLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.MessageBox; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; import controller.MemberController; import controller.UserWordController; import controller.WordController; import dto.Admin; import dto.Member; import dto.UserWord; import dto.Word; import view.MenuView; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.layout.RowData; import org.eclipse.swt.graphics.Point; public class GUIMainView { // Title Height static private final int programWidth = 800; static private final int programHeight = 1000; // Word Test Variables static private int count = 0; static private int score = 0; static private int run = 0; static private int life = 0; static private int bonus = 0; static Random rand = new Random(); static boolean bSecondLayout = false; static Member loginMember; static Button buttonLogin; private static String passwordText; private static String useridText; static List<Integer> numList = new ArrayList<Integer>(); static List<Integer> orderList = new ArrayList<Integer>(); // Main Display and Shell private static Display mainDisplay = new Display(); private static Shell mainShell = new Shell(mainDisplay, SWT.CLOSE|SWT.TITLE|SWT.MIN|SWT.NO_REDRAW_RESIZE); private static StyledText ConsoleField = new StyledText(mainShell, SWT.BORDER | SWT.WRAP | SWT.V_SCROLL); private static void initConsoleField(){ ConsoleField.setLayoutData(new RowData(programWidth-37, programHeight-150)); ConsoleField.setEditable(false); } public static void ConsoleFieldVisible(boolean visible) { getConsoleField().setVisible(visible); } public static Display getMainDisplay() { return mainDisplay; } public static Shell getMainShell() { return mainShell; } public static String getPasswordText() { return passwordText; } public static void setPasswordText(String password) { passwordText = password; } public static String getUseridText() { return useridText; } public static void setUseridText(String userid) { useridText = userid; } public static StyledText getConsoleField() { return ConsoleField; } public static void main(String[] string) { ConsoleFieldVisible(false); // Background Color // Color colorBackground = new Color(display, 242, 242, 242); Color colorTitle = new Color (mainDisplay, 102, 153, 255); // System Font Data FontData systemFontData = mainDisplay.getSystemFont().getFontData()[0]; // Font Bold Font fontTitle = new Font(mainDisplay, systemFontData.getName(), 22, SWT.BOLD); Font fontButton = new Font(mainDisplay, systemFontData.getName(), 12, SWT.BOLD); // Icon Random Image Random rand = new Random(); int randNum = rand.nextInt(2)+1; Image imageIcon = resize(new Image(mainDisplay, "./src/img/icon." + randNum + ".png"), 128, 128); // Main Shell mainShell.setText("잊혀질 단어장"); mainShell.setBounds(40, 40, programWidth, programHeight); mainShell.setMinimumSize(new Point(programWidth, programHeight)); mainShell.setImage(imageIcon); // mainShell.setBackground(colorBackground); int x = (mainDisplay.getBounds().width - mainShell.getSize().x) / 2; int y = (mainDisplay.getBounds().height - mainShell.getSize().y) / 2; mainShell.setLocation(x, y); // Dialog MessageBox dialogInfo = new MessageBox(mainShell, SWT.ICON_QUESTION | SWT.OK); MessageBox dialogQuestion = new MessageBox(mainShell, SWT.ICON_WARNING | SWT.OK | SWT.CANCEL); RowLayout rowLayout = new RowLayout(SWT.VERTICAL); rowLayout.wrap = false; rowLayout.fill = false; rowLayout.justify = false; rowLayout.center = true; mainShell.setLayout(rowLayout); final Label labelTitleImage = new Label(mainShell, SWT.CENTER); labelTitleImage.setLayoutData(new RowData(programWidth, (mainShell.getSize().y+mainShell.getSize().y/3) - mainDisplay.getBounds().height)); labelTitleImage.setImage(imageIcon); final Label labelTitleText = new Label(mainShell, SWT.CENTER); labelTitleText.setLayoutData(new RowData(programWidth, (mainShell.getSize().y+mainShell.getSize().y/3) - mainDisplay.getBounds().height)); labelTitleText.setFont(fontTitle); labelTitleText.setForeground(colorTitle); labelTitleText.setImage(imageIcon); labelTitleText.setText("Welcome back :)"); /* * TEXT FIELD - USERID */ Text useridField = new Text(mainShell, SWT.BORDER | SWT.CENTER | SWT.SINGLE); useridField.setTextLimit(16); useridField.setLayoutData(new RowData(352, 32)); useridField.setText("ID / E-mail"); useridField.addFocusListener(new FocusListener() { @Override public void focusGained(FocusEvent e) { } @Override public void focusLost(FocusEvent e) { if (useridField.getText().isEmpty()) { useridField.setText("ID / E-mail"); } } }); useridField.addListener(SWT.Traverse, new Listener() { @Override public void handleEvent(Event event) { if (event.detail == SWT.TRAVERSE_RETURN){ loginCheck(); } } }); useridField.addMouseListener(new MouseAdapter() { @Override public void mouseDown(MouseEvent e) { String str = useridField.getText(); if (str.equals("ID / E-mail")) useridField.setText(""); } }); useridField.addVerifyListener(new VerifyListener() { @Override public void verifyText(VerifyEvent e) { if (e.text.length() > 0) { String str = useridField.getText(); if (str.contains("ID / E-mail")) useridField.setText(""); } for (int i = 0; i < e.text.length(); i++) { if (Character.isWhitespace(e.text.charAt(i))) { if (e.text.equals("ID / E-mail")) break; dialogInfo.setText("Login Information"); dialogInfo.setMessage("아이디는 공백을 포함할 수 없습니다 :("); dialogInfo.open(); e.doit = false; return; } } setUseridText(useridField.getText() + e.text); } }); /* * TEXT FIELD - PASSWORD */ Text passwordField = new Text(mainShell, SWT.BORDER | SWT.PASSWORD | SWT.CENTER | SWT.SINGLE); passwordField.setTextLimit(16); passwordField.setLayoutData(new RowData(352, 32)); passwordField.setText("<PASSWORD>"); passwordField.addVerifyListener(new VerifyListener() { @Override public void verifyText(VerifyEvent e) { setPasswordText(passwordField.getText() + e.text); } }); passwordField.addFocusListener(new FocusListener() { @Override public void focusGained(FocusEvent e) { String str = passwordField.getText(); if (str.equals("PASSWORD")) passwordField.setText(""); } public void focusLost(FocusEvent e) { if (passwordField.getText().isEmpty()) { passwordField.setText("<PASSWORD>"); } } }); passwordField.addListener(SWT.Traverse, new Listener() { @Override public void handleEvent(Event event){ if (event.detail == SWT.TRAVERSE_RETURN){ loginCheck(); } } }); /* * Button - Login */ buttonLogin = new Button(mainShell, SWT.PUSH); buttonLogin.setText("Login"); buttonLogin.setFont(fontButton); buttonLogin.setForeground(colorTitle); buttonLogin.setLayoutData(new RowData(200, 64)); buttonLogin.addListener(SWT.Selection, new Listener() { public void handleEvent(Event e) { loginCheck(); } } ); /* * Button - Guest */ Button buttonGuest = new Button(mainShell, SWT.PUSH); buttonGuest.setText("Guest"); buttonGuest.setLayoutData(new RowData(200, 40)); buttonGuest.addListener(SWT.Selection, new Listener() { public void handleEvent(Event e) { bSecondLayout = true; dialogInfo.setText("Login Information"); dialogInfo.setMessage("Guest Login"); dialogInfo.open(); MenuView.printNonUserMenu(); } }); /* * Button - Guest */ Button buttonRegister = new Button(mainShell, SWT.PUSH); buttonRegister.setText("Register"); buttonRegister.setLayoutData(new RowData(200, 40)); buttonRegister.addListener(SWT.Selection, new Listener() { public void handleEvent(Event e) { registerCheck(); } }); // Open Shell mainShell.open(); while (! mainShell.isDisposed() && ! mainDisplay.isDisposed()) { if (! mainDisplay.readAndDispatch()) { if (bSecondLayout) { bSecondLayout = false; buttonRegister.dispose(); buttonGuest.dispose(); buttonLogin.dispose(); labelTitleText.dispose(); labelTitleImage.dispose(); useridField.dispose(); passwordField.dispose(); initConsoleField(); Button buttonReturn = new Button(mainShell, SWT.PUSH); buttonReturn.moveAbove(ConsoleField); buttonReturn.setText("Main"); buttonReturn.setLayoutData(new RowData(160, 36)); buttonReturn.addListener(SWT.Selection, new Listener() { public void handleEvent(Event e) { if (MenuView.CurrentMenu > 2 && MenuView.CurrentMenu != 80 && MenuView.CurrentMenu != 90) { dialogQuestion.setText(":<"); dialogQuestion.setMessage("메인 메뉴로 돌아가시겠습니까?"); int result = dialogQuestion.open(); if (result == SWT.OK) { if (loginMember == null) MenuView.printNonUserMenu(); else if (Admin.getUserNo() == loginMember.getUserNo()) MenuView.printAdminMenu(); else MenuView.printUserMenu(loginMember.getUserId(), loginMember.getUserNo()); } } } }); ConsoleFieldVisible(true); Text InputField = new Text(mainShell, SWT.BORDER | SWT.FILL); InputField.setLayoutData(new RowData(300, 30)); InputField.setTextLimit(48); InputField.setFocus(); InputField.addListener(SWT.Traverse, new Listener() { @Override public void handleEvent(Event event) { if (event.detail == SWT.TRAVERSE_RETURN && InputField.getText().length() > 0){ if (MenuView.CurrentMenu > 0 && MenuView.CurrentMenu != 20) appendConsoleField("\"" + InputField.getText() + "\""); else { } String text = InputField.getText(); InputField.setText(""); checkEvent(text); } } }); mainShell.requestLayout(); } mainDisplay.sleep(); } } mainDisplay.dispose(); } private static void registerCheck() { MessageBox dialogInfo = new MessageBox(mainShell, SWT.ICON_QUESTION | SWT.OK); if (useridText == null || passwordText == null || useridText.equals("ID / E-mail") || passwordText.equals("<PASSWORD>")) { dialogInfo.setText("Login Information"); dialogInfo.setMessage("아이디와 비밀번호를 입력해주세요."); dialogInfo.open(); return; } // User ID Length Check if (useridText.length() < 3) { dialogInfo.setText("Login Information"); dialogInfo.setMessage("아이디는 3자리 이상이어야 합니다."); dialogInfo.open(); return; } // User Password Length Check if (passwordText.length() < 4){ dialogInfo.setText("Login Information"); dialogInfo.setMessage("비밀번호는 4자리 이상이어야 합니다."); dialogInfo.open(); return; } // User ID & Password Check if (registerUser(useridText, passwordText)) { dialogInfo.setText("Registration Successful"); dialogInfo.setMessage("User: " + useridText + "\n등록하신 아이디로 로그인하실 수 있습니다."); dialogInfo.open(); return; } else { dialogInfo.setText("Registration Failed"); dialogInfo.setMessage("User: " + useridText + "\n이미 존재하는 아이디 입니다."); dialogInfo.open(); return; } } private static void loginCheck() { MessageBox dialogInfo = new MessageBox(mainShell, SWT.ICON_QUESTION | SWT.OK); if (useridText == null || passwordText == null || useridText.equals("ID / E-mail") || passwordText.equals("<PASSWORD>")) { dialogInfo.setText("Login Information"); dialogInfo.setMessage("아이디와 비밀번호를 입력해주세요."); dialogInfo.open(); return; } // User ID Length Check if (useridText.length() < 3) { dialogInfo.setText("Login Information"); dialogInfo.setMessage("아이디는 3자리 이상이어야 합니다."); dialogInfo.open(); return; } // User Password Length Check if (passwordText.length() < 4){ dialogInfo.setText("Login Information"); dialogInfo.setMessage("비밀번호는 4자리 이상이어야 합니다."); dialogInfo.open(); return; } // User ID & Password Check loginUser(useridText, passwordText); if (loginMember != null) { dialogInfo.setText("Login Information"); dialogInfo.setMessage("User: " + useridText + "\n로그인 되었습니다."); dialogInfo.open(); bSecondLayout = true; return; } else { dialogInfo.setText("Login Information"); dialogInfo.setMessage("아이디 또는 비밀번호가 틀렸습니다"); dialogInfo.open(); return; } } private static void checkEvent(String text) { if (MenuView.CurrentMenu == 1) { // MenuView.printUserMenu - 일반 유저 메뉴 try { int SelectedMenu = Integer.parseInt(text); switch(SelectedMenu) { case 1: // 전체 검색 MenuView.CurrentMenu = 10; MenuView.printAllWord(); break; case 2: // 단어 시험 count = 1; score = 0; run = 0; MenuView.CurrentMenu = 20; MenuView.wordTest(loginMember.getUserNo()); break; case 3: // 단어 게임 count = 0; score = 0; run = 0; life = 5; bonus = 0; MenuView.CurrentMenu = 21; MenuView.wordGame(loginMember.getUserNo()); break; case 4: // 랭킹 MenuView.CurrentMenu = 70; MemberController.rank(); break; case 5: // 단어 추가 MenuView.CurrentMenu = 30; MenuView.printInputWord(loginMember.getUserNo()); break; case 6: // 단어 삭제 MenuView.CurrentMenu = 40; MenuView.printDeleteWord(loginMember.getUserNo()); break; case 7: // 오답 노트 MenuView.CurrentMenu = 50; WordController.wordSelectByWordNo(loginMember.getUserNo()); break; case 8: // 오답 노트 초기화 MenuView.CurrentMenu = 60; setConsoleField("===== 오답 노트 초기화 ====="); WordController.resetTestNote(loginMember.getUserNo()); break; default: appendConsoleField("일치하는 메뉴가 없습니다."); } } catch (NumberFormatException e) { appendConsoleField("숫자만 입력 가능합니다."); } } else if (MenuView.CurrentMenu == 10) { // MenuView.printAllWord - 전체 출력 선택지 메뉴 try { int SelectedMenu = Integer.parseInt(text); switch(SelectedMenu) { case 1: MenuView.CurrentMenu = 11; setConsoleField("===== 전체 검색 ====="); WordController.wordSelect(); return; case 2: MenuView.CurrentMenu = 12; appendConsoleField("검색할 영단어를 입력하세요 "); return; case 3: MenuView.CurrentMenu = 13; appendConsoleField("검색할 알파벳을 입력하세요 "); return; case 4: MenuView.CurrentMenu = 14; appendConsoleField("검색할 한글을 입력하세요 "); return; case 5: MenuView.CurrentMenu = 15; setConsoleField("===== 개인 단어 검색 ====="); WordController.wordSelectByUser(loginMember.getUserNo()); return; default: appendConsoleField("일치하는 메뉴가 없습니다."); break; } } catch (NumberFormatException e) { appendConsoleField("숫자만 입력 가능합니다."); } } else if (MenuView.CurrentMenu == 12) { // WordController.wordSelectByWord - 영단어 검색 if (text.matches("^[a-zA-Z]*$")) { setConsoleField("===== \"" + text + "\" 에 대한 영단어 검색 ====="); WordController.wordSelectByWord(text.toLowerCase()); } else { appendConsoleField("영문만 입력 가능합니다"); } } else if (MenuView.CurrentMenu == 13) { // WordController.wordSelectByAlphabet - 알파벳 검색 if (text.length() == 1 && text.matches("^[a-zA-Z]*$")) { setConsoleField("===== \"" + text + "\" 에 대한 알파벳 검색 ====="); WordController.wordSelectByAlphabet(text); } else { appendConsoleField("한 글자의 알파벳만 입력 가능합니다"); } } else if (MenuView.CurrentMenu == 14) { // WordController.wordSelectByWordKor - 한글 검색 if (!text.matches("^[a-zA-Z0-9]*$")) { setConsoleField("===== \"" + text + "\" 에 대한 한글 검색 ====="); WordController.wordSelectByWordKor(text); } else { appendConsoleField("영문과 숫자는 입력할 수 없습니다"); } } else if (MenuView.CurrentMenu == 80) { // MenuView.printNonUserMenu - Guest 메뉴 try { int SelectedMenu = Integer.parseInt(text); switch(SelectedMenu) { case 1: // 전체 검색 MenuView.CurrentMenu = 81; MenuView.printAllWordGuest(); break; case 2: // 단어 시험 count = 1; score = 0; run = 0; MenuView.CurrentMenu = 20; MenuView.wordTest(0); break; case 3: // 단어 게임 count = 0; score = 0; run = 0; life = 5; bonus = 0; MenuView.CurrentMenu = 21; MenuView.wordGame(0); break; default: appendConsoleField("일치하는 메뉴가 없습니다."); } } catch (NumberFormatException e) { appendConsoleField("숫자만 입력 가능합니다."); } } else if (MenuView.CurrentMenu == 81) { // MenuView.printAllWordGuest - Guest 전체 출력 선택지 메뉴 try { int SelectedMenu = Integer.parseInt(text); switch(SelectedMenu) { case 1: MenuView.CurrentMenu = 11; setConsoleField("===== 전체 검색 ====="); WordController.wordSelect(); return; case 2: MenuView.CurrentMenu = 12; appendConsoleField("검색할 영단어를 입력하세요 "); return; case 3: MenuView.CurrentMenu = 13; appendConsoleField("검색할 알파벳을 입력하세요 "); return; case 4: MenuView.CurrentMenu = 14; appendConsoleField("검색할 한글을 입력하세요 "); return; case 5: MenuView.CurrentMenu = 15; setConsoleField("===== 개인 단어 검색 ====="); WordController.wordSelectByUser(loginMember.getUserNo()); return; default: appendConsoleField("일치하는 메뉴가 없습니다."); break; } } catch (NumberFormatException e) { appendConsoleField("숫자만 입력 가능합니다."); } } else if (MenuView.CurrentMenu == 90) { // MenuView.printAdminMenu - Administrator 메뉴 try { int SelectedMenu = Integer.parseInt(text); switch(SelectedMenu) { case 1: MenuView.CurrentMenu = 81; MenuView.printInputAdminWord(); break; case 2: MenuView.CurrentMenu = 82; MenuView.printDeleteAdminWord(); break; case 3: MenuView.CurrentMenu = 83; MemberController.rank(); break; case 4: MenuView.CurrentMenu = 84; MenuView.printUpdateAdminMember(); break; case 5: MenuView.CurrentMenu = 85; MenuView.printDeleteAdminMember(); break; default: appendConsoleField("일치하는 메뉴가 없습니다."); } } catch (NumberFormatException e) { appendConsoleField("숫자만 입력 가능합니다."); } } } public static void resetConsoleField() { ConsoleField.setText(""); } public static void appendConsoleField(String text) { text = "\n" + text; ConsoleField.append(text); ConsoleField.setTopIndex(ConsoleField.getLineCount() - 1); ConsoleField.setLineAlignment(0, ConsoleField.getLineCount(), SWT.CENTER); } public static void setConsoleField(String text) { ConsoleField.setText(text); ConsoleField.setLineAlignment(0, ConsoleField.getLineCount(), SWT.CENTER); } public static boolean registerUser(String userid, String password) { return MemberController.register(userid, password, userid); } public static void loginUser(String userid, String password) { loginMember = MemberController.login(userid, password); } /** 이미지 리사이징 * * @param image * @param width * @param height * @return */ static Image resize(Image image, int width, int height) { Image scaled = new Image(Display.getDefault(), width, height); GC gc = new GC(scaled); gc.setAntialias(SWT.ON); gc.setInterpolation(SWT.HIGH); gc.drawImage(image, 0, 0, image.getBounds().width, image.getBounds().height, 0, 0, width, height); gc.dispose(); image.dispose(); // don't forget about me! return scaled; } public static String getInputDialog(String title, String desc) { String result = ""; final Shell shell = new Shell(mainDisplay, SWT.TITLE | SWT.BORDER | SWT.APPLICATION_MODAL | SWT.CENTER); shell.setText(title); shell.setLocation(800, 400); shell.setLayout(new GridLayout(2, true)); shell.setLayoutData(new GridData(300, 300)); Label label = new Label(shell, SWT.NULL); label.setText(desc); final Text text = new Text(shell, SWT.SINGLE | SWT.BORDER | SWT.CENTER); text.setTextLimit(16); text.setLayoutData(new GridData(200, 30)); text.addListener(SWT.Traverse, new Listener() { @Override public void handleEvent(Event event) { if (event.detail == SWT.TRAVERSE_RETURN && text.getText().length() > 0){ appendConsoleField("\"" + text.getText() + "\""); shell.dispose(); } } }); shell.pack(); shell.open(); while (!shell.isDisposed()) { if (!mainDisplay.readAndDispatch()) { result = text.getText(); mainDisplay.sleep(); } } shell.dispose(); return result; } /** * 단어 시험 (전체 DB 참조) * @param list * @param userNo */ public static void wordTest(List<Word> list, int userNo) { List<Integer> orderList = GUIMainView.makeRandom(10-run, list.size()); for (Integer i : orderList) { GUIMainView.appendConsoleField("문제 " + count + "번"); GUIMainView.appendConsoleField(list.get(i).getWordEng() + "의 뜻은?"); System.out.println("[DEBUG] 정답 >> " + list.get(i).getWordKor()); if (WordController.getAnswer(list.get(i).getWordNo(), getInputDialog("전체 단어 [" + count + " / 10]", list.get(i).getWordEng() + "의 뜻은?"))) { GUIMainView.appendConsoleField("\n정답입니다\n____________________________________________________________________________________\n\n"); score++; } else { MemberController.insertTest(userNo, null, list.get(i).getWordLevel(), score, 10 - score, Integer.toString(list.get(i).getWordNo())); GUIMainView.appendConsoleField("\n틀렸습니다\n____________________________________________________________________________________\n\n"); } count++; } if (userNo > 0) { MemberController.updatePoint(userNo, score); loginMember.setPoints(loginMember.getPoints() + score); GUIMainView.appendConsoleField("고생하셨습니다.\n총 " + score + " 문제 맞추셨으며 누적 점수는 " + loginMember.getPoints() + " 포인트 입니다"); } else GUIMainView.appendConsoleField("고생하셨습니다.\n총 " + score + " 문제 맞추셨습니다"); } /** * 단어 시험 (개인DB 참조) * @param list */ public static void userWordTest(List<UserWord> list) { if (list.size() < 1) return; while (true) { run = rand.nextInt(10) + 1; if (run <= list.size() && run > 0) { break; } } List<Integer> orderList = GUIMainView.makeRandom(run, list.size()); for (Integer i : orderList) { GUIMainView.appendConsoleField("(개인 단어) 문제 " + count + "번"); GUIMainView.appendConsoleField(list.get(i).getUserEng() + "의 뜻은?"); System.out.println("[DEBUG] 정답 >> " + list.get(i).getUserKor()); if (UserWordController.getAnswer(list.get(i).getUserWordNo(), getInputDialog("개인 단어 [" + count + " / 10]", list.get(i).getUserEng() + "의 뜻은?"))) { GUIMainView.appendConsoleField("\n정답입니다\n____________________________________________________________________________________\n\n"); score++; } else { MemberController.insertTest(list.get(i).getUserNo(), null, list.get(i).getUserLevel(), score, 10 - score, Integer.toString(list.get(i).getUserWordNo())); GUIMainView.appendConsoleField("\n틀렸습니다\n____________________________________________________________________________________\n\n"); } count++; } } /** * 단어 게임 (전체 DB 참조) * @param list * @param userNo */ public static int wordGame(List<Word> list, int userNo) { List<Integer> orderList = GUIMainView.makeRandom(1, list.size()); for (Integer i : orderList) { count++; GUIMainView.appendConsoleField("문제 " + count + "번 [라이프 " + life + " / 5]"); GUIMainView.appendConsoleField(list.get(i).getWordEng() + "의 뜻은?"); System.out.println("[DEBUG] 정답 >> " + list.get(i).getWordKor()); if (WordController.getAnswer(list.get(i).getWordNo(), getInputDialog("전체 단어 [" + count + "]", list.get(i).getWordEng() + "의 뜻은?"))) { GUIMainView.appendConsoleField("\n정답입니다\n____________________________________________________________________________________\n\n"); score++; bonus++; if (bonus >= 5) { bonus = 0; if (life < 5) GUIMainView.appendConsoleField("5문제 라이프 보너스 !\n" + "[라이프 " + ++life + " / 5]\n\n____________________________________________________________________________________\n\n"); } } else { life--; if (userNo > 0) MemberController.insertTest(userNo, null, list.get(i).getWordLevel(), score, count - score, Integer.toString(list.get(i).getWordNo())); GUIMainView.appendConsoleField("\n틀렸습니다\n____________________________________________________________________________________\n\n"); } break; } if (life == 0) { if (userNo > 0) { loginMember.setPoints(loginMember.getPoints() + score); MemberController.updatePoint(loginMember.getUserNo(), score); GUIMainView.appendConsoleField("고생하셨습니다.\n총 " + score + " 문제 맞추셨으며 누적 점수는 " + loginMember.getPoints() + " 포인트 입니다"); } else GUIMainView.appendConsoleField("고생하셨습니다.\n총 " + score + " 문제 맞추셨습니다"); } return life; } /** * 단어 게임 (개인DB 참조) * @param list */ public static int userWordGame(List<UserWord> list) { if (list.size() < 1) return 0; List<Integer> orderList = GUIMainView.makeRandom(1, list.size()); for (Integer i : orderList) { count++; GUIMainView.appendConsoleField("(개인 단어) 문제 " + count + "번 [라이프 " + life + " / 5]"); GUIMainView.appendConsoleField(list.get(i).getUserEng() + "의 뜻은?"); System.out.println("[DEBUG] 정답 >> " + list.get(i).getUserKor()); if (UserWordController.getAnswer(list.get(i).getUserWordNo(), getInputDialog("개인 단어 [" + count + "]", list.get(i).getUserEng() + "의 뜻은?"))) { GUIMainView.appendConsoleField("\n정답입니다\n____________________________________________________________________________________\n\n"); score++; bonus++; if (bonus >= 5) { bonus = 0; if (life < 5) GUIMainView.appendConsoleField("5문제 라이프 보너스 !\n" + "[라이프 " + ++life + " / 5]\n\n____________________________________________________________________________________\n\n"); } } else { life--; MemberController.insertTest(list.get(i).getUserNo(), null, list.get(i).getUserLevel(), score, count - score, Integer.toString(list.get(i).getUserWordNo())); GUIMainView.appendConsoleField("\n틀렸습니다\n____________________________________________________________________________________\n\n"); } if (life == 0) { loginMember.setPoints(loginMember.getPoints() + score); MemberController.updatePoint(loginMember.getUserNo(), score); GUIMainView.appendConsoleField("고생하셨습니다.\n총 " + score + " 문제 맞추셨으며 누적 점수는 " + loginMember.getPoints() + " 포인트 입니다"); } break; } return life; } /** * 단어시험용 랜덤 10개 뽑기 * @param run * @param size * @return */ public static List<Integer> makeRandom(int run, int size) { numList.clear(); for (int i = 0; i < run; i++) { int number = rand.nextInt(size); if (!numList.contains(number)) { numList.add(number); } else { i--; } } return numList; } }
31,336
0.596948
0.586943
923
31.163597
28.696798
177
false
false
0
0
0
0
0
0
3.04442
false
false
1
25ef4b61b807da1982ad10df0ffb230dd56275c6
31,722,628,514,164
fa91450deb625cda070e82d5c31770be5ca1dec6
/Diff-Raw-Data/10/10_af32e3dd4961319145b734b77346d76916120e6d/Main/10_af32e3dd4961319145b734b77346d76916120e6d_Main_t.java
b0927ecc2a1cdebc5583f7b6d7c92b718ba306ad
[]
no_license
zhongxingyu/Seer
https://github.com/zhongxingyu/Seer
48e7e5197624d7afa94d23f849f8ea2075bcaec0
c11a3109fdfca9be337e509ecb2c085b60076213
refs/heads/master
2023-07-06T12:48:55.516000
2023-06-22T07:55:56
2023-06-22T07:55:56
259,613,157
6
2
null
false
2023-06-22T07:55:57
2020-04-28T11:07:49
2023-06-21T00:53:27
2023-06-22T07:55:57
2,849,868
2
2
0
null
false
false
package com.michalkazior.simplemusicplayer; import java.util.ArrayList; import java.util.Collections; import com.michalkazior.simplemusicplayer.Player.State; import android.app.Activity; import android.app.AlertDialog; import android.content.BroadcastReceiver; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ContextMenu.ContextMenuInfo; import android.view.View.OnClickListener; import android.view.View.OnCreateContextMenuListener; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ListView; import android.widget.SeekBar; import android.widget.TextView; import android.widget.AdapterView.AdapterContextMenuInfo; import android.widget.SeekBar.OnSeekBarChangeListener; /** * Main activity. * * The user may manage the list of enqueued songs, play, pause. */ public class Main extends Activity { private Button playButton, skipButton; private TextView songTime; private SeekBar songSeekBar; private ListView enqueuedSongs; private Song[] songs = {}; private Player.State state = State.IS_STOPPED; private Song selectedSong = null; /* * Position of the seekbar before user started draging. * * -1 means the user is not dragging the seekbar. */ private int oldSeekBarPosition = -1; /** * Context menu for enqueued list items */ private enum ContextMenu { PLAY_NOW { @Override public void call(Main m) { if (m.songs.length > 0 && m.songs[0] != m.selectedSong) { m.sendBroadcast(Player.Remote.Request.RemoveSong.getIntent().putExtra("song", m.selectedSong)); m.sendBroadcast(Player.Remote.Request.EnqueueSong .getIntent() .putExtra("song", m.selectedSong) .putExtra("index", 0)); } } @Override public int getLabelId() { return R.string.context_menu_play_now; } }, PLAY_NEXT { @Override public void call(Main m) { m.sendBroadcast(Player.Remote.Request.RemoveSong.getIntent().putExtra("song", m.selectedSong)); m.sendBroadcast(Player.Remote.Request.EnqueueSong .getIntent() .putExtra("song", m.selectedSong) .putExtra("index", 1)); } @Override public int getLabelId() { return R.string.context_menu_play_next; } }, REMOVE { @Override public void call(Main m) { m.sendBroadcast(Player.Remote.Request.RemoveSong.getIntent().putExtra("song", m.selectedSong)); } @Override public int getLabelId() { return R.string.context_menu_remove; } }, MOVE_UP { @Override public void call(Main m) { m.sendBroadcast(Player.Remote.Request.MoveSong .getIntent() .putExtra("song", m.selectedSong) .putExtra("offset", -1)); } @Override public int getLabelId() { return R.string.context_menu_move_up; } }, MOVE_DOWN { @Override public void call(Main m) { m.sendBroadcast(Player.Remote.Request.MoveSong .getIntent() .putExtra("song", m.selectedSong) .putExtra("offset", 1)); } @Override public int getLabelId() { return R.string.context_menu_move_down; } }, CLONE { @Override public void call(Main m) { m.sendBroadcast(Player.Remote.Request.EnqueueSong.getIntent().putExtra("song", m.selectedSong)); } @Override public int getLabelId() { return R.string.context_menu_clone; } }; public abstract void call(Main m); public abstract int getLabelId(); public static final void generate(Menu menu) { for (ContextMenu item : ContextMenu.values()) { menu.add(0, item.ordinal(), 0, item.getLabelId()); } } public static final void run(Main main, MenuItem item) { values()[item.getItemId()].call(main); } }; /** * Option menu (pops up on Menu button press) */ private enum OptionMenu { REMOVE_ALL { @Override public int getLabelId() { return R.string.option_menu_remove_all; } @Override public void call(Main m) { new AlertDialog.Builder(m) .setMessage(R.string.dialog_are_you_sure) .setPositiveButton(R.string.dialog_yes, new DialogOk(m)) .setNegativeButton(R.string.dialog_no, null) .show(); } class DialogOk implements DialogInterface.OnClickListener { private Main m; public DialogOk(Main m) { super(); this.m = m; } @Override public void onClick(DialogInterface dialog, int which) { for (int i = 1; i < m.songs.length; ++i) { m.sendBroadcast(Player.Remote.Request.RemoveSong.getIntent().putExtra( "song", m.songs[i])); } } }; }, SHUFFLE { @Override public int getLabelId() { return R.string.option_menu_shuffle; } @Override public void call(Main m) { new AlertDialog.Builder(m) .setMessage(R.string.dialog_are_you_sure) .setPositiveButton(R.string.dialog_yes, new DialogOk(m)) .setNegativeButton(R.string.dialog_no, null) .show(); } class DialogOk implements DialogInterface.OnClickListener { private Main m; public DialogOk(Main m) { super(); this.m = m; } @Override public void onClick(DialogInterface dialog, int which) { /* * Remove all songs, shuffle locally and then re-add. */ ArrayList<Song> songs = new ArrayList<Song>(); for (int i = 1; i < m.songs.length; ++i) { m.sendBroadcast(Player.Remote.Request.RemoveSong.getIntent().putExtra( "song", m.songs[i])); songs.add(m.songs[i]); } Collections.shuffle(songs); for (Song song : songs) { m.sendBroadcast(Player.Remote.Request.EnqueueSong.getIntent().putExtra( "song", song)); } } }; }, ENQUEUE_NEW { @Override public int getLabelId() { return R.string.option_menu_enqueue_new; } @Override public void call(Main m) { m.startActivity(new Intent(m, Songlist.class)); } }; public abstract int getLabelId(); public abstract void call(Main m); public static void generate(Menu menu) { for (OptionMenu item : values()) { menu.add(0, item.ordinal(), 0, item.getLabelId()); } } public static void run(Main main, MenuItem item) { values()[item.getItemId()].call(main); } }; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); playButton = (Button) findViewById(R.id.playButton); skipButton = (Button) findViewById(R.id.skipButton); songTime = (TextView) findViewById(R.id.songTime); songSeekBar = (SeekBar) findViewById(R.id.songSeekBar); enqueuedSongs = (ListView) findViewById(R.id.enqueuedSongs); registerReceiver(new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { int duration = intent.getIntExtra("duration", 0); int position = intent.getIntExtra("position", 0); state = (State) intent.getSerializableExtra("state"); switch (state) { case IS_STOPPED: songSeekBar.setMax(0); songSeekBar.setProgress(0); songTime.setText(""); break; case IS_PLAYING: songTime.setText(String.format("%d:%02d / %d:%02d (%d%%)", (position / 1000) / 60, (position / 1000) % 60, (duration / 1000) / 60, (duration / 1000) % 60, Math.round(100 * position / duration))); if (oldSeekBarPosition == -1) { songSeekBar.setMax(duration); songSeekBar.setProgress(position); } playButton.setText(R.string.button_pause); break; case IS_PAUSED: playButton.setText(R.string.button_play); break; } } }, Player.Remote.Reply.State.getIntentFilter()); /* * Update enqueued songs listview upon Reply.EnqueuedSongs */ registerReceiver(new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { songs = Player.parcelableArrayToSongs(intent.getParcelableArrayExtra("songs")); enqueuedSongs.setAdapter(new MainSongAdapter( getApplicationContext(), R.layout.listitem, songs)); } }, Player.Remote.Reply.EnqueuedSongs.getIntentFilter()); /* * If the service isn't running yet, the broadcast will be ignored. */ sendBroadcast(Player.Remote.Request.GetAvailableSongs.getIntent()); sendBroadcast(Player.Remote.Request.GetEnqueuedSongs.getIntent()); sendBroadcast(Player.Remote.Request.GetState.getIntent()); startService(new Intent(this, Player.class)); playButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { switch (state) { case IS_PLAYING: sendBroadcast(Player.Remote.Request.Stop.getIntent()); break; case IS_STOPPED: case IS_PAUSED: sendBroadcast(Player.Remote.Request.Play.getIntent()); break; } } }); skipButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { sendBroadcast(Player.Remote.Request.PlayNext.getIntent()); } }); /* * We send a seek request when the user has lifted his finger. */ songSeekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() { private int lastProgress = 0; @Override public void onStopTrackingTouch(SeekBar seekBar) { oldSeekBarPosition = -1; sendBroadcast(Player.Remote.Request.Seek.getIntent().putExtra("position", lastProgress)); } @Override public void onStartTrackingTouch(SeekBar seekBar) { oldSeekBarPosition = seekBar.getProgress(); } @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { if (fromUser) { lastProgress = progress; } } }); enqueuedSongs.setOnCreateContextMenuListener(new OnCreateContextMenuListener() { @Override public void onCreateContextMenu(android.view.ContextMenu menu, View v, ContextMenuInfo menuInfo) { AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo; selectedSong = (Song) enqueuedSongs.getItemAtPosition(info.position); ContextMenu.generate(menu); } }); } @Override public boolean onContextItemSelected(MenuItem item) { ContextMenu.run(this, item); return super.onContextItemSelected(item); } @Override protected void onDestroy() { /* * When the playback is stopped we destroy the backend service. * * This means we'll lose enqueued songs list of course. */ switch (state) { case IS_ON_HOLD_BY_CALL: case IS_ON_HOLD_BY_HEADSET: case IS_PAUSED: case IS_STOPPED: stopService(new Intent(this, Player.class)); break; } super.onDestroy(); } @Override public boolean onCreateOptionsMenu(Menu menu) { OptionMenu.generate(menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { OptionMenu.run(this, item); return super.onOptionsItemSelected(item); } private class MainSongAdapter extends SongAdapter { public MainSongAdapter(Context context, int textViewResourceId, Song[] objects) { super(context, textViewResourceId, objects); } @Override public View getView(int position, View convertView, ViewGroup parent) { View v = super.getView(position, convertView, parent); if (v != null) { if (position == 0) v.setBackgroundDrawable(getResources().getDrawable( R.drawable.listitem_selector_first)); else v.setBackgroundDrawable(getResources().getDrawable( R.drawable.listitem_selector)); } return v; } }; }
UTF-8
Java
12,043
java
10_af32e3dd4961319145b734b77346d76916120e6d_Main_t.java
Java
[]
null
[]
package com.michalkazior.simplemusicplayer; import java.util.ArrayList; import java.util.Collections; import com.michalkazior.simplemusicplayer.Player.State; import android.app.Activity; import android.app.AlertDialog; import android.content.BroadcastReceiver; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ContextMenu.ContextMenuInfo; import android.view.View.OnClickListener; import android.view.View.OnCreateContextMenuListener; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ListView; import android.widget.SeekBar; import android.widget.TextView; import android.widget.AdapterView.AdapterContextMenuInfo; import android.widget.SeekBar.OnSeekBarChangeListener; /** * Main activity. * * The user may manage the list of enqueued songs, play, pause. */ public class Main extends Activity { private Button playButton, skipButton; private TextView songTime; private SeekBar songSeekBar; private ListView enqueuedSongs; private Song[] songs = {}; private Player.State state = State.IS_STOPPED; private Song selectedSong = null; /* * Position of the seekbar before user started draging. * * -1 means the user is not dragging the seekbar. */ private int oldSeekBarPosition = -1; /** * Context menu for enqueued list items */ private enum ContextMenu { PLAY_NOW { @Override public void call(Main m) { if (m.songs.length > 0 && m.songs[0] != m.selectedSong) { m.sendBroadcast(Player.Remote.Request.RemoveSong.getIntent().putExtra("song", m.selectedSong)); m.sendBroadcast(Player.Remote.Request.EnqueueSong .getIntent() .putExtra("song", m.selectedSong) .putExtra("index", 0)); } } @Override public int getLabelId() { return R.string.context_menu_play_now; } }, PLAY_NEXT { @Override public void call(Main m) { m.sendBroadcast(Player.Remote.Request.RemoveSong.getIntent().putExtra("song", m.selectedSong)); m.sendBroadcast(Player.Remote.Request.EnqueueSong .getIntent() .putExtra("song", m.selectedSong) .putExtra("index", 1)); } @Override public int getLabelId() { return R.string.context_menu_play_next; } }, REMOVE { @Override public void call(Main m) { m.sendBroadcast(Player.Remote.Request.RemoveSong.getIntent().putExtra("song", m.selectedSong)); } @Override public int getLabelId() { return R.string.context_menu_remove; } }, MOVE_UP { @Override public void call(Main m) { m.sendBroadcast(Player.Remote.Request.MoveSong .getIntent() .putExtra("song", m.selectedSong) .putExtra("offset", -1)); } @Override public int getLabelId() { return R.string.context_menu_move_up; } }, MOVE_DOWN { @Override public void call(Main m) { m.sendBroadcast(Player.Remote.Request.MoveSong .getIntent() .putExtra("song", m.selectedSong) .putExtra("offset", 1)); } @Override public int getLabelId() { return R.string.context_menu_move_down; } }, CLONE { @Override public void call(Main m) { m.sendBroadcast(Player.Remote.Request.EnqueueSong.getIntent().putExtra("song", m.selectedSong)); } @Override public int getLabelId() { return R.string.context_menu_clone; } }; public abstract void call(Main m); public abstract int getLabelId(); public static final void generate(Menu menu) { for (ContextMenu item : ContextMenu.values()) { menu.add(0, item.ordinal(), 0, item.getLabelId()); } } public static final void run(Main main, MenuItem item) { values()[item.getItemId()].call(main); } }; /** * Option menu (pops up on Menu button press) */ private enum OptionMenu { REMOVE_ALL { @Override public int getLabelId() { return R.string.option_menu_remove_all; } @Override public void call(Main m) { new AlertDialog.Builder(m) .setMessage(R.string.dialog_are_you_sure) .setPositiveButton(R.string.dialog_yes, new DialogOk(m)) .setNegativeButton(R.string.dialog_no, null) .show(); } class DialogOk implements DialogInterface.OnClickListener { private Main m; public DialogOk(Main m) { super(); this.m = m; } @Override public void onClick(DialogInterface dialog, int which) { for (int i = 1; i < m.songs.length; ++i) { m.sendBroadcast(Player.Remote.Request.RemoveSong.getIntent().putExtra( "song", m.songs[i])); } } }; }, SHUFFLE { @Override public int getLabelId() { return R.string.option_menu_shuffle; } @Override public void call(Main m) { new AlertDialog.Builder(m) .setMessage(R.string.dialog_are_you_sure) .setPositiveButton(R.string.dialog_yes, new DialogOk(m)) .setNegativeButton(R.string.dialog_no, null) .show(); } class DialogOk implements DialogInterface.OnClickListener { private Main m; public DialogOk(Main m) { super(); this.m = m; } @Override public void onClick(DialogInterface dialog, int which) { /* * Remove all songs, shuffle locally and then re-add. */ ArrayList<Song> songs = new ArrayList<Song>(); for (int i = 1; i < m.songs.length; ++i) { m.sendBroadcast(Player.Remote.Request.RemoveSong.getIntent().putExtra( "song", m.songs[i])); songs.add(m.songs[i]); } Collections.shuffle(songs); for (Song song : songs) { m.sendBroadcast(Player.Remote.Request.EnqueueSong.getIntent().putExtra( "song", song)); } } }; }, ENQUEUE_NEW { @Override public int getLabelId() { return R.string.option_menu_enqueue_new; } @Override public void call(Main m) { m.startActivity(new Intent(m, Songlist.class)); } }; public abstract int getLabelId(); public abstract void call(Main m); public static void generate(Menu menu) { for (OptionMenu item : values()) { menu.add(0, item.ordinal(), 0, item.getLabelId()); } } public static void run(Main main, MenuItem item) { values()[item.getItemId()].call(main); } }; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); playButton = (Button) findViewById(R.id.playButton); skipButton = (Button) findViewById(R.id.skipButton); songTime = (TextView) findViewById(R.id.songTime); songSeekBar = (SeekBar) findViewById(R.id.songSeekBar); enqueuedSongs = (ListView) findViewById(R.id.enqueuedSongs); registerReceiver(new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { int duration = intent.getIntExtra("duration", 0); int position = intent.getIntExtra("position", 0); state = (State) intent.getSerializableExtra("state"); switch (state) { case IS_STOPPED: songSeekBar.setMax(0); songSeekBar.setProgress(0); songTime.setText(""); break; case IS_PLAYING: songTime.setText(String.format("%d:%02d / %d:%02d (%d%%)", (position / 1000) / 60, (position / 1000) % 60, (duration / 1000) / 60, (duration / 1000) % 60, Math.round(100 * position / duration))); if (oldSeekBarPosition == -1) { songSeekBar.setMax(duration); songSeekBar.setProgress(position); } playButton.setText(R.string.button_pause); break; case IS_PAUSED: playButton.setText(R.string.button_play); break; } } }, Player.Remote.Reply.State.getIntentFilter()); /* * Update enqueued songs listview upon Reply.EnqueuedSongs */ registerReceiver(new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { songs = Player.parcelableArrayToSongs(intent.getParcelableArrayExtra("songs")); enqueuedSongs.setAdapter(new MainSongAdapter( getApplicationContext(), R.layout.listitem, songs)); } }, Player.Remote.Reply.EnqueuedSongs.getIntentFilter()); /* * If the service isn't running yet, the broadcast will be ignored. */ sendBroadcast(Player.Remote.Request.GetAvailableSongs.getIntent()); sendBroadcast(Player.Remote.Request.GetEnqueuedSongs.getIntent()); sendBroadcast(Player.Remote.Request.GetState.getIntent()); startService(new Intent(this, Player.class)); playButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { switch (state) { case IS_PLAYING: sendBroadcast(Player.Remote.Request.Stop.getIntent()); break; case IS_STOPPED: case IS_PAUSED: sendBroadcast(Player.Remote.Request.Play.getIntent()); break; } } }); skipButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { sendBroadcast(Player.Remote.Request.PlayNext.getIntent()); } }); /* * We send a seek request when the user has lifted his finger. */ songSeekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() { private int lastProgress = 0; @Override public void onStopTrackingTouch(SeekBar seekBar) { oldSeekBarPosition = -1; sendBroadcast(Player.Remote.Request.Seek.getIntent().putExtra("position", lastProgress)); } @Override public void onStartTrackingTouch(SeekBar seekBar) { oldSeekBarPosition = seekBar.getProgress(); } @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { if (fromUser) { lastProgress = progress; } } }); enqueuedSongs.setOnCreateContextMenuListener(new OnCreateContextMenuListener() { @Override public void onCreateContextMenu(android.view.ContextMenu menu, View v, ContextMenuInfo menuInfo) { AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo; selectedSong = (Song) enqueuedSongs.getItemAtPosition(info.position); ContextMenu.generate(menu); } }); } @Override public boolean onContextItemSelected(MenuItem item) { ContextMenu.run(this, item); return super.onContextItemSelected(item); } @Override protected void onDestroy() { /* * When the playback is stopped we destroy the backend service. * * This means we'll lose enqueued songs list of course. */ switch (state) { case IS_ON_HOLD_BY_CALL: case IS_ON_HOLD_BY_HEADSET: case IS_PAUSED: case IS_STOPPED: stopService(new Intent(this, Player.class)); break; } super.onDestroy(); } @Override public boolean onCreateOptionsMenu(Menu menu) { OptionMenu.generate(menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { OptionMenu.run(this, item); return super.onOptionsItemSelected(item); } private class MainSongAdapter extends SongAdapter { public MainSongAdapter(Context context, int textViewResourceId, Song[] objects) { super(context, textViewResourceId, objects); } @Override public View getView(int position, View convertView, ViewGroup parent) { View v = super.getView(position, convertView, parent); if (v != null) { if (position == 0) v.setBackgroundDrawable(getResources().getDrawable( R.drawable.listitem_selector_first)); else v.setBackgroundDrawable(getResources().getDrawable( R.drawable.listitem_selector)); } return v; } }; }
12,043
0.65756
0.653159
439
26.430525
22.254156
84
false
false
0
0
0
0
0
0
3.236902
false
false
1
955090af992e1a112a8baaf7129649af1dc37173
33,938,831,609,072
e7aad9c122e93620d56ace7708f6c7b12d946999
/src/test/java/com/kidream/dept/tongtianxia/library/ProductTest.java
34481ba8a87f65d34fd0e458b543fdb852870965
[]
no_license
kafka-pxq/ERP-kidream
https://github.com/kafka-pxq/ERP-kidream
d3bae88a321e1a093c097763be83c3a0a2bb0587
462234a7ffef8e797b64826e475946de49f401df
refs/heads/master
2022-12-23T06:47:16.045000
2020-03-19T15:47:24
2020-03-19T15:47:24
248,540,947
2
0
null
false
2022-12-16T14:59:47
2020-03-19T15:40:34
2020-04-29T08:36:39
2022-12-16T14:59:27
4,249
2
0
4
JavaScript
false
false
package com.kidream.dept.tongtianxia.library; import java.util.List; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.kidream.dept.tongtianxia.library.domin.Product; import com.kidream.dept.tongtianxia.library.service.ProductService; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:spring/spring-mybatis.xml") public class ProductTest { @Autowired private ProductService ps; @Test public void testListAll() throws Exception { List<Product> list = ps.listAll(); for (Product p : list) { System.out.println("编号:"+p.getId()+"产品名称:"+p.getProduct_name()+"产品属性"+p.getAttribute()+"产品库存量"+p.getInventory()+"出版社:"+p.getPublisher().getPublisher_name()+"类型:"+p.getSubject().getSubject_name()+"单价:"+p.getUnitPrice()+"折扣:"+p.getDiscount()); System.out.println("折扣价:"+p.getDiscount_price()+"折扣总价:"+p.getTotal_discount_price()); } } }
UTF-8
Java
1,160
java
ProductTest.java
Java
[]
null
[]
package com.kidream.dept.tongtianxia.library; import java.util.List; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.kidream.dept.tongtianxia.library.domin.Product; import com.kidream.dept.tongtianxia.library.service.ProductService; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:spring/spring-mybatis.xml") public class ProductTest { @Autowired private ProductService ps; @Test public void testListAll() throws Exception { List<Product> list = ps.listAll(); for (Product p : list) { System.out.println("编号:"+p.getId()+"产品名称:"+p.getProduct_name()+"产品属性"+p.getAttribute()+"产品库存量"+p.getInventory()+"出版社:"+p.getPublisher().getPublisher_name()+"类型:"+p.getSubject().getSubject_name()+"单价:"+p.getUnitPrice()+"折扣:"+p.getDiscount()); System.out.println("折扣价:"+p.getDiscount_price()+"折扣总价:"+p.getTotal_discount_price()); } } }
1,160
0.768946
0.766174
28
37.642857
47.349171
244
false
false
0
0
0
0
0
0
1.071429
false
false
1
df4c987a7f8996da18977470926b3800782f364f
36,876,589,231,463
21e83306076b9e5a56cae46652f0b534d3fe16e5
/crm-stubs/src/main/java/ru/sbrf/efs/rmkmcib/bht/config/RmKmAppConfig.java
afa6c8db4d50827f75dda6182304f65e45f37396
[]
no_license
AndreyGrand/stubs
https://github.com/AndreyGrand/stubs
11761ca5773837f4ab720ac77ff2c1899be54d69
7c533d668cca94a23f0af57c2082bc28d8e4d473
refs/heads/master
2021-01-20T19:30:10.358000
2016-08-16T12:24:52
2016-08-16T12:32:24
65,818,346
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ru.sbrf.efs.rmkmcib.bht.config; import org.apache.activemq.ActiveMQConnectionFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; import org.springframework.jms.core.JmsTemplate; /** * Created by sbt-manayev-iye on 02.08.2016. * */ @Configuration @PropertySource("classpath:application.properties") @ComponentScan(basePackages = {"ru.sbrf.efs.rmkmcib.bht.app"}) public class RmKmAppConfig { @Value("${activemq.url}") String activeMqUrl; @Value("${activemq.queues.out}") String activeMqOutQueue; @Value("${activemq.queues.in}") String activeMqInQueue; @Bean public JmsTemplate jmsTemplate() { JmsTemplate jmsTemplate = new JmsTemplate(); jmsTemplate.setConnectionFactory(connectionFactory()); return jmsTemplate; } @Bean public ActiveMQConnectionFactory connectionFactory() { ActiveMQConnectionFactory activeMQConnectionFactory = new ActiveMQConnectionFactory(); activeMQConnectionFactory.setBrokerURL(activeMqUrl); return activeMQConnectionFactory; } }
UTF-8
Java
1,320
java
RmKmAppConfig.java
Java
[ { "context": "framework.jms.core.JmsTemplate;\n\n/**\n * Created by sbt-manayev-iye on 02.08.2016.\n *\n */\n@Configuration\n@PropertySou", "end": 473, "score": 0.999556303024292, "start": 458, "tag": "USERNAME", "value": "sbt-manayev-iye" } ]
null
[]
package ru.sbrf.efs.rmkmcib.bht.config; import org.apache.activemq.ActiveMQConnectionFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; import org.springframework.jms.core.JmsTemplate; /** * Created by sbt-manayev-iye on 02.08.2016. * */ @Configuration @PropertySource("classpath:application.properties") @ComponentScan(basePackages = {"ru.sbrf.efs.rmkmcib.bht.app"}) public class RmKmAppConfig { @Value("${activemq.url}") String activeMqUrl; @Value("${activemq.queues.out}") String activeMqOutQueue; @Value("${activemq.queues.in}") String activeMqInQueue; @Bean public JmsTemplate jmsTemplate() { JmsTemplate jmsTemplate = new JmsTemplate(); jmsTemplate.setConnectionFactory(connectionFactory()); return jmsTemplate; } @Bean public ActiveMQConnectionFactory connectionFactory() { ActiveMQConnectionFactory activeMQConnectionFactory = new ActiveMQConnectionFactory(); activeMQConnectionFactory.setBrokerURL(activeMqUrl); return activeMQConnectionFactory; } }
1,320
0.759091
0.75303
44
29
25.098896
94
false
false
0
0
0
0
0
0
0.386364
false
false
1
382f094706673306c02b2c399a029e1313a58fa7
36,017,595,780,596
4153c342f4e029be6be19b34cb3eb19f52310a58
/src/test/java/com/huawei/JsonConfigWriterTest.java
e18a5b7892d8d1ce16e583b417fea3609b52ebe5
[]
no_license
arkadius2006/public-cloud-consolidation
https://github.com/arkadius2006/public-cloud-consolidation
736f865f38d29d2c0b21739f6f488dab45d633a4
af94b8dec242d39f239021ab4c32b5726c52b189
refs/heads/master
2022-11-30T20:41:53.589000
2020-08-07T13:53:44
2020-08-07T13:53:44
221,456,542
0
0
null
false
2022-11-15T23:33:26
2019-11-13T12:40:28
2020-08-07T13:53:48
2022-11-15T23:33:23
427
0
0
2
Java
false
false
package com.huawei; import com.huawei.algorithm.Generator; import com.huawei.io.JsonConfigurationWriter; import org.junit.Test; import java.io.IOException; import java.io.StringWriter; public class JsonConfigWriterTest { @Test public void test() throws IOException { Cloud config = new Generator(1, 1).generate(); StringWriter sw = new StringWriter(); new JsonConfigurationWriter().write(config, sw); String s = sw.toString(); System.out.println(s); } }
UTF-8
Java
512
java
JsonConfigWriterTest.java
Java
[]
null
[]
package com.huawei; import com.huawei.algorithm.Generator; import com.huawei.io.JsonConfigurationWriter; import org.junit.Test; import java.io.IOException; import java.io.StringWriter; public class JsonConfigWriterTest { @Test public void test() throws IOException { Cloud config = new Generator(1, 1).generate(); StringWriter sw = new StringWriter(); new JsonConfigurationWriter().write(config, sw); String s = sw.toString(); System.out.println(s); } }
512
0.693359
0.689453
21
23.380953
19.124844
56
false
false
0
0
0
0
0
0
0.619048
false
false
1
8b909d8fd2dad4eeb100858e15a293e518fb5862
39,178,691,699,507
b33cade42fa3dfff225ea4e9b4636d2394c348c1
/lab a20.3 (abstract classes)/GoldCustomer.java
6182dfab287243f4b9db28685626f601d2db2eb7
[ "MIT" ]
permissive
Ali-Kazmi/AP-CSA
https://github.com/Ali-Kazmi/AP-CSA
e75542d844f4346ac3a9791a75a7c54387cd36f9
e2c0860a72b08c8a41c7244be6d2f4c5e52be5bf
refs/heads/master
2020-04-27T22:30:55.377000
2019-04-18T02:18:24
2019-04-18T02:18:24
174,739,838
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * Last name: Kazmi * First name: Ali * Student ID: 12106808 * Period 2 */ public class GoldCustomer extends Customer { final double serviceDiscountRate = 0.15; //Do not add any more fields //Add your methods along with their documentation /** * Creates gold customer with the name, gold member type, service discount rate * @param n name of the customer */ public GoldCustomer(String n){ super(n); memberType="Gold"; super.serviceDiscountRate=this.serviceDiscountRate; } }
UTF-8
Java
528
java
GoldCustomer.java
Java
[ { "context": "/**\n * Last name: Kazmi \n * First name: Ali \n * Student ID: 12106808\n * P", "end": 23, "score": 0.999721109867096, "start": 18, "tag": "NAME", "value": "Kazmi" }, { "context": "/**\n * Last name: Kazmi \n * First name: Ali \n * Student ID: 12106808\n * Period 2\n */\npublic c", "end": 43, "score": 0.9998364448547363, "start": 40, "tag": "NAME", "value": "Ali" } ]
null
[]
/** * Last name: Kazmi * First name: Ali * Student ID: 12106808 * Period 2 */ public class GoldCustomer extends Customer { final double serviceDiscountRate = 0.15; //Do not add any more fields //Add your methods along with their documentation /** * Creates gold customer with the name, gold member type, service discount rate * @param n name of the customer */ public GoldCustomer(String n){ super(n); memberType="Gold"; super.serviceDiscountRate=this.serviceDiscountRate; } }
528
0.681818
0.659091
22
23.045454
21.289087
80
false
false
0
0
0
0
0
0
0.590909
false
false
1
7421a2bf04dbdd3947839a464df3b0dbcd8b5787
31,164,282,759,186
e728a921f83c614dbe8c0da3a07a064b9e7611da
/app/src/main/java/com/example/benbriggs/food_journal/adapters/MainProductAdapter.java
51041ef50d4cbbaa5b71eeba48f471bc998599d8
[]
no_license
benbriggsy/Food-journal
https://github.com/benbriggsy/Food-journal
68491c0de05d23ba647ee5b1daa97db47491cab2
2d7cbe1ab57ade56ecaba41c633e6c24f97d705e
refs/heads/master
2021-05-08T23:39:24.414000
2018-05-07T16:03:41
2018-05-07T16:03:41
119,715,666
0
0
null
false
2018-04-12T15:03:21
2018-01-31T16:51:16
2018-03-16T10:32:34
2018-04-12T15:03:21
207
0
0
0
Java
false
null
package com.example.benbriggs.food_journal.adapters; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import android.widget.Toast; import com.example.benbriggs.food_journal.MainActivity; import com.example.benbriggs.food_journal.R; import com.example.benbriggs.food_journal.user.Basket; import com.example.benbriggs.food_journal.user.FoodItem; import java.util.ArrayList; /** * A class that handles the inflation of the list of products on the main screen */ public class MainProductAdapter extends RecyclerView.Adapter<MainProductAdapter.MainProductViewHolder>{ private Basket mBasket; private ArrayList<FoodItem> mFoodItems; private Context mContext; private MainActivity mMainActivity; public MainProductAdapter(Basket Basket, Context context, MainActivity mainActivity){ mBasket = Basket; mFoodItems = mBasket.getProducts(); mContext = context; mMainActivity = mainActivity; } @Override public MainProductViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()) .inflate(R.layout.main_product_list_item, parent, false); MainProductViewHolder viewHolder = new MainProductViewHolder(view); return viewHolder; } @Override public void onBindViewHolder(MainProductViewHolder holder, int position) { holder.bindFoodItem(mFoodItems.get(position)); } @Override public int getItemCount() { return mFoodItems.size(); } public class MainProductViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{ public TextView mProductName; public MainProductViewHolder(View itemView) { super(itemView); itemView.setOnClickListener(this); mProductName = (TextView) itemView.findViewById(R.id.listMainProductName); } public void bindFoodItem(FoodItem foodItem){ mProductName.setText(foodItem.getProductName()); } @Override public void onClick(View view) { //mFoodItems.remove(getAdapterPosition()); Toast.makeText(mContext, "Item removed", Toast.LENGTH_SHORT).show(); mMainActivity.removeScannedItem(getAdapterPosition()); } } }
UTF-8
Java
2,464
java
MainProductAdapter.java
Java
[ { "context": "package com.example.benbriggs.food_journal.adapters;\n\nimport android.content.Co", "end": 29, "score": 0.8194877505302429, "start": 20, "tag": "USERNAME", "value": "benbriggs" }, { "context": "port android.widget.Toast;\n\nimport com.example.benbriggs.food_journal.MainActivity;\nimport com.example.ben", "end": 316, "score": 0.9365171790122986, "start": 310, "tag": "USERNAME", "value": "briggs" }, { "context": "ggs.food_journal.MainActivity;\nimport com.example.benbriggs.food_journal.R;\nimport com.example.benbriggs.food", "end": 372, "score": 0.8334383964538574, "start": 363, "tag": "USERNAME", "value": "benbriggs" }, { "context": "e.benbriggs.food_journal.R;\nimport com.example.benbriggs.food_journal.user.Basket;\nimport com.example.benb", "end": 417, "score": 0.9056835174560547, "start": 411, "tag": "USERNAME", "value": "briggs" }, { "context": "s.food_journal.user.Basket;\nimport com.example.benbriggs.food_journal.user.FoodItem;\n\nimport java.util.Arr", "end": 472, "score": 0.6825324892997742, "start": 466, "tag": "USERNAME", "value": "briggs" } ]
null
[]
package com.example.benbriggs.food_journal.adapters; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import android.widget.Toast; import com.example.benbriggs.food_journal.MainActivity; import com.example.benbriggs.food_journal.R; import com.example.benbriggs.food_journal.user.Basket; import com.example.benbriggs.food_journal.user.FoodItem; import java.util.ArrayList; /** * A class that handles the inflation of the list of products on the main screen */ public class MainProductAdapter extends RecyclerView.Adapter<MainProductAdapter.MainProductViewHolder>{ private Basket mBasket; private ArrayList<FoodItem> mFoodItems; private Context mContext; private MainActivity mMainActivity; public MainProductAdapter(Basket Basket, Context context, MainActivity mainActivity){ mBasket = Basket; mFoodItems = mBasket.getProducts(); mContext = context; mMainActivity = mainActivity; } @Override public MainProductViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()) .inflate(R.layout.main_product_list_item, parent, false); MainProductViewHolder viewHolder = new MainProductViewHolder(view); return viewHolder; } @Override public void onBindViewHolder(MainProductViewHolder holder, int position) { holder.bindFoodItem(mFoodItems.get(position)); } @Override public int getItemCount() { return mFoodItems.size(); } public class MainProductViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{ public TextView mProductName; public MainProductViewHolder(View itemView) { super(itemView); itemView.setOnClickListener(this); mProductName = (TextView) itemView.findViewById(R.id.listMainProductName); } public void bindFoodItem(FoodItem foodItem){ mProductName.setText(foodItem.getProductName()); } @Override public void onClick(View view) { //mFoodItems.remove(getAdapterPosition()); Toast.makeText(mContext, "Item removed", Toast.LENGTH_SHORT).show(); mMainActivity.removeScannedItem(getAdapterPosition()); } } }
2,464
0.717938
0.717532
73
32.753426
28.547859
103
false
false
0
0
0
0
0
0
0.575342
false
false
1
530fecdab11027029a1a1e2e7821c4a384a7702e
24,781,961,315,582
9de50f8d337b7e09b22589b7d6ee628b271d8aa0
/test/src/Util/JudgeUtil.java
a8493322d15434607e3f11d874e64d6933df9791
[]
no_license
XuDongZe/Java-C-Project
https://github.com/XuDongZe/Java-C-Project
2cb51943b8b9e44898680f86fa651f5da689159d
e58aec5ac6c0360ed51d07f9fedd3d638400c441
refs/heads/master
2021-07-17T02:16:36.537000
2021-07-07T11:56:25
2021-07-07T11:56:25
173,602,390
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package Util; import javax.swing.JOptionPane; import Constant.Constant; import Game.MyPanel; import Poro.Player; import Util.SoundUtil; /** * * @ClassName: JudgeUtil * @Description: 判断游戏是否结束,游戏规则 * @author xudongze * @date 2018年7月17日 下午10:27:23 * */ public class JudgeUtil implements Constant{ private Player player; private MyPanel gamePanel; public JudgeUtil(Player player, MyPanel panel) { this.player = player; this.gamePanel = panel; } public JudgeUtil() { } //判断是否通过 public void judgeSuccess() { if(player.getPlayerX() == COL-2 && player.getPlayerY() == ROW-2) { System.out.println("chenggong"); //短时间的声音音频加载类实例化 SoundUtil.playSound("sound/win_wav.wav"); //通关提示框 JOptionPane.showMessageDialog(null, "当前关卡:\t" + MapUtil.getcurrentMapNo() + "通过!"); if( MapUtil.getcurrentMapNo() == MapUtil.getMapCounts() ) { //通关提示框 JOptionPane.showMessageDialog(null, "恭喜您已经通关!"); }else { //加载下一关地图 MapUtil.loadNextMap(); //显示下一关地图 gamePanel.repaint(); } } } }
GB18030
Java
1,192
java
JudgeUtil.java
Java
[ { "context": "JudgeUtil \n* @Description: 判断游戏是否结束,游戏规则\n* @author xudongze\n* @date 2018年7月17日 下午10:27:23 \n*\n */\npublic class", "end": 220, "score": 0.9997214674949646, "start": 212, "tag": "USERNAME", "value": "xudongze" } ]
null
[]
package Util; import javax.swing.JOptionPane; import Constant.Constant; import Game.MyPanel; import Poro.Player; import Util.SoundUtil; /** * * @ClassName: JudgeUtil * @Description: 判断游戏是否结束,游戏规则 * @author xudongze * @date 2018年7月17日 下午10:27:23 * */ public class JudgeUtil implements Constant{ private Player player; private MyPanel gamePanel; public JudgeUtil(Player player, MyPanel panel) { this.player = player; this.gamePanel = panel; } public JudgeUtil() { } //判断是否通过 public void judgeSuccess() { if(player.getPlayerX() == COL-2 && player.getPlayerY() == ROW-2) { System.out.println("chenggong"); //短时间的声音音频加载类实例化 SoundUtil.playSound("sound/win_wav.wav"); //通关提示框 JOptionPane.showMessageDialog(null, "当前关卡:\t" + MapUtil.getcurrentMapNo() + "通过!"); if( MapUtil.getcurrentMapNo() == MapUtil.getMapCounts() ) { //通关提示框 JOptionPane.showMessageDialog(null, "恭喜您已经通关!"); }else { //加载下一关地图 MapUtil.loadNextMap(); //显示下一关地图 gamePanel.repaint(); } } } }
1,192
0.674664
0.660269
53
18.660378
17.373743
68
false
false
0
0
0
0
0
0
1.830189
false
false
1
1f5acbcc8d6d30f2d3d5219c590bcd81cdb6cadd
5,540,507,837,334
59b647f5b58e62d966e8044bbf973f54c3b553c4
/src/main/java/blood/steel/server/model/character/Inventory.java
278f957009192c44be6f097a1e66d067f12aed43
[]
no_license
artemmoskalev/mmo_server
https://github.com/artemmoskalev/mmo_server
70322d8a03ed32383cbd3456f380ca8538dd6d04
18abec5c2ed0c2cb169821852689551d4a84b392
refs/heads/master
2021-01-06T20:45:39.496000
2015-02-17T19:22:42
2015-02-17T19:22:42
30,932,671
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package blood.steel.server.model.character; import java.util.List; import javax.persistence.*; import blood.steel.server.model.items.*; @Embeddable public class Inventory { private int totalInventorySize; private int currentInventorySize; @OneToMany(cascade={CascadeType.ALL}) @JoinColumn protected List<Item> inventory; public Inventory() { } public Inventory(int totalSize) { this.totalInventorySize = totalSize; } public int getTotalInventorySize() { return totalInventorySize; } public void setTotalInventorySize(int totalInventorySize) { this.totalInventorySize = totalInventorySize; } public int getCurrentInventorySize() { return currentInventorySize; } public void setCurrentInventorySize(int currentInventorySize) { this.currentInventorySize = currentInventorySize; } public boolean addItem(Item item) { if(totalInventorySize >= item.getWeight() + currentInventorySize) { inventory.add(item); currentInventorySize += item.getWeight(); return true; } else { return false; } } public boolean removeItem(Item item) { if(inventory.remove(item)) { currentInventorySize = currentInventorySize-item.getWeight(); return true; } else { return false; } } public Item getItemById(long id) { Item article = null; for(Item item : inventory) { if(item.getId() == id) { article = item; break; } } return article; } public List<Item> getItemList() { return inventory; } }
UTF-8
Java
1,473
java
Inventory.java
Java
[]
null
[]
package blood.steel.server.model.character; import java.util.List; import javax.persistence.*; import blood.steel.server.model.items.*; @Embeddable public class Inventory { private int totalInventorySize; private int currentInventorySize; @OneToMany(cascade={CascadeType.ALL}) @JoinColumn protected List<Item> inventory; public Inventory() { } public Inventory(int totalSize) { this.totalInventorySize = totalSize; } public int getTotalInventorySize() { return totalInventorySize; } public void setTotalInventorySize(int totalInventorySize) { this.totalInventorySize = totalInventorySize; } public int getCurrentInventorySize() { return currentInventorySize; } public void setCurrentInventorySize(int currentInventorySize) { this.currentInventorySize = currentInventorySize; } public boolean addItem(Item item) { if(totalInventorySize >= item.getWeight() + currentInventorySize) { inventory.add(item); currentInventorySize += item.getWeight(); return true; } else { return false; } } public boolean removeItem(Item item) { if(inventory.remove(item)) { currentInventorySize = currentInventorySize-item.getWeight(); return true; } else { return false; } } public Item getItemById(long id) { Item article = null; for(Item item : inventory) { if(item.getId() == id) { article = item; break; } } return article; } public List<Item> getItemList() { return inventory; } }
1,473
0.72573
0.72573
68
20.661764
18.482592
69
false
false
0
0
0
0
0
0
1.794118
false
false
1
6523d4a1899bf54c71070ea07b1820825b75807b
28,260,884,821,299
a770e95028afb71f3b161d43648c347642819740
/sources/org/telegram/ui/PassportActivity$$ExternalSyntheticLambda47.java
9227b1c272aafc73a9959f8661754759ed174950
[]
no_license
Edicksonjga/TGDecompiledBeta
https://github.com/Edicksonjga/TGDecompiledBeta
d7aa48a2b39bbaefd4752299620ff7b72b515c83
d1db6a445d5bed43c1dc8213fb8dbefd96f6c51b
refs/heads/master
2023-08-25T04:12:15.592000
2021-10-28T20:24:07
2021-10-28T20:24:07
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.telegram.ui; public final /* synthetic */ class PassportActivity$$ExternalSyntheticLambda47 implements Runnable { public final /* synthetic */ PassportActivity f$0; public /* synthetic */ PassportActivity$$ExternalSyntheticLambda47(PassportActivity passportActivity) { this.f$0 = passportActivity; } public final void run() { this.f$0.needHideProgress(); } }
UTF-8
Java
410
java
PassportActivity$$ExternalSyntheticLambda47.java
Java
[]
null
[]
package org.telegram.ui; public final /* synthetic */ class PassportActivity$$ExternalSyntheticLambda47 implements Runnable { public final /* synthetic */ PassportActivity f$0; public /* synthetic */ PassportActivity$$ExternalSyntheticLambda47(PassportActivity passportActivity) { this.f$0 = passportActivity; } public final void run() { this.f$0.needHideProgress(); } }
410
0.712195
0.695122
13
30.538462
35.411026
107
false
false
0
0
0
0
0
0
0.307692
false
false
1
7d8f2e43d3141eacb98deb551a78ac4099500daa
962,072,677,976
9d415dbeb592c262c8a869e15ee4caa150e89186
/src/main/java/org/neo4j/constraints/ConstrainApp.java
6b6f04ba794d29bd72d19f7c80d30871390b2c2a
[]
no_license
jexp/neo4j-constraints
https://github.com/jexp/neo4j-constraints
a54e1be04576211c57943622abe851c67de78be9
7caced10577e87bcb8f492f7658b9828f41c68c0
refs/heads/master
2016-09-06T07:24:14.752000
2014-10-10T21:05:07
2014-10-10T21:05:07
25,037,451
1
0
null
false
2014-10-10T21:06:37
2014-10-10T13:48:15
2014-10-10T20:37:06
2014-10-10T21:05:08
0
2
1
1
Java
null
null
package org.neo4j.constraints; import org.neo4j.kernel.impl.core.GraphProperties; import org.neo4j.kernel.impl.core.NodeManager; import org.neo4j.shell.*; import org.neo4j.shell.kernel.apps.TransactionProvidingApp; /** * @author mh * @since 10.10.14 */ public class ConstrainApp extends TransactionProvidingApp { @Override protected Continuation exec(AppCommandParser appCommandParser, Session session, Output output) throws Exception { String line = appCommandParser.getLineWithoutApp(); Constraint constraint = ConstraintParser.parse(line); storeConstraint(constraint); return Continuation.INPUT_COMPLETE; } private void storeConstraint(Constraint constraint) { GraphProperties props = getServer().getDb().getDependencyResolver().resolveDependency(NodeManager.class).getGraphProperties(); ConstraintPersister constraintPersister = new ConstraintPersister(props); Constraint.Constraints constraints = constraintPersister.restore(); constraints.add(constraint); constraintPersister.persist(constraints); } @Override public String getName() { return "constrain"; } }
UTF-8
Java
1,187
java
ConstrainApp.java
Java
[ { "context": "rnel.apps.TransactionProvidingApp;\n\n/**\n * @author mh\n * @since 10.10.14\n */\npublic class ConstrainApp ", "end": 234, "score": 0.9995732307434082, "start": 232, "tag": "USERNAME", "value": "mh" } ]
null
[]
package org.neo4j.constraints; import org.neo4j.kernel.impl.core.GraphProperties; import org.neo4j.kernel.impl.core.NodeManager; import org.neo4j.shell.*; import org.neo4j.shell.kernel.apps.TransactionProvidingApp; /** * @author mh * @since 10.10.14 */ public class ConstrainApp extends TransactionProvidingApp { @Override protected Continuation exec(AppCommandParser appCommandParser, Session session, Output output) throws Exception { String line = appCommandParser.getLineWithoutApp(); Constraint constraint = ConstraintParser.parse(line); storeConstraint(constraint); return Continuation.INPUT_COMPLETE; } private void storeConstraint(Constraint constraint) { GraphProperties props = getServer().getDb().getDependencyResolver().resolveDependency(NodeManager.class).getGraphProperties(); ConstraintPersister constraintPersister = new ConstraintPersister(props); Constraint.Constraints constraints = constraintPersister.restore(); constraints.add(constraint); constraintPersister.persist(constraints); } @Override public String getName() { return "constrain"; } }
1,187
0.740522
0.731255
35
32.914288
33.297253
134
false
false
0
0
0
0
0
0
0.485714
false
false
1