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
059b27b76eef7d5a97e605900a19be602fda27a3
3,418,793,995,815
7cbae2cffdcb8ea7cf0eda157a0ed6f6306a58a5
/fxbworld/fxbworld-service/src/main/java/com/fxb/world/service/sys/SysUserResourcesService.java
de4b106c1b898249be0b7d09a141c30fcdacef2e
[]
no_license
Timmyds/test
https://github.com/Timmyds/test
59eef66eb25ac9a7fe9aecc1093f09a76342575b
1d9be50a231a84c533d244d481b173cb59b5e269
refs/heads/master
2020-04-05T14:04:29.251000
2017-08-01T10:18:40
2017-08-01T10:18:40
94,754,543
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/*package com.fxb.world.service.sys; import java.util.ArrayList; import java.util.List; import javax.annotation.Resource; import org.springframework.stereotype.Service; import com.dtds.platform.util.bean.Result; import com.dtds.platform.util.exception.FunctionException; import com.tsh.usercentre.dao.SysUserResourcesDao; import com.tsh.usercentre.po.system.SysUserResourcesPo; import com.tsh.usercentre.util.MessageResource; *//** * * @author ds * *//* @Service public class SysUserResourcesService { @Resource SysUserResourcesDao sysUserResourcesDao; *//** * * @param result * @param userId * @return * @throws Exception * @author ds * @date 2017年2月8日 * @version 3.1.0 *//* public Result querySysUserResourcesByuserIdService(Result result, Long userId,Integer status) throws Exception { if (userId == null) { result.setMsg(MessageResource.PARAMETERS_ERROR); throw new FunctionException(result, ""); } List<Long> list=new ArrayList<Long>(); result=sysUserResourcesDao.querySysUserResourcesByUserId(result, userId,status); List<SysUserResourcesPo> suList = result.getData(); for (SysUserResourcesPo sysUserResourcesPo : suList) { list.add(sysUserResourcesPo.getResourcesId()); } result.setData(list); return result; } *//** * * @param result * @param poList * @return * @throws Exception *//* public Result saveSysUserResourcesListService(Result result, List<SysUserResourcesPo> poList) throws Exception { return sysUserResourcesDao.saveSysUserResourcesList(result, poList); } *//** * * @param result * @param userId * @return * @throws Exception *//* public Result delSysUserResourcesService(Result result, Long userId,Integer status) throws Exception { if (null == userId|| status==null) { result.setMsg(MessageResource.PARAMETERS_ERROR); throw new FunctionException(result, ""); } return sysUserResourcesDao.delSysUserResources(result, userId,status); } } */
UTF-8
Java
1,978
java
SysUserResourcesService.java
Java
[ { "context": "rcentre.util.MessageResource;\n*//**\n * \n * @author ds\n *\n *//*\n@Service\npublic class SysUserResourcesSe", "end": 453, "score": 0.9992853999137878, "start": 451, "tag": "USERNAME", "value": "ds" }, { "context": "erId\n\t * @return\n\t * @throws Exception\n\t * @author ds\n\t * @date 2017年2月8日\n\t * @version 3.1.0\n\t *//*\n\tpu", "end": 661, "score": 0.9991477131843567, "start": 659, "tag": "USERNAME", "value": "ds" } ]
null
[]
/*package com.fxb.world.service.sys; import java.util.ArrayList; import java.util.List; import javax.annotation.Resource; import org.springframework.stereotype.Service; import com.dtds.platform.util.bean.Result; import com.dtds.platform.util.exception.FunctionException; import com.tsh.usercentre.dao.SysUserResourcesDao; import com.tsh.usercentre.po.system.SysUserResourcesPo; import com.tsh.usercentre.util.MessageResource; *//** * * @author ds * *//* @Service public class SysUserResourcesService { @Resource SysUserResourcesDao sysUserResourcesDao; *//** * * @param result * @param userId * @return * @throws Exception * @author ds * @date 2017年2月8日 * @version 3.1.0 *//* public Result querySysUserResourcesByuserIdService(Result result, Long userId,Integer status) throws Exception { if (userId == null) { result.setMsg(MessageResource.PARAMETERS_ERROR); throw new FunctionException(result, ""); } List<Long> list=new ArrayList<Long>(); result=sysUserResourcesDao.querySysUserResourcesByUserId(result, userId,status); List<SysUserResourcesPo> suList = result.getData(); for (SysUserResourcesPo sysUserResourcesPo : suList) { list.add(sysUserResourcesPo.getResourcesId()); } result.setData(list); return result; } *//** * * @param result * @param poList * @return * @throws Exception *//* public Result saveSysUserResourcesListService(Result result, List<SysUserResourcesPo> poList) throws Exception { return sysUserResourcesDao.saveSysUserResourcesList(result, poList); } *//** * * @param result * @param userId * @return * @throws Exception *//* public Result delSysUserResourcesService(Result result, Long userId,Integer status) throws Exception { if (null == userId|| status==null) { result.setMsg(MessageResource.PARAMETERS_ERROR); throw new FunctionException(result, ""); } return sysUserResourcesDao.delSysUserResources(result, userId,status); } } */
1,978
0.737323
0.732759
77
24.623377
26.647793
113
false
false
0
0
0
0
0
0
1.441558
false
false
12
8e403f57372e0af32e0bad53f6e88ad474091bdd
15,204,184,253,978
53806da7a08120b0455a4e86966c3872bf9c8994
/src/main/java/com/soft/service/GoodsService.java
3818584ddbe330faf92fab5a4e2635fd3f4cec38
[]
no_license
diaomina/garbage-collection
https://github.com/diaomina/garbage-collection
196150d76a0bf5a94617bc3eb2e84e1d917a9864
08e8d868ced272167f88b6d8028a23e0746177f4
refs/heads/master
2022-12-11T04:05:01.557000
2021-12-14T08:28:01
2021-12-14T08:28:01
239,526,032
33
14
null
false
2022-11-16T08:26:21
2020-02-10T14:04:23
2022-10-15T02:09:34
2022-11-16T08:26:19
4,521
22
15
14
Java
false
false
package com.soft.service; import java.util.List; import com.soft.model.Goods; /** * * @ClassName: GoodsService * @Description: 商品的业务接口 * @author: ljy * @date: 2019年12月10日 下午5:51:46 */ public interface GoodsService { // 根据商品类型查找 List<Goods> getByGoodsType(Integer goodstype); // 根据id查找 Goods getById(Integer id); // 获取所有 List<Goods> getAll(); // 添加 int add(Goods goods); // 修改 int update(Goods goods); // 删除 int delete(Integer id); }
UTF-8
Java
532
java
GoodsService.java
Java
[ { "context": " GoodsService\n * @Description: 商品的业务接口\n * @author: ljy\n * @date: 2019年12月10日 下午5:51:46\n */\npublic interf", "end": 157, "score": 0.999653697013855, "start": 154, "tag": "USERNAME", "value": "ljy" } ]
null
[]
package com.soft.service; import java.util.List; import com.soft.model.Goods; /** * * @ClassName: GoodsService * @Description: 商品的业务接口 * @author: ljy * @date: 2019年12月10日 下午5:51:46 */ public interface GoodsService { // 根据商品类型查找 List<Goods> getByGoodsType(Integer goodstype); // 根据id查找 Goods getById(Integer id); // 获取所有 List<Goods> getAll(); // 添加 int add(Goods goods); // 修改 int update(Goods goods); // 删除 int delete(Integer id); }
532
0.670259
0.642241
34
12.647058
12.672069
47
false
false
0
0
0
0
0
0
0.676471
false
false
12
8ea426fb39688b0ca1996ba60e8f51436673f5b7
11,218,454,608,187
a1e30aa8e41a2303cf5fe28296a074410982b96b
/src/main/java/web/commands/EnkeltCarportCommand.java
83ccaf4dcc186fba2701206f46cc0449d1c99a06
[]
no_license
wehba-dotcom/Carport_exam
https://github.com/wehba-dotcom/Carport_exam
46698492b91dd4ca26d3423ce8c779143f68958b
337d59da0323e02ad0847824ab09446f63efc9a1
refs/heads/main
2023-05-13T06:08:58.946000
2021-05-27T10:56:06
2021-05-27T10:56:06
369,210,186
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package web.commands; public class EnkeltCarportCommand extends CommandUnprotectedPage{ public EnkeltCarportCommand(String pageToShow) { super(pageToShow); } }
UTF-8
Java
177
java
EnkeltCarportCommand.java
Java
[]
null
[]
package web.commands; public class EnkeltCarportCommand extends CommandUnprotectedPage{ public EnkeltCarportCommand(String pageToShow) { super(pageToShow); } }
177
0.762712
0.762712
7
24.285715
23.73493
65
false
false
0
0
0
0
0
0
0.285714
false
false
12
eb1f22174d63d1c851c17b1363e11e47a1532b45
27,874,337,774,467
62b36b279296d999fbab6df95309c05b45262f86
/plugins/gradle/src/org/jetbrains/plugins/gradle/config/GradleSettingsListenerAdapter.java
1ae90bc7b2f13c47659df64a87f4f4c90e4da947
[ "Apache-2.0" ]
permissive
huwensen/intellij-community
https://github.com/huwensen/intellij-community
2e84b5d447f0e8b227024190be5912b5feceec7c
abb490446a7f9abbc55f100b166cadee7dba60ae
refs/heads/master
2023-07-23T19:14:15.258000
2023-07-17T21:40:16
2023-07-18T02:33:37
201,616,287
1
0
Apache-2.0
true
2019-08-10T10:41:04
2019-08-10T10:41:03
2019-08-10T10:40:55
2019-08-09T22:01:05
3,208,375
0
0
0
null
false
false
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.plugins.gradle.config; import com.intellij.openapi.externalSystem.settings.ExternalSystemSettingsListener; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.plugins.gradle.settings.DistributionType; import org.jetbrains.plugins.gradle.settings.GradleProjectSettings; import org.jetbrains.plugins.gradle.settings.GradleSettingsListener; import org.jetbrains.plugins.gradle.settings.TestRunner; public abstract class GradleSettingsListenerAdapter implements ExternalSystemSettingsListener<GradleProjectSettings>, GradleSettingsListener { @Override public void onGradleHomeChange(@Nullable String oldPath, @Nullable String newPath, @NotNull String linkedProjectPath) { } @Override public void onGradleDistributionTypeChange(DistributionType currentValue, @NotNull String linkedProjectPath) { } @Override public void onServiceDirectoryPathChange(@Nullable String oldPath, @Nullable String newPath) { } @Override public void onGradleVmOptionsChange(@Nullable String oldOptions, @Nullable String newOptions) { } @Override public void onBuildDelegationChange(boolean delegatedBuild, @NotNull String linkedProjectPath) { } @Override public void onTestRunnerChange(@NotNull TestRunner currentTestRunner, @NotNull String linkedProjectPath) { } }
UTF-8
Java
1,541
java
GradleSettingsListenerAdapter.java
Java
[]
null
[]
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.plugins.gradle.config; import com.intellij.openapi.externalSystem.settings.ExternalSystemSettingsListener; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.plugins.gradle.settings.DistributionType; import org.jetbrains.plugins.gradle.settings.GradleProjectSettings; import org.jetbrains.plugins.gradle.settings.GradleSettingsListener; import org.jetbrains.plugins.gradle.settings.TestRunner; public abstract class GradleSettingsListenerAdapter implements ExternalSystemSettingsListener<GradleProjectSettings>, GradleSettingsListener { @Override public void onGradleHomeChange(@Nullable String oldPath, @Nullable String newPath, @NotNull String linkedProjectPath) { } @Override public void onGradleDistributionTypeChange(DistributionType currentValue, @NotNull String linkedProjectPath) { } @Override public void onServiceDirectoryPathChange(@Nullable String oldPath, @Nullable String newPath) { } @Override public void onGradleVmOptionsChange(@Nullable String oldOptions, @Nullable String newOptions) { } @Override public void onBuildDelegationChange(boolean delegatedBuild, @NotNull String linkedProjectPath) { } @Override public void onTestRunnerChange(@NotNull TestRunner currentTestRunner, @NotNull String linkedProjectPath) { } }
1,541
0.791045
0.784555
37
40.648647
43.726555
121
false
false
0
0
0
0
0
0
0.432432
false
false
12
4bed66e426cc4e6d988857382d6c47c2119c06e9
10,204,842,320,297
d73d2157c9c3b55cd42a6af08b1f2660a3e6a09d
/czic_exchangeRateSimulation/src/main/java/com/bbva/czic/exchangeratesimulation/facade/v01/impl/SrvExchangeRateSimulationV01.java
bd75128b3f3aa0ccb20381883a0355d76fc0828a
[]
no_license
fgparamio/soa-bbva-net
https://github.com/fgparamio/soa-bbva-net
9e7195ad1971279c9af6688782832663278fce60
fde84c94945063a5476718ddc61f23d782f78db7
refs/heads/master
2017-05-26T18:19:56.501000
2015-12-29T21:53:12
2015-12-29T21:53:12
27,878,707
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.bbva.czic.exchangeratesimulation.facade.v01.impl; import javax.annotation.Resource; import javax.ws.rs.Consumes; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.UriInfo; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.bbva.czic.dto.net.ExchangeRateSimulation; import com.bbva.czic.exchangeratesimulation.business.ISrvIntExchangeRateSimulation; import com.bbva.czic.exchangeratesimulation.business.dto.DTOIntExchangeRateSimulation; import com.bbva.czic.exchangeratesimulation.facade.v01.ISrvExchangeRateSimulationV01; import com.bbva.czic.exchangeratesimulation.facade.v01.mapper.IExchangeRateSimulationMapper; import com.bbva.jee.arq.spring.core.servicing.annotations.SMC; import com.bbva.jee.arq.spring.core.servicing.annotations.SN; import com.bbva.jee.arq.spring.core.servicing.annotations.VN; import com.bbva.jee.arq.spring.core.servicing.utils.BusinessServicesToolKit; import com.wordnik.swagger.annotations.Api; import com.wordnik.swagger.annotations.ApiOperation; import com.wordnik.swagger.annotations.ApiParam; import com.wordnik.swagger.annotations.ApiResponse; import com.wordnik.swagger.annotations.ApiResponses; @Path("/V01") @SN(registryID = "SN201500333", logicalID = "exchangeRateSimulation") @VN(vnn = "V01") @Api(value = "/exchangeRateSimulation/V01", description = "SN exchangeRateSimulation") @Produces({ MediaType.APPLICATION_JSON }) @Service public class SrvExchangeRateSimulationV01 implements ISrvExchangeRateSimulationV01, com.bbva.jee.arq.spring.core.servicing.utils.ContextAware { private static Log log = LogFactory.getLog(SrvExchangeRateSimulationV01.class); public HttpHeaders httpHeaders; @Autowired BusinessServicesToolKit bussinesToolKit; public UriInfo uriInfo; @Override public void setUriInfo(UriInfo ui) { this.uriInfo = ui; } @Override public void setHttpHeaders(HttpHeaders httpHeaders) { this.httpHeaders = httpHeaders; } @Resource(name = "exchangeRateSimulation-mapper") public IExchangeRateSimulationMapper exchangeRateMapper; @Autowired ISrvIntExchangeRateSimulation srvIntExchangeRateSimulation; @Override @ApiOperation(value = "Operación que obtiene las tasas vigentes en el momento o las tasas de un avance de operacion", notes = "Consulta de tasas", response = ExchangeRateSimulation.class) @ApiResponses(value = { @ApiResponse(code = -1, message = "aliasGCE1"), @ApiResponse(code = -1, message = "aliasGCE2"), @ApiResponse(code = 200, message = "Added Sucessfully", response = Response.class), @ApiResponse(code = 500, message = "Technical Error") }) @POST @Path("/{simulateId}") @Consumes({ MediaType.APPLICATION_JSON }) @SMC(registryID = "SMC201500334", logicalID = "getExchangeRateSimulation") public ExchangeRateSimulation getExchangeRateSimulation( @ApiParam(value = "Simulate identifier param") @PathParam("simulateId") String simulateId, @ApiParam(value = "exchangeRate information", required = true) ExchangeRateSimulation exchangeRateSimulation) { // 2. Mapping to DTOIntExchangeRateSimulation DTOIntExchangeRateSimulation dtoIntExchangeRate = exchangeRateMapper.map(exchangeRateSimulation); dtoIntExchangeRate.setId(simulateId); // 3. Invoke SrvIntAccounts and Mapping to canonical DTO DTOIntExchangeRateSimulation resultado = srvIntExchangeRateSimulation .getExchangeRateSimulation(dtoIntExchangeRate); return exchangeRateMapper.map(resultado); } }
UTF-8
Java
3,746
java
SrvExchangeRateSimulationV01.java
Java
[]
null
[]
package com.bbva.czic.exchangeratesimulation.facade.v01.impl; import javax.annotation.Resource; import javax.ws.rs.Consumes; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.UriInfo; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.bbva.czic.dto.net.ExchangeRateSimulation; import com.bbva.czic.exchangeratesimulation.business.ISrvIntExchangeRateSimulation; import com.bbva.czic.exchangeratesimulation.business.dto.DTOIntExchangeRateSimulation; import com.bbva.czic.exchangeratesimulation.facade.v01.ISrvExchangeRateSimulationV01; import com.bbva.czic.exchangeratesimulation.facade.v01.mapper.IExchangeRateSimulationMapper; import com.bbva.jee.arq.spring.core.servicing.annotations.SMC; import com.bbva.jee.arq.spring.core.servicing.annotations.SN; import com.bbva.jee.arq.spring.core.servicing.annotations.VN; import com.bbva.jee.arq.spring.core.servicing.utils.BusinessServicesToolKit; import com.wordnik.swagger.annotations.Api; import com.wordnik.swagger.annotations.ApiOperation; import com.wordnik.swagger.annotations.ApiParam; import com.wordnik.swagger.annotations.ApiResponse; import com.wordnik.swagger.annotations.ApiResponses; @Path("/V01") @SN(registryID = "SN201500333", logicalID = "exchangeRateSimulation") @VN(vnn = "V01") @Api(value = "/exchangeRateSimulation/V01", description = "SN exchangeRateSimulation") @Produces({ MediaType.APPLICATION_JSON }) @Service public class SrvExchangeRateSimulationV01 implements ISrvExchangeRateSimulationV01, com.bbva.jee.arq.spring.core.servicing.utils.ContextAware { private static Log log = LogFactory.getLog(SrvExchangeRateSimulationV01.class); public HttpHeaders httpHeaders; @Autowired BusinessServicesToolKit bussinesToolKit; public UriInfo uriInfo; @Override public void setUriInfo(UriInfo ui) { this.uriInfo = ui; } @Override public void setHttpHeaders(HttpHeaders httpHeaders) { this.httpHeaders = httpHeaders; } @Resource(name = "exchangeRateSimulation-mapper") public IExchangeRateSimulationMapper exchangeRateMapper; @Autowired ISrvIntExchangeRateSimulation srvIntExchangeRateSimulation; @Override @ApiOperation(value = "Operación que obtiene las tasas vigentes en el momento o las tasas de un avance de operacion", notes = "Consulta de tasas", response = ExchangeRateSimulation.class) @ApiResponses(value = { @ApiResponse(code = -1, message = "aliasGCE1"), @ApiResponse(code = -1, message = "aliasGCE2"), @ApiResponse(code = 200, message = "Added Sucessfully", response = Response.class), @ApiResponse(code = 500, message = "Technical Error") }) @POST @Path("/{simulateId}") @Consumes({ MediaType.APPLICATION_JSON }) @SMC(registryID = "SMC201500334", logicalID = "getExchangeRateSimulation") public ExchangeRateSimulation getExchangeRateSimulation( @ApiParam(value = "Simulate identifier param") @PathParam("simulateId") String simulateId, @ApiParam(value = "exchangeRate information", required = true) ExchangeRateSimulation exchangeRateSimulation) { // 2. Mapping to DTOIntExchangeRateSimulation DTOIntExchangeRateSimulation dtoIntExchangeRate = exchangeRateMapper.map(exchangeRateSimulation); dtoIntExchangeRate.setId(simulateId); // 3. Invoke SrvIntAccounts and Mapping to canonical DTO DTOIntExchangeRateSimulation resultado = srvIntExchangeRateSimulation .getExchangeRateSimulation(dtoIntExchangeRate); return exchangeRateMapper.map(resultado); } }
3,746
0.809079
0.795728
91
40.153847
33.311687
188
false
false
0
0
0
0
0
0
1.296703
false
false
12
9ace7e62dad5413886b9ad882e2093e7c84ec209
26,061,861,578,712
d68b7352852928c4a1f816bf8d7250246b06a084
/src/main/java/org/rythmengine/spring/web/result/Forbidden.java
6ed65c16762e941f6243753afa2f20dc69d0f136
[ "Apache-2.0" ]
permissive
greenlaw110/spring-rythm
https://github.com/greenlaw110/spring-rythm
8b430bda036e91256f354ff818c596476aed422b
a654016371c72dabaea50ac9a57626da7614d236
refs/heads/master
2021-01-02T08:45:39.376000
2017-08-29T07:38:47
2017-08-29T07:38:47
10,471,083
1
6
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.rythmengine.spring.web.result; import org.springframework.http.HttpStatus; /** * Created by luog on 30/12/13. */ public class Forbidden extends Result { /** * @param why a description of the problem */ public Forbidden(String why) { super(HttpStatus.FORBIDDEN, why); } public Forbidden() { super(HttpStatus.FORBIDDEN); } }
UTF-8
Java
388
java
Forbidden.java
Java
[ { "context": "pringframework.http.HttpStatus;\n\n/**\n * Created by luog on 30/12/13.\n */\npublic class Forbidden extends R", "end": 111, "score": 0.9996294975280762, "start": 107, "tag": "USERNAME", "value": "luog" } ]
null
[]
package org.rythmengine.spring.web.result; import org.springframework.http.HttpStatus; /** * Created by luog on 30/12/13. */ public class Forbidden extends Result { /** * @param why a description of the problem */ public Forbidden(String why) { super(HttpStatus.FORBIDDEN, why); } public Forbidden() { super(HttpStatus.FORBIDDEN); } }
388
0.64433
0.628866
21
17.476191
17.826195
46
false
false
0
0
0
0
0
0
0.238095
false
false
12
ba9710ec55cfe179b12a936e194a62594674867b
12,498,354,863,364
198a464a04eb1fdec50cba469dc0db31a66d7684
/Clash of Foods/src/Model/Entry.java
5fb84846564420b6e2529ccae798ee3acfd03338
[]
no_license
noreebia/university-projects
https://github.com/noreebia/university-projects
07d75e461c0ad218c5383290fe9e953544bd8160
6615c403a79b6eb981d9fbae749a8772bd4d68ed
refs/heads/master
2021-01-18T16:45:50.796000
2017-12-27T05:40:36
2017-12-27T05:40:36
34,984,615
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 Model; /** * * @author 이상명'spc */ public class Entry { private int key; private Object obj; public Entry(int key,Object obj){ this.key = key; this.obj = obj; } public Entry(){ } public int getKey(){ return this.key; } public Object getObj(){ return this.obj; } public String toString(){ return "{"+key+","+obj.toString()+"}"; } }
UTF-8
Java
570
java
Entry.java
Java
[ { "context": "the editor.\n */\n\npackage Model;\n\n/**\n *\n * @author 이상명'spc\n */\npublic class Entry {\n\tprivate int key;\n\tp", "end": 223, "score": 0.7545387744903564, "start": 220, "tag": "NAME", "value": "이상명" }, { "context": "editor.\n */\n\npackage Model;\n\n/**\n *\n * @author 이상명'spc\n */\npublic class Entry {\n\tprivate int key;\n\tpriva", "end": 227, "score": 0.8532934188842773, "start": 224, "tag": "USERNAME", "value": "spc" } ]
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 Model; /** * * @author 이상명'spc */ public class Entry { private int key; private Object obj; public Entry(int key,Object obj){ this.key = key; this.obj = obj; } public Entry(){ } public int getKey(){ return this.key; } public Object getObj(){ return this.obj; } public String toString(){ return "{"+key+","+obj.toString()+"}"; } }
570
0.641844
0.641844
37
14.216216
17.350342
79
false
false
0
0
0
0
0
0
1.135135
false
false
12
23f227fbc49ca1e985a9e45dad1fc7dd3a4f6d16
21,320,217,665,831
40b30056d677f201253f5317df08397d63b28676
/backend/src/main/java/com/example/cinema/cinemabookingsystem/blservice/coupon/CouponBlService.java
6820472f2077c0212995da7658da342ba8099512
[]
no_license
Green-Wood/CinemaBookingSystem
https://github.com/Green-Wood/CinemaBookingSystem
6f7f20610ad11bcb35b443a0d36bff2885a3c25d
361ebd0224a914449c1d03ca2bfd723b4542495f
refs/heads/master
2020-04-29T13:57:35.221000
2019-09-27T14:05:17
2019-09-27T14:05:17
176,182,748
6
2
null
false
2020-09-04T15:19:21
2019-03-18T01:24:22
2020-06-28T13:42:42
2020-09-04T15:19:19
6,646
8
1
1
HTML
false
false
package com.example.cinema.cinemabookingsystem.blservice.coupon; import com.example.cinema.cinemabookingsystem.parameter.coupon.InsertCouponParameter; import com.example.cinema.cinemabookingsystem.response.coupon.GetAllCouponsResponse; import com.example.cinema.cinemabookingsystem.response.coupon.GetCouponByIdResponse; import com.example.cinema.cinemabookingsystem.response.coupon.GetCouponsByUserIdResponse; import com.example.cinema.cinemabookingsystem.response.coupon.InsertCouponResponse; /** * @author mars */ public interface CouponBlService { /** * 根据用户id来查询优惠券 * @param userId * @return */ GetCouponsByUserIdResponse getCouponsByUser(int userId); /** * 增加一种类型的优惠券 * @param couponParameter * @return */ InsertCouponResponse addCoupon(InsertCouponParameter couponParameter); /** * 通过id得到优惠券 * @param couponId * @return */ GetCouponByIdResponse getCouponById(int couponId); /** * * @return */ GetAllCouponsResponse getAllCoupons(); }
UTF-8
Java
1,109
java
CouponBlService.java
Java
[ { "context": "ponse.coupon.InsertCouponResponse;\n\n/**\n * @author mars\n */\npublic interface CouponBlService {\n /**\n ", "end": 516, "score": 0.9981118440628052, "start": 512, "tag": "USERNAME", "value": "mars" } ]
null
[]
package com.example.cinema.cinemabookingsystem.blservice.coupon; import com.example.cinema.cinemabookingsystem.parameter.coupon.InsertCouponParameter; import com.example.cinema.cinemabookingsystem.response.coupon.GetAllCouponsResponse; import com.example.cinema.cinemabookingsystem.response.coupon.GetCouponByIdResponse; import com.example.cinema.cinemabookingsystem.response.coupon.GetCouponsByUserIdResponse; import com.example.cinema.cinemabookingsystem.response.coupon.InsertCouponResponse; /** * @author mars */ public interface CouponBlService { /** * 根据用户id来查询优惠券 * @param userId * @return */ GetCouponsByUserIdResponse getCouponsByUser(int userId); /** * 增加一种类型的优惠券 * @param couponParameter * @return */ InsertCouponResponse addCoupon(InsertCouponParameter couponParameter); /** * 通过id得到优惠券 * @param couponId * @return */ GetCouponByIdResponse getCouponById(int couponId); /** * * @return */ GetAllCouponsResponse getAllCoupons(); }
1,109
0.735545
0.735545
39
26.051283
28.988901
89
false
false
0
0
0
0
0
0
0.25641
false
false
12
1080a4f1bbe5cace327f224286a96a4fd801746c
25,821,343,383,944
fbaf5900d7915b9de7f447b1fcb2db625f0e0161
/src/main/java/apple/AppleClassifier.java
6ace3a273493c6b16f00f02e19abe8e570e0a9ec
[]
no_license
river923/java9
https://github.com/river923/java9
77501ccbe61a332d3a4906ebc9097d6a81c49a4e
642c0795409d45e1a35f15aa3bc1a8cad4ba2b40
refs/heads/master
2023-07-28T06:04:42.079000
2021-09-03T08:15:27
2021-09-03T08:15:27
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package apple; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.function.Predicate; public class AppleClassifier { // filtering, mapping, reducing public static void main(String[] args) { List<Apple> apples = Arrays.asList( new Apple(250, "green"), new Apple(350, "red"), new Apple(550, "green"), new Apple(150, "red"), new Apple(450, "green"), new Apple(250, "green"), new Apple(550, "red") ); // 1. 300 그램 이상인 사과를 필터링 // List<Apple> appleOver300 = new ArrayList<>(); // for (Apple apple : apples) { // if (apple.getWeight() > 300) { // appleOver300.add(apple); // } // } Predicate<Apple> condition = a -> a.getColor().equals("red") && a.getWeight() > 300; List<Apple> filterApples = filterApples(apples, apple -> apple.getWeight() > 300); System.out.println(); } public static List<Apple> filterApples(List<Apple> inventory, Predicate<Apple> predicate) { List<Apple> newList = new ArrayList<>(); for (Apple apple : inventory) { if (predicate.test(apple)) { newList.add(apple); } } return newList; } }
UTF-8
Java
1,389
java
AppleClassifier.java
Java
[]
null
[]
package apple; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.function.Predicate; public class AppleClassifier { // filtering, mapping, reducing public static void main(String[] args) { List<Apple> apples = Arrays.asList( new Apple(250, "green"), new Apple(350, "red"), new Apple(550, "green"), new Apple(150, "red"), new Apple(450, "green"), new Apple(250, "green"), new Apple(550, "red") ); // 1. 300 그램 이상인 사과를 필터링 // List<Apple> appleOver300 = new ArrayList<>(); // for (Apple apple : apples) { // if (apple.getWeight() > 300) { // appleOver300.add(apple); // } // } Predicate<Apple> condition = a -> a.getColor().equals("red") && a.getWeight() > 300; List<Apple> filterApples = filterApples(apples, apple -> apple.getWeight() > 300); System.out.println(); } public static List<Apple> filterApples(List<Apple> inventory, Predicate<Apple> predicate) { List<Apple> newList = new ArrayList<>(); for (Apple apple : inventory) { if (predicate.test(apple)) { newList.add(apple); } } return newList; } }
1,389
0.531821
0.50256
48
27.479166
23.783739
95
false
false
0
0
0
0
0
0
0.645833
false
false
12
9973d90c4ba115e41bb2cf8e6c988e169588d864
2,602,750,236,115
6f259707b4b88d3d2a85fb8d1e92c99537989326
/src/main/java/br/com/web/model/client/StatusTypeResponseList.java
b60a2ff20d713362d0b68320286a41185ff28d0b
[]
no_license
mhtoyoda/invviteMe-web
https://github.com/mhtoyoda/invviteMe-web
27b6dd9c33b1c6dbfde04803b8582eb8887745bf
56b07b7bccb5c477dd09285fbd8673ed5d29efa9
refs/heads/master
2021-01-17T12:38:57.566000
2016-06-14T02:39:21
2016-06-14T02:39:21
59,716,339
0
1
null
false
2016-06-09T02:29:25
2016-05-26T03:20:42
2016-05-29T03:20:41
2016-06-09T02:29:24
2,735
0
1
0
HTML
null
null
package br.com.web.model.client; import java.util.List; public class StatusTypeResponseList { private List<StatusType> statusTypes; private Message message; public List<StatusType> getStatusTypes() { return statusTypes; } public void setStatusTypes(List<StatusType> statusTypes) { this.statusTypes = statusTypes; } public Message getMessage() { return message; } public void setMessage(Message message) { this.message = message; } }
UTF-8
Java
457
java
StatusTypeResponseList.java
Java
[]
null
[]
package br.com.web.model.client; import java.util.List; public class StatusTypeResponseList { private List<StatusType> statusTypes; private Message message; public List<StatusType> getStatusTypes() { return statusTypes; } public void setStatusTypes(List<StatusType> statusTypes) { this.statusTypes = statusTypes; } public Message getMessage() { return message; } public void setMessage(Message message) { this.message = message; } }
457
0.752735
0.752735
25
17.32
17.778009
59
false
false
0
0
0
0
0
0
1.04
false
false
12
8769ba6adeab06585b158e4b3f5b9c89c5d0e9ef
4,964,982,203,865
2136b014aa51acff8c6fd6d9a985a1866239b35a
/app/src/main/java/com/mohammadkiani/androidroomdbdemo/model/Employee.java
cfb203029aafb0e8f0f4bf45fd343ae8db77f480
[]
no_license
GurjeetC0817568/AndroidRoomDBDemo
https://github.com/GurjeetC0817568/AndroidRoomDBDemo
a2bacadbd24e51e1bd3fcc2ecea687a4713415b3
b5c4d5e3333726fc8c3ba9426b266af54d28b9d6
refs/heads/master
2023-08-22T05:20:06.016000
2021-10-12T14:58:23
2021-10-12T14:58:23
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.mohammadkiani.androidroomdbdemo.model; import androidx.annotation.NonNull; import androidx.room.ColumnInfo; import androidx.room.Entity; import androidx.room.ForeignKey; import androidx.room.Ignore; import androidx.room.PrimaryKey; import static androidx.room.ForeignKey.CASCADE; import static androidx.room.ForeignKey.NO_ACTION; // this is our entity in Room db @Entity( tableName = "employee_table", foreignKeys = @ForeignKey(entity = Department.class, parentColumns = "dept_id", childColumns = "department_id", onDelete = CASCADE, onUpdate = NO_ACTION) ) public class Employee { @PrimaryKey(autoGenerate = true) @ColumnInfo(name = "id") private long id; @ColumnInfo(name = "department_id") private long departmentId; @ColumnInfo(name = "name") @NonNull private String name; @ColumnInfo(name = "department") private String departmentName; @ColumnInfo(name = "joining_date") private String joiningDate; @ColumnInfo(name = "salary") private double salary; private String contract; @Ignore public Employee() { } public Employee(@NonNull String name, String departmentName, String joiningDate, double salary, String contract) { this.name = name; this.departmentName = departmentName; this.joiningDate = joiningDate; this.salary = salary; this.contract = contract; } public long getId() { return id; } public void setId(long id) { this.id = id; } @NonNull public String getName() { return name; } public void setName(@NonNull String name) { this.name = name; } public String getDepartmentName() { return departmentName; } public void setDepartmentName(String departmentName) { this.departmentName = departmentName; } public String getJoiningDate() { return joiningDate; } public void setJoiningDate(String joiningDate) { this.joiningDate = joiningDate; } public double getSalary() { return salary; } public void setSalary(double salary) { this.salary = salary; } public long getDepartmentId() { return departmentId; } public void setDepartmentId(long departmentId) { this.departmentId = departmentId; } public String getContract() { return contract; } public void setContract(String contract) { this.contract = contract; } public enum Contract { FULL_TIME, PART_TIME } }
UTF-8
Java
2,618
java
Employee.java
Java
[ { "context": "package com.mohammadkiani.androidroomdbdemo.model;\n\nimport androidx.an", "end": 20, "score": 0.5685655474662781, "start": 17, "tag": "USERNAME", "value": "mad" }, { "context": "package com.mohammadkiani.androidroomdbdemo.model;\n\nimport androidx.annotat", "end": 25, "score": 0.7595380544662476, "start": 21, "tag": "USERNAME", "value": "iani" } ]
null
[]
package com.mohammadkiani.androidroomdbdemo.model; import androidx.annotation.NonNull; import androidx.room.ColumnInfo; import androidx.room.Entity; import androidx.room.ForeignKey; import androidx.room.Ignore; import androidx.room.PrimaryKey; import static androidx.room.ForeignKey.CASCADE; import static androidx.room.ForeignKey.NO_ACTION; // this is our entity in Room db @Entity( tableName = "employee_table", foreignKeys = @ForeignKey(entity = Department.class, parentColumns = "dept_id", childColumns = "department_id", onDelete = CASCADE, onUpdate = NO_ACTION) ) public class Employee { @PrimaryKey(autoGenerate = true) @ColumnInfo(name = "id") private long id; @ColumnInfo(name = "department_id") private long departmentId; @ColumnInfo(name = "name") @NonNull private String name; @ColumnInfo(name = "department") private String departmentName; @ColumnInfo(name = "joining_date") private String joiningDate; @ColumnInfo(name = "salary") private double salary; private String contract; @Ignore public Employee() { } public Employee(@NonNull String name, String departmentName, String joiningDate, double salary, String contract) { this.name = name; this.departmentName = departmentName; this.joiningDate = joiningDate; this.salary = salary; this.contract = contract; } public long getId() { return id; } public void setId(long id) { this.id = id; } @NonNull public String getName() { return name; } public void setName(@NonNull String name) { this.name = name; } public String getDepartmentName() { return departmentName; } public void setDepartmentName(String departmentName) { this.departmentName = departmentName; } public String getJoiningDate() { return joiningDate; } public void setJoiningDate(String joiningDate) { this.joiningDate = joiningDate; } public double getSalary() { return salary; } public void setSalary(double salary) { this.salary = salary; } public long getDepartmentId() { return departmentId; } public void setDepartmentId(long departmentId) { this.departmentId = departmentId; } public String getContract() { return contract; } public void setContract(String contract) { this.contract = contract; } public enum Contract { FULL_TIME, PART_TIME } }
2,618
0.646677
0.646677
117
21.376068
19.121174
118
false
false
0
0
0
0
0
0
0.384615
false
false
12
9b96ec52d934cbb147f515f6bc25ade67c7aeefa
7,078,106,168,521
307a9fdafcbe25fa67743a3c6eb630217b57bc1d
/JavaProject/src/hashmap/HashMapDemo.java
b3f2b0de9112e710a58ba2bc9b21adc518abb2ff
[]
no_license
srathore2/java_project
https://github.com/srathore2/java_project
b0b0be5f76375114cea055108600c7f8469ae18e
c426ba7b0ae5c4f4bf7692dfb6cfca8cf0878eaa
refs/heads/master
2023-05-23T14:04:52.046000
2021-06-14T10:20:11
2021-06-14T10:20:11
260,198,007
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package hashmap; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Set; import hashmap.*; public class HashMapDemo { public static void main(String[] args) { Map<String,Emp>hm=new HashMap<String,Emp>(); hm.put("one", new Emp(100, "ram", "setu")); hm.put("Two", new Emp(111, "ram", "setu")); hm.put("Ttree", new Emp(110, "rama", "sattu")); //hm.put(null, new Emp(112, "ram", "setuunul")); //hm.put(null, null); Set<String>key=hm.keySet(); Iterator<String>itr=key.iterator(); // in one line //Iterator itr2=hm.keySet().iterator();--getting error for duplicate ,unknown source // Iterator<String>itr2=hm.keySet().iterator();--same error for this also while(itr.hasNext()){ //take key String st=itr.next(); Emp e1=hm.get(st); System.out.println(e1); } System.out.println("2nd map"); Map<String,Emp>hm1=new HashMap<String,Emp>(); hm1.put("four", new Emp(112, "sam", "setu")); Set<String>key1=hm1.keySet(); Iterator<String>itr1=key1.iterator(); while(itr1.hasNext()){ //take key String st=itr1.next(); System.out.println("string"+st); Emp e2=hm1.get(st); System.out.println(e2); } System.out.println("swap maps"); Map<String,Emp>hm3=new HashMap<String,Emp>(); hm3=hm1; hm1=hm; hm=hm3; System.out.println("map 1"); Set<String>key2=hm.keySet(); Iterator<String>itr2=key2.iterator(); while(itr2.hasNext()){ //take key String st=itr2.next(); Emp e1=hm.get(st); System.out.println(e1); } System.out.println("map 2"); Set<String>key3=hm1.keySet(); Iterator<String>itr3=key3.iterator(); while(itr3.hasNext()){ //take key String st=itr3.next(); Emp e2=hm1.get(st); System.out.println(e2); } /* System.out.println("##############Key Set For each loop################"); // for each loop for(Object keys:hm.keySet()){ System.out.println(hm.get(keys)); } System.out.println("#####EntrySet###########3"); Set<Map.Entry<String, Emp>> set=hm.entrySet(); Iterator<Map.Entry<String, Emp>>itr3=set.iterator(); while(itr3.hasNext()){ Map.Entry<String,Emp> keyvalue=itr3.next(); System.out.println("key"+keyvalue.getKey()+"value"+keyvalue.getValue()); } System.out.println("##########try in one line########### "); Iterator itr4 = hm.entrySet().iterator(); while(itr4.hasNext()){ Map.Entry<String,Emp> keyvalue=(Map.Entry) itr4.next(); System.out.println("key"+keyvalue.getKey()+"value"+keyvalue.getValue()); } System.out.println("#########for each entry set#######"); for(Map.Entry<String, Emp> entry:hm.entrySet()){ System.out.println("key"+entry.getKey()+"value"+entry.getValue()); } System.out.println("##########general map exercise#####"); System.out.println(hm.size()); */ } }
UTF-8
Java
2,911
java
HashMapDemo.java
Java
[ { "context": "hMap<String,Emp>();\n\t\thm.put(\"one\", new Emp(100, \"ram\", \"setu\"));\n\t\thm.put(\"Two\", new Emp(111, \"ram\", \"", "end": 286, "score": 0.9996410608291626, "start": 283, "tag": "NAME", "value": "ram" }, { "context": "ring,Emp>();\n\t\thm.put(\"one\", new Emp(100, \"ram\", \"setu\"));\n\t\thm.put(\"Two\", new Emp(111, \"ram\", \"setu\"));", "end": 294, "score": 0.9981904029846191, "start": 290, "tag": "NAME", "value": "setu" }, { "context": "0, \"ram\", \"setu\"));\n\t\thm.put(\"Two\", new Emp(111, \"ram\", \"setu\"));\n\t\thm.put(\"Ttree\", new Emp(110, \"rama\"", "end": 332, "score": 0.999648928642273, "start": 329, "tag": "NAME", "value": "ram" }, { "context": "\", \"setu\"));\n\t\thm.put(\"Two\", new Emp(111, \"ram\", \"setu\"));\n\t\thm.put(\"Ttree\", new Emp(110, \"rama\", \"sattu", "end": 340, "score": 0.99824458360672, "start": 336, "tag": "NAME", "value": "setu" }, { "context": " \"ram\", \"setu\"));\n\t\thm.put(\"Ttree\", new Emp(110, \"rama\", \"sattu\"));\n\t\t//hm.put(null, new Emp(112, \"ram\",", "end": 381, "score": 0.9992899894714355, "start": 377, "tag": "NAME", "value": "rama" }, { "context": "\"setu\"));\n\t\thm.put(\"Ttree\", new Emp(110, \"rama\", \"sattu\"));\n\t\t//hm.put(null, new Emp(112, \"ram\", \"setuunu", "end": 390, "score": 0.9986090064048767, "start": 385, "tag": "NAME", "value": "sattu" }, { "context": "\"rama\", \"sattu\"));\n\t\t//hm.put(null, new Emp(112, \"ram\", \"setuunul\"));\n\t\t//hm.put(null, null);\n\t\t \n\t\t Se", "end": 429, "score": 0.9996048808097839, "start": 426, "tag": "NAME", "value": "ram" }, { "context": " \"sattu\"));\n\t\t//hm.put(null, new Emp(112, \"ram\", \"setuunul\"));\n\t\t//hm.put(null, null);\n\t\t \n\t\t Set<String>key", "end": 441, "score": 0.9989206194877625, "start": 433, "tag": "NAME", "value": "setuunul" }, { "context": "p<String,Emp>();\n\t\t\thm1.put(\"four\", new Emp(112, \"sam\", \"setu\"));\n\t\t\t Set<String>key1=hm1.keySet();\n\t\t\t", "end": 971, "score": 0.9996772408485413, "start": 968, "tag": "NAME", "value": "sam" }, { "context": "g,Emp>();\n\t\t\thm1.put(\"four\", new Emp(112, \"sam\", \"setu\"));\n\t\t\t Set<String>key1=hm1.keySet();\n\t\t\t Iterato", "end": 979, "score": 0.9986655712127686, "start": 975, "tag": "NAME", "value": "setu" } ]
null
[]
package hashmap; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Set; import hashmap.*; public class HashMapDemo { public static void main(String[] args) { Map<String,Emp>hm=new HashMap<String,Emp>(); hm.put("one", new Emp(100, "ram", "setu")); hm.put("Two", new Emp(111, "ram", "setu")); hm.put("Ttree", new Emp(110, "rama", "sattu")); //hm.put(null, new Emp(112, "ram", "setuunul")); //hm.put(null, null); Set<String>key=hm.keySet(); Iterator<String>itr=key.iterator(); // in one line //Iterator itr2=hm.keySet().iterator();--getting error for duplicate ,unknown source // Iterator<String>itr2=hm.keySet().iterator();--same error for this also while(itr.hasNext()){ //take key String st=itr.next(); Emp e1=hm.get(st); System.out.println(e1); } System.out.println("2nd map"); Map<String,Emp>hm1=new HashMap<String,Emp>(); hm1.put("four", new Emp(112, "sam", "setu")); Set<String>key1=hm1.keySet(); Iterator<String>itr1=key1.iterator(); while(itr1.hasNext()){ //take key String st=itr1.next(); System.out.println("string"+st); Emp e2=hm1.get(st); System.out.println(e2); } System.out.println("swap maps"); Map<String,Emp>hm3=new HashMap<String,Emp>(); hm3=hm1; hm1=hm; hm=hm3; System.out.println("map 1"); Set<String>key2=hm.keySet(); Iterator<String>itr2=key2.iterator(); while(itr2.hasNext()){ //take key String st=itr2.next(); Emp e1=hm.get(st); System.out.println(e1); } System.out.println("map 2"); Set<String>key3=hm1.keySet(); Iterator<String>itr3=key3.iterator(); while(itr3.hasNext()){ //take key String st=itr3.next(); Emp e2=hm1.get(st); System.out.println(e2); } /* System.out.println("##############Key Set For each loop################"); // for each loop for(Object keys:hm.keySet()){ System.out.println(hm.get(keys)); } System.out.println("#####EntrySet###########3"); Set<Map.Entry<String, Emp>> set=hm.entrySet(); Iterator<Map.Entry<String, Emp>>itr3=set.iterator(); while(itr3.hasNext()){ Map.Entry<String,Emp> keyvalue=itr3.next(); System.out.println("key"+keyvalue.getKey()+"value"+keyvalue.getValue()); } System.out.println("##########try in one line########### "); Iterator itr4 = hm.entrySet().iterator(); while(itr4.hasNext()){ Map.Entry<String,Emp> keyvalue=(Map.Entry) itr4.next(); System.out.println("key"+keyvalue.getKey()+"value"+keyvalue.getValue()); } System.out.println("#########for each entry set#######"); for(Map.Entry<String, Emp> entry:hm.entrySet()){ System.out.println("key"+entry.getKey()+"value"+entry.getValue()); } System.out.println("##########general map exercise#####"); System.out.println(hm.size()); */ } }
2,911
0.605977
0.585022
100
28.110001
20.864273
87
false
false
0
0
0
0
0
0
3.17
false
false
12
71bfd9f54d6515d89ca97708dc8127af4714beef
4,776,003,701,509
d595a480be2f25d02af78ee7f2e2be4c8885c8c3
/RPGTextOO/src/model/Healing.java
5138d661a8deea97514ab3b9129c6a9d1840a8cc
[]
no_license
ClementInfoDUT/RPGtextOO
https://github.com/ClementInfoDUT/RPGtextOO
7ba3fa492cc6fa1b8d7a43aff2d600f2c0632dc5
65344bec194453296f98f7a3ae0a34d7b5025d38
refs/heads/main
2023-04-26T07:37:09.034000
2021-06-04T16:51:11
2021-06-04T16:51:11
358,179,911
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package model; public class Healing extends Item{ private int heal; private boolean used = false; public Healing(String name, int heal) { super(name); this.setHeal(heal); } public int getHeal() { return heal; } public void setHeal(int heal) { this.heal = heal; } public boolean isUsed() { return used; } public void setUsed(boolean used) { this.used = used; } }
UTF-8
Java
396
java
Healing.java
Java
[]
null
[]
package model; public class Healing extends Item{ private int heal; private boolean used = false; public Healing(String name, int heal) { super(name); this.setHeal(heal); } public int getHeal() { return heal; } public void setHeal(int heal) { this.heal = heal; } public boolean isUsed() { return used; } public void setUsed(boolean used) { this.used = used; } }
396
0.664141
0.664141
29
12.655172
12.9089
40
false
false
0
0
0
0
0
0
1.241379
false
false
12
bf4c6b1d92266d0d4d666012cb75d79eae6f5e3c
12,146,167,532,325
0068b1dd300f7cdd9d691d338a5472664f036e51
/app/src/main/java/br/com/codinglab/abasteca/activities/LoginActivity.java
55ca42030d0f4d2f94a6f59dfd9682c3cbae8904
[]
no_license
grascovit/abasteca-app
https://github.com/grascovit/abasteca-app
2d4351e7026fc6357354591c7e2ef2ff8785ab4a
31ebde9dd42ebb24077494eb56129a17fbb03578
refs/heads/master
2016-05-05T22:20:54.213000
2016-05-04T16:23:18
2016-05-04T16:23:18
55,791,154
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package br.com.codinglab.abasteca.activities; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.support.design.widget.Snackbar; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.EditText; import java.util.UUID; import br.com.codinglab.abasteca.R; import br.com.codinglab.abasteca.apiservices.SessionService; import br.com.codinglab.abasteca.models.Session; import br.com.codinglab.abasteca.requests.RestApiClient; import br.com.codinglab.abasteca.services.EmailSenderService; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; public class LoginActivity extends AppCompatActivity { @BindView(R.id.editTextEmail) EditText editTextEmail; @BindView(R.id.editTextPassword) EditText editTextPassword; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); ButterKnife.bind(this); } @OnClick(R.id.buttonLogin) void loginUser(final View view) { String email = editTextEmail.getText().toString(); String password = editTextPassword.getText().toString(); if (email.isEmpty() || password.isEmpty()) { Snackbar.make(view, "Há campos que não foram preenchidos. Tente novamente", Snackbar.LENGTH_SHORT).show(); } else { Session login = new Session(editTextEmail.getText().toString(), editTextPassword.getText().toString()); Call<Session> loginCall = RestApiClient.createService(SessionService.class).createSession(login); loginCall.enqueue(new Callback<Session>() { String message; @Override public void onResponse(Call<Session> call, Response<Session> response) { if (response.code() == 200) { Intent intent = new Intent(LoginActivity.this, MainActivity.class); intent.putExtra("userId", response.body().getId()); intent.putExtra("authenticationToken", response.body().getAuthenticationToken()); LoginActivity.this.startActivity(intent); } else if (response.code() == 422) { message = "O email ou senha informados estão incorretos"; } else { message = "Houve um erro ao comunicar com o servidor. Tente novamente"; } if (message != null) { Snackbar.make(view, message, Snackbar.LENGTH_SHORT).show(); } } @Override public void onFailure(Call<Session> call, Throwable t) { Snackbar.make(view, "Houve um erro ao comunicar com o servidor. Tente novamente", Snackbar.LENGTH_SHORT).show(); } }); } } @OnClick(R.id.buttonOpenRegisterForm) void openRegisterForm() { Intent intent = new Intent(this, RegisterActivity.class); startActivity(intent); } @OnClick(R.id.textViewForgotPassword) void openForgotPasswordForm() { final View dialogView = getLayoutInflater().inflate(R.layout.dialog_forgot_password, null); final EditText editTextEmailForgotPassword = ButterKnife.findById(dialogView, R.id.editTextEmailForgotPassword); new AlertDialog.Builder(this) .setTitle("Esqueci minha senha") .setMessage("Informe seu email abaixo e lhe enviaremos uma nova senha") .setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { String emailAddress = editTextEmailForgotPassword.getText().toString(); new EmailSenderService(LoginActivity.this).execute(emailAddress, "Recuperar senha", "A sua nova senha é " + UUID.randomUUID()); } }) .setNegativeButton("Cancelar", null) .setView(dialogView) .create() .show(); } }
UTF-8
Java
4,402
java
LoginActivity.java
Java
[]
null
[]
package br.com.codinglab.abasteca.activities; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.support.design.widget.Snackbar; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.EditText; import java.util.UUID; import br.com.codinglab.abasteca.R; import br.com.codinglab.abasteca.apiservices.SessionService; import br.com.codinglab.abasteca.models.Session; import br.com.codinglab.abasteca.requests.RestApiClient; import br.com.codinglab.abasteca.services.EmailSenderService; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; public class LoginActivity extends AppCompatActivity { @BindView(R.id.editTextEmail) EditText editTextEmail; @BindView(R.id.editTextPassword) EditText editTextPassword; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); ButterKnife.bind(this); } @OnClick(R.id.buttonLogin) void loginUser(final View view) { String email = editTextEmail.getText().toString(); String password = editTextPassword.getText().toString(); if (email.isEmpty() || password.isEmpty()) { Snackbar.make(view, "Há campos que não foram preenchidos. Tente novamente", Snackbar.LENGTH_SHORT).show(); } else { Session login = new Session(editTextEmail.getText().toString(), editTextPassword.getText().toString()); Call<Session> loginCall = RestApiClient.createService(SessionService.class).createSession(login); loginCall.enqueue(new Callback<Session>() { String message; @Override public void onResponse(Call<Session> call, Response<Session> response) { if (response.code() == 200) { Intent intent = new Intent(LoginActivity.this, MainActivity.class); intent.putExtra("userId", response.body().getId()); intent.putExtra("authenticationToken", response.body().getAuthenticationToken()); LoginActivity.this.startActivity(intent); } else if (response.code() == 422) { message = "O email ou senha informados estão incorretos"; } else { message = "Houve um erro ao comunicar com o servidor. Tente novamente"; } if (message != null) { Snackbar.make(view, message, Snackbar.LENGTH_SHORT).show(); } } @Override public void onFailure(Call<Session> call, Throwable t) { Snackbar.make(view, "Houve um erro ao comunicar com o servidor. Tente novamente", Snackbar.LENGTH_SHORT).show(); } }); } } @OnClick(R.id.buttonOpenRegisterForm) void openRegisterForm() { Intent intent = new Intent(this, RegisterActivity.class); startActivity(intent); } @OnClick(R.id.textViewForgotPassword) void openForgotPasswordForm() { final View dialogView = getLayoutInflater().inflate(R.layout.dialog_forgot_password, null); final EditText editTextEmailForgotPassword = ButterKnife.findById(dialogView, R.id.editTextEmailForgotPassword); new AlertDialog.Builder(this) .setTitle("Esqueci minha senha") .setMessage("Informe seu email abaixo e lhe enviaremos uma nova senha") .setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { String emailAddress = editTextEmailForgotPassword.getText().toString(); new EmailSenderService(LoginActivity.this).execute(emailAddress, "Recuperar senha", "A sua nova senha é " + UUID.randomUUID()); } }) .setNegativeButton("Cancelar", null) .setView(dialogView) .create() .show(); } }
4,402
0.632106
0.629832
108
39.722221
33.534622
151
false
false
0
0
0
0
0
0
0.648148
false
false
12
8fbca3828aaf3cec8803cd98badb9e914e89b577
14,001,593,440,595
7918c0640a6ba79bc09a1d4002a4df749b352fe3
/LeetCodeByCategory/src/string_array/ProductOfArrayExceptSelf.java
d9923ef88c2ae0b4bd201782fa7d80a655d8cea7
[]
no_license
dingpl716/LeetCode
https://github.com/dingpl716/LeetCode
5a73fd546722888f810a93486dbe9b1f9be20df1
8c24fee8a970484b9efcfc893b412f317a777db7
refs/heads/master
2021-01-19T10:26:11.493000
2020-03-27T03:23:06
2020-03-27T03:23:06
37,182,052
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package string_array; // Given an array of n integers where n > 1, nums, return an array // output such that output[i] is equal to the product of all the elements of nums except nums[i]. // // Solve it without division and in O(n). // // For example, given [1,2,3,4], return [24,12,8,6]. // // Follow up: // Could you solve it with constant space complexity? // (Note: The output array does not count as extra space for the purpose of space complexity analysis.) /** * 核心思想,要有DP的思维, nums[i]的值被除res[i]以外的所有其他res所需要 * @author Dingp * */ public class ProductOfArrayExceptSelf { public int[] productExceptSelf(int[] nums) { if (nums == null) { return null; } int[] res = new int[nums.length]; if (res.length == 0) { return res; } // 在这里置1的原因是,在从右向左扫描时我们需要做res[i] *= product // 如果不置1,那就永远为0了 res[0] = 1; // 从左边进行迭代连乘,可以保证现在res[i]上的乘积有nums[i]以前的所有数 for (int i = 1; i < res.length; ++i) { res[i] = nums[i - 1] * res[i - 1]; } // 从右边进行迭代连乘,可以保证现在res[i]上有nums[i]以后的所有数 int product = 1; for (int i = res.length - 1; i >= 0; --i) { res[i] *= product; product *= nums[i]; } return res; } public static void main(String[] args) { ProductOfArrayExceptSelf p = new ProductOfArrayExceptSelf(); int[] nums = new int[]{0, 0}; p.productExceptSelf(nums); } }
UTF-8
Java
1,719
java
ProductOfArrayExceptSelf.java
Java
[ { "context": "要有DP的思维, nums[i]的值被除res[i]以外的所有其他res所需要\n * @author Dingp\n *\n */\npublic class ProductOfArrayExceptSelf {\n\n ", "end": 538, "score": 0.9040670990943909, "start": 533, "tag": "USERNAME", "value": "Dingp" } ]
null
[]
package string_array; // Given an array of n integers where n > 1, nums, return an array // output such that output[i] is equal to the product of all the elements of nums except nums[i]. // // Solve it without division and in O(n). // // For example, given [1,2,3,4], return [24,12,8,6]. // // Follow up: // Could you solve it with constant space complexity? // (Note: The output array does not count as extra space for the purpose of space complexity analysis.) /** * 核心思想,要有DP的思维, nums[i]的值被除res[i]以外的所有其他res所需要 * @author Dingp * */ public class ProductOfArrayExceptSelf { public int[] productExceptSelf(int[] nums) { if (nums == null) { return null; } int[] res = new int[nums.length]; if (res.length == 0) { return res; } // 在这里置1的原因是,在从右向左扫描时我们需要做res[i] *= product // 如果不置1,那就永远为0了 res[0] = 1; // 从左边进行迭代连乘,可以保证现在res[i]上的乘积有nums[i]以前的所有数 for (int i = 1; i < res.length; ++i) { res[i] = nums[i - 1] * res[i - 1]; } // 从右边进行迭代连乘,可以保证现在res[i]上有nums[i]以后的所有数 int product = 1; for (int i = res.length - 1; i >= 0; --i) { res[i] *= product; product *= nums[i]; } return res; } public static void main(String[] args) { ProductOfArrayExceptSelf p = new ProductOfArrayExceptSelf(); int[] nums = new int[]{0, 0}; p.productExceptSelf(nums); } }
1,719
0.55814
0.541528
55
26.363636
23.790268
103
false
false
0
0
0
0
0
0
0.872727
false
false
12
d63973863acf36f72392cf899bfd1d0ab112b43e
6,356,551,608,450
c5df3b30ee00e237d1595b4a4eba0011a328d0df
/AsyncTask/app/src/main/java/com/mcs/android/asynctask/PostActivity.java
40afe69e567ed6ede6f3b61040f19d0fbc30903b
[]
no_license
shornabho/AndroidStudioProjects
https://github.com/shornabho/AndroidStudioProjects
cc87ccb72199dc339ff5a92f141169110a230ede
6c21dc77548e2b477fef74c1125231bd6ca21e6c
refs/heads/master
2023-05-13T05:04:50.043000
2021-05-18T10:28:57
2021-05-18T10:28:57
368,487,299
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.mcs.android.asynctask; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.app.AppCompatDelegate; import androidx.core.app.NotificationCompat; import androidx.core.app.NotificationManagerCompat; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.ProgressDialog; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.BitmapFactory; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.widget.LinearLayout; import android.widget.TextView; import com.mcs.android.asynctask.adapters.CommentsRecyclerViewAdapter; import com.mcs.android.asynctask.models.Comment; import com.mcs.android.asynctask.models.Post; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import static com.mcs.android.asynctask.BaseApplication.CHANNEL_POST_ID; public class PostActivity extends AppCompatActivity { private NotificationManagerCompat notificationManager; private TextView postTitle; private TextView postAuthor; private TextView postBody; private RecyclerView commentsRecyclerView; private CommentsRecyclerViewAdapter commentsRecyclerViewAdapter; ProgressDialog progressDialog; Post currentPost; ArrayList<Comment> commentsList = new ArrayList<Comment>(); private SharedPreferences sharedPreferences; private class CommentLoaderTask extends AsyncTask<String, Void, JSONArray> { @Override protected void onPreExecute() { super.onPreExecute(); progressDialog = new ProgressDialog(PostActivity.this); progressDialog.setMessage("Loading comments..."); progressDialog.setCancelable(false); progressDialog.setIndeterminate(false); progressDialog.show(); } @Override protected JSONArray doInBackground(String... urls) { String stringResult = ""; JSONArray jsonArrayResult = new JSONArray(); URL url; HttpURLConnection connection; try { url = new URL(urls[0]); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.connect(); InputStream inputStream = connection.getInputStream(); InputStreamReader inputStreamReader = new InputStreamReader(inputStream); int data = inputStreamReader.read(); while (data != -1) { char current = (char) data; stringResult += current; data = inputStreamReader.read(); } Log.i("StringCommentResult", stringResult); // Now that the data is loaded from the url // The data needs to be parsed using Simple JSON by Google JSONParser jsonParser = new JSONParser(); jsonArrayResult = (org.json.simple.JSONArray) jsonParser.parse(stringResult); } catch (MalformedURLException e) { Log.i("CaughtException", "Malformed URL Exception"); e.printStackTrace(); } catch (IOException e) { Log.i("CaughtException", "IO Exception"); e.printStackTrace(); } catch (ParseException e) { Log.i("CaughtException", "Parse Exception"); e.printStackTrace(); } return jsonArrayResult; } @Override protected void onPostExecute(JSONArray jsonArray) { super.onPostExecute(jsonArray); for (int i = 0; i < jsonArray.size(); i++) { JSONObject jsonObject = (JSONObject) jsonArray.get(i); long postId = (long) jsonObject.get("postId"); long id = (long) jsonObject.get("id"); String authorName = (String) jsonObject.get("name"); String authorEmail = (String) jsonObject.get("email"); String body = (String) jsonObject.get("body"); Comment comment = new Comment(postId, id, authorName, authorEmail, body.replace("\n", " ")); commentsList.add(comment); } if (jsonArray.size() > 0) commentsRecyclerViewAdapter.notifyDataSetChanged(); progressDialog.hide(); Intent intent = new Intent(PostActivity.this, PostActivity.class); intent.putExtra("post", currentPost); PendingIntent pendingIntent = PendingIntent.getActivity(PostActivity.this, 0, intent, 0); Notification notification = new NotificationCompat.Builder(PostActivity.this, CHANNEL_POST_ID) .setSmallIcon(R.drawable.ic_post) .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_post)) .setContentTitle(currentPost.getTitle().toUpperCase()) .setContentText(currentPost.getBody()) .setPriority(NotificationCompat.PRIORITY_HIGH) .setContentIntent(pendingIntent) .build(); notificationManager.notify(1, notification); } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); sharedPreferences = getSharedPreferences("com.mcs.android.asynctask.settings", MODE_PRIVATE); boolean darkMode = sharedPreferences.getBoolean("darkMode", false); if (darkMode) { AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES); } else { AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO); } setContentView(R.layout.activity_post); Bundle bundle = getIntent().getExtras(); currentPost = bundle.getParcelable("post"); commentsRecyclerView = (RecyclerView) findViewById(R.id.commentsRecyclerView); commentsRecyclerView.setLayoutManager(new LinearLayoutManager(this)); commentsRecyclerViewAdapter = new CommentsRecyclerViewAdapter(this, commentsList); commentsRecyclerView.setAdapter(commentsRecyclerViewAdapter); postTitle = (TextView) findViewById(R.id.postTitle); postAuthor = (TextView) findViewById(R.id.postAuthor); postBody = (TextView) findViewById(R.id.postBody); LinearLayout linearLayout = (LinearLayout) postBody.getParent(); linearLayout.setClickable(false); linearLayout.setFocusable(false); linearLayout.setForeground(null); postTitle.setText(currentPost.getTitle()); postAuthor.setText("User " + currentPost.getUserId()); postBody.setText(currentPost.getBody()); notificationManager = NotificationManagerCompat.from(this); CommentLoaderTask commentLoaderTask = new CommentLoaderTask(); commentLoaderTask.execute("https://jsonplaceholder.typicode.com/posts/" + currentPost.getId() + "/comments"); } @Override protected void onRestart() { super.onRestart(); recreate(); } @Override protected void onDestroy() { super.onDestroy(); if (progressDialog != null && progressDialog.isShowing()) { progressDialog.dismiss(); } progressDialog = null; } }
UTF-8
Java
7,893
java
PostActivity.java
Java
[]
null
[]
package com.mcs.android.asynctask; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.app.AppCompatDelegate; import androidx.core.app.NotificationCompat; import androidx.core.app.NotificationManagerCompat; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.ProgressDialog; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.BitmapFactory; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.widget.LinearLayout; import android.widget.TextView; import com.mcs.android.asynctask.adapters.CommentsRecyclerViewAdapter; import com.mcs.android.asynctask.models.Comment; import com.mcs.android.asynctask.models.Post; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import static com.mcs.android.asynctask.BaseApplication.CHANNEL_POST_ID; public class PostActivity extends AppCompatActivity { private NotificationManagerCompat notificationManager; private TextView postTitle; private TextView postAuthor; private TextView postBody; private RecyclerView commentsRecyclerView; private CommentsRecyclerViewAdapter commentsRecyclerViewAdapter; ProgressDialog progressDialog; Post currentPost; ArrayList<Comment> commentsList = new ArrayList<Comment>(); private SharedPreferences sharedPreferences; private class CommentLoaderTask extends AsyncTask<String, Void, JSONArray> { @Override protected void onPreExecute() { super.onPreExecute(); progressDialog = new ProgressDialog(PostActivity.this); progressDialog.setMessage("Loading comments..."); progressDialog.setCancelable(false); progressDialog.setIndeterminate(false); progressDialog.show(); } @Override protected JSONArray doInBackground(String... urls) { String stringResult = ""; JSONArray jsonArrayResult = new JSONArray(); URL url; HttpURLConnection connection; try { url = new URL(urls[0]); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.connect(); InputStream inputStream = connection.getInputStream(); InputStreamReader inputStreamReader = new InputStreamReader(inputStream); int data = inputStreamReader.read(); while (data != -1) { char current = (char) data; stringResult += current; data = inputStreamReader.read(); } Log.i("StringCommentResult", stringResult); // Now that the data is loaded from the url // The data needs to be parsed using Simple JSON by Google JSONParser jsonParser = new JSONParser(); jsonArrayResult = (org.json.simple.JSONArray) jsonParser.parse(stringResult); } catch (MalformedURLException e) { Log.i("CaughtException", "Malformed URL Exception"); e.printStackTrace(); } catch (IOException e) { Log.i("CaughtException", "IO Exception"); e.printStackTrace(); } catch (ParseException e) { Log.i("CaughtException", "Parse Exception"); e.printStackTrace(); } return jsonArrayResult; } @Override protected void onPostExecute(JSONArray jsonArray) { super.onPostExecute(jsonArray); for (int i = 0; i < jsonArray.size(); i++) { JSONObject jsonObject = (JSONObject) jsonArray.get(i); long postId = (long) jsonObject.get("postId"); long id = (long) jsonObject.get("id"); String authorName = (String) jsonObject.get("name"); String authorEmail = (String) jsonObject.get("email"); String body = (String) jsonObject.get("body"); Comment comment = new Comment(postId, id, authorName, authorEmail, body.replace("\n", " ")); commentsList.add(comment); } if (jsonArray.size() > 0) commentsRecyclerViewAdapter.notifyDataSetChanged(); progressDialog.hide(); Intent intent = new Intent(PostActivity.this, PostActivity.class); intent.putExtra("post", currentPost); PendingIntent pendingIntent = PendingIntent.getActivity(PostActivity.this, 0, intent, 0); Notification notification = new NotificationCompat.Builder(PostActivity.this, CHANNEL_POST_ID) .setSmallIcon(R.drawable.ic_post) .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_post)) .setContentTitle(currentPost.getTitle().toUpperCase()) .setContentText(currentPost.getBody()) .setPriority(NotificationCompat.PRIORITY_HIGH) .setContentIntent(pendingIntent) .build(); notificationManager.notify(1, notification); } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); sharedPreferences = getSharedPreferences("com.mcs.android.asynctask.settings", MODE_PRIVATE); boolean darkMode = sharedPreferences.getBoolean("darkMode", false); if (darkMode) { AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES); } else { AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO); } setContentView(R.layout.activity_post); Bundle bundle = getIntent().getExtras(); currentPost = bundle.getParcelable("post"); commentsRecyclerView = (RecyclerView) findViewById(R.id.commentsRecyclerView); commentsRecyclerView.setLayoutManager(new LinearLayoutManager(this)); commentsRecyclerViewAdapter = new CommentsRecyclerViewAdapter(this, commentsList); commentsRecyclerView.setAdapter(commentsRecyclerViewAdapter); postTitle = (TextView) findViewById(R.id.postTitle); postAuthor = (TextView) findViewById(R.id.postAuthor); postBody = (TextView) findViewById(R.id.postBody); LinearLayout linearLayout = (LinearLayout) postBody.getParent(); linearLayout.setClickable(false); linearLayout.setFocusable(false); linearLayout.setForeground(null); postTitle.setText(currentPost.getTitle()); postAuthor.setText("User " + currentPost.getUserId()); postBody.setText(currentPost.getBody()); notificationManager = NotificationManagerCompat.from(this); CommentLoaderTask commentLoaderTask = new CommentLoaderTask(); commentLoaderTask.execute("https://jsonplaceholder.typicode.com/posts/" + currentPost.getId() + "/comments"); } @Override protected void onRestart() { super.onRestart(); recreate(); } @Override protected void onDestroy() { super.onDestroy(); if (progressDialog != null && progressDialog.isShowing()) { progressDialog.dismiss(); } progressDialog = null; } }
7,893
0.658558
0.657671
205
37.507317
27.554756
117
false
false
0
0
0
0
0
0
0.702439
false
false
12
0efe5d6f576a4d3179cec70b6951ec3f11b88811
22,247,930,605,862
7367a2ccb6e3c358e239ad8511bf54464ae6054e
/core/src/test/java/com/hngd/web/controller/TagController.java
372a71c21d2a6c27711d576f6791f6aa004b33f6
[]
no_license
tanqidong1992/code-doc-tool
https://github.com/tanqidong1992/code-doc-tool
1e7cbeab5b9acb9791338c6b1348a83ad188b12f
9b8eea19b0f4c19a31540c7ef8b924cd571e52c9
refs/heads/main
2023-08-21T11:02:03.599000
2021-09-28T06:36:33
2021-09-28T06:36:33
367,232,700
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.hngd.web.controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; public class TagController { /** * No Class Tag Test * @author tqd * */ @RestController @RequestMapping("no/class/tag") public static class NoClassTagController{ /** * get tag * @param id the id of the tag to obtain * @summary obtain tag by tag id * @tags tag manager,tag,tqd * @return */ @GetMapping("/") public String getTag(String id) { return id; } } /** * Exists Class Tag Test * @tags class tag1,class tag2 * @author tqd * */ @RestController @RequestMapping("exits/class/tag") public static class ExistsClassTagController{ /** * get tag * @param id the id of the tag to obtain * @summary obtain tag by tag id * @tags tag manager,tag,tqd * @return */ @GetMapping("/") public String getTag(String id) { return id; } } }
UTF-8
Java
1,288
java
TagController.java
Java
[ { "context": "\n /**\r\n * No Class Tag Test\r\n * @author tqd\r\n *\r\n */\r\n @RestController\r\n @Reque", "end": 311, "score": 0.999692440032959, "start": 308, "tag": "USERNAME", "value": "tqd" }, { "context": " * @tags class tag1,class tag2\r\n * @author tqd\r\n *\r\n */\r\n @RestController\r\n @Reque", "end": 847, "score": 0.9996777772903442, "start": 844, "tag": "USERNAME", "value": "tqd" } ]
null
[]
package com.hngd.web.controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; public class TagController { /** * No Class Tag Test * @author tqd * */ @RestController @RequestMapping("no/class/tag") public static class NoClassTagController{ /** * get tag * @param id the id of the tag to obtain * @summary obtain tag by tag id * @tags tag manager,tag,tqd * @return */ @GetMapping("/") public String getTag(String id) { return id; } } /** * Exists Class Tag Test * @tags class tag1,class tag2 * @author tqd * */ @RestController @RequestMapping("exits/class/tag") public static class ExistsClassTagController{ /** * get tag * @param id the id of the tag to obtain * @summary obtain tag by tag id * @tags tag manager,tag,tqd * @return */ @GetMapping("/") public String getTag(String id) { return id; } } }
1,288
0.539596
0.538043
52
22.76923
17.016525
62
false
false
0
0
0
0
0
0
0.211538
false
false
12
2175416a5ad8f1f915ac6fa7dda3cb6b855c5cdb
10,926,396,825,328
51a27288561898a8134893fa83bad5eca4298b62
/test3/src/test3/maximum_app_profit.java
4f0a667a789d4e1e7aa68b5a3bebac21f34bd649
[]
no_license
lokiSpy/CODING_NINJAS_NUCLEUS_2018
https://github.com/lokiSpy/CODING_NINJAS_NUCLEUS_2018
9f3c2da38cef4224cdaa4e0d80909e756ef17a39
4734a63efa4385eb5cb96133064941a1a744a950
refs/heads/master
2020-04-21T08:42:44.533000
2019-02-06T16:03:20
2019-02-06T16:03:20
169,427,376
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package test3; import java.util.*; public class maximum_app_profit { public static int maximumProfit(int budget[]) { Arrays.sort(budget); int cost[] = new int[budget.length] ; for(int i=0 ; i<budget.length ; i++) { cost[i] = budget[i] * (budget.length-i) ; } int max = Integer.MIN_VALUE ; for(int i =0 ; i< cost.length ; i++ ) { if( cost[i] > max) { max = cost[i] ; } } return max ; } public static void main(String[] args) { int [] array = { 30 , 20 , 53 , 14 } ; System.out.println(maximumProfit(array)); } }
UTF-8
Java
569
java
maximum_app_profit.java
Java
[]
null
[]
package test3; import java.util.*; public class maximum_app_profit { public static int maximumProfit(int budget[]) { Arrays.sort(budget); int cost[] = new int[budget.length] ; for(int i=0 ; i<budget.length ; i++) { cost[i] = budget[i] * (budget.length-i) ; } int max = Integer.MIN_VALUE ; for(int i =0 ; i< cost.length ; i++ ) { if( cost[i] > max) { max = cost[i] ; } } return max ; } public static void main(String[] args) { int [] array = { 30 , 20 , 53 , 14 } ; System.out.println(maximumProfit(array)); } }
569
0.572935
0.553603
34
15.735294
16.652697
46
false
false
0
0
0
0
0
0
1.970588
false
false
12
29a5e8cc67c1907df1d203cf07c858a48a301201
29,068,338,707,347
331756b0c99fcbf11c0dcf09b058181e7d262ab6
/src/main/java/task2/CommandExecutor.java
de7b02cb8635a01058fb5de63f127f56e123fb86
[]
no_license
Kasymkhankhubiyev/Java_tasks_summer
https://github.com/Kasymkhankhubiyev/Java_tasks_summer
9def0e382fb44f654f10f00143848715a4d46e10
ed4a84c995054a0e2b84e776b6a7bc747cc7b50c
refs/heads/master
2022-12-12T18:20:09.078000
2020-09-09T16:25:55
2020-09-09T16:25:55
281,144,964
0
1
null
false
2020-09-09T16:25:56
2020-07-20T14:50:33
2020-09-09T16:25:23
2020-09-09T16:25:55
100
0
1
0
Java
false
false
package task2; import java.io.IOException; import java.io.Writer; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Scanner; public class CommandExecutor { final String delimeter = " "; private final Context context; private final Scanner scanner; private final CommandFactory commandFactory; private final Writer writer; public CommandExecutor(Context context, Scanner scanner, CommandFactory commandFactory, Writer writer) { this.context = context; this.scanner = scanner; this.commandFactory = commandFactory; this.writer = writer; } public void run() throws IOException { while (!context.getExit() && scanner.hasNextLine()){ //получаем строки String line = scanner.nextLine(); String[] substring = line.split(delimeter); //здесь у нас список из имени комманды и аргументов if(!line.startsWith("#")) { List<String> lineWords = new ArrayList<>(Arrays.asList(substring)); // превращаем массив в ArrayList так как с ним удобнее работать lineWords.removeIf(s -> s.isEmpty()); // удаляем все пустые строки, они могли появиться если мы напишем 2 пробелла подряд например if (lineWords.size() > 0) { // дальше делаем что-то только если пользователь не ввел пустую строку String commandName = lineWords.remove(0); // получаем имя команды заодно удалив его из списка try { commandFactory.createCommand(commandName).execute(context, lineWords); } catch (CommandException e) { writer.write(commandName + ":" + e.getMessage() +"\n"); writer.flush(); } catch (DecodeException e) { writer.write("Unknown command: " + commandName + "\n"); writer.flush(); } } } } writer.close(); scanner.close(); } }
UTF-8
Java
2,339
java
CommandExecutor.java
Java
[]
null
[]
package task2; import java.io.IOException; import java.io.Writer; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Scanner; public class CommandExecutor { final String delimeter = " "; private final Context context; private final Scanner scanner; private final CommandFactory commandFactory; private final Writer writer; public CommandExecutor(Context context, Scanner scanner, CommandFactory commandFactory, Writer writer) { this.context = context; this.scanner = scanner; this.commandFactory = commandFactory; this.writer = writer; } public void run() throws IOException { while (!context.getExit() && scanner.hasNextLine()){ //получаем строки String line = scanner.nextLine(); String[] substring = line.split(delimeter); //здесь у нас список из имени комманды и аргументов if(!line.startsWith("#")) { List<String> lineWords = new ArrayList<>(Arrays.asList(substring)); // превращаем массив в ArrayList так как с ним удобнее работать lineWords.removeIf(s -> s.isEmpty()); // удаляем все пустые строки, они могли появиться если мы напишем 2 пробелла подряд например if (lineWords.size() > 0) { // дальше делаем что-то только если пользователь не ввел пустую строку String commandName = lineWords.remove(0); // получаем имя команды заодно удалив его из списка try { commandFactory.createCommand(commandName).execute(context, lineWords); } catch (CommandException e) { writer.write(commandName + ":" + e.getMessage() +"\n"); writer.flush(); } catch (DecodeException e) { writer.write("Unknown command: " + commandName + "\n"); writer.flush(); } } } } writer.close(); scanner.close(); } }
2,339
0.599034
0.597101
49
41.2449
37.405407
147
false
false
0
0
0
0
0
0
0.673469
false
false
12
6217ea7c75c6b992aaababe861d4a2df8c4bb352
4,011,499,471,564
c07204f38ae06a60c9929665dd88634337f7b9cb
/farklı_maas_hesaplama/saatli_calisan.java
81da212595b159ed2fd57dc961e39c0932efe1fe
[]
no_license
Beyzacbn/Nesneye_Yonelik_Programlama
https://github.com/Beyzacbn/Nesneye_Yonelik_Programlama
648109c8cc3d5a6036604b573b6070b63a109bdd
95eb5d4e99e2fdc7646ba65e94969653e2808cd8
refs/heads/master
2020-04-30T10:17:34.788000
2019-03-20T18:06:00
2019-03-20T18:06:00
176,773,385
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
public class SaatliCalisan extends Calisan { private double ucret; private double saat; public SaatliCalisan(String ad ,String soyad ,String TC,double saatlikUcret,double calismaSaat) { super(ad,soyad,TC); setUcret(saatlikUcret); setSaat(calismaSaat); } public void setUcret(double saatlikUcret) { if(saatlikUcret>=0.0) ucret=saatlikUcret; else throw new IllegalArgumentException("saatlik ücret 0dan buyuk olmalı"); } public double getUcret() { return ucret; } public void setSaat(double calismaSaati) { if(calismaSaati >=0.0 && calismaSaati <=168) saat=calismaSaati; else throw new IllegalArgumentException("çalişma saati 0-168 aralığında olmalı"); } public double getSaat() { return saat; } public double kazanc() { if(saat<=40) return getSaat()*getUcret(); else return 40*getUcret()+(getSaat()-40)*getUcret()*1.5; } public String toString() { return String.format ("Saatli Calisan: %s \n Saatlik Ucret: %.2f \n Calisma Saati : %.2f ",super.toString(),getUcret(),getSaat()); } }
UTF-8
Java
1,088
java
saatli_calisan.java
Java
[]
null
[]
public class SaatliCalisan extends Calisan { private double ucret; private double saat; public SaatliCalisan(String ad ,String soyad ,String TC,double saatlikUcret,double calismaSaat) { super(ad,soyad,TC); setUcret(saatlikUcret); setSaat(calismaSaat); } public void setUcret(double saatlikUcret) { if(saatlikUcret>=0.0) ucret=saatlikUcret; else throw new IllegalArgumentException("saatlik ücret 0dan buyuk olmalı"); } public double getUcret() { return ucret; } public void setSaat(double calismaSaati) { if(calismaSaati >=0.0 && calismaSaati <=168) saat=calismaSaati; else throw new IllegalArgumentException("çalişma saati 0-168 aralığında olmalı"); } public double getSaat() { return saat; } public double kazanc() { if(saat<=40) return getSaat()*getUcret(); else return 40*getUcret()+(getSaat()-40)*getUcret()*1.5; } public String toString() { return String.format ("Saatli Calisan: %s \n Saatlik Ucret: %.2f \n Calisma Saati : %.2f ",super.toString(),getUcret(),getSaat()); } }
1,088
0.688889
0.668519
55
18.618181
26.377325
132
false
false
0
0
0
0
0
0
1.854545
false
false
12
73d43c864c396a5b0f59d527cbdbf4cb184479a5
32,942,399,187,403
9b47a6ba59fa05f4b73b3a0f31ed19c2dacb4dec
/JAVA/Unit2/TwentyOne.java
64a9f0720e2d84ce749865a6bb7fdd1f1163a8da
[]
no_license
trifirew/ICS2O1
https://github.com/trifirew/ICS2O1
966e79f818bba967d87ff53f2d3e519c20ff4d6d
fa7f198103ad27f76f9ccb354bc4ae6fb4cf8172
refs/heads/master
2021-01-22T06:07:04.595000
2017-05-29T23:16:59
2017-05-29T23:16:59
81,735,705
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * Keisun Wu * 20170318 * 2.4.6 A variation of the game of 21 */ import java.util.*; public class TwentyOne { public static void main(String[] args) { Scanner input = new Scanner(System.in); Random r = new Random(); int[] num = {0, 0, 0, 0}; int sum = 0; for (byte i=0; i<2; i++) { num[i] = r.nextInt(10) + 1; sum += num[i]; System.out.println("Number " + (i+1) + " is " + num[i]); } if (sum >= 18 && sum <=21) { System.out.println("You WIN!"); } else if(sum < 18) { while (true) { System.out.print("Do you want 1 or 2 additional numbers? "); byte additionalNum = input.nextByte(); if (additionalNum == 1 || additionalNum == 2) { for (byte i=2; i<additionalNum+2; i++) { num[i] = r.nextInt(10) + 1; sum += num[i]; System.out.println("Number " + (i+1) + " is " + num[i]); } break; } else { System.out.println("Invalid option!"); } } if (sum < 18) { System.out.println("You LOSE!"); } else if (sum > 21) { System.out.println("You WIN!"); } } } }
UTF-8
Java
1,177
java
TwentyOne.java
Java
[ { "context": "/*\n* Keisun Wu\n* 20170318\n* 2.4.6 A variation of the game of 21\n", "end": 14, "score": 0.9998468160629272, "start": 5, "tag": "NAME", "value": "Keisun Wu" } ]
null
[]
/* * <NAME> * 20170318 * 2.4.6 A variation of the game of 21 */ import java.util.*; public class TwentyOne { public static void main(String[] args) { Scanner input = new Scanner(System.in); Random r = new Random(); int[] num = {0, 0, 0, 0}; int sum = 0; for (byte i=0; i<2; i++) { num[i] = r.nextInt(10) + 1; sum += num[i]; System.out.println("Number " + (i+1) + " is " + num[i]); } if (sum >= 18 && sum <=21) { System.out.println("You WIN!"); } else if(sum < 18) { while (true) { System.out.print("Do you want 1 or 2 additional numbers? "); byte additionalNum = input.nextByte(); if (additionalNum == 1 || additionalNum == 2) { for (byte i=2; i<additionalNum+2; i++) { num[i] = r.nextInt(10) + 1; sum += num[i]; System.out.println("Number " + (i+1) + " is " + num[i]); } break; } else { System.out.println("Invalid option!"); } } if (sum < 18) { System.out.println("You LOSE!"); } else if (sum > 21) { System.out.println("You WIN!"); } } } }
1,174
0.483432
0.446049
47
24.042553
19.085426
68
false
false
0
0
0
0
0
0
0.574468
false
false
12
246421974fd50a141cc9a0564ecf4f40bf8f644d
8,014,408,984,308
3e79d7c1305dbb1814bde2f5d08e06f74b0d7e91
/src/main/java/br/com/alura/spring/data/repository/FuncionarioRepository.java
45bf139f1597716b8fda0709ce66d4ec56fd314c
[]
no_license
ShinoharaHelioAk/spring-data
https://github.com/ShinoharaHelioAk/spring-data
d945f2018eff832d06cba38b0d195783ec986824
33f77915c3d17b832bbb7a675cb5c2774a296816
refs/heads/master
2023-01-11T19:24:37.543000
2020-11-20T19:58:12
2020-11-20T19:58:12
314,655,673
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package br.com.alura.spring.data.repository; import java.time.LocalDate; import java.util.List; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import org.springframework.data.jpa.repository.Query; //import org.springframework.data.repository.CrudRepository; import org.springframework.data.repository.PagingAndSortingRepository; import org.springframework.stereotype.Repository; import br.com.alura.spring.data.orm.Funcionario; import br.com.alura.spring.data.projecoes.FuncionarioProjecao; //public interface FuncionarioRepository extends CrudRepository<Funcionario, Integer> {} @Repository public interface FuncionarioRepository extends PagingAndSortingRepository<Funcionario, Integer>, JpaSpecificationExecutor<Funcionario> { //JpaSpecificationExecutor<Funcionario> --> Permite realizar queries dinâmicas, equivalente à biblioteca de Criteria do JPA. //Derived Queries. List<Funcionario> findByNome(String nome); Page<Funcionario> findByNomeLike(String nome, Pageable pageable); List<Funcionario> findByNomeLike(String nome); //List<Funcionario> findByNomeAndSalarioGreaterThanAndDataContratacao(String nome, Double salario, LocalDate data); //Nas 2 linhas abaixo, usando JPQL. @Query("select f from Funcionario f where f.nome = :nome and f.salario >= :salario and f.dataContratacao = :data") List<Funcionario> findNomeSalarioMaiorDataContratacao(String nome, Double salario, LocalDate data); //Nas 2 linhas abaixo, usando Native Queries. @Query(value = "select * from Funcionarios f where data_contratacao >= :data", nativeQuery = true) List<Funcionario> findDataContratacaoMaior(LocalDate data); //Usando Projection com Native Query. @Query(value = "SELECT f.id, f.nome, f.salario FROM funcionarios f", nativeQuery = true) List<FuncionarioProjecao> findFuncionarioSalario(); }
UTF-8
Java
1,930
java
FuncionarioRepository.java
Java
[]
null
[]
package br.com.alura.spring.data.repository; import java.time.LocalDate; import java.util.List; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import org.springframework.data.jpa.repository.Query; //import org.springframework.data.repository.CrudRepository; import org.springframework.data.repository.PagingAndSortingRepository; import org.springframework.stereotype.Repository; import br.com.alura.spring.data.orm.Funcionario; import br.com.alura.spring.data.projecoes.FuncionarioProjecao; //public interface FuncionarioRepository extends CrudRepository<Funcionario, Integer> {} @Repository public interface FuncionarioRepository extends PagingAndSortingRepository<Funcionario, Integer>, JpaSpecificationExecutor<Funcionario> { //JpaSpecificationExecutor<Funcionario> --> Permite realizar queries dinâmicas, equivalente à biblioteca de Criteria do JPA. //Derived Queries. List<Funcionario> findByNome(String nome); Page<Funcionario> findByNomeLike(String nome, Pageable pageable); List<Funcionario> findByNomeLike(String nome); //List<Funcionario> findByNomeAndSalarioGreaterThanAndDataContratacao(String nome, Double salario, LocalDate data); //Nas 2 linhas abaixo, usando JPQL. @Query("select f from Funcionario f where f.nome = :nome and f.salario >= :salario and f.dataContratacao = :data") List<Funcionario> findNomeSalarioMaiorDataContratacao(String nome, Double salario, LocalDate data); //Nas 2 linhas abaixo, usando Native Queries. @Query(value = "select * from Funcionarios f where data_contratacao >= :data", nativeQuery = true) List<Funcionario> findDataContratacaoMaior(LocalDate data); //Usando Projection com Native Query. @Query(value = "SELECT f.id, f.nome, f.salario FROM funcionarios f", nativeQuery = true) List<FuncionarioProjecao> findFuncionarioSalario(); }
1,930
0.813797
0.812759
39
48.435898
38.318367
136
false
false
0
0
0
0
0
0
1.333333
false
false
12
36f10e5a94c1eb13ed6973d6971ace3ad9b9ee19
14,929,306,351,296
952f0eab1657f9a790f6b04be76d6634d6cf2cba
/src/javathread/BankAccount.java
bba62e895b440aa6b2403751056df38d553b2bf2
[]
no_license
skPythonGreaterThanJava/JavaThread
https://github.com/skPythonGreaterThanJava/JavaThread
c99700be97a0e64bc02e0c733a96111f1b79aeea
2f9c9e3671317fcd7127432a93cf874a52a176d3
refs/heads/master
2023-01-19T03:18:52.658000
2020-12-01T12:32:29
2020-12-01T12:32:29
315,610,697
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 javathread; /** * * @author sesana.federico */ public class BankAccount { private int total; private int tax = 100; public BankAccount(int total) { this.total = total; } public void add(int amount) { total += (amount - tax); } public int tot(){ return total; } }
UTF-8
Java
554
java
BankAccount.java
Java
[ { "context": ".\r\n */\r\npackage javathread;\r\n\r\n/**\r\n *\r\n * @author sesana.federico\r\n */\r\npublic class BankAccount {\r\n private int", "end": 248, "score": 0.9636168479919434, "start": 233, "tag": "NAME", "value": "sesana.federico" } ]
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 javathread; /** * * @author sesana.federico */ public class BankAccount { private int total; private int tax = 100; public BankAccount(int total) { this.total = total; } public void add(int amount) { total += (amount - tax); } public int tot(){ return total; } }
554
0.586643
0.581227
27
18.518518
18.970484
79
false
false
0
0
0
0
0
0
0.333333
false
false
12
1dfc5978a75d0a8102608c5ce11bc9ed66d8ea20
6,605,659,759,238
85b761b6edfec8d3e2a582f07a0f55f9b17a05cf
/app/src/main/java/com/ellize/ltc/User.java
9f0c44981aab0165d44e450332e53a11ef90b3a2
[]
no_license
SecurityBand/Nemezida.Rationalizator
https://github.com/SecurityBand/Nemezida.Rationalizator
3a810fc3a11c153ed7267a12180a93edcd4c9285
07e92fbd7056a75f180be99ef6ddbbb6fe288b33
refs/heads/master
2023-01-18T13:54:17.396000
2020-11-29T02:06:16
2020-11-29T02:06:16
316,794,280
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.ellize.ltc; public class User { public String login; public String psw; public String token; public String fio; public String inn; public String company; public String code; public String avatar_url; public String locale; public boolean isLogined; public User(String login, String psw) { this.login = login; this.psw = psw; isLogined = false; token = null; code = ""; avatar_url = ""; locale = ""; } }
UTF-8
Java
522
java
User.java
Java
[]
null
[]
package com.ellize.ltc; public class User { public String login; public String psw; public String token; public String fio; public String inn; public String company; public String code; public String avatar_url; public String locale; public boolean isLogined; public User(String login, String psw) { this.login = login; this.psw = psw; isLogined = false; token = null; code = ""; avatar_url = ""; locale = ""; } }
522
0.584291
0.584291
26
19.076923
10.908441
43
false
false
0
0
0
0
0
0
0.730769
false
false
12
796fdd18eb2c3160dd4a82f033c0148c7c28ab1c
7,181,185,330,610
f913fcf55c0f68390be636410866aea69774f178
/src/java/catalogos/TipoTelefonoBean.java
a458f9fc63f2c2ea278a99c6f9e2e0b207cd30e0
[]
no_license
Erick-Hdez/ErickJSF
https://github.com/Erick-Hdez/ErickJSF
edd52ac0019cadf9ea7370046ef61d5753528f7d
c3fee5211c7f4a71873143cafcf323f33c5f4cc9
refs/heads/main
2023-05-02T10:37:32.219000
2021-05-21T01:54:14
2021-05-21T01:54:14
366,485,923
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 catalogos; import java.util.ArrayList; import java.util.logging.Level; import java.util.logging.Logger; import javax.faces.application.FacesMessage; import javax.faces.bean.ManagedBean; import javax.faces.bean.RequestScoped; import javax.faces.bean.ViewScoped; import javax.faces.context.FacesContext; import modelos.CatalogoModeloTipoTelefono; import objetos.TipoTelefono; import respuestas.Respuesta; import respuestas.RespuestaTipoTelefono; /** * * @author Erick Corral * @Fecha 2021-04-16 */ @ManagedBean @RequestScoped @ViewScoped public class TipoTelefonoBean { private ArrayList<TipoTelefono> listaTipoTelefono; private TipoTelefono tipoTelefono; public TipoTelefonoBean() { mostrarCatalogoTipoTelefono(); tipoTelefono = new TipoTelefono(); } // muestra el catálogo C_TIPO_TELEFONO public void mostrarCatalogoTipoTelefono() { RespuestaTipoTelefono respuesta = CatalogoModeloTipoTelefono.getListaTipoTelefono(); try { if (respuesta.getRespuesta().getId() == 0) { listaTipoTelefono = (ArrayList<TipoTelefono>) respuesta.getListaTipoTelefono(); FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Cargando datos ", respuesta.getRespuesta().getMensaje()); FacesContext.getCurrentInstance().addMessage(null, msg); } else { System.out.println(respuesta.getRespuesta().getMensaje()); FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "No se enontraron resultados ", respuesta.getRespuesta().getMensaje()); FacesContext.getCurrentInstance().addMessage(null, msg); } } catch (Exception ex) { Logger.getLogger(TipoTelefonoBean.class.getName()).log(Level.SEVERE, null, ex); } } // insertar datos en el catálogo C_TIPO_TELEFONO public void insertarDatosTipoTelefono() { Respuesta respuesta = CatalogoModeloTipoTelefono.insertarRegistroTipoTelefono(tipoTelefono); try { if (respuesta.getId() != 0) { System.out.println(respuesta.getMensaje()); FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "No se encontraron resultados ", respuesta.getMensaje()); FacesContext.getCurrentInstance().addMessage(null, msg); } else { mostrarCatalogoTipoTelefono(); tipoTelefono = new TipoTelefono(); FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Datos agrgados exitosamente ", respuesta.getMensaje()); FacesContext.getCurrentInstance().addMessage(null, msg); } } catch (Exception ex) { Logger.getLogger(TipoTelefonoBean.class.getName()).log(Level.SEVERE, null, ex); } } // editar fila en catálogo C_TIPO_TELEFONO public void editarDatosTipoTelefono(TipoTelefono tipoTelefono) { Respuesta respuesta = CatalogoModeloTipoTelefono.editarRegistroTipoTelefono(tipoTelefono); try { if (respuesta.getId() != 0) { System.out.println(respuesta.getMensaje()); FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "No se encontraron resultados ", respuesta.getMensaje()); FacesContext.getCurrentInstance().addMessage(null, msg); } else { mostrarCatalogoTipoTelefono(); FacesMessage msg = new FacesMessage("Fila editada exitosamente..."); FacesContext.getCurrentInstance().addMessage(null, msg); } } catch (Exception ex) { Logger.getLogger(TipoTelefonoBean.class.getName()).log(Level.SEVERE, null, ex); } } // eliminar fila de catálogo C_TIPO_TELEFONO public void eliminarDatosTipoTelefono(TipoTelefono tipoTelefono) { Respuesta respuesta = CatalogoModeloTipoTelefono.eliminarRegistroTipoTelefono(tipoTelefono); try { if (respuesta.getId() != 0) { System.out.println(respuesta.getMensaje()); FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "No se encontraron resultados ", respuesta.getMensaje()); FacesContext.getCurrentInstance().addMessage(null, msg); } else { mostrarCatalogoTipoTelefono(); FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Fila eliminada exitosamente...", respuesta.getMensaje()); FacesContext.getCurrentInstance().addMessage(null, msg); } } catch (Exception ex) { Logger.getLogger(TipoTelefonoBean.class.getName()).log(Level.SEVERE, null, ex); } } //<editor-fold defaultstate="collapsed" desc="GETS y SETS"> public ArrayList<TipoTelefono> getListaTipoTelefono() { return listaTipoTelefono; } public void setListaTipoTelefono(ArrayList<TipoTelefono> listaTipoTelefono) { this.listaTipoTelefono = listaTipoTelefono; } /** * @return the tipoTelefono */ public TipoTelefono getTipoTelefono() { return tipoTelefono; } /** * @param tipoTelefono the tipoTelefono to set */ public void setTipoTelefono(TipoTelefono tipoTelefono) { this.tipoTelefono = tipoTelefono; } //</editor-fold> }
UTF-8
Java
5,601
java
TipoTelefonoBean.java
Java
[ { "context": "spuestas.RespuestaTipoTelefono;\n\n/**\n *\n * @author Erick Corral\n * @Fecha 2021-04-16\n */\n\n@ManagedBean\n@RequestSc", "end": 669, "score": 0.9998329281806946, "start": 657, "tag": "NAME", "value": "Erick Corral" } ]
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 catalogos; import java.util.ArrayList; import java.util.logging.Level; import java.util.logging.Logger; import javax.faces.application.FacesMessage; import javax.faces.bean.ManagedBean; import javax.faces.bean.RequestScoped; import javax.faces.bean.ViewScoped; import javax.faces.context.FacesContext; import modelos.CatalogoModeloTipoTelefono; import objetos.TipoTelefono; import respuestas.Respuesta; import respuestas.RespuestaTipoTelefono; /** * * @author <NAME> * @Fecha 2021-04-16 */ @ManagedBean @RequestScoped @ViewScoped public class TipoTelefonoBean { private ArrayList<TipoTelefono> listaTipoTelefono; private TipoTelefono tipoTelefono; public TipoTelefonoBean() { mostrarCatalogoTipoTelefono(); tipoTelefono = new TipoTelefono(); } // muestra el catálogo C_TIPO_TELEFONO public void mostrarCatalogoTipoTelefono() { RespuestaTipoTelefono respuesta = CatalogoModeloTipoTelefono.getListaTipoTelefono(); try { if (respuesta.getRespuesta().getId() == 0) { listaTipoTelefono = (ArrayList<TipoTelefono>) respuesta.getListaTipoTelefono(); FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Cargando datos ", respuesta.getRespuesta().getMensaje()); FacesContext.getCurrentInstance().addMessage(null, msg); } else { System.out.println(respuesta.getRespuesta().getMensaje()); FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "No se enontraron resultados ", respuesta.getRespuesta().getMensaje()); FacesContext.getCurrentInstance().addMessage(null, msg); } } catch (Exception ex) { Logger.getLogger(TipoTelefonoBean.class.getName()).log(Level.SEVERE, null, ex); } } // insertar datos en el catálogo C_TIPO_TELEFONO public void insertarDatosTipoTelefono() { Respuesta respuesta = CatalogoModeloTipoTelefono.insertarRegistroTipoTelefono(tipoTelefono); try { if (respuesta.getId() != 0) { System.out.println(respuesta.getMensaje()); FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "No se encontraron resultados ", respuesta.getMensaje()); FacesContext.getCurrentInstance().addMessage(null, msg); } else { mostrarCatalogoTipoTelefono(); tipoTelefono = new TipoTelefono(); FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Datos agrgados exitosamente ", respuesta.getMensaje()); FacesContext.getCurrentInstance().addMessage(null, msg); } } catch (Exception ex) { Logger.getLogger(TipoTelefonoBean.class.getName()).log(Level.SEVERE, null, ex); } } // editar fila en catálogo C_TIPO_TELEFONO public void editarDatosTipoTelefono(TipoTelefono tipoTelefono) { Respuesta respuesta = CatalogoModeloTipoTelefono.editarRegistroTipoTelefono(tipoTelefono); try { if (respuesta.getId() != 0) { System.out.println(respuesta.getMensaje()); FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "No se encontraron resultados ", respuesta.getMensaje()); FacesContext.getCurrentInstance().addMessage(null, msg); } else { mostrarCatalogoTipoTelefono(); FacesMessage msg = new FacesMessage("Fila editada exitosamente..."); FacesContext.getCurrentInstance().addMessage(null, msg); } } catch (Exception ex) { Logger.getLogger(TipoTelefonoBean.class.getName()).log(Level.SEVERE, null, ex); } } // eliminar fila de catálogo C_TIPO_TELEFONO public void eliminarDatosTipoTelefono(TipoTelefono tipoTelefono) { Respuesta respuesta = CatalogoModeloTipoTelefono.eliminarRegistroTipoTelefono(tipoTelefono); try { if (respuesta.getId() != 0) { System.out.println(respuesta.getMensaje()); FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "No se encontraron resultados ", respuesta.getMensaje()); FacesContext.getCurrentInstance().addMessage(null, msg); } else { mostrarCatalogoTipoTelefono(); FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Fila eliminada exitosamente...", respuesta.getMensaje()); FacesContext.getCurrentInstance().addMessage(null, msg); } } catch (Exception ex) { Logger.getLogger(TipoTelefonoBean.class.getName()).log(Level.SEVERE, null, ex); } } //<editor-fold defaultstate="collapsed" desc="GETS y SETS"> public ArrayList<TipoTelefono> getListaTipoTelefono() { return listaTipoTelefono; } public void setListaTipoTelefono(ArrayList<TipoTelefono> listaTipoTelefono) { this.listaTipoTelefono = listaTipoTelefono; } /** * @return the tipoTelefono */ public TipoTelefono getTipoTelefono() { return tipoTelefono; } /** * @param tipoTelefono the tipoTelefono to set */ public void setTipoTelefono(TipoTelefono tipoTelefono) { this.tipoTelefono = tipoTelefono; } //</editor-fold> }
5,595
0.662676
0.660532
148
36.817566
36.174324
151
false
false
0
0
0
0
0
0
0.587838
false
false
12
6f2f4b6af85ee05c908ccc6c6ca4afd146e5769d
4,312,147,181,584
8a9c31f98c6d5ec491546c98edeb3590c5c77147
/BinarySearchTree.java
0921d8260165afdb2c9977c1da6e4924c9eb3064
[]
no_license
chenkai319/2D-Rectangle-BST-
https://github.com/chenkai319/2D-Rectangle-BST-
5ff8e9a1753f7e715466f10225f4f73fdbbc8905
29326ae1d9a9b4185f8b0f13347a5e332f498c09
refs/heads/master
2020-05-24T17:53:51.418000
2019-05-18T19:37:38
2019-05-18T19:37:38
187,397,319
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.util.Stack; import java.util.Iterator; /** * This data structure used to store the collection of rectangles * and will be in the Binary Search Tree * * @author Chenkairen * @author Hung Tran * * @param <T> * Actual Object * @param <E> * Key data type * * @version 1.0 */ public class BinarySearchTree<T extends Comparable<T>, E extends Comparable<E>> implements Iterable<Node<T, E>> { private Node<T, E> root; private int nodeCount; /** * Default constructor */ public BinarySearchTree() { root = null; this.nodeCount = 0; } /** * clear the tree */ public void clear() { root = null; this.nodeCount = 0; } /***** HELPER*FUNCTIONS ********/ /** * Depth helper * * @param subTreeNode * The node * @param level * the depth level */ private void setDepthHelper(Node<T, E> subTreeNode, int level) { if (subTreeNode == null) { return; } else { subTreeNode.setDept(level); setDepthHelper(subTreeNode.getLeftChild(), level + 1); setDepthHelper(subTreeNode.getRightChild(), level + 1); } } /** * Delete maximum node * * @param subTreeNode * the node * @return the node */ private Node<T, E> deleteMax(Node<T, E> subTreeNode) { if (subTreeNode.getRightChild() == null) { return subTreeNode.getLeftChild(); } subTreeNode.setRightChild(deleteMax(subTreeNode.getRightChild())); return subTreeNode; } /** * get maximum node * * @param subTreeNode * the node * @return the max node */ private Node<T, E> getMax(Node<T, E> subTreeNode) { if (subTreeNode.getRightChild() == null) { return subTreeNode; } return getMax(subTreeNode.getRightChild()); } /** * The helper function that take in a subtree node, it will look for * the target item by traversing through the tree * * @param subTreeNode * the node * @param target * the remove target * @return an updated node */ private Node<T, E> removeHelper(Node<T, E> subTreeNode, T target) { if (target == null) { return null; } // go to the right of the tree if target is bigger than current node if (subTreeNode.getData().compareTo(target) > 0) /* move */ { subTreeNode.setLeftChild(removeHelper(subTreeNode.getLeftChild(), target)); } // go to the left of the tree if target is smaller than current node else if (subTreeNode.getData().compareTo(target) < 0) { subTreeNode.setRightChild(removeHelper(subTreeNode.getRightChild(), target)); } else if (!subTreeNode.isDeleteTarget()) { subTreeNode.setLeftChild(removeHelper(subTreeNode.getLeftChild(), target)); } else // Found target { if (subTreeNode.getLeftChild() == null) { return subTreeNode.getRightChild(); } else { Node<T, E> temp = getMax(subTreeNode.getLeftChild()); temp.activateDelete(); subTreeNode.setData(temp.getData()); subTreeNode.deactivateDelete(); subTreeNode.setLeftChild(deleteMax(subTreeNode.getLeftChild())); } } return subTreeNode; } /** * Find the node base on its name * * @param subTreeNode * the node * @param target * find item * @return found item */ public T findNodeHelper(Node<T, E> subTreeNode, T target) { if (subTreeNode == null) { return null; } if (subTreeNode.getData().compareTo(target) == 0) { subTreeNode.activateDelete(); return subTreeNode.getData(); } else if (findNodeHelper(subTreeNode.getLeftChild(), target) == null) { return findNodeHelper(subTreeNode.getRightChild(), target); } else { return findNodeHelper(subTreeNode.getLeftChild(), target); } } /** * Search all element * * @param subTreeNode * the node * @param target * The target to search for * @return an object */ private T searchAllHelper(Node<T, E> subTreeNode, T target) { if (subTreeNode == null) { return null; } if (subTreeNode.getData().compareTo(target) == 0) { System.out.println(subTreeNode.getData().toString()); return searchAllHelper(subTreeNode.getLeftChild(), target); } else if (subTreeNode.getData().compareTo(target) > 0) { return searchAllHelper(subTreeNode.getLeftChild(), target); } else { return searchAllHelper(subTreeNode.getRightChild(), target); } } /** * take in a subtree node then dumb it. * * @param subTreeNode * the target node */ private void dumpHelper(Node<T, E> subTreeNode) { if (subTreeNode != null) { dumpHelper(subTreeNode.getLeftChild()); if (subTreeNode != null) { System.out.println("Node has depth " + subTreeNode.getDept() + ", Value " + subTreeNode.getData().toString()); } dumpHelper(subTreeNode.getRightChild()); } } /** * Insert a node into the tree with BST order. * * @param subTreeNode * the node * @param item * the item needed to insert * @return an node */ private Node<T, E> insertHelper(Node<T, E> subTreeNode, T item) { if (subTreeNode == null) { return new Node<T, E>(item); } if (item.compareTo(subTreeNode.getData()) <= 0) { subTreeNode.setLeftChild(this.insertHelper(subTreeNode .getLeftChild(), item)); } else { subTreeNode.setRightChild(this.insertHelper(subTreeNode .getRightChild(), item)); } return subTreeNode; } /********* END*HELPER*FUNCTIONS ***************/ /** * check to see if the tree is empty * * @return true if the tree is empty */ public boolean isTreeEmpty() { return (root == null); } /** * Insert an item into a tree * * @param item * the item */ public void insert(T item) { { root = insertHelper(root, item); } nodeCount++; } /** * remove item from a tree * * @param target * the remove target * @param flag * the flag is off if remove target by finding it in * the tree first * If the flag is on, it will remove which node has deleted * flag activated without finding it * @return true if the item is removed */ public boolean remove(T target, boolean flag) { if (target == null) { return false; } if (root == null) { return false; } if (!flag) { T targetFound = findNodeHelper(root, target); if (targetFound == null) { return false; } root = removeHelper(root, targetFound); } else { root = removeHelper(root, target); } nodeCount--; return true; } /** * search item from a tree * * @param target * the item to search for * @return true if item is found */ public boolean search(T target) { if (findNodeHelper(root, target) == null) { return false; } this.searchAllHelper(root, target); return true; } /** * Dump a tree */ public void dump() { if (this.isTreeEmpty()) { System.out.println("Node has depth 0, Value (null)"); System.out.println("BST size is: " + this.nodeCount); } else { this.setDepthHelper(root, 0); dumpHelper(root); System.out.println("BST size is: " + this.nodeCount); } } /** * @Override override iterator */ @Override public Iterator<Node<T, E>> iterator() { return new BTSIterator(this); } /** * create an iteration of a tree with inorder tranverse. * * @author Hung Tran * @author Chenkai Ren * @version 1.0 */ class BTSIterator implements Iterator<Node<T, E>> { private Node<T, E> currentNode; private Stack<Node<T, E>> container = new Stack<Node<T, E>>(); /** * default iterator * * @param bst * binary search tree */ public BTSIterator(BinarySearchTree<T, E> bst) { currentNode = root; while (currentNode != null) { container.push(currentNode); currentNode = currentNode.getLeftChild(); } } /** * check to see if the next item is available * * @return true if there is next node */ public boolean hasNext() { return (!(currentNode == null && container.isEmpty())); } /** * get the next item * * @return the next item */ public Node<T, E> next() { while (currentNode != null) { container.push(currentNode); currentNode = currentNode.getLeftChild(); } Node<T, E> temp = container.pop(); currentNode = temp; currentNode = currentNode.getRightChild(); return temp; } } }
UTF-8
Java
10,213
java
BinarySearchTree.java
Java
[ { "context": "d will be in the Binary Search Tree\n * \n * @author Chenkairen\n * @author Hung Tran\n *\n * @param <T>\n * ", "end": 182, "score": 0.6064119935035706, "start": 178, "tag": "USERNAME", "value": "Chen" }, { "context": "l be in the Binary Search Tree\n * \n * @author Chenkairen\n * @author Hung Tran\n *\n * @param <T>\n * ", "end": 188, "score": 0.972500741481781, "start": 182, "tag": "NAME", "value": "kairen" }, { "context": "y Search Tree\n * \n * @author Chenkairen\n * @author Hung Tran\n *\n * @param <T>\n * Actual Object\n * @", "end": 209, "score": 0.9995794892311096, "start": 200, "tag": "NAME", "value": "Hung Tran" }, { "context": "ree with inorder tranverse.\n * \n * @author Hung Tran\n * @author Chenkai Ren\n * @version 1.0\n ", "end": 8879, "score": 0.999793291091919, "start": 8870, "tag": "NAME", "value": "Hung Tran" }, { "context": "e.\n * \n * @author Hung Tran\n * @author Chenkai Ren\n * @version 1.0\n */\n class BTSIterator", "end": 8906, "score": 0.9997931122779846, "start": 8895, "tag": "NAME", "value": "Chenkai Ren" } ]
null
[]
import java.util.Stack; import java.util.Iterator; /** * This data structure used to store the collection of rectangles * and will be in the Binary Search Tree * * @author Chenkairen * @author <NAME> * * @param <T> * Actual Object * @param <E> * Key data type * * @version 1.0 */ public class BinarySearchTree<T extends Comparable<T>, E extends Comparable<E>> implements Iterable<Node<T, E>> { private Node<T, E> root; private int nodeCount; /** * Default constructor */ public BinarySearchTree() { root = null; this.nodeCount = 0; } /** * clear the tree */ public void clear() { root = null; this.nodeCount = 0; } /***** HELPER*FUNCTIONS ********/ /** * Depth helper * * @param subTreeNode * The node * @param level * the depth level */ private void setDepthHelper(Node<T, E> subTreeNode, int level) { if (subTreeNode == null) { return; } else { subTreeNode.setDept(level); setDepthHelper(subTreeNode.getLeftChild(), level + 1); setDepthHelper(subTreeNode.getRightChild(), level + 1); } } /** * Delete maximum node * * @param subTreeNode * the node * @return the node */ private Node<T, E> deleteMax(Node<T, E> subTreeNode) { if (subTreeNode.getRightChild() == null) { return subTreeNode.getLeftChild(); } subTreeNode.setRightChild(deleteMax(subTreeNode.getRightChild())); return subTreeNode; } /** * get maximum node * * @param subTreeNode * the node * @return the max node */ private Node<T, E> getMax(Node<T, E> subTreeNode) { if (subTreeNode.getRightChild() == null) { return subTreeNode; } return getMax(subTreeNode.getRightChild()); } /** * The helper function that take in a subtree node, it will look for * the target item by traversing through the tree * * @param subTreeNode * the node * @param target * the remove target * @return an updated node */ private Node<T, E> removeHelper(Node<T, E> subTreeNode, T target) { if (target == null) { return null; } // go to the right of the tree if target is bigger than current node if (subTreeNode.getData().compareTo(target) > 0) /* move */ { subTreeNode.setLeftChild(removeHelper(subTreeNode.getLeftChild(), target)); } // go to the left of the tree if target is smaller than current node else if (subTreeNode.getData().compareTo(target) < 0) { subTreeNode.setRightChild(removeHelper(subTreeNode.getRightChild(), target)); } else if (!subTreeNode.isDeleteTarget()) { subTreeNode.setLeftChild(removeHelper(subTreeNode.getLeftChild(), target)); } else // Found target { if (subTreeNode.getLeftChild() == null) { return subTreeNode.getRightChild(); } else { Node<T, E> temp = getMax(subTreeNode.getLeftChild()); temp.activateDelete(); subTreeNode.setData(temp.getData()); subTreeNode.deactivateDelete(); subTreeNode.setLeftChild(deleteMax(subTreeNode.getLeftChild())); } } return subTreeNode; } /** * Find the node base on its name * * @param subTreeNode * the node * @param target * find item * @return found item */ public T findNodeHelper(Node<T, E> subTreeNode, T target) { if (subTreeNode == null) { return null; } if (subTreeNode.getData().compareTo(target) == 0) { subTreeNode.activateDelete(); return subTreeNode.getData(); } else if (findNodeHelper(subTreeNode.getLeftChild(), target) == null) { return findNodeHelper(subTreeNode.getRightChild(), target); } else { return findNodeHelper(subTreeNode.getLeftChild(), target); } } /** * Search all element * * @param subTreeNode * the node * @param target * The target to search for * @return an object */ private T searchAllHelper(Node<T, E> subTreeNode, T target) { if (subTreeNode == null) { return null; } if (subTreeNode.getData().compareTo(target) == 0) { System.out.println(subTreeNode.getData().toString()); return searchAllHelper(subTreeNode.getLeftChild(), target); } else if (subTreeNode.getData().compareTo(target) > 0) { return searchAllHelper(subTreeNode.getLeftChild(), target); } else { return searchAllHelper(subTreeNode.getRightChild(), target); } } /** * take in a subtree node then dumb it. * * @param subTreeNode * the target node */ private void dumpHelper(Node<T, E> subTreeNode) { if (subTreeNode != null) { dumpHelper(subTreeNode.getLeftChild()); if (subTreeNode != null) { System.out.println("Node has depth " + subTreeNode.getDept() + ", Value " + subTreeNode.getData().toString()); } dumpHelper(subTreeNode.getRightChild()); } } /** * Insert a node into the tree with BST order. * * @param subTreeNode * the node * @param item * the item needed to insert * @return an node */ private Node<T, E> insertHelper(Node<T, E> subTreeNode, T item) { if (subTreeNode == null) { return new Node<T, E>(item); } if (item.compareTo(subTreeNode.getData()) <= 0) { subTreeNode.setLeftChild(this.insertHelper(subTreeNode .getLeftChild(), item)); } else { subTreeNode.setRightChild(this.insertHelper(subTreeNode .getRightChild(), item)); } return subTreeNode; } /********* END*HELPER*FUNCTIONS ***************/ /** * check to see if the tree is empty * * @return true if the tree is empty */ public boolean isTreeEmpty() { return (root == null); } /** * Insert an item into a tree * * @param item * the item */ public void insert(T item) { { root = insertHelper(root, item); } nodeCount++; } /** * remove item from a tree * * @param target * the remove target * @param flag * the flag is off if remove target by finding it in * the tree first * If the flag is on, it will remove which node has deleted * flag activated without finding it * @return true if the item is removed */ public boolean remove(T target, boolean flag) { if (target == null) { return false; } if (root == null) { return false; } if (!flag) { T targetFound = findNodeHelper(root, target); if (targetFound == null) { return false; } root = removeHelper(root, targetFound); } else { root = removeHelper(root, target); } nodeCount--; return true; } /** * search item from a tree * * @param target * the item to search for * @return true if item is found */ public boolean search(T target) { if (findNodeHelper(root, target) == null) { return false; } this.searchAllHelper(root, target); return true; } /** * Dump a tree */ public void dump() { if (this.isTreeEmpty()) { System.out.println("Node has depth 0, Value (null)"); System.out.println("BST size is: " + this.nodeCount); } else { this.setDepthHelper(root, 0); dumpHelper(root); System.out.println("BST size is: " + this.nodeCount); } } /** * @Override override iterator */ @Override public Iterator<Node<T, E>> iterator() { return new BTSIterator(this); } /** * create an iteration of a tree with inorder tranverse. * * @author <NAME> * @author <NAME> * @version 1.0 */ class BTSIterator implements Iterator<Node<T, E>> { private Node<T, E> currentNode; private Stack<Node<T, E>> container = new Stack<Node<T, E>>(); /** * default iterator * * @param bst * binary search tree */ public BTSIterator(BinarySearchTree<T, E> bst) { currentNode = root; while (currentNode != null) { container.push(currentNode); currentNode = currentNode.getLeftChild(); } } /** * check to see if the next item is available * * @return true if there is next node */ public boolean hasNext() { return (!(currentNode == null && container.isEmpty())); } /** * get the next item * * @return the next item */ public Node<T, E> next() { while (currentNode != null) { container.push(currentNode); currentNode = currentNode.getLeftChild(); } Node<T, E> temp = container.pop(); currentNode = temp; currentNode = currentNode.getRightChild(); return temp; } } }
10,202
0.51268
0.511113
397
24.725441
21.698244
80
false
false
0
0
0
0
0
0
0.332494
false
false
12
8c9204e2dfabaa04f1b532bb2814b5110964a848
14,989,435,879,849
435e667bce1a9d30e10af1872f9ca0143d672972
/src/codeGen/PrintManager.java
6fa0dbb1e90ee5724233bc4459f591948b394218
[]
no_license
tola95/wacc_32
https://github.com/tola95/wacc_32
93ca5a786b69c4051098bf53e88d88ba5cb76402
1c58b4a9e0d3e6f8c9140e0c4f32f33d7e5cc3aa
refs/heads/master
2021-01-16T18:21:12.687000
2014-12-11T17:43:27
2014-12-11T17:43:27
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package codeGen; import java.util.Arrays; import java.util.List; public class PrintManager { private List<Boolean> prints = Arrays.asList(false, false, false, false, false, false); private List<Boolean> reads = Arrays.asList(false, false, false); private List<Boolean> errors = Arrays.asList(false, false, false, false); private List<Boolean> free = Arrays.asList(false, false); public boolean freepair() { return helperPrint(free, 0); } public boolean overflow() { return helperPrint(errors, 0); } public boolean runtime() { return helperPrint(errors, 2); } public boolean nullReference() { return helperPrint(errors, 1); } public boolean array_bounds() { return helperPrint(errors, 3); } public boolean print_string() { return helperPrint(prints, 0); } public boolean print_int() { return helperPrint(prints, 1); } public boolean print_char() { return helperPrint(prints, 2); } public boolean print_array() { return helperPrint(prints, 3); } public boolean print_pair() { return helperPrint(prints, 4); } public boolean print_bool() { return helperPrint(prints, 5); } public boolean read_char() { return helperPrint(reads, 0); } public boolean read_int() { return helperPrint(reads, 1); } public boolean read_string() { return helperPrint(reads, 2); } private boolean helperPrint(List<Boolean> list, int i) { boolean value = list.get(i); if (!value) { list.set(i, true); } return value; } }
UTF-8
Java
1,501
java
PrintManager.java
Java
[]
null
[]
package codeGen; import java.util.Arrays; import java.util.List; public class PrintManager { private List<Boolean> prints = Arrays.asList(false, false, false, false, false, false); private List<Boolean> reads = Arrays.asList(false, false, false); private List<Boolean> errors = Arrays.asList(false, false, false, false); private List<Boolean> free = Arrays.asList(false, false); public boolean freepair() { return helperPrint(free, 0); } public boolean overflow() { return helperPrint(errors, 0); } public boolean runtime() { return helperPrint(errors, 2); } public boolean nullReference() { return helperPrint(errors, 1); } public boolean array_bounds() { return helperPrint(errors, 3); } public boolean print_string() { return helperPrint(prints, 0); } public boolean print_int() { return helperPrint(prints, 1); } public boolean print_char() { return helperPrint(prints, 2); } public boolean print_array() { return helperPrint(prints, 3); } public boolean print_pair() { return helperPrint(prints, 4); } public boolean print_bool() { return helperPrint(prints, 5); } public boolean read_char() { return helperPrint(reads, 0); } public boolean read_int() { return helperPrint(reads, 1); } public boolean read_string() { return helperPrint(reads, 2); } private boolean helperPrint(List<Boolean> list, int i) { boolean value = list.get(i); if (!value) { list.set(i, true); } return value; } }
1,501
0.683544
0.674217
77
18.493507
19.178331
88
false
false
0
0
0
0
0
0
1.818182
false
false
12
b7d1be64ad0ec6319b8209aff3400828616d9e6d
601,295,443,725
3d013b4fc0a1340584e693fc57193bce430f750b
/i-shop-vertical-application/i-shop-web-admin/src/main/java/com/illusory/i/shop/web/admin/web/controller/UploadController.java
4310736d103acd167aa277779349fc4ffcf47f77
[ "MIT" ]
permissive
illusorycloud/i-shop
https://github.com/illusorycloud/i-shop
614f9261d62e1c027412c3a513990add56bd3782
953ba5ff9a630075992ac714b682e656653c417e
refs/heads/master
2020-05-01T03:25:59.226000
2019-04-09T05:22:49
2019-04-09T05:22:49
177,244,777
1
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.illusory.i.shop.web.admin.web.controller; import org.springframework.stereotype.Controller; 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.multipart.MultipartFile; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; import javax.servlet.http.HttpServletRequest; /** * 文件上传 * @author illusoryCloud * @version 1.0.0 * @date 2019/3/26 22:10 */ @Controller public class UploadController { private static final String UPLOAD_PATH = "/static/upload/"; /** * 文件上传 * * @param dropFile Dropzone * @param editorFiles wangEditor * @return */ @ResponseBody @RequestMapping(value = "upload", method = RequestMethod.POST) public Map<String, Object> upload(MultipartFile dropFile, MultipartFile[] editorFiles, HttpServletRequest request) { Map<String, Object> result = new HashMap<>(); // Dropzone 上传 if (dropFile != null) { result.put("fileName", writeFile(dropFile, request)); } // wangEditor 上传 if (editorFiles != null && editorFiles.length > 0) { List<String> fileNames = new ArrayList<>(); for (MultipartFile editorFile : editorFiles) { fileNames.add(writeFile(editorFile, request)); } result.put("errno", 0); result.put("data", fileNames); } return result; } /** * 将图片写入指定目录 * * @param multipartFile * @param request * @return 返回文件完整路径 */ private String writeFile(MultipartFile multipartFile, HttpServletRequest request) { // 获取文件后缀 String fileName = multipartFile.getOriginalFilename(); String fileSuffix = fileName.substring(fileName.lastIndexOf(".")); // 文件存放路径 String filePath = request.getSession().getServletContext().getRealPath(UPLOAD_PATH); // 判断路径是否存在,不存在则创建文件夹 File file = new File(filePath); if (!file.exists()) { file.mkdir(); } // 将文件写入目标 file = new File(filePath, UUID.randomUUID() + fileSuffix); try { multipartFile.transferTo(file); } catch (IOException e) { e.printStackTrace(); } // 返回文件完整路径 String serverPath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort(); return serverPath + UPLOAD_PATH + file.getName(); } }
UTF-8
Java
2,854
java
UploadController.java
Java
[ { "context": "t.http.HttpServletRequest;\n\n/**\n * 文件上传\n * @author illusoryCloud\n * @version 1.0.0\n * @date 2019/3/26 22:10\n */\n@C", "end": 603, "score": 0.9996713399887085, "start": 590, "tag": "USERNAME", "value": "illusoryCloud" } ]
null
[]
package com.illusory.i.shop.web.admin.web.controller; import org.springframework.stereotype.Controller; 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.multipart.MultipartFile; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; import javax.servlet.http.HttpServletRequest; /** * 文件上传 * @author illusoryCloud * @version 1.0.0 * @date 2019/3/26 22:10 */ @Controller public class UploadController { private static final String UPLOAD_PATH = "/static/upload/"; /** * 文件上传 * * @param dropFile Dropzone * @param editorFiles wangEditor * @return */ @ResponseBody @RequestMapping(value = "upload", method = RequestMethod.POST) public Map<String, Object> upload(MultipartFile dropFile, MultipartFile[] editorFiles, HttpServletRequest request) { Map<String, Object> result = new HashMap<>(); // Dropzone 上传 if (dropFile != null) { result.put("fileName", writeFile(dropFile, request)); } // wangEditor 上传 if (editorFiles != null && editorFiles.length > 0) { List<String> fileNames = new ArrayList<>(); for (MultipartFile editorFile : editorFiles) { fileNames.add(writeFile(editorFile, request)); } result.put("errno", 0); result.put("data", fileNames); } return result; } /** * 将图片写入指定目录 * * @param multipartFile * @param request * @return 返回文件完整路径 */ private String writeFile(MultipartFile multipartFile, HttpServletRequest request) { // 获取文件后缀 String fileName = multipartFile.getOriginalFilename(); String fileSuffix = fileName.substring(fileName.lastIndexOf(".")); // 文件存放路径 String filePath = request.getSession().getServletContext().getRealPath(UPLOAD_PATH); // 判断路径是否存在,不存在则创建文件夹 File file = new File(filePath); if (!file.exists()) { file.mkdir(); } // 将文件写入目标 file = new File(filePath, UUID.randomUUID() + fileSuffix); try { multipartFile.transferTo(file); } catch (IOException e) { e.printStackTrace(); } // 返回文件完整路径 String serverPath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort(); return serverPath + UPLOAD_PATH + file.getName(); } }
2,854
0.633407
0.627494
95
27.494738
26.405293
120
false
false
0
0
0
0
0
0
0.463158
false
false
12
127e3fc317edbd1ae058d463b42c93086f7d0bcf
22,539,988,383,873
177d9e3d473ed0309fbc7c513157122eb6290376
/Trabalho_poo/src/model/Produto.java
535ff88738d80939fd96fe7bbce9c636fa112d01
[]
no_license
alles2/lancheria-bot
https://github.com/alles2/lancheria-bot
34af5b468dae5114c29d768642ffc450dbf0817d
58811748e5dca220a7b4905ea7a9dea25ea4a6c5
refs/heads/main
2023-06-27T09:49:19.634000
2021-07-26T16:06:22
2021-07-26T16:06:22
389,678,203
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 model; import java.sql.ResultSet; import java.sql.SQLException; /** * * @author m13247 */ public class Produto { public void addProduto(String descricao, String categoria, double preco) throws ClassNotFoundException, SQLException, Exception { //método para adicionar um novo produto banco_dados.ComandosBd comandos = new banco_dados.ComandosBd(); ResultSet categorias = comandos.getCategoria(categoria); int categoriaId = 0; while (categorias.next()) { categoriaId = categorias.getInt("id"); } comandos.addProduto(descricao, categoriaId, preco); } public ResultSet getProdutos() throws ClassNotFoundException, SQLException { //método que retorna todos os produtos banco_dados.ComandosBd comandos = new banco_dados.ComandosBd(); return comandos.getProdutos(); } public void deleteProduto(String produto) throws Exception { //método para deletar um produto banco_dados.ComandosBd comandos = new banco_dados.ComandosBd(); libsUtil.Util lib = new libsUtil.Util(); int id = lib.transformaIdParaInt(produto); //é usada a lib, para transformar o id em string para int, pois o dado foi capturado no jtable ResultSet dadosProdAdicionadas = comandos.getProdutosComPedido(); boolean podeExcluirProduto = true; while (dadosProdAdicionadas.next()) { if (dadosProdAdicionadas.getString("id").equals(produto)) { podeExcluirProduto = false; } } if(!podeExcluirProduto){ throw new Exception("Você não pode excluir esse produto, pois ele está cadastrado em um pedido!"); } comandos.deleteProduto(id); } public void updateProduto(int id, String descricao, String categoria, double preco) throws Exception { //método para atualizar produto banco_dados.ComandosBd comandos = new banco_dados.ComandosBd(); ResultSet categorias = comandos.getCategoria(categoria); int categoriaId = 0; while (categorias.next()) { categoriaId = categorias.getInt("id"); } comandos.updateProduto(id, descricao, categoriaId, preco); } public ResultSet getProdutosDeCategoria(String descricaoCategoria) throws ClassNotFoundException, SQLException { //retorna produtos de determinada categoria banco_dados.ComandosBd comandos = new banco_dados.ComandosBd(); return comandos.getProdutosComCategoria(descricaoCategoria); } public int getProdutoId(String descricao) throws ClassNotFoundException, SQLException { banco_dados.ComandosBd comandos = new banco_dados.ComandosBd(); ResultSet produto = comandos.getProduto(descricao); int produtoId = 0; while (produto.next()) { produtoId = produto.getInt("id"); } return produtoId; } public double getProdutoPreco(String descricao) throws ClassNotFoundException, SQLException { banco_dados.ComandosBd comandos = new banco_dados.ComandosBd(); ResultSet produto = comandos.getProduto(descricao); double preco = 0; while (produto.next()) { preco = produto.getDouble("preco"); } return preco; } }
UTF-8
Java
3,634
java
Produto.java
Java
[ { "context": "port java.sql.SQLException;\r\n\r\n/**\r\n *\r\n * @author m13247\r\n */\r\npublic class Produto {\r\n\r\n public void add", "end": 295, "score": 0.9654524922370911, "start": 289, "tag": "USERNAME", "value": "m13247" } ]
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 model; import java.sql.ResultSet; import java.sql.SQLException; /** * * @author m13247 */ public class Produto { public void addProduto(String descricao, String categoria, double preco) throws ClassNotFoundException, SQLException, Exception { //método para adicionar um novo produto banco_dados.ComandosBd comandos = new banco_dados.ComandosBd(); ResultSet categorias = comandos.getCategoria(categoria); int categoriaId = 0; while (categorias.next()) { categoriaId = categorias.getInt("id"); } comandos.addProduto(descricao, categoriaId, preco); } public ResultSet getProdutos() throws ClassNotFoundException, SQLException { //método que retorna todos os produtos banco_dados.ComandosBd comandos = new banco_dados.ComandosBd(); return comandos.getProdutos(); } public void deleteProduto(String produto) throws Exception { //método para deletar um produto banco_dados.ComandosBd comandos = new banco_dados.ComandosBd(); libsUtil.Util lib = new libsUtil.Util(); int id = lib.transformaIdParaInt(produto); //é usada a lib, para transformar o id em string para int, pois o dado foi capturado no jtable ResultSet dadosProdAdicionadas = comandos.getProdutosComPedido(); boolean podeExcluirProduto = true; while (dadosProdAdicionadas.next()) { if (dadosProdAdicionadas.getString("id").equals(produto)) { podeExcluirProduto = false; } } if(!podeExcluirProduto){ throw new Exception("Você não pode excluir esse produto, pois ele está cadastrado em um pedido!"); } comandos.deleteProduto(id); } public void updateProduto(int id, String descricao, String categoria, double preco) throws Exception { //método para atualizar produto banco_dados.ComandosBd comandos = new banco_dados.ComandosBd(); ResultSet categorias = comandos.getCategoria(categoria); int categoriaId = 0; while (categorias.next()) { categoriaId = categorias.getInt("id"); } comandos.updateProduto(id, descricao, categoriaId, preco); } public ResultSet getProdutosDeCategoria(String descricaoCategoria) throws ClassNotFoundException, SQLException { //retorna produtos de determinada categoria banco_dados.ComandosBd comandos = new banco_dados.ComandosBd(); return comandos.getProdutosComCategoria(descricaoCategoria); } public int getProdutoId(String descricao) throws ClassNotFoundException, SQLException { banco_dados.ComandosBd comandos = new banco_dados.ComandosBd(); ResultSet produto = comandos.getProduto(descricao); int produtoId = 0; while (produto.next()) { produtoId = produto.getInt("id"); } return produtoId; } public double getProdutoPreco(String descricao) throws ClassNotFoundException, SQLException { banco_dados.ComandosBd comandos = new banco_dados.ComandosBd(); ResultSet produto = comandos.getProduto(descricao); double preco = 0; while (produto.next()) { preco = produto.getDouble("preco"); } return preco; } }
3,634
0.650028
0.647546
106
32.207546
33.755981
145
false
false
0
0
0
0
0
0
0.537736
false
false
12
ab8f0c0e5c37876ef4495279066bcbc9210eb6dd
27,762,668,618,497
1a5fc0348b57abc429332014a6b9047e10bd94d1
/module/OAuth/App/oauth-admin/service-rest/core/src/main/java/org/jepria/oauth/client/dao/ClientDaoImpl.java
b74528cd30b50bd03f218690627aef2a8fa00f30
[ "Apache-2.0" ]
permissive
Jepria/oauth
https://github.com/Jepria/oauth
6fdedc5628c0fa01059b2b6aefe27743d47d8a18
555f1103b06f586647af6504dddab5e1966aa237
refs/heads/develop
2022-02-26T16:19:14.936000
2022-02-15T15:15:43
2022-02-15T15:15:43
235,527,989
1
0
Apache-2.0
false
2022-02-27T22:59:24
2020-01-22T08:17:27
2021-10-11T06:50:10
2022-02-27T22:59:22
135,739
1
0
3
HTML
false
false
package org.jepria.oauth.client.dao; import org.jepria.compat.server.dao.ResultSetMapper; import org.jepria.oauth.client.dto.ClientCreateDto; import org.jepria.oauth.client.dto.ClientDto; import org.jepria.oauth.client.dto.ClientSearchDto; import org.jepria.oauth.client.dto.ClientUpdateDto; import org.jepria.server.data.DaoSupport; import org.jepria.server.data.DtoUtil; import org.jepria.server.data.OptionDto; import java.sql.ResultSet; import java.sql.SQLException; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import static org.jepria.oauth.client.ClientFieldNames.*; public class ClientDaoImpl implements ClientDao { @Override public List<?> find(Object template, Integer operatorId) { ClientSearchDto searchTemplate = (ClientSearchDto) template; String sqlQuery = "begin " + "? := pkg_OAuth.findClient(" + "clientShortName => ? " + ", clientName => ? " + ", clientNameEn => ? " + ", maxRowCount => ? " + ", operatorId => ? " + ");" + " end;"; List<ClientDto> records = null; records = DaoSupport.getInstance().find(sqlQuery, new ResultSetMapper<ClientDto>() { @Override public void map(ResultSet rs, ClientDto dto) throws SQLException { dto.setClientId(rs.getString(CLIENT_SHORT_NAME)); dto.setClientSecret(rs.getString(CLIENT_SECRET)); dto.setClientName(rs.getString(CLIENT_NAME)); dto.setClientNameEn(rs.getString(CLIENT_NAME_EN)); dto.setApplicationType(rs.getString(APPLICATION_TYPE)); dto.setLoginModuleUri(rs.getString(LOGIN_MODULE_URI)); dto.setGrantTypes(getClientGrantTypes(dto.getClientId(), operatorId)); Integer clientOperatorId = getInteger(rs, OPERATOR_ID); if (clientOperatorId != null) dto.setScope(getClientRoles(clientOperatorId, operatorId)); } } , ClientDto.class , searchTemplate.getClientId() , DtoUtil.startsWith(searchTemplate.getClientName()) , DtoUtil.startsWith(searchTemplate.getClientNameEn()) , searchTemplate.getMaxRowCount() , operatorId); return records; } @Override public List<ClientDto> findByPrimaryKey(Map<String, ?> primaryKeyMap, final Integer operatorId) { String sqlQuery = "begin " + "? := pkg_OAuth.findClient(" + "clientShortName => ? " + ", clientName => ? " + ", clientNameEn => ? " + ", maxRowCount => ? " + ", operatorId => ? " + ");" + " end;"; List<ClientDto> records = null; records = DaoSupport.getInstance().find(sqlQuery, new ResultSetMapper<ClientDto>() { @Override public void map(ResultSet rs, ClientDto dto) throws SQLException { dto.setClientId(rs.getString(CLIENT_SHORT_NAME)); dto.setClientSecret(rs.getString(CLIENT_SECRET)); dto.setClientName(rs.getString(CLIENT_NAME)); dto.setClientNameEn(rs.getString(CLIENT_NAME_EN)); dto.setApplicationType(rs.getString(APPLICATION_TYPE)); dto.setLoginModuleUri(rs.getString(LOGIN_MODULE_URI)); dto.setGrantTypes(getClientGrantTypes(dto.getClientId(), operatorId)); Integer clientOperatorId = getInteger(rs, OPERATOR_ID); if (clientOperatorId != null) dto.setScope(getClientRoles(getInteger(rs, OPERATOR_ID), operatorId)); } } , ClientDto.class , primaryKeyMap.get(CLIENT_ID) , null , null , null , operatorId); return records; } @Override public Object create(Object record, Integer operatorId) { ClientCreateDto dto = (ClientCreateDto) record; String sqlQuery = "begin " + "? := pkg_OAuth.createClient(" + "clientShortName => ? " + ", clientName => ? " + ", clientNameEn => ? " + ", applicationType => ? " + ", loginModuleUri => ? " + ", grantTypeList => ? " + ", roleShortNameList => ? " + ", operatorId => ? " + ");" + "end;"; DaoSupport.getInstance().create(sqlQuery, String.class , dto.getClientId() , dto.getClientName() , dto.getClientNameEn() , dto.getApplicationType() , dto.getLoginModuleUri() , dto.getGrantTypes() != null ? dto.getGrantTypes().stream().collect(Collectors.joining(",")) : null , dto.getScope() != null ? dto.getScope().stream().collect(Collectors.joining(",")) : null , operatorId ); return dto.getClientId(); } @Override public void update(Map<String, ?> primaryKey, Object record, Integer operatorId) { ClientUpdateDto dto = (ClientUpdateDto) record; String sqlQuery = "begin " + "pkg_OAuth.updateClient(" + "clientShortName => ? " + ", clientName => ? " + ", clientNameEn => ? " + ", applicationType => ? " + ", loginModuleUri => ? " + ", grantTypeList => ? " + ", roleShortNameList => ? " + ", operatorId => ? " + ");" + "end;"; DaoSupport.getInstance().update(sqlQuery , primaryKey.get(CLIENT_ID) , dto.getClientName() , dto.getClientNameEn() , dto.getApplicationType() , dto.getLoginModuleUri() , dto.getGrantTypes() != null ? dto.getGrantTypes().stream().collect(Collectors.joining(",")) : null , dto.getScope() != null ? dto.getScope().stream().collect(Collectors.joining(",")) : null , operatorId ); } @Override public void delete(Map<String, ?> primaryKey, Integer operatorId) { String sqlQuery = "begin " + "pkg_OAuth.deleteClient(" + "clientShortName => ? " + ", operatorId => ? " + ");" + "end;"; DaoSupport.getInstance().delete(sqlQuery , primaryKey.get(CLIENT_ID) , operatorId ); } @Override public List<String> getClientGrantTypes(String clientId, Integer operatorId) { String sqlQuery = "begin " + "? := pkg_OAuth.getClientGrant(" + "clientShortName => ? " + ", operatorId => ? " + ");" + " end;"; List<OptionDto<String>> grantTypes = DaoSupport.getInstance().find(sqlQuery, new ResultSetMapper<OptionDto<String>>() { @Override public void map(ResultSet rs, OptionDto<String> result) throws SQLException { result.setValue(rs.getString(GRANT_TYPE)); } } , OptionDto.class , clientId , operatorId); return grantTypes.stream().map(option -> option.getValue()).collect(Collectors.toList()); } @Override public List<OptionDto<String>> getRoles(String roleName, String roleNameEn, Integer maxRowCount, Integer operatorId) { String sqlQuery = "begin " + "? := pkg_OAuth.getRoles(" + "roleName => ? " + ", roleNameEn => ? " + ", maxRowCount => ? " + ", operatorId => ? " + ");" + " end;"; List<OptionDto<String>> result = null; result = DaoSupport.getInstance().find(sqlQuery, new ResultSetMapper<OptionDto<String>>() { @Override public void map(ResultSet rs, OptionDto<String> result) throws SQLException { result.setValue(rs.getString(SHORT_NAME)); result.setName(rs.getString(ROLE_NAME)); } } , OptionDto.class , DtoUtil.startsWith(roleName) , DtoUtil.startsWith(roleNameEn) , maxRowCount , operatorId); return result; } private List<OptionDto<String>> getClientRoles(Integer clientOperatorId, Integer operatorId) { String sqlQuery = "begin " + "? := pkg_operator.getRoles(" + "operatorId => ? " + ");" + " end;"; List<OptionDto<String>> result; result = DaoSupport.getInstance().find(sqlQuery, new ResultSetMapper<OptionDto<String>>() { @Override public void map(ResultSet rs, OptionDto<String> result) throws SQLException { result.setValue(rs.getString(SHORT_NAME)); result.setName(rs.getString(ROLE_NAME)); } } , OptionDto.class , clientOperatorId); return result; } }
UTF-8
Java
8,242
java
ClientDaoImpl.java
Java
[]
null
[]
package org.jepria.oauth.client.dao; import org.jepria.compat.server.dao.ResultSetMapper; import org.jepria.oauth.client.dto.ClientCreateDto; import org.jepria.oauth.client.dto.ClientDto; import org.jepria.oauth.client.dto.ClientSearchDto; import org.jepria.oauth.client.dto.ClientUpdateDto; import org.jepria.server.data.DaoSupport; import org.jepria.server.data.DtoUtil; import org.jepria.server.data.OptionDto; import java.sql.ResultSet; import java.sql.SQLException; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import static org.jepria.oauth.client.ClientFieldNames.*; public class ClientDaoImpl implements ClientDao { @Override public List<?> find(Object template, Integer operatorId) { ClientSearchDto searchTemplate = (ClientSearchDto) template; String sqlQuery = "begin " + "? := pkg_OAuth.findClient(" + "clientShortName => ? " + ", clientName => ? " + ", clientNameEn => ? " + ", maxRowCount => ? " + ", operatorId => ? " + ");" + " end;"; List<ClientDto> records = null; records = DaoSupport.getInstance().find(sqlQuery, new ResultSetMapper<ClientDto>() { @Override public void map(ResultSet rs, ClientDto dto) throws SQLException { dto.setClientId(rs.getString(CLIENT_SHORT_NAME)); dto.setClientSecret(rs.getString(CLIENT_SECRET)); dto.setClientName(rs.getString(CLIENT_NAME)); dto.setClientNameEn(rs.getString(CLIENT_NAME_EN)); dto.setApplicationType(rs.getString(APPLICATION_TYPE)); dto.setLoginModuleUri(rs.getString(LOGIN_MODULE_URI)); dto.setGrantTypes(getClientGrantTypes(dto.getClientId(), operatorId)); Integer clientOperatorId = getInteger(rs, OPERATOR_ID); if (clientOperatorId != null) dto.setScope(getClientRoles(clientOperatorId, operatorId)); } } , ClientDto.class , searchTemplate.getClientId() , DtoUtil.startsWith(searchTemplate.getClientName()) , DtoUtil.startsWith(searchTemplate.getClientNameEn()) , searchTemplate.getMaxRowCount() , operatorId); return records; } @Override public List<ClientDto> findByPrimaryKey(Map<String, ?> primaryKeyMap, final Integer operatorId) { String sqlQuery = "begin " + "? := pkg_OAuth.findClient(" + "clientShortName => ? " + ", clientName => ? " + ", clientNameEn => ? " + ", maxRowCount => ? " + ", operatorId => ? " + ");" + " end;"; List<ClientDto> records = null; records = DaoSupport.getInstance().find(sqlQuery, new ResultSetMapper<ClientDto>() { @Override public void map(ResultSet rs, ClientDto dto) throws SQLException { dto.setClientId(rs.getString(CLIENT_SHORT_NAME)); dto.setClientSecret(rs.getString(CLIENT_SECRET)); dto.setClientName(rs.getString(CLIENT_NAME)); dto.setClientNameEn(rs.getString(CLIENT_NAME_EN)); dto.setApplicationType(rs.getString(APPLICATION_TYPE)); dto.setLoginModuleUri(rs.getString(LOGIN_MODULE_URI)); dto.setGrantTypes(getClientGrantTypes(dto.getClientId(), operatorId)); Integer clientOperatorId = getInteger(rs, OPERATOR_ID); if (clientOperatorId != null) dto.setScope(getClientRoles(getInteger(rs, OPERATOR_ID), operatorId)); } } , ClientDto.class , primaryKeyMap.get(CLIENT_ID) , null , null , null , operatorId); return records; } @Override public Object create(Object record, Integer operatorId) { ClientCreateDto dto = (ClientCreateDto) record; String sqlQuery = "begin " + "? := pkg_OAuth.createClient(" + "clientShortName => ? " + ", clientName => ? " + ", clientNameEn => ? " + ", applicationType => ? " + ", loginModuleUri => ? " + ", grantTypeList => ? " + ", roleShortNameList => ? " + ", operatorId => ? " + ");" + "end;"; DaoSupport.getInstance().create(sqlQuery, String.class , dto.getClientId() , dto.getClientName() , dto.getClientNameEn() , dto.getApplicationType() , dto.getLoginModuleUri() , dto.getGrantTypes() != null ? dto.getGrantTypes().stream().collect(Collectors.joining(",")) : null , dto.getScope() != null ? dto.getScope().stream().collect(Collectors.joining(",")) : null , operatorId ); return dto.getClientId(); } @Override public void update(Map<String, ?> primaryKey, Object record, Integer operatorId) { ClientUpdateDto dto = (ClientUpdateDto) record; String sqlQuery = "begin " + "pkg_OAuth.updateClient(" + "clientShortName => ? " + ", clientName => ? " + ", clientNameEn => ? " + ", applicationType => ? " + ", loginModuleUri => ? " + ", grantTypeList => ? " + ", roleShortNameList => ? " + ", operatorId => ? " + ");" + "end;"; DaoSupport.getInstance().update(sqlQuery , primaryKey.get(CLIENT_ID) , dto.getClientName() , dto.getClientNameEn() , dto.getApplicationType() , dto.getLoginModuleUri() , dto.getGrantTypes() != null ? dto.getGrantTypes().stream().collect(Collectors.joining(",")) : null , dto.getScope() != null ? dto.getScope().stream().collect(Collectors.joining(",")) : null , operatorId ); } @Override public void delete(Map<String, ?> primaryKey, Integer operatorId) { String sqlQuery = "begin " + "pkg_OAuth.deleteClient(" + "clientShortName => ? " + ", operatorId => ? " + ");" + "end;"; DaoSupport.getInstance().delete(sqlQuery , primaryKey.get(CLIENT_ID) , operatorId ); } @Override public List<String> getClientGrantTypes(String clientId, Integer operatorId) { String sqlQuery = "begin " + "? := pkg_OAuth.getClientGrant(" + "clientShortName => ? " + ", operatorId => ? " + ");" + " end;"; List<OptionDto<String>> grantTypes = DaoSupport.getInstance().find(sqlQuery, new ResultSetMapper<OptionDto<String>>() { @Override public void map(ResultSet rs, OptionDto<String> result) throws SQLException { result.setValue(rs.getString(GRANT_TYPE)); } } , OptionDto.class , clientId , operatorId); return grantTypes.stream().map(option -> option.getValue()).collect(Collectors.toList()); } @Override public List<OptionDto<String>> getRoles(String roleName, String roleNameEn, Integer maxRowCount, Integer operatorId) { String sqlQuery = "begin " + "? := pkg_OAuth.getRoles(" + "roleName => ? " + ", roleNameEn => ? " + ", maxRowCount => ? " + ", operatorId => ? " + ");" + " end;"; List<OptionDto<String>> result = null; result = DaoSupport.getInstance().find(sqlQuery, new ResultSetMapper<OptionDto<String>>() { @Override public void map(ResultSet rs, OptionDto<String> result) throws SQLException { result.setValue(rs.getString(SHORT_NAME)); result.setName(rs.getString(ROLE_NAME)); } } , OptionDto.class , DtoUtil.startsWith(roleName) , DtoUtil.startsWith(roleNameEn) , maxRowCount , operatorId); return result; } private List<OptionDto<String>> getClientRoles(Integer clientOperatorId, Integer operatorId) { String sqlQuery = "begin " + "? := pkg_operator.getRoles(" + "operatorId => ? " + ");" + " end;"; List<OptionDto<String>> result; result = DaoSupport.getInstance().find(sqlQuery, new ResultSetMapper<OptionDto<String>>() { @Override public void map(ResultSet rs, OptionDto<String> result) throws SQLException { result.setValue(rs.getString(SHORT_NAME)); result.setName(rs.getString(ROLE_NAME)); } } , OptionDto.class , clientOperatorId); return result; } }
8,242
0.605193
0.605193
240
33.341667
24.396378
120
false
false
0
0
0
0
0
0
0.775
false
false
12
89397f059e8a8a74501b3b932267615275145c1a
16,973,710,775,307
495bb36aabe304d817b805642d9be3862872428a
/cn-spark/src/main/java/utils/JdbcUtils.java
0dfd1aebbd16a456c2c1c4db8ebbc2ac0cb1d0fa
[]
no_license
oym-miao/CN-Spark
https://github.com/oym-miao/CN-Spark
4356d9a770d9fba3ae18e82ccf7b32db570a39d8
da2bc650d0784650aaff91a86e91975668f32e12
refs/heads/master
2022-07-12T21:24:53.569000
2020-02-05T18:43:18
2020-02-05T18:43:18
160,645,247
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package utils; import java.sql.*; public class JdbcUtils { private static String url = "jdbc:mysql://oym2.com:3306/mysql?createDatabaseIfNotExist=true&amp;useSSL=false&amp;autoReconnect=true&amp;failOverReadOnly=false&amp;maxReconnects=10&amp;characterEncoding=UTF-8"; private static String user = "root"; private static String pwd = "miao"; private JdbcUtils() { } public static void main(String[] args){ try{ Connection conn=getConnection(); /* String sql = "insert into textFile (value) values(?)"; PreparedStatement pstmt; pstmt = (PreparedStatement) conn.prepareStatement(sql); pstmt.setString(1,"test"); pstmt.executeUpdate(); free(pstmt,conn);*/ System.out.println("******"+conn); }catch (SQLException e){ e.printStackTrace(); } } // 1、注册驱动oracle.jdbc.driver.OracleDriver static { try { Class.forName("com.mysql.jdbc.Driver"); } catch (ClassNotFoundException e) { e.printStackTrace(); System.out.println("数据库驱动加载失败!"); } } // 2、建立一个连接 public static Connection getConnection() throws SQLException { return DriverManager.getConnection(url, user, pwd); } // 3、关闭资源 public static void free(Statement stmt, Connection conn) { try { if (stmt != null) stmt.close(); } catch (SQLException e) { e.printStackTrace(); } finally { try { if (conn != null) conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } // 3、关闭资源2 public static void free2(ResultSet rs, Statement stmt, Connection conn) { try { if (rs != null) rs.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { try { if (stmt != null) stmt.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { try { if (conn != null) conn.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } }
UTF-8
Java
2,291
java
JdbcUtils.java
Java
[ { "context": "ring user = \"root\";\n\tprivate static String pwd = \"miao\";\n\n\tprivate JdbcUtils() {\n\n\t}\n\n\tpublic static voi", "end": 344, "score": 0.9990624785423279, "start": 340, "tag": "PASSWORD", "value": "miao" } ]
null
[]
package utils; import java.sql.*; public class JdbcUtils { private static String url = "jdbc:mysql://oym2.com:3306/mysql?createDatabaseIfNotExist=true&amp;useSSL=false&amp;autoReconnect=true&amp;failOverReadOnly=false&amp;maxReconnects=10&amp;characterEncoding=UTF-8"; private static String user = "root"; private static String pwd = "<PASSWORD>"; private JdbcUtils() { } public static void main(String[] args){ try{ Connection conn=getConnection(); /* String sql = "insert into textFile (value) values(?)"; PreparedStatement pstmt; pstmt = (PreparedStatement) conn.prepareStatement(sql); pstmt.setString(1,"test"); pstmt.executeUpdate(); free(pstmt,conn);*/ System.out.println("******"+conn); }catch (SQLException e){ e.printStackTrace(); } } // 1、注册驱动oracle.jdbc.driver.OracleDriver static { try { Class.forName("com.mysql.jdbc.Driver"); } catch (ClassNotFoundException e) { e.printStackTrace(); System.out.println("数据库驱动加载失败!"); } } // 2、建立一个连接 public static Connection getConnection() throws SQLException { return DriverManager.getConnection(url, user, pwd); } // 3、关闭资源 public static void free(Statement stmt, Connection conn) { try { if (stmt != null) stmt.close(); } catch (SQLException e) { e.printStackTrace(); } finally { try { if (conn != null) conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } // 3、关闭资源2 public static void free2(ResultSet rs, Statement stmt, Connection conn) { try { if (rs != null) rs.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { try { if (stmt != null) stmt.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { try { if (conn != null) conn.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } }
2,297
0.581949
0.575213
88
24.318182
26.789391
210
false
false
0
0
0
0
0
0
1.943182
false
false
12
76bf5630c766796e67f02d8e634ba3f8f880dc28
8,280,696,967,521
3be85a458353321c726b447370b32bceef7a1c4f
/src/view/TheQuest3.java
f2f5645ff5e050b968bce654f979a3caab3b91b6
[]
no_license
newprofano/JogoQuix-troll
https://github.com/newprofano/JogoQuix-troll
78045e8a52565110fdae118e374966e3e8e46e7a
ed513e4f272f309d0381e446c55f4f81831b121f
refs/heads/master
2020-04-04T16:47:08.457000
2019-03-13T06:31:03
2019-03-13T06:31:03
156,093,199
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package view; import javax.swing.JOptionPane; /* * 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. */ /** * * @author PC-PC */ public class TheQuest3 extends javax.swing.JFrame { /** * Creates new form TheQuest */ public TheQuest3() { initComponents(); txPrayer.setText(TheGame.getNickName()); txPontos.setText(""+TheGame.getPontos()); lbContador.setText("0"); this.setLocationRelativeTo(null); } /** * 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() { txPrayer = new javax.swing.JLabel(); txPontos = new javax.swing.JLabel(); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); lbContador = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); jLabel6 = new javax.swing.JLabel(); txResposta3 = new javax.swing.JTextField(); jButton1 = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); addMouseWheelListener(new java.awt.event.MouseWheelListener() { public void mouseWheelMoved(java.awt.event.MouseWheelEvent evt) { Scrolando(evt); } }); jLabel1.setForeground(new java.awt.Color(0, 0, 255)); jLabel1.setText("Prayer:"); jLabel2.setForeground(new java.awt.Color(0, 0, 255)); jLabel2.setText("Pontos:"); jLabel3.setText("Perguntas"); jLabel4.setText("<html>3)Meu Principal Objetivo com sa merda de joguin é brincar, então para<br>brincar um pouco, para achar a resposta desta alternativa rode o scroll<br>cada vez que você usar o scroll seu contador sera acrescentado em +1, o limite dele é 50 e depois 0 novamente, em determinado numero a resposta aparecerá Em algum Lugar da tela, se vire xD.</html>"); lbContador.setText("contador"); jLabel5.setText("Contador->"); txResposta3.setText("Coloque a resposta aqui"); txResposta3.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { txResposta3MouseClicked(evt); } }); jButton1.setText("enviar"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(txResposta3, javax.swing.GroupLayout.PREFERRED_SIZE, 278, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addContainerGap()) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel2) .addComponent(jLabel1)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(txPrayer, javax.swing.GroupLayout.PREFERRED_SIZE, 128, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(txPontos))) .addGroup(layout.createSequentialGroup() .addGap(98, 98, 98) .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 101, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(43, 43, 43) .addComponent(jLabel5) .addGap(2, 2, 2) .addComponent(lbContador)) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 371, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel6))) .addGap(0, 0, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(txPrayer) .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 14, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(txPontos) .addComponent(jLabel2)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel3) .addComponent(lbContador) .addComponent(jLabel5)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 140, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel6) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(txResposta3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton1)) .addContainerGap(29, Short.MAX_VALUE)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void Scrolando(java.awt.event.MouseWheelEvent evt) {//GEN-FIRST:event_Scrolando // TODO add your handling code here: int contador = Integer.parseInt(lbContador.getText()); if (contador <50) { contador++; lbContador.setText(""+contador); jLabel3.setText("Perguntas"); if (contador == 37) { jLabel3.setText("alone"); } } else{ contador = 0; lbContador.setText(""+contador); } }//GEN-LAST:event_Scrolando private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed // TODO add your handling code here: if ("alone".equals(txResposta3.getText())) { TheGame.setPontos(+30); new TheQuest4().setVisible(true); dispose(); } else{ new TheGameOver().setVisible(true); dispose(); } }//GEN-LAST:event_jButton1ActionPerformed private void txResposta3MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_txResposta3MouseClicked // TODO add your handling code here: txResposta3.setText(""); }//GEN-LAST:event_txResposta3MouseClicked /** * @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(TheQuest1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(TheQuest1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(TheQuest1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(TheQuest1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new TheQuest1().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButton1; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JLabel lbContador; private javax.swing.JLabel txPontos; private javax.swing.JLabel txPrayer; private javax.swing.JTextField txResposta3; // End of variables declaration//GEN-END:variables }
UTF-8
Java
10,935
java
TheQuest3.java
Java
[ { "context": "the template in the editor.\n */\n\n/**\n *\n * @author PC-PC\n */\npublic class TheQuest3 extends javax.swing.JF", "end": 258, "score": 0.9995284676551819, "start": 253, "tag": "USERNAME", "value": "PC-PC" } ]
null
[]
package view; import javax.swing.JOptionPane; /* * 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. */ /** * * @author PC-PC */ public class TheQuest3 extends javax.swing.JFrame { /** * Creates new form TheQuest */ public TheQuest3() { initComponents(); txPrayer.setText(TheGame.getNickName()); txPontos.setText(""+TheGame.getPontos()); lbContador.setText("0"); this.setLocationRelativeTo(null); } /** * 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() { txPrayer = new javax.swing.JLabel(); txPontos = new javax.swing.JLabel(); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); lbContador = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); jLabel6 = new javax.swing.JLabel(); txResposta3 = new javax.swing.JTextField(); jButton1 = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); addMouseWheelListener(new java.awt.event.MouseWheelListener() { public void mouseWheelMoved(java.awt.event.MouseWheelEvent evt) { Scrolando(evt); } }); jLabel1.setForeground(new java.awt.Color(0, 0, 255)); jLabel1.setText("Prayer:"); jLabel2.setForeground(new java.awt.Color(0, 0, 255)); jLabel2.setText("Pontos:"); jLabel3.setText("Perguntas"); jLabel4.setText("<html>3)Meu Principal Objetivo com sa merda de joguin é brincar, então para<br>brincar um pouco, para achar a resposta desta alternativa rode o scroll<br>cada vez que você usar o scroll seu contador sera acrescentado em +1, o limite dele é 50 e depois 0 novamente, em determinado numero a resposta aparecerá Em algum Lugar da tela, se vire xD.</html>"); lbContador.setText("contador"); jLabel5.setText("Contador->"); txResposta3.setText("Coloque a resposta aqui"); txResposta3.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { txResposta3MouseClicked(evt); } }); jButton1.setText("enviar"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(txResposta3, javax.swing.GroupLayout.PREFERRED_SIZE, 278, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addContainerGap()) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel2) .addComponent(jLabel1)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(txPrayer, javax.swing.GroupLayout.PREFERRED_SIZE, 128, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(txPontos))) .addGroup(layout.createSequentialGroup() .addGap(98, 98, 98) .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 101, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(43, 43, 43) .addComponent(jLabel5) .addGap(2, 2, 2) .addComponent(lbContador)) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 371, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel6))) .addGap(0, 0, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(txPrayer) .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 14, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(txPontos) .addComponent(jLabel2)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel3) .addComponent(lbContador) .addComponent(jLabel5)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 140, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel6) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(txResposta3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton1)) .addContainerGap(29, Short.MAX_VALUE)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void Scrolando(java.awt.event.MouseWheelEvent evt) {//GEN-FIRST:event_Scrolando // TODO add your handling code here: int contador = Integer.parseInt(lbContador.getText()); if (contador <50) { contador++; lbContador.setText(""+contador); jLabel3.setText("Perguntas"); if (contador == 37) { jLabel3.setText("alone"); } } else{ contador = 0; lbContador.setText(""+contador); } }//GEN-LAST:event_Scrolando private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed // TODO add your handling code here: if ("alone".equals(txResposta3.getText())) { TheGame.setPontos(+30); new TheQuest4().setVisible(true); dispose(); } else{ new TheGameOver().setVisible(true); dispose(); } }//GEN-LAST:event_jButton1ActionPerformed private void txResposta3MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_txResposta3MouseClicked // TODO add your handling code here: txResposta3.setText(""); }//GEN-LAST:event_txResposta3MouseClicked /** * @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(TheQuest1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(TheQuest1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(TheQuest1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(TheQuest1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new TheQuest1().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButton1; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JLabel lbContador; private javax.swing.JLabel txPontos; private javax.swing.JLabel txPrayer; private javax.swing.JTextField txResposta3; // End of variables declaration//GEN-END:variables }
10,935
0.620677
0.608875
243
43.979424
40.14341
378
false
false
0
0
0
0
0
0
0.526749
false
false
12
663e3168bff706e3b4249bd9ad7483426d6e056a
7,292,854,489,180
2927b820b25e5ce6bee8e8965b7c9c940410e1c5
/app/src/main/java/com/padcmyanmar/myapplication/delegates/JobItemDelegate.java
b6ea4f2606ed78e04dea7de249825c1fb5183430
[ "MIT" ]
permissive
SuLaiYee/haulio-technical-SLY
https://github.com/SuLaiYee/haulio-technical-SLY
7dcf18f8dda52f82701584983228a69758d2f2e4
f3a499a244bbae0832f3ca39a9eb3de5e736595d
refs/heads/master
2020-12-19T20:11:55.863000
2020-01-24T08:45:03
2020-01-24T08:45:03
235,840,154
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.padcmyanmar.myapplication.delegates; import com.padcmyanmar.myapplication.data.vos.JobVO; public interface JobItemDelegate { void onTapJobItem(JobVO jobVO); }
UTF-8
Java
177
java
JobItemDelegate.java
Java
[]
null
[]
package com.padcmyanmar.myapplication.delegates; import com.padcmyanmar.myapplication.data.vos.JobVO; public interface JobItemDelegate { void onTapJobItem(JobVO jobVO); }
177
0.813559
0.813559
7
24.285715
21.585142
52
false
false
0
0
0
0
0
0
0.428571
false
false
12
5c70ed63a6d69f0157d1eca137dbe09f23c168f7
1,013,612,340,277
5a03c73af0d28181c3998c6f5318a43d1af86607
/app/src/main/java/test/com/chestnut/SoundTouch/MainActivity.java
c88f8465a56b9d4025c3e3941933ac1f6a0ff17c
[]
no_license
ChestnutPlus/ModulesSoundTouch
https://github.com/ChestnutPlus/ModulesSoundTouch
803e4b77799fc0452f5e12f3904689db88ac84c2
5ae8db58c116acd84a43b3702fc5b1e6849b3153
refs/heads/master
2021-01-23T06:09:27.773000
2018-10-10T07:53:03
2018-10-10T07:53:03
86,338,356
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package test.com.chestnut.SoundTouch; import android.app.Activity; import android.os.Bundle; import android.os.Environment; import android.view.View; import com.chestnut.common.helper.MediaPlayerHelper; import com.chestnut.common.utils.LogUtils; import io.reactivex.schedulers.Schedulers; public class MainActivity extends Activity implements View.OnClickListener{ private Recorder recorder = new Recorder(); private MediaPlayerHelper mediaPlayerHelper = new MediaPlayerHelper(); private String wav; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); findViewById(R.id.btn_play).setOnClickListener(this); findViewById(R.id.btn_start).setOnClickListener(this); findViewById(R.id.btn_end).setOnClickListener(this); mediaPlayerHelper.init(this); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.btn_play: if (wav!=null) { mediaPlayerHelper.setUrl(wav); mediaPlayerHelper.play(); } break; case R.id.btn_start: wav = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM)+"/_"+ System.currentTimeMillis()+".wav"; recorder.record(wav,1,-3,1) .subscribeOn(Schedulers.newThread()) .subscribe(integer -> { LogUtils.i("MainActivity","record:"+integer); }); break; case R.id.btn_end: recorder.stop(); break; } } }
UTF-8
Java
1,745
java
MainActivity.java
Java
[]
null
[]
package test.com.chestnut.SoundTouch; import android.app.Activity; import android.os.Bundle; import android.os.Environment; import android.view.View; import com.chestnut.common.helper.MediaPlayerHelper; import com.chestnut.common.utils.LogUtils; import io.reactivex.schedulers.Schedulers; public class MainActivity extends Activity implements View.OnClickListener{ private Recorder recorder = new Recorder(); private MediaPlayerHelper mediaPlayerHelper = new MediaPlayerHelper(); private String wav; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); findViewById(R.id.btn_play).setOnClickListener(this); findViewById(R.id.btn_start).setOnClickListener(this); findViewById(R.id.btn_end).setOnClickListener(this); mediaPlayerHelper.init(this); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.btn_play: if (wav!=null) { mediaPlayerHelper.setUrl(wav); mediaPlayerHelper.play(); } break; case R.id.btn_start: wav = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM)+"/_"+ System.currentTimeMillis()+".wav"; recorder.record(wav,1,-3,1) .subscribeOn(Schedulers.newThread()) .subscribe(integer -> { LogUtils.i("MainActivity","record:"+integer); }); break; case R.id.btn_end: recorder.stop(); break; } } }
1,745
0.606877
0.605158
51
33.215687
25.663214
136
false
false
0
0
0
0
0
0
0.588235
false
false
12
d104422282f9566cd925789493838c883e58b810
27,504,970,575,927
a0239b84bac9751ca3cf3e44bcc16e6b0483dffd
/src/main/java/com/czu/kof/dea/SocialMediaAlghorithmCZU/alghorithm/DeaRecord.java
9d193e57b8e8acf8639d154bfd4de821f1d909e9
[]
no_license
OndrejS1/CZUDea
https://github.com/OndrejS1/CZUDea
e6fd4e797857ad94ff55c7b50dba8a3e7b37b908
14eb700034ab58edd42530d364c0542beefdbee9
refs/heads/master
2021-07-03T12:20:30.944000
2019-10-20T15:40:49
2019-10-20T15:40:49
216,385,063
1
0
null
false
2021-03-19T20:22:11
2019-10-20T15:38:00
2019-11-17T22:46:22
2021-03-19T20:22:09
84
0
0
1
Java
false
false
package com.czu.kof.dea.SocialMediaAlghorithmCZU.alghorithm; public class DeaRecord { /** * The values of features that are considered as input. It can be empty if * if no input is assumed. */ private final double[] input; /** * The values of features that are considered as output. */ private final double[] output; /** * Constructor of DEA Record with only output * * @param output The output part of our data record */ public DeaRecord(double[] output) { this.output=output; this.input= new double[0]; } /** * Constructor of DEA Record with both input and output * * @param output The output part of our data record * @param input The input part of our data record */ public DeaRecord(double[] output, double[] input) { this.output=output; this.input=input; } /** * Getter for input * * @return Returns the input part of our data. */ public double[] getInput() { return input; } /** * Getter for output * * @return Returns the output part of our data. */ public double[] getOutput() { return output; } }
UTF-8
Java
1,251
java
DeaRecord.java
Java
[]
null
[]
package com.czu.kof.dea.SocialMediaAlghorithmCZU.alghorithm; public class DeaRecord { /** * The values of features that are considered as input. It can be empty if * if no input is assumed. */ private final double[] input; /** * The values of features that are considered as output. */ private final double[] output; /** * Constructor of DEA Record with only output * * @param output The output part of our data record */ public DeaRecord(double[] output) { this.output=output; this.input= new double[0]; } /** * Constructor of DEA Record with both input and output * * @param output The output part of our data record * @param input The input part of our data record */ public DeaRecord(double[] output, double[] input) { this.output=output; this.input=input; } /** * Getter for input * * @return Returns the input part of our data. */ public double[] getInput() { return input; } /** * Getter for output * * @return Returns the output part of our data. */ public double[] getOutput() { return output; } }
1,251
0.580336
0.579536
57
20.947369
21.324083
78
false
false
0
0
0
0
0
0
0.175439
false
false
12
71073a622f9c3630449476e5fc46cdfde55f8953
21,680,994,968,909
ec08bdc56491123fc4d77bbb29bc43fea82de263
/src/Personnels/CDD.java
36b10af5e8417eb2ae38f1f1c5e87a2baf56381b
[]
no_license
LNayet/POA
https://github.com/LNayet/POA
7db8dd90eff9191b13048b71fb485f3df6fd9f14
fa773e1b291cf11407a3f6fbceef384f9daf65fb
refs/heads/master
2021-07-07T23:29:49.727000
2017-10-02T15:30:08
2017-10-02T15:30:08
104,768,456
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package Personnels; import java.util.Date; /** * Created by lunayetn on 25/09/2017. */ public class CDD extends Contrat { private Date fin; public CDD(double salaire, Date debut, Date fin) { super(salaire, debut); this.fin=fin; } public Date getFin() { return fin; } public void setFin(Date fin) { this.fin = fin; } }
UTF-8
Java
388
java
CDD.java
Java
[ { "context": "onnels;\n\nimport java.util.Date;\n\n/**\n * Created by lunayetn on 25/09/2017.\n */\npublic class CDD extends Contr", "end": 71, "score": 0.9996735453605652, "start": 63, "tag": "USERNAME", "value": "lunayetn" } ]
null
[]
package Personnels; import java.util.Date; /** * Created by lunayetn on 25/09/2017. */ public class CDD extends Contrat { private Date fin; public CDD(double salaire, Date debut, Date fin) { super(salaire, debut); this.fin=fin; } public Date getFin() { return fin; } public void setFin(Date fin) { this.fin = fin; } }
388
0.585052
0.564433
23
15.869565
14.602872
52
false
false
0
0
0
0
0
0
0.434783
false
false
12
ac83f1241cbe33886afd37a2619e89aae567516c
33,225,867,071,309
fdcbbe523d639d1c12dc63b5f228eda74b61b34c
/src/Solution804.java
8c1b9dfcb589f1b76dcdf97d0357bd195a270c89
[]
no_license
mattli4/leetcode
https://github.com/mattli4/leetcode
db356266e298d35119f30e60556ee80e6814fa4b
a2c5c509515cd34e9b74ca460d88a0663952dda9
refs/heads/master
2022-03-18T22:11:53.417000
2022-02-09T13:22:10
2022-02-09T13:22:10
100,368,623
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.util.HashMap; import java.util.HashSet; public class Solution804 { public int uniqueMorseRepresentations(String[] words) { int n = words.length; if (n == 0) return 0; String [] val = {".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."}; HashMap<Integer, String> hp = new HashMap<>(); HashSet<String> hs = new HashSet<>(); for(int i = 0; i < 26; i++){ hp.put('a' + i, val[i]); } for(String str:words){ String s = ""; for(int i = 0; i < str.length(); i++){ s += hp.get((int)str.charAt(i)); } hs.add(s); } return hs.size(); } public static void main(String[] args) { String []a = {"gin", "zen", "gig", "msg"}; new Solution804().uniqueMorseRepresentations(a); } }
UTF-8
Java
971
java
Solution804.java
Java
[]
null
[]
import java.util.HashMap; import java.util.HashSet; public class Solution804 { public int uniqueMorseRepresentations(String[] words) { int n = words.length; if (n == 0) return 0; String [] val = {".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."}; HashMap<Integer, String> hp = new HashMap<>(); HashSet<String> hs = new HashSet<>(); for(int i = 0; i < 26; i++){ hp.put('a' + i, val[i]); } for(String str:words){ String s = ""; for(int i = 0; i < str.length(); i++){ s += hp.get((int)str.charAt(i)); } hs.add(s); } return hs.size(); } public static void main(String[] args) { String []a = {"gin", "zen", "gig", "msg"}; new Solution804().uniqueMorseRepresentations(a); } }
971
0.406797
0.394439
28
33.67857
34.279369
186
false
false
0
0
0
0
0
0
1.714286
false
false
12
5097fd0cb3b119ec861836374f61d09711fb09be
8,804,683,019,236
8baea93ee2c1458a777d9921bcd624b01e584c8f
/src/Player.java
571091d1b8d3984a517c6d78507ead93ab982da4
[]
no_license
maciejGolebio/MinMaxTicTacToe
https://github.com/maciejGolebio/MinMaxTicTacToe
6c145c416f60b9f5ab7a3ab732151ff4b248296e
691dce56d3d091473c0a97e719c32cfc57b03ee0
refs/heads/master
2020-05-30T04:41:40.662000
2019-05-31T06:56:05
2019-05-31T06:56:05
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
public interface Player { boolean makeMove(); }
UTF-8
Java
53
java
Player.java
Java
[]
null
[]
public interface Player { boolean makeMove(); }
53
0.679245
0.679245
3
16.333334
10.873004
25
false
false
0
0
0
0
0
0
0.333333
false
false
12
7b0528f61970c96f97807d13745720f7bd32f4d2
28,157,805,596,764
2acdb7eb861c84a3bd96019db95f3a542f374935
/src/ImgDiffPercent.java
b2428c5d21c3eaa7aa44bc1ab3f50d959504a5fa
[]
no_license
manirajmkr/CI
https://github.com/manirajmkr/CI
0e672e265cc191d07aa0d1fd3ccfa9e63311265f
88543067f34a1df7847f925646dc5630fd49e5a3
refs/heads/master
2021-01-10T07:50:53.752000
2016-03-22T13:04:02
2016-03-22T13:04:02
54,473,196
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.awt.image.BufferedImage; import java.awt.image.DataBufferByte; import javax.imageio.ImageIO; import org.apache.commons.io.FileUtils; import org.openqa.selenium.OutputType; import org.openqa.selenium.TakesScreenshot; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; public class ImgDiffPercent { static long currentMsec; static long end,MaxTolerant; static List<String> Initiallist = new ArrayList<String>(); static List<String> AllImgList = new ArrayList<String>(); static List<String> Finallist = new ArrayList<String>(); static List<String> FinalListWithOutBlank = new ArrayList<String>(); static List<String> Templist = new ArrayList<String>(); static int scrCount=1; static int part=1; static int maxlimt=0; public static void main(String str[]) throws IOException, InterruptedException { WebDriver driver=new FirefoxDriver(); //Load the url driver.get("http://publish.rcc.bps-core.com/creative_preview/rtb/2271/46/d9/46d96486d2e7514aed5f3b739fcca765.shtml"); getScreenshot(driver, 0, 0); //Get Master image long startTime = System.nanoTime(); //Adding the master screentshot directly into the FinallList Finallist.add("C:\\Users\\Administrator\\Desktop\\Pagesource\\Part0Screenshot1.png"); FinalListWithOutBlank.add("C:\\Users\\Administrator\\Desktop\\Pagesource\\Part0Screenshot1.png"); currentMsec= System.currentTimeMillis(); end = currentMsec+5000; MaxTolerant=currentMsec+300000; //Getting the next image imediate after the Master image getScreenshot(driver, 1, 10); //Looping for 10sec for change in ads while(System.currentTimeMillis() < end && System.currentTimeMillis() < MaxTolerant) { if(scrCount>1) { getPicDiff(driver); // System.out.println("Main call"); } } //Looping for deleting the unwanted image files for(int StrartPart=1;StrartPart<part;StrartPart++) { int totalPart=0; double PictureIndex=0.0; for(int Start=0;Start<(Initiallist.size()-1);Start++) { String srt; String str1; if(part>9) { srt=Initiallist.get(Start); str1="Part"+StrartPart+"Screen"; } else { srt=Initiallist.get(Start); str1="Part"+StrartPart; } if(srt.contains(str1)) { // System.out.println(Initiallist.get(Start)); Templist.add(Initiallist.get(Start)); totalPart++; } } // System.out.println("So the total is ======> "+totalPart); PictureIndex=totalPart/1.3; if(Math.round(PictureIndex)>0 && Templist.size()>1) { if(Math.round(PictureIndex) > (Templist.size()-1)) { PictureIndex=totalPart/2; } Finallist.add(Templist.get((int) Math.round(PictureIndex))); Templist = new ArrayList<String>(); } // System.out.println(Templist.size()); if(Templist.size()==1) { Finallist.add(Templist.get(0)); Templist = new ArrayList<String>(); } } //Removing the unwanted pictures from the local storage AllImgList.removeAll(Finallist); for (String path : AllImgList) { try { // System.out.println(path); File f = new File(path); f.delete(); } catch(Exception e) { System.out.println("Exception"+e); } } //RemovING blank images from the finallist for (String pic : Finallist) { BufferedImage image = ImageIO.read(new File(pic)); final byte[] pixels = ((DataBufferByte) image.getRaster().getDataBuffer()).getData(); final int width = image.getWidth(); final int height = image.getHeight(); final boolean hasAlphaChannel = image.getAlphaRaster() != null; boolean blankImage=true; int[][] result = new int[height][width]; if (hasAlphaChannel) { final int pixelLength = 4; for (int pixel = 0, row = 0, col = 0; pixel < pixels.length; pixel += pixelLength) { int argb = 0; argb += (((int) pixels[pixel] & 0xff) << 24); // alpha argb += ((int) pixels[pixel + 1] & 0xff); // blue argb += (((int) pixels[pixel + 2] & 0xff) << 8); // green argb += (((int) pixels[pixel + 3] & 0xff) << 16); // red result[row][col] = argb; if(result[row][col]!=result[0][0]) { blankImage=false; } col++; if (col == width) { col = 0; row++; } } } else { final int pixelLength = 3; for (int pixel = 0, row = 0, col = 0; pixel < pixels.length; pixel += pixelLength) { int argb = 0; argb += -16777216; // 255 alpha argb += ((int) pixels[pixel] & 0xff); // blue argb += (((int) pixels[pixel + 1] & 0xff) << 8); // green argb += (((int) pixels[pixel + 2] & 0xff) << 16); // red result[row][col] = argb; if(result[row][col]!=result[0][0]) { blankImage=false; } col++; if (col == width) { col = 0; row++; } } } if(blankImage==true) { try { System.out.println("Blank image found and its deleted"); File f = new File(pic); f.delete(); } catch(Exception e) { System.out.println("Exception"+e); } }else { FinalListWithOutBlank.add(pic); } } //FinalListWithOutBlank list will have the final screenshot list System.out.println("FinalListWithOutBlank size"+FinalListWithOutBlank.size()); if(FinalListWithOutBlank.size()==2) { System.out.println("Its an static display creative "); // File f = new File(FinalListWithOutBlank.get(1)); // f.delete(); FinalListWithOutBlank.remove(1); } else{ if(FinalListWithOutBlank.size()==0) { System.out.println("Its an Blank creative "); }else{ System.out.println("Its an Animated or dynamic display creative ");} } long endTime = System.nanoTime(); System.out.println("total execution time==>"+(double)(endTime - startTime) / 1000000000.0+"seconds"); System.out.println("FinalListWithOutBlank "+FinalListWithOutBlank); } //Getting screenshot public static void getScreenshot(WebDriver driver, int partCount, int sleep) throws InterruptedException { Thread.sleep(sleep); File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE); try { FileUtils.copyFile(scrFile, new File("C:\\Users\\Administrator\\Desktop\\Pagesource\\Part"+partCount+"Screenshot"+scrCount+".png")); } catch (IOException e) { e.printStackTrace(); } Initiallist.add("C:\\Users\\Administrator\\Desktop\\Pagesource\\Part"+partCount+"Screenshot"+scrCount+".png"); AllImgList.add("C:\\Users\\Administrator\\Desktop\\Pagesource\\Part"+partCount+"Screenshot"+scrCount+".png"); scrCount++; } //Finding the diffreence between the images public static void getPicDiff(WebDriver driver) throws IOException, InterruptedException { Boolean CheckNewImage=true; Boolean CheckSameImage=true; BufferedImage img = null; BufferedImage img1 = null; double changePercent = 0.40; if(Initiallist.size()==1) { CheckNewImage=false; CheckSameImage=false; } for(int j=0;j<(Initiallist.size()-1);j++) { try { img = ImageIO.read(new File(Initiallist.get(Initiallist.size()-1))); img1 =ImageIO.read(new File(Initiallist.get(j))); // System.out.println("Comparing last element "+(Initiallist.get(Initiallist.size()-1))+"\t with mylist\t"+ Initiallist.get(j)); } catch (IOException e) { e.printStackTrace(); } int width1 = img.getWidth(null); // int width2 = bimg1.getWidth(null); int height1 = img.getHeight(null); // int height2 = bimg1.getHeight(null); // if ((width1 != width2) || (height1 != height2)) // { // System.err.println("Error: Images dimensions mismatch"); // } long diff = 0; for (int y = 0; y < height1; y++) { for (int x = 0; x < width1; x++) { int rgb1 = img.getRGB(x, y); int rgb2 = img1.getRGB(x, y); int r1 = (rgb1 >> 16) & 0xff; int g1 = (rgb1 >> 8) & 0xff; int b1 = (rgb1 ) & 0xff; int r2 = (rgb2 >> 16) & 0xff; int g2 = (rgb2 >> 8) & 0xff; int b2 = (rgb2 ) & 0xff; diff += Math.abs(r1 - r2); diff += Math.abs(g1 - g2); diff += Math.abs(b1 - b2); } } double n = width1 * height1 * 3; double p = diff / n / 255.0; // System.out.println("diff percent: " + (p * 100.0)); //Considering changePercent for determine the new image if((p * 100.0)<=changePercent) { CheckNewImage=false; if((p * 100.0) == 0.0) { CheckSameImage=false; Initiallist.remove(Initiallist.size()-1); } } } if(CheckNewImage==true || CheckSameImage==true) { getScreenshot(driver, part,0); part++; currentMsec= System.currentTimeMillis(); end = currentMsec+5000; }else { getScreenshot(driver, part,0); } } }
UTF-8
Java
10,386
java
ImgDiffPercent.java
Java
[]
null
[]
import java.awt.image.BufferedImage; import java.awt.image.DataBufferByte; import javax.imageio.ImageIO; import org.apache.commons.io.FileUtils; import org.openqa.selenium.OutputType; import org.openqa.selenium.TakesScreenshot; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; public class ImgDiffPercent { static long currentMsec; static long end,MaxTolerant; static List<String> Initiallist = new ArrayList<String>(); static List<String> AllImgList = new ArrayList<String>(); static List<String> Finallist = new ArrayList<String>(); static List<String> FinalListWithOutBlank = new ArrayList<String>(); static List<String> Templist = new ArrayList<String>(); static int scrCount=1; static int part=1; static int maxlimt=0; public static void main(String str[]) throws IOException, InterruptedException { WebDriver driver=new FirefoxDriver(); //Load the url driver.get("http://publish.rcc.bps-core.com/creative_preview/rtb/2271/46/d9/46d96486d2e7514aed5f3b739fcca765.shtml"); getScreenshot(driver, 0, 0); //Get Master image long startTime = System.nanoTime(); //Adding the master screentshot directly into the FinallList Finallist.add("C:\\Users\\Administrator\\Desktop\\Pagesource\\Part0Screenshot1.png"); FinalListWithOutBlank.add("C:\\Users\\Administrator\\Desktop\\Pagesource\\Part0Screenshot1.png"); currentMsec= System.currentTimeMillis(); end = currentMsec+5000; MaxTolerant=currentMsec+300000; //Getting the next image imediate after the Master image getScreenshot(driver, 1, 10); //Looping for 10sec for change in ads while(System.currentTimeMillis() < end && System.currentTimeMillis() < MaxTolerant) { if(scrCount>1) { getPicDiff(driver); // System.out.println("Main call"); } } //Looping for deleting the unwanted image files for(int StrartPart=1;StrartPart<part;StrartPart++) { int totalPart=0; double PictureIndex=0.0; for(int Start=0;Start<(Initiallist.size()-1);Start++) { String srt; String str1; if(part>9) { srt=Initiallist.get(Start); str1="Part"+StrartPart+"Screen"; } else { srt=Initiallist.get(Start); str1="Part"+StrartPart; } if(srt.contains(str1)) { // System.out.println(Initiallist.get(Start)); Templist.add(Initiallist.get(Start)); totalPart++; } } // System.out.println("So the total is ======> "+totalPart); PictureIndex=totalPart/1.3; if(Math.round(PictureIndex)>0 && Templist.size()>1) { if(Math.round(PictureIndex) > (Templist.size()-1)) { PictureIndex=totalPart/2; } Finallist.add(Templist.get((int) Math.round(PictureIndex))); Templist = new ArrayList<String>(); } // System.out.println(Templist.size()); if(Templist.size()==1) { Finallist.add(Templist.get(0)); Templist = new ArrayList<String>(); } } //Removing the unwanted pictures from the local storage AllImgList.removeAll(Finallist); for (String path : AllImgList) { try { // System.out.println(path); File f = new File(path); f.delete(); } catch(Exception e) { System.out.println("Exception"+e); } } //RemovING blank images from the finallist for (String pic : Finallist) { BufferedImage image = ImageIO.read(new File(pic)); final byte[] pixels = ((DataBufferByte) image.getRaster().getDataBuffer()).getData(); final int width = image.getWidth(); final int height = image.getHeight(); final boolean hasAlphaChannel = image.getAlphaRaster() != null; boolean blankImage=true; int[][] result = new int[height][width]; if (hasAlphaChannel) { final int pixelLength = 4; for (int pixel = 0, row = 0, col = 0; pixel < pixels.length; pixel += pixelLength) { int argb = 0; argb += (((int) pixels[pixel] & 0xff) << 24); // alpha argb += ((int) pixels[pixel + 1] & 0xff); // blue argb += (((int) pixels[pixel + 2] & 0xff) << 8); // green argb += (((int) pixels[pixel + 3] & 0xff) << 16); // red result[row][col] = argb; if(result[row][col]!=result[0][0]) { blankImage=false; } col++; if (col == width) { col = 0; row++; } } } else { final int pixelLength = 3; for (int pixel = 0, row = 0, col = 0; pixel < pixels.length; pixel += pixelLength) { int argb = 0; argb += -16777216; // 255 alpha argb += ((int) pixels[pixel] & 0xff); // blue argb += (((int) pixels[pixel + 1] & 0xff) << 8); // green argb += (((int) pixels[pixel + 2] & 0xff) << 16); // red result[row][col] = argb; if(result[row][col]!=result[0][0]) { blankImage=false; } col++; if (col == width) { col = 0; row++; } } } if(blankImage==true) { try { System.out.println("Blank image found and its deleted"); File f = new File(pic); f.delete(); } catch(Exception e) { System.out.println("Exception"+e); } }else { FinalListWithOutBlank.add(pic); } } //FinalListWithOutBlank list will have the final screenshot list System.out.println("FinalListWithOutBlank size"+FinalListWithOutBlank.size()); if(FinalListWithOutBlank.size()==2) { System.out.println("Its an static display creative "); // File f = new File(FinalListWithOutBlank.get(1)); // f.delete(); FinalListWithOutBlank.remove(1); } else{ if(FinalListWithOutBlank.size()==0) { System.out.println("Its an Blank creative "); }else{ System.out.println("Its an Animated or dynamic display creative ");} } long endTime = System.nanoTime(); System.out.println("total execution time==>"+(double)(endTime - startTime) / 1000000000.0+"seconds"); System.out.println("FinalListWithOutBlank "+FinalListWithOutBlank); } //Getting screenshot public static void getScreenshot(WebDriver driver, int partCount, int sleep) throws InterruptedException { Thread.sleep(sleep); File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE); try { FileUtils.copyFile(scrFile, new File("C:\\Users\\Administrator\\Desktop\\Pagesource\\Part"+partCount+"Screenshot"+scrCount+".png")); } catch (IOException e) { e.printStackTrace(); } Initiallist.add("C:\\Users\\Administrator\\Desktop\\Pagesource\\Part"+partCount+"Screenshot"+scrCount+".png"); AllImgList.add("C:\\Users\\Administrator\\Desktop\\Pagesource\\Part"+partCount+"Screenshot"+scrCount+".png"); scrCount++; } //Finding the diffreence between the images public static void getPicDiff(WebDriver driver) throws IOException, InterruptedException { Boolean CheckNewImage=true; Boolean CheckSameImage=true; BufferedImage img = null; BufferedImage img1 = null; double changePercent = 0.40; if(Initiallist.size()==1) { CheckNewImage=false; CheckSameImage=false; } for(int j=0;j<(Initiallist.size()-1);j++) { try { img = ImageIO.read(new File(Initiallist.get(Initiallist.size()-1))); img1 =ImageIO.read(new File(Initiallist.get(j))); // System.out.println("Comparing last element "+(Initiallist.get(Initiallist.size()-1))+"\t with mylist\t"+ Initiallist.get(j)); } catch (IOException e) { e.printStackTrace(); } int width1 = img.getWidth(null); // int width2 = bimg1.getWidth(null); int height1 = img.getHeight(null); // int height2 = bimg1.getHeight(null); // if ((width1 != width2) || (height1 != height2)) // { // System.err.println("Error: Images dimensions mismatch"); // } long diff = 0; for (int y = 0; y < height1; y++) { for (int x = 0; x < width1; x++) { int rgb1 = img.getRGB(x, y); int rgb2 = img1.getRGB(x, y); int r1 = (rgb1 >> 16) & 0xff; int g1 = (rgb1 >> 8) & 0xff; int b1 = (rgb1 ) & 0xff; int r2 = (rgb2 >> 16) & 0xff; int g2 = (rgb2 >> 8) & 0xff; int b2 = (rgb2 ) & 0xff; diff += Math.abs(r1 - r2); diff += Math.abs(g1 - g2); diff += Math.abs(b1 - b2); } } double n = width1 * height1 * 3; double p = diff / n / 255.0; // System.out.println("diff percent: " + (p * 100.0)); //Considering changePercent for determine the new image if((p * 100.0)<=changePercent) { CheckNewImage=false; if((p * 100.0) == 0.0) { CheckSameImage=false; Initiallist.remove(Initiallist.size()-1); } } } if(CheckNewImage==true || CheckSameImage==true) { getScreenshot(driver, part,0); part++; currentMsec= System.currentTimeMillis(); end = currentMsec+5000; }else { getScreenshot(driver, part,0); } } }
10,386
0.542268
0.521182
326
29.85276
25.926804
140
false
false
0
0
0
0
0
0
2.791411
false
false
12
da959ea390b015bcedf6774c00543fd9cd1a0cef
19,250,043,486,077
e3418c5b383670d6d2b807caefbc23c71eb4e72f
/cdn-demo/src/main/java/com/oones/cdn/AppConfig.java
e4210c65bfad3edd7bafdf3ee9082603eb80e38d
[]
permissive
sontruong/springboot2-example
https://github.com/sontruong/springboot2-example
0b5c6e31da272cd84c0d858eded4260387d3856c
8d0efd3583b612ef10c56098f004410e6bf580cb
refs/heads/master
2021-06-17T16:14:10.020000
2021-04-18T03:54:36
2021-04-18T03:54:36
199,111,926
0
0
Apache-2.0
false
2021-04-26T20:40:24
2019-07-27T03:46:29
2021-04-18T03:52:33
2021-04-26T20:40:24
712
0
0
2
Java
false
false
/** * */ package com.oones.cdn; /** * @author son.truong * */ public class AppConfig { public static final String APPLICATION_CONSUMES = "application/json"; public static final String APPLICATION_CONTENT_TYPES = "text/plain"; }
UTF-8
Java
238
java
AppConfig.java
Java
[ { "context": "/**\n * \n */\npackage com.oones.cdn;\n\n/**\n * @author son.truong\n *\n */\npublic class AppConfig {\n\n\tpublic static f", "end": 61, "score": 0.9752025604248047, "start": 51, "tag": "USERNAME", "value": "son.truong" } ]
null
[]
/** * */ package com.oones.cdn; /** * @author son.truong * */ public class AppConfig { public static final String APPLICATION_CONSUMES = "application/json"; public static final String APPLICATION_CONTENT_TYPES = "text/plain"; }
238
0.693277
0.693277
14
16
23.342175
70
false
false
0
0
0
0
0
0
0.357143
false
false
12
aefae21fa25c5d4ad8ed2bdc04824209e1141c03
2,173,253,521,265
d3aef8ddbf952ba2c2abf4f6fcdb73fe8a9c87b5
/stella-nfe/src/main/java/br/com/caelum/stella/nfe/fluid/InfCad.java
9d61d58d06eec7f54ae2df23b6a72db3e10e7ae4
[ "Apache-2.0" ]
permissive
ronaldoaraujo/caelum-stella
https://github.com/ronaldoaraujo/caelum-stella
075a81344c1a92cb9570fe06c3f5b66fef631760
e2b787fbdaba119043104808963540a3ba7b7c4b
refs/heads/master
2021-01-15T20:33:16.010000
2013-11-21T20:53:12
2013-11-21T20:53:12
2,396,639
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package br.com.caelum.stella.nfe.fluid; @net.vidageek.fluid.annotations.FluidClass(br.com.caelum.stella.nfe.modelo.InfCad.class) public interface InfCad<T> extends net.vidageek.fluid.FluidInterface<T> { @net.vidageek.fluid.annotations.FluidField("ie") InfCad<T> withIe(java.lang.String ie); @net.vidageek.fluid.annotations.FluidField("cnpj") InfCad<T> withCnpj(java.lang.String cnpj); @net.vidageek.fluid.annotations.FluidField("cpf") InfCad<T> withCpf(java.lang.String cpf); @net.vidageek.fluid.annotations.FluidField("uf") InfCad<T> withUf(br.com.caelum.stella.nfe.modelo.TUf uf); @net.vidageek.fluid.annotations.FluidField("cSit") InfCad<T> withCSit(java.lang.String cSit); @net.vidageek.fluid.annotations.FluidField("xNome") InfCad<T> withXNome(java.lang.String xNome); @net.vidageek.fluid.annotations.FluidField("xFant") InfCad<T> withXFant(java.lang.String xFant); @net.vidageek.fluid.annotations.FluidField("xRegApur") InfCad<T> withXRegApur(java.lang.String xRegApur); @net.vidageek.fluid.annotations.FluidField("cnae") InfCad<T> withCnae(java.lang.String cnae); @net.vidageek.fluid.annotations.FluidField("dIniAtiv") InfCad<T> withDIniAtiv(java.lang.String dIniAtiv); @net.vidageek.fluid.annotations.FluidField("dUltSit") InfCad<T> withDUltSit(java.lang.String dUltSit); @net.vidageek.fluid.annotations.FluidField("dBaixa") InfCad<T> withDBaixa(java.lang.String dBaixa); @net.vidageek.fluid.annotations.FluidField("ieUnica") InfCad<T> withIeUnica(java.lang.String ieUnica); @net.vidageek.fluid.annotations.FluidField("ieAtual") InfCad<T> withIeAtual(java.lang.String ieAtual); @net.vidageek.fluid.annotations.FluidField("ender") Endereco<InfCad<T>> withEnder(); }
UTF-8
Java
1,809
java
InfCad.java
Java
[]
null
[]
package br.com.caelum.stella.nfe.fluid; @net.vidageek.fluid.annotations.FluidClass(br.com.caelum.stella.nfe.modelo.InfCad.class) public interface InfCad<T> extends net.vidageek.fluid.FluidInterface<T> { @net.vidageek.fluid.annotations.FluidField("ie") InfCad<T> withIe(java.lang.String ie); @net.vidageek.fluid.annotations.FluidField("cnpj") InfCad<T> withCnpj(java.lang.String cnpj); @net.vidageek.fluid.annotations.FluidField("cpf") InfCad<T> withCpf(java.lang.String cpf); @net.vidageek.fluid.annotations.FluidField("uf") InfCad<T> withUf(br.com.caelum.stella.nfe.modelo.TUf uf); @net.vidageek.fluid.annotations.FluidField("cSit") InfCad<T> withCSit(java.lang.String cSit); @net.vidageek.fluid.annotations.FluidField("xNome") InfCad<T> withXNome(java.lang.String xNome); @net.vidageek.fluid.annotations.FluidField("xFant") InfCad<T> withXFant(java.lang.String xFant); @net.vidageek.fluid.annotations.FluidField("xRegApur") InfCad<T> withXRegApur(java.lang.String xRegApur); @net.vidageek.fluid.annotations.FluidField("cnae") InfCad<T> withCnae(java.lang.String cnae); @net.vidageek.fluid.annotations.FluidField("dIniAtiv") InfCad<T> withDIniAtiv(java.lang.String dIniAtiv); @net.vidageek.fluid.annotations.FluidField("dUltSit") InfCad<T> withDUltSit(java.lang.String dUltSit); @net.vidageek.fluid.annotations.FluidField("dBaixa") InfCad<T> withDBaixa(java.lang.String dBaixa); @net.vidageek.fluid.annotations.FluidField("ieUnica") InfCad<T> withIeUnica(java.lang.String ieUnica); @net.vidageek.fluid.annotations.FluidField("ieAtual") InfCad<T> withIeAtual(java.lang.String ieAtual); @net.vidageek.fluid.annotations.FluidField("ender") Endereco<InfCad<T>> withEnder(); }
1,809
0.735766
0.735766
51
34.490196
26.455566
88
false
false
0
0
0
0
0
0
0.313726
false
false
12
c8ab8f7a4478727eb32ca3837c15e829e188785a
15,401,752,784,424
64ee2c0f8caddc5aa8af3f14e125cd6b46de6fe0
/EidI_A2.3/src/NormalTime.java
9d3680eed49496ae1b9df2bde61ed27060ea9a08
[]
no_license
Darkluke1111/EidI-Blatt2
https://github.com/Darkluke1111/EidI-Blatt2
b3f429018a916e27a111bbed3962d6f47a3e28a9
4d28b53af68e1fb635d78d2e3ab71f4386d8faef
refs/heads/master
2018-04-21T06:59:54.077000
2017-11-29T20:45:58
2017-11-29T20:45:58
90,956,146
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
public class NormalTime extends Time{ public NormalTime(short hours, short minutes, short seconds) { super(hours,minutes,seconds, (short) 24, (short) 60, (short) 60); } public int getTotalSeconds() { return (((hours * maxMinutes) + minutes * maxSeconds) + seconds); } }
UTF-8
Java
284
java
NormalTime.java
Java
[]
null
[]
public class NormalTime extends Time{ public NormalTime(short hours, short minutes, short seconds) { super(hours,minutes,seconds, (short) 24, (short) 60, (short) 60); } public int getTotalSeconds() { return (((hours * maxMinutes) + minutes * maxSeconds) + seconds); } }
284
0.690141
0.669014
11
24.727272
27.899466
67
false
false
0
0
0
0
0
0
1.727273
false
false
12
0b7e09793544be8c37230a66c59e2526878a5af5
21,526,376,144,183
c107d55b5a25580629400f87dd0e102cb2d3804d
/src/main/java/com/lq/utils/HttpUtils.java
aeaae243d18738d8102e181ebeaca6755f5194a2
[ "MIT" ]
permissive
lxlx704034204/proxy
https://github.com/lxlx704034204/proxy
97bdcdd892a40e45f13c825661f53185083fc224
dbd62190518af68d559e8523210d20f4226c6ad1
refs/heads/master
2021-01-24T01:46:24.208000
2018-02-12T05:21:25
2018-02-12T05:21:25
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.lq.utils; import com.alibaba.fastjson.JSONObject; import com.lq.po.ResIp; import com.lq.po.ResultIPsPo; import org.jsoup.Connection; import org.jsoup.Jsoup; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class HttpUtils { private static Logger LOGGER = LoggerFactory.getLogger(HttpUtils.class); /** * 检查ip是否过期 * * @param ip * @return */ public static Boolean chechISTimeOut(ResIp ip) { String url = "http://www.xdaili.cn/ipagent//checkIp/ipList?ip_ports%5B%5D=" + ip.getIp() + "%3A" + ip.getPort(); Connection conn = Jsoup.connect(url); try { String res = conn.get().text(); ResultIPsPo resultIPsPo = JSONObject.parseObject(res, ResultIPsPo.class); if (resultIPsPo.getRESULT().get(0).getTime() == null) { LOGGER.info("这个ip过期了"); return false; } else { LOGGER.info("这个ip可以使用,响应时间为" + resultIPsPo.getRESULT().get(0).getTime()); return true; } } catch (Exception e) { LOGGER.info("检查ip是否过期,异常" + e.toString()); return false; } } public static ResultIPsPo getIp() { LOGGER.info("initIP..........."); String url = "http://api.xdaili.cn/xdaili-api//greatRecharge/getGreatIp?spiderId=80f33066216b483b9e935d982e428289&orderno=YZ2018238955QxghNP&returnType=2&count=1"; Connection conn = Jsoup.connect(url); try { String res = conn.get().text(); LOGGER.info(res); return JSONObject.parseObject(res, ResultIPsPo.class); } catch (Exception e) { LOGGER.error(e.toString()); return new ResultIPsPo(); } } }
UTF-8
Java
1,832
java
HttpUtils.java
Java
[]
null
[]
package com.lq.utils; import com.alibaba.fastjson.JSONObject; import com.lq.po.ResIp; import com.lq.po.ResultIPsPo; import org.jsoup.Connection; import org.jsoup.Jsoup; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class HttpUtils { private static Logger LOGGER = LoggerFactory.getLogger(HttpUtils.class); /** * 检查ip是否过期 * * @param ip * @return */ public static Boolean chechISTimeOut(ResIp ip) { String url = "http://www.xdaili.cn/ipagent//checkIp/ipList?ip_ports%5B%5D=" + ip.getIp() + "%3A" + ip.getPort(); Connection conn = Jsoup.connect(url); try { String res = conn.get().text(); ResultIPsPo resultIPsPo = JSONObject.parseObject(res, ResultIPsPo.class); if (resultIPsPo.getRESULT().get(0).getTime() == null) { LOGGER.info("这个ip过期了"); return false; } else { LOGGER.info("这个ip可以使用,响应时间为" + resultIPsPo.getRESULT().get(0).getTime()); return true; } } catch (Exception e) { LOGGER.info("检查ip是否过期,异常" + e.toString()); return false; } } public static ResultIPsPo getIp() { LOGGER.info("initIP..........."); String url = "http://api.xdaili.cn/xdaili-api//greatRecharge/getGreatIp?spiderId=80f33066216b483b9e935d982e428289&orderno=YZ2018238955QxghNP&returnType=2&count=1"; Connection conn = Jsoup.connect(url); try { String res = conn.get().text(); LOGGER.info(res); return JSONObject.parseObject(res, ResultIPsPo.class); } catch (Exception e) { LOGGER.error(e.toString()); return new ResultIPsPo(); } } }
1,832
0.591422
0.566027
53
32.433964
31.424368
171
false
false
0
0
0
0
0
0
0.584906
false
false
12
9ffcecfa99ef7502bc3988b099423ba5e350537a
3,599,182,658,353
035dc1423bafefcd31841fa824ed5740fea3a822
/Test/src/Main.java
9bf3160264d59d14d2fbc969bbb22ae395ec67d1
[]
no_license
Ma3tin/TestRepository
https://github.com/Ma3tin/TestRepository
8dad1090d3ce1fe759928278f7cf0ec3afbae953
968807178c9e59f2551e87c22ffcb983b6e300de
refs/heads/master
2023-01-02T14:50:42.537000
2020-10-19T07:44:26
2020-10-19T07:44:26
305,289,661
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
public class Main { public static void main(String[] args) { System.out.println("Ahoj EDUCAnet"); } }
UTF-8
Java
118
java
Main.java
Java
[ { "context": "ain(String[] args) {\n System.out.println(\"Ahoj EDUCAnet\");\n }\n}\n", "end": 106, "score": 0.7591661214828491, "start": 94, "tag": "NAME", "value": "hoj EDUCAnet" } ]
null
[]
public class Main { public static void main(String[] args) { System.out.println("A<NAME>"); } }
112
0.618644
0.618644
5
22.6
18.467268
44
false
false
0
0
0
0
0
0
0.2
false
false
12
bec38bd52191e87d552df68fe0f785f7522bc745
15,281,493,693,388
a3dfa0f622f7bae3e319fbba5afe7d6057b1e7a4
/app/src/main/java/com/example/q/pacemaker/GoalActivity.java
e89ce1887bc489cfc7b1e3f41fb03a24285e7742
[]
no_license
HRH-allday/PaceMaker
https://github.com/HRH-allday/PaceMaker
377c6bcedbcaaaf89dbf6cfd3078746e94880ba6
a100ba519456bc7da7f1b43acf6241fb916ceef9
refs/heads/master
2021-01-11T22:02:43.708000
2017-01-17T20:26:30
2017-01-17T20:26:30
78,904,000
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.q.pacemaker; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.PackageManager; import android.location.Location; import android.location.LocationManager; import android.os.Build; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.design.widget.CollapsingToolbarLayout; import android.support.design.widget.NavigationView; import android.support.design.widget.TabLayout; import android.support.v4.app.ActivityCompat; import android.support.v4.view.ViewPager; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.CardView; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.support.v7.widget.helper.ItemTouchHelper; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.SubMenu; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.example.q.pacemaker.Utilities.RoundedImageView; import com.example.q.pacemaker.Utilities.SendJSON; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.location.LocationListener; import com.google.android.gms.location.LocationRequest; import com.google.android.gms.location.LocationServices; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.Marker; import com.google.android.gms.maps.model.MarkerOptions; import com.google.firebase.iid.FirebaseInstanceId; import com.squareup.picasso.Picasso; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.concurrent.ExecutionException; import static com.example.q.pacemaker.MainActivity.myUserInfo; import static com.example.q.pacemaker.R.id.todo; /** * Created by q on 2017-01-14. */ public class GoalActivity extends AppCompatActivity implements TabLayout.OnTabSelectedListener, GoogleApiClient.ConnectionCallbacks, LocationListener, GoogleApiClient.OnConnectionFailedListener, GoogleMap.OnMapClickListener, OnMapReadyCallback { private ArrayList<CustomizeData> customizeDatas = new ArrayList<>(); private CardView todoView; private CardView routineView; public static JSONArray mTodoList = new JSONArray(); public static JSONArray mMondayList = new JSONArray(); public static JSONArray mTuesdayList = new JSONArray(); public static JSONArray mWednesdayList = new JSONArray(); public static JSONArray mThursdayList = new JSONArray(); public static JSONArray mFridayList = new JSONArray(); public static JSONArray mSaturdayList = new JSONArray(); public static JSONArray mSundayList = new JSONArray(); public static JSONArray mMemoList = new JSONArray(); public String title; public String description; private String cloneID; private String token; private String photoUrl; private String pid; public TextView todoTextView; public EditText todoEdit; public Button todoButton; public RecyclerView todoRecyclerView; public RecyclerView.LayoutManager mLayoutManager; public RecyclerView.Adapter todoAdapter; public TabLayout tabLayout; public RoutineAdapter adapter; public ViewPager viewPager; public Button memo_plus; public EditText memoEditView; public RecyclerView memoRecyclerView; public RecyclerView.Adapter memoAdapter; public RecyclerView.LayoutManager memoLayoutManager; private Button shareButton; private Toolbar toolbar; private static final String TAG = "@@@"; private static final int SELECT_PHOTO = 1; private static final int SELECT_LOCATION = 2; SupportMapFragment mapFragment; LatLng selectedPoint = new LatLng(37.56, 126.97); private String latitude="37.56", longitude="126.97"; private GoogleMap googleMap; private GoogleApiClient mGoogleApiClient = null; private LocationRequest mLocationRequest; LocationManager locationManager; private static final int REQUEST_CODE_LOCATION = 2000; private static final int REQUEST_CODE_GPS = 2001; boolean setGPS = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_goal); toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); token = FirebaseInstanceId.getInstance().getToken(); Intent intent = getIntent(); cloneID = intent.getStringExtra("cid"); ArrayList<TodoListData> todoLists = new ArrayList<>(); ArrayList<ArrayList<TodoListData>> mRoutineList = new ArrayList<>(); ArrayList<TodoListData> memoLists = new ArrayList<>(); ArrayList<String> titleLists = new ArrayList<>(); ArrayList<String> cidLists = new ArrayList<>(); try { JSONObject req = new JSONObject(); req.put("token", token); JSONObject res = new SendJSON(App.server_url + App.routing_user_info, req.toString(), App.JSONcontentsType).execute().get(); if (res != null && res.has("result") && res.getString("result").equals("success")) { JSONObject userData = res.getJSONObject("user"); Log.i("userData", userData.toString()); JSONArray titles = userData.getJSONArray("goals_title"); JSONArray cids = userData.getJSONArray("goals_id"); for(int i = 0; i < titles.length() ; i++){ titleLists.add(titles.getString(i)); cidLists.add(cids.getString(i)); } } }catch (JSONException | InterruptedException | ExecutionException e) { e.printStackTrace(); } try { JSONObject req = new JSONObject(); req.put("cid", cloneID); JSONObject res = new SendJSON(App.server_url + App.routing_goal_clone_info, req.toString(), App.JSONcontentsType).execute().get(); if (res != null && res.has("result") && res.getString("result").equals("success")) { Log.i("clone", res.toString()); JSONObject cloneData = res.getJSONObject("clone"); title = cloneData.getString("title"); pid = cloneData.getString("pid"); mMondayList = cloneData.getJSONArray("mon"); mTuesdayList = cloneData.getJSONArray("tue"); mWednesdayList = cloneData.getJSONArray("wed"); mThursdayList = cloneData.getJSONArray("thu"); mFridayList = cloneData.getJSONArray("fri"); mSaturdayList = cloneData.getJSONArray("sat"); mSundayList = cloneData.getJSONArray("sun"); photoUrl = cloneData.getString("photo"); Log.i("photo", photoUrl); mMemoList = cloneData.getJSONArray("memo"); mTodoList = cloneData.getJSONArray("todo"); latitude = cloneData.getString("latitude"); longitude = cloneData.getString("longitude"); for(int i = 0; i < mTodoList.length() ; i++){ todoLists.add(new TodoListData(mTodoList.getString(i), "#ff1616")); } for(int i = 0; i < mMemoList.length() ; i++){ memoLists.add(new TodoListData(mMemoList.getString(i), "#ff1616")); } ArrayList<TodoListData> tlds = new ArrayList<>(); for(int i = 0; i < mMondayList.length() ; i++){ tlds.add(new TodoListData(mMondayList.getString(i), "#ff1616")); } mRoutineList.add(tlds); tlds = new ArrayList<>(); for(int i = 0; i < mTuesdayList.length() ; i++){ tlds.add(new TodoListData(mTuesdayList.getString(i), "#ff1616")); } mRoutineList.add(tlds); tlds = new ArrayList<>(); for(int i = 0; i < mWednesdayList.length() ; i++){ tlds.add(new TodoListData(mWednesdayList.getString(i), "#ff1616")); } mRoutineList.add(tlds); tlds = new ArrayList<>(); for(int i = 0; i < mThursdayList.length() ; i++){ tlds.add(new TodoListData(mThursdayList.getString(i), "#ff1616")); } mRoutineList.add(tlds); tlds = new ArrayList<>(); for(int i = 0; i < mFridayList.length() ; i++){ tlds.add(new TodoListData(mFridayList.getString(i), "#ff1616")); } mRoutineList.add(tlds); tlds = new ArrayList<>(); for(int i = 0; i < mSaturdayList.length() ; i++){ tlds.add(new TodoListData(mSaturdayList.getString(i), "#ff1616")); } mRoutineList.add(tlds); tlds = new ArrayList<>(); for(int i = 0; i < mSundayList.length() ; i++){ tlds.add(new TodoListData(mSundayList.getString(i), "#ff1616")); } mRoutineList.add(tlds); } }catch (JSONException | InterruptedException | ExecutionException e) { e.printStackTrace(); } //Imageview setting ImageView goalCloneImage = (ImageView) findViewById(R.id.goal_clone_image); Picasso.with(getApplicationContext()).load(photoUrl).into(goalCloneImage); CollapsingToolbarLayout collapsingToolbarLayout = (CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar); collapsingToolbarLayout.setTitle(title); // Maps mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.goal_map_fragment); locationManager = (LocationManager) getSystemService(LOCATION_SERVICE); mapFragment.getMapAsync(this); // nav drawer setting NavigationView navigationView = (NavigationView) findViewById(R.id.main_nav_list); navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() { @Override public boolean onNavigationItemSelected(final MenuItem item) { Intent intent; switch (item.getItemId()){ case R.id.go_main: intent = new Intent(getApplicationContext(), MainActivity.class); startActivity(intent); finish(); break; case R.id.go_community: intent = new Intent(getApplicationContext(), CommunityGoals.class); startActivity(intent); finish(); break; default: break; } return false; } }); View viewNavHeader = navigationView.getHeaderView(0); RoundedImageView profileImage = (RoundedImageView) viewNavHeader.findViewById(R.id.profile_image); Picasso.with(getApplicationContext()).load(myUserInfo.url).into(profileImage); TextView userName = (TextView) viewNavHeader.findViewById(R.id.username_profile); userName.setText(myUserInfo.userName); final Menu menu = navigationView.getMenu(); final SubMenu subMenu = menu.addSubMenu("나의 목표"); for (int i = 0; i < titleLists.size() ; i++) { Intent intentNav = new Intent(getApplicationContext(), GoalActivity.class); intent.putExtra("cid", cidLists.get(i)); subMenu.add(titleLists.get(i)).setIcon(R.drawable.ic_done).setIntent(intentNav); } // todo card todoView = (CardView) findViewById(R.id.cardview); todoEdit = (EditText) findViewById(R.id.todo_edit); todoButton = (Button) findViewById(R.id.todo_button); todoButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String todo = todoEdit.getText().toString().trim(); if(todo.equals("")) return; else{ todoEdit.setText(""); mTodoList.put(todo); try { JSONObject req = new JSONObject(); req.put("new_todo", todo); req.put("cid", cloneID); JSONObject res = new SendJSON(App.server_url + App.routing_add_todo, req.toString(), App.JSONcontentsType).execute().get(); if (res != null && res.has("result") && res.getString("result").equals("success")) { ((TodoListAdapter) todoAdapter).addItem(new TodoListData(todo, "#ff1616"), 0); } }catch (JSONException | InterruptedException | ExecutionException e) { e.printStackTrace(); } } } }); todoTextView = (TextView) findViewById(todo); todoRecyclerView = (RecyclerView) findViewById(R.id.todoRecyclerView); mLayoutManager = new LinearLayoutManager(this); todoRecyclerView.setLayoutManager(mLayoutManager); todoTextView.setText("오늘의 할 일"); todoAdapter = new TodoListAdapter(todoLists); todoRecyclerView.setAdapter(todoAdapter); ItemTouchHelper.SimpleCallback simpleItemTouchCallback = new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT) { @Override public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) { return false; } @Override public void onSwiped(RecyclerView.ViewHolder viewHolder, int swipeDir) { //Remove swiped item from list and notify the RecyclerView try { JSONObject req = new JSONObject(); req.put("cid", cloneID); req.put("index", viewHolder.getAdapterPosition()); JSONObject res = new SendJSON(App.server_url + App.routing_get_remove_clone_todo, req.toString(), App.JSONcontentsType).execute().get(); if (res != null && res.has("result") && res.getString("result").equals("success")) { } }catch (JSONException | InterruptedException | ExecutionException e) { e.printStackTrace(); } } }; ItemTouchHelper itemTouchHelper = new ItemTouchHelper(simpleItemTouchCallback); //itemTouchHelper.attachToRecyclerView(todoRecyclerView); // routine card routineView = (CardView) findViewById(R.id.routine_cardview); tabLayout = (TabLayout) findViewById(R.id.routine_tablayout); tabLayout.addTab(tabLayout.newTab().setText("월")); tabLayout.addTab(tabLayout.newTab().setText("화")); tabLayout.addTab(tabLayout.newTab().setText("수")); tabLayout.addTab(tabLayout.newTab().setText("목")); tabLayout.addTab(tabLayout.newTab().setText("금")); tabLayout.addTab(tabLayout.newTab().setText("토")); tabLayout.addTab(tabLayout.newTab().setText("일")); viewPager = (ViewPager) findViewById(R.id.routine_viewpager); adapter = new RoutineAdapter(getSupportFragmentManager(), mRoutineList.get(0),mRoutineList.get(1),mRoutineList.get(2),mRoutineList.get(3),mRoutineList.get(4),mRoutineList.get(5),mRoutineList.get(6), 1, cloneID); viewPager.setAdapter(adapter); viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout)); tabLayout.addOnTabSelectedListener(this); // memo card todoView = (CardView) findViewById(R.id.cardview); memo_plus = (Button) findViewById(R.id.memo_button); memoEditView = (EditText) findViewById(R.id.memo_edit); memoRecyclerView = (RecyclerView) findViewById(R.id.memoRecyclerView); memoLayoutManager = new LinearLayoutManager(this); memoRecyclerView.setLayoutManager(memoLayoutManager); memoAdapter = new TodoListAdapter(memoLists); memoRecyclerView.setAdapter(memoAdapter); String memo; memo_plus.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String edit = memoEditView.getText().toString().trim(); if(edit.equals("")) return; else { memoEditView.setText(""); mMemoList.put(edit); try { JSONObject req = new JSONObject(); req.put("new_memo", edit); req.put("cid", cloneID); JSONObject res = new SendJSON(App.server_url + App.routing_add_memo, req.toString(), App.JSONcontentsType).execute().get(); if (res != null && res.has("result") && res.getString("result").equals("success")) { ((TodoListAdapter) memoAdapter).addItem(new TodoListData(edit, "#ff1616"), 0); } }catch (JSONException | InterruptedException | ExecutionException e) { e.printStackTrace(); } } } }); ItemTouchHelper.SimpleCallback simpleItemTouchCallback2 = new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT) { @Override public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) { return false; } @Override public void onSwiped(RecyclerView.ViewHolder viewHolder, int swipeDir) { //Remove swiped item from list and notify the RecyclerView try { JSONObject req = new JSONObject(); req.put("cid", cloneID); req.put("index", viewHolder.getAdapterPosition()); JSONObject res = new SendJSON(App.server_url + App.routing_get_remove_clone_memo, req.toString(), App.JSONcontentsType).execute().get(); if (res != null && res.has("result") && res.getString("result").equals("success")) { } }catch (JSONException | InterruptedException | ExecutionException e) { e.printStackTrace(); } } }; ItemTouchHelper itemTouchHelper2 = new ItemTouchHelper(simpleItemTouchCallback2); //itemTouchHelper2.attachToRecyclerView(memoRecyclerView); //share shareButton = (Button) findViewById(R.id.share_button); title = "제목"; description = "설명"; shareButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent msg = new Intent(Intent.ACTION_SEND); msg.addCategory(Intent.CATEGORY_DEFAULT); msg.putExtra(Intent.EXTRA_TEXT, description); msg.putExtra(Intent.EXTRA_SUBJECT, title); msg.setType("text/plain"); startActivity(Intent.createChooser(msg, "공유")); } }); } protected synchronized void buildGoogleApiClient() { mGoogleApiClient = new GoogleApiClient.Builder(this) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .addApi(LocationServices.API) .build(); mGoogleApiClient.connect(); } //GPS 활성화를 위한 다이얼로그 보여주기 private void showGPSDisabledAlertToUser() { AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this); alertDialogBuilder.setMessage("GPS가 비활성화 되어있습니다. 활성화 할까요?") .setCancelable(false) .setPositiveButton("설정", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { Intent callGPSSettingIntent = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS); startActivityForResult(callGPSSettingIntent, REQUEST_CODE_GPS); } }); alertDialogBuilder.setNegativeButton("취소", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }); AlertDialog alert = alertDialogBuilder.create(); alert.show(); } @Override public void onMapReady(GoogleMap map) { googleMap = map; selectedPoint = new LatLng(Double.parseDouble(latitude), Double.parseDouble(longitude)); Marker selectedMarker = googleMap.addMarker(new MarkerOptions().position(selectedPoint)); googleMap.moveCamera(CameraUpdateFactory.newLatLng(selectedPoint)); googleMap.animateCamera(CameraUpdateFactory.zoomTo(15)); googleMap.setOnMapClickListener(GoalActivity.this); googleMap.setOnMapLoadedCallback(new GoogleMap.OnMapLoadedCallback() { @Override public void onMapLoaded() { Log.d( TAG, "onMapLoaded" ); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { checkLocationPermission(); } else { if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) && !setGPS) { Log.d(TAG, "onMapLoaded"); showGPSDisabledAlertToUser(); } if (mGoogleApiClient == null) { buildGoogleApiClient(); } googleMap.setMyLocationEnabled(false); } } }); //구글 플레이 서비스 초기화 if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { if (ActivityCompat.checkSelfPermission( this, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED || ActivityCompat.checkSelfPermission( this, android.Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) { buildGoogleApiClient(); googleMap.setMyLocationEnabled(false); } else { googleMap.moveCamera(CameraUpdateFactory.newLatLng(selectedPoint)); googleMap.animateCamera(CameraUpdateFactory.zoomTo(15)); } } else { buildGoogleApiClient(); googleMap.setMyLocationEnabled(false); } } @Override public void onMapClick(LatLng point) { Intent selectLocationIntent = new Intent(getApplicationContext(), MapsActivity.class); startActivityForResult(selectLocationIntent, SELECT_LOCATION); } public boolean checkLocationPermission() { Log.d( TAG, "checkLocationPermission"); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { //퍼미션 요청을 위해 UI를 보여줘야 하는지 검사 if (ActivityCompat.shouldShowRequestPermissionRationale(this, android.Manifest.permission.ACCESS_FINE_LOCATION)) { // Show an expanation to the user *asynchronously* -- don't block // this thread waiting for the user's response! After the user // sees the explanation, try again to request the permission. //Prompt the user once explanation has been shown; requestPermissions(new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION, android.Manifest.permission.ACCESS_COARSE_LOCATION}, REQUEST_CODE_LOCATION); } else //UI보여줄 필요 없이 요청 requestPermissions(new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION, android.Manifest.permission.ACCESS_COARSE_LOCATION}, REQUEST_CODE_LOCATION); return false; } else { Log.d( TAG, "checkLocationPermission"+"이미 퍼미션 획득한 경우"); if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) && !setGPS) { Log.d(TAG, "checkLocationPermission Version >= M"); showGPSDisabledAlertToUser(); } if (mGoogleApiClient == null) { Log.d( TAG, "checkLocationPermission "+"mGoogleApiClient==NULL"); buildGoogleApiClient(); } else Log.d( TAG, "checkLocationPermission "+"mGoogleApiClient!=NULL"); if ( mGoogleApiClient.isConnected() ) Log.d( TAG, "checkLocationPermission"+"mGoogleApiClient 연결되 있음"); else Log.d( TAG, "checkLocationPermission"+"mGoogleApiClient 끊어져 있음"); mGoogleApiClient.reconnect();//이미 연결되 있는 경우이므로 다시 연결 googleMap.setMyLocationEnabled(false); } } else { if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) && !setGPS) { Log.d(TAG, "checkLocationPermission Version < M"); showGPSDisabledAlertToUser(); } if (mGoogleApiClient == null) { buildGoogleApiClient(); } googleMap.setMyLocationEnabled(false); } return true; } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); switch (requestCode) { case REQUEST_CODE_LOCATION: { if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { //퍼미션이 허가된 경우 if ((ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED || ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED)) { if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) && !setGPS) { Log.d(TAG, "onRequestPermissionsResult"); showGPSDisabledAlertToUser(); } if (mGoogleApiClient == null) { buildGoogleApiClient(); } googleMap.setMyLocationEnabled(true); } } else { Toast.makeText(this, "퍼미션 취소", Toast.LENGTH_LONG).show(); } return; } } } @Override public void onConnected(@Nullable Bundle bundle) { Log.d( TAG, "onConnected" ); if ( locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) setGPS = true; mLocationRequest = new LocationRequest(); //mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY); mLocationRequest.setInterval(1000); mLocationRequest.setFastestInterval(1000); if (ActivityCompat.checkSelfPermission( this, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED || ActivityCompat.checkSelfPermission( this, android.Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) { Log.d( TAG, "onConnected " + "getLocationAvailability mGoogleApiClient.isConnected()="+mGoogleApiClient.isConnected() ); if ( !mGoogleApiClient.isConnected() ) mGoogleApiClient.connect(); // LocationAvailability locationAvailability = LocationServices.FusedLocationApi.getLocationAvailability(mGoogleApiClient); if ( setGPS && mGoogleApiClient.isConnected() )//|| locationAvailability.isLocationAvailable() ) { Log.d( TAG, "onConnected " + "requestLocationUpdates" ); LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this); Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient); if ( location == null ) return; /* //현재 위치에 마커 생성 LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude()); MarkerOptions markerOptions = new MarkerOptions(); markerOptions.position(latLng); markerOptions.title("현재위치"); // googleMap.addMarker(markerOptions); //지도 상에서 보여주는 영역 이동 googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng)); googleMap.animateCamera(CameraUpdateFactory.zoomTo(15)); */ } } } @Override public void onConnectionFailed(ConnectionResult result) { Log.d(TAG, "Connection failed: ConnectionResult.getErrorCode() = " + result.getErrorCode()); } @Override public void onConnectionSuspended(int cause) { //구글 플레이 서비스 연결이 해제되었을 때, 재연결 시도 Log.d(TAG, "Connection suspended"); mGoogleApiClient.connect(); } @Override protected void onStart() { super.onStart(); if (mGoogleApiClient != null) mGoogleApiClient.connect(); } @Override public void onResume() { super.onResume(); if (mGoogleApiClient != null) mGoogleApiClient.connect(); } @Override protected void onStop() { if (mGoogleApiClient != null && mGoogleApiClient.isConnected()) { mGoogleApiClient.disconnect(); } super.onStop(); } @Override public void onPause() { if ( mGoogleApiClient != null && mGoogleApiClient.isConnected()) { mGoogleApiClient.disconnect(); } super.onPause(); } @Override protected void onDestroy() { Log.d( TAG, "OnDestroy"); if (mGoogleApiClient != null) { mGoogleApiClient.unregisterConnectionCallbacks(this); mGoogleApiClient.unregisterConnectionFailedListener(this); if (mGoogleApiClient.isConnected()) { LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this); } mGoogleApiClient.disconnect(); mGoogleApiClient = null; } super.onDestroy(); } @Override public void onLocationChanged(Location location) { /* String errorMessage = ""; googleMap.clear(); //현재 위치에 마커 생성 LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude()); MarkerOptions markerOptions = new MarkerOptions(); markerOptions.position(latLng); markerOptions.title("현재위치"); googleMap.addMarker(markerOptions); //지도 상에서 보여주는 영역 이동 googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng)); googleMap.animateCamera(CameraUpdateFactory.zoomTo(15)); googleMap.getUiSettings().setCompassEnabled(true); //지오코더... GPS를 주소로 변환 Geocoder geocoder = new Geocoder(this, Locale.getDefault()); // Address found using the Geocoder. List<Address> addresses = null; try { // Using getFromLocation() returns an array of Addresses for the area immediately // surrounding the given latitude and longitude. The results are a best guess and are // not guaranteed to be accurate. addresses = geocoder.getFromLocation( location.getLatitude(), location.getLongitude(), // In this sample, we get just a single address. 1); } catch (IOException ioException) { // Catch network or other I/O problems. errorMessage = "지오코더 서비스 사용불가"; Toast.makeText( this, errorMessage, Toast.LENGTH_LONG).show(); } catch (IllegalArgumentException illegalArgumentException) { // Catch invalid latitude or longitude values. errorMessage = "잘못된 GPS 좌표"; Toast.makeText( this, errorMessage, Toast.LENGTH_LONG).show(); } // Handle case where no address was found. if (addresses == null || addresses.size() == 0) { if (errorMessage.isEmpty()) { errorMessage = "주소 미발견"; Log.e(TAG, errorMessage); } Toast.makeText( this, errorMessage, Toast.LENGTH_LONG).show(); } else { Address address = addresses.get(0); //Toast.makeText( this, address.getAddressLine(0).toString(), Toast.LENGTH_LONG).show(); } */ } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.invisible_menu, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.go_community_clone: Intent intent = new Intent(getApplicationContext(), CommunityActivity.class); intent.putExtra("pid", pid); startActivity(intent); return true; case R.id.go_goal_info: return true; case R.id.delete_clone: return true; default: return super.onOptionsItemSelected(item); } } @Override public void onTabSelected(TabLayout.Tab tab) { viewPager.setCurrentItem(tab.getPosition()); } @Override public void onTabUnselected(TabLayout.Tab tab) { } @Override public void onTabReselected(TabLayout.Tab tab) { } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); switch (requestCode) { case SELECT_LOCATION: if (resultCode == RESULT_OK) { try { String location = data.getData().toString(); String delim = "[/]"; String[] tokens = location.split(delim); latitude = tokens[0]; longitude = tokens[1]; selectedPoint = new LatLng(Double.parseDouble(latitude), Double.parseDouble(longitude)); googleMap.clear(); Marker selectedMarker = googleMap.addMarker(new MarkerOptions().position(selectedPoint)); googleMap.moveCamera(CameraUpdateFactory.newLatLng(selectedPoint)); googleMap.animateCamera(CameraUpdateFactory.zoomTo(15)); JSONObject req = new JSONObject(); req.put("cid", cloneID); req.put("latitude", latitude); req.put("longitude", longitude); JSONObject res = new SendJSON(App.server_url + App.routing_update_clone_location, req.toString(), App.JSONcontentsType).execute().get(); if (res != null && res.has("result") && res.getString("result").equals("success")) { Log.i("UPDATED", "Location"); } Log.e("LOCATION : ", location); Log.e("latitude", latitude); Log.e("longitude", longitude); } catch (Exception e) { e.printStackTrace(); } } case REQUEST_CODE_GPS: //Log.d(TAG,""+resultCode); //if (resultCode == RESULT_OK) //사용자가 GPS 활성 시켰는지 검사 if ( locationManager == null) locationManager = (LocationManager) getSystemService(LOCATION_SERVICE); if ( locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) { // GPS 가 ON으로 변경되었을 때의 처리. setGPS = true; mapFragment.getMapAsync(GoalActivity.this); } default: break; } } }
UTF-8
Java
38,597
java
GoalActivity.java
Java
[ { "context": ".example.q.pacemaker.R.id.todo;\n\n/**\n * Created by q on 2017-01-14.\n */\n\npublic class GoalActivity ext", "end": 2383, "score": 0.9643815159797668, "start": 2382, "tag": "USERNAME", "value": "q" }, { "context": " setSupportActionBar(toolbar);\n token = FirebaseInstanceId.getInstance().getToken();\n\n Intent intent ", "end": 5015, "score": 0.6758296489715576, "start": 4997, "tag": "KEY", "value": "FirebaseInstanceId" }, { "context": "nBar(toolbar);\n token = FirebaseInstanceId.getInstance().getToken();\n\n Intent intent = getIntent(", "end": 5027, "score": 0.6796400547027588, "start": 5016, "tag": "KEY", "value": "getInstance" }, { "context": "\n token = FirebaseInstanceId.getInstance().getToken();\n\n Intent intent = getIntent();\n ", "end": 5038, "score": 0.8004237413406372, "start": 5030, "tag": "KEY", "value": "getToken" } ]
null
[]
package com.example.q.pacemaker; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.PackageManager; import android.location.Location; import android.location.LocationManager; import android.os.Build; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.design.widget.CollapsingToolbarLayout; import android.support.design.widget.NavigationView; import android.support.design.widget.TabLayout; import android.support.v4.app.ActivityCompat; import android.support.v4.view.ViewPager; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.CardView; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.support.v7.widget.helper.ItemTouchHelper; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.SubMenu; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.example.q.pacemaker.Utilities.RoundedImageView; import com.example.q.pacemaker.Utilities.SendJSON; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.location.LocationListener; import com.google.android.gms.location.LocationRequest; import com.google.android.gms.location.LocationServices; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.Marker; import com.google.android.gms.maps.model.MarkerOptions; import com.google.firebase.iid.FirebaseInstanceId; import com.squareup.picasso.Picasso; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.concurrent.ExecutionException; import static com.example.q.pacemaker.MainActivity.myUserInfo; import static com.example.q.pacemaker.R.id.todo; /** * Created by q on 2017-01-14. */ public class GoalActivity extends AppCompatActivity implements TabLayout.OnTabSelectedListener, GoogleApiClient.ConnectionCallbacks, LocationListener, GoogleApiClient.OnConnectionFailedListener, GoogleMap.OnMapClickListener, OnMapReadyCallback { private ArrayList<CustomizeData> customizeDatas = new ArrayList<>(); private CardView todoView; private CardView routineView; public static JSONArray mTodoList = new JSONArray(); public static JSONArray mMondayList = new JSONArray(); public static JSONArray mTuesdayList = new JSONArray(); public static JSONArray mWednesdayList = new JSONArray(); public static JSONArray mThursdayList = new JSONArray(); public static JSONArray mFridayList = new JSONArray(); public static JSONArray mSaturdayList = new JSONArray(); public static JSONArray mSundayList = new JSONArray(); public static JSONArray mMemoList = new JSONArray(); public String title; public String description; private String cloneID; private String token; private String photoUrl; private String pid; public TextView todoTextView; public EditText todoEdit; public Button todoButton; public RecyclerView todoRecyclerView; public RecyclerView.LayoutManager mLayoutManager; public RecyclerView.Adapter todoAdapter; public TabLayout tabLayout; public RoutineAdapter adapter; public ViewPager viewPager; public Button memo_plus; public EditText memoEditView; public RecyclerView memoRecyclerView; public RecyclerView.Adapter memoAdapter; public RecyclerView.LayoutManager memoLayoutManager; private Button shareButton; private Toolbar toolbar; private static final String TAG = "@@@"; private static final int SELECT_PHOTO = 1; private static final int SELECT_LOCATION = 2; SupportMapFragment mapFragment; LatLng selectedPoint = new LatLng(37.56, 126.97); private String latitude="37.56", longitude="126.97"; private GoogleMap googleMap; private GoogleApiClient mGoogleApiClient = null; private LocationRequest mLocationRequest; LocationManager locationManager; private static final int REQUEST_CODE_LOCATION = 2000; private static final int REQUEST_CODE_GPS = 2001; boolean setGPS = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_goal); toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); token = FirebaseInstanceId.getInstance().getToken(); Intent intent = getIntent(); cloneID = intent.getStringExtra("cid"); ArrayList<TodoListData> todoLists = new ArrayList<>(); ArrayList<ArrayList<TodoListData>> mRoutineList = new ArrayList<>(); ArrayList<TodoListData> memoLists = new ArrayList<>(); ArrayList<String> titleLists = new ArrayList<>(); ArrayList<String> cidLists = new ArrayList<>(); try { JSONObject req = new JSONObject(); req.put("token", token); JSONObject res = new SendJSON(App.server_url + App.routing_user_info, req.toString(), App.JSONcontentsType).execute().get(); if (res != null && res.has("result") && res.getString("result").equals("success")) { JSONObject userData = res.getJSONObject("user"); Log.i("userData", userData.toString()); JSONArray titles = userData.getJSONArray("goals_title"); JSONArray cids = userData.getJSONArray("goals_id"); for(int i = 0; i < titles.length() ; i++){ titleLists.add(titles.getString(i)); cidLists.add(cids.getString(i)); } } }catch (JSONException | InterruptedException | ExecutionException e) { e.printStackTrace(); } try { JSONObject req = new JSONObject(); req.put("cid", cloneID); JSONObject res = new SendJSON(App.server_url + App.routing_goal_clone_info, req.toString(), App.JSONcontentsType).execute().get(); if (res != null && res.has("result") && res.getString("result").equals("success")) { Log.i("clone", res.toString()); JSONObject cloneData = res.getJSONObject("clone"); title = cloneData.getString("title"); pid = cloneData.getString("pid"); mMondayList = cloneData.getJSONArray("mon"); mTuesdayList = cloneData.getJSONArray("tue"); mWednesdayList = cloneData.getJSONArray("wed"); mThursdayList = cloneData.getJSONArray("thu"); mFridayList = cloneData.getJSONArray("fri"); mSaturdayList = cloneData.getJSONArray("sat"); mSundayList = cloneData.getJSONArray("sun"); photoUrl = cloneData.getString("photo"); Log.i("photo", photoUrl); mMemoList = cloneData.getJSONArray("memo"); mTodoList = cloneData.getJSONArray("todo"); latitude = cloneData.getString("latitude"); longitude = cloneData.getString("longitude"); for(int i = 0; i < mTodoList.length() ; i++){ todoLists.add(new TodoListData(mTodoList.getString(i), "#ff1616")); } for(int i = 0; i < mMemoList.length() ; i++){ memoLists.add(new TodoListData(mMemoList.getString(i), "#ff1616")); } ArrayList<TodoListData> tlds = new ArrayList<>(); for(int i = 0; i < mMondayList.length() ; i++){ tlds.add(new TodoListData(mMondayList.getString(i), "#ff1616")); } mRoutineList.add(tlds); tlds = new ArrayList<>(); for(int i = 0; i < mTuesdayList.length() ; i++){ tlds.add(new TodoListData(mTuesdayList.getString(i), "#ff1616")); } mRoutineList.add(tlds); tlds = new ArrayList<>(); for(int i = 0; i < mWednesdayList.length() ; i++){ tlds.add(new TodoListData(mWednesdayList.getString(i), "#ff1616")); } mRoutineList.add(tlds); tlds = new ArrayList<>(); for(int i = 0; i < mThursdayList.length() ; i++){ tlds.add(new TodoListData(mThursdayList.getString(i), "#ff1616")); } mRoutineList.add(tlds); tlds = new ArrayList<>(); for(int i = 0; i < mFridayList.length() ; i++){ tlds.add(new TodoListData(mFridayList.getString(i), "#ff1616")); } mRoutineList.add(tlds); tlds = new ArrayList<>(); for(int i = 0; i < mSaturdayList.length() ; i++){ tlds.add(new TodoListData(mSaturdayList.getString(i), "#ff1616")); } mRoutineList.add(tlds); tlds = new ArrayList<>(); for(int i = 0; i < mSundayList.length() ; i++){ tlds.add(new TodoListData(mSundayList.getString(i), "#ff1616")); } mRoutineList.add(tlds); } }catch (JSONException | InterruptedException | ExecutionException e) { e.printStackTrace(); } //Imageview setting ImageView goalCloneImage = (ImageView) findViewById(R.id.goal_clone_image); Picasso.with(getApplicationContext()).load(photoUrl).into(goalCloneImage); CollapsingToolbarLayout collapsingToolbarLayout = (CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar); collapsingToolbarLayout.setTitle(title); // Maps mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.goal_map_fragment); locationManager = (LocationManager) getSystemService(LOCATION_SERVICE); mapFragment.getMapAsync(this); // nav drawer setting NavigationView navigationView = (NavigationView) findViewById(R.id.main_nav_list); navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() { @Override public boolean onNavigationItemSelected(final MenuItem item) { Intent intent; switch (item.getItemId()){ case R.id.go_main: intent = new Intent(getApplicationContext(), MainActivity.class); startActivity(intent); finish(); break; case R.id.go_community: intent = new Intent(getApplicationContext(), CommunityGoals.class); startActivity(intent); finish(); break; default: break; } return false; } }); View viewNavHeader = navigationView.getHeaderView(0); RoundedImageView profileImage = (RoundedImageView) viewNavHeader.findViewById(R.id.profile_image); Picasso.with(getApplicationContext()).load(myUserInfo.url).into(profileImage); TextView userName = (TextView) viewNavHeader.findViewById(R.id.username_profile); userName.setText(myUserInfo.userName); final Menu menu = navigationView.getMenu(); final SubMenu subMenu = menu.addSubMenu("나의 목표"); for (int i = 0; i < titleLists.size() ; i++) { Intent intentNav = new Intent(getApplicationContext(), GoalActivity.class); intent.putExtra("cid", cidLists.get(i)); subMenu.add(titleLists.get(i)).setIcon(R.drawable.ic_done).setIntent(intentNav); } // todo card todoView = (CardView) findViewById(R.id.cardview); todoEdit = (EditText) findViewById(R.id.todo_edit); todoButton = (Button) findViewById(R.id.todo_button); todoButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String todo = todoEdit.getText().toString().trim(); if(todo.equals("")) return; else{ todoEdit.setText(""); mTodoList.put(todo); try { JSONObject req = new JSONObject(); req.put("new_todo", todo); req.put("cid", cloneID); JSONObject res = new SendJSON(App.server_url + App.routing_add_todo, req.toString(), App.JSONcontentsType).execute().get(); if (res != null && res.has("result") && res.getString("result").equals("success")) { ((TodoListAdapter) todoAdapter).addItem(new TodoListData(todo, "#ff1616"), 0); } }catch (JSONException | InterruptedException | ExecutionException e) { e.printStackTrace(); } } } }); todoTextView = (TextView) findViewById(todo); todoRecyclerView = (RecyclerView) findViewById(R.id.todoRecyclerView); mLayoutManager = new LinearLayoutManager(this); todoRecyclerView.setLayoutManager(mLayoutManager); todoTextView.setText("오늘의 할 일"); todoAdapter = new TodoListAdapter(todoLists); todoRecyclerView.setAdapter(todoAdapter); ItemTouchHelper.SimpleCallback simpleItemTouchCallback = new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT) { @Override public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) { return false; } @Override public void onSwiped(RecyclerView.ViewHolder viewHolder, int swipeDir) { //Remove swiped item from list and notify the RecyclerView try { JSONObject req = new JSONObject(); req.put("cid", cloneID); req.put("index", viewHolder.getAdapterPosition()); JSONObject res = new SendJSON(App.server_url + App.routing_get_remove_clone_todo, req.toString(), App.JSONcontentsType).execute().get(); if (res != null && res.has("result") && res.getString("result").equals("success")) { } }catch (JSONException | InterruptedException | ExecutionException e) { e.printStackTrace(); } } }; ItemTouchHelper itemTouchHelper = new ItemTouchHelper(simpleItemTouchCallback); //itemTouchHelper.attachToRecyclerView(todoRecyclerView); // routine card routineView = (CardView) findViewById(R.id.routine_cardview); tabLayout = (TabLayout) findViewById(R.id.routine_tablayout); tabLayout.addTab(tabLayout.newTab().setText("월")); tabLayout.addTab(tabLayout.newTab().setText("화")); tabLayout.addTab(tabLayout.newTab().setText("수")); tabLayout.addTab(tabLayout.newTab().setText("목")); tabLayout.addTab(tabLayout.newTab().setText("금")); tabLayout.addTab(tabLayout.newTab().setText("토")); tabLayout.addTab(tabLayout.newTab().setText("일")); viewPager = (ViewPager) findViewById(R.id.routine_viewpager); adapter = new RoutineAdapter(getSupportFragmentManager(), mRoutineList.get(0),mRoutineList.get(1),mRoutineList.get(2),mRoutineList.get(3),mRoutineList.get(4),mRoutineList.get(5),mRoutineList.get(6), 1, cloneID); viewPager.setAdapter(adapter); viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout)); tabLayout.addOnTabSelectedListener(this); // memo card todoView = (CardView) findViewById(R.id.cardview); memo_plus = (Button) findViewById(R.id.memo_button); memoEditView = (EditText) findViewById(R.id.memo_edit); memoRecyclerView = (RecyclerView) findViewById(R.id.memoRecyclerView); memoLayoutManager = new LinearLayoutManager(this); memoRecyclerView.setLayoutManager(memoLayoutManager); memoAdapter = new TodoListAdapter(memoLists); memoRecyclerView.setAdapter(memoAdapter); String memo; memo_plus.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String edit = memoEditView.getText().toString().trim(); if(edit.equals("")) return; else { memoEditView.setText(""); mMemoList.put(edit); try { JSONObject req = new JSONObject(); req.put("new_memo", edit); req.put("cid", cloneID); JSONObject res = new SendJSON(App.server_url + App.routing_add_memo, req.toString(), App.JSONcontentsType).execute().get(); if (res != null && res.has("result") && res.getString("result").equals("success")) { ((TodoListAdapter) memoAdapter).addItem(new TodoListData(edit, "#ff1616"), 0); } }catch (JSONException | InterruptedException | ExecutionException e) { e.printStackTrace(); } } } }); ItemTouchHelper.SimpleCallback simpleItemTouchCallback2 = new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT) { @Override public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) { return false; } @Override public void onSwiped(RecyclerView.ViewHolder viewHolder, int swipeDir) { //Remove swiped item from list and notify the RecyclerView try { JSONObject req = new JSONObject(); req.put("cid", cloneID); req.put("index", viewHolder.getAdapterPosition()); JSONObject res = new SendJSON(App.server_url + App.routing_get_remove_clone_memo, req.toString(), App.JSONcontentsType).execute().get(); if (res != null && res.has("result") && res.getString("result").equals("success")) { } }catch (JSONException | InterruptedException | ExecutionException e) { e.printStackTrace(); } } }; ItemTouchHelper itemTouchHelper2 = new ItemTouchHelper(simpleItemTouchCallback2); //itemTouchHelper2.attachToRecyclerView(memoRecyclerView); //share shareButton = (Button) findViewById(R.id.share_button); title = "제목"; description = "설명"; shareButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent msg = new Intent(Intent.ACTION_SEND); msg.addCategory(Intent.CATEGORY_DEFAULT); msg.putExtra(Intent.EXTRA_TEXT, description); msg.putExtra(Intent.EXTRA_SUBJECT, title); msg.setType("text/plain"); startActivity(Intent.createChooser(msg, "공유")); } }); } protected synchronized void buildGoogleApiClient() { mGoogleApiClient = new GoogleApiClient.Builder(this) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .addApi(LocationServices.API) .build(); mGoogleApiClient.connect(); } //GPS 활성화를 위한 다이얼로그 보여주기 private void showGPSDisabledAlertToUser() { AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this); alertDialogBuilder.setMessage("GPS가 비활성화 되어있습니다. 활성화 할까요?") .setCancelable(false) .setPositiveButton("설정", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { Intent callGPSSettingIntent = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS); startActivityForResult(callGPSSettingIntent, REQUEST_CODE_GPS); } }); alertDialogBuilder.setNegativeButton("취소", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }); AlertDialog alert = alertDialogBuilder.create(); alert.show(); } @Override public void onMapReady(GoogleMap map) { googleMap = map; selectedPoint = new LatLng(Double.parseDouble(latitude), Double.parseDouble(longitude)); Marker selectedMarker = googleMap.addMarker(new MarkerOptions().position(selectedPoint)); googleMap.moveCamera(CameraUpdateFactory.newLatLng(selectedPoint)); googleMap.animateCamera(CameraUpdateFactory.zoomTo(15)); googleMap.setOnMapClickListener(GoalActivity.this); googleMap.setOnMapLoadedCallback(new GoogleMap.OnMapLoadedCallback() { @Override public void onMapLoaded() { Log.d( TAG, "onMapLoaded" ); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { checkLocationPermission(); } else { if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) && !setGPS) { Log.d(TAG, "onMapLoaded"); showGPSDisabledAlertToUser(); } if (mGoogleApiClient == null) { buildGoogleApiClient(); } googleMap.setMyLocationEnabled(false); } } }); //구글 플레이 서비스 초기화 if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { if (ActivityCompat.checkSelfPermission( this, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED || ActivityCompat.checkSelfPermission( this, android.Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) { buildGoogleApiClient(); googleMap.setMyLocationEnabled(false); } else { googleMap.moveCamera(CameraUpdateFactory.newLatLng(selectedPoint)); googleMap.animateCamera(CameraUpdateFactory.zoomTo(15)); } } else { buildGoogleApiClient(); googleMap.setMyLocationEnabled(false); } } @Override public void onMapClick(LatLng point) { Intent selectLocationIntent = new Intent(getApplicationContext(), MapsActivity.class); startActivityForResult(selectLocationIntent, SELECT_LOCATION); } public boolean checkLocationPermission() { Log.d( TAG, "checkLocationPermission"); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { //퍼미션 요청을 위해 UI를 보여줘야 하는지 검사 if (ActivityCompat.shouldShowRequestPermissionRationale(this, android.Manifest.permission.ACCESS_FINE_LOCATION)) { // Show an expanation to the user *asynchronously* -- don't block // this thread waiting for the user's response! After the user // sees the explanation, try again to request the permission. //Prompt the user once explanation has been shown; requestPermissions(new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION, android.Manifest.permission.ACCESS_COARSE_LOCATION}, REQUEST_CODE_LOCATION); } else //UI보여줄 필요 없이 요청 requestPermissions(new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION, android.Manifest.permission.ACCESS_COARSE_LOCATION}, REQUEST_CODE_LOCATION); return false; } else { Log.d( TAG, "checkLocationPermission"+"이미 퍼미션 획득한 경우"); if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) && !setGPS) { Log.d(TAG, "checkLocationPermission Version >= M"); showGPSDisabledAlertToUser(); } if (mGoogleApiClient == null) { Log.d( TAG, "checkLocationPermission "+"mGoogleApiClient==NULL"); buildGoogleApiClient(); } else Log.d( TAG, "checkLocationPermission "+"mGoogleApiClient!=NULL"); if ( mGoogleApiClient.isConnected() ) Log.d( TAG, "checkLocationPermission"+"mGoogleApiClient 연결되 있음"); else Log.d( TAG, "checkLocationPermission"+"mGoogleApiClient 끊어져 있음"); mGoogleApiClient.reconnect();//이미 연결되 있는 경우이므로 다시 연결 googleMap.setMyLocationEnabled(false); } } else { if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) && !setGPS) { Log.d(TAG, "checkLocationPermission Version < M"); showGPSDisabledAlertToUser(); } if (mGoogleApiClient == null) { buildGoogleApiClient(); } googleMap.setMyLocationEnabled(false); } return true; } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); switch (requestCode) { case REQUEST_CODE_LOCATION: { if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { //퍼미션이 허가된 경우 if ((ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED || ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED)) { if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) && !setGPS) { Log.d(TAG, "onRequestPermissionsResult"); showGPSDisabledAlertToUser(); } if (mGoogleApiClient == null) { buildGoogleApiClient(); } googleMap.setMyLocationEnabled(true); } } else { Toast.makeText(this, "퍼미션 취소", Toast.LENGTH_LONG).show(); } return; } } } @Override public void onConnected(@Nullable Bundle bundle) { Log.d( TAG, "onConnected" ); if ( locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) setGPS = true; mLocationRequest = new LocationRequest(); //mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY); mLocationRequest.setInterval(1000); mLocationRequest.setFastestInterval(1000); if (ActivityCompat.checkSelfPermission( this, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED || ActivityCompat.checkSelfPermission( this, android.Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) { Log.d( TAG, "onConnected " + "getLocationAvailability mGoogleApiClient.isConnected()="+mGoogleApiClient.isConnected() ); if ( !mGoogleApiClient.isConnected() ) mGoogleApiClient.connect(); // LocationAvailability locationAvailability = LocationServices.FusedLocationApi.getLocationAvailability(mGoogleApiClient); if ( setGPS && mGoogleApiClient.isConnected() )//|| locationAvailability.isLocationAvailable() ) { Log.d( TAG, "onConnected " + "requestLocationUpdates" ); LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this); Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient); if ( location == null ) return; /* //현재 위치에 마커 생성 LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude()); MarkerOptions markerOptions = new MarkerOptions(); markerOptions.position(latLng); markerOptions.title("현재위치"); // googleMap.addMarker(markerOptions); //지도 상에서 보여주는 영역 이동 googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng)); googleMap.animateCamera(CameraUpdateFactory.zoomTo(15)); */ } } } @Override public void onConnectionFailed(ConnectionResult result) { Log.d(TAG, "Connection failed: ConnectionResult.getErrorCode() = " + result.getErrorCode()); } @Override public void onConnectionSuspended(int cause) { //구글 플레이 서비스 연결이 해제되었을 때, 재연결 시도 Log.d(TAG, "Connection suspended"); mGoogleApiClient.connect(); } @Override protected void onStart() { super.onStart(); if (mGoogleApiClient != null) mGoogleApiClient.connect(); } @Override public void onResume() { super.onResume(); if (mGoogleApiClient != null) mGoogleApiClient.connect(); } @Override protected void onStop() { if (mGoogleApiClient != null && mGoogleApiClient.isConnected()) { mGoogleApiClient.disconnect(); } super.onStop(); } @Override public void onPause() { if ( mGoogleApiClient != null && mGoogleApiClient.isConnected()) { mGoogleApiClient.disconnect(); } super.onPause(); } @Override protected void onDestroy() { Log.d( TAG, "OnDestroy"); if (mGoogleApiClient != null) { mGoogleApiClient.unregisterConnectionCallbacks(this); mGoogleApiClient.unregisterConnectionFailedListener(this); if (mGoogleApiClient.isConnected()) { LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this); } mGoogleApiClient.disconnect(); mGoogleApiClient = null; } super.onDestroy(); } @Override public void onLocationChanged(Location location) { /* String errorMessage = ""; googleMap.clear(); //현재 위치에 마커 생성 LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude()); MarkerOptions markerOptions = new MarkerOptions(); markerOptions.position(latLng); markerOptions.title("현재위치"); googleMap.addMarker(markerOptions); //지도 상에서 보여주는 영역 이동 googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng)); googleMap.animateCamera(CameraUpdateFactory.zoomTo(15)); googleMap.getUiSettings().setCompassEnabled(true); //지오코더... GPS를 주소로 변환 Geocoder geocoder = new Geocoder(this, Locale.getDefault()); // Address found using the Geocoder. List<Address> addresses = null; try { // Using getFromLocation() returns an array of Addresses for the area immediately // surrounding the given latitude and longitude. The results are a best guess and are // not guaranteed to be accurate. addresses = geocoder.getFromLocation( location.getLatitude(), location.getLongitude(), // In this sample, we get just a single address. 1); } catch (IOException ioException) { // Catch network or other I/O problems. errorMessage = "지오코더 서비스 사용불가"; Toast.makeText( this, errorMessage, Toast.LENGTH_LONG).show(); } catch (IllegalArgumentException illegalArgumentException) { // Catch invalid latitude or longitude values. errorMessage = "잘못된 GPS 좌표"; Toast.makeText( this, errorMessage, Toast.LENGTH_LONG).show(); } // Handle case where no address was found. if (addresses == null || addresses.size() == 0) { if (errorMessage.isEmpty()) { errorMessage = "주소 미발견"; Log.e(TAG, errorMessage); } Toast.makeText( this, errorMessage, Toast.LENGTH_LONG).show(); } else { Address address = addresses.get(0); //Toast.makeText( this, address.getAddressLine(0).toString(), Toast.LENGTH_LONG).show(); } */ } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.invisible_menu, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.go_community_clone: Intent intent = new Intent(getApplicationContext(), CommunityActivity.class); intent.putExtra("pid", pid); startActivity(intent); return true; case R.id.go_goal_info: return true; case R.id.delete_clone: return true; default: return super.onOptionsItemSelected(item); } } @Override public void onTabSelected(TabLayout.Tab tab) { viewPager.setCurrentItem(tab.getPosition()); } @Override public void onTabUnselected(TabLayout.Tab tab) { } @Override public void onTabReselected(TabLayout.Tab tab) { } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); switch (requestCode) { case SELECT_LOCATION: if (resultCode == RESULT_OK) { try { String location = data.getData().toString(); String delim = "[/]"; String[] tokens = location.split(delim); latitude = tokens[0]; longitude = tokens[1]; selectedPoint = new LatLng(Double.parseDouble(latitude), Double.parseDouble(longitude)); googleMap.clear(); Marker selectedMarker = googleMap.addMarker(new MarkerOptions().position(selectedPoint)); googleMap.moveCamera(CameraUpdateFactory.newLatLng(selectedPoint)); googleMap.animateCamera(CameraUpdateFactory.zoomTo(15)); JSONObject req = new JSONObject(); req.put("cid", cloneID); req.put("latitude", latitude); req.put("longitude", longitude); JSONObject res = new SendJSON(App.server_url + App.routing_update_clone_location, req.toString(), App.JSONcontentsType).execute().get(); if (res != null && res.has("result") && res.getString("result").equals("success")) { Log.i("UPDATED", "Location"); } Log.e("LOCATION : ", location); Log.e("latitude", latitude); Log.e("longitude", longitude); } catch (Exception e) { e.printStackTrace(); } } case REQUEST_CODE_GPS: //Log.d(TAG,""+resultCode); //if (resultCode == RESULT_OK) //사용자가 GPS 활성 시켰는지 검사 if ( locationManager == null) locationManager = (LocationManager) getSystemService(LOCATION_SERVICE); if ( locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) { // GPS 가 ON으로 변경되었을 때의 처리. setGPS = true; mapFragment.getMapAsync(GoalActivity.this); } default: break; } } }
38,597
0.596762
0.593003
919
40.400436
34.030785
219
false
false
0
0
0
0
0
0
0.688792
false
false
12
f58d62b142906c616c400ab119114e60cf1453b9
30,709,016,185,169
1d62f26b22e5692f8391f1637bb8b6986fda1e89
/src/Data.java
d9b4dbd53e5af7192af02afc3878c49800b1c6dc
[]
no_license
ramizion/ReadMyLips
https://github.com/ramizion/ReadMyLips
4fe214f62cd3fd54f03fba3213716298a92c7c49
941a95628e7f6950ec6ab198aeed283db7afe2d4
refs/heads/main
2023-04-15T22:12:42.807000
2021-05-01T22:22:19
2021-05-01T22:22:19
363,518,525
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.HashMap; import java.util.Optional; import javafx.application.Platform; import javafx.geometry.Insets; import javafx.scene.Node; import javafx.scene.control.Alert; import javafx.scene.control.Button; import javafx.scene.control.ButtonBar.ButtonData; import javafx.scene.control.ButtonType; import javafx.scene.control.Alert.AlertType; import javafx.scene.control.CheckBox; import javafx.scene.control.ChoiceDialog; import javafx.scene.control.Dialog; import javafx.scene.control.Label; import javafx.scene.control.PasswordField; import javafx.scene.layout.GridPane; import javafx.util.Pair; public class Data { // Number of viseme private final static int visemesAmount = 4; // FPS - Frames per second private final static int framesForMorph = 37; // Number of triangles in one map private final static int triangleAmount = 14; // Default time between 2 visemes (phoneme) private final static int defaultTimeForPhonemes = 500; // Milliseconds // Message for exit from the system private final static String messageExit = "Do you want to log off?"; // Message - Not an image format private final static String messageNotSaved = "The current project is not saved." + " \n Do you want to save your project?\n"; // Message - ask to save before exit private final static String messageNotImage = "Image cannot be found." + " \n Try again.\n"; // Message - worng text private final static String messageWrongText = "The text you entered isn't enabled.\n" + "Please, try again."; // URL to empty viseme - black image private final static String emptyImageUrl = "\\image\\visemeExample\\empty.png"; // All viseme type private final static HashMap <Character,Integer> visemesType2Phoneme = new HashMap <Character,Integer>(){{ put('s',0); // Silence put('a',1); // "Fatah" put('i',2); // "Hirik" put('o',3); // "Holam" }}; // Phoneme v.s Nikud // Can be more than one Nikud to one phoneme private final static HashMap <Character,Character> phonemesNikud = new HashMap <Character,Character>(){{ put('Ç','a'); put('Ä','i'); put('É','o'); put(' ','s'); }}; // Time between 2 visemes (phoneme) // Character "*" for all phonemes. Times in milliseconds private final static HashMap <List<Character>,Integer> phonemesTime = new HashMap <List<Character>,Integer>(){{ put(Arrays.asList('s','*'),Integer.valueOf(250)); put(Arrays.asList('a','a'),Integer.valueOf(500)); put(Arrays.asList('a','i'),Integer.valueOf(500)); put(Arrays.asList('a','o'),Integer.valueOf(500)); put(Arrays.asList('i','o'),Integer.valueOf(500)); }}; // Extension Filter of Image private final static String[] extensionImage={"*.TIF","*.JPG","*.PNG","*.GIF","*.JEPG"}; /** * alert Message - Warning with 2 options: Yes. No * @return boolean: TRUE for 'YES', and FALSE for 'No' * @param alertContent - String of the message * @param defaultButton - 'y' for 'YES' button as a default, 'n' for 'No' */ static public void alertMessageWarningOnlyOK(String alertContent){ Alert alert = new Alert(AlertType.ERROR); alert.setTitle("Confirmation Dialog"); alert.setHeaderText("Error"); alert.setContentText(alertContent); alert.getButtonTypes().clear(); alert.getButtonTypes().addAll(ButtonType.OK); alert.showAndWait(); } /** * alert Message - Warning with 2 options: Yes. No * @return boolean: TRUE for 'YES', and FALSE for 'No' * @param alertContent - String of the message * @param defaultButton - 'y' for 'YES' button as a default, 'n' for 'No' */ static public boolean alertMessageWarning(String alertContent, char defaultButton){ Alert alert = new Alert(AlertType.CONFIRMATION); alert.setTitle("Confirmation Dialog"); alert.setHeaderText("Are you sure?"); alert.setContentText(alertContent); alert.getButtonTypes().clear(); alert.getButtonTypes().addAll(ButtonType.YES, ButtonType.NO); defaultButton=Character.toLowerCase(defaultButton); Button yesButton = (Button) alert.getDialogPane().lookupButton(ButtonType.YES); yesButton.setDefaultButton(defaultButton=='y'); Button noButton = (Button) alert.getDialogPane().lookupButton(ButtonType.NO); noButton.setDefaultButton(defaultButton=='n'); final Optional<ButtonType> result = alert.showAndWait(); return (result.get() == ButtonType.YES); } /** * @return the messagenotimage */ public static String getMessagenotimage() { return messageNotImage; } /** * @return the messagewrongtext */ public static String getMessagewrongtext() { return messageWrongText; } /** * @return the extensionimage */ public static String[] getExtensionimage() { return extensionImage; } /** * @return String: URL to empty viseme - black image */ public static String getEmptyimageurl() { return emptyImageUrl; } /** * @return the int: FPS - Frames per second */ public static int getFramesformorph() { return framesForMorph; } /** * @return int: Default time between 2 visemes (phoneme) */ public static int getDefaulttimeforphonemes() { return defaultTimeForPhonemes; } /** * @return int: FPS - Frames per second */ public static int getFramesForMorph() { return framesForMorph; } /** * @return the phonemestime */ public static HashMap<List<Character>, Integer> getPhonemestime() { return phonemesTime; } /** * @return the triangleamount */ public static int getTriangleamount() { return triangleAmount; } /** * @return int: Number of viseme */ public static int getVisemesamount() { return visemesAmount; } /** * @return HashMap<Character,Integer>: all visemes type and their phoneme */ public static HashMap<Character,Integer> getVisemestype2phoneme() { return visemesType2Phoneme; } /** * @return HashMap<Character, Character>: Nikud and their phoneme */ public static HashMap<Character, Character> getPhonemesnikud() { return phonemesNikud; } /** * @return String: Message for exit from the system */ public static String getMessageexit() { return messageExit; } /** * @return String: Message - ask to save before exit */ public static String getMessagenotsaved() { return messageNotSaved; } }
WINDOWS-1252
Java
6,321
java
Data.java
Java
[ { "context": " HashMap <Character,Integer>(){{\n\t\tput('s',0);\t\t// Silence\n\t\tput('a',1);\t\t// \"Fatah\"\n\t\tput('i',2);\t\t// \"Hiri", "end": 1870, "score": 0.9712200164794922, "start": 1863, "tag": "NAME", "value": "Silence" }, { "context": "(){{\n\t\tput('s',0);\t\t// Silence\n\t\tput('a',1);\t\t// \"Fatah\"\n\t\tput('i',2);\t\t// \"Hirik\"\n\t\tput('o',3);\t\t// \"Hol", "end": 1895, "score": 0.9995357394218445, "start": 1890, "tag": "NAME", "value": "Fatah" }, { "context": "ence\n\t\tput('a',1);\t\t// \"Fatah\"\n\t\tput('i',2);\t\t// \"Hirik\"\n\t\tput('o',3);\t\t// \"Holam\"\n\t}};\n\t// Phoneme v.s N", "end": 1921, "score": 0.9993722438812256, "start": 1916, "tag": "NAME", "value": "Hirik" }, { "context": "tah\"\n\t\tput('i',2);\t\t// \"Hirik\"\n\t\tput('o',3);\t\t// \"Holam\"\n\t}};\n\t// Phoneme v.s Nikud\n\t// Can be more than ", "end": 1947, "score": 0.9994974136352539, "start": 1942, "tag": "NAME", "value": "Holam" }, { "context": "ik\"\n\t\tput('o',3);\t\t// \"Holam\"\n\t}};\n\t// Phoneme v.s Nikud\n\t// Can be more than one Nikud to one phoneme\n\tpr", "end": 1975, "score": 0.8818409442901611, "start": 1970, "tag": "NAME", "value": "Nikud" } ]
null
[]
import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.HashMap; import java.util.Optional; import javafx.application.Platform; import javafx.geometry.Insets; import javafx.scene.Node; import javafx.scene.control.Alert; import javafx.scene.control.Button; import javafx.scene.control.ButtonBar.ButtonData; import javafx.scene.control.ButtonType; import javafx.scene.control.Alert.AlertType; import javafx.scene.control.CheckBox; import javafx.scene.control.ChoiceDialog; import javafx.scene.control.Dialog; import javafx.scene.control.Label; import javafx.scene.control.PasswordField; import javafx.scene.layout.GridPane; import javafx.util.Pair; public class Data { // Number of viseme private final static int visemesAmount = 4; // FPS - Frames per second private final static int framesForMorph = 37; // Number of triangles in one map private final static int triangleAmount = 14; // Default time between 2 visemes (phoneme) private final static int defaultTimeForPhonemes = 500; // Milliseconds // Message for exit from the system private final static String messageExit = "Do you want to log off?"; // Message - Not an image format private final static String messageNotSaved = "The current project is not saved." + " \n Do you want to save your project?\n"; // Message - ask to save before exit private final static String messageNotImage = "Image cannot be found." + " \n Try again.\n"; // Message - worng text private final static String messageWrongText = "The text you entered isn't enabled.\n" + "Please, try again."; // URL to empty viseme - black image private final static String emptyImageUrl = "\\image\\visemeExample\\empty.png"; // All viseme type private final static HashMap <Character,Integer> visemesType2Phoneme = new HashMap <Character,Integer>(){{ put('s',0); // Silence put('a',1); // "Fatah" put('i',2); // "Hirik" put('o',3); // "Holam" }}; // Phoneme v.s Nikud // Can be more than one Nikud to one phoneme private final static HashMap <Character,Character> phonemesNikud = new HashMap <Character,Character>(){{ put('Ç','a'); put('Ä','i'); put('É','o'); put(' ','s'); }}; // Time between 2 visemes (phoneme) // Character "*" for all phonemes. Times in milliseconds private final static HashMap <List<Character>,Integer> phonemesTime = new HashMap <List<Character>,Integer>(){{ put(Arrays.asList('s','*'),Integer.valueOf(250)); put(Arrays.asList('a','a'),Integer.valueOf(500)); put(Arrays.asList('a','i'),Integer.valueOf(500)); put(Arrays.asList('a','o'),Integer.valueOf(500)); put(Arrays.asList('i','o'),Integer.valueOf(500)); }}; // Extension Filter of Image private final static String[] extensionImage={"*.TIF","*.JPG","*.PNG","*.GIF","*.JEPG"}; /** * alert Message - Warning with 2 options: Yes. No * @return boolean: TRUE for 'YES', and FALSE for 'No' * @param alertContent - String of the message * @param defaultButton - 'y' for 'YES' button as a default, 'n' for 'No' */ static public void alertMessageWarningOnlyOK(String alertContent){ Alert alert = new Alert(AlertType.ERROR); alert.setTitle("Confirmation Dialog"); alert.setHeaderText("Error"); alert.setContentText(alertContent); alert.getButtonTypes().clear(); alert.getButtonTypes().addAll(ButtonType.OK); alert.showAndWait(); } /** * alert Message - Warning with 2 options: Yes. No * @return boolean: TRUE for 'YES', and FALSE for 'No' * @param alertContent - String of the message * @param defaultButton - 'y' for 'YES' button as a default, 'n' for 'No' */ static public boolean alertMessageWarning(String alertContent, char defaultButton){ Alert alert = new Alert(AlertType.CONFIRMATION); alert.setTitle("Confirmation Dialog"); alert.setHeaderText("Are you sure?"); alert.setContentText(alertContent); alert.getButtonTypes().clear(); alert.getButtonTypes().addAll(ButtonType.YES, ButtonType.NO); defaultButton=Character.toLowerCase(defaultButton); Button yesButton = (Button) alert.getDialogPane().lookupButton(ButtonType.YES); yesButton.setDefaultButton(defaultButton=='y'); Button noButton = (Button) alert.getDialogPane().lookupButton(ButtonType.NO); noButton.setDefaultButton(defaultButton=='n'); final Optional<ButtonType> result = alert.showAndWait(); return (result.get() == ButtonType.YES); } /** * @return the messagenotimage */ public static String getMessagenotimage() { return messageNotImage; } /** * @return the messagewrongtext */ public static String getMessagewrongtext() { return messageWrongText; } /** * @return the extensionimage */ public static String[] getExtensionimage() { return extensionImage; } /** * @return String: URL to empty viseme - black image */ public static String getEmptyimageurl() { return emptyImageUrl; } /** * @return the int: FPS - Frames per second */ public static int getFramesformorph() { return framesForMorph; } /** * @return int: Default time between 2 visemes (phoneme) */ public static int getDefaulttimeforphonemes() { return defaultTimeForPhonemes; } /** * @return int: FPS - Frames per second */ public static int getFramesForMorph() { return framesForMorph; } /** * @return the phonemestime */ public static HashMap<List<Character>, Integer> getPhonemestime() { return phonemesTime; } /** * @return the triangleamount */ public static int getTriangleamount() { return triangleAmount; } /** * @return int: Number of viseme */ public static int getVisemesamount() { return visemesAmount; } /** * @return HashMap<Character,Integer>: all visemes type and their phoneme */ public static HashMap<Character,Integer> getVisemestype2phoneme() { return visemesType2Phoneme; } /** * @return HashMap<Character, Character>: Nikud and their phoneme */ public static HashMap<Character, Character> getPhonemesnikud() { return phonemesNikud; } /** * @return String: Message for exit from the system */ public static String getMessageexit() { return messageExit; } /** * @return String: Message - ask to save before exit */ public static String getMessagenotsaved() { return messageNotSaved; } }
6,321
0.706236
0.700696
220
27.709091
25.156544
113
false
false
0
0
0
0
0
0
1.645455
false
false
12
528ab37cb67984b965849cd51ab46da7d27f7d4a
893,353,214,809
e71edc4128cc635dce10cdacced2acece4b9c686
/src/main/java/mx/unam/is/controlador/CrearEmpresa.java
565b03462c1b981573e538e0a37d7b2e8160f186
[]
no_license
acv629/bolsa
https://github.com/acv629/bolsa
b6c3e934d4247f85785bc83867338c0a8641e3ad
5cf6ae030080a84731ec3c59e4ecb11b1a1b5161
refs/heads/master
2020-02-16T16:39:43.066000
2018-03-20T02:18:31
2018-03-20T02:18:31
125,126,000
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 mx.unam.is.controlador; import java.io.Serializable; import javax.faces.bean.ManagedBean; import javax.faces.bean.ViewScoped; import mx.unam.is.modelo.Empresa; import mx.unam.is.modelo.EmpresaDAO; /** * * @author acv629 */ @ManagedBean @ViewScoped public class CrearEmpresa implements Serializable { private String nombre; private String presidente; private String oficinas; private String fundacion; private Integer numeroEmpleados; private String contacto; public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public String getPresidente() { return presidente; } public void setPresidente(String presidente) { this.presidente = presidente; } public String getOficinas() { return oficinas; } public void setOficinas(String oficinas) { this.oficinas = oficinas; } public String getFundacion() { return fundacion; } public void setFundacion(String fundacion) { this.fundacion = fundacion; } public Integer getNumeroEmpleados() { return numeroEmpleados; } public void setNumeroEmpleados(Integer numeroEmpleados) { this.numeroEmpleados = numeroEmpleados; } public String getContacto() { return contacto; } public void setContacto(String contacto) { this.contacto = contacto; } public String crearNuevaEmpresa() { EmpresaDAO empresaDAO = new EmpresaDAO(); Empresa nuevaEmpresa = new Empresa(); nuevaEmpresa.setContacto(contacto); nuevaEmpresa.setFundacion(fundacion); nuevaEmpresa.setIdEmpresa(0); nuevaEmpresa.setNombre(nombre); nuevaEmpresa.setNumeroEmpleados(numeroEmpleados); nuevaEmpresa.setOficinas(oficinas); nuevaEmpresa.setPresidente(presidente); empresaDAO.guarda(nuevaEmpresa); return "ver_empresas?faces-redirect=true"; } }
UTF-8
Java
2,059
java
CrearEmpresa.java
Java
[ { "context": "t mx.unam.is.modelo.EmpresaDAO;\n\n/**\n *\n * @author acv629\n */\n@ManagedBean\n@ViewScoped\npublic class CrearEm", "end": 416, "score": 0.9996252059936523, "start": 410, "tag": "USERNAME", "value": "acv629" } ]
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 mx.unam.is.controlador; import java.io.Serializable; import javax.faces.bean.ManagedBean; import javax.faces.bean.ViewScoped; import mx.unam.is.modelo.Empresa; import mx.unam.is.modelo.EmpresaDAO; /** * * @author acv629 */ @ManagedBean @ViewScoped public class CrearEmpresa implements Serializable { private String nombre; private String presidente; private String oficinas; private String fundacion; private Integer numeroEmpleados; private String contacto; public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public String getPresidente() { return presidente; } public void setPresidente(String presidente) { this.presidente = presidente; } public String getOficinas() { return oficinas; } public void setOficinas(String oficinas) { this.oficinas = oficinas; } public String getFundacion() { return fundacion; } public void setFundacion(String fundacion) { this.fundacion = fundacion; } public Integer getNumeroEmpleados() { return numeroEmpleados; } public void setNumeroEmpleados(Integer numeroEmpleados) { this.numeroEmpleados = numeroEmpleados; } public String getContacto() { return contacto; } public void setContacto(String contacto) { this.contacto = contacto; } public String crearNuevaEmpresa() { EmpresaDAO empresaDAO = new EmpresaDAO(); Empresa nuevaEmpresa = new Empresa(); nuevaEmpresa.setContacto(contacto); nuevaEmpresa.setFundacion(fundacion); nuevaEmpresa.setIdEmpresa(0); nuevaEmpresa.setNombre(nombre); nuevaEmpresa.setNumeroEmpleados(numeroEmpleados); nuevaEmpresa.setOficinas(oficinas); nuevaEmpresa.setPresidente(presidente); empresaDAO.guarda(nuevaEmpresa); return "ver_empresas?faces-redirect=true"; } }
2,059
0.728509
0.726566
94
20.904255
18.857285
79
false
false
0
0
0
0
0
0
0.404255
false
false
12
b047271fa174e1c4b2d1efdf0659845e3d5e5a3e
20,306,605,384,241
6fa9eda692cf4fe6d48f2d40600db59c20803577
/platform-common/src/main/java/com/softicar/platform/common/core/java/jar/JarFile.java
736d357e62af7776c3b85551b9d4e01a992623a6
[ "MIT" ]
permissive
softicar/platform
https://github.com/softicar/platform
a5cbfcfe0e6097feae7f42d3058e716836c9f592
a6dad805156fc230a47eb7406959f29c59f2d1c2
refs/heads/main
2023-09-01T12:16:01.370000
2023-08-29T08:50:46
2023-08-29T08:50:46
408,834,598
4
2
MIT
false
2023-08-08T12:40:04
2021-09-21T13:38:04
2023-01-31T19:10:09
2023-08-08T12:40:03
12,735
5
1
3
Java
false
false
package com.softicar.platform.common.core.java.jar; import java.io.File; public class JarFile { private final File file; public JarFile(File file) { this.file = file; } public File getFile() { return file; } public JarFileEntryIterable getEntries() { return new JarFileEntryIterable(file); } }
UTF-8
Java
316
java
JarFile.java
Java
[]
null
[]
package com.softicar.platform.common.core.java.jar; import java.io.File; public class JarFile { private final File file; public JarFile(File file) { this.file = file; } public File getFile() { return file; } public JarFileEntryIterable getEntries() { return new JarFileEntryIterable(file); } }
316
0.71519
0.71519
23
12.73913
15.820233
51
false
false
0
0
0
0
0
0
0.826087
false
false
12
9d52b3d2315a21bb10fba98f411b5818a675fd80
28,260,884,812,948
e66b2698e2d9cce8265ff124c7cea10f8c02fc16
/server/authority-test/src/main/java/com/sp/fc/web/config/CustomMetadataSource.java
d875dca54f28e1fe420692edcf4e0be9d1c34e8a
[]
no_license
zidol/springboot_sec_basic_auth
https://github.com/zidol/springboot_sec_basic_auth
7d799c0debc4e40bbca31638abf191921d7eee4b
7d96d9dd018c968d6d15d7ac798a325511e61e97
refs/heads/main
2023-06-15T18:27:50.064000
2021-07-06T08:42:26
2021-07-06T08:42:26
380,874,986
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.sp.fc.web.config; import com.sp.fc.web.controller.PaperController; import org.aopalliance.intercept.MethodInvocation; import org.springframework.core.annotation.AnnotationUtils; import org.springframework.core.log.LogMessage; import org.springframework.security.access.ConfigAttribute; import org.springframework.security.access.SecurityConfig; import org.springframework.security.access.SecurityMetadataSource; import org.springframework.security.access.method.MethodSecurityMetadataSource; import org.springframework.security.access.prepost.PrePostAnnotationSecurityMetadataSource; import org.springframework.util.ClassUtils; import java.lang.annotation.Annotation; import java.lang.reflect.Method; import java.util.Collection; import java.util.List; public class CustomMetadataSource implements MethodSecurityMetadataSource { @Override public Collection<ConfigAttribute> getAttributes(Method method, Class<?> targetClass) { PrePostAnnotationSecurityMetadataSource prePostAnnotationSecurityMetadataSource; //constrollerdp @Secured({"SCHOOL_PRIMARY"}를 선언 하지 않아도 custom voter를 찾아오게됨 // if (method.getName().equals("getPapersByPrimary") && targetClass == PaperController.class){ // return List.of(new SecurityConfig("SCHOOL_PRIMARY")); // } //custom annotation 사용 CustomSecurityTag annotation = findAnnotation(method, targetClass, CustomSecurityTag.class); if (annotation != null) { return List.of(new SecurityConfig("SCHOOL_PRIMARY")); } return null; } @Override public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException { return null; } @Override public Collection<ConfigAttribute> getAllConfigAttributes() { return null; } @Override public boolean supports(Class<?> clazz) { return MethodInvocation.class.isAssignableFrom(clazz); } private <A extends Annotation> A findAnnotation(Method method, Class<?> targetClass, Class<A> annotationClass) { Method specificMethod = ClassUtils.getMostSpecificMethod(method, targetClass); A annotation = AnnotationUtils.findAnnotation(specificMethod, annotationClass); if (annotation != null) { return annotation; } return annotation; } }
UTF-8
Java
2,396
java
CustomMetadataSource.java
Java
[]
null
[]
package com.sp.fc.web.config; import com.sp.fc.web.controller.PaperController; import org.aopalliance.intercept.MethodInvocation; import org.springframework.core.annotation.AnnotationUtils; import org.springframework.core.log.LogMessage; import org.springframework.security.access.ConfigAttribute; import org.springframework.security.access.SecurityConfig; import org.springframework.security.access.SecurityMetadataSource; import org.springframework.security.access.method.MethodSecurityMetadataSource; import org.springframework.security.access.prepost.PrePostAnnotationSecurityMetadataSource; import org.springframework.util.ClassUtils; import java.lang.annotation.Annotation; import java.lang.reflect.Method; import java.util.Collection; import java.util.List; public class CustomMetadataSource implements MethodSecurityMetadataSource { @Override public Collection<ConfigAttribute> getAttributes(Method method, Class<?> targetClass) { PrePostAnnotationSecurityMetadataSource prePostAnnotationSecurityMetadataSource; //constrollerdp @Secured({"SCHOOL_PRIMARY"}를 선언 하지 않아도 custom voter를 찾아오게됨 // if (method.getName().equals("getPapersByPrimary") && targetClass == PaperController.class){ // return List.of(new SecurityConfig("SCHOOL_PRIMARY")); // } //custom annotation 사용 CustomSecurityTag annotation = findAnnotation(method, targetClass, CustomSecurityTag.class); if (annotation != null) { return List.of(new SecurityConfig("SCHOOL_PRIMARY")); } return null; } @Override public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException { return null; } @Override public Collection<ConfigAttribute> getAllConfigAttributes() { return null; } @Override public boolean supports(Class<?> clazz) { return MethodInvocation.class.isAssignableFrom(clazz); } private <A extends Annotation> A findAnnotation(Method method, Class<?> targetClass, Class<A> annotationClass) { Method specificMethod = ClassUtils.getMostSpecificMethod(method, targetClass); A annotation = AnnotationUtils.findAnnotation(specificMethod, annotationClass); if (annotation != null) { return annotation; } return annotation; } }
2,396
0.746193
0.746193
63
36.523811
33.756294
116
false
false
0
0
0
0
0
0
0.539683
false
false
12
16f9538048743ca7a314ce2eb2d41a5cb8a48fdd
4,252,017,689,120
71dc08ecd65afd5096645619eee08c09fc80f50d
/src/main/java/com/tomatolive/library/service/TokenDialogService.java
07f4a941bbd84544b0e206b39bfcbef35a67ba52
[]
no_license
lanshifu/FFmpegDemo
https://github.com/lanshifu/FFmpegDemo
d5a4a738feadcb15d8728ee92f9eb00f00c77413
fdbafde0bb8150503ae68c42ae98361c030bf046
refs/heads/master
2020-06-25T12:24:12.590000
2019-09-08T07:35:16
2019-09-08T07:35:16
199,304,834
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.tomatolive.library.service; import android.app.IntentService; import android.content.Intent; import android.support.annotation.Nullable; import android.support.v4.content.LocalBroadcastManager; public class TokenDialogService extends IntentService { public TokenDialogService() { super("TokenDialogService"); } /* Access modifiers changed, original: protected */ public void onHandleIntent(@Nullable Intent intent) { try { Thread.sleep(500); LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent("LIVE_TOKEN_INVALID_ACTION")); } catch (InterruptedException e) { e.printStackTrace(); Thread.currentThread().interrupt(); } } }
UTF-8
Java
751
java
TokenDialogService.java
Java
[]
null
[]
package com.tomatolive.library.service; import android.app.IntentService; import android.content.Intent; import android.support.annotation.Nullable; import android.support.v4.content.LocalBroadcastManager; public class TokenDialogService extends IntentService { public TokenDialogService() { super("TokenDialogService"); } /* Access modifiers changed, original: protected */ public void onHandleIntent(@Nullable Intent intent) { try { Thread.sleep(500); LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent("LIVE_TOKEN_INVALID_ACTION")); } catch (InterruptedException e) { e.printStackTrace(); Thread.currentThread().interrupt(); } } }
751
0.696405
0.691079
23
31.652174
25.352488
107
false
false
0
0
0
0
0
0
0.478261
false
false
12
179636285c7fc38b544f2c96962131c6d880d6cf
29,472,065,641,705
3c65e7fbb85626fbbf5c977c2fcbafa94b6788c1
/src/com/njq/nongfadai/thread/masterworker/Client.java
7c4fbd00d9ff541f954a095ceea450d22418ac2b
[]
no_license
JavaOpenSourceProgrammersMrJerrik/Thread
https://github.com/JavaOpenSourceProgrammersMrJerrik/Thread
8d8694e2541623c670474db40079aeeba4f68ca2
ffcdc6232bf46023370b72722c375581e32197ae
refs/heads/master
2021-01-25T01:21:51.650000
2017-06-23T03:19:17
2017-06-23T03:19:17
94,751,042
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.njq.nongfadai.thread.masterworker; import java.util.Map; public class Client { public static void main(String[] args) { long startTime = System.currentTimeMillis(); Master master = new Master(new PlusWorker(), 10); for (int i = 0; i < 100; i++) { master.submit(i); } master.execute(); while (!master.isComplete()) { } Map<String, Object> resultMap = master.getResultMap(); System.out.println("resultMap: " + resultMap); System.out.println("总任务个数: " + PlusWorker.getTotalCount()); long endTime = System.currentTimeMillis(); System.out.println("总耗时: " + (endTime - startTime)/1000.0); } }
UTF-8
Java
655
java
Client.java
Java
[]
null
[]
package com.njq.nongfadai.thread.masterworker; import java.util.Map; public class Client { public static void main(String[] args) { long startTime = System.currentTimeMillis(); Master master = new Master(new PlusWorker(), 10); for (int i = 0; i < 100; i++) { master.submit(i); } master.execute(); while (!master.isComplete()) { } Map<String, Object> resultMap = master.getResultMap(); System.out.println("resultMap: " + resultMap); System.out.println("总任务个数: " + PlusWorker.getTotalCount()); long endTime = System.currentTimeMillis(); System.out.println("总耗时: " + (endTime - startTime)/1000.0); } }
655
0.672926
0.655712
25
24.559999
21.949177
61
false
false
0
0
0
0
0
0
1.96
false
false
12
e6d7470f705e7ef74d6b315bf2d983c389b9c4e8
3,788,161,164,074
8b6dcf962bcf7c3cf89814c4c0d51b2fc109943e
/src/main/java/com/dkb/springsessionjpa/SpringSessionJpaApplication.java
a3a22c2cb85668731cb3088ecd001ab3a7544e42
[]
no_license
dineshbhagat/spring-session-jpa
https://github.com/dineshbhagat/spring-session-jpa
e5c139f30abc73304ea8ac0ddba48abdb8dde7aa
b270776a8b95745297a49597566c0b8930b8f6c7
refs/heads/master
2020-04-28T23:22:21.880000
2019-03-14T16:52:31
2019-03-14T16:52:31
175,652,107
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.dkb.springsessionjpa; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class SpringSessionJpaApplication { public static void main(String[] args) { SpringApplication.run(SpringSessionJpaApplication.class, args); } }
UTF-8
Java
337
java
SpringSessionJpaApplication.java
Java
[]
null
[]
package com.dkb.springsessionjpa; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class SpringSessionJpaApplication { public static void main(String[] args) { SpringApplication.run(SpringSessionJpaApplication.class, args); } }
337
0.833828
0.833828
13
24.923077
25.263113
68
false
false
0
0
0
0
0
0
0.692308
false
false
3
3fb591a4363699948e5bcc4d51b3d568f73c8c82
5,523,327,948,590
344aed60fa5d259a41f4b446e8f41fefd78a1773
/app/src/main/java/www/ntej/com/worldclocks/MySuggestionProvider.java
e1521d7184fb6e44d843eea19ece681ea6209257
[]
no_license
ntej/WorldClocks
https://github.com/ntej/WorldClocks
de37dae2eb16411d2ed5ca524a54a05483ffaeb2
f1b7f18333906f64d132d7f2f777d2a252b8a05b
refs/heads/master
2021-06-12T13:20:58.272000
2017-01-17T20:59:45
2017-01-17T20:59:45
76,594,151
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package www.ntej.com.worldclocks; import android.content.SearchRecentSuggestionsProvider; /** * Created by navatejareddy on 12/31/16. */ public class MySuggestionProvider extends SearchRecentSuggestionsProvider { public final static String AUTHORITY = "www.ntej.com.worldclocks.MySuggestionProvider"; public final static int MODE = DATABASE_MODE_QUERIES; public MySuggestionProvider() { setupSuggestions(AUTHORITY,MODE); } }
UTF-8
Java
460
java
MySuggestionProvider.java
Java
[ { "context": "earchRecentSuggestionsProvider;\n\n/**\n * Created by navatejareddy on 12/31/16.\n */\n\npublic class MySuggestionProvid", "end": 123, "score": 0.9984546899795532, "start": 110, "tag": "USERNAME", "value": "navatejareddy" } ]
null
[]
package www.ntej.com.worldclocks; import android.content.SearchRecentSuggestionsProvider; /** * Created by navatejareddy on 12/31/16. */ public class MySuggestionProvider extends SearchRecentSuggestionsProvider { public final static String AUTHORITY = "www.ntej.com.worldclocks.MySuggestionProvider"; public final static int MODE = DATABASE_MODE_QUERIES; public MySuggestionProvider() { setupSuggestions(AUTHORITY,MODE); } }
460
0.758696
0.745652
18
24.555555
28.727112
91
false
false
0
0
0
0
0
0
0.333333
false
false
3
622600ab24afbe26f0c733d5c52df795bf4b3a3b
5,523,327,949,197
f5cad1b932d129db08b85dd00733bbc9bdc7ec86
/src/main/java/guru/springframework/repositories/UserDao.java
3ddeccb9ba7fe3de073e3bdad10a519a060f84e1
[]
no_license
kanimohi/Student
https://github.com/kanimohi/Student
9b958ea21dc052196c9d897a2c3bb8fe065fba58
472e1d71dadc492bfe24b06b9e8cdf0b506dba60
refs/heads/master
2022-07-30T02:20:48.600000
2020-03-17T13:26:46
2020-03-17T13:26:46
236,472,586
0
0
null
false
2022-06-21T02:42:21
2020-01-27T11:07:15
2020-03-17T13:27:30
2022-06-21T02:42:20
1,099
0
0
1
Java
false
false
package guru.springframework.repositories; import guru.springframework.domain.DAOUser; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; @Repository public interface UserDao extends CrudRepository<DAOUser, Integer> { DAOUser findByUsername(String username); }
UTF-8
Java
325
java
UserDao.java
Java
[]
null
[]
package guru.springframework.repositories; import guru.springframework.domain.DAOUser; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; @Repository public interface UserDao extends CrudRepository<DAOUser, Integer> { DAOUser findByUsername(String username); }
325
0.843077
0.843077
10
31.5
24.5
67
false
false
0
0
0
0
0
0
0.6
false
false
3
bf701e098a9240f1dcf89a6f84c97a4f66fd5030
6,640,019,447,873
905e336dde5e9cd0eb3aa083229ccd8dbc84faec
/WEB-INF/src/com/dnd_api/persistence/util/HibernateUtil.java
561864ac10f9edc6d6ad8382479464f31e5a8119
[]
no_license
perryph/samplecode
https://github.com/perryph/samplecode
bc0161dfc8bb463ddfae7626d3b40f1c9e451b09
657f20f5360bb5649446b522f39eab9d707c19ec
refs/heads/master
2021-01-19T03:40:50.365000
2016-05-31T13:26:12
2016-05-31T13:26:12
60,088,293
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.dnd_api.persistence.util; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.boot.MetadataSources; import org.hibernate.boot.registry.StandardServiceRegistry; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; public class HibernateUtil { private static SessionFactory sessionFactory; public static void closeSession(Session currentSession) { try { currentSession.close(); currentSession = null; } catch (Exception e) { System.out.println(e.getMessage()); } } public static void closeTransaction(Transaction currentTransaction) { try { currentTransaction.commit(); } catch (Exception e) { System.out.println(e.getMessage()); } } public static Transaction setupTransaction(Session currentSession) { return currentSession.beginTransaction(); } public static SessionFactory getSessionFactory() { if(sessionFactory == null) sessionFactory = buildSessionFactory(); return sessionFactory; } private static SessionFactory buildSessionFactory() { try { final StandardServiceRegistry registry = new StandardServiceRegistryBuilder() .configure() // configures settings from hibernate.cfg.xml .build(); sessionFactory = new MetadataSources(registry) .buildMetadata() .buildSessionFactory(); return sessionFactory; } catch (Exception ex) { System.out.println(ex.getMessage()); return null; } } }
UTF-8
Java
1,500
java
HibernateUtil.java
Java
[]
null
[]
package com.dnd_api.persistence.util; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.boot.MetadataSources; import org.hibernate.boot.registry.StandardServiceRegistry; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; public class HibernateUtil { private static SessionFactory sessionFactory; public static void closeSession(Session currentSession) { try { currentSession.close(); currentSession = null; } catch (Exception e) { System.out.println(e.getMessage()); } } public static void closeTransaction(Transaction currentTransaction) { try { currentTransaction.commit(); } catch (Exception e) { System.out.println(e.getMessage()); } } public static Transaction setupTransaction(Session currentSession) { return currentSession.beginTransaction(); } public static SessionFactory getSessionFactory() { if(sessionFactory == null) sessionFactory = buildSessionFactory(); return sessionFactory; } private static SessionFactory buildSessionFactory() { try { final StandardServiceRegistry registry = new StandardServiceRegistryBuilder() .configure() // configures settings from hibernate.cfg.xml .build(); sessionFactory = new MetadataSources(registry) .buildMetadata() .buildSessionFactory(); return sessionFactory; } catch (Exception ex) { System.out.println(ex.getMessage()); return null; } } }
1,500
0.746667
0.746667
54
26.777779
23.198553
80
false
false
0
0
0
0
0
0
2.018518
false
false
3
58a28ec06f57ea4b0f2fcc5ab6195c687fa80fb6
7,395,933,690,217
5c39a4a36f3159cec7f6593f3715b30f8f9dad36
/Task05.java
a689b0bd3ededdbb7c7090e34e9e3a2a35b7eae6
[]
no_license
SDASTV/JB31_Unit02Spiridonov
https://github.com/SDASTV/JB31_Unit02Spiridonov
e67ec61fb6ce78c00338e62ee1a5c7a64fa44085
e17b6bc1954027e38fba5460922adb4a7e43541e
refs/heads/main
2023-05-05T13:52:09.368000
2021-05-26T07:11:42
2021-05-26T07:11:42
370,937,832
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package by.epam.unit02.main; public class Task05 { public static void main(String[] args) { int x, y; double result; x = 1 + (int)(Math.random() * 180); y = 1 + (int)(Math.random() * 180); result = (Math.sin(Math.toDegrees(x)) + Math.cos(Math.toDegrees(y))) / (Math.cos(Math.toDegrees(x)) - Math.sin(Math.toDegrees(y))) * Math.tan(Math.toDegrees(x * y)); System.out.println("x = " + x + ", y = " + y + ", result = " + result); } }
UTF-8
Java
457
java
Task05.java
Java
[]
null
[]
package by.epam.unit02.main; public class Task05 { public static void main(String[] args) { int x, y; double result; x = 1 + (int)(Math.random() * 180); y = 1 + (int)(Math.random() * 180); result = (Math.sin(Math.toDegrees(x)) + Math.cos(Math.toDegrees(y))) / (Math.cos(Math.toDegrees(x)) - Math.sin(Math.toDegrees(y))) * Math.tan(Math.toDegrees(x * y)); System.out.println("x = " + x + ", y = " + y + ", result = " + result); } }
457
0.584245
0.557987
15
29.466667
24.818989
73
false
false
0
0
0
0
0
0
2.133333
false
false
3
f82905b5dd85234e43417009124fa42235ee2669
18,932,215,850,018
f07e50cc12cde67329e05f8602b00770b10be297
/src/test/java/com/tripb/backer/rest/json/NativeTripResourceIT.java
f7c6589a9eac446317535c8dfe84f9914828e828
[]
no_license
fatlun1981/backer
https://github.com/fatlun1981/backer
d44fb94650b27253a750b04433b0870daaf95d38
386e41afa468e090a6ac0744ffc762f73047b4ea
refs/heads/master
2023-07-15T14:38:59.410000
2021-08-15T15:13:00
2021-08-15T15:13:00
372,236,914
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.tripb.backer.rest.json; import io.quarkus.test.junit.NativeImageTest; @NativeImageTest public class NativeTripResourceIT extends TripResourceTest { // Execute the same tests but in native mode. }
UTF-8
Java
214
java
NativeTripResourceIT.java
Java
[]
null
[]
package com.tripb.backer.rest.json; import io.quarkus.test.junit.NativeImageTest; @NativeImageTest public class NativeTripResourceIT extends TripResourceTest { // Execute the same tests but in native mode. }
214
0.799065
0.799065
9
22.888889
23.076899
60
false
false
0
0
0
0
0
0
0.222222
false
false
3
56c153f63129418b389ad715a55a6eba4c488dc3
9,139,690,416,904
852ede2e2d0c2e86edd360460d2b60a48226757d
/ulah-core/src/test/java/org/commonjava/ulah/db/AccountTransactionDataManagerTest.java
f3722de993bb04a275e6212c52a871b3be8f9ea7
[]
no_license
jdcasey/ulah
https://github.com/jdcasey/ulah
1a8c26e985474769ca82b5e2efdcfa297b0b6ac6
cffeb83e66c5435c30ead053d08ea0798dcdd8ef
refs/heads/master
2016-09-06T10:46:44.132000
2015-03-17T04:55:40
2015-03-17T04:55:40
30,174,393
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.commonjava.ulah.db; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.notNullValue; import static org.hamcrest.CoreMatchers.nullValue; import static org.junit.Assert.assertThat; import java.math.BigDecimal; import java.math.MathContext; import java.math.RoundingMode; import java.util.Date; import java.util.List; import org.commonjava.ulah.model.Account; import org.commonjava.ulah.model.AccountTransaction; import org.junit.Before; import org.junit.Test; public class AccountTransactionDataManagerTest extends AbstractDataManagerTest { private AccountTransactionDataManager transactions; private AccountDataManager accounts; private Account from; private Account to; @Before public void setupTransactions() { transactions = new AccountTransactionDataManager(wrappers, new AccountDataManager(wrappers), new TransactionTagDataManager(wrappers)); accounts = new AccountDataManager(wrappers); from = accounts.storeAccount(new Account("from")); to = accounts.storeAccount(new Account("to")); } @Test public void storeAndRetrieveTransactionById() { AccountTransaction tx = new AccountTransaction( from, to, new BigDecimal(10.22, new MathContext(4, RoundingMode.HALF_UP)), "test transaction"); AccountTransaction result = transactions.storeTransaction(tx); assertThat(result.getAmount(), equalTo(tx.getAmount())); assertThat(result.getMemo(), equalTo(tx.getMemo())); assertThat(result.getId(), notNullValue()); Long id = result.getId(); result = transactions.getTransaction(id); assertThat(result.getAmount(), equalTo(tx.getAmount())); assertThat(result.getMemo(), equalTo(tx.getMemo())); assertThat(result.getId(), equalTo(id)); } @Test public void storeDeleteAndFailToRetrieveTransactionById() { AccountTransaction tx = new AccountTransaction( from, to, new BigDecimal(10.22, new MathContext(4, RoundingMode.HALF_UP)), "test transaction"); AccountTransaction result = transactions.storeTransaction(tx); assertThat(result.getAmount(), equalTo(tx.getAmount())); assertThat(result.getMemo(), equalTo(tx.getMemo())); assertThat(result.getId(), notNullValue()); Long id = result.getId(); transactions.deleteTransaction(result); result = transactions.getTransaction(id); assertThat(result, nullValue()); } @Test public void newTransactionDeductedFromSourceAccount() { AccountTransaction tx = new AccountTransaction( from, to, new BigDecimal(10.22, new MathContext(4, RoundingMode.HALF_UP)), "test transaction"); AccountTransaction result = transactions.storeTransaction(tx); assertThat(result.getAmount(), equalTo(tx.getAmount())); assertThat(result.getMemo(), equalTo(tx.getMemo())); assertThat(result.getId(), notNullValue()); BigDecimal balance = transactions.getAccountBalance(from.getId()); assertThat(balance.doubleValue(), equalTo(-10.22)); } @Test public void newTransactionAddedToTargetAccount() { AccountTransaction tx = new AccountTransaction( from, to, new BigDecimal(10.22, new MathContext(4, RoundingMode.HALF_UP)), "test transaction"); AccountTransaction result = transactions.storeTransaction(tx); assertThat(result.getAmount(), equalTo(tx.getAmount())); assertThat(result.getMemo(), equalTo(tx.getMemo())); assertThat(result.getId(), notNullValue()); BigDecimal balance = transactions.getAccountBalance(to.getId()); assertThat(balance.doubleValue(), equalTo(10.22)); } @Test public void newTransactionsSummedAppropriatelyInTargetAccount() { transactions .storeTransaction(new AccountTransaction(from, to, new BigDecimal(10.22, new MathContext(4, RoundingMode.HALF_UP)), "test transaction")); transactions.storeTransaction(new AccountTransaction(to, from, new BigDecimal(1.22, new MathContext(4, RoundingMode.HALF_UP)), "test refund transaction")); BigDecimal balance = transactions.getAccountBalance(to.getId()); assertThat(balance.doubleValue(), equalTo(9.0)); } @Test public void newTransactionsSummedAppropriatelyInSourceAccount() { transactions .storeTransaction(new AccountTransaction(from, to, new BigDecimal(10.22, new MathContext(4, RoundingMode.HALF_UP)), "test transaction")); transactions.storeTransaction(new AccountTransaction(to, from, new BigDecimal(1.22, new MathContext(4, RoundingMode.HALF_UP)), "test refund transaction")); BigDecimal balance = transactions.getAccountBalance(from.getId()); assertThat(balance.doubleValue(), equalTo(-9.0)); } public void accountTransactionsExcludeThoseBetweenOtherAccounts() { Account third = accounts.storeAccount(new Account("third")); transactions.storeTransaction(new AccountTransaction(to, third, new BigDecimal(1.10), "excluded transaction")); transactions .storeTransaction(new AccountTransaction(from, to, new BigDecimal(10.00, new MathContext(4, RoundingMode.HALF_UP)), "included transaction")); List<AccountTransaction> txns = transactions.getAccountTransactions( from.getId(), new Date(0), new Date(), 0, 3); assertThat(txns, notNullValue()); assertThat(txns.size(), equalTo(1)); assertThat(txns.get(0).getAmount().doubleValue(), equalTo(10.00)); } public void allTransactionsIncludeThoseBetweenAnyAccounts() { Account third = accounts.storeAccount(new Account("third")); transactions.storeTransaction(new AccountTransaction(to, third, new BigDecimal(1.10), "excluded transaction")); transactions .storeTransaction(new AccountTransaction(from, to, new BigDecimal(10.00, new MathContext(4, RoundingMode.HALF_UP)), "included transaction")); List<AccountTransaction> txns = transactions.getAllTransactions( new Date(0), new Date(), 0, 3); assertThat(txns, notNullValue()); assertThat(txns.size(), equalTo(2)); assertThat(txns.get(0).getAmount().doubleValue(), equalTo(1.10)); assertThat(txns.get(1).getAmount().doubleValue(), equalTo(10.00)); } }
UTF-8
Java
6,961
java
AccountTransactionDataManagerTest.java
Java
[]
null
[]
package org.commonjava.ulah.db; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.notNullValue; import static org.hamcrest.CoreMatchers.nullValue; import static org.junit.Assert.assertThat; import java.math.BigDecimal; import java.math.MathContext; import java.math.RoundingMode; import java.util.Date; import java.util.List; import org.commonjava.ulah.model.Account; import org.commonjava.ulah.model.AccountTransaction; import org.junit.Before; import org.junit.Test; public class AccountTransactionDataManagerTest extends AbstractDataManagerTest { private AccountTransactionDataManager transactions; private AccountDataManager accounts; private Account from; private Account to; @Before public void setupTransactions() { transactions = new AccountTransactionDataManager(wrappers, new AccountDataManager(wrappers), new TransactionTagDataManager(wrappers)); accounts = new AccountDataManager(wrappers); from = accounts.storeAccount(new Account("from")); to = accounts.storeAccount(new Account("to")); } @Test public void storeAndRetrieveTransactionById() { AccountTransaction tx = new AccountTransaction( from, to, new BigDecimal(10.22, new MathContext(4, RoundingMode.HALF_UP)), "test transaction"); AccountTransaction result = transactions.storeTransaction(tx); assertThat(result.getAmount(), equalTo(tx.getAmount())); assertThat(result.getMemo(), equalTo(tx.getMemo())); assertThat(result.getId(), notNullValue()); Long id = result.getId(); result = transactions.getTransaction(id); assertThat(result.getAmount(), equalTo(tx.getAmount())); assertThat(result.getMemo(), equalTo(tx.getMemo())); assertThat(result.getId(), equalTo(id)); } @Test public void storeDeleteAndFailToRetrieveTransactionById() { AccountTransaction tx = new AccountTransaction( from, to, new BigDecimal(10.22, new MathContext(4, RoundingMode.HALF_UP)), "test transaction"); AccountTransaction result = transactions.storeTransaction(tx); assertThat(result.getAmount(), equalTo(tx.getAmount())); assertThat(result.getMemo(), equalTo(tx.getMemo())); assertThat(result.getId(), notNullValue()); Long id = result.getId(); transactions.deleteTransaction(result); result = transactions.getTransaction(id); assertThat(result, nullValue()); } @Test public void newTransactionDeductedFromSourceAccount() { AccountTransaction tx = new AccountTransaction( from, to, new BigDecimal(10.22, new MathContext(4, RoundingMode.HALF_UP)), "test transaction"); AccountTransaction result = transactions.storeTransaction(tx); assertThat(result.getAmount(), equalTo(tx.getAmount())); assertThat(result.getMemo(), equalTo(tx.getMemo())); assertThat(result.getId(), notNullValue()); BigDecimal balance = transactions.getAccountBalance(from.getId()); assertThat(balance.doubleValue(), equalTo(-10.22)); } @Test public void newTransactionAddedToTargetAccount() { AccountTransaction tx = new AccountTransaction( from, to, new BigDecimal(10.22, new MathContext(4, RoundingMode.HALF_UP)), "test transaction"); AccountTransaction result = transactions.storeTransaction(tx); assertThat(result.getAmount(), equalTo(tx.getAmount())); assertThat(result.getMemo(), equalTo(tx.getMemo())); assertThat(result.getId(), notNullValue()); BigDecimal balance = transactions.getAccountBalance(to.getId()); assertThat(balance.doubleValue(), equalTo(10.22)); } @Test public void newTransactionsSummedAppropriatelyInTargetAccount() { transactions .storeTransaction(new AccountTransaction(from, to, new BigDecimal(10.22, new MathContext(4, RoundingMode.HALF_UP)), "test transaction")); transactions.storeTransaction(new AccountTransaction(to, from, new BigDecimal(1.22, new MathContext(4, RoundingMode.HALF_UP)), "test refund transaction")); BigDecimal balance = transactions.getAccountBalance(to.getId()); assertThat(balance.doubleValue(), equalTo(9.0)); } @Test public void newTransactionsSummedAppropriatelyInSourceAccount() { transactions .storeTransaction(new AccountTransaction(from, to, new BigDecimal(10.22, new MathContext(4, RoundingMode.HALF_UP)), "test transaction")); transactions.storeTransaction(new AccountTransaction(to, from, new BigDecimal(1.22, new MathContext(4, RoundingMode.HALF_UP)), "test refund transaction")); BigDecimal balance = transactions.getAccountBalance(from.getId()); assertThat(balance.doubleValue(), equalTo(-9.0)); } public void accountTransactionsExcludeThoseBetweenOtherAccounts() { Account third = accounts.storeAccount(new Account("third")); transactions.storeTransaction(new AccountTransaction(to, third, new BigDecimal(1.10), "excluded transaction")); transactions .storeTransaction(new AccountTransaction(from, to, new BigDecimal(10.00, new MathContext(4, RoundingMode.HALF_UP)), "included transaction")); List<AccountTransaction> txns = transactions.getAccountTransactions( from.getId(), new Date(0), new Date(), 0, 3); assertThat(txns, notNullValue()); assertThat(txns.size(), equalTo(1)); assertThat(txns.get(0).getAmount().doubleValue(), equalTo(10.00)); } public void allTransactionsIncludeThoseBetweenAnyAccounts() { Account third = accounts.storeAccount(new Account("third")); transactions.storeTransaction(new AccountTransaction(to, third, new BigDecimal(1.10), "excluded transaction")); transactions .storeTransaction(new AccountTransaction(from, to, new BigDecimal(10.00, new MathContext(4, RoundingMode.HALF_UP)), "included transaction")); List<AccountTransaction> txns = transactions.getAllTransactions( new Date(0), new Date(), 0, 3); assertThat(txns, notNullValue()); assertThat(txns.size(), equalTo(2)); assertThat(txns.get(0).getAmount().doubleValue(), equalTo(1.10)); assertThat(txns.get(1).getAmount().doubleValue(), equalTo(10.00)); } }
6,961
0.647464
0.634823
185
36.627026
28.13205
81
false
false
0
0
0
0
0
0
0.918919
false
false
3
eec430ea1865305736e4d9434b6264c1f686fdfe
12,094,627,919,230
016fc45277892c96025ee857decde92f9e3cd637
/L7_DP/IntersectingChordInCircle.java
e3be9cf907c232ae6c3f11c5519b95ec51748a3c
[]
no_license
kratipaw/InterviewBit-JavaSolutions
https://github.com/kratipaw/InterviewBit-JavaSolutions
fb759441bd9b128d09fff08e611e17b76663fa26
b74e265b787eca7d9725c6d142575ca14ffd74f3
refs/heads/master
2020-04-05T00:29:52.674000
2019-12-10T02:46:22
2019-12-10T02:46:22
156,395,637
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * Given a number N, return number of ways you can draw N chords in a circle * with 2*N points such that no 2 chords intersect. * Two ways are different if there exists a chord which is present in one way and * not in other. * * For example, * * N=2 * If points are numbered 1 to 4 in clockwise direction, then different ways to * draw chords are: * {(1-2), (3-4)} and {(1-4), (2-3)} * * So, we return 2. * Notes: * * 1 ≤ N ≤ 1000 * Return answer modulo 109+7. * */ public class IntersectingChordInCircle { public static void main(String[] args) { // TODO Auto-generated method stub int N; N = 2; System.out.println(chordCnt(N)); N = 1; System.out.println(chordCnt(N)); N = 4; System.out.println(chordCnt(N)); N = 3; System.out.println(chordCnt(N)); N = 20; //ans = 564120378 System.out.println(chordCnt(N)); N = 31; //ans = 937414464 System.out.println(chordCnt(N)); } private static int chordCnt(int A) { int points = 2 * A; long dp[] = new long[points + 1]; dp[0] = 1; dp[2] = 1; for (int i = 4; i <= points; i+=2) { for (int j = 0; j < i; j+=2) { dp[i] = (dp[i] + dp[j] * dp[i - j -2]) % 1000000007; } } return (int) (dp[points]); } }
UTF-8
Java
1,461
java
IntersectingChordInCircle.java
Java
[]
null
[]
/** * Given a number N, return number of ways you can draw N chords in a circle * with 2*N points such that no 2 chords intersect. * Two ways are different if there exists a chord which is present in one way and * not in other. * * For example, * * N=2 * If points are numbered 1 to 4 in clockwise direction, then different ways to * draw chords are: * {(1-2), (3-4)} and {(1-4), (2-3)} * * So, we return 2. * Notes: * * 1 ≤ N ≤ 1000 * Return answer modulo 109+7. * */ public class IntersectingChordInCircle { public static void main(String[] args) { // TODO Auto-generated method stub int N; N = 2; System.out.println(chordCnt(N)); N = 1; System.out.println(chordCnt(N)); N = 4; System.out.println(chordCnt(N)); N = 3; System.out.println(chordCnt(N)); N = 20; //ans = 564120378 System.out.println(chordCnt(N)); N = 31; //ans = 937414464 System.out.println(chordCnt(N)); } private static int chordCnt(int A) { int points = 2 * A; long dp[] = new long[points + 1]; dp[0] = 1; dp[2] = 1; for (int i = 4; i <= points; i+=2) { for (int j = 0; j < i; j+=2) { dp[i] = (dp[i] + dp[j] * dp[i - j -2]) % 1000000007; } } return (int) (dp[points]); } }
1,461
0.502402
0.454358
62
22.5
20.677048
82
false
false
0
0
0
0
0
0
0.580645
false
false
3
14dfff5008faa2a03e44be8b09d952f1891ca314
25,838,523,262,641
4cd41c8a18134345f22d53049fc94609e8a0e9a9
/src/main/java/bolao/model/Usuario.java
fc21731bcdf4f0d9a0e39981a938202f159da5ed
[]
no_license
Fred-Trovao/bolao_trovao
https://github.com/Fred-Trovao/bolao_trovao
ee048f31bb993e31898680a1219fe3ad7830cf72
6563e4bbf6884eb8cf977684dcbdb39e83b61ed1
refs/heads/master
2018-07-27T02:39:24.527000
2018-06-16T12:28:30
2018-06-16T12:28:30
19,440,869
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package bolao.model; import java.io.Serializable; import java.util.HashSet; import java.util.Set; import javax.persistence.Column; import javax.persistence.ElementCollection; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.Table; import javax.persistence.UniqueConstraint; @Entity @Table(name="tb_usuario") public class Usuario implements Serializable{ private static final long serialVersionUID = 3026097908340994246L; @Id @GeneratedValue(strategy=GenerationType.IDENTITY) private Long id; @Column(nullable = false) private String nome; @Column(nullable = false) private String telefone; @Column(unique = true, nullable = false) private String login; @Column(nullable = false) private String senha; @Column(nullable = false) private boolean ativo; @Column(nullable = false) private boolean pago; @ElementCollection(targetClass = String.class) @JoinTable( name = "tb_usuario_permissao", uniqueConstraints ={@UniqueConstraint(columnNames = {"id_usuario","permissao"})}, joinColumns = @JoinColumn(name = "id_usuario")) @Column(name = "permissao", length=50) private Set<String> permissao; public Usuario(){ this.permissao = new HashSet<String>(); } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } public String getSenha() { return senha; } public void setSenha(String senha) { this.senha = senha; } public boolean isAtivo() { return ativo; } public void setAtivo(boolean ativo) { this.ativo = ativo; } public Set<String> getPermissao() { return permissao; } public void setPermissao(Set<String> permissao) { this.permissao = permissao; } public String getTelefone() { return telefone; } public void setTelefone(String telefone) { this.telefone = telefone; } public String getLogin() { return login; } public void setLogin(String login) { this.login = login; } public void addPermissao(String permissao){ this.permissao.add(permissao); } public void removePermissao(String permissao){ this.permissao.remove(permissao); } public boolean isPago() { return pago; } public void setPago(boolean pago) { this.pago = pago; } public static long getSerialversionuid() { return serialVersionUID; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (ativo ? 1231 : 1237); result = prime * result + ((id == null) ? 0 : id.hashCode()); result = prime * result + ((login == null) ? 0 : login.hashCode()); result = prime * result + ((nome == null) ? 0 : nome.hashCode()); result = prime * result + (pago ? 1231 : 1237); result = prime * result + ((permissao == null) ? 0 : permissao.hashCode()); result = prime * result + ((senha == null) ? 0 : senha.hashCode()); result = prime * result + ((telefone == null) ? 0 : telefone.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Usuario other = (Usuario) obj; if (ativo != other.ativo) return false; if (id == null) { if (other.id != null) return false; } else if (!id.equals(other.id)) return false; if (login == null) { if (other.login != null) return false; } else if (!login.equals(other.login)) return false; if (nome == null) { if (other.nome != null) return false; } else if (!nome.equals(other.nome)) return false; if (pago != other.pago) return false; if (permissao == null) { if (other.permissao != null) return false; } else if (!permissao.equals(other.permissao)) return false; if (senha == null) { if (other.senha != null) return false; } else if (!senha.equals(other.senha)) return false; if (telefone == null) { if (other.telefone != null) return false; } else if (!telefone.equals(other.telefone)) return false; return true; } }
UTF-8
Java
4,281
java
Usuario.java
Java
[]
null
[]
package bolao.model; import java.io.Serializable; import java.util.HashSet; import java.util.Set; import javax.persistence.Column; import javax.persistence.ElementCollection; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.Table; import javax.persistence.UniqueConstraint; @Entity @Table(name="tb_usuario") public class Usuario implements Serializable{ private static final long serialVersionUID = 3026097908340994246L; @Id @GeneratedValue(strategy=GenerationType.IDENTITY) private Long id; @Column(nullable = false) private String nome; @Column(nullable = false) private String telefone; @Column(unique = true, nullable = false) private String login; @Column(nullable = false) private String senha; @Column(nullable = false) private boolean ativo; @Column(nullable = false) private boolean pago; @ElementCollection(targetClass = String.class) @JoinTable( name = "tb_usuario_permissao", uniqueConstraints ={@UniqueConstraint(columnNames = {"id_usuario","permissao"})}, joinColumns = @JoinColumn(name = "id_usuario")) @Column(name = "permissao", length=50) private Set<String> permissao; public Usuario(){ this.permissao = new HashSet<String>(); } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } public String getSenha() { return senha; } public void setSenha(String senha) { this.senha = senha; } public boolean isAtivo() { return ativo; } public void setAtivo(boolean ativo) { this.ativo = ativo; } public Set<String> getPermissao() { return permissao; } public void setPermissao(Set<String> permissao) { this.permissao = permissao; } public String getTelefone() { return telefone; } public void setTelefone(String telefone) { this.telefone = telefone; } public String getLogin() { return login; } public void setLogin(String login) { this.login = login; } public void addPermissao(String permissao){ this.permissao.add(permissao); } public void removePermissao(String permissao){ this.permissao.remove(permissao); } public boolean isPago() { return pago; } public void setPago(boolean pago) { this.pago = pago; } public static long getSerialversionuid() { return serialVersionUID; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (ativo ? 1231 : 1237); result = prime * result + ((id == null) ? 0 : id.hashCode()); result = prime * result + ((login == null) ? 0 : login.hashCode()); result = prime * result + ((nome == null) ? 0 : nome.hashCode()); result = prime * result + (pago ? 1231 : 1237); result = prime * result + ((permissao == null) ? 0 : permissao.hashCode()); result = prime * result + ((senha == null) ? 0 : senha.hashCode()); result = prime * result + ((telefone == null) ? 0 : telefone.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Usuario other = (Usuario) obj; if (ativo != other.ativo) return false; if (id == null) { if (other.id != null) return false; } else if (!id.equals(other.id)) return false; if (login == null) { if (other.login != null) return false; } else if (!login.equals(other.login)) return false; if (nome == null) { if (other.nome != null) return false; } else if (!nome.equals(other.nome)) return false; if (pago != other.pago) return false; if (permissao == null) { if (other.permissao != null) return false; } else if (!permissao.equals(other.permissao)) return false; if (senha == null) { if (other.senha != null) return false; } else if (!senha.equals(other.senha)) return false; if (telefone == null) { if (other.telefone != null) return false; } else if (!telefone.equals(other.telefone)) return false; return true; } }
4,281
0.676711
0.665966
196
20.846939
17.289463
84
false
false
0
0
0
0
0
0
1.77551
false
false
3
0923a8bbcefd927c9fd3688708bd65f277395668
14,431,090,124,193
e47b81c50676e1b345e6c3c6d2c87312ab7baec9
/app/src/main/java/com/newdjk/member/ui/entity/DugsEntity.java
88ef02ac7a6c3ef010bb6436a28ab11a71fc0e7d
[]
no_license
huhaiAndroid/Member
https://github.com/huhaiAndroid/Member
4fbb29a14f7cd5ebd31dc7b805f8c394e4d6ac1c
dbc138ac87b456818455ae386635e70bfab3ad2f
refs/heads/master
2020-10-01T14:42:20.545000
2019-12-12T08:35:27
2019-12-12T08:35:27
227,557,925
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.newdjk.member.ui.entity; import java.util.List; /** * Created by EDZ on 2018/11/8. */ public class DugsEntity { /** * Code : 0 * Message : * Data : {"Total":297,"ReturnData":[{"Id":25,"Name":"阿司匹林肠溶片","Manufacturer":"德国拜耳医药保健有限公司启东分公司","MedicationCompanyName":"新起点药房"},{"Id":64,"Name":"奥利司他胶囊","Manufacturer":"中山万汉医药科技有限公司","MedicationCompanyName":"新起点药房"}]} */ private int Code; private String Message; private DataBean Data; public int getCode() { return Code; } public void setCode(int Code) { this.Code = Code; } public String getMessage() { return Message; } public void setMessage(String Message) { this.Message = Message; } public DataBean getData() { return Data; } public void setData(DataBean Data) { this.Data = Data; } public static class DataBean { /** * Total : 297 * ReturnData : [{"Id":25,"Name":"阿司匹林肠溶片","Manufacturer":"德国拜耳医药保健有限公司启东分公司","MedicationCompanyName":"新起点药房"},{"Id":64,"Name":"奥利司他胶囊","Manufacturer":"中山万汉医药科技有限公司","MedicationCompanyName":"新起点药房"}] */ private int Total; private List<ReturnDataBean> ReturnData; public int getTotal() { return Total; } public void setTotal(int Total) { this.Total = Total; } public List<ReturnDataBean> getReturnData() { return ReturnData; } public void setReturnData(List<ReturnDataBean> ReturnData) { this.ReturnData = ReturnData; } public static class ReturnDataBean { /** * Id : 25 * Name : 阿司匹林肠溶片 * Manufacturer : 德国拜耳医药保健有限公司启东分公司 * MedicationCompanyName : 新起点药房 */ private int Id; private String Name; private String Manufacturer; private String MedicationCompanyName; public int getId() { return Id; } public void setId(int Id) { this.Id = Id; } public String getName() { return Name; } public void setName(String Name) { this.Name = Name; } public String getManufacturer() { return Manufacturer; } public void setManufacturer(String Manufacturer) { this.Manufacturer = Manufacturer; } public String getMedicationCompanyName() { return MedicationCompanyName; } public void setMedicationCompanyName(String MedicationCompanyName) { this.MedicationCompanyName = MedicationCompanyName; } } } }
UTF-8
Java
3,134
java
DugsEntity.java
Java
[ { "context": "entity;\n\nimport java.util.List;\n\n/**\n * Created by EDZ on 2018/11/8.\n */\n\npublic class DugsEntity {\n\n\n ", "end": 83, "score": 0.9993720650672913, "start": 80, "tag": "USERNAME", "value": "EDZ" }, { "context": " /**\n * Id : 25\n * Name : 阿司匹林肠溶片\n * Manufacturer : 德国拜耳医药保健有限公司启东分公司\n ", "end": 1743, "score": 0.9953204393386841, "start": 1736, "tag": "NAME", "value": "阿司匹林肠溶片" } ]
null
[]
package com.newdjk.member.ui.entity; import java.util.List; /** * Created by EDZ on 2018/11/8. */ public class DugsEntity { /** * Code : 0 * Message : * Data : {"Total":297,"ReturnData":[{"Id":25,"Name":"阿司匹林肠溶片","Manufacturer":"德国拜耳医药保健有限公司启东分公司","MedicationCompanyName":"新起点药房"},{"Id":64,"Name":"奥利司他胶囊","Manufacturer":"中山万汉医药科技有限公司","MedicationCompanyName":"新起点药房"}]} */ private int Code; private String Message; private DataBean Data; public int getCode() { return Code; } public void setCode(int Code) { this.Code = Code; } public String getMessage() { return Message; } public void setMessage(String Message) { this.Message = Message; } public DataBean getData() { return Data; } public void setData(DataBean Data) { this.Data = Data; } public static class DataBean { /** * Total : 297 * ReturnData : [{"Id":25,"Name":"阿司匹林肠溶片","Manufacturer":"德国拜耳医药保健有限公司启东分公司","MedicationCompanyName":"新起点药房"},{"Id":64,"Name":"奥利司他胶囊","Manufacturer":"中山万汉医药科技有限公司","MedicationCompanyName":"新起点药房"}] */ private int Total; private List<ReturnDataBean> ReturnData; public int getTotal() { return Total; } public void setTotal(int Total) { this.Total = Total; } public List<ReturnDataBean> getReturnData() { return ReturnData; } public void setReturnData(List<ReturnDataBean> ReturnData) { this.ReturnData = ReturnData; } public static class ReturnDataBean { /** * Id : 25 * Name : 阿司匹林肠溶片 * Manufacturer : 德国拜耳医药保健有限公司启东分公司 * MedicationCompanyName : 新起点药房 */ private int Id; private String Name; private String Manufacturer; private String MedicationCompanyName; public int getId() { return Id; } public void setId(int Id) { this.Id = Id; } public String getName() { return Name; } public void setName(String Name) { this.Name = Name; } public String getManufacturer() { return Manufacturer; } public void setManufacturer(String Manufacturer) { this.Manufacturer = Manufacturer; } public String getMedicationCompanyName() { return MedicationCompanyName; } public void setMedicationCompanyName(String MedicationCompanyName) { this.MedicationCompanyName = MedicationCompanyName; } } } }
3,134
0.5394
0.531032
117
23.512821
31.293377
224
false
false
0
0
0
0
0
0
0.376068
false
false
3
0eea9fd7a173e571a5be5c73283f618820163677
7,808,250,553,810
895706817472d27e4459791a86533a3e6ed10202
/src/main/java/com/solution/boj/solution/stackSequence.java
cc2887c27c0eecc6c564cecbc5c5b1f1a8f0e115
[]
no_license
shfksekdrms2/BOJ
https://github.com/shfksekdrms2/BOJ
8701ad424512462640d42c597a69fb53648e8997
51dfa011cc7575614d89801f87e410aafaf241b2
refs/heads/master
2022-12-09T05:30:56.772000
2022-11-30T02:44:56
2022-11-30T02:44:56
112,995,528
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.solution.boj.solution; import java.util.ArrayList; import java.util.Scanner; //1874 public class stackSequence { public static void main(String[] args) { ArrayList<Integer> list = new ArrayList<Integer>(); //���� list ArrayList<Integer> list2 = new ArrayList<Integer>(); //�������� Ȯ���ϴ� list ArrayList<String> listTotal = new ArrayList<String>(); Scanner sc = new Scanner(System.in); boolean success = true; int n = sc.nextInt(); int i, j, k = 0; for (i = 0; i < n; i++) { list.add(sc.nextInt()); } int value = 1; for (j = 0; j < n * 2; j++) { if (list2.isEmpty() == true) { list2.add(value++); listTotal.add("+"); } else { if (list2.get(list2.size() - 1) < list.get(k)) { list2.add(value++); listTotal.add("+"); } else if (list2.get(list2.size() - 1) == list.get(k)) { // System.out.println("list2.get(list2.size()-1: "+list2.get(list2.size()-1)); list2.remove(list2.size() - 1); k++; listTotal.add("-"); } else { success = false; break; } } } // System.out.println("listTotal.size(): "+listTotal.size()); if (success == true && list2.isEmpty() == true && value == n + 1 && j == n * 2) { for (i = 0; i < n * 2; i++) { System.out.println(listTotal.get(i)); } } else { System.out.println("NO"); } } }
UTF-8
Java
1,719
java
stackSequence.java
Java
[]
null
[]
package com.solution.boj.solution; import java.util.ArrayList; import java.util.Scanner; //1874 public class stackSequence { public static void main(String[] args) { ArrayList<Integer> list = new ArrayList<Integer>(); //���� list ArrayList<Integer> list2 = new ArrayList<Integer>(); //�������� Ȯ���ϴ� list ArrayList<String> listTotal = new ArrayList<String>(); Scanner sc = new Scanner(System.in); boolean success = true; int n = sc.nextInt(); int i, j, k = 0; for (i = 0; i < n; i++) { list.add(sc.nextInt()); } int value = 1; for (j = 0; j < n * 2; j++) { if (list2.isEmpty() == true) { list2.add(value++); listTotal.add("+"); } else { if (list2.get(list2.size() - 1) < list.get(k)) { list2.add(value++); listTotal.add("+"); } else if (list2.get(list2.size() - 1) == list.get(k)) { // System.out.println("list2.get(list2.size()-1: "+list2.get(list2.size()-1)); list2.remove(list2.size() - 1); k++; listTotal.add("-"); } else { success = false; break; } } } // System.out.println("listTotal.size(): "+listTotal.size()); if (success == true && list2.isEmpty() == true && value == n + 1 && j == n * 2) { for (i = 0; i < n * 2; i++) { System.out.println(listTotal.get(i)); } } else { System.out.println("NO"); } } }
1,719
0.44451
0.424926
48
34.104168
22.067358
89
false
false
0
0
0
0
0
0
0.833333
false
false
3
a80d81e61ef1dc9c7d07043ce039416cadb7f9f4
7,808,250,556,621
58802b8543b7db115d8174352317145db1b4ebdb
/app/src/main/java/com/example/lenovocomp/password_manager/Register.java
d907cdb042d410a587335abf2377ffb9b495b6b5
[]
no_license
abdulrehman03365/Passwordmanager
https://github.com/abdulrehman03365/Passwordmanager
0a7a068f2e084d4eab2239873c3544b8ae591c2b
dd8ecbb762ee354ed6a1ae9e100f37cb60865794
refs/heads/master
2020-04-08T05:24:25.229000
2018-11-25T15:56:59
2018-11-25T15:56:59
159,059,108
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.lenovocomp.password_manager; import android.content.Intent; import android.support.annotation.NonNull; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.AuthResult; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseAuthException; public class Register extends AppCompatActivity implements View.OnClickListener{ private FirebaseAuth mAuth; public Button signupbt; public EditText emailtxt; public EditText passwordtxt; @Override public void onStart() { super.onStart(); mAuth= FirebaseAuth.getInstance(); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_sout); signupbt = (Button) findViewById(R.id.Signupbt); emailtxt = (EditText) findViewById(R.id.Emailtxt); passwordtxt = (EditText) findViewById(R.id.passwordbox); signupbt.setOnClickListener(this); mAuth=FirebaseAuth.getInstance(); } @Override public void onClick(View v) { String email = emailtxt.getText().toString(); String password = passwordtxt.getText().toString(); mAuth.createUserWithEmailAndPassword( email, password).addOnCompleteListener(Register.this, new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if (task.isSuccessful()) { Toast.makeText(Register.this, "yo", Toast.LENGTH_LONG).show(); Intent intent = new Intent(Register.this, Login.class); startActivity(intent); } else { if(!task.isSuccessful()){ FirebaseAuthException e = (FirebaseAuthException )task.getException(); Toast.makeText(Register.this, "Failed Registration: "+e.getMessage(), Toast.LENGTH_SHORT).show(); } } } }); } }
UTF-8
Java
2,365
java
Register.java
Java
[]
null
[]
package com.example.lenovocomp.password_manager; import android.content.Intent; import android.support.annotation.NonNull; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.AuthResult; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseAuthException; public class Register extends AppCompatActivity implements View.OnClickListener{ private FirebaseAuth mAuth; public Button signupbt; public EditText emailtxt; public EditText passwordtxt; @Override public void onStart() { super.onStart(); mAuth= FirebaseAuth.getInstance(); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_sout); signupbt = (Button) findViewById(R.id.Signupbt); emailtxt = (EditText) findViewById(R.id.Emailtxt); passwordtxt = (EditText) findViewById(R.id.passwordbox); signupbt.setOnClickListener(this); mAuth=FirebaseAuth.getInstance(); } @Override public void onClick(View v) { String email = emailtxt.getText().toString(); String password = passwordtxt.getText().toString(); mAuth.createUserWithEmailAndPassword( email, password).addOnCompleteListener(Register.this, new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if (task.isSuccessful()) { Toast.makeText(Register.this, "yo", Toast.LENGTH_LONG).show(); Intent intent = new Intent(Register.this, Login.class); startActivity(intent); } else { if(!task.isSuccessful()){ FirebaseAuthException e = (FirebaseAuthException )task.getException(); Toast.makeText(Register.this, "Failed Registration: "+e.getMessage(), Toast.LENGTH_SHORT).show(); } } } }); } }
2,365
0.653277
0.652854
78
29.320513
28.92408
138
false
false
0
0
0
0
0
0
0.538462
false
false
3
85a0206f64486317775dc87e6019cf6b30667aca
8,933,531,987,667
82e0704e9fb3615b363c48b65821902e5945d6d6
/src/main/java/com/wangming/pattern/structural/decorator/SuasageDecorator.java
f8dc345abaf8092f920f5f306c9061fae38d4e24
[]
no_license
wangming91/design
https://github.com/wangming91/design
1d41fd491c96a3c16a5dc507eb74142d694f5053
06aba4ceb35ae049f08761eec66c16ee2a637e23
refs/heads/master
2020-04-14T22:39:24.575000
2019-03-12T05:50:49
2019-03-12T05:50:49
164,172,195
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.wangming.pattern.structural.decorator; /** * @Auther: ming.wang * @Date: 2019/2/23 13:52 * @Description: 具体的装饰类(香肠) */ public class SuasageDecorator extends AbstractDecorator { public SuasageDecorator(Cake cake) { super(cake); } @Override public String getName() { return super.getName()+" 再加一根香肠"; } @Override public long cost() { return super.cost()+2; } }
UTF-8
Java
468
java
SuasageDecorator.java
Java
[ { "context": "ing.pattern.structural.decorator;\n\n/**\n * @Auther: ming.wang\n * @Date: 2019/2/23 13:52\n * @Description: 具体的装饰类", "end": 77, "score": 0.9666443467140198, "start": 68, "tag": "USERNAME", "value": "ming.wang" } ]
null
[]
package com.wangming.pattern.structural.decorator; /** * @Auther: ming.wang * @Date: 2019/2/23 13:52 * @Description: 具体的装饰类(香肠) */ public class SuasageDecorator extends AbstractDecorator { public SuasageDecorator(Cake cake) { super(cake); } @Override public String getName() { return super.getName()+" 再加一根香肠"; } @Override public long cost() { return super.cost()+2; } }
468
0.62156
0.594037
24
17.166666
16.957462
57
false
false
0
0
0
0
0
0
0.166667
false
false
3
f362c089eb646f11f147d4a76a2b8ef6e5283852
31,404,800,877,567
e5a14a68c3953ae9bd5f9d4f58d05959de552c63
/Contents/core/java/field/bytecode/protect/annotations/Aliasing.java
9342c09c05cfe8b00f21e13a934c1d21b77d375e
[]
no_license
GardenerOfEden/Field
https://github.com/GardenerOfEden/Field
d2d022067363e0bdaf1deb1d04b2f5c64970ce4f
213fc210af8b1c2f24184b4251b72bf0457de119
refs/heads/master
2021-01-14T13:21:10.711000
2016-09-16T17:32:39
2016-09-16T17:32:39
68,333,650
0
0
null
true
2016-09-15T21:43:53
2016-09-15T21:43:53
2016-08-27T23:16:11
2015-05-20T20:07:41
116,805
0
0
0
null
null
null
package field.bytecode.protect.annotations; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target(value={ElementType.CONSTRUCTOR, ElementType.METHOD}) @Retention(value=RetentionPolicy.RUNTIME) public @interface Aliasing { public String key() default ""; public String value() default ""; }
UTF-8
Java
409
java
Aliasing.java
Java
[]
null
[]
package field.bytecode.protect.annotations; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target(value={ElementType.CONSTRUCTOR, ElementType.METHOD}) @Retention(value=RetentionPolicy.RUNTIME) public @interface Aliasing { public String key() default ""; public String value() default ""; }
409
0.806846
0.806846
13
30.461538
18.053831
60
false
false
0
0
0
0
0
0
0.769231
false
false
3
aac663bb66b8ff0c88df916c1b0aba8efb80cefa
1,580,547,977,554
f09488156127577a28fe1891c0443a43ef1aaf29
/lib/QMBForm/src/main/java/com/quemb/qmbform/view/FormButtonFieldCell.java
bac5732ec1cee754f6181e32d5faaec8ee2380f2
[ "MIT" ]
permissive
quemb/QMBForm-FontAwesomeExtension
https://github.com/quemb/QMBForm-FontAwesomeExtension
5efc255e2fe022255ae36da8448ca197341559ce
c8fdc9008c7954422c3f792e54dfe6736ebfd89c
refs/heads/master
2016-09-02T06:15:15.377000
2015-01-14T10:45:31
2015-01-14T10:45:31
29,010,122
3
2
null
false
2015-01-14T10:45:34
2015-01-09T09:36:40
2015-01-14T10:45:33
2015-01-14T10:45:33
0
0
3
0
Java
null
null
package com.quemb.qmbform.view; import com.quemb.qmbform.R; import com.quemb.qmbform.descriptor.RowDescriptor; import android.content.Context; /** * Created by tonimoeckel on 15.07.14. */ public class FormButtonFieldCell extends FormTitleFieldCell { public FormButtonFieldCell(Context context, RowDescriptor rowDescriptor) { super(context, rowDescriptor); } @Override protected int getResource() { return R.layout.button_field_cell; } @Override public void onCellSelected() { super.onCellSelected(); } }
UTF-8
Java
585
java
FormButtonFieldCell.java
Java
[ { "context": "import android.content.Context;\n\n/**\n * Created by tonimoeckel on 15.07.14.\n */\npublic class FormButtonFieldCell", "end": 175, "score": 0.9987034797668457, "start": 164, "tag": "USERNAME", "value": "tonimoeckel" } ]
null
[]
package com.quemb.qmbform.view; import com.quemb.qmbform.R; import com.quemb.qmbform.descriptor.RowDescriptor; import android.content.Context; /** * Created by tonimoeckel on 15.07.14. */ public class FormButtonFieldCell extends FormTitleFieldCell { public FormButtonFieldCell(Context context, RowDescriptor rowDescriptor) { super(context, rowDescriptor); } @Override protected int getResource() { return R.layout.button_field_cell; } @Override public void onCellSelected() { super.onCellSelected(); } }
585
0.68718
0.676923
32
17.28125
19.021755
61
false
false
0
0
0
0
0
0
0.28125
false
false
3
bf695666c23c348901d5f66a5321100bc10286ef
27,127,013,454,608
4d984a1741df433ec08e8105ea922bd13c336207
/src/model/DataStructure.java
5b6123bbb028011188d1dfde9ad7f6acb7bbbe64
[]
no_license
brian-pratama/QEC
https://github.com/brian-pratama/QEC
bcedd383b0eb33adcde90029106ac0b79d77dcb3
1003456d9975628f7b373e3da74555ea3804aa86
refs/heads/master
2021-08-27T17:00:35.605000
2017-02-18T06:13:01
2017-02-18T06:13:01
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package model; public class DataStructure { /* * class untuk setiap orang yang menunggu di antrian * time: waktu arrival/departure * status: arrival/departure */ public class person{ private double time; private String status; public person(double time, String status){ setTime(time); setStatus(status); } public void setTime(double time){ this.time = time; } public double getTime(){ return time; } public void setStatus(String status){ this.status = status; } public String getStatus(){ return status; } } public class nQueue{ public nQueue(int Q, double time){ setQ(Q); setTime(time); } private int Q; private double time; public void setQ(int Q){ this.Q = Q; } public int getQ(){ return Q; } public void setTime(double time){ this.time = time; } public double getTime(){ return time; } } }
UTF-8
Java
1,005
java
DataStructure.java
Java
[]
null
[]
package model; public class DataStructure { /* * class untuk setiap orang yang menunggu di antrian * time: waktu arrival/departure * status: arrival/departure */ public class person{ private double time; private String status; public person(double time, String status){ setTime(time); setStatus(status); } public void setTime(double time){ this.time = time; } public double getTime(){ return time; } public void setStatus(String status){ this.status = status; } public String getStatus(){ return status; } } public class nQueue{ public nQueue(int Q, double time){ setQ(Q); setTime(time); } private int Q; private double time; public void setQ(int Q){ this.Q = Q; } public int getQ(){ return Q; } public void setTime(double time){ this.time = time; } public double getTime(){ return time; } } }
1,005
0.58209
0.58209
66
13.227273
12.93667
53
false
false
0
0
0
0
0
0
2.151515
false
false
3
6fdf45ac3c2bfbab236907771f019dfafff1ffaa
28,217,935,146,181
6dc40cb729e165b73c8bd89a15e289de598c1150
/antrpc-commons/src/main/java/io/github/wanggit/antrpc/commons/utils/NetUtil.java
b6d9381a2543564210f525a6a7bad71d88028a63
[ "Apache-2.0" ]
permissive
wanggit/antrpc
https://github.com/wanggit/antrpc
7066c859a66fd0c276649fdbd9ba106a5809d951
1eb19a3f32d916af31e12cd7207740217e0b9f5e
refs/heads/master
2020-08-22T22:31:22.416000
2020-03-25T08:02:50
2020-03-25T08:02:50
216,488,768
2
1
Apache-2.0
false
2020-03-25T07:19:56
2019-10-21T05:58:56
2020-03-24T10:42:11
2020-03-25T07:19:55
78,547
1
1
0
Java
false
false
package io.github.wanggit.antrpc.commons.utils; import lombok.extern.slf4j.Slf4j; import java.net.InetAddress; import java.net.UnknownHostException; @Slf4j public abstract class NetUtil { public static String getLocalIp() { try { InetAddress inetAddress = InetAddress.getLocalHost(); return inetAddress.getHostAddress(); } catch (UnknownHostException e) { if (log.isErrorEnabled()) { log.error("Unable to obtain native IP address.", e); } throw new RuntimeException(); } } }
UTF-8
Java
587
java
NetUtil.java
Java
[ { "context": "package io.github.wanggit.antrpc.commons.utils;\n\nimport lombok.extern.slf4j", "end": 25, "score": 0.9924615621566772, "start": 18, "tag": "USERNAME", "value": "wanggit" } ]
null
[]
package io.github.wanggit.antrpc.commons.utils; import lombok.extern.slf4j.Slf4j; import java.net.InetAddress; import java.net.UnknownHostException; @Slf4j public abstract class NetUtil { public static String getLocalIp() { try { InetAddress inetAddress = InetAddress.getLocalHost(); return inetAddress.getHostAddress(); } catch (UnknownHostException e) { if (log.isErrorEnabled()) { log.error("Unable to obtain native IP address.", e); } throw new RuntimeException(); } } }
587
0.630324
0.625213
22
25.681818
21.344334
68
false
false
0
0
0
0
0
0
0.409091
false
false
3
fc00fb9237b15d66a66bf482d25fab58b0de7e30
16,973,710,758,477
4efd9381fd9fae03a3edafc61387aab4543bb5a5
/src/main/java/net/maitland/quest/parser/sax/SaxQuestParser.java
b951c6ac04d3cecaece29351a8163536eed59cb4
[]
no_license
dtsm12/quest-story-player
https://github.com/dtsm12/quest-story-player
7506bfa1e59bafee598575d004e7905356560a3f
2039c332b229073fdab32fe9d9bd8e240bc8fb42
refs/heads/master
2021-01-12T02:31:21.194000
2017-07-23T21:36:17
2017-07-23T21:36:17
78,055,592
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package net.maitland.quest.parser.sax; import net.maitland.quest.model.*; import net.maitland.quest.model.attribute.Attribute; import net.maitland.quest.model.attribute.NumberAttribute; import net.maitland.quest.model.attribute.StateAttribute; import net.maitland.quest.model.attribute.StringAttribute; import net.maitland.quest.parser.AbstractQuestParser; import org.apache.commons.beanutils.PropertyUtils; import org.xml.sax.Attributes; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.XMLReader; import org.xml.sax.helpers.DefaultHandler; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import java.beans.Statement; import java.io.IOException; import java.io.InputStream; import java.io.StringReader; import java.lang.reflect.InvocationTargetException; /** * Created by David on 06/01/2017. */ public class SaxQuestParser extends AbstractQuestParser { @Override public Quest parseQuest(InputStream story) throws IOException { try { String storyStr = removeMixedContent(story); StringReader sr = new StringReader(storyStr); QuestContentHandler qch = new QuestContentHandler(); SAXParserFactory spf = SAXParserFactory.newInstance(); SAXParser saxParser = spf.newSAXParser(); XMLReader xmlReader = saxParser.getXMLReader(); xmlReader.setEntityResolver(new ClasspathSystemEntityResolver()); xmlReader.setContentHandler(qch); xmlReader.parse(new InputSource(sr)); return qch.getQuest(); } catch (Exception e) { throw new IOException(e); } } private class QuestContentHandler extends DefaultHandler { private Quest quest; private About about; private QuestStation station; private QuestSection questSection; private Text text; private Choice choice; private StringBuilder currentCharacters = new StringBuilder(); public Quest getQuest() { return quest; } @Override public void startDocument() throws SAXException { this.quest = new Quest(); } @Override public void endDocument() throws SAXException { } @Override public void characters(char[] ch, int start, int length) throws SAXException { for (int i = start; i < start + length; i++) { if(Character.isISOControl(ch[i]) == false) { currentCharacters.append(ch[i]); } else { currentCharacters.append(" "); } } } @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { this.currentCharacters = new StringBuilder(); if (qName.equals("about")) { startAbout(attributes); } if (qName.equals("title")) { startTitle(attributes); } if (qName.equals("author")) { startAuthor(attributes); } if (qName.equals("intro")) { startIntro(attributes); } if (qName.equals("station")) { startStation(attributes); } if (qName.equals("text")) { startText(attributes); } if (qName.equals("include")) { startInclude(attributes); } if (qName.equals("in")) { startIncludeRule(attributes); } if (qName.equals("choice")) { startChoice(attributes); } if (qName.equals("number")) { startNumber(attributes); } if (qName.equals("string")) { startString(attributes); } if (qName.equals("state")) { startState(attributes); } if (qName.equals("if")) { startIf(attributes); } if (qName.equals("else")) { startElse(attributes); } } @Override public void endElement(String uri, String localName, String qName) throws SAXException { if (qName.equals("about")) { endAbout(); } if (qName.equals("title")) { endTitle(); } if (qName.equals("author")) { endAuthor(); } if (qName.equals("intro")) { endIntro(); } if (qName.equals("station")) { endStation(); } if (qName.equals("text")) { endText(); } if (qName.equals("include")) { endInclude(); } if (qName.equals("in")) { endIncludeRule(); } if (qName.equals("choice")) { endChoice(); } if (qName.equals("number")) { endNumber(); } if (qName.equals("string")) { endString(); } if (qName.equals("state")) { endState(); } if (qName.equals("if")) { endIf(); } if (qName.equals("else")) { endElse(); } } protected void startAbout(Attributes attributes) throws SAXException { this.about = new About(); } protected void endAbout() throws SAXException { this.quest.setAbout(this.about); } protected void startTitle(Attributes attributes) throws SAXException { } protected void endTitle() throws SAXException { this.about.setTitle(getCharacters()); } protected void startAuthor(Attributes attributes) throws SAXException { } protected void endAuthor() throws SAXException { this.about.setAuthor(getCharacters()); } protected void startIntro(Attributes attributes) throws SAXException { } protected void endIntro() throws SAXException { this.about.setIntro(getCharacters()); } protected void startStation(Attributes attributes) throws SAXException { String id = attributes.getValue("id"); this.station = new QuestStation(); this.station.setId(id); this.questSection = this.station; } protected void endStation() throws SAXException { this.quest.addStation(this.station); this.station = null; this.questSection = null; } protected void startText(Attributes attributes) throws SAXException { String check = attributes.getValue("check"); this.text = new Text(); this.text.setCheck(check); } protected void endText() throws SAXException { this.text.setValue(getCharacters()); this.questSection.addText(this.text); this.text = null; } protected void startInclude(Attributes attributes) throws SAXException { String check = attributes.getValue("check"); String process = attributes.getValue("process"); IncludedStation include = new IncludedStation(); include.setCheck(check); if (process != null) { include.setProcess(IncludeProcess.valueOf(process)); } this.station.setStationIncludeRules(include); } protected void endInclude() throws SAXException { } protected void startIncludeRule(Attributes attributes) throws SAXException { String station = attributes.getValue("station"); this.station.getStationIncludeRules().addStationPatterns(station); } protected void endIncludeRule() throws SAXException { } protected void startChoice(Attributes attributes) throws SAXException { String stationId = attributes.getValue("station"); String check = attributes.getValue("check"); this.choice = new Choice(); this.choice.setStationId(stationId); this.choice.setCheck(check); } protected void endChoice() throws SAXException { this.choice.setText(getCharacters()); this.questSection.addChoice(this.choice); this.choice = null; } protected void startNumber(Attributes properties) throws SAXException { NumberAttribute attribute = new NumberAttribute(); setAttributes(attribute, properties); this.questSection.addAttribute(attribute); } protected void setAttributes(Attribute target, Attributes properties) throws SAXException { for (int i=0; i< properties.getLength();i++) { try { PropertyUtils.setSimpleProperty(target, properties.getLocalName(i), properties.getValue(i)); } catch (Exception e) { throw new SAXException(e); } } } protected void endNumber() throws SAXException { } protected void startString(Attributes attributes) throws SAXException { String name = attributes.getValue("name"); String value = attributes.getValue("value"); StringAttribute attribute = new StringAttribute(name, value); this.questSection.addAttribute(attribute); } protected void endString() throws SAXException { } protected void startState(Attributes attributes) throws SAXException { String name = attributes.getValue("name"); String value = attributes.getValue("value"); StateAttribute attribute = new StateAttribute(name, value); this.questSection.addAttribute(attribute); } protected void endState() throws SAXException { } protected void startIf(Attributes attributes) throws SAXException { String check = attributes.getValue("check"); IfSection ifSection = new IfSection(); ifSection.setCheck(check); this.questSection = ifSection; } protected void endIf() throws SAXException { this.station.addCondition((IfSection) this.questSection); this.questSection = this.station; } protected void startElse(Attributes attributes) throws SAXException { ElseSection elseSection = new ElseSection(); this.questSection = elseSection; } protected void endElse() throws SAXException { this.station.setElseCondition((ElseSection) this.questSection); this.questSection = this.station; } protected String getCharacters() { return this.currentCharacters.toString().replace(".", ". "); } } }
UTF-8
Java
11,259
java
SaxQuestParser.java
Java
[ { "context": "lect.InvocationTargetException;\n\n/**\n * Created by David on 06/01/2017.\n */\npublic class SaxQuestParser ex", "end": 848, "score": 0.9982936382293701, "start": 843, "tag": "NAME", "value": "David" } ]
null
[]
package net.maitland.quest.parser.sax; import net.maitland.quest.model.*; import net.maitland.quest.model.attribute.Attribute; import net.maitland.quest.model.attribute.NumberAttribute; import net.maitland.quest.model.attribute.StateAttribute; import net.maitland.quest.model.attribute.StringAttribute; import net.maitland.quest.parser.AbstractQuestParser; import org.apache.commons.beanutils.PropertyUtils; import org.xml.sax.Attributes; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.XMLReader; import org.xml.sax.helpers.DefaultHandler; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import java.beans.Statement; import java.io.IOException; import java.io.InputStream; import java.io.StringReader; import java.lang.reflect.InvocationTargetException; /** * Created by David on 06/01/2017. */ public class SaxQuestParser extends AbstractQuestParser { @Override public Quest parseQuest(InputStream story) throws IOException { try { String storyStr = removeMixedContent(story); StringReader sr = new StringReader(storyStr); QuestContentHandler qch = new QuestContentHandler(); SAXParserFactory spf = SAXParserFactory.newInstance(); SAXParser saxParser = spf.newSAXParser(); XMLReader xmlReader = saxParser.getXMLReader(); xmlReader.setEntityResolver(new ClasspathSystemEntityResolver()); xmlReader.setContentHandler(qch); xmlReader.parse(new InputSource(sr)); return qch.getQuest(); } catch (Exception e) { throw new IOException(e); } } private class QuestContentHandler extends DefaultHandler { private Quest quest; private About about; private QuestStation station; private QuestSection questSection; private Text text; private Choice choice; private StringBuilder currentCharacters = new StringBuilder(); public Quest getQuest() { return quest; } @Override public void startDocument() throws SAXException { this.quest = new Quest(); } @Override public void endDocument() throws SAXException { } @Override public void characters(char[] ch, int start, int length) throws SAXException { for (int i = start; i < start + length; i++) { if(Character.isISOControl(ch[i]) == false) { currentCharacters.append(ch[i]); } else { currentCharacters.append(" "); } } } @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { this.currentCharacters = new StringBuilder(); if (qName.equals("about")) { startAbout(attributes); } if (qName.equals("title")) { startTitle(attributes); } if (qName.equals("author")) { startAuthor(attributes); } if (qName.equals("intro")) { startIntro(attributes); } if (qName.equals("station")) { startStation(attributes); } if (qName.equals("text")) { startText(attributes); } if (qName.equals("include")) { startInclude(attributes); } if (qName.equals("in")) { startIncludeRule(attributes); } if (qName.equals("choice")) { startChoice(attributes); } if (qName.equals("number")) { startNumber(attributes); } if (qName.equals("string")) { startString(attributes); } if (qName.equals("state")) { startState(attributes); } if (qName.equals("if")) { startIf(attributes); } if (qName.equals("else")) { startElse(attributes); } } @Override public void endElement(String uri, String localName, String qName) throws SAXException { if (qName.equals("about")) { endAbout(); } if (qName.equals("title")) { endTitle(); } if (qName.equals("author")) { endAuthor(); } if (qName.equals("intro")) { endIntro(); } if (qName.equals("station")) { endStation(); } if (qName.equals("text")) { endText(); } if (qName.equals("include")) { endInclude(); } if (qName.equals("in")) { endIncludeRule(); } if (qName.equals("choice")) { endChoice(); } if (qName.equals("number")) { endNumber(); } if (qName.equals("string")) { endString(); } if (qName.equals("state")) { endState(); } if (qName.equals("if")) { endIf(); } if (qName.equals("else")) { endElse(); } } protected void startAbout(Attributes attributes) throws SAXException { this.about = new About(); } protected void endAbout() throws SAXException { this.quest.setAbout(this.about); } protected void startTitle(Attributes attributes) throws SAXException { } protected void endTitle() throws SAXException { this.about.setTitle(getCharacters()); } protected void startAuthor(Attributes attributes) throws SAXException { } protected void endAuthor() throws SAXException { this.about.setAuthor(getCharacters()); } protected void startIntro(Attributes attributes) throws SAXException { } protected void endIntro() throws SAXException { this.about.setIntro(getCharacters()); } protected void startStation(Attributes attributes) throws SAXException { String id = attributes.getValue("id"); this.station = new QuestStation(); this.station.setId(id); this.questSection = this.station; } protected void endStation() throws SAXException { this.quest.addStation(this.station); this.station = null; this.questSection = null; } protected void startText(Attributes attributes) throws SAXException { String check = attributes.getValue("check"); this.text = new Text(); this.text.setCheck(check); } protected void endText() throws SAXException { this.text.setValue(getCharacters()); this.questSection.addText(this.text); this.text = null; } protected void startInclude(Attributes attributes) throws SAXException { String check = attributes.getValue("check"); String process = attributes.getValue("process"); IncludedStation include = new IncludedStation(); include.setCheck(check); if (process != null) { include.setProcess(IncludeProcess.valueOf(process)); } this.station.setStationIncludeRules(include); } protected void endInclude() throws SAXException { } protected void startIncludeRule(Attributes attributes) throws SAXException { String station = attributes.getValue("station"); this.station.getStationIncludeRules().addStationPatterns(station); } protected void endIncludeRule() throws SAXException { } protected void startChoice(Attributes attributes) throws SAXException { String stationId = attributes.getValue("station"); String check = attributes.getValue("check"); this.choice = new Choice(); this.choice.setStationId(stationId); this.choice.setCheck(check); } protected void endChoice() throws SAXException { this.choice.setText(getCharacters()); this.questSection.addChoice(this.choice); this.choice = null; } protected void startNumber(Attributes properties) throws SAXException { NumberAttribute attribute = new NumberAttribute(); setAttributes(attribute, properties); this.questSection.addAttribute(attribute); } protected void setAttributes(Attribute target, Attributes properties) throws SAXException { for (int i=0; i< properties.getLength();i++) { try { PropertyUtils.setSimpleProperty(target, properties.getLocalName(i), properties.getValue(i)); } catch (Exception e) { throw new SAXException(e); } } } protected void endNumber() throws SAXException { } protected void startString(Attributes attributes) throws SAXException { String name = attributes.getValue("name"); String value = attributes.getValue("value"); StringAttribute attribute = new StringAttribute(name, value); this.questSection.addAttribute(attribute); } protected void endString() throws SAXException { } protected void startState(Attributes attributes) throws SAXException { String name = attributes.getValue("name"); String value = attributes.getValue("value"); StateAttribute attribute = new StateAttribute(name, value); this.questSection.addAttribute(attribute); } protected void endState() throws SAXException { } protected void startIf(Attributes attributes) throws SAXException { String check = attributes.getValue("check"); IfSection ifSection = new IfSection(); ifSection.setCheck(check); this.questSection = ifSection; } protected void endIf() throws SAXException { this.station.addCondition((IfSection) this.questSection); this.questSection = this.station; } protected void startElse(Attributes attributes) throws SAXException { ElseSection elseSection = new ElseSection(); this.questSection = elseSection; } protected void endElse() throws SAXException { this.station.setElseCondition((ElseSection) this.questSection); this.questSection = this.station; } protected String getCharacters() { return this.currentCharacters.toString().replace(".", ". "); } } }
11,259
0.566214
0.565414
369
29.512196
25.117296
121
false
false
0
0
0
0
0
0
0.398374
false
false
3
167e2eafeda415636194c695bbadf457e3b3b750
9,990,093,945,162
8284e5621d157b41842b2927200e83c68497e252
/app/src/main/java/com/example/administrator/smallhappypay/activity/test/ChartTwoActivity.java
504d5a4863c01928d0060bb343f98276d36c5bb5
[]
no_license
Shlhenry/SmallHappypay
https://github.com/Shlhenry/SmallHappypay
db8eb100c7afe269a1edaaf5f46f87ace8a9e4c0
c5c7b160bcf79eb7a4e9f2fdbaadbaea8be5f0b0
refs/heads/master
2020-03-26T23:23:07.259000
2018-08-21T08:19:33
2018-08-21T08:19:33
145,537,494
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.administrator.smallhappypay.activity.test; import android.app.Activity; import android.graphics.Color; import android.graphics.drawable.GradientDrawable; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.LinearLayout; import android.widget.PopupWindow; import android.widget.TextView; import android.widget.Toast; import com.example.administrator.smallhappypay.BaseActivity; import com.example.administrator.smallhappypay.R; import com.example.administrator.smallhappypay.net.Api; import com.example.administrator.smallhappypay.util.ChartBean; import com.github.mikephil.charting.charts.BarChart; import com.github.mikephil.charting.components.AxisBase; import com.github.mikephil.charting.components.Legend; import com.github.mikephil.charting.components.XAxis; import com.github.mikephil.charting.components.YAxis; import com.github.mikephil.charting.data.BarData; import com.github.mikephil.charting.data.BarDataSet; import com.github.mikephil.charting.data.BarEntry; import com.github.mikephil.charting.formatter.IAxisValueFormatter; import com.qmuiteam.qmui.util.QMUIDisplayHelper; import com.qmuiteam.qmui.widget.popup.QMUIListPopup; import com.qmuiteam.qmui.widget.popup.QMUIPopup; import java.util.ArrayList; import java.util.Calendar; import java.util.Collections; import java.util.List; import java.util.Locale; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; import static com.example.administrator.smallhappypay.App.getContext; public class ChartTwoActivity extends BaseActivity { @BindView(R.id.chart) BarChart barChart; @BindView(R.id.charttwo_ll) LinearLayout charttwoLl; @BindView(R.id.chart_month_tv) TextView chartMonthTv; private ChartBean chartBean; private QMUIListPopup mListPopup; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_chart_two); ButterKnife.bind(this); chartdata("883000000000105", "2018-07"); } private void zfb() { List<BarEntry> entriesGroup1 = new ArrayList<>(); List<BarEntry> entriesGroup2 = new ArrayList<>(); List<BarEntry> entriesGroup3 = new ArrayList<>(); List<ChartBean.MapBean.MonthMapBean.ZfbBeanX> zfbBeans = chartBean.getMap().getMonthMap().getZfb(); for (int i = 1; i <= getDayOfMonth(); i++) { boolean flag = true; for (ChartBean.MapBean.MonthMapBean.ZfbBeanX bean : zfbBeans) { if (bean.getTimequantum() == i) { entriesGroup1.add(new BarEntry(i+1, (float) bean.getTranmoney())); flag = false; break; } } if (flag) { entriesGroup1.add(new BarEntry(i, 0)); } } List<ChartBean.MapBean.MonthMapBean.WxBeanX> wxBeans = chartBean.getMap().getMonthMap().getWx(); for (int i = 1; i <= getDayOfMonth(); i++) { boolean flag = true; for (ChartBean.MapBean.MonthMapBean.WxBeanX bean : wxBeans) { if (bean.getTimequantum() == i) { entriesGroup2.add(new BarEntry(i, (float) bean.getTranmoney())); flag = false; break; } } if (flag) { entriesGroup2.add(new BarEntry(i, 0)); } } List<ChartBean.MapBean.MonthMapBean.PosBeanX> posBeans = chartBean.getMap().getMonthMap().getPos(); for (int i = 1; i <= getDayOfMonth(); i++) { boolean flag = true; for (ChartBean.MapBean.MonthMapBean.PosBeanX bean : posBeans) { if (bean.getTimequantum() == i) { entriesGroup3.add(new BarEntry(i, (float) bean.getTranmoney())); flag = false; break; } } if (flag) { entriesGroup3.add(new BarEntry(i, 0)); } } YAxis yAxis = barChart.getAxisLeft(); yAxis.setTextSize(12f); // 设置字体大小 yAxis.setAxisMinimum(0f); // 设置坐标轴从0开始 yAxis.setTextColor(Color.RED); // 设置字体颜色为黑色 // yAxis.setAxisMaximum(100f); yAxis.setGranularity(1f); // 设置间隔为1 yAxis.setLabelCount(10, true); // 设置标签个数 //设置坐标轴线条颜色 yAxis.setAxisLineColor(Color.parseColor("#ffffff")); yAxis.setGridColor(Color.parseColor("#1affffff"));//网格线颜色 //Y轴字颜色 yAxis.setTextColor(Color.parseColor("#fdfdfd")); YAxis rightYAxis = barChart.getAxisRight(); //设置Y轴是否显示 rightYAxis.setEnabled(false); //右侧Y轴不显示 yAxis.setValueFormatter(new IAxisValueFormatter() { @Override public String getFormattedValue(float value, AxisBase axis) { return (int) value + "元"; } }); XAxis xAxis = barChart.getXAxis(); xAxis.setPosition(XAxis.XAxisPosition.BOTTOM); xAxis.setTextSize(10f); xAxis.setTextColor(Color.RED); xAxis.setDrawAxisLine(true); xAxis.setDrawGridLines(false); xAxis.setLabelCount(10); xAxis.setGranularity(1f); xAxis.setPosition(XAxis.XAxisPosition.BOTTOM); xAxis.setAxisLineColor(Color.parseColor("#1affffff"));//网格线颜色 //X轴字颜色 xAxis.setTextColor(Color.parseColor("#fdfdfd")); //设置坐标轴线条颜色 xAxis.setAxisLineColor(Color.parseColor("#ffffff")); xAxis.setValueFormatter(new IAxisValueFormatter() { @Override public String getFormattedValue(float value, AxisBase axis) { return (int) value + "号"; } }); //两组数据 BarDataSet set1 = new BarDataSet(entriesGroup1, "支付宝交易"); BarDataSet set2 = new BarDataSet(entriesGroup2, "微信交易"); BarDataSet set3 = new BarDataSet(entriesGroup3, "POS交易"); set1.setColor(GradientDrawable.LINEAR_GRADIENT); set1.setColor(Color.parseColor("#039feb")); set1.setValueTextColor(Color.parseColor("#ffffff")); set2.setColor(Color.parseColor("#19d100")); set2.setValueTextColor(Color.parseColor("#ffffff")); set3.setColor(Color.parseColor("#f7b43b")); set3.setValueTextColor(Color.parseColor("#ffffff")); //描述文字的颜色 Legend mLegend = barChart.getLegend(); // 设置坐标线描述?? 的样式 mLegend.setEnabled(false);//坐标线开关是否显示 mLegend.setTextColor(Color.parseColor("#ffffff"));// 坐标线描述文字的颜色 mLegend.setTextSize(8);// 坐标线描述文字的大小,单位dp int amount = 3;//条形图的组数三组 float groupSpace = 0.12f; //柱状图组之间的间距 float barSpace = (float) ((1 - 0.12) / amount / 10); // x4 DataSet float barWidth = (float) ((1 - 0.12) / amount / 10 * 9); // x4 DataSet // xAxis.setLabelCount(getDayOfMonth() , false); BarData data = new BarData(set1, set2, set3); //设置组数据 data.setBarWidth(barWidth); // 设置柱状条宽度 barChart.setData(data); barChart.groupBars(1f, groupSpace, barSpace); // 设置组样式宽度等 barChart.invalidate(); // 刷新 } private void chartdata(String am_number, String month) { Api.gethttpService().getReportData(am_number, month).enqueue(new Callback<ChartBean>() { @Override public void onResponse(Call<ChartBean> call, Response<ChartBean> response) { chartBean = response.body(); zfb(); } @Override public void onFailure(Call<ChartBean> call, Throwable t) { } }); } //java获取当前月的天数 public int getDayOfMonth() { Calendar aCalendar = Calendar.getInstance(Locale.CHINA); int day = aCalendar.getActualMaximum(Calendar.DATE); return day; } private void initListPopupIfNeed() { if (mListPopup == null) { List<Integer> mlist = new ArrayList<Integer>(); for (int i = 1; i <= 12; i++) { mlist.add(i); } ArrayAdapter adapter = new ArrayAdapter<>(ChartTwoActivity.this, R.layout.simple_list_item, mlist); mListPopup = new QMUIListPopup(ChartTwoActivity.this, QMUIPopup.DIRECTION_NONE, adapter);//必须使用本类类名不能getcontext mListPopup.create(QMUIDisplayHelper.dp2px(getContext(), 50), QMUIDisplayHelper.dp2px(getContext(), 200), new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { int a=i+1; String b=a < 10 ? "0" + a : a+""; chartMonthTv.setText(i+1+""); chartdata("883000000000105", "2017-"+b); mListPopup.dismiss(); } }); mListPopup.setOnDismissListener(new PopupWindow.OnDismissListener() { @Override public void onDismiss() { } }); } } @OnClick({R.id.chart_month_tv, R.id.charttwo_ll}) public void onViewClicked(View view) { switch (view.getId()) { case R.id.chart_month_tv: break; case R.id.charttwo_ll: initListPopupIfNeed(); mListPopup.setAnimStyle(QMUIPopup.ANIM_GROW_FROM_CENTER); mListPopup.setPreferredDirection(QMUIPopup.DIRECTION_BOTTOM); mListPopup.show(view); break; } } }
UTF-8
Java
10,460
java
ChartTwoActivity.java
Java
[]
null
[]
package com.example.administrator.smallhappypay.activity.test; import android.app.Activity; import android.graphics.Color; import android.graphics.drawable.GradientDrawable; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.LinearLayout; import android.widget.PopupWindow; import android.widget.TextView; import android.widget.Toast; import com.example.administrator.smallhappypay.BaseActivity; import com.example.administrator.smallhappypay.R; import com.example.administrator.smallhappypay.net.Api; import com.example.administrator.smallhappypay.util.ChartBean; import com.github.mikephil.charting.charts.BarChart; import com.github.mikephil.charting.components.AxisBase; import com.github.mikephil.charting.components.Legend; import com.github.mikephil.charting.components.XAxis; import com.github.mikephil.charting.components.YAxis; import com.github.mikephil.charting.data.BarData; import com.github.mikephil.charting.data.BarDataSet; import com.github.mikephil.charting.data.BarEntry; import com.github.mikephil.charting.formatter.IAxisValueFormatter; import com.qmuiteam.qmui.util.QMUIDisplayHelper; import com.qmuiteam.qmui.widget.popup.QMUIListPopup; import com.qmuiteam.qmui.widget.popup.QMUIPopup; import java.util.ArrayList; import java.util.Calendar; import java.util.Collections; import java.util.List; import java.util.Locale; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; import static com.example.administrator.smallhappypay.App.getContext; public class ChartTwoActivity extends BaseActivity { @BindView(R.id.chart) BarChart barChart; @BindView(R.id.charttwo_ll) LinearLayout charttwoLl; @BindView(R.id.chart_month_tv) TextView chartMonthTv; private ChartBean chartBean; private QMUIListPopup mListPopup; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_chart_two); ButterKnife.bind(this); chartdata("883000000000105", "2018-07"); } private void zfb() { List<BarEntry> entriesGroup1 = new ArrayList<>(); List<BarEntry> entriesGroup2 = new ArrayList<>(); List<BarEntry> entriesGroup3 = new ArrayList<>(); List<ChartBean.MapBean.MonthMapBean.ZfbBeanX> zfbBeans = chartBean.getMap().getMonthMap().getZfb(); for (int i = 1; i <= getDayOfMonth(); i++) { boolean flag = true; for (ChartBean.MapBean.MonthMapBean.ZfbBeanX bean : zfbBeans) { if (bean.getTimequantum() == i) { entriesGroup1.add(new BarEntry(i+1, (float) bean.getTranmoney())); flag = false; break; } } if (flag) { entriesGroup1.add(new BarEntry(i, 0)); } } List<ChartBean.MapBean.MonthMapBean.WxBeanX> wxBeans = chartBean.getMap().getMonthMap().getWx(); for (int i = 1; i <= getDayOfMonth(); i++) { boolean flag = true; for (ChartBean.MapBean.MonthMapBean.WxBeanX bean : wxBeans) { if (bean.getTimequantum() == i) { entriesGroup2.add(new BarEntry(i, (float) bean.getTranmoney())); flag = false; break; } } if (flag) { entriesGroup2.add(new BarEntry(i, 0)); } } List<ChartBean.MapBean.MonthMapBean.PosBeanX> posBeans = chartBean.getMap().getMonthMap().getPos(); for (int i = 1; i <= getDayOfMonth(); i++) { boolean flag = true; for (ChartBean.MapBean.MonthMapBean.PosBeanX bean : posBeans) { if (bean.getTimequantum() == i) { entriesGroup3.add(new BarEntry(i, (float) bean.getTranmoney())); flag = false; break; } } if (flag) { entriesGroup3.add(new BarEntry(i, 0)); } } YAxis yAxis = barChart.getAxisLeft(); yAxis.setTextSize(12f); // 设置字体大小 yAxis.setAxisMinimum(0f); // 设置坐标轴从0开始 yAxis.setTextColor(Color.RED); // 设置字体颜色为黑色 // yAxis.setAxisMaximum(100f); yAxis.setGranularity(1f); // 设置间隔为1 yAxis.setLabelCount(10, true); // 设置标签个数 //设置坐标轴线条颜色 yAxis.setAxisLineColor(Color.parseColor("#ffffff")); yAxis.setGridColor(Color.parseColor("#1affffff"));//网格线颜色 //Y轴字颜色 yAxis.setTextColor(Color.parseColor("#fdfdfd")); YAxis rightYAxis = barChart.getAxisRight(); //设置Y轴是否显示 rightYAxis.setEnabled(false); //右侧Y轴不显示 yAxis.setValueFormatter(new IAxisValueFormatter() { @Override public String getFormattedValue(float value, AxisBase axis) { return (int) value + "元"; } }); XAxis xAxis = barChart.getXAxis(); xAxis.setPosition(XAxis.XAxisPosition.BOTTOM); xAxis.setTextSize(10f); xAxis.setTextColor(Color.RED); xAxis.setDrawAxisLine(true); xAxis.setDrawGridLines(false); xAxis.setLabelCount(10); xAxis.setGranularity(1f); xAxis.setPosition(XAxis.XAxisPosition.BOTTOM); xAxis.setAxisLineColor(Color.parseColor("#1affffff"));//网格线颜色 //X轴字颜色 xAxis.setTextColor(Color.parseColor("#fdfdfd")); //设置坐标轴线条颜色 xAxis.setAxisLineColor(Color.parseColor("#ffffff")); xAxis.setValueFormatter(new IAxisValueFormatter() { @Override public String getFormattedValue(float value, AxisBase axis) { return (int) value + "号"; } }); //两组数据 BarDataSet set1 = new BarDataSet(entriesGroup1, "支付宝交易"); BarDataSet set2 = new BarDataSet(entriesGroup2, "微信交易"); BarDataSet set3 = new BarDataSet(entriesGroup3, "POS交易"); set1.setColor(GradientDrawable.LINEAR_GRADIENT); set1.setColor(Color.parseColor("#039feb")); set1.setValueTextColor(Color.parseColor("#ffffff")); set2.setColor(Color.parseColor("#19d100")); set2.setValueTextColor(Color.parseColor("#ffffff")); set3.setColor(Color.parseColor("#f7b43b")); set3.setValueTextColor(Color.parseColor("#ffffff")); //描述文字的颜色 Legend mLegend = barChart.getLegend(); // 设置坐标线描述?? 的样式 mLegend.setEnabled(false);//坐标线开关是否显示 mLegend.setTextColor(Color.parseColor("#ffffff"));// 坐标线描述文字的颜色 mLegend.setTextSize(8);// 坐标线描述文字的大小,单位dp int amount = 3;//条形图的组数三组 float groupSpace = 0.12f; //柱状图组之间的间距 float barSpace = (float) ((1 - 0.12) / amount / 10); // x4 DataSet float barWidth = (float) ((1 - 0.12) / amount / 10 * 9); // x4 DataSet // xAxis.setLabelCount(getDayOfMonth() , false); BarData data = new BarData(set1, set2, set3); //设置组数据 data.setBarWidth(barWidth); // 设置柱状条宽度 barChart.setData(data); barChart.groupBars(1f, groupSpace, barSpace); // 设置组样式宽度等 barChart.invalidate(); // 刷新 } private void chartdata(String am_number, String month) { Api.gethttpService().getReportData(am_number, month).enqueue(new Callback<ChartBean>() { @Override public void onResponse(Call<ChartBean> call, Response<ChartBean> response) { chartBean = response.body(); zfb(); } @Override public void onFailure(Call<ChartBean> call, Throwable t) { } }); } //java获取当前月的天数 public int getDayOfMonth() { Calendar aCalendar = Calendar.getInstance(Locale.CHINA); int day = aCalendar.getActualMaximum(Calendar.DATE); return day; } private void initListPopupIfNeed() { if (mListPopup == null) { List<Integer> mlist = new ArrayList<Integer>(); for (int i = 1; i <= 12; i++) { mlist.add(i); } ArrayAdapter adapter = new ArrayAdapter<>(ChartTwoActivity.this, R.layout.simple_list_item, mlist); mListPopup = new QMUIListPopup(ChartTwoActivity.this, QMUIPopup.DIRECTION_NONE, adapter);//必须使用本类类名不能getcontext mListPopup.create(QMUIDisplayHelper.dp2px(getContext(), 50), QMUIDisplayHelper.dp2px(getContext(), 200), new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { int a=i+1; String b=a < 10 ? "0" + a : a+""; chartMonthTv.setText(i+1+""); chartdata("883000000000105", "2017-"+b); mListPopup.dismiss(); } }); mListPopup.setOnDismissListener(new PopupWindow.OnDismissListener() { @Override public void onDismiss() { } }); } } @OnClick({R.id.chart_month_tv, R.id.charttwo_ll}) public void onViewClicked(View view) { switch (view.getId()) { case R.id.chart_month_tv: break; case R.id.charttwo_ll: initListPopupIfNeed(); mListPopup.setAnimStyle(QMUIPopup.ANIM_GROW_FROM_CENTER); mListPopup.setPreferredDirection(QMUIPopup.DIRECTION_BOTTOM); mListPopup.show(view); break; } } }
10,460
0.600318
0.586385
274
34.671532
26.823322
156
false
false
0
0
0
0
0
0
0.689781
false
false
3
1108fbe530afcf28a8c3ba72bbc5ac8567c24a4c
30,932,354,480,249
059a855e25e34df806c97b26f1204ed479e6fa2a
/app/src/main/java/com/apps/konhel/jewishbutton/MainActivity.java
e9fe52edf7273cb731fe5f5b4d6d632122057e1b
[]
no_license
Helliox/JewishButton
https://github.com/Helliox/JewishButton
59a5a6ed1354eff344cccbae729eee91d44fc1bc
f58c013ddaccc34a982c861752d6711d2e9cc708
refs/heads/master
2020-03-30T01:59:39.428000
2018-09-28T15:47:46
2018-09-28T15:47:46
150,606,526
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.apps.konhel.jewishbutton; import android.content.Context; import android.content.DialogInterface; import android.content.pm.ActivityInfo; import android.graphics.Point; import android.media.MediaPlayer; import android.os.Handler; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.Display; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ImageView; import com.google.android.gms.ads.AdRequest; import com.google.android.gms.ads.AdView; import com.google.android.gms.ads.InterstitialAd; import com.google.android.gms.ads.MobileAds; import java.util.Timer; import java.util.TimerTask; public class MainActivity extends AppCompatActivity { private AdView mAdview; private InterstitialAd mInterstitialAd; private ImageView jew; private ImageView songList; private float jewY; private Timer timer = new Timer(); private Handler handler = new Handler(); private int timePassed=0; private int biggerJump=0; MediaPlayer playMusic; private int duration; private Runnable TEST = new Runnable() { @Override public void run() { timer.cancel(); timer.purge(); timer=new Timer(); biggerJump=0; jew.setY(0); jewY=0; } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); setContentView(R.layout.activity_main); playMusic = MediaPlayer.create(this, R.raw.judaism_intensifies); jew = (ImageView) findViewById(R.id.jew); MobileAds.initialize(this,"ca-app-pub-3940256099942544~3347511713"); mInterstitialAd = new InterstitialAd(this); mInterstitialAd.setAdUnitId("ca-app-pub-3940256099942544/1033173712"); mAdview = (AdView)findViewById(R.id.adView); AdRequest adRequest = new AdRequest.Builder().addTestDevice(AdRequest.DEVICE_ID_EMULATOR).build(); mInterstitialAd.loadAd(new AdRequest.Builder().build()); final String[] songs = {"Judaism intensifies","Goy dropped a shekel"}; ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.select_dialog_item,songs); AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("Choose a song..."); builder.setAdapter(adapter, new DialogInterface.OnClickListener(){ @Override public void onClick(DialogInterface dialogInterface, int arg){ switch(arg) { case 0: if(playMusic.isPlaying()==true){ playMusic.stop(); } timer.cancel(); timer.purge(); timer=new Timer(); handler.removeCallbacks(TEST); jew.setY(0); jewY=0; playMusic = MediaPlayer.create(getAppContext(), R.raw.judaism_intensifies); duration = playMusic.getDuration(); break; case 1: if(playMusic.isPlaying()==true){ playMusic.stop(); } timer.cancel(); timer.purge(); timer=new Timer(); handler.removeCallbacks(TEST); jew.setY(0); jewY=0; playMusic = MediaPlayer.create(getAppContext(), R.raw.goy); duration = playMusic.getDuration(); break; } } }); final AlertDialog a = builder.create(); songList = (ImageView) findViewById(R.id.songMenu); songList.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { a.show(); } }); mAdview.loadAd(adRequest); final Handler handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { mInterstitialAd.show(); } },3200); duration = playMusic.getDuration(); Button jewishButton = findViewById(R.id.jewishButton); jewishButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { playMusic.start(); ButtonPressed(duration); } }); } @Override public void onDestroy() { playMusic.stop(); playMusic.release(); super.onDestroy(); } public Context getAppContext() { return super.getApplicationContext(); } public void ButtonPressed(int dur) { WindowManager wm = getWindowManager(); Display disp = wm.getDefaultDisplay(); Point size = new Point(); disp.getSize(size); handler.postDelayed(TEST, dur); timer.schedule(new TimerTask() { @Override public void run() { handler.post(new Runnable() { @Override public void run() { changePos1(); timePassed++; } }); } }, 20, 120); timer.schedule(new TimerTask() { @Override public void run() { handler.post(new Runnable() { @Override public void run() { changePos2(); } }); } }, 20, 120); timer.schedule(new TimerTask() { @Override public void run() { handler.post(new Runnable() { @Override public void run() { changePos3(); } }); } }, 20, 120); timer.schedule(new TimerTask() { @Override public void run() { handler.post(new Runnable() { @Override public void run() { changePos4(); } }); } }, 20, 120); timer.schedule(new TimerTask() { @Override public void run() { handler.post(new Runnable() { @Override public void run() { changePos5(); } }); } }, 20, 120); timer.schedule(new TimerTask() { @Override public void run() { handler.post(new Runnable() { @Override public void run() { changePos6(); } }); } }, 20, 120); } public void changePos1() { if(timePassed>20) { biggerJump+=3; timePassed=0; } jewY -=10+biggerJump; jew.setY(jewY); } public void changePos2() { jewY -=30+biggerJump; jew.setY(jewY); } public void changePos3() { jewY -=60+biggerJump; jew.setY(jewY); } public void changePos4(){ jewY +=10+biggerJump; jew.setY(jewY); } public void changePos5() { jewY +=30+biggerJump; jew.setY(jewY); } public void changePos6() { jewY +=60+biggerJump; jew.setY(jewY); } }
UTF-8
Java
8,215
java
MainActivity.java
Java
[]
null
[]
package com.apps.konhel.jewishbutton; import android.content.Context; import android.content.DialogInterface; import android.content.pm.ActivityInfo; import android.graphics.Point; import android.media.MediaPlayer; import android.os.Handler; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.Display; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ImageView; import com.google.android.gms.ads.AdRequest; import com.google.android.gms.ads.AdView; import com.google.android.gms.ads.InterstitialAd; import com.google.android.gms.ads.MobileAds; import java.util.Timer; import java.util.TimerTask; public class MainActivity extends AppCompatActivity { private AdView mAdview; private InterstitialAd mInterstitialAd; private ImageView jew; private ImageView songList; private float jewY; private Timer timer = new Timer(); private Handler handler = new Handler(); private int timePassed=0; private int biggerJump=0; MediaPlayer playMusic; private int duration; private Runnable TEST = new Runnable() { @Override public void run() { timer.cancel(); timer.purge(); timer=new Timer(); biggerJump=0; jew.setY(0); jewY=0; } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); setContentView(R.layout.activity_main); playMusic = MediaPlayer.create(this, R.raw.judaism_intensifies); jew = (ImageView) findViewById(R.id.jew); MobileAds.initialize(this,"ca-app-pub-3940256099942544~3347511713"); mInterstitialAd = new InterstitialAd(this); mInterstitialAd.setAdUnitId("ca-app-pub-3940256099942544/1033173712"); mAdview = (AdView)findViewById(R.id.adView); AdRequest adRequest = new AdRequest.Builder().addTestDevice(AdRequest.DEVICE_ID_EMULATOR).build(); mInterstitialAd.loadAd(new AdRequest.Builder().build()); final String[] songs = {"Judaism intensifies","Goy dropped a shekel"}; ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.select_dialog_item,songs); AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("Choose a song..."); builder.setAdapter(adapter, new DialogInterface.OnClickListener(){ @Override public void onClick(DialogInterface dialogInterface, int arg){ switch(arg) { case 0: if(playMusic.isPlaying()==true){ playMusic.stop(); } timer.cancel(); timer.purge(); timer=new Timer(); handler.removeCallbacks(TEST); jew.setY(0); jewY=0; playMusic = MediaPlayer.create(getAppContext(), R.raw.judaism_intensifies); duration = playMusic.getDuration(); break; case 1: if(playMusic.isPlaying()==true){ playMusic.stop(); } timer.cancel(); timer.purge(); timer=new Timer(); handler.removeCallbacks(TEST); jew.setY(0); jewY=0; playMusic = MediaPlayer.create(getAppContext(), R.raw.goy); duration = playMusic.getDuration(); break; } } }); final AlertDialog a = builder.create(); songList = (ImageView) findViewById(R.id.songMenu); songList.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { a.show(); } }); mAdview.loadAd(adRequest); final Handler handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { mInterstitialAd.show(); } },3200); duration = playMusic.getDuration(); Button jewishButton = findViewById(R.id.jewishButton); jewishButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { playMusic.start(); ButtonPressed(duration); } }); } @Override public void onDestroy() { playMusic.stop(); playMusic.release(); super.onDestroy(); } public Context getAppContext() { return super.getApplicationContext(); } public void ButtonPressed(int dur) { WindowManager wm = getWindowManager(); Display disp = wm.getDefaultDisplay(); Point size = new Point(); disp.getSize(size); handler.postDelayed(TEST, dur); timer.schedule(new TimerTask() { @Override public void run() { handler.post(new Runnable() { @Override public void run() { changePos1(); timePassed++; } }); } }, 20, 120); timer.schedule(new TimerTask() { @Override public void run() { handler.post(new Runnable() { @Override public void run() { changePos2(); } }); } }, 20, 120); timer.schedule(new TimerTask() { @Override public void run() { handler.post(new Runnable() { @Override public void run() { changePos3(); } }); } }, 20, 120); timer.schedule(new TimerTask() { @Override public void run() { handler.post(new Runnable() { @Override public void run() { changePos4(); } }); } }, 20, 120); timer.schedule(new TimerTask() { @Override public void run() { handler.post(new Runnable() { @Override public void run() { changePos5(); } }); } }, 20, 120); timer.schedule(new TimerTask() { @Override public void run() { handler.post(new Runnable() { @Override public void run() { changePos6(); } }); } }, 20, 120); } public void changePos1() { if(timePassed>20) { biggerJump+=3; timePassed=0; } jewY -=10+biggerJump; jew.setY(jewY); } public void changePos2() { jewY -=30+biggerJump; jew.setY(jewY); } public void changePos3() { jewY -=60+biggerJump; jew.setY(jewY); } public void changePos4(){ jewY +=10+biggerJump; jew.setY(jewY); } public void changePos5() { jewY +=30+biggerJump; jew.setY(jewY); } public void changePos6() { jewY +=60+biggerJump; jew.setY(jewY); } }
8,215
0.515277
0.499817
272
29.202206
20.485817
117
false
false
0
0
0
0
0
0
0.580882
false
false
3
f7fdb49edf55ed6c36500e1db86760fa7c90c9c3
9,294,309,247,282
62ad82a870730de70687c483ec9929e9c4902d4f
/springcloud-service-provider/src/main/java/com/lanou/provider/service/CalcServiceImpl.java
244aa5d79bec5131f775a53fcf908478aaa44542
[]
no_license
zjt-zjt/springcloud
https://github.com/zjt-zjt/springcloud
eeacb49b228a42c1d3d684020634ce22922fc96e
3ab6b6c053d77e96038b61ef93413923b8fc0356
refs/heads/master
2020-12-05T12:02:51.139000
2020-01-06T13:07:17
2020-01-06T13:07:17
232,102,697
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.lanou.provider.service; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cloud.client.serviceregistry.Registration; import org.springframework.stereotype.Service; import java.util.Random; @Slf4j @Service public class CalcServiceImpl { @Autowired private Registration registration; public int add(int num1,int num2){ String serviceInfo = registration.getHost()+"-"+registration.getInstanceId(); log.info(serviceInfo+"->" + num1 + "+" + num2 + "=" + (num1 + num2)); // 模拟处理时间长的服务调用 Random random = new Random(); int sleepTime = random.nextInt(3000); log.info("休眠时间:" + sleepTime+"ms."); try { Thread.sleep(sleepTime); } catch (InterruptedException e) { e.printStackTrace(); } return num1+num2; } }
UTF-8
Java
945
java
CalcServiceImpl.java
Java
[]
null
[]
package com.lanou.provider.service; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cloud.client.serviceregistry.Registration; import org.springframework.stereotype.Service; import java.util.Random; @Slf4j @Service public class CalcServiceImpl { @Autowired private Registration registration; public int add(int num1,int num2){ String serviceInfo = registration.getHost()+"-"+registration.getInstanceId(); log.info(serviceInfo+"->" + num1 + "+" + num2 + "=" + (num1 + num2)); // 模拟处理时间长的服务调用 Random random = new Random(); int sleepTime = random.nextInt(3000); log.info("休眠时间:" + sleepTime+"ms."); try { Thread.sleep(sleepTime); } catch (InterruptedException e) { e.printStackTrace(); } return num1+num2; } }
945
0.656422
0.639956
37
23.621622
23.662436
86
false
false
0
0
0
0
0
0
0.432432
false
false
3
1363ea598810120122a3a13476745a8ea8e00e39
6,262,062,336,794
71d908b862312165c58bf5b1322a82db99747b08
/app/src/main/java/com/jpdas/orgodev/UtilsCustomizationUI/HideAndSeekPassword.java
bd8351f1a4107de908f1202355f43a3013922d17
[]
no_license
dasjp7/OrgoDev
https://github.com/dasjp7/OrgoDev
9cff172702e9be2dad52f995fa894da426c69b1e
b93689fa53ba0e9c0838dbe54521f4f8eb1d588a
refs/heads/master
2020-09-02T10:54:31.914000
2019-11-02T19:53:57
2019-11-02T19:53:57
219,206,004
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.jpdas.orgodev.UtilsCustomizationUI; import android.content.Context; import android.content.res.Configuration; import android.content.res.TypedArray; import android.graphics.Rect; import android.graphics.Typeface; import android.graphics.drawable.Drawable; import android.os.Build; import android.os.Bundle; import android.os.Parcelable; import android.support.annotation.ColorInt; import android.support.annotation.DrawableRes; import android.support.v4.content.ContextCompat; import android.support.v4.graphics.drawable.DrawableCompat; import android.text.Editable; import android.text.TextUtils; import android.text.TextWatcher; import android.text.method.PasswordTransformationMethod; import android.text.method.TransformationMethod; import android.util.AttributeSet; import android.view.MotionEvent; import com.jpdas.orgodev.R; import com.scottyab.showhidepasswordedittext.ShowHidePasswordEditText; public class HideAndSeekPassword extends ShowHidePasswordEditText { private static final String TAG = ShowHidePasswordEditText.class.getSimpleName(); private boolean isShowingPassword = false; private Drawable drawableEnd; private boolean leftToRight = true; private int tintColor = 0; private final int DEFAULT_ADDITIONAL_TOUCH_TARGET_SIZE = 40; @DrawableRes private int visibilityIndicatorShow; @DrawableRes private int visibilityIndicatorHide; private int additionalTouchTargetSize = 40; private static final String IS_SHOWING_PASSWORD_STATE_KEY = "IS_SHOWING_PASSWORD_STATE_KEY"; private static final String SUPER_STATE_KEY = "SUPER_STATE_KEY"; public HideAndSeekPassword(Context context) { super(context); init(null); } public HideAndSeekPassword(Context context, AttributeSet attrs) { super(context, attrs); init(attrs); } public HideAndSeekPassword(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); init(attrs); } private void init(AttributeSet attrs) { if (attrs != null || !isInEditMode()) { Typeface tf = Typeface.createFromAsset(getContext().getAssets(), "fonts/WorkSans-Bold.ttf"); setTypeface(tf); TypedArray attrsArray = this.getContext().obtainStyledAttributes(attrs, R.styleable.ShowHidePasswordEditText); this.visibilityIndicatorShow = attrsArray.getResourceId(R.styleable.ShowHidePasswordEditText_drawable_show, R.drawable.show); this.visibilityIndicatorHide = attrsArray.getResourceId(R.styleable.ShowHidePasswordEditText_drawable_hide, R.drawable.hide1); this.tintColor = attrsArray.getColor(R.styleable.ShowHidePasswordEditText_tint_color, 0); this.additionalTouchTargetSize = attrsArray.getDimensionPixelSize(R.styleable.ShowHidePasswordEditText_additionalTouchTargetSize, 40); attrsArray.recycle(); } else { this.visibilityIndicatorShow = R.drawable.ic_visibility_grey_900_24dp; this.visibilityIndicatorHide = R.drawable.ic_visibility_off_grey_900_24dp; } this.leftToRight = this.isLeftToRight(); this.setMaxLines(1); this.setSingleLine(true); this.isShowingPassword = false; this.maskPassword(); this.setSaveEnabled(true); if (!TextUtils.isEmpty(this.getText())) { this.showPasswordVisibilityIndicator(true); } this.addTextChangedListener(new TextWatcher() { public void beforeTextChanged(CharSequence s, int start, int count, int after) { } public void onTextChanged(CharSequence s, int start, int before, int count) { if (s.length() > 0) { HideAndSeekPassword.this.showPasswordVisibilityIndicator(true); } else { HideAndSeekPassword.this.showPasswordVisibilityIndicator(false); } } public void afterTextChanged(Editable s) { } }); } private boolean isLeftToRight() { if (Build.VERSION.SDK_INT < 17) { return true; } else { Configuration config = this.getResources().getConfiguration(); return config.getLayoutDirection() != 1; } } public void setCompoundDrawables(Drawable left, Drawable top, Drawable right, Drawable bottom) { if (this.leftToRight && right != null) { this.drawableEnd = right; } else if (!this.leftToRight && left != null) { this.drawableEnd = left; } super.setCompoundDrawables(left, top, right, bottom); } public void setTintColor(@ColorInt int tintColor) { this.tintColor = tintColor; } public boolean onTouchEvent(MotionEvent event) { if (event.getAction() == 1 && this.drawableEnd != null) { Rect bounds = this.drawableEnd.getBounds(); int x = (int)event.getX(); int drawableWidthWithPadding = bounds.width() + (this.leftToRight ? this.getPaddingRight() : this.getPaddingLeft()) + this.additionalTouchTargetSize; if (this.leftToRight && x >= this.getRight() - drawableWidthWithPadding || !this.leftToRight && x <= this.getLeft() + drawableWidthWithPadding) { this.togglePasswordVisibility(); event.setAction(3); } } return super.onTouchEvent(event); } private void showPasswordVisibilityIndicator(boolean show) { Drawable[] existingDrawables = this.getCompoundDrawables(); Drawable left = existingDrawables[0]; Drawable top = existingDrawables[1]; Drawable right = existingDrawables[2]; Drawable bottom = existingDrawables[3]; if (show) { Drawable original = this.isShowingPassword ? ContextCompat.getDrawable(this.getContext(), this.visibilityIndicatorHide) : ContextCompat.getDrawable(this.getContext(), this.visibilityIndicatorShow); original.mutate(); if (this.tintColor == 0) { this.setCompoundDrawablesWithIntrinsicBounds(this.leftToRight ? left : original, top, this.leftToRight ? original : right, bottom); } else { Drawable wrapper = DrawableCompat.wrap(original); DrawableCompat.setTint(wrapper, this.tintColor); this.setCompoundDrawablesWithIntrinsicBounds(this.leftToRight ? left : wrapper, top, this.leftToRight ? wrapper : right, bottom); } } else { this.setCompoundDrawablesWithIntrinsicBounds(this.leftToRight ? left : null, top, this.leftToRight ? null : right, bottom); } } private void unmaskPassword() { this.setTransformationMethod((TransformationMethod)null); } private void maskPassword() { this.setTransformationMethod(PasswordTransformationMethod.getInstance()); } public void togglePasswordVisibility() { int selectionStart = this.getSelectionStart(); int selectionEnd = this.getSelectionEnd(); if (this.isShowingPassword) { this.maskPassword(); } else { this.unmaskPassword(); } this.setSelection(selectionStart, selectionEnd); this.isShowingPassword = !this.isShowingPassword; this.showPasswordVisibilityIndicator(true); } protected void finalize() throws Throwable { this.drawableEnd = null; super.finalize(); } @DrawableRes public int getVisibilityIndicatorShow() { return this.visibilityIndicatorShow; } public void setVisibilityIndicatorShow(@DrawableRes int visibilityIndicatorShow) { this.visibilityIndicatorShow = visibilityIndicatorShow; } @DrawableRes public int getVisibilityIndicatorHide() { return this.visibilityIndicatorHide; } public void setVisibilityIndicatorHide(@DrawableRes int visibilityIndicatorHide) { this.visibilityIndicatorHide = visibilityIndicatorHide; } public boolean isShowingPassword() { return this.isShowingPassword; } public int getAdditionalTouchTargetSizePixels() { return this.additionalTouchTargetSize; } public void setAdditionalTouchTargetSizePixels(int additionalTouchTargetSize) { this.additionalTouchTargetSize = additionalTouchTargetSize; } public Parcelable onSaveInstanceState() { Bundle bundle = new Bundle(); bundle.putParcelable("SUPER_STATE_KEY", super.onSaveInstanceState()); bundle.putBoolean("IS_SHOWING_PASSWORD_STATE_KEY", this.isShowingPassword); return bundle; } public void onRestoreInstanceState(Parcelable state) { if (state instanceof Bundle) { Bundle bundle = (Bundle)state; this.isShowingPassword = bundle.getBoolean("IS_SHOWING_PASSWORD_STATE_KEY", false); if (this.isShowingPassword) { this.unmaskPassword(); } state = bundle.getParcelable("SUPER_STATE_KEY"); } super.onRestoreInstanceState(state); } }
UTF-8
Java
9,159
java
HideAndSeekPassword.java
Java
[]
null
[]
package com.jpdas.orgodev.UtilsCustomizationUI; import android.content.Context; import android.content.res.Configuration; import android.content.res.TypedArray; import android.graphics.Rect; import android.graphics.Typeface; import android.graphics.drawable.Drawable; import android.os.Build; import android.os.Bundle; import android.os.Parcelable; import android.support.annotation.ColorInt; import android.support.annotation.DrawableRes; import android.support.v4.content.ContextCompat; import android.support.v4.graphics.drawable.DrawableCompat; import android.text.Editable; import android.text.TextUtils; import android.text.TextWatcher; import android.text.method.PasswordTransformationMethod; import android.text.method.TransformationMethod; import android.util.AttributeSet; import android.view.MotionEvent; import com.jpdas.orgodev.R; import com.scottyab.showhidepasswordedittext.ShowHidePasswordEditText; public class HideAndSeekPassword extends ShowHidePasswordEditText { private static final String TAG = ShowHidePasswordEditText.class.getSimpleName(); private boolean isShowingPassword = false; private Drawable drawableEnd; private boolean leftToRight = true; private int tintColor = 0; private final int DEFAULT_ADDITIONAL_TOUCH_TARGET_SIZE = 40; @DrawableRes private int visibilityIndicatorShow; @DrawableRes private int visibilityIndicatorHide; private int additionalTouchTargetSize = 40; private static final String IS_SHOWING_PASSWORD_STATE_KEY = "IS_SHOWING_PASSWORD_STATE_KEY"; private static final String SUPER_STATE_KEY = "SUPER_STATE_KEY"; public HideAndSeekPassword(Context context) { super(context); init(null); } public HideAndSeekPassword(Context context, AttributeSet attrs) { super(context, attrs); init(attrs); } public HideAndSeekPassword(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); init(attrs); } private void init(AttributeSet attrs) { if (attrs != null || !isInEditMode()) { Typeface tf = Typeface.createFromAsset(getContext().getAssets(), "fonts/WorkSans-Bold.ttf"); setTypeface(tf); TypedArray attrsArray = this.getContext().obtainStyledAttributes(attrs, R.styleable.ShowHidePasswordEditText); this.visibilityIndicatorShow = attrsArray.getResourceId(R.styleable.ShowHidePasswordEditText_drawable_show, R.drawable.show); this.visibilityIndicatorHide = attrsArray.getResourceId(R.styleable.ShowHidePasswordEditText_drawable_hide, R.drawable.hide1); this.tintColor = attrsArray.getColor(R.styleable.ShowHidePasswordEditText_tint_color, 0); this.additionalTouchTargetSize = attrsArray.getDimensionPixelSize(R.styleable.ShowHidePasswordEditText_additionalTouchTargetSize, 40); attrsArray.recycle(); } else { this.visibilityIndicatorShow = R.drawable.ic_visibility_grey_900_24dp; this.visibilityIndicatorHide = R.drawable.ic_visibility_off_grey_900_24dp; } this.leftToRight = this.isLeftToRight(); this.setMaxLines(1); this.setSingleLine(true); this.isShowingPassword = false; this.maskPassword(); this.setSaveEnabled(true); if (!TextUtils.isEmpty(this.getText())) { this.showPasswordVisibilityIndicator(true); } this.addTextChangedListener(new TextWatcher() { public void beforeTextChanged(CharSequence s, int start, int count, int after) { } public void onTextChanged(CharSequence s, int start, int before, int count) { if (s.length() > 0) { HideAndSeekPassword.this.showPasswordVisibilityIndicator(true); } else { HideAndSeekPassword.this.showPasswordVisibilityIndicator(false); } } public void afterTextChanged(Editable s) { } }); } private boolean isLeftToRight() { if (Build.VERSION.SDK_INT < 17) { return true; } else { Configuration config = this.getResources().getConfiguration(); return config.getLayoutDirection() != 1; } } public void setCompoundDrawables(Drawable left, Drawable top, Drawable right, Drawable bottom) { if (this.leftToRight && right != null) { this.drawableEnd = right; } else if (!this.leftToRight && left != null) { this.drawableEnd = left; } super.setCompoundDrawables(left, top, right, bottom); } public void setTintColor(@ColorInt int tintColor) { this.tintColor = tintColor; } public boolean onTouchEvent(MotionEvent event) { if (event.getAction() == 1 && this.drawableEnd != null) { Rect bounds = this.drawableEnd.getBounds(); int x = (int)event.getX(); int drawableWidthWithPadding = bounds.width() + (this.leftToRight ? this.getPaddingRight() : this.getPaddingLeft()) + this.additionalTouchTargetSize; if (this.leftToRight && x >= this.getRight() - drawableWidthWithPadding || !this.leftToRight && x <= this.getLeft() + drawableWidthWithPadding) { this.togglePasswordVisibility(); event.setAction(3); } } return super.onTouchEvent(event); } private void showPasswordVisibilityIndicator(boolean show) { Drawable[] existingDrawables = this.getCompoundDrawables(); Drawable left = existingDrawables[0]; Drawable top = existingDrawables[1]; Drawable right = existingDrawables[2]; Drawable bottom = existingDrawables[3]; if (show) { Drawable original = this.isShowingPassword ? ContextCompat.getDrawable(this.getContext(), this.visibilityIndicatorHide) : ContextCompat.getDrawable(this.getContext(), this.visibilityIndicatorShow); original.mutate(); if (this.tintColor == 0) { this.setCompoundDrawablesWithIntrinsicBounds(this.leftToRight ? left : original, top, this.leftToRight ? original : right, bottom); } else { Drawable wrapper = DrawableCompat.wrap(original); DrawableCompat.setTint(wrapper, this.tintColor); this.setCompoundDrawablesWithIntrinsicBounds(this.leftToRight ? left : wrapper, top, this.leftToRight ? wrapper : right, bottom); } } else { this.setCompoundDrawablesWithIntrinsicBounds(this.leftToRight ? left : null, top, this.leftToRight ? null : right, bottom); } } private void unmaskPassword() { this.setTransformationMethod((TransformationMethod)null); } private void maskPassword() { this.setTransformationMethod(PasswordTransformationMethod.getInstance()); } public void togglePasswordVisibility() { int selectionStart = this.getSelectionStart(); int selectionEnd = this.getSelectionEnd(); if (this.isShowingPassword) { this.maskPassword(); } else { this.unmaskPassword(); } this.setSelection(selectionStart, selectionEnd); this.isShowingPassword = !this.isShowingPassword; this.showPasswordVisibilityIndicator(true); } protected void finalize() throws Throwable { this.drawableEnd = null; super.finalize(); } @DrawableRes public int getVisibilityIndicatorShow() { return this.visibilityIndicatorShow; } public void setVisibilityIndicatorShow(@DrawableRes int visibilityIndicatorShow) { this.visibilityIndicatorShow = visibilityIndicatorShow; } @DrawableRes public int getVisibilityIndicatorHide() { return this.visibilityIndicatorHide; } public void setVisibilityIndicatorHide(@DrawableRes int visibilityIndicatorHide) { this.visibilityIndicatorHide = visibilityIndicatorHide; } public boolean isShowingPassword() { return this.isShowingPassword; } public int getAdditionalTouchTargetSizePixels() { return this.additionalTouchTargetSize; } public void setAdditionalTouchTargetSizePixels(int additionalTouchTargetSize) { this.additionalTouchTargetSize = additionalTouchTargetSize; } public Parcelable onSaveInstanceState() { Bundle bundle = new Bundle(); bundle.putParcelable("SUPER_STATE_KEY", super.onSaveInstanceState()); bundle.putBoolean("IS_SHOWING_PASSWORD_STATE_KEY", this.isShowingPassword); return bundle; } public void onRestoreInstanceState(Parcelable state) { if (state instanceof Bundle) { Bundle bundle = (Bundle)state; this.isShowingPassword = bundle.getBoolean("IS_SHOWING_PASSWORD_STATE_KEY", false); if (this.isShowingPassword) { this.unmaskPassword(); } state = bundle.getParcelable("SUPER_STATE_KEY"); } super.onRestoreInstanceState(state); } }
9,159
0.678022
0.674419
234
38.141026
35.382908
209
false
false
0
0
0
0
0
0
0.666667
false
false
3
c61aaa1ec6f9d323d314d87adea8d186b585a4b6
4,148,938,411,590
668739af099edfec9a6605a574ccb383ce431651
/src/ui/FindPassWdFrame.java
64e7b1956c81920f6d4c7cf3002bb37a68bd105a
[]
no_license
Playstudy47/MJU-1st-semester-final
https://github.com/Playstudy47/MJU-1st-semester-final
5b2fc57ef1cce74c94fe6211fc25bd4425e4a151
1e58dd3a4eb215cac38e24e986418bfd25eda265
refs/heads/master
2020-07-11T20:12:27.410000
2019-08-27T06:40:37
2019-08-27T06:40:37
204,635,227
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ui; import java.awt.Color; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.FileNotFoundException; import java.util.Vector; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.UIManager; import controller.CRegister; import entity.ERegister; public class FindPassWdFrame extends JFrame { private static final long serialVersionUID = 1L; private JButton m_confirmButton; private JLabel m_idLabel, m_nameLabel; private JTextField m_idField, m_nameField; private JPanel m_idPanel, m_namePanel, m_confirmPanel; private CRegister m_cRegister; private Vector<ERegister> m_eRegisters; private NoticeFrame m_noticeFrame; public FindPassWdFrame() { this.m_noticeFrame = new NoticeFrame(); this.m_eRegisters = new Vector<ERegister>(); this.m_cRegister = new CRegister(); this.m_idPanel = new JPanel(); this.m_namePanel = new JPanel(); this.m_confirmPanel = new JPanel(); this.m_confirmButton = new JButton("확인"); this.m_idLabel = new JLabel("아이디"); this.m_nameLabel = new JLabel("이름"); this.m_idField = new JTextField(10); this.m_nameField = new JTextField(10); this.m_idPanel.add(this.m_idLabel); this.m_idPanel.add(this.m_idField); this.m_namePanel.add(this.m_nameLabel); this.m_namePanel.add(this.m_nameField); this.m_confirmPanel.add(this.m_confirmButton); this.m_confirmButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { boolean flag = false; String passWd = null; String userName = null; try { m_eRegisters = m_cRegister.getItems("../LMS/data/login"); } catch (FileNotFoundException e) { e.printStackTrace(); } for (ERegister eRegister : m_eRegisters) { if(m_idField.getText().equals(eRegister.getId()) && m_nameField.getText().equals(eRegister.getName())) { flag = true; passWd = eRegister.getPasswd(); userName = eRegister.getName(); } } if(flag) { m_noticeFrame.findPassWdSuccessed(userName, passWd); } else { m_noticeFrame.findPassWdFailed(); } } }); this.m_confirmButton.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseEntered(java.awt.event.MouseEvent evt) { m_confirmButton.setBackground(Color.WHITE); } public void mouseExited(java.awt.event.MouseEvent evt) { m_confirmButton.setBackground(UIManager.getColor("control")); } }); this.add(this.m_idPanel); this.add(this.m_namePanel); this.add(this.m_confirmPanel); this.setResizable(false); this.setLayout(new GridLayout(3,1)); this.setTitle("비밀번호 찾기"); this.setLocation(500, 300); this.setSize(250, 300); this.setVisible(true); } }
UHC
Java
2,929
java
FindPassWdFrame.java
Java
[ { "context": "tName()))\n\t\t\t\t\t{\n\t\t\t\t\t\tflag = true;\n\t\t\t\t\t\tpassWd = eRegister.getPasswd();\n\t\t\t\t\t\tuserName = eRegister.g", "end": 2054, "score": 0.8404209613800049, "start": 2053, "tag": "PASSWORD", "value": "e" } ]
null
[]
package ui; import java.awt.Color; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.FileNotFoundException; import java.util.Vector; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.UIManager; import controller.CRegister; import entity.ERegister; public class FindPassWdFrame extends JFrame { private static final long serialVersionUID = 1L; private JButton m_confirmButton; private JLabel m_idLabel, m_nameLabel; private JTextField m_idField, m_nameField; private JPanel m_idPanel, m_namePanel, m_confirmPanel; private CRegister m_cRegister; private Vector<ERegister> m_eRegisters; private NoticeFrame m_noticeFrame; public FindPassWdFrame() { this.m_noticeFrame = new NoticeFrame(); this.m_eRegisters = new Vector<ERegister>(); this.m_cRegister = new CRegister(); this.m_idPanel = new JPanel(); this.m_namePanel = new JPanel(); this.m_confirmPanel = new JPanel(); this.m_confirmButton = new JButton("확인"); this.m_idLabel = new JLabel("아이디"); this.m_nameLabel = new JLabel("이름"); this.m_idField = new JTextField(10); this.m_nameField = new JTextField(10); this.m_idPanel.add(this.m_idLabel); this.m_idPanel.add(this.m_idField); this.m_namePanel.add(this.m_nameLabel); this.m_namePanel.add(this.m_nameField); this.m_confirmPanel.add(this.m_confirmButton); this.m_confirmButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { boolean flag = false; String passWd = null; String userName = null; try { m_eRegisters = m_cRegister.getItems("../LMS/data/login"); } catch (FileNotFoundException e) { e.printStackTrace(); } for (ERegister eRegister : m_eRegisters) { if(m_idField.getText().equals(eRegister.getId()) && m_nameField.getText().equals(eRegister.getName())) { flag = true; passWd = eRegister.getPasswd(); userName = eRegister.getName(); } } if(flag) { m_noticeFrame.findPassWdSuccessed(userName, passWd); } else { m_noticeFrame.findPassWdFailed(); } } }); this.m_confirmButton.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseEntered(java.awt.event.MouseEvent evt) { m_confirmButton.setBackground(Color.WHITE); } public void mouseExited(java.awt.event.MouseEvent evt) { m_confirmButton.setBackground(UIManager.getColor("control")); } }); this.add(this.m_idPanel); this.add(this.m_namePanel); this.add(this.m_confirmPanel); this.setResizable(false); this.setLayout(new GridLayout(3,1)); this.setTitle("비밀번호 찾기"); this.setLocation(500, 300); this.setSize(250, 300); this.setVisible(true); } }
2,929
0.699621
0.693076
106
26.386793
19.810694
107
false
false
0
0
0
0
0
0
2.924528
false
false
3
0d14b7ea8a67900c5cadee3f21981c827abcf2de
29,712,583,772,762
ad283d1028f7c7f6b655ce9f182681b12b554c9f
/core/src/com/rtype/game/MainCharacter.java
aae3fcfe667fa0ce895c46c7c9fcb91a0128579c
[]
no_license
Edu-gamo/RType
https://github.com/Edu-gamo/RType
6b02da83e9088b8d5d4952f6156646efca1ccff9
4dee4270e2e2ebf814aa7a8d08d796a2ea38a2b4
refs/heads/master
2021-05-06T04:15:32.972000
2018-01-15T12:42:11
2018-01-15T12:42:11
114,922,299
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.rtype.game; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Input; import com.badlogic.gdx.graphics.g2d.Animation; import com.badlogic.gdx.graphics.g2d.Sprite; import com.badlogic.gdx.graphics.g2d.TextureAtlas; import com.badlogic.gdx.graphics.g2d.TextureRegion; /** * Created by egaona on 12/18/2017. */ public class MainCharacter extends GameObject { private float speed = 250.0f; private float maxShootDelay = 0.25f; private float shootDelay = 0.0f; private int lives = 5; private boolean invulnerable = false; private float maxInvulnerableTime = 1.0f; private float invulnerableTime = 0.0f; private TextureAtlas textureAtlas; private Animation currentAnimation, idle, up, down, transUp, transDown, transUpRev, transDownRev; private float time = 0f; public MainCharacter(TextureAtlas texture){ textureAtlas = texture; idle = new Animation(1/9f, textureAtlas.findRegions("Ship_idle")); idle.setPlayMode(Animation.PlayMode.LOOP); up = new Animation(1/9f, textureAtlas.findRegions("Ship_up")); up.setPlayMode(Animation.PlayMode.LOOP); down = new Animation(1/9f, textureAtlas.findRegions("Ship_down")); down.setPlayMode(Animation.PlayMode.LOOP); transUp = new Animation(1/9f, textureAtlas.findRegions("Ship_transitionUp")); transUp.setPlayMode(Animation.PlayMode.NORMAL); transDown = new Animation(1/9f, textureAtlas.findRegions("Ship_transitionDown")); transDown.setPlayMode(Animation.PlayMode.NORMAL); transUpRev = new Animation(1/9f, textureAtlas.findRegions("Ship_transitionUp")); transUpRev.setPlayMode(Animation.PlayMode.REVERSED); transDownRev = new Animation(1/9f, textureAtlas.findRegions("Ship_transitionDown")); transDownRev.setPlayMode(Animation.PlayMode.REVERSED); currentAnimation = idle; TextureRegion txtrgn = (TextureRegion) currentAnimation.getKeyFrame(time, true); sprite = new Sprite(txtrgn); setScale(1.5f); setPosition(0, Gdx.graphics.getHeight()/2-getHeight()/2); } public void goUp(float delta){ if(getY() + getHeight() <= Gdx.graphics.getHeight()){ setY(getY() + speed*delta); if(currentAnimation != up && currentAnimation != transUp){ time = 0f; currentAnimation = transUp; } if(currentAnimation == transUp && currentAnimation.isAnimationFinished(time)) currentAnimation = up; }else{ currentAnimation = idle; } } public void goDown(float delta){ if(getY() >= 0){ setY(getY() - speed*delta); if(currentAnimation != down && currentAnimation != transDown){ time = 0f; currentAnimation = transDown; } if(currentAnimation == transDown && currentAnimation.isAnimationFinished(time)) currentAnimation = down; }else{ currentAnimation = idle; } } public void goRight(float delta){ if(getX() + getWidth() <= Gdx.graphics.getWidth()) setX(getX() + speed*delta); } public void goLeft(float delta){ if(getX() >= 0) setX(getX() - speed*delta); } public void getHit(){ lives--; invulnerable = true; invulnerableTime = 0.0f; setPosition(0, Gdx.graphics.getHeight()/2-getHeight()/2); RTypeGame.addScore(-25); if(lives == 0) alive = false; } public boolean isInvulnerable(){ return invulnerable; } public int getLives(){ return lives; } public void setLives(int _lives){ lives = _lives; if(lives > 0) alive = true; } @Override public void act(float delta) { time += delta; sprite.setRegion((TextureRegion) currentAnimation.getKeyFrame(time, true)); if(invulnerable){ sprite.setAlpha(invulnerableTime%0.25f); invulnerableTime += delta; if(invulnerableTime >= maxInvulnerableTime){ invulnerable = false; sprite.setAlpha(1f); } } shootDelay += delta; if(!Gdx.input.isKeyPressed(Input.Keys.UP) && !Gdx.input.isKeyPressed(Input.Keys.W) && !Gdx.input.isKeyPressed(Input.Keys.DOWN) && !Gdx.input.isKeyPressed(Input.Keys.S)){ if(currentAnimation == up || currentAnimation == transUp){ time = 0f; currentAnimation = transUpRev; }else if(currentAnimation == down || currentAnimation == transDown){ time = 0f; currentAnimation = transDownRev; }else if((currentAnimation == transUpRev || currentAnimation == transDownRev) && currentAnimation.isAnimationFinished(time)) { currentAnimation = idle; } } if(Gdx.input.isKeyPressed(Input.Keys.UP) || Gdx.input.isKeyPressed(Input.Keys.W)) goUp(delta); if(Gdx.input.isKeyPressed(Input.Keys.DOWN) || Gdx.input.isKeyPressed(Input.Keys.S)) goDown(delta); if(Gdx.input.isKeyPressed(Input.Keys.RIGHT) || Gdx.input.isKeyPressed(Input.Keys.D)) goRight(delta); if(Gdx.input.isKeyPressed(Input.Keys.LEFT) || Gdx.input.isKeyPressed(Input.Keys.A)) goLeft(delta); if(Gdx.input.isKeyPressed(Input.Keys.SPACE) && shootDelay >= maxShootDelay){ shootDelay = 0.0f; //Shoot BulletManager.addBullet(getX()+getWidth(), getY()+getHeight()/2, true); } } }
UTF-8
Java
5,596
java
MainCharacter.java
Java
[ { "context": "gdx.graphics.g2d.TextureRegion;\n\n/**\n * Created by egaona on 12/18/2017.\n */\n\npublic class MainCharacter ex", "end": 306, "score": 0.999659538269043, "start": 300, "tag": "USERNAME", "value": "egaona" } ]
null
[]
package com.rtype.game; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Input; import com.badlogic.gdx.graphics.g2d.Animation; import com.badlogic.gdx.graphics.g2d.Sprite; import com.badlogic.gdx.graphics.g2d.TextureAtlas; import com.badlogic.gdx.graphics.g2d.TextureRegion; /** * Created by egaona on 12/18/2017. */ public class MainCharacter extends GameObject { private float speed = 250.0f; private float maxShootDelay = 0.25f; private float shootDelay = 0.0f; private int lives = 5; private boolean invulnerable = false; private float maxInvulnerableTime = 1.0f; private float invulnerableTime = 0.0f; private TextureAtlas textureAtlas; private Animation currentAnimation, idle, up, down, transUp, transDown, transUpRev, transDownRev; private float time = 0f; public MainCharacter(TextureAtlas texture){ textureAtlas = texture; idle = new Animation(1/9f, textureAtlas.findRegions("Ship_idle")); idle.setPlayMode(Animation.PlayMode.LOOP); up = new Animation(1/9f, textureAtlas.findRegions("Ship_up")); up.setPlayMode(Animation.PlayMode.LOOP); down = new Animation(1/9f, textureAtlas.findRegions("Ship_down")); down.setPlayMode(Animation.PlayMode.LOOP); transUp = new Animation(1/9f, textureAtlas.findRegions("Ship_transitionUp")); transUp.setPlayMode(Animation.PlayMode.NORMAL); transDown = new Animation(1/9f, textureAtlas.findRegions("Ship_transitionDown")); transDown.setPlayMode(Animation.PlayMode.NORMAL); transUpRev = new Animation(1/9f, textureAtlas.findRegions("Ship_transitionUp")); transUpRev.setPlayMode(Animation.PlayMode.REVERSED); transDownRev = new Animation(1/9f, textureAtlas.findRegions("Ship_transitionDown")); transDownRev.setPlayMode(Animation.PlayMode.REVERSED); currentAnimation = idle; TextureRegion txtrgn = (TextureRegion) currentAnimation.getKeyFrame(time, true); sprite = new Sprite(txtrgn); setScale(1.5f); setPosition(0, Gdx.graphics.getHeight()/2-getHeight()/2); } public void goUp(float delta){ if(getY() + getHeight() <= Gdx.graphics.getHeight()){ setY(getY() + speed*delta); if(currentAnimation != up && currentAnimation != transUp){ time = 0f; currentAnimation = transUp; } if(currentAnimation == transUp && currentAnimation.isAnimationFinished(time)) currentAnimation = up; }else{ currentAnimation = idle; } } public void goDown(float delta){ if(getY() >= 0){ setY(getY() - speed*delta); if(currentAnimation != down && currentAnimation != transDown){ time = 0f; currentAnimation = transDown; } if(currentAnimation == transDown && currentAnimation.isAnimationFinished(time)) currentAnimation = down; }else{ currentAnimation = idle; } } public void goRight(float delta){ if(getX() + getWidth() <= Gdx.graphics.getWidth()) setX(getX() + speed*delta); } public void goLeft(float delta){ if(getX() >= 0) setX(getX() - speed*delta); } public void getHit(){ lives--; invulnerable = true; invulnerableTime = 0.0f; setPosition(0, Gdx.graphics.getHeight()/2-getHeight()/2); RTypeGame.addScore(-25); if(lives == 0) alive = false; } public boolean isInvulnerable(){ return invulnerable; } public int getLives(){ return lives; } public void setLives(int _lives){ lives = _lives; if(lives > 0) alive = true; } @Override public void act(float delta) { time += delta; sprite.setRegion((TextureRegion) currentAnimation.getKeyFrame(time, true)); if(invulnerable){ sprite.setAlpha(invulnerableTime%0.25f); invulnerableTime += delta; if(invulnerableTime >= maxInvulnerableTime){ invulnerable = false; sprite.setAlpha(1f); } } shootDelay += delta; if(!Gdx.input.isKeyPressed(Input.Keys.UP) && !Gdx.input.isKeyPressed(Input.Keys.W) && !Gdx.input.isKeyPressed(Input.Keys.DOWN) && !Gdx.input.isKeyPressed(Input.Keys.S)){ if(currentAnimation == up || currentAnimation == transUp){ time = 0f; currentAnimation = transUpRev; }else if(currentAnimation == down || currentAnimation == transDown){ time = 0f; currentAnimation = transDownRev; }else if((currentAnimation == transUpRev || currentAnimation == transDownRev) && currentAnimation.isAnimationFinished(time)) { currentAnimation = idle; } } if(Gdx.input.isKeyPressed(Input.Keys.UP) || Gdx.input.isKeyPressed(Input.Keys.W)) goUp(delta); if(Gdx.input.isKeyPressed(Input.Keys.DOWN) || Gdx.input.isKeyPressed(Input.Keys.S)) goDown(delta); if(Gdx.input.isKeyPressed(Input.Keys.RIGHT) || Gdx.input.isKeyPressed(Input.Keys.D)) goRight(delta); if(Gdx.input.isKeyPressed(Input.Keys.LEFT) || Gdx.input.isKeyPressed(Input.Keys.A)) goLeft(delta); if(Gdx.input.isKeyPressed(Input.Keys.SPACE) && shootDelay >= maxShootDelay){ shootDelay = 0.0f; //Shoot BulletManager.addBullet(getX()+getWidth(), getY()+getHeight()/2, true); } } }
5,596
0.625268
0.613117
157
34.643311
31.443815
138
false
false
0
0
0
0
0
0
0.707006
false
false
3
fdb1186a058a8a4b52d7740bb5fae801a22dd20a
13,726,715,511,196
894349b8d90540252fb5608b7d0b8b36e8966fbf
/app/src/main/java/com/example/chattingapp/Model/Users.java
908106bd5c500982830b2f6c9a411d5229e91179
[]
no_license
mangolithic/ChattingApp
https://github.com/mangolithic/ChattingApp
0049690b879599a2aeaa516031812fba8481d8cf
f3caee771b5cbdbb62046bfc47cd149fd63e9ab9
refs/heads/master
2023-05-03T14:59:14.208000
2021-06-02T08:13:10
2021-06-02T08:13:10
369,957,453
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.chattingapp.Model; public class Users { private String id; private String username; private String password; private String email; private String imageURL; private String about; private String search; //constructors public Users() { } public Users(String id, String username, String imageURL, String password, String email, String search) { this.id = id; this.username = username; this.password = password; this.email = email; this.imageURL = imageURL; this.about = about; this.search = search; } //getters and setters public String getId(){ return id; } public void setId(String id) { this.id = id; } public String getUsername(){ return username; } public void setUsername(String username) { this.username = username; } public String getImageURL() { return imageURL; } public void setImageURL(String imageURL) { this.imageURL = imageURL; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getAbout() { return about; } public void setAbout(String about) { this.about = about; } public void setSearch(String search){this.search = search;} public String getSearch(){return search;} }
UTF-8
Java
1,618
java
Users.java
Java
[ { "context": "h) {\n this.id = id;\n this.username = username;\n this.password = password;\n this.e", "end": 463, "score": 0.9960556030273438, "start": 455, "tag": "USERNAME", "value": "username" }, { "context": " this.username = username;\n this.password = password;\n this.email = email;\n this.imageUR", "end": 497, "score": 0.9961563944816589, "start": 489, "tag": "PASSWORD", "value": "password" }, { "context": "\n\n public String getUsername(){\n return username;\n }\n\n public void setUsername(String userna", "end": 827, "score": 0.8971521854400635, "start": 819, "tag": "USERNAME", "value": "username" }, { "context": "sername(String username) {\n this.username = username;\n }\n\n public String getImageURL() {\n ", "end": 915, "score": 0.9575476050376892, "start": 907, "tag": "USERNAME", "value": "username" }, { "context": "assword(String password) {\n this.password = password;\n }\n\n public String getEmail() {\n re", "end": 1223, "score": 0.9095046520233154, "start": 1215, "tag": "PASSWORD", "value": "password" } ]
null
[]
package com.example.chattingapp.Model; public class Users { private String id; private String username; private String password; private String email; private String imageURL; private String about; private String search; //constructors public Users() { } public Users(String id, String username, String imageURL, String password, String email, String search) { this.id = id; this.username = username; this.password = <PASSWORD>; this.email = email; this.imageURL = imageURL; this.about = about; this.search = search; } //getters and setters public String getId(){ return id; } public void setId(String id) { this.id = id; } public String getUsername(){ return username; } public void setUsername(String username) { this.username = username; } public String getImageURL() { return imageURL; } public void setImageURL(String imageURL) { this.imageURL = imageURL; } public String getPassword() { return password; } public void setPassword(String password) { this.password = <PASSWORD>; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getAbout() { return about; } public void setAbout(String about) { this.about = about; } public void setSearch(String search){this.search = search;} public String getSearch(){return search;} }
1,622
0.60445
0.60445
80
19.225
18.44585
109
false
false
0
0
0
0
0
0
0.425
false
false
3
f8da7990874e1ae27853e4a49376458b5f407170
31,533,649,915,253
8a4f84cccfc847aad5537d91bb0989297fb7f348
/src/donotfightforthefood/models/Restaurant.java
272cc7e4ae8b24cd7fb7786103bbe922c983beae
[]
no_license
lumuller/SimpleJavaExample
https://github.com/lumuller/SimpleJavaExample
00bf94e7346be64edabc82d76d0f4f5b9597ba50
18d00c63e117659a73f2418dda41ac29b2c068c8
refs/heads/master
2020-04-30T19:52:32.559000
2019-03-22T01:33:30
2019-03-22T01:33:30
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package donotfightforthefood.models; /** * * @author Luana Müller */ public class Restaurant { private String restName; private double averagePrice; private String typeOfFood; public Restaurant(String restName, double averagePrice, String typeOfFood) { this.restName = restName; this.averagePrice = averagePrice; this.typeOfFood = typeOfFood; } public String getRestName() { return restName; } public void setRestName(String restName) { this.restName = restName; } public double getAveragePrice() { return averagePrice; } public void setAveragePrice(double averagePrice) { this.averagePrice = averagePrice; } public String getTypeOfFood() { return typeOfFood; } public void setTypeOfFood(String typeOfFood) { this.typeOfFood = typeOfFood; } @Override public String toString(){ return restName+";"+averagePrice+";"+typeOfFood; } }
UTF-8
Java
1,017
java
Restaurant.java
Java
[ { "context": "ge donotfightforthefood.models;\n\n/**\n *\n * @author Luana Müller\n */\npublic class Restaurant {\n \n private St", "end": 68, "score": 0.9997581243515015, "start": 56, "tag": "NAME", "value": "Luana Müller" } ]
null
[]
package donotfightforthefood.models; /** * * @author <NAME> */ public class Restaurant { private String restName; private double averagePrice; private String typeOfFood; public Restaurant(String restName, double averagePrice, String typeOfFood) { this.restName = restName; this.averagePrice = averagePrice; this.typeOfFood = typeOfFood; } public String getRestName() { return restName; } public void setRestName(String restName) { this.restName = restName; } public double getAveragePrice() { return averagePrice; } public void setAveragePrice(double averagePrice) { this.averagePrice = averagePrice; } public String getTypeOfFood() { return typeOfFood; } public void setTypeOfFood(String typeOfFood) { this.typeOfFood = typeOfFood; } @Override public String toString(){ return restName+";"+averagePrice+";"+typeOfFood; } }
1,010
0.641732
0.641732
48
20.166666
19.355591
80
false
false
0
0
0
0
0
0
0.375
false
false
3
e540b35f5ab78a1dc99acf06d48c8e10d5e04b3f
29,300,266,916,355
c08f212c637812fd16196efbb0e4a712771cf406
/src/main/java/org/angular/controller/TarefaController.java
ea7cd32e0b72f1363a691d702be4a2c70c7a059a
[]
no_license
RafaelSouza92/AngularJsVraptorContatos
https://github.com/RafaelSouza92/AngularJsVraptorContatos
d19c50b7a2dc0811dec2ea24cd40e7be2b34b796
1da87fe425a54ea2fa311de19759a8e5f753ce93
refs/heads/master
2021-01-18T10:30:42.576000
2013-11-20T22:14:58
2013-11-20T22:14:58
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.angular.controller; import org.angular.application.Controller; import org.angular.entity.Tarefa; import org.angular.repository.TarefaRepository; import org.angular.security.SecRole; import br.com.caelum.vraptor.Consumes; import br.com.caelum.vraptor.Delete; import br.com.caelum.vraptor.Get; import br.com.caelum.vraptor.Path; import br.com.caelum.vraptor.Post; import br.com.caelum.vraptor.Put; import br.com.caelum.vraptor.Resource; import br.com.caelum.vraptor.Result; /** * * @author trgp * * Controller da entidade Tarefa para crud utilizando restful * * Perceba que a anotação @Consumes é utilizada pois a camada da view envia o objeto em formato json e o vraptor se encarrega de transformar em objeto * */ @Resource @Path("tarefas") @SecRole(roles={"ROLE_ADMIN"}) //Configuração de permissão para a role de admin public class TarefaController extends Controller { private TarefaRepository repository; public TarefaController(Result result, TarefaRepository repository) { super(result); this.repository = repository; } @Get @Path({"","/"}) public void list() { serializer(repository.findAll()).serialize(); } @Get @Path("/{start}/{limit}") public void list(Integer start, Integer limit) { serializer(repository.pagination(start, limit, null)).serialize(); } @Get @Path("/{id}") public void find(Long id) { serializer(repository.find(id),true).serialize(); } @Post @Path({"","/"}) @Consumes("application/json") public void insert(Tarefa tarefa) { repository.insert(tarefa); result.nothing(); } @Put @Path("/{tarefa.id}") @Consumes("application/json") public void update(Tarefa tarefa) { repository.update(tarefa); result.nothing(); } @Delete @Path("/{tarefa.id}") public void delete(Tarefa tarefa) { repository.delete(tarefa); result.nothing(); } @Override protected String[] excludeProps() { return new String[]{ "usuario.username", "usuario.password", "usuario.email", "usuario.ativo", "usuario.tries", "usuario.perfis" }; } }
UTF-8
Java
2,049
java
TarefaController.java
Java
[ { "context": " br.com.caelum.vraptor.Result;\n\n/**\n * \n * @author trgp\n *\n * Controller da entidade Tarefa para crud uti", "end": 510, "score": 0.9996666312217712, "start": 506, "tag": "USERNAME", "value": "trgp" }, { "context": "ing[] excludeProps() {\n\t\treturn new String[]{\n\t\t\t\"usuario.username\",\n\t\t\t\"usuario.password\",\n\t\t\t\"usuario.ema", "end": 1918, "score": 0.5287719964981079, "start": 1911, "tag": "USERNAME", "value": "usuario" }, { "context": "cludeProps() {\n\t\treturn new String[]{\n\t\t\t\"usuario.username\",\n\t\t\t\"usuario.password\",\n\t\t\t\"usuario.email\",\n\t\t\t\"", "end": 1927, "score": 0.9213634729385376, "start": 1919, "tag": "USERNAME", "value": "username" }, { "context": "ord\",\n\t\t\t\"usuario.email\",\n\t\t\t\"usuario.ativo\",\n\t\t\t\"usuario.tries\",\n\t\t\t\"usuario.perfis\"\n\t\t};\n\t}\n\n}", "end": 2004, "score": 0.7163918018341064, "start": 1997, "tag": "USERNAME", "value": "usuario" }, { "context": "\t\"usuario.email\",\n\t\t\t\"usuario.ativo\",\n\t\t\t\"usuario.tries\",\n\t\t\t\"usuario.perfis\"\n\t\t};\n\t}\n\n}", "end": 2010, "score": 0.9402017593383789, "start": 2005, "tag": "USERNAME", "value": "tries" }, { "context": "ail\",\n\t\t\t\"usuario.ativo\",\n\t\t\t\"usuario.tries\",\n\t\t\t\"usuario.perfis\"\n\t\t};\n\t}\n\n}", "end": 2024, "score": 0.5212180614471436, "start": 2017, "tag": "USERNAME", "value": "usuario" }, { "context": "\t\"usuario.ativo\",\n\t\t\t\"usuario.tries\",\n\t\t\t\"usuario.perfis\"\n\t\t};\n\t}\n\n}", "end": 2031, "score": 0.9265478253364563, "start": 2025, "tag": "USERNAME", "value": "perfis" } ]
null
[]
package org.angular.controller; import org.angular.application.Controller; import org.angular.entity.Tarefa; import org.angular.repository.TarefaRepository; import org.angular.security.SecRole; import br.com.caelum.vraptor.Consumes; import br.com.caelum.vraptor.Delete; import br.com.caelum.vraptor.Get; import br.com.caelum.vraptor.Path; import br.com.caelum.vraptor.Post; import br.com.caelum.vraptor.Put; import br.com.caelum.vraptor.Resource; import br.com.caelum.vraptor.Result; /** * * @author trgp * * Controller da entidade Tarefa para crud utilizando restful * * Perceba que a anotação @Consumes é utilizada pois a camada da view envia o objeto em formato json e o vraptor se encarrega de transformar em objeto * */ @Resource @Path("tarefas") @SecRole(roles={"ROLE_ADMIN"}) //Configuração de permissão para a role de admin public class TarefaController extends Controller { private TarefaRepository repository; public TarefaController(Result result, TarefaRepository repository) { super(result); this.repository = repository; } @Get @Path({"","/"}) public void list() { serializer(repository.findAll()).serialize(); } @Get @Path("/{start}/{limit}") public void list(Integer start, Integer limit) { serializer(repository.pagination(start, limit, null)).serialize(); } @Get @Path("/{id}") public void find(Long id) { serializer(repository.find(id),true).serialize(); } @Post @Path({"","/"}) @Consumes("application/json") public void insert(Tarefa tarefa) { repository.insert(tarefa); result.nothing(); } @Put @Path("/{tarefa.id}") @Consumes("application/json") public void update(Tarefa tarefa) { repository.update(tarefa); result.nothing(); } @Delete @Path("/{tarefa.id}") public void delete(Tarefa tarefa) { repository.delete(tarefa); result.nothing(); } @Override protected String[] excludeProps() { return new String[]{ "usuario.username", "usuario.password", "usuario.email", "usuario.ativo", "usuario.tries", "usuario.perfis" }; } }
2,049
0.719041
0.719041
91
21.461538
22.85372
150
false
false
0
0
0
0
0
0
1.252747
false
false
3
f373b5ccd6054bbc26f3cfbd48944a912b5b8dc1
23,562,190,609,303
fdb4abc0630f1169ff4f071fae1569bf76cd6c99
/app/src/main/java/com/tianyu/myvideodemo/activity/FullVideoActivity.java
a95dbc5485aa57100572863a2701bb551e633f48
[]
no_license
Sonny-Zhao/VideoView
https://github.com/Sonny-Zhao/VideoView
c9ce6e24cfccbca40a07d5f749742e752c125845
f8770b6369d4722bb1d658e89fbf0a68ee072443
refs/heads/master
2020-03-11T01:36:12.839000
2018-04-16T06:38:48
2018-04-16T06:38:48
129,696,301
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.tianyu.myvideodemo.activity; import android.app.Activity; import android.content.Intent; import android.content.pm.ActivityInfo; import android.os.Bundle; import android.view.Window; import android.view.WindowManager; import com.tianyu.myvideodemo.R; import com.tianyu.myvideodemo.model.VideoBean; import com.tianyu.myvideodemo.widget.MediaHelp; import com.tianyu.myvideodemo.widget.VideoMediaController; import com.tianyu.myvideodemo.widget.VideoSuperPlayer; /** * 全屏播放 * * @author shisheng.zhao */ public class FullVideoActivity extends Activity { private VideoSuperPlayer mVideo; private String videoUrl; private int position; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.requestWindowFeature(Window.FEATURE_NO_TITLE); this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);// 横屏 this.getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); setContentView(R.layout.activity_video_full); videoUrl = getIntent().getExtras().getString("videoUrl"); position = getIntent().getExtras().getInt("position"); initView(); initData(); } private void initView() { mVideo = (VideoSuperPlayer) findViewById(R.id.videoSuperPlayer); } private void initData() { mVideo.loadAndPlay(MediaHelp.getInstance(), videoUrl, position, true); mVideo.setPageType(VideoMediaController.PageType.EXPAND); mVideo.setVideoPlayCallback(new VideoSuperPlayer.VideoPlayCallbackImpl() { @Override public void onSwitchPageType() { if (getRequestedOrientation() == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) { finish(); } } @Override public void onPlayFinish() { finish(); } @Override public void onCloseVideo() { finish(); } }); } @Override public void finish() { Intent intent = new Intent(); intent.putExtra("position", mVideo.getCurrentPosition()); setResult(RESULT_OK, intent); super.finish(); } @Override protected void onPause() { super.onPause(); MediaHelp.pause(); } @Override protected void onResume() { super.onResume(); MediaHelp.resume(); } }
UTF-8
Java
2,488
java
FullVideoActivity.java
Java
[ { "context": "idget.VideoSuperPlayer;\n\n/**\n * 全屏播放\n *\n * @author shisheng.zhao\n */\npublic class FullVideoActivity extends Activi", "end": 514, "score": 0.9985074996948242, "start": 501, "tag": "NAME", "value": "shisheng.zhao" } ]
null
[]
package com.tianyu.myvideodemo.activity; import android.app.Activity; import android.content.Intent; import android.content.pm.ActivityInfo; import android.os.Bundle; import android.view.Window; import android.view.WindowManager; import com.tianyu.myvideodemo.R; import com.tianyu.myvideodemo.model.VideoBean; import com.tianyu.myvideodemo.widget.MediaHelp; import com.tianyu.myvideodemo.widget.VideoMediaController; import com.tianyu.myvideodemo.widget.VideoSuperPlayer; /** * 全屏播放 * * @author shisheng.zhao */ public class FullVideoActivity extends Activity { private VideoSuperPlayer mVideo; private String videoUrl; private int position; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.requestWindowFeature(Window.FEATURE_NO_TITLE); this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);// 横屏 this.getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); setContentView(R.layout.activity_video_full); videoUrl = getIntent().getExtras().getString("videoUrl"); position = getIntent().getExtras().getInt("position"); initView(); initData(); } private void initView() { mVideo = (VideoSuperPlayer) findViewById(R.id.videoSuperPlayer); } private void initData() { mVideo.loadAndPlay(MediaHelp.getInstance(), videoUrl, position, true); mVideo.setPageType(VideoMediaController.PageType.EXPAND); mVideo.setVideoPlayCallback(new VideoSuperPlayer.VideoPlayCallbackImpl() { @Override public void onSwitchPageType() { if (getRequestedOrientation() == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) { finish(); } } @Override public void onPlayFinish() { finish(); } @Override public void onCloseVideo() { finish(); } }); } @Override public void finish() { Intent intent = new Intent(); intent.putExtra("position", mVideo.getCurrentPosition()); setResult(RESULT_OK, intent); super.finish(); } @Override protected void onPause() { super.onPause(); MediaHelp.pause(); } @Override protected void onResume() { super.onResume(); MediaHelp.resume(); } }
2,488
0.647011
0.647011
85
28.129412
23.336811
93
false
false
0
0
0
0
0
0
0.517647
false
false
3
0318ef4ee341256c3c65afe1787e96dfe13a2f6c
20,160,576,506,356
8ab43fa5f7cfe6e8b8723c2f3f8917d1dbac9ded
/ProjektyStudentow/2018_Dabrowski_Filip/CarShowroomCompany/src/main/java/user/iterator/CarListIterator.java
20d0e6522e96205b30a69f49ea1b54e38bec2cf0
[]
no_license
fdabrowski/DesignPatterns
https://github.com/fdabrowski/DesignPatterns
76c876e20e1dd0f437afb05d368628d9dd1a19a1
00a2499fd4e8ae7b0cafa891065a5ea96cc35d4c
refs/heads/master
2020-04-05T15:47:40.488000
2019-01-10T20:23:08
2019-01-10T20:23:08
156,984,619
0
1
null
true
2018-11-10T13:38:37
2018-11-10T13:38:37
2018-11-04T17:54:12
2018-11-06T20:03:57
8,795
0
0
0
null
false
null
package user.iterator; import car.cars.Car; import java.util.List; public class CarListIterator implements CarIterator { List<Car> boughtCars; int position = 0; public CarListIterator(List<Car> boughtCars) { this.boughtCars = boughtCars; } @Override public boolean hasNext() { if (position >= boughtCars.size() || boughtCars.get(position)== null) { return false; } else { return true; } } @Override public Car next() { Car car = boughtCars.get(position); position++; return car; } }
UTF-8
Java
611
java
CarListIterator.java
Java
[]
null
[]
package user.iterator; import car.cars.Car; import java.util.List; public class CarListIterator implements CarIterator { List<Car> boughtCars; int position = 0; public CarListIterator(List<Car> boughtCars) { this.boughtCars = boughtCars; } @Override public boolean hasNext() { if (position >= boughtCars.size() || boughtCars.get(position)== null) { return false; } else { return true; } } @Override public Car next() { Car car = boughtCars.get(position); position++; return car; } }
611
0.585925
0.584288
32
18.09375
18.395582
79
false
false
0
0
0
0
0
0
0.40625
false
false
3
8f55e1ea151fed7801131d53621d6355195f269f
29,635,274,344,983
381f1ce13aaa6e6f7c114e67ecde5cc36959c184
/src/main/java/cs677/subdist/SubDistJob.java
4b6793a6505de8920942d26da0c32e4561f99ffc
[]
no_license
ohbriansung/big_data_project_2
https://github.com/ohbriansung/big_data_project_2
c51340330511a07dd647f81fad0173cc622c97a8
df20157132ab0836a0580295f229ff5f053944ae
refs/heads/master
2020-04-15T10:26:52.783000
2018-11-15T06:03:19
2018-11-15T06:03:19
164,596,574
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package cs677.subdist; import cs677.Writables.TextCountMapWritable; import cs677.Writables.TextCountWritable; import cs677.common.Constants; import cs677.common.FileCreator; import cs677.common.TimerStuff; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.Mapper; import org.apache.hadoop.mapreduce.Reducer; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; import org.json.JSONObject; import java.io.IOException; import java.time.Duration; import java.time.Instant; import java.util.ArrayList; import java.util.HashMap; import java.util.TreeMap; // yarn jar P2-1.0.jar cs677.subdist.SubDistJob /samples/* /test/subdist // yarn jar P2-1.0.jar cs677.subdist.SubDistJob /data/20* /out/subdist public class SubDistJob { public static void main(String[] args) { if (args.length != 2) { System.out.println("required args: <input_path> <output_path>"); System.exit(-1); } String input = args[0]; String output = args[1]; try { Instant t1 = Instant.now(); Configuration conf = new Configuration(); /* Setup */ Job job = Job.getInstance(conf, "subdist"); job.setJarByClass(SubDistJob.class); /* Input path */ FileInputFormat.addInputPath(job, new Path(input)); System.out.println("Input path: " + input); /* Output path */ Path outPath = FileCreator.findEmptyPath(conf, output); System.out.println("Output path: " + outPath.toString()); FileOutputFormat.setOutputPath(job, outPath); /* Mapper */ job.setMapperClass(SubDistMapper.class); job.setMapOutputKeyClass(Text.class); job.setMapOutputValueClass(TextCountWritable.class); /* Reducer */ job.setReducerClass(SubDistReducer.class); job.setOutputKeyClass(Text.class); job.setOutputValueClass(TextCountMapWritable.class); /* Wait job to complete */ boolean completed = job.waitForCompletion(true); System.out.println(Instant.now()); System.out.println("Input path: " + input); System.out.println("Output path: " + outPath.toString()); Instant t2 = Instant.now(); System.out.println("Time Taken: " + TimerStuff.formatDuration(Duration.between(t1, t2))); System.exit(completed ? 0 : 1); } catch (Exception e) { e.printStackTrace(); } } private static class SubDistMapper extends Mapper<LongWritable, Text, Text, TextCountWritable> { public SubDistMapper() {} @Override protected void map(LongWritable key, Text value, Context context) throws InterruptedException, IOException { JSONObject jsonObject = new JSONObject(value.toString()); String user = jsonObject.getString(Constants.AUTHOR); if (user.equals(Constants.DELETED)) return; String sub = jsonObject.getString(Constants.SUBREDDIT); context.write(new Text(sub), new TextCountWritable(user, 1)); } } private static class SubDistReducer extends Reducer<Text, TextCountWritable, Text, TextCountMapWritable> { public SubDistReducer() {} @Override protected void reduce(Text key, Iterable<TextCountWritable> values, Context context) throws InterruptedException, IOException { HashMap<String, Long> userCountMap = new HashMap<>(); for (TextCountWritable value : values) { long count = value.getCount(); String user = value.getText(); count += userCountMap.getOrDefault(user, 0L); userCountMap.put(user, count); } TreeMap<String, Long> binMap = new TreeMap<>(); userCountMap.forEach( (k, v) -> binMap.put(v.toString(), binMap.getOrDefault(v.toString(), 0L) + 1)); TextCountMapWritable outVal = new TextCountMapWritable(binMap); context.write(key, outVal); } } }
UTF-8
Java
4,025
java
SubDistJob.java
Java
[]
null
[]
package cs677.subdist; import cs677.Writables.TextCountMapWritable; import cs677.Writables.TextCountWritable; import cs677.common.Constants; import cs677.common.FileCreator; import cs677.common.TimerStuff; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.Mapper; import org.apache.hadoop.mapreduce.Reducer; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; import org.json.JSONObject; import java.io.IOException; import java.time.Duration; import java.time.Instant; import java.util.ArrayList; import java.util.HashMap; import java.util.TreeMap; // yarn jar P2-1.0.jar cs677.subdist.SubDistJob /samples/* /test/subdist // yarn jar P2-1.0.jar cs677.subdist.SubDistJob /data/20* /out/subdist public class SubDistJob { public static void main(String[] args) { if (args.length != 2) { System.out.println("required args: <input_path> <output_path>"); System.exit(-1); } String input = args[0]; String output = args[1]; try { Instant t1 = Instant.now(); Configuration conf = new Configuration(); /* Setup */ Job job = Job.getInstance(conf, "subdist"); job.setJarByClass(SubDistJob.class); /* Input path */ FileInputFormat.addInputPath(job, new Path(input)); System.out.println("Input path: " + input); /* Output path */ Path outPath = FileCreator.findEmptyPath(conf, output); System.out.println("Output path: " + outPath.toString()); FileOutputFormat.setOutputPath(job, outPath); /* Mapper */ job.setMapperClass(SubDistMapper.class); job.setMapOutputKeyClass(Text.class); job.setMapOutputValueClass(TextCountWritable.class); /* Reducer */ job.setReducerClass(SubDistReducer.class); job.setOutputKeyClass(Text.class); job.setOutputValueClass(TextCountMapWritable.class); /* Wait job to complete */ boolean completed = job.waitForCompletion(true); System.out.println(Instant.now()); System.out.println("Input path: " + input); System.out.println("Output path: " + outPath.toString()); Instant t2 = Instant.now(); System.out.println("Time Taken: " + TimerStuff.formatDuration(Duration.between(t1, t2))); System.exit(completed ? 0 : 1); } catch (Exception e) { e.printStackTrace(); } } private static class SubDistMapper extends Mapper<LongWritable, Text, Text, TextCountWritable> { public SubDistMapper() {} @Override protected void map(LongWritable key, Text value, Context context) throws InterruptedException, IOException { JSONObject jsonObject = new JSONObject(value.toString()); String user = jsonObject.getString(Constants.AUTHOR); if (user.equals(Constants.DELETED)) return; String sub = jsonObject.getString(Constants.SUBREDDIT); context.write(new Text(sub), new TextCountWritable(user, 1)); } } private static class SubDistReducer extends Reducer<Text, TextCountWritable, Text, TextCountMapWritable> { public SubDistReducer() {} @Override protected void reduce(Text key, Iterable<TextCountWritable> values, Context context) throws InterruptedException, IOException { HashMap<String, Long> userCountMap = new HashMap<>(); for (TextCountWritable value : values) { long count = value.getCount(); String user = value.getText(); count += userCountMap.getOrDefault(user, 0L); userCountMap.put(user, count); } TreeMap<String, Long> binMap = new TreeMap<>(); userCountMap.forEach( (k, v) -> binMap.put(v.toString(), binMap.getOrDefault(v.toString(), 0L) + 1)); TextCountMapWritable outVal = new TextCountMapWritable(binMap); context.write(key, outVal); } } }
4,025
0.695155
0.683727
120
32.541668
24.639364
98
false
false
0
0
0
0
0
0
0.75
false
false
3
f0f9123cfdebd2c229861d46894c624e7654fef0
14,130,442,436,484
cb0f01d114939927760cd633ba706aa5c7b3263e
/service-provider/src/main/java/com/owen/compress/Lz4Helper.java
6b979dbfc324a66f34073bafcd4e9c17a6fdf955
[]
no_license
hi794510874/springcloud-learning
https://github.com/hi794510874/springcloud-learning
ec88698131be77673de9c90d1d0f7868d861ac84
be78ac04f12bfbc5f2c9ba3314309a304169074a
refs/heads/master
2021-05-16T10:16:46.696000
2019-10-15T02:53:34
2019-10-15T02:53:34
104,205,370
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.owen.compress; import net.jpountz.lz4.*; import java.io.*; import static net.jpountz.lz4.LZ4Factory.*; /** * Created by huang_b on 2017/12/6. */ public class Lz4Helper { public static byte[] lz4Compress(byte[] data) throws IOException { LZ4Factory factory = fastestInstance(); // factory.highCompressor(6); ByteArrayOutputStream byteOutput = new ByteArrayOutputStream(); LZ4Compressor compressor = factory.fastCompressor(); LZ4BlockOutputStream compressedOutput = new LZ4BlockOutputStream(byteOutput, 8192, compressor); compressedOutput.write(data); compressedOutput.close(); return byteOutput.toByteArray(); } public static byte[] lz4DecompressReturnBytes(byte[] data) throws IOException { LZ4Factory factory = fastestInstance(); ByteArrayOutputStream baos = new ByteArrayOutputStream(8192); LZ4FastDecompressor decompresser = factory.fastDecompressor(); LZ4BlockInputStream lzis = new LZ4BlockInputStream(new ByteArrayInputStream(data), decompresser); int count; byte[] buffer = new byte[8192]; while ((count = lzis.read(buffer)) != -1) { baos.write(buffer, 0, count); } lzis.close(); return baos.toByteArray(); } public static <T> byte[] lz4Compress(T t) throws IOException { ByteArrayOutputStream bo = new ByteArrayOutputStream(); ObjectOutputStream oo = new ObjectOutputStream(bo); oo.writeObject(t); byte[] bytes = bo.toByteArray(); byte[] result = lz4Compress(bytes); return result; } public static <T> T lz4Decompress(byte[] bytes) throws IOException, ClassNotFoundException { byte[] temp = lz4DecompressReturnBytes(bytes); T t = null; ByteArrayInputStream bi = new ByteArrayInputStream(temp); ObjectInputStream oi = new ObjectInputStream(bi); t = (T) oi.readObject(); return t; } }
UTF-8
Java
1,997
java
Lz4Helper.java
Java
[ { "context": "c net.jpountz.lz4.LZ4Factory.*;\n\n/**\n * Created by huang_b on 2017/12/6.\n */\npublic class Lz4Helper {\n pu", "end": 144, "score": 0.999611496925354, "start": 137, "tag": "USERNAME", "value": "huang_b" } ]
null
[]
package com.owen.compress; import net.jpountz.lz4.*; import java.io.*; import static net.jpountz.lz4.LZ4Factory.*; /** * Created by huang_b on 2017/12/6. */ public class Lz4Helper { public static byte[] lz4Compress(byte[] data) throws IOException { LZ4Factory factory = fastestInstance(); // factory.highCompressor(6); ByteArrayOutputStream byteOutput = new ByteArrayOutputStream(); LZ4Compressor compressor = factory.fastCompressor(); LZ4BlockOutputStream compressedOutput = new LZ4BlockOutputStream(byteOutput, 8192, compressor); compressedOutput.write(data); compressedOutput.close(); return byteOutput.toByteArray(); } public static byte[] lz4DecompressReturnBytes(byte[] data) throws IOException { LZ4Factory factory = fastestInstance(); ByteArrayOutputStream baos = new ByteArrayOutputStream(8192); LZ4FastDecompressor decompresser = factory.fastDecompressor(); LZ4BlockInputStream lzis = new LZ4BlockInputStream(new ByteArrayInputStream(data), decompresser); int count; byte[] buffer = new byte[8192]; while ((count = lzis.read(buffer)) != -1) { baos.write(buffer, 0, count); } lzis.close(); return baos.toByteArray(); } public static <T> byte[] lz4Compress(T t) throws IOException { ByteArrayOutputStream bo = new ByteArrayOutputStream(); ObjectOutputStream oo = new ObjectOutputStream(bo); oo.writeObject(t); byte[] bytes = bo.toByteArray(); byte[] result = lz4Compress(bytes); return result; } public static <T> T lz4Decompress(byte[] bytes) throws IOException, ClassNotFoundException { byte[] temp = lz4DecompressReturnBytes(bytes); T t = null; ByteArrayInputStream bi = new ByteArrayInputStream(temp); ObjectInputStream oi = new ObjectInputStream(bi); t = (T) oi.readObject(); return t; } }
1,997
0.663996
0.643966
57
34.035088
28.509134
105
false
false
0
0
0
0
0
0
0.684211
false
false
3
b921e85194b7f2097c99e3b69dc487089f526b90
4,947,802,360,924
a6c75dd65cda282c29b0ecb390c7dc5d80b48ad1
/LiquorBottles-service/src/main/java/muni/fi/pa165/liquorbottles/service/services/impl/StoreServiceImpl.java
fe05fe768d1548d207f0cb47220d0de07d1de7b2
[]
no_license
XLipcak/bottles-registry
https://github.com/XLipcak/bottles-registry
df692cde2becf17094de61337c4e3cef55dab720
e40d8b22304c8117b367d816eecb4373c3f8e670
refs/heads/master
2021-05-28T02:05:22.228000
2015-01-25T22:43:40
2015-01-25T22:43:40
24,786,818
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package muni.fi.pa165.liquorbottles.service.services.impl; import java.util.List; import javax.persistence.PersistenceException; import muni.fi.pa165.liquorbottles.persistenceLayer.dao.StoreDAO; import muni.fi.pa165.liquorbottles.persistenceLayer.entities.Store; import muni.fi.pa165.liquorbottles.api.dto.StoreDTO; import muni.fi.pa165.liquorbottles.api.dto.UserDTO; import muni.fi.pa165.liquorbottles.service.dto.convertor.DozerStoreDTOConvertor; import muni.fi.pa165.liquorbottles.api.services.StoreService; import muni.fi.pa165.liquorbottles.api.services.UserService; import muni.fi.pa165.liquorbottles.persistenceLayer.dao.UserDAO; import org.springframework.beans.factory.annotation.Required; import org.springframework.dao.NonTransientDataAccessResourceException; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.security.access.annotation.Secured; /** * * @author Matus Novak, Masaryk University */ @Service @Transactional public class StoreServiceImpl implements StoreService { StoreDAO storeDAO; DozerStoreDTOConvertor dozerStoreDTOConvertor = new DozerStoreDTOConvertor(); @Override @Secured({"ROLE_ADMIN", "ROLE_POLICE", "ROLE_STORE", "ROLE_PRODUCER"}) public List<StoreDTO> findAll() { try { List<Store> store = storeDAO.findAll(); return dozerStoreDTOConvertor.fromEntityToDTO(store); } catch (PersistenceException ex) { throw new NonTransientDataAccessResourceException("Operation failed!", ex); } } @Override @Secured({"ROLE_ADMIN", "ROLE_POLICE", "ROLE_STORE", "ROLE_PRODUCER"}) public StoreDTO findById(long id) { try { Store store = storeDAO.findById(id); return dozerStoreDTOConvertor.fromEntityToDTO(store); } catch (PersistenceException ex) { throw new NonTransientDataAccessResourceException("Operation failed!", ex); } } @Override @Secured({"ROLE_ADMIN", "ROLE_POLICE"}) public StoreDTO findByAddress(String address) { try { Store store = storeDAO.findByAddress(address); return dozerStoreDTOConvertor.fromEntityToDTO(store); } catch (PersistenceException ex) { throw new NonTransientDataAccessResourceException("Operation failed!", ex); } } @Override @Secured({"ROLE_ADMIN", "ROLE_POLICE"}) public List<StoreDTO> findByFilter(String name, String address) { try { List<Store> store = storeDAO.findByFilter(name, address); return dozerStoreDTOConvertor.fromEntityToDTO(store); } catch (PersistenceException ex) { throw new NonTransientDataAccessResourceException("Operation failed!", ex); } } @Override @Secured({"ROLE_ADMIN"}) public void insertStore(StoreDTO storeDTO) { try { Store store = dozerStoreDTOConvertor.fromDTOToEntity(storeDTO); storeDAO.insertStore(store); storeDTO.setId(store.getId()); } catch (PersistenceException ex) { throw new IllegalMonitorStateException(ex.getMessage()); } } @Override @Secured({"ROLE_ADMIN"}) public void updateStore(StoreDTO storeDTO) { try { Store store = dozerStoreDTOConvertor.fromDTOToEntity(storeDTO); if(store.getPassword().equals("")){ store.setPassword(storeDAO.findById(store.getId()).getPassword()); } storeDAO.updateStore(store); } catch (PersistenceException ex) { throw new IllegalMonitorStateException(ex.getMessage()); } } @Override @Secured({"ROLE_ADMIN"}) public void deleteStore(StoreDTO storeDTO) { try { Store store = dozerStoreDTOConvertor.fromDTOToEntity(storeDTO); storeDAO.deleteStore(store); } catch (PersistenceException ex) { throw new NonTransientDataAccessResourceException("Operation failed!", ex); } } @Required @Secured({"ROLE_ADMIN"}) public void setStoreDAO(StoreDAO storeDAO) { this.storeDAO = storeDAO; } }
UTF-8
Java
4,230
java
StoreServiceImpl.java
Java
[ { "context": "rity.access.annotation.Secured;\n\n/**\n *\n * @author Matus Novak, Masaryk University\n */\n@Service\n@Transactional\np", "end": 977, "score": 0.9994638562202454, "start": 966, "tag": "NAME", "value": "Matus Novak" } ]
null
[]
package muni.fi.pa165.liquorbottles.service.services.impl; import java.util.List; import javax.persistence.PersistenceException; import muni.fi.pa165.liquorbottles.persistenceLayer.dao.StoreDAO; import muni.fi.pa165.liquorbottles.persistenceLayer.entities.Store; import muni.fi.pa165.liquorbottles.api.dto.StoreDTO; import muni.fi.pa165.liquorbottles.api.dto.UserDTO; import muni.fi.pa165.liquorbottles.service.dto.convertor.DozerStoreDTOConvertor; import muni.fi.pa165.liquorbottles.api.services.StoreService; import muni.fi.pa165.liquorbottles.api.services.UserService; import muni.fi.pa165.liquorbottles.persistenceLayer.dao.UserDAO; import org.springframework.beans.factory.annotation.Required; import org.springframework.dao.NonTransientDataAccessResourceException; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.security.access.annotation.Secured; /** * * @author <NAME>, Masaryk University */ @Service @Transactional public class StoreServiceImpl implements StoreService { StoreDAO storeDAO; DozerStoreDTOConvertor dozerStoreDTOConvertor = new DozerStoreDTOConvertor(); @Override @Secured({"ROLE_ADMIN", "ROLE_POLICE", "ROLE_STORE", "ROLE_PRODUCER"}) public List<StoreDTO> findAll() { try { List<Store> store = storeDAO.findAll(); return dozerStoreDTOConvertor.fromEntityToDTO(store); } catch (PersistenceException ex) { throw new NonTransientDataAccessResourceException("Operation failed!", ex); } } @Override @Secured({"ROLE_ADMIN", "ROLE_POLICE", "ROLE_STORE", "ROLE_PRODUCER"}) public StoreDTO findById(long id) { try { Store store = storeDAO.findById(id); return dozerStoreDTOConvertor.fromEntityToDTO(store); } catch (PersistenceException ex) { throw new NonTransientDataAccessResourceException("Operation failed!", ex); } } @Override @Secured({"ROLE_ADMIN", "ROLE_POLICE"}) public StoreDTO findByAddress(String address) { try { Store store = storeDAO.findByAddress(address); return dozerStoreDTOConvertor.fromEntityToDTO(store); } catch (PersistenceException ex) { throw new NonTransientDataAccessResourceException("Operation failed!", ex); } } @Override @Secured({"ROLE_ADMIN", "ROLE_POLICE"}) public List<StoreDTO> findByFilter(String name, String address) { try { List<Store> store = storeDAO.findByFilter(name, address); return dozerStoreDTOConvertor.fromEntityToDTO(store); } catch (PersistenceException ex) { throw new NonTransientDataAccessResourceException("Operation failed!", ex); } } @Override @Secured({"ROLE_ADMIN"}) public void insertStore(StoreDTO storeDTO) { try { Store store = dozerStoreDTOConvertor.fromDTOToEntity(storeDTO); storeDAO.insertStore(store); storeDTO.setId(store.getId()); } catch (PersistenceException ex) { throw new IllegalMonitorStateException(ex.getMessage()); } } @Override @Secured({"ROLE_ADMIN"}) public void updateStore(StoreDTO storeDTO) { try { Store store = dozerStoreDTOConvertor.fromDTOToEntity(storeDTO); if(store.getPassword().equals("")){ store.setPassword(storeDAO.findById(store.getId()).getPassword()); } storeDAO.updateStore(store); } catch (PersistenceException ex) { throw new IllegalMonitorStateException(ex.getMessage()); } } @Override @Secured({"ROLE_ADMIN"}) public void deleteStore(StoreDTO storeDTO) { try { Store store = dozerStoreDTOConvertor.fromDTOToEntity(storeDTO); storeDAO.deleteStore(store); } catch (PersistenceException ex) { throw new NonTransientDataAccessResourceException("Operation failed!", ex); } } @Required @Secured({"ROLE_ADMIN"}) public void setStoreDAO(StoreDAO storeDAO) { this.storeDAO = storeDAO; } }
4,225
0.682979
0.676596
117
35.153847
27.471699
87
false
false
0
0
0
0
0
0
0.495726
false
false
3
9756bf657b517f041632bf668a0f77e964aa5c9d
4,947,802,360,352
55b9fd4f4d2f8777e00637e466ff3f29b1c37eee
/ExperimentPurpose/src/com/turtle/models/Address.java
11491d3d4d4183610307b050c6764bd22745fac9
[]
no_license
Atif-Nayar-Ansari/Rest
https://github.com/Atif-Nayar-Ansari/Rest
f16b0b4525fd947c9bfbaf0fff53773bf1e7ec12
6f80a9435c809cfdd44dcaf1146b66458bd31877
refs/heads/master
2022-12-24T01:18:17.530000
2020-09-30T17:46:10
2020-09-30T17:46:10
299,781,875
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.turtle.models; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement public class Address { private String ano; private String aname; public Address() { } public String getAno() { return ano; } public void setAno(String ano) { this.ano = ano; } public String getAname() { return aname; } public void setAname(String aname) { this.aname = aname; } @Override public String toString() { return "Address [ano=" + ano + ", aname=" + aname + "]"; } }
UTF-8
Java
507
java
Address.java
Java
[]
null
[]
package com.turtle.models; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement public class Address { private String ano; private String aname; public Address() { } public String getAno() { return ano; } public void setAno(String ano) { this.ano = ano; } public String getAname() { return aname; } public void setAname(String aname) { this.aname = aname; } @Override public String toString() { return "Address [ano=" + ano + ", aname=" + aname + "]"; } }
507
0.662722
0.662722
34
13.911765
14.864818
58
false
false
0
0
0
0
0
0
1.176471
false
false
3
57cdab21294b1821ac6b1aba086add351bec6fb7
27,212,912,821,943
4722c8930347a329f6a99f4a54dc00a14b17d9e5
/app/src/main/java/com/incc/softwareproject/socialngatutor/adapters/viewholder/CollegeRecyclerItemViewHolder.java
249ff0b0b1852b3f9cee8f143aa4a75370c40253
[]
no_license
omgcarlo/SocialNgaTutor
https://github.com/omgcarlo/SocialNgaTutor
e8309e575081930b654fcc9afb61f13ac085b64f
5815853a960d9dac9aa136a459435953090fc462
refs/heads/master
2021-01-10T05:54:20.652000
2016-03-03T03:26:52
2016-03-03T03:26:52
48,947,968
0
2
null
false
2016-01-20T03:48:37
2016-01-03T14:11:26
2016-01-18T13:45:51
2016-01-20T03:44:22
56,355
0
1
2
Java
null
null
package com.incc.softwareproject.socialngatutor.adapters.viewholder; import android.content.Context; import android.content.Intent; import android.support.v4.view.ViewPropertyAnimatorListener; import android.support.v7.widget.RecyclerView; import android.view.View; import android.widget.ImageButton; import android.widget.TextView; import com.incc.softwareproject.socialngatutor.CourseActivity; import com.incc.softwareproject.socialngatutor.R; import jp.wasabeef.recyclerview.animators.holder.AnimateViewHolder; /** * Created by carlo on 22/02/2016. */ public class CollegeRecyclerItemViewHolder extends AnimateViewHolder implements View.OnClickListener{ private TextView tv_code; private TextView tv_name; private TextView tv_dean; private ImageButton nextBtn; private Context context; public CollegeRecyclerItemViewHolder(View parent, TextView code, TextView name, TextView dean, ImageButton next) { super(parent); tv_code = code; tv_name = name; tv_dean = dean; nextBtn = next; tv_code.setOnClickListener(this); tv_name.setOnClickListener(this); tv_dean.setOnClickListener(this); nextBtn.setOnClickListener(this); this.context = parent.getContext(); } public static CollegeRecyclerItemViewHolder newInstance(View parent) { TextView code = (TextView) parent.findViewById(R.id.item_college_code); TextView name = (TextView) parent.findViewById(R.id.item_college_name); TextView dean = (TextView) parent.findViewById(R.id.item_college_dean); ImageButton next = (ImageButton) parent.findViewById(R.id.item_college_next_btn); return new CollegeRecyclerItemViewHolder(parent,code,name,dean,next); } @Override public void animateAddImpl(ViewPropertyAnimatorListener listener) { } @Override public void animateRemoveImpl(ViewPropertyAnimatorListener listener) { } public void setCode(String code) { this.tv_code.setText(code); } public void setName(String name) { this.tv_name.setText(name); } public void setDean(String dean) { this.tv_dean.setText(dean == null || dean.equals("null")? "" : dean); } @Override public void onClick(View v) { Intent i = new Intent(context, CourseActivity.class); i.putExtra("Code",tv_code.getText().toString()); context.startActivity(i); } }
UTF-8
Java
2,462
java
CollegeRecyclerItemViewHolder.java
Java
[ { "context": "ators.holder.AnimateViewHolder;\n\n/**\n * Created by carlo on 22/02/2016.\n */\npublic class CollegeRecyclerIt", "end": 541, "score": 0.997136652469635, "start": 536, "tag": "USERNAME", "value": "carlo" } ]
null
[]
package com.incc.softwareproject.socialngatutor.adapters.viewholder; import android.content.Context; import android.content.Intent; import android.support.v4.view.ViewPropertyAnimatorListener; import android.support.v7.widget.RecyclerView; import android.view.View; import android.widget.ImageButton; import android.widget.TextView; import com.incc.softwareproject.socialngatutor.CourseActivity; import com.incc.softwareproject.socialngatutor.R; import jp.wasabeef.recyclerview.animators.holder.AnimateViewHolder; /** * Created by carlo on 22/02/2016. */ public class CollegeRecyclerItemViewHolder extends AnimateViewHolder implements View.OnClickListener{ private TextView tv_code; private TextView tv_name; private TextView tv_dean; private ImageButton nextBtn; private Context context; public CollegeRecyclerItemViewHolder(View parent, TextView code, TextView name, TextView dean, ImageButton next) { super(parent); tv_code = code; tv_name = name; tv_dean = dean; nextBtn = next; tv_code.setOnClickListener(this); tv_name.setOnClickListener(this); tv_dean.setOnClickListener(this); nextBtn.setOnClickListener(this); this.context = parent.getContext(); } public static CollegeRecyclerItemViewHolder newInstance(View parent) { TextView code = (TextView) parent.findViewById(R.id.item_college_code); TextView name = (TextView) parent.findViewById(R.id.item_college_name); TextView dean = (TextView) parent.findViewById(R.id.item_college_dean); ImageButton next = (ImageButton) parent.findViewById(R.id.item_college_next_btn); return new CollegeRecyclerItemViewHolder(parent,code,name,dean,next); } @Override public void animateAddImpl(ViewPropertyAnimatorListener listener) { } @Override public void animateRemoveImpl(ViewPropertyAnimatorListener listener) { } public void setCode(String code) { this.tv_code.setText(code); } public void setName(String name) { this.tv_name.setText(name); } public void setDean(String dean) { this.tv_dean.setText(dean == null || dean.equals("null")? "" : dean); } @Override public void onClick(View v) { Intent i = new Intent(context, CourseActivity.class); i.putExtra("Code",tv_code.getText().toString()); context.startActivity(i); } }
2,462
0.70918
0.705118
78
30.564102
28.800636
118
false
false
0
0
0
0
0
0
0.628205
false
false
3
89b017c77a68cfd90b8f6503e4eaabb068db954d
13,683,765,845,431
689aa080c8954437a4512cf70bc8b7c6449d9a01
/src/main/java/com/ideamoment/emars/model/enumeration/ProductType.java
f831ec2b9aca77aa4d2c7cd41ac9090bf4b5731f
[]
no_license
chinakite/emars
https://github.com/chinakite/emars
f9977bba14865525de01de3d5a72f21dee505e9b
98a61372f782b8efae7997f2b6996e0c0303422c
refs/heads/master
2021-04-30T05:19:18.906000
2019-02-25T16:09:45
2019-02-25T16:09:45
121,412,568
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * */ package com.ideamoment.emars.model.enumeration; /** * @author Chinakite * */ public class ProductType { public static final String TEXT = "0"; public static final String AUDIO = "1"; }
UTF-8
Java
220
java
ProductType.java
Java
[ { "context": "eamoment.emars.model.enumeration;\n\n\n/**\n * @author Chinakite\n *\n */\npublic class ProductType {\n \n public", "end": 86, "score": 0.9824870228767395, "start": 77, "tag": "NAME", "value": "Chinakite" } ]
null
[]
/** * */ package com.ideamoment.emars.model.enumeration; /** * @author Chinakite * */ public class ProductType { public static final String TEXT = "0"; public static final String AUDIO = "1"; }
220
0.613636
0.604545
16
12.75
16.543503
47
false
false
0
0
0
0
0
0
0.1875
false
false
3
03fa5d5bd2e341b5296fb1d964563a8ee7677dc4
2,095,944,083,043
c021fb4157fa0abe89cf67f62c031bcf41377dea
/pdf-splitter-swing/src/main/java/com/tommontom/pdfsplitter/PdfMerge.java
130a96a33b144dbc33624dc89da2c061dadef46c
[]
no_license
TomMonTom/PDF-Splitter
https://github.com/TomMonTom/PDF-Splitter
e02c138bf807b0239b3a20e66ffb77ef35746268
65b312d200e83c5b493d022b0f135b835db3b167
refs/heads/master
2021-01-25T07:08:50.306000
2019-03-05T07:55:41
2019-03-05T07:55:41
29,113,492
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.tommontom.pdfsplitter; import java.io.File; import java.io.FileOutputStream; /** * * @author tthompson */ import java.io.IOException; import java.util.ArrayList; import java.util.List; import com.itextpdf.text.Document; import com.itextpdf.text.DocumentException; import com.itextpdf.text.Image; import com.itextpdf.text.PageSize; import com.itextpdf.text.Rectangle; import com.itextpdf.text.pdf.PdfCopy; import com.itextpdf.text.pdf.PdfReader; import com.itextpdf.text.pdf.PdfWriter; import com.itextpdf.text.pdf.SimpleBookmark; import java.beans.PropertyChangeEvent; import java.io.ByteArrayOutputStream; import java.io.OutputStream; import java.nio.file.Files; import java.nio.file.Path; import java.util.Arrays; import java.util.HashMap; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JProgressBar; import javax.swing.SwingWorker; public class PdfMerge extends SwingWorker<Integer, Integer> { public String newFileListing = ""; //Counters for various operations private final ArrayList<HashMap<String, Object>> bookmarks = new ArrayList<>(); //an array list is instantiated for bookmarks to be saved File[] files; int counterDir; int over; public PdfMerge(File[] files, int counterDir, int over) { this.files = files; this.counterDir = counterDir; this.over = over; } protected Integer doInBackground() throws Exception { pdfMerge(files, counterDir); return null; } protected void done() { } public void pdfMerge(File[] files, int counterDir) throws InterruptedException { File newFiles = files[0]; String DEFAULT_PATH = newFiles.getParent(); File[] listOfFiles = files; String[] listImages = new String[listOfFiles.length]; String[] filesBook = new String[listOfFiles.length]; Arrays.sort(listOfFiles); // Sorts the files according to numeral filenames. (eg: Page 1, pg1, etc.) int i = 0; try { //add the file info to a list with the path and filename in place, then outputs the information to the doMerge method. for (File f : listOfFiles) { if (f.getName().toLowerCase().endsWith(".jpg")) { listImages[i] = f.getPath(); } if (f.getName().toLowerCase().endsWith(".gif")) { listImages[i] = f.getPath(); } if (f.getName().toLowerCase().endsWith(".png")) { listImages[i] = f.getPath(); } if (f.getName().toLowerCase().endsWith(".tif")) { listImages[i] = f.getPath(); } if (f.getName().toLowerCase().endsWith(".tiff")) { listImages[i] = f.getPath(); } if (f.getName().toLowerCase().endsWith(".jpeg")) { listImages[i] = f.getPath(); } if (f.exists() && !f.getName().startsWith(".", 0)) { newFileListing += ("Files Merged:" + DEFAULT_PATH + "/" + f + "\n"); } i++; } String filenameOutput = listOfFiles[0].getName(); newFileListing += ("File Made:" + DEFAULT_PATH + "/" + "(" + "Merged PDFs" + ")" +over+ ".pdf" + "\n"); doMerge(files, filesBook, listImages, counterDir); } catch (DocumentException ex) { Logger.getLogger(PdfMerge.class .getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(PdfMerge.class .getName()).log(Level.SEVERE, null, ex); } } public void doMerge(File[] files, String[] filesBook, String[] imageList, int counterDir) throws DocumentException, IOException, InterruptedException { int n = 0; int o = 0; int counter = 0; int pdfcounter = 0; Document document = new Document(PageSize.LETTER, 0, 0, 0, 0); for (int j = 0; j < files.length; j++) { int processed = ((j * 100) / files.length); setProgress(processed); if (files[j].getName().toLowerCase().endsWith(".pdf")) { pdfcounter++; } } PdfCopy copy = null; //instantiation of a pdf object is made as the copy version if (pdfcounter > 0) { if (counterDir == 0) { copy = new PdfCopy(document, new FileOutputStream(files[0].getParent() + "/" + "(" + "Merged PDFs" + ")" + over + ".pdf")); } else if (counterDir > 0) { String basePath = files[0].getPath().toString().substring(0, files[0].getPath().toString().lastIndexOf("/")); int i = basePath.lastIndexOf('/'); if (i > 0) { i = basePath.lastIndexOf('/', i); } String tail = (i >= 0) ? basePath.substring(0, i + 1) : null; copy = new PdfCopy(document, new FileOutputStream(tail + "/" + "(" + "Merged PDFs" + ")"+ over + ".pdf")); } // a counter is made to detect if a pdf exists in the file list. } Image img; // object for images to be merged List<HashMap<String, Object>> tmp; //for generated bookmarks a temporary hashtable object is made document.open(); for (int j = 0; j < files.length; j++) { if (files[j].getName().toLowerCase().endsWith(".pdf")) { counter++; PdfReader encrypt = new PdfReader(files[j].getPath()); if (encrypt.isEncrypted()) { newFileListing += ("File: " + files[j].getName() + " is encrypted, please decrypt file before splitting" + "\n"); return; } PdfReader reader = new PdfReader(files[j].getPath()); reader.consolidateNamedDestinations(); tmp = SimpleBookmark.getBookmark(reader); if (SimpleBookmark.getBookmark(reader) == null) { HashMap<String, Object> newTmp = new HashMap<>(); //to generate bookmarks from images, another object is made newTmp.put("Title", filesBook[j]); newTmp.put("Action", "GoTo"); newTmp.put("Page", String.format("%d Fit", o++)); bookmarks.add(newTmp); } if (!reader.isEncrypted()) { copy.addDocument(reader); if (tmp != null) { bookmarks.addAll(tmp); } SimpleBookmark.shiftPageNumbers(tmp, n, null); n += reader.getNumberOfPages(); } } } OutputStream out = null; Document documentimg = null; PdfWriter imageWriter = null; if (pdfcounter == 0) { out = new FileOutputStream(new File(imageList[0] + "(" + "Merged" + ")" + ".pdf")); documentimg = new Document(PageSize.LETTER); documentimg.setMargins(0, 0, 0, 0); imageWriter = PdfWriter.getInstance(documentimg, out); } /*Go through the list of images. If the filelist contains only images then copy those images to a new pdf document. If the file list contains both images and pdf documents then copy to memory and place into the merged pdf file at the end of the pdf. */ for (int i = 0; i < imageList.length; i++) { if (imageList[i] != null) { File tmpImg = new File(imageList[i]); Path path = tmpImg.toPath(); byte[] data = Files.readAllBytes(path); img = Image.getInstance(data); if (img.getPlainHeight() < img.getPlainWidth()) { img.setRotationDegrees(-90); } Rectangle resize = new Rectangle(PageSize.LETTER); img.scaleToFit(resize); if (counter == 0) { documentimg.open(); documentimg.newPage(); documentimg.add(img); documentimg.newPage(); } if (counter > 0) { Document imageDocument = new Document(PageSize.LETTER); imageDocument.setMargins(0, 0, 0, 0); ByteArrayOutputStream imageDocumentOutputStream = new ByteArrayOutputStream(); PdfWriter imageDocumentWriter = PdfWriter.getInstance(imageDocument, imageDocumentOutputStream); imageDocument.open(); imageDocument.newPage(); imageDocument.add(img); imageDocument.close(); PdfReader imageDocumentReader = new PdfReader(imageDocumentOutputStream.toByteArray()); imageDocumentWriter.close(); copy.addPage(copy.getImportedPage(imageDocumentReader, 1)); imageDocumentReader.close(); } } } bookmarkGen(imageList, n); if (!bookmarks.isEmpty() && pdfcounter > 0) { copy.setOutlines(bookmarks); } else { imageWriter.setOutlines(bookmarks); } if (counter > 0) { document.close(); } else if (counter == 0) { documentimg.close(); } setProgress(100); setProgress(0); } private void bookmarkGen(String[] imageList, int n) { for (int i = 0; i < imageList.length; i++) { System.out.println("Trigger Bookmark Images\n"); if (imageList[i] != null) { if (n==0){ n=1; } HashMap<String, Object> newTmp = new HashMap<>(); //to generate bookmarks from images, another object is made newTmp.put("Title", imageList[i].substring(imageList[i].lastIndexOf("/"), imageList[i].lastIndexOf("."))); newTmp.put("Action", "GoTo"); newTmp.put("Page", String.format("%d Fit", n++)); bookmarks.add(newTmp); System.out.println("N equals:" + n); System.out.println("HashMap ="+newTmp); } } } }
UTF-8
Java
10,929
java
PdfMerge.java
Java
[ { "context": "ort java.io.FileOutputStream;\r\n/**\r\n *\r\n * @author tthompson\r\n */\r\nimport java.io.IOException;\r\nimport java.ut", "end": 313, "score": 0.999321460723877, "start": 304, "tag": "USERNAME", "value": "tthompson" } ]
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.tommontom.pdfsplitter; import java.io.File; import java.io.FileOutputStream; /** * * @author tthompson */ import java.io.IOException; import java.util.ArrayList; import java.util.List; import com.itextpdf.text.Document; import com.itextpdf.text.DocumentException; import com.itextpdf.text.Image; import com.itextpdf.text.PageSize; import com.itextpdf.text.Rectangle; import com.itextpdf.text.pdf.PdfCopy; import com.itextpdf.text.pdf.PdfReader; import com.itextpdf.text.pdf.PdfWriter; import com.itextpdf.text.pdf.SimpleBookmark; import java.beans.PropertyChangeEvent; import java.io.ByteArrayOutputStream; import java.io.OutputStream; import java.nio.file.Files; import java.nio.file.Path; import java.util.Arrays; import java.util.HashMap; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JProgressBar; import javax.swing.SwingWorker; public class PdfMerge extends SwingWorker<Integer, Integer> { public String newFileListing = ""; //Counters for various operations private final ArrayList<HashMap<String, Object>> bookmarks = new ArrayList<>(); //an array list is instantiated for bookmarks to be saved File[] files; int counterDir; int over; public PdfMerge(File[] files, int counterDir, int over) { this.files = files; this.counterDir = counterDir; this.over = over; } protected Integer doInBackground() throws Exception { pdfMerge(files, counterDir); return null; } protected void done() { } public void pdfMerge(File[] files, int counterDir) throws InterruptedException { File newFiles = files[0]; String DEFAULT_PATH = newFiles.getParent(); File[] listOfFiles = files; String[] listImages = new String[listOfFiles.length]; String[] filesBook = new String[listOfFiles.length]; Arrays.sort(listOfFiles); // Sorts the files according to numeral filenames. (eg: Page 1, pg1, etc.) int i = 0; try { //add the file info to a list with the path and filename in place, then outputs the information to the doMerge method. for (File f : listOfFiles) { if (f.getName().toLowerCase().endsWith(".jpg")) { listImages[i] = f.getPath(); } if (f.getName().toLowerCase().endsWith(".gif")) { listImages[i] = f.getPath(); } if (f.getName().toLowerCase().endsWith(".png")) { listImages[i] = f.getPath(); } if (f.getName().toLowerCase().endsWith(".tif")) { listImages[i] = f.getPath(); } if (f.getName().toLowerCase().endsWith(".tiff")) { listImages[i] = f.getPath(); } if (f.getName().toLowerCase().endsWith(".jpeg")) { listImages[i] = f.getPath(); } if (f.exists() && !f.getName().startsWith(".", 0)) { newFileListing += ("Files Merged:" + DEFAULT_PATH + "/" + f + "\n"); } i++; } String filenameOutput = listOfFiles[0].getName(); newFileListing += ("File Made:" + DEFAULT_PATH + "/" + "(" + "Merged PDFs" + ")" +over+ ".pdf" + "\n"); doMerge(files, filesBook, listImages, counterDir); } catch (DocumentException ex) { Logger.getLogger(PdfMerge.class .getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(PdfMerge.class .getName()).log(Level.SEVERE, null, ex); } } public void doMerge(File[] files, String[] filesBook, String[] imageList, int counterDir) throws DocumentException, IOException, InterruptedException { int n = 0; int o = 0; int counter = 0; int pdfcounter = 0; Document document = new Document(PageSize.LETTER, 0, 0, 0, 0); for (int j = 0; j < files.length; j++) { int processed = ((j * 100) / files.length); setProgress(processed); if (files[j].getName().toLowerCase().endsWith(".pdf")) { pdfcounter++; } } PdfCopy copy = null; //instantiation of a pdf object is made as the copy version if (pdfcounter > 0) { if (counterDir == 0) { copy = new PdfCopy(document, new FileOutputStream(files[0].getParent() + "/" + "(" + "Merged PDFs" + ")" + over + ".pdf")); } else if (counterDir > 0) { String basePath = files[0].getPath().toString().substring(0, files[0].getPath().toString().lastIndexOf("/")); int i = basePath.lastIndexOf('/'); if (i > 0) { i = basePath.lastIndexOf('/', i); } String tail = (i >= 0) ? basePath.substring(0, i + 1) : null; copy = new PdfCopy(document, new FileOutputStream(tail + "/" + "(" + "Merged PDFs" + ")"+ over + ".pdf")); } // a counter is made to detect if a pdf exists in the file list. } Image img; // object for images to be merged List<HashMap<String, Object>> tmp; //for generated bookmarks a temporary hashtable object is made document.open(); for (int j = 0; j < files.length; j++) { if (files[j].getName().toLowerCase().endsWith(".pdf")) { counter++; PdfReader encrypt = new PdfReader(files[j].getPath()); if (encrypt.isEncrypted()) { newFileListing += ("File: " + files[j].getName() + " is encrypted, please decrypt file before splitting" + "\n"); return; } PdfReader reader = new PdfReader(files[j].getPath()); reader.consolidateNamedDestinations(); tmp = SimpleBookmark.getBookmark(reader); if (SimpleBookmark.getBookmark(reader) == null) { HashMap<String, Object> newTmp = new HashMap<>(); //to generate bookmarks from images, another object is made newTmp.put("Title", filesBook[j]); newTmp.put("Action", "GoTo"); newTmp.put("Page", String.format("%d Fit", o++)); bookmarks.add(newTmp); } if (!reader.isEncrypted()) { copy.addDocument(reader); if (tmp != null) { bookmarks.addAll(tmp); } SimpleBookmark.shiftPageNumbers(tmp, n, null); n += reader.getNumberOfPages(); } } } OutputStream out = null; Document documentimg = null; PdfWriter imageWriter = null; if (pdfcounter == 0) { out = new FileOutputStream(new File(imageList[0] + "(" + "Merged" + ")" + ".pdf")); documentimg = new Document(PageSize.LETTER); documentimg.setMargins(0, 0, 0, 0); imageWriter = PdfWriter.getInstance(documentimg, out); } /*Go through the list of images. If the filelist contains only images then copy those images to a new pdf document. If the file list contains both images and pdf documents then copy to memory and place into the merged pdf file at the end of the pdf. */ for (int i = 0; i < imageList.length; i++) { if (imageList[i] != null) { File tmpImg = new File(imageList[i]); Path path = tmpImg.toPath(); byte[] data = Files.readAllBytes(path); img = Image.getInstance(data); if (img.getPlainHeight() < img.getPlainWidth()) { img.setRotationDegrees(-90); } Rectangle resize = new Rectangle(PageSize.LETTER); img.scaleToFit(resize); if (counter == 0) { documentimg.open(); documentimg.newPage(); documentimg.add(img); documentimg.newPage(); } if (counter > 0) { Document imageDocument = new Document(PageSize.LETTER); imageDocument.setMargins(0, 0, 0, 0); ByteArrayOutputStream imageDocumentOutputStream = new ByteArrayOutputStream(); PdfWriter imageDocumentWriter = PdfWriter.getInstance(imageDocument, imageDocumentOutputStream); imageDocument.open(); imageDocument.newPage(); imageDocument.add(img); imageDocument.close(); PdfReader imageDocumentReader = new PdfReader(imageDocumentOutputStream.toByteArray()); imageDocumentWriter.close(); copy.addPage(copy.getImportedPage(imageDocumentReader, 1)); imageDocumentReader.close(); } } } bookmarkGen(imageList, n); if (!bookmarks.isEmpty() && pdfcounter > 0) { copy.setOutlines(bookmarks); } else { imageWriter.setOutlines(bookmarks); } if (counter > 0) { document.close(); } else if (counter == 0) { documentimg.close(); } setProgress(100); setProgress(0); } private void bookmarkGen(String[] imageList, int n) { for (int i = 0; i < imageList.length; i++) { System.out.println("Trigger Bookmark Images\n"); if (imageList[i] != null) { if (n==0){ n=1; } HashMap<String, Object> newTmp = new HashMap<>(); //to generate bookmarks from images, another object is made newTmp.put("Title", imageList[i].substring(imageList[i].lastIndexOf("/"), imageList[i].lastIndexOf("."))); newTmp.put("Action", "GoTo"); newTmp.put("Page", String.format("%d Fit", n++)); bookmarks.add(newTmp); System.out.println("N equals:" + n); System.out.println("HashMap ="+newTmp); } } } }
10,929
0.526123
0.520999
274
37.88686
30.834116
141
false
false
0
0
0
0
0
0
0.751825
false
false
3
f388860c8c9459c754ce3bf0eb29cd894ff1699e
16,973,710,796,201
a7b0a261b57d0e7b01cb6e9fdeee74bdda6f79ea
/src/java/fr/paris/lutece/plugins/plu/business/folder/FolderHome.java
31988b9d372ed8ff860074f18a2b9c7217dc99fe
[]
no_license
lutece-secteur-public/urbanisme-plugin-plu
https://github.com/lutece-secteur-public/urbanisme-plugin-plu
a5960fa76ee7e81e573df4c55bdfddc1cb933de9
687f2b39bfb205b547712f1bde1f29ec8a1d093d
refs/heads/master
2020-03-31T08:06:19.683000
2015-09-21T08:27:29
2015-09-21T08:27:29
42,853,491
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * Copyright (c) 2002-2011, Mairie de Paris * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright notice * and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice * and the following disclaimer in the documentation and/or other materials * provided with the distribution. * * 3. Neither the name of 'Mairie de Paris' nor 'Lutece' nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * License 1.0 */ package fr.paris.lutece.plugins.plu.business.folder; import fr.paris.lutece.portal.service.image.ImageResource; import fr.paris.lutece.portal.service.jpa.AbstractLuteceHome; import java.util.List; /** * This class provides instances management methods (create, find, ...) for Folder objects * @author vLopez */ public class FolderHome extends AbstractLuteceHome<Integer, Folder, IFolderDAO> implements IFolderHome { /** * Returns a folder object * @return The last folder created */ public Folder findLastFolder( ) { return getDao( ).findLastFolder( ); } /** * Returns a folder object * @param title the folder title * @return A folder object with the same title */ public Folder findForTestTitle( String title ) { return getDao( ).findForTestTitle( title ); } /** * Returns a folder object * @param nIdAtome the atome id * @return A folder object associated with the atome id */ public Folder findByAtome( int nIdAtome ) { return getDao( ).findByAtome( nIdAtome ); } /** * Returns a folder object * @param nIdVersion the version id * @return A folder object associated with the version id */ public Folder findByVersion( int nIdVersion ) { return getDao( ).findByVersion( nIdVersion ); } /** * Returns a folder object * @param nKey the folder id * @return A folder object which has a child or an atome */ public Folder findForDelete( int nKey ) { return getDao( ).findForDelete( nKey ); } /** * Returns a list of folder objects * @param pluId the plu id * @return A list of folder with the same plu id */ public List<Folder> findByPluId( int pluId ) { return getDao( ).findByPluId( pluId ); } /** * Returns a list of folder objects * @param parentId the folder parent id * @return A list of folder with the same folder parent id */ public List<Folder> findByParent( int parentId ) { return getDao( ).findByParent( parentId ); } /** * Finds by filter * @param filter the filter * @return the folder list */ public List<Folder> findByFilter( FolderFilter filter ) { return getDao( ).findByFilter( filter ); } /** * Loads the image representing the folder * * @param nIdFolder int identifier of the Folder to fetch * @return the image resource */ public ImageResource getImageResource( int nIdFolder ) { return getDao( ).getImageResource( nIdFolder ); } /** * Loads the html specifique representing the folder * * @param nIdFolder int identifier of the Folder to fetch * @return the html specifique */ public ImageResource getHtmlResource( int nIdFolder ) { return getDao( ).getHtmlResource( nIdFolder ); } }
UTF-8
Java
4,710
java
FolderHome.java
Java
[ { "context": "/*\r\n * Copyright (c) 2002-2011, Mairie de Paris\r\n * All rights reserved.\r\n *\r\n * Redistribution a", "end": 47, "score": 0.9996551871299744, "start": 32, "tag": "NAME", "value": "Mairie de Paris" }, { "context": "(create, find, ...) for Folder objects\r\n * @author vLopez\r\n */\r\npublic class FolderHome extends AbstractLut", "end": 1938, "score": 0.9993908405303955, "start": 1932, "tag": "USERNAME", "value": "vLopez" } ]
null
[]
/* * Copyright (c) 2002-2011, <NAME> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright notice * and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice * and the following disclaimer in the documentation and/or other materials * provided with the distribution. * * 3. Neither the name of 'Mairie de Paris' nor 'Lutece' nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * License 1.0 */ package fr.paris.lutece.plugins.plu.business.folder; import fr.paris.lutece.portal.service.image.ImageResource; import fr.paris.lutece.portal.service.jpa.AbstractLuteceHome; import java.util.List; /** * This class provides instances management methods (create, find, ...) for Folder objects * @author vLopez */ public class FolderHome extends AbstractLuteceHome<Integer, Folder, IFolderDAO> implements IFolderHome { /** * Returns a folder object * @return The last folder created */ public Folder findLastFolder( ) { return getDao( ).findLastFolder( ); } /** * Returns a folder object * @param title the folder title * @return A folder object with the same title */ public Folder findForTestTitle( String title ) { return getDao( ).findForTestTitle( title ); } /** * Returns a folder object * @param nIdAtome the atome id * @return A folder object associated with the atome id */ public Folder findByAtome( int nIdAtome ) { return getDao( ).findByAtome( nIdAtome ); } /** * Returns a folder object * @param nIdVersion the version id * @return A folder object associated with the version id */ public Folder findByVersion( int nIdVersion ) { return getDao( ).findByVersion( nIdVersion ); } /** * Returns a folder object * @param nKey the folder id * @return A folder object which has a child or an atome */ public Folder findForDelete( int nKey ) { return getDao( ).findForDelete( nKey ); } /** * Returns a list of folder objects * @param pluId the plu id * @return A list of folder with the same plu id */ public List<Folder> findByPluId( int pluId ) { return getDao( ).findByPluId( pluId ); } /** * Returns a list of folder objects * @param parentId the folder parent id * @return A list of folder with the same folder parent id */ public List<Folder> findByParent( int parentId ) { return getDao( ).findByParent( parentId ); } /** * Finds by filter * @param filter the filter * @return the folder list */ public List<Folder> findByFilter( FolderFilter filter ) { return getDao( ).findByFilter( filter ); } /** * Loads the image representing the folder * * @param nIdFolder int identifier of the Folder to fetch * @return the image resource */ public ImageResource getImageResource( int nIdFolder ) { return getDao( ).getImageResource( nIdFolder ); } /** * Loads the html specifique representing the folder * * @param nIdFolder int identifier of the Folder to fetch * @return the html specifique */ public ImageResource getHtmlResource( int nIdFolder ) { return getDao( ).getHtmlResource( nIdFolder ); } }
4,701
0.649045
0.646285
148
29.824324
27.252254
102
false
false
0
0
0
0
0
0
0.263514
false
false
3
4040946248e13fda3c09efc8ca4df649aa36ac69
4,647,154,648,275
98f7c1c690f435e5b6f51c0da897086c770ea604
/CouponSystem/src/db_building/CreateDB.java
2b7d3de2faca5c76878632e34a243809b37cb9f1
[]
no_license
NulaKr/CouponSystem
https://github.com/NulaKr/CouponSystem
a86e27b84ded68fe4f31de4fbe5722f82af18a08
575b3c822b85a053ccd3479c73196ca655650058
refs/heads/master
2020-03-27T09:18:44.429000
2018-09-20T05:00:38
2018-09-20T05:00:38
146,329,948
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package db_building; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; public class CreateDB { public static void main(String[] args) { // This will be the DB in which the tables are stored String url = "jdbc:derby://localhost:1527/CouponSystem;create=true;"; try (Connection conn = DriverManager.getConnection(url)) { System.out.println("connected"); //The different table creation String createCompany = "CREATE TABLE Company(ID BIGINT NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1), compname VARCHAR(40), password VARCHAR(16), email VARCHAR(30))"; String createCustomer = "CREATE TABLE Customer(ID BIGINT NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1), cust_name VARCHAR(30), password VARCHAR(16))"; String createCoupon = "CREATE TABLE Coupon(ID BIGINT NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1), title VARCHAR(100), start_date DATE, end_date DATE, amount INT, type VARCHAR(30), message VARCHAR(1000), price FLOAT, image VARCHAR(40))"; String createJoinCustCoupon = "CREATE TABLE Join_Customer_Coupon (cust_id BIGINT, coupon_id BIGINT, primary key(cust_id, coupon_id))"; String createJoinCompCoupon = "CREATE TABLE Join_Company_Coupon (comp_id BIGINT, coupon_id BIGINT, primary key(comp_id, coupon_id))"; // Create a statement Statement stmt = conn.createStatement(); //execute the table creation stmt.executeUpdate(createCompany); stmt.executeUpdate(createCoupon); stmt.executeUpdate(createCustomer); stmt.executeUpdate(createJoinCompCoupon); stmt.executeUpdate(createJoinCustCoupon); } catch (SQLException e) { e.printStackTrace(); } } }
UTF-8
Java
1,930
java
CreateDB.java
Java
[ { "context": "NT BY 1), compname VARCHAR(40), password VARCHAR(16), email VARCHAR(30))\";\n String createC", "end": 685, "score": 0.6833915114402771, "start": 684, "tag": "PASSWORD", "value": "6" } ]
null
[]
package db_building; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; public class CreateDB { public static void main(String[] args) { // This will be the DB in which the tables are stored String url = "jdbc:derby://localhost:1527/CouponSystem;create=true;"; try (Connection conn = DriverManager.getConnection(url)) { System.out.println("connected"); //The different table creation String createCompany = "CREATE TABLE Company(ID BIGINT NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1), compname VARCHAR(40), password VARCHAR(16), email VARCHAR(30))"; String createCustomer = "CREATE TABLE Customer(ID BIGINT NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1), cust_name VARCHAR(30), password VARCHAR(16))"; String createCoupon = "CREATE TABLE Coupon(ID BIGINT NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1), title VARCHAR(100), start_date DATE, end_date DATE, amount INT, type VARCHAR(30), message VARCHAR(1000), price FLOAT, image VARCHAR(40))"; String createJoinCustCoupon = "CREATE TABLE Join_Customer_Coupon (cust_id BIGINT, coupon_id BIGINT, primary key(cust_id, coupon_id))"; String createJoinCompCoupon = "CREATE TABLE Join_Company_Coupon (comp_id BIGINT, coupon_id BIGINT, primary key(comp_id, coupon_id))"; // Create a statement Statement stmt = conn.createStatement(); //execute the table creation stmt.executeUpdate(createCompany); stmt.executeUpdate(createCoupon); stmt.executeUpdate(createCustomer); stmt.executeUpdate(createJoinCompCoupon); stmt.executeUpdate(createJoinCustCoupon); } catch (SQLException e) { e.printStackTrace(); } } }
1,930
0.679275
0.663212
41
46.07317
60.046482
273
false
false
0
0
0
0
0
0
1.04878
false
false
3
5b18a0440234f37f7082391145ccbccf16289655
17,300,128,307,669
fce9538bd54a88c082fb09e0456b656b8cff9bd1
/app/src/main/java/com/geekbrains/widgetexample2/WidgetNotesFactory.java
e3c419984d6455bb1f644ebf0d0a6ea683657208
[]
no_license
rumpilstilstkin/Lesson8
https://github.com/rumpilstilstkin/Lesson8
f98123614939fb06d9e28246dc31403d370edbd4
e1fefadd0ac070d529ba4655ffb40c843b8a7c1a
refs/heads/master
2020-03-13T08:37:55.397000
2018-04-25T18:27:58
2018-04-25T18:27:58
131,047,324
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.geekbrains.widgetexample2; import android.content.Context; import android.content.Intent; import android.widget.RemoteViews; import android.widget.RemoteViewsService; import java.util.ArrayList; import java.util.List; public class WidgetNotesFactory implements RemoteViewsService.RemoteViewsFactory { Context mContext; private List<Note> records; public WidgetNotesFactory(Context context, Intent intent) { mContext = context; } public void onCreate() { records = new ArrayList<Note>(); } @Override public int getCount() { return records.size(); } @Override public long getItemId(int position) { return position; } @Override public RemoteViews getLoadingView() { return null; } @Override public RemoteViews getViewAt(int position) { RemoteViews rView = new RemoteViews(mContext.getPackageName(), R.layout.item_widget); rView.setTextViewText(R.id.text, records.get(position).toString()); Intent clickIntent = new Intent(); clickIntent.putExtra(WidgetNotes.NOTE_TEXT, records.get(position).toString()); rView.setOnClickFillInIntent(R.id.text, clickIntent); return rView; } @Override public int getViewTypeCount() { return 1; } @Override public boolean hasStableIds() { return true; } @Override public void onDataSetChanged() { records.clear(); NoteDataSource notesDataSource = new NoteDataSource(mContext); notesDataSource.open(); records = notesDataSource.getAllNotes(); notesDataSource.close(); } @Override public void onDestroy() { } }
UTF-8
Java
1,746
java
WidgetNotesFactory.java
Java
[]
null
[]
package com.geekbrains.widgetexample2; import android.content.Context; import android.content.Intent; import android.widget.RemoteViews; import android.widget.RemoteViewsService; import java.util.ArrayList; import java.util.List; public class WidgetNotesFactory implements RemoteViewsService.RemoteViewsFactory { Context mContext; private List<Note> records; public WidgetNotesFactory(Context context, Intent intent) { mContext = context; } public void onCreate() { records = new ArrayList<Note>(); } @Override public int getCount() { return records.size(); } @Override public long getItemId(int position) { return position; } @Override public RemoteViews getLoadingView() { return null; } @Override public RemoteViews getViewAt(int position) { RemoteViews rView = new RemoteViews(mContext.getPackageName(), R.layout.item_widget); rView.setTextViewText(R.id.text, records.get(position).toString()); Intent clickIntent = new Intent(); clickIntent.putExtra(WidgetNotes.NOTE_TEXT, records.get(position).toString()); rView.setOnClickFillInIntent(R.id.text, clickIntent); return rView; } @Override public int getViewTypeCount() { return 1; } @Override public boolean hasStableIds() { return true; } @Override public void onDataSetChanged() { records.clear(); NoteDataSource notesDataSource = new NoteDataSource(mContext); notesDataSource.open(); records = notesDataSource.getAllNotes(); notesDataSource.close(); } @Override public void onDestroy() { } }
1,746
0.659221
0.658076
75
22.280001
21.768209
86
false
false
0
0
0
0
0
0
0.426667
false
false
3
5da5e661728cb7ddde6fd850edc0fc1f5a960e90
32,323,923,909,184
2a397e1beede156e7a9b28ecfe2850d6572dfded
/src/main/java/ua/andriosta/projects/jaxbObjects/ReservetionResult.java
9aca50dfab2d00293eafea4dccc87dcc834aa6f6
[]
no_license
AndriOsta/RailwayStation
https://github.com/AndriOsta/RailwayStation
ce42648be86b111fe0ac1c8dbf87ab6f02c62f3f
0904b5742d88b287238fd6d903a975a163044892
refs/heads/master
2021-01-16T17:56:02.344000
2017-08-11T11:46:12
2017-08-11T11:46:12
100,026,039
2
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 ua.andriosta.projects.jaxbObjects; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import ua.andriosta.projects.objects.Reservation; @XmlRootElement(name = "reservationResult") @XmlAccessorType(XmlAccessType.NONE) public class ReservetionResult { @XmlElement(name = "reservation") private Reservation reservation; public Reservation getReservation() { return reservation; } public void setReservation(Reservation reservation) { this.reservation = reservation; } }
UTF-8
Java
853
java
ReservetionResult.java
Java
[]
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 ua.andriosta.projects.jaxbObjects; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import ua.andriosta.projects.objects.Reservation; @XmlRootElement(name = "reservationResult") @XmlAccessorType(XmlAccessType.NONE) public class ReservetionResult { @XmlElement(name = "reservation") private Reservation reservation; public Reservation getReservation() { return reservation; } public void setReservation(Reservation reservation) { this.reservation = reservation; } }
853
0.762016
0.762016
30
27.433332
22.816198
79
false
false
0
0
0
0
0
0
0.4
false
false
3
388fa249212c54847c7283bf309ce293563c5de5
29,463,475,684,614
62dc07c6c16998a0a19d54937f1be5eb0ceea1ff
/fesdweb/src/fesdweb/data/AdvancedSearchDataService.java
df68d212674be51107e94fcf103d10731e3addc6
[]
no_license
atowfiq/FESD_website-scripts
https://github.com/atowfiq/FESD_website-scripts
5e9c174abddea33affba11770fa806b7730645ba
50a12f543aeed54d1e23563ed30b750637b3c5d5
refs/heads/master
2022-09-18T06:33:28.074000
2017-08-01T17:25:59
2017-08-01T17:25:59
267,652,427
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package fesdweb.data; import java.sql.CallableStatement; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import com.mysql.fabric.xmlrpc.base.Array; import fesdweb.model.Compound; import fesdweb.model.Element; import fesdweb.model.SpaceGroup; public class AdvancedSearchDataService { public AdvancedSearchDataService() { } public ArrayList<Compound> SearchCompoundByOrbital( String addtionalElements, Boolean isShowAll, int spaceGroup, String crystalSystem,String query,double emin,double emax) { query=query.length()==0?"true=true":query; ArrayList<Compound> compoundList = new ArrayList<Compound>(); Connection conn = DataUtils.CreateConnection(); try { Statement stmt = conn.createStatement(); String compoundQuery = "Select atomicno, _cod_database_code, _chemical_formula_sum,_space_group_IT_number,_symmetry_cell_setting, id, source, _database_code_ICSD , _symmetry_space_group_name_HM,bsexists,dosexists from compound"; compoundQuery =String.format(compoundQuery+ " where (%s=0 or _space_group_it_number='%s') and (char_length('%s')=0 or _symmetry_cell_setting='%s') and id ",spaceGroup,spaceGroup,crystalSystem,crystalSystem); String bandQuery = String.format(" (compoundid,`index`) in (select compoundid,`index` from bandstructuredata where energymin>=%s and energymax<=%s )", emin,emax); String q = String.format(compoundQuery + " in (select distinct compoundid from partialbandstructuredata where %s and %s) order by source desc;" , query,bandQuery); ResultSet rs = stmt.executeQuery(q); while (rs.next()) { String formula = rs.getString("_chemical_formula_sum"); Compound c = new Compound(rs.getInt("atomicno") , rs.getInt("_cod_database_code"),formula, rs.getInt("_space_group_IT_number"), rs.getString("_symmetry_cell_setting"), rs.getString("_symmetry_space_group_name_HM"),rs.getInt("id"),rs.getString("source"),rs.getInt("_database_code_ICSD"),rs.getBoolean("bsexists"),rs.getBoolean("dosexists")); compoundList.add(c); } rs.close(); stmt.close(); conn.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return compoundList; } }
UTF-8
Java
2,307
java
AdvancedSearchDataService.java
Java
[]
null
[]
package fesdweb.data; import java.sql.CallableStatement; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import com.mysql.fabric.xmlrpc.base.Array; import fesdweb.model.Compound; import fesdweb.model.Element; import fesdweb.model.SpaceGroup; public class AdvancedSearchDataService { public AdvancedSearchDataService() { } public ArrayList<Compound> SearchCompoundByOrbital( String addtionalElements, Boolean isShowAll, int spaceGroup, String crystalSystem,String query,double emin,double emax) { query=query.length()==0?"true=true":query; ArrayList<Compound> compoundList = new ArrayList<Compound>(); Connection conn = DataUtils.CreateConnection(); try { Statement stmt = conn.createStatement(); String compoundQuery = "Select atomicno, _cod_database_code, _chemical_formula_sum,_space_group_IT_number,_symmetry_cell_setting, id, source, _database_code_ICSD , _symmetry_space_group_name_HM,bsexists,dosexists from compound"; compoundQuery =String.format(compoundQuery+ " where (%s=0 or _space_group_it_number='%s') and (char_length('%s')=0 or _symmetry_cell_setting='%s') and id ",spaceGroup,spaceGroup,crystalSystem,crystalSystem); String bandQuery = String.format(" (compoundid,`index`) in (select compoundid,`index` from bandstructuredata where energymin>=%s and energymax<=%s )", emin,emax); String q = String.format(compoundQuery + " in (select distinct compoundid from partialbandstructuredata where %s and %s) order by source desc;" , query,bandQuery); ResultSet rs = stmt.executeQuery(q); while (rs.next()) { String formula = rs.getString("_chemical_formula_sum"); Compound c = new Compound(rs.getInt("atomicno") , rs.getInt("_cod_database_code"),formula, rs.getInt("_space_group_IT_number"), rs.getString("_symmetry_cell_setting"), rs.getString("_symmetry_space_group_name_HM"),rs.getInt("id"),rs.getString("source"),rs.getInt("_database_code_ICSD"),rs.getBoolean("bsexists"),rs.getBoolean("dosexists")); compoundList.add(c); } rs.close(); stmt.close(); conn.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return compoundList; } }
2,307
0.727352
0.726051
61
36.819672
54.471684
231
false
false
0
0
0
0
0
0
2.737705
false
false
3
23438c45822e78d4466686bb9b3cd305616cdad5
17,858,474,059,789
210492182b44af2622134476760c70ef231229eb
/leetcode/PalindromeNumber.java
b04e0c9ceedc45495991b3f2abb012cd100271fe
[]
no_license
blingwang/coding-collections
https://github.com/blingwang/coding-collections
e4647bb292474b4180ececd5932e40218098fd65
f577196b63064ab55bb7686d1fc38653eb4dbc47
refs/heads/master
2021-01-19T01:23:17.673000
2018-03-27T16:36:54
2018-03-27T16:36:54
11,449,235
3
0
null
null
null
null
null
null
null
null
null
null
null
null
null
public class PalindromeNumber { public boolean isPalindrome(int x) { if (x < 0) return false; int div = 1; // for single digit while (x / div >= 10) { div *= 10; } while (x > 0) { int left = x % 10; int right = x / div; if (left != right) return false; x = (x % div) / 10; div /= 100; // x will reduce to 0 before div } return true; } public boolean isPalindrome2(int x) { // avoid overflow if (x < 0) return false; long origion = x; long reverse = 0; while (x != 0) { reverse = reverse * 10 + x % 10; x /= 10; } return reverse == origion; } }
UTF-8
Java
820
java
PalindromeNumber.java
Java
[]
null
[]
public class PalindromeNumber { public boolean isPalindrome(int x) { if (x < 0) return false; int div = 1; // for single digit while (x / div >= 10) { div *= 10; } while (x > 0) { int left = x % 10; int right = x / div; if (left != right) return false; x = (x % div) / 10; div /= 100; // x will reduce to 0 before div } return true; } public boolean isPalindrome2(int x) { // avoid overflow if (x < 0) return false; long origion = x; long reverse = 0; while (x != 0) { reverse = reverse * 10 + x % 10; x /= 10; } return reverse == origion; } }
820
0.409756
0.379268
34
23.117647
15.256175
59
false
false
0
0
0
0
0
0
0.441176
false
false
3
efc5fe44b5a50f3081ca275840c8b57c1f4289ed
27,152,783,282,551
a49d2bd382af4c46d8938146c0e1bdaea7bd5970
/web-admin/src/main/java/com/rancho/web/admin/domain/dto/menu/MenuParam.java
c6336e3320e8a714bbb7f114cdfd81087dbbeacd
[ "Apache-2.0" ]
permissive
freedom541/rancho-web
https://github.com/freedom541/rancho-web
a85537ed82359706740604e4fd9f05bf081c7d72
9cb532de572135731c407213d5827032fba2acb0
refs/heads/master
2023-03-28T11:38:27.581000
2021-03-19T02:52:59
2021-03-19T02:52:59
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.rancho.web.admin.domain.dto.menu; import lombok.Data; @Data public class MenuParam { }
UTF-8
Java
101
java
MenuParam.java
Java
[]
null
[]
package com.rancho.web.admin.domain.dto.menu; import lombok.Data; @Data public class MenuParam { }
101
0.762376
0.762376
7
13.428572
15.701293
45
false
false
0
0
0
0
0
0
0.285714
false
false
3
abe5be450151aa1ca8f620b2639dbda4030c1681
26,628,797,280,803
6ba17982c4da62e5424fcd47f1bdf008d2806662
/src/main/java/net/easyjava/framework/utils/SignUtils.java
e898dc20e292fb286d123e8fa7f2ac1bd5089bb9
[]
no_license
wxnacy/EasyJava-Framework
https://github.com/wxnacy/EasyJava-Framework
4c3052706321ee4efbedf2cea170fa4e2e04d2cb
bd93c9b3d8e16ff8b1baba7845453a3127fea2be
refs/heads/master
2017-12-23T21:50:50.721000
2016-11-21T10:28:01
2016-11-21T10:28:01
72,608,850
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package net.easyjava.framework.utils; import net.easyjava.tools.http.HttpTools; import net.easyjava.tools.lang.MapTools; import net.easyjava.tools.lang.StringTools; import net.easyjava.tools.security.SignTools; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.security.NoSuchAlgorithmException; import java.util.SortedMap; import java.util.TreeMap; /** * Created by wxnacy on 16/8/22. */ public class SignUtils { protected static final String API_SIGN_KEY = "a2dc8a390e92ab87678a5bf922fbd5dd"; static Logger logger = LoggerFactory.getLogger(SignUtils.class); /** * 获取加密地址 * @param url * @param params * @return */ public static final String getSignUrl(String url,SortedMap<String, String> params){ params.put("randomStr", StringTools.getRandom(32)); params.put("timestamp", System.currentTimeMillis()+""); String sign = null; try { sign = SignTools.createSign(params, API_SIGN_KEY); } catch (NoSuchAlgorithmException e) { logger.error("生成sign失败",e.fillInStackTrace()); } params.put("sign",sign); String parStr = MapTools.toParamString(params); StringBuffer sb = new StringBuffer(); sb.append(url).append("?").append(parStr); return sb.toString(); } public static void main(String[] args) { SortedMap<String, String> params = new TreeMap(); params.put("id","1"); String result = getSignUrl("http://user.newoinfo.com/m/user/one",params); System.out.println("result = " + result); try { String data = HttpTools.get(result); System.out.println("data = " + data); } catch (IOException e) { e.printStackTrace(); } } }
UTF-8
Java
1,850
java
SignUtils.java
Java
[ { "context": "dMap;\nimport java.util.TreeMap;\n\n/**\n * Created by wxnacy on 16/8/22.\n */\npublic class SignUtils {\n prot", "end": 424, "score": 0.9996722340583801, "start": 418, "tag": "USERNAME", "value": "wxnacy" }, { "context": " protected static final String API_SIGN_KEY = \"a2dc8a390e92ab87678a5bf922fbd5dd\";\n static Logger logger = LoggerFactory.getLog", "end": 548, "score": 0.9996923208236694, "start": 516, "tag": "KEY", "value": "a2dc8a390e92ab87678a5bf922fbd5dd" } ]
null
[]
package net.easyjava.framework.utils; import net.easyjava.tools.http.HttpTools; import net.easyjava.tools.lang.MapTools; import net.easyjava.tools.lang.StringTools; import net.easyjava.tools.security.SignTools; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.security.NoSuchAlgorithmException; import java.util.SortedMap; import java.util.TreeMap; /** * Created by wxnacy on 16/8/22. */ public class SignUtils { protected static final String API_SIGN_KEY = "<KEY>"; static Logger logger = LoggerFactory.getLogger(SignUtils.class); /** * 获取加密地址 * @param url * @param params * @return */ public static final String getSignUrl(String url,SortedMap<String, String> params){ params.put("randomStr", StringTools.getRandom(32)); params.put("timestamp", System.currentTimeMillis()+""); String sign = null; try { sign = SignTools.createSign(params, API_SIGN_KEY); } catch (NoSuchAlgorithmException e) { logger.error("生成sign失败",e.fillInStackTrace()); } params.put("sign",sign); String parStr = MapTools.toParamString(params); StringBuffer sb = new StringBuffer(); sb.append(url).append("?").append(parStr); return sb.toString(); } public static void main(String[] args) { SortedMap<String, String> params = new TreeMap(); params.put("id","1"); String result = getSignUrl("http://user.newoinfo.com/m/user/one",params); System.out.println("result = " + result); try { String data = HttpTools.get(result); System.out.println("data = " + data); } catch (IOException e) { e.printStackTrace(); } } }
1,823
0.644809
0.630055
62
28.516129
23.806168
87
false
false
0
0
0
0
0
0
0.645161
false
false
3
5344df0cfc686edfdca9706fdb638f11e0e06785
28,458,453,337,992
66d3122f8f031d6e8b27e8ead7aa5ae0d7e33b45
/net/minecraft/world/dimension/Dimension.java
3cae7a21c047fbd3f7d36951a40a8dfb51996b56
[]
no_license
gurachan/minecraft1.14-dp
https://github.com/gurachan/minecraft1.14-dp
c10059787555028f87a4c8183ff74e6e1cfbf056
34daddc03be27d5a0ee2ab9bc8b1deb050277208
refs/heads/master
2022-01-07T01:43:52.836000
2019-05-08T17:18:13
2019-05-08T17:18:13
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package net.minecraft.world.dimension; import net.minecraft.util.math.Vec3d; import net.minecraft.world.chunk.ChunkPos; import net.minecraft.world.gen.chunk.ChunkGenerator; import net.minecraft.world.border.WorldBorder; import net.minecraft.world.level.LevelGeneratorType; import net.minecraft.util.math.BlockPos; import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; import javax.annotation.Nullable; import net.minecraft.util.math.MathHelper; import net.minecraft.world.World; public abstract class Dimension { public static final float[] MOON_PHASE_TO_SIZE; protected final World world; private final DimensionType type; protected boolean waterVaporizes; protected boolean isNether; protected final float[] lightLevelToBrightness; private final float[] backgroundColor; public Dimension(final World world, final DimensionType type) { this.lightLevelToBrightness = new float[16]; this.backgroundColor = new float[4]; this.world = world; this.type = type; this.initializeLightLevelToBrightness(); } protected void initializeLightLevelToBrightness() { final float float1 = 0.0f; for (int integer2 = 0; integer2 <= 15; ++integer2) { final float float2 = 1.0f - integer2 / 15.0f; this.lightLevelToBrightness[integer2] = (1.0f - float2) / (float2 * 3.0f + 1.0f) * 1.0f + 0.0f; } } public int getMoonPhase(final long time) { return (int)(time / 24000L % 8L + 8L) % 8; } @Nullable @Environment(EnvType.CLIENT) public float[] getBackgroundColor(final float skyAngle, final float tickDelta) { final float float3 = 0.4f; final float float4 = MathHelper.cos(skyAngle * 6.2831855f) - 0.0f; final float float5 = -0.0f; if (float4 >= -0.4f && float4 <= 0.4f) { final float float6 = (float4 + 0.0f) / 0.4f * 0.5f + 0.5f; float float7 = 1.0f - (1.0f - MathHelper.sin(float6 * 3.1415927f)) * 0.99f; float7 *= float7; this.backgroundColor[0] = float6 * 0.3f + 0.7f; this.backgroundColor[1] = float6 * float6 * 0.7f + 0.2f; this.backgroundColor[2] = float6 * float6 * 0.0f + 0.2f; this.backgroundColor[3] = float7; return this.backgroundColor; } return null; } @Environment(EnvType.CLIENT) public float getCloudHeight() { return 128.0f; } @Environment(EnvType.CLIENT) public boolean c() { return true; } @Nullable public BlockPos getForcedSpawnPoint() { return null; } @Environment(EnvType.CLIENT) public double getHorizonShadingRatio() { if (this.world.getLevelProperties().getGeneratorType() == LevelGeneratorType.FLAT) { return 1.0; } return 0.03125; } public boolean doesWaterVaporize() { return this.waterVaporizes; } public boolean hasSkyLight() { return this.type.hasSkyLight(); } public boolean isNether() { return this.isNether; } public float[] getLightLevelToBrightness() { return this.lightLevelToBrightness; } public WorldBorder createWorldBorder() { return new WorldBorder(); } public void saveWorldData() { } public void update() { } public abstract ChunkGenerator<?> createChunkGenerator(); @Nullable public abstract BlockPos getSpawningBlockInChunk(final ChunkPos arg1, final boolean arg2); @Nullable public abstract BlockPos getTopSpawningBlockPosition(final int arg1, final int arg2, final boolean arg3); public abstract float getSkyAngle(final long arg1, final float arg2); public abstract boolean hasVisibleSky(); @Environment(EnvType.CLIENT) public abstract Vec3d getFogColor(final float arg1, final float arg2); public abstract boolean canPlayersSleep(); @Environment(EnvType.CLIENT) public abstract boolean shouldRenderFog(final int arg1, final int arg2); public abstract DimensionType getType(); static { MOON_PHASE_TO_SIZE = new float[] { 1.0f, 0.75f, 0.5f, 0.25f, 0.0f, 0.25f, 0.5f, 0.75f }; } }
UTF-8
Java
4,329
java
Dimension.java
Java
[]
null
[]
package net.minecraft.world.dimension; import net.minecraft.util.math.Vec3d; import net.minecraft.world.chunk.ChunkPos; import net.minecraft.world.gen.chunk.ChunkGenerator; import net.minecraft.world.border.WorldBorder; import net.minecraft.world.level.LevelGeneratorType; import net.minecraft.util.math.BlockPos; import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; import javax.annotation.Nullable; import net.minecraft.util.math.MathHelper; import net.minecraft.world.World; public abstract class Dimension { public static final float[] MOON_PHASE_TO_SIZE; protected final World world; private final DimensionType type; protected boolean waterVaporizes; protected boolean isNether; protected final float[] lightLevelToBrightness; private final float[] backgroundColor; public Dimension(final World world, final DimensionType type) { this.lightLevelToBrightness = new float[16]; this.backgroundColor = new float[4]; this.world = world; this.type = type; this.initializeLightLevelToBrightness(); } protected void initializeLightLevelToBrightness() { final float float1 = 0.0f; for (int integer2 = 0; integer2 <= 15; ++integer2) { final float float2 = 1.0f - integer2 / 15.0f; this.lightLevelToBrightness[integer2] = (1.0f - float2) / (float2 * 3.0f + 1.0f) * 1.0f + 0.0f; } } public int getMoonPhase(final long time) { return (int)(time / 24000L % 8L + 8L) % 8; } @Nullable @Environment(EnvType.CLIENT) public float[] getBackgroundColor(final float skyAngle, final float tickDelta) { final float float3 = 0.4f; final float float4 = MathHelper.cos(skyAngle * 6.2831855f) - 0.0f; final float float5 = -0.0f; if (float4 >= -0.4f && float4 <= 0.4f) { final float float6 = (float4 + 0.0f) / 0.4f * 0.5f + 0.5f; float float7 = 1.0f - (1.0f - MathHelper.sin(float6 * 3.1415927f)) * 0.99f; float7 *= float7; this.backgroundColor[0] = float6 * 0.3f + 0.7f; this.backgroundColor[1] = float6 * float6 * 0.7f + 0.2f; this.backgroundColor[2] = float6 * float6 * 0.0f + 0.2f; this.backgroundColor[3] = float7; return this.backgroundColor; } return null; } @Environment(EnvType.CLIENT) public float getCloudHeight() { return 128.0f; } @Environment(EnvType.CLIENT) public boolean c() { return true; } @Nullable public BlockPos getForcedSpawnPoint() { return null; } @Environment(EnvType.CLIENT) public double getHorizonShadingRatio() { if (this.world.getLevelProperties().getGeneratorType() == LevelGeneratorType.FLAT) { return 1.0; } return 0.03125; } public boolean doesWaterVaporize() { return this.waterVaporizes; } public boolean hasSkyLight() { return this.type.hasSkyLight(); } public boolean isNether() { return this.isNether; } public float[] getLightLevelToBrightness() { return this.lightLevelToBrightness; } public WorldBorder createWorldBorder() { return new WorldBorder(); } public void saveWorldData() { } public void update() { } public abstract ChunkGenerator<?> createChunkGenerator(); @Nullable public abstract BlockPos getSpawningBlockInChunk(final ChunkPos arg1, final boolean arg2); @Nullable public abstract BlockPos getTopSpawningBlockPosition(final int arg1, final int arg2, final boolean arg3); public abstract float getSkyAngle(final long arg1, final float arg2); public abstract boolean hasVisibleSky(); @Environment(EnvType.CLIENT) public abstract Vec3d getFogColor(final float arg1, final float arg2); public abstract boolean canPlayersSleep(); @Environment(EnvType.CLIENT) public abstract boolean shouldRenderFog(final int arg1, final int arg2); public abstract DimensionType getType(); static { MOON_PHASE_TO_SIZE = new float[] { 1.0f, 0.75f, 0.5f, 0.25f, 0.0f, 0.25f, 0.5f, 0.75f }; } }
4,329
0.641488
0.604759
138
30.369566
25.447893
109
false
false
0
0
0
0
0
0
0.557971
false
false
3
697fac8b0271c10f8dd25b357ac784a0dd6fb072
32,779,190,447,517
a0a0c1c73a0849b41695eeaff415069fc50ac599
/src/oop/B.java
aefe60516cb079d58c220b2c1c77cfe75e37646f
[]
no_license
mz-nibir/Java-Tutorial-Practise
https://github.com/mz-nibir/Java-Tutorial-Practise
633f3fbc931934be498ea013e1b9a1652407fea7
48aafa43a9375e7d69d5da2a805729339e31411b
refs/heads/master
2023-01-02T17:39:17.840000
2020-10-28T11:02:13
2020-10-28T11:02:13
305,773,938
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package oop; public class B extends A { void display() { System.out.println("B class"); } }
UTF-8
Java
108
java
B.java
Java
[]
null
[]
package oop; public class B extends A { void display() { System.out.println("B class"); } }
108
0.583333
0.583333
13
7.307693
10.556694
32
false
false
0
0
0
0
0
0
0.846154
false
false
3
9566c6cb6172fece9d79f8347d03827d138da062
33,260,226,775,921
4b0b6ad397df1645b10796db60cd83bb3edaffa0
/exam-web/src/main/java/com/he/exam/model/backoperator/SessionBagImpl.java
cdb77b732dae7aaf851520d53d0ecd4924c84a53
[]
no_license
ShawnLoveGame/git_workspace
https://github.com/ShawnLoveGame/git_workspace
68e3f78dc3e1951381c420eb2a9e9a46cf8ac31b
526ec5880e4afc39593fcc9d14f648c2f8c6a113
refs/heads/master
2020-04-26T21:48:46.905000
2018-06-21T07:25:07
2018-06-21T07:25:07
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.he.exam.model.backoperator; import com.he.exam.model.backoperator.vo.BackOperatorVO; /** * * Class Name : 存放登录信息 * * Description : 这里记述class说明<br> * * @see * */ public class SessionBagImpl { private BackOperatorVO backOperatorVO; public BackOperatorVO getBackOperatorVO() { return backOperatorVO; } public void setBackOperatorVO(BackOperatorVO backOperatorVO) { this.backOperatorVO = backOperatorVO; } }
UTF-8
Java
492
java
SessionBagImpl.java
Java
[]
null
[]
package com.he.exam.model.backoperator; import com.he.exam.model.backoperator.vo.BackOperatorVO; /** * * Class Name : 存放登录信息 * * Description : 这里记述class说明<br> * * @see * */ public class SessionBagImpl { private BackOperatorVO backOperatorVO; public BackOperatorVO getBackOperatorVO() { return backOperatorVO; } public void setBackOperatorVO(BackOperatorVO backOperatorVO) { this.backOperatorVO = backOperatorVO; } }
492
0.698718
0.698718
25
17.719999
20.551437
66
false
false
0
0
0
0
0
0
0.2
false
false
3
4f590fcd550463eec35c62dbd810b2b52277c109
15,023,795,640,505
e8b1d0741087c712bb25da2d2cecc15f0bc497b5
/src/Core/Subject/Time.java
eed53a5645c21e6d5affa884876f210d0dad1376
[]
no_license
louay-hesham/ScheduleGenerator
https://github.com/louay-hesham/ScheduleGenerator
4c6300fb86c788200034d61a4924cb1fe5111795
3537e75c91aff69f2eb8bec31a53fcdf2f1c5242
refs/heads/master
2021-01-11T08:41:27.855000
2017-02-07T13:09:57
2017-02-07T13:09:57
70,155,076
1
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package Core.Subject; /** * Created by louay on 1/30/2017. */ public class Time { public final int day, from, to, period; public final MeetingType type; public Time(int day, int from, int to, MeetingType type) { this.day = day; this.from = from; this.to = to; this.type = type; this.period = (this.to / 2) + 1; } public Time(int day, int period, MeetingType type) { this.period = period; this.day = day; this.type = type; this.to = (period * 2) - 1; switch (type) { case LAB_HALF: case TUT_HALF: case SEC_LECTURE: this.from = this.to; break; case LAB_FULL: case TUT_FULL: case LECTURE: default: this.from = this.to - 1; break; } } public Time(String str, MeetingType type) { String[] times = str.split(" "); this.day = Integer.decode(times[0]); this.from = Integer.decode(times[1]); this.to = Integer.decode(times[2]); this.period = (this.to / 2) + 1; switch (type) { case LECTURE: case SEC_LECTURE: case TUT_FULL: case TUT_HALF: case LAB_FULL: case LAB_HALF: { this.type = type; break; } case TUT_UNKNOWN: { if (this.from == this.to) { this.type = MeetingType.TUT_HALF; } else { this.type = MeetingType.TUT_FULL; } break; } case LAB_UNKNOWN: { if (this.from == this.to) { this.type = MeetingType.LAB_HALF; } else { this.type = MeetingType.LAB_FULL; } break; } default: this.type = MeetingType.LECTURE; break; } } @Override public boolean equals(Object obj) { return obj instanceof Time && ((Time) obj).day == this.day && ((Time) obj).from == this.from && ((Time) obj).to == this.to; } public String getTypeString() { switch (this.type) { case LECTURE: return "Lecture"; case SEC_LECTURE: return "Secondary Lecture"; case TUT_HALF: case TUT_FULL: return "Tutorial"; case LAB_HALF: case LAB_FULL: return "Lab"; default: return "Unknown"; } } public MeetingType getType() { return type; } public String toString() { StringBuilder sb = new StringBuilder(); sb.append(this.day + " " + this.from + " " + this.to + "\r\n"); return sb.toString(); } }
UTF-8
Java
2,954
java
Time.java
Java
[ { "context": "package Core.Subject;\n\n/**\n * Created by louay on 1/30/2017.\n */\n\npublic class Time {\n\n publi", "end": 46, "score": 0.9995250105857849, "start": 41, "tag": "USERNAME", "value": "louay" } ]
null
[]
package Core.Subject; /** * Created by louay on 1/30/2017. */ public class Time { public final int day, from, to, period; public final MeetingType type; public Time(int day, int from, int to, MeetingType type) { this.day = day; this.from = from; this.to = to; this.type = type; this.period = (this.to / 2) + 1; } public Time(int day, int period, MeetingType type) { this.period = period; this.day = day; this.type = type; this.to = (period * 2) - 1; switch (type) { case LAB_HALF: case TUT_HALF: case SEC_LECTURE: this.from = this.to; break; case LAB_FULL: case TUT_FULL: case LECTURE: default: this.from = this.to - 1; break; } } public Time(String str, MeetingType type) { String[] times = str.split(" "); this.day = Integer.decode(times[0]); this.from = Integer.decode(times[1]); this.to = Integer.decode(times[2]); this.period = (this.to / 2) + 1; switch (type) { case LECTURE: case SEC_LECTURE: case TUT_FULL: case TUT_HALF: case LAB_FULL: case LAB_HALF: { this.type = type; break; } case TUT_UNKNOWN: { if (this.from == this.to) { this.type = MeetingType.TUT_HALF; } else { this.type = MeetingType.TUT_FULL; } break; } case LAB_UNKNOWN: { if (this.from == this.to) { this.type = MeetingType.LAB_HALF; } else { this.type = MeetingType.LAB_FULL; } break; } default: this.type = MeetingType.LECTURE; break; } } @Override public boolean equals(Object obj) { return obj instanceof Time && ((Time) obj).day == this.day && ((Time) obj).from == this.from && ((Time) obj).to == this.to; } public String getTypeString() { switch (this.type) { case LECTURE: return "Lecture"; case SEC_LECTURE: return "Secondary Lecture"; case TUT_HALF: case TUT_FULL: return "Tutorial"; case LAB_HALF: case LAB_FULL: return "Lab"; default: return "Unknown"; } } public MeetingType getType() { return type; } public String toString() { StringBuilder sb = new StringBuilder(); sb.append(this.day + " " + this.from + " " + this.to + "\r\n"); return sb.toString(); } }
2,954
0.448206
0.442451
110
25.845455
18.509548
131
false
false
0
0
0
0
0
0
0.454545
false
false
3
b299e164bfb15b680bd164e90688d396ad7737cd
28,587,302,367,975
0d9c036373115dd3eb8bbee1b61bacb24fab7779
/riposte-spi/src/test/java/com/nike/riposte/server/config/distributedtracing/ProxyRouterSpanNamingAndTaggingStrategyTest.java
0075402d6fccbb23d0caacfcb2c4e92fbc716bce
[ "Apache-2.0" ]
permissive
123monkey/riposte
https://github.com/123monkey/riposte
2799c28c9e7ab75010ebcbe0cfb555c056f66c7c
454f52843b1bf36070754fe3a7bbe4603b7be904
refs/heads/master
2020-05-25T20:12:07.995000
2019-03-11T18:54:37
2019-03-11T18:54:37
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.nike.riposte.server.config.distributedtracing; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.junit.Test; import io.netty.handler.codec.http.HttpRequest; import io.netty.handler.codec.http.HttpResponse; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verifyZeroInteractions; /** * Tests the functionality of {@link ProxyRouterSpanNamingAndTaggingStrategy}. * * @author Nic Munroe */ public class ProxyRouterSpanNamingAndTaggingStrategyTest { @Test public void default_annotation_method_implementations_return_expected_values() { // given ProxyRouterSpanNamingAndTaggingStrategy<?> defaultImpl = new DefaultProxyRouterSpanNamingAndTaggingStrategy(); HttpResponse responseMock = mock(HttpResponse.class); Throwable errorMock = mock(Throwable.class); // expect assertThat(defaultImpl.shouldAddConnStartAnnotation()).isTrue(); assertThat(defaultImpl.connStartAnnotationName()).isEqualTo("conn.start"); assertThat(defaultImpl.shouldAddConnFinishAnnotation()).isTrue(); assertThat(defaultImpl.connFinishAnnotationName()).isEqualTo("conn.finish"); verifyZeroInteractions(responseMock, errorMock); } private static class DefaultProxyRouterSpanNamingAndTaggingStrategy<S> extends ProxyRouterSpanNamingAndTaggingStrategy<S> { @Override public @Nullable String doGetInitialSpanName(@NotNull HttpRequest request) { return null; } @Override public void doChangeSpanName(@NotNull S span, @NotNull String newName) { } @Override public void doHandleResponseTaggingAndFinalSpanName( @NotNull S span, @Nullable HttpRequest request, @Nullable HttpResponse response, @Nullable Throwable error ) { } @Override public void doHandleRequestTagging(@NotNull S span, @NotNull HttpRequest request) { } } }
UTF-8
Java
2,047
java
ProxyRouterSpanNamingAndTaggingStrategyTest.java
Java
[ { "context": "RouterSpanNamingAndTaggingStrategy}.\n *\n * @author Nic Munroe\n */\npublic class ProxyRouterSpanNamingAndTaggingS", "end": 531, "score": 0.9998744130134583, "start": 521, "tag": "NAME", "value": "Nic Munroe" } ]
null
[]
package com.nike.riposte.server.config.distributedtracing; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.junit.Test; import io.netty.handler.codec.http.HttpRequest; import io.netty.handler.codec.http.HttpResponse; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verifyZeroInteractions; /** * Tests the functionality of {@link ProxyRouterSpanNamingAndTaggingStrategy}. * * @author <NAME> */ public class ProxyRouterSpanNamingAndTaggingStrategyTest { @Test public void default_annotation_method_implementations_return_expected_values() { // given ProxyRouterSpanNamingAndTaggingStrategy<?> defaultImpl = new DefaultProxyRouterSpanNamingAndTaggingStrategy(); HttpResponse responseMock = mock(HttpResponse.class); Throwable errorMock = mock(Throwable.class); // expect assertThat(defaultImpl.shouldAddConnStartAnnotation()).isTrue(); assertThat(defaultImpl.connStartAnnotationName()).isEqualTo("conn.start"); assertThat(defaultImpl.shouldAddConnFinishAnnotation()).isTrue(); assertThat(defaultImpl.connFinishAnnotationName()).isEqualTo("conn.finish"); verifyZeroInteractions(responseMock, errorMock); } private static class DefaultProxyRouterSpanNamingAndTaggingStrategy<S> extends ProxyRouterSpanNamingAndTaggingStrategy<S> { @Override public @Nullable String doGetInitialSpanName(@NotNull HttpRequest request) { return null; } @Override public void doChangeSpanName(@NotNull S span, @NotNull String newName) { } @Override public void doHandleResponseTaggingAndFinalSpanName( @NotNull S span, @Nullable HttpRequest request, @Nullable HttpResponse response, @Nullable Throwable error ) { } @Override public void doHandleRequestTagging(@NotNull S span, @NotNull HttpRequest request) { } } }
2,043
0.741085
0.741085
55
36.236362
33.58894
118
false
false
0
0
0
0
0
0
0.436364
false
false
3