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
sequence
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
sequence
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
4f828753f9950b0991977f568f22ad59af3562c3
29,712,583,783,384
7df6a2c81f0682c43b83e33c4f6808fba1a57311
/spring-data-cassandra/src/test/java/org/springframework/data/cassandra/repository/query/ReactivePartTreeCassandraQueryUnitTests.java
b2315a709a0d545cc2ac4e4e1dafe90d99e14eb6
[ "Apache-2.0" ]
permissive
spring-projects/spring-data-cassandra
https://github.com/spring-projects/spring-data-cassandra
0f322956672fe0708fbcbeaa96abd632784c376b
746541447cb1d2a308bde2b12d65e937693a2f10
refs/heads/main
2023-08-31T03:26:47.928000
2023-08-29T11:36:24
2023-08-30T12:10:49
2,183,665
331
332
Apache-2.0
false
2023-07-12T07:24:45
2011-08-10T06:16:44
2023-06-25T02:11:37
2023-07-11T13:30:02
15,973
356
306
37
Java
false
false
/* * Copyright 2016-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.data.cassandra.repository.query; import static org.assertj.core.api.Assertions.*; import static org.mockito.Mockito.*; import io.reactivex.rxjava3.core.Single; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import java.lang.reflect.Method; import java.util.Arrays; import java.util.List; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.data.cassandra.core.ReactiveCassandraOperations; import org.springframework.data.cassandra.core.convert.MappingCassandraConverter; import org.springframework.data.cassandra.core.cql.QueryOptions; import org.springframework.data.cassandra.core.mapping.CassandraMappingContext; import org.springframework.data.cassandra.core.mapping.UserTypeResolver; import org.springframework.data.cassandra.domain.Person; import org.springframework.data.cassandra.repository.Consistency; import org.springframework.data.cassandra.repository.MapIdCassandraRepository; import org.springframework.data.cassandra.repository.Query; import org.springframework.data.projection.ProjectionFactory; import org.springframework.data.projection.SpelAwareProxyProjectionFactory; import org.springframework.data.repository.core.support.DefaultRepositoryMetadata; import org.springframework.util.ClassUtils; import com.datastax.oss.driver.api.core.DefaultConsistencyLevel; import com.datastax.oss.driver.api.core.cql.SimpleStatement; import com.datastax.oss.driver.api.core.type.codec.registry.CodecRegistry; /** * Unit tests for {@link ReactivePartTreeCassandraQuery}. * * @author Mark Paluch */ @ExtendWith(MockitoExtension.class) class ReactivePartTreeCassandraQueryUnitTests { @Mock ReactiveCassandraOperations mockCassandraOperations; @Mock UserTypeResolver userTypeResolver; private CassandraMappingContext mappingContext; @BeforeEach void setUp() { mappingContext = new CassandraMappingContext(); mappingContext.setUserTypeResolver(userTypeResolver); when(mockCassandraOperations.getConverter()).thenReturn(new MappingCassandraConverter(mappingContext)); } @Test // DATACASS-335 void shouldDeriveSimpleQuery() { String query = deriveQueryFromMethod("findByLastname", "foo"); assertThat(query).isEqualTo("SELECT * FROM person WHERE lastname='foo'"); } @Test // DATACASS-335 void shouldDeriveSimpleQueryWithoutNames() { String query = deriveQueryFromMethod("findPersonBy"); assertThat(query).isEqualTo("SELECT * FROM person"); } @Test // DATACASS-335 void shouldDeriveAndQuery() { String query = deriveQueryFromMethod("findByFirstnameAndLastname", "foo", "bar"); assertThat(query).isEqualTo("SELECT * FROM person WHERE firstname='foo' AND lastname='bar'"); } @Test // DATACASS-376 void shouldAllowFiltering() { String query = deriveQueryFromMethod("findPersonByFirstname", "foo"); assertThat(query).isEqualTo("SELECT * FROM person WHERE firstname='foo' ALLOW FILTERING"); } @Test // DATACASS-335, DATACASS-313 void usesDynamicProjection() { String query = deriveQueryFromMethod("findDynamicallyProjectedBy", PersonProjection.class); assertThat(query).isEqualTo("SELECT firstname,lastname FROM person"); } @Test // DATACASS-146 void shouldApplyQueryOptions() { QueryOptions queryOptions = QueryOptions.builder().pageSize(777).build(); SimpleStatement statement = deriveQueryFromMethod(Repo.class, "findByFirstname", new Class[] { QueryOptions.class, String.class }, queryOptions, "Walter"); assertThat(statement.getQuery()).isEqualTo("SELECT * FROM person WHERE firstname=?"); assertThat(statement.getPageSize()).isEqualTo(777); } @Test // DATACASS-146 void shouldApplyConsistencyLevel() { SimpleStatement statement = deriveQueryFromMethod(Repo.class, "findPersonBy", new Class[0]); assertThat(statement.getQuery()).isEqualTo("SELECT * FROM person"); assertThat(statement.getConsistencyLevel()).isEqualTo(DefaultConsistencyLevel.LOCAL_ONE); } @Test // DATACASS-512 void shouldCreateCountQuery() { SimpleStatement statement = deriveQueryFromMethod(PartTreeCassandraQueryUnitTests.Repo.class, "countBy", new Class[0]); assertThat(statement.getQuery()).isEqualTo("SELECT count(1) FROM person"); } @Test // DATACASS-611 void shouldCreateDeleteQuery() { SimpleStatement statement = deriveQueryFromMethod(PartTreeCassandraQueryUnitTests.Repo.class, "deleteAllByLastname", new Class[] { String.class }, "Walter"); assertThat(statement.getQuery()).isEqualTo("DELETE FROM person WHERE lastname=?"); } @Test // DATACASS-512, GH-1401 void shouldCreateExistsQuery() { SimpleStatement statement = deriveQueryFromMethod(PartTreeCassandraQueryUnitTests.Repo.class, "existsBy", new Class[0]); assertThat(statement.getQuery()).isEqualTo("SELECT * FROM person LIMIT ?"); } private String deriveQueryFromMethod(String method, Object... args) { Class<?>[] types = new Class<?>[args.length]; for (int i = 0; i < args.length; i++) { types[i] = ClassUtils.getUserClass(args[i].getClass()); } SimpleStatement statement = deriveQueryFromMethod(Repo.class, method, types, args); String query = statement.getQuery(); List<Object> positionalValues = statement.getPositionalValues(); for (Object positionalValue : positionalValues) { query = query.replaceFirst("\\?", positionalValue != null ? CodecRegistry.DEFAULT.codecFor((Class) positionalValue.getClass()).format(positionalValue) : "NULL"); } return query; } private SimpleStatement deriveQueryFromMethod(Class<?> repositoryInterface, String method, Class<?>[] types, Object... args) { ReactivePartTreeCassandraQuery partTreeQuery = createQueryForMethod(repositoryInterface, method, types); CassandraParameterAccessor accessor = new CassandraParametersParameterAccessor(partTreeQuery.getQueryMethod(), args); return partTreeQuery.createQuery(new ConvertingParameterAccessor(mockCassandraOperations.getConverter(), accessor)) .block(); } private ReactivePartTreeCassandraQuery createQueryForMethod(Class<?> repositoryInterface, String methodName, Class<?>... paramTypes) { Class<?>[] userTypes = Arrays.stream(paramTypes)// .map(it -> it.getName().contains("Mockito") ? it.getSuperclass() : it)// .toArray(size -> new Class<?>[size]); try { Method method = repositoryInterface.getMethod(methodName, userTypes); ProjectionFactory factory = new SpelAwareProxyProjectionFactory(); ReactiveCassandraQueryMethod queryMethod = new ReactiveCassandraQueryMethod(method, new DefaultRepositoryMetadata(repositoryInterface), factory, mappingContext); return new ReactivePartTreeCassandraQuery(queryMethod, mockCassandraOperations); } catch (NoSuchMethodException | SecurityException e) { throw new IllegalArgumentException(e.getMessage(), e); } } @SuppressWarnings("unused") interface Repo extends MapIdCassandraRepository<Person> { @Query() Flux<Person> findByLastname(String lastname); Flux<Person> findByFirstnameAndLastname(String firstname, String lastname); Flux<Person> findPersonByFirstnameAndLastname(String firstname, String lastname); Flux<Person> findByFirstname(QueryOptions queryOptions, String firstname); Mono<Long> countBy(); Mono<Boolean> deleteAllByLastname(String lastname); Mono<Boolean> existsBy(); @Consistency(DefaultConsistencyLevel.LOCAL_ONE) Flux<Person> findPersonBy(); @Query(allowFiltering = true) Flux<Person> findPersonByFirstname(String name); Mono<PersonProjection> findPersonProjectedBy(); <T> Single<T> findDynamicallyProjectedBy(Class<T> type); } private interface PersonProjection { String getFirstname(); String getLastname(); } }
UTF-8
Java
8,469
java
ReactivePartTreeCassandraQueryUnitTests.java
Java
[ { "context": "ink ReactivePartTreeCassandraQuery}.\n *\n * @author Mark Paluch\n */\n@ExtendWith(MockitoExtension.class)\nclass Rea", "end": 2363, "score": 0.9998413920402527, "start": 2352, "tag": "NAME", "value": "Mark Paluch" }, { "context": "ueryOptions.class, String.class }, queryOptions, \"Walter\");\n\n\t\tassertThat(statement.getQuery()).isEqualTo(", "end": 4241, "score": 0.9989171624183655, "start": 4235, "tag": "NAME", "value": "Walter" }, { "context": "llByLastname\",\n\t\t\t\tnew Class[] { String.class }, \"Walter\");\n\n\t\tassertThat(statement.getQuery()).isEqualTo(", "end": 5199, "score": 0.9989969730377197, "start": 5193, "tag": "NAME", "value": "Walter" } ]
null
[]
/* * Copyright 2016-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.data.cassandra.repository.query; import static org.assertj.core.api.Assertions.*; import static org.mockito.Mockito.*; import io.reactivex.rxjava3.core.Single; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import java.lang.reflect.Method; import java.util.Arrays; import java.util.List; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.data.cassandra.core.ReactiveCassandraOperations; import org.springframework.data.cassandra.core.convert.MappingCassandraConverter; import org.springframework.data.cassandra.core.cql.QueryOptions; import org.springframework.data.cassandra.core.mapping.CassandraMappingContext; import org.springframework.data.cassandra.core.mapping.UserTypeResolver; import org.springframework.data.cassandra.domain.Person; import org.springframework.data.cassandra.repository.Consistency; import org.springframework.data.cassandra.repository.MapIdCassandraRepository; import org.springframework.data.cassandra.repository.Query; import org.springframework.data.projection.ProjectionFactory; import org.springframework.data.projection.SpelAwareProxyProjectionFactory; import org.springframework.data.repository.core.support.DefaultRepositoryMetadata; import org.springframework.util.ClassUtils; import com.datastax.oss.driver.api.core.DefaultConsistencyLevel; import com.datastax.oss.driver.api.core.cql.SimpleStatement; import com.datastax.oss.driver.api.core.type.codec.registry.CodecRegistry; /** * Unit tests for {@link ReactivePartTreeCassandraQuery}. * * @author <NAME> */ @ExtendWith(MockitoExtension.class) class ReactivePartTreeCassandraQueryUnitTests { @Mock ReactiveCassandraOperations mockCassandraOperations; @Mock UserTypeResolver userTypeResolver; private CassandraMappingContext mappingContext; @BeforeEach void setUp() { mappingContext = new CassandraMappingContext(); mappingContext.setUserTypeResolver(userTypeResolver); when(mockCassandraOperations.getConverter()).thenReturn(new MappingCassandraConverter(mappingContext)); } @Test // DATACASS-335 void shouldDeriveSimpleQuery() { String query = deriveQueryFromMethod("findByLastname", "foo"); assertThat(query).isEqualTo("SELECT * FROM person WHERE lastname='foo'"); } @Test // DATACASS-335 void shouldDeriveSimpleQueryWithoutNames() { String query = deriveQueryFromMethod("findPersonBy"); assertThat(query).isEqualTo("SELECT * FROM person"); } @Test // DATACASS-335 void shouldDeriveAndQuery() { String query = deriveQueryFromMethod("findByFirstnameAndLastname", "foo", "bar"); assertThat(query).isEqualTo("SELECT * FROM person WHERE firstname='foo' AND lastname='bar'"); } @Test // DATACASS-376 void shouldAllowFiltering() { String query = deriveQueryFromMethod("findPersonByFirstname", "foo"); assertThat(query).isEqualTo("SELECT * FROM person WHERE firstname='foo' ALLOW FILTERING"); } @Test // DATACASS-335, DATACASS-313 void usesDynamicProjection() { String query = deriveQueryFromMethod("findDynamicallyProjectedBy", PersonProjection.class); assertThat(query).isEqualTo("SELECT firstname,lastname FROM person"); } @Test // DATACASS-146 void shouldApplyQueryOptions() { QueryOptions queryOptions = QueryOptions.builder().pageSize(777).build(); SimpleStatement statement = deriveQueryFromMethod(Repo.class, "findByFirstname", new Class[] { QueryOptions.class, String.class }, queryOptions, "Walter"); assertThat(statement.getQuery()).isEqualTo("SELECT * FROM person WHERE firstname=?"); assertThat(statement.getPageSize()).isEqualTo(777); } @Test // DATACASS-146 void shouldApplyConsistencyLevel() { SimpleStatement statement = deriveQueryFromMethod(Repo.class, "findPersonBy", new Class[0]); assertThat(statement.getQuery()).isEqualTo("SELECT * FROM person"); assertThat(statement.getConsistencyLevel()).isEqualTo(DefaultConsistencyLevel.LOCAL_ONE); } @Test // DATACASS-512 void shouldCreateCountQuery() { SimpleStatement statement = deriveQueryFromMethod(PartTreeCassandraQueryUnitTests.Repo.class, "countBy", new Class[0]); assertThat(statement.getQuery()).isEqualTo("SELECT count(1) FROM person"); } @Test // DATACASS-611 void shouldCreateDeleteQuery() { SimpleStatement statement = deriveQueryFromMethod(PartTreeCassandraQueryUnitTests.Repo.class, "deleteAllByLastname", new Class[] { String.class }, "Walter"); assertThat(statement.getQuery()).isEqualTo("DELETE FROM person WHERE lastname=?"); } @Test // DATACASS-512, GH-1401 void shouldCreateExistsQuery() { SimpleStatement statement = deriveQueryFromMethod(PartTreeCassandraQueryUnitTests.Repo.class, "existsBy", new Class[0]); assertThat(statement.getQuery()).isEqualTo("SELECT * FROM person LIMIT ?"); } private String deriveQueryFromMethod(String method, Object... args) { Class<?>[] types = new Class<?>[args.length]; for (int i = 0; i < args.length; i++) { types[i] = ClassUtils.getUserClass(args[i].getClass()); } SimpleStatement statement = deriveQueryFromMethod(Repo.class, method, types, args); String query = statement.getQuery(); List<Object> positionalValues = statement.getPositionalValues(); for (Object positionalValue : positionalValues) { query = query.replaceFirst("\\?", positionalValue != null ? CodecRegistry.DEFAULT.codecFor((Class) positionalValue.getClass()).format(positionalValue) : "NULL"); } return query; } private SimpleStatement deriveQueryFromMethod(Class<?> repositoryInterface, String method, Class<?>[] types, Object... args) { ReactivePartTreeCassandraQuery partTreeQuery = createQueryForMethod(repositoryInterface, method, types); CassandraParameterAccessor accessor = new CassandraParametersParameterAccessor(partTreeQuery.getQueryMethod(), args); return partTreeQuery.createQuery(new ConvertingParameterAccessor(mockCassandraOperations.getConverter(), accessor)) .block(); } private ReactivePartTreeCassandraQuery createQueryForMethod(Class<?> repositoryInterface, String methodName, Class<?>... paramTypes) { Class<?>[] userTypes = Arrays.stream(paramTypes)// .map(it -> it.getName().contains("Mockito") ? it.getSuperclass() : it)// .toArray(size -> new Class<?>[size]); try { Method method = repositoryInterface.getMethod(methodName, userTypes); ProjectionFactory factory = new SpelAwareProxyProjectionFactory(); ReactiveCassandraQueryMethod queryMethod = new ReactiveCassandraQueryMethod(method, new DefaultRepositoryMetadata(repositoryInterface), factory, mappingContext); return new ReactivePartTreeCassandraQuery(queryMethod, mockCassandraOperations); } catch (NoSuchMethodException | SecurityException e) { throw new IllegalArgumentException(e.getMessage(), e); } } @SuppressWarnings("unused") interface Repo extends MapIdCassandraRepository<Person> { @Query() Flux<Person> findByLastname(String lastname); Flux<Person> findByFirstnameAndLastname(String firstname, String lastname); Flux<Person> findPersonByFirstnameAndLastname(String firstname, String lastname); Flux<Person> findByFirstname(QueryOptions queryOptions, String firstname); Mono<Long> countBy(); Mono<Boolean> deleteAllByLastname(String lastname); Mono<Boolean> existsBy(); @Consistency(DefaultConsistencyLevel.LOCAL_ONE) Flux<Person> findPersonBy(); @Query(allowFiltering = true) Flux<Person> findPersonByFirstname(String name); Mono<PersonProjection> findPersonProjectedBy(); <T> Single<T> findDynamicallyProjectedBy(Class<T> type); } private interface PersonProjection { String getFirstname(); String getLastname(); } }
8,464
0.776125
0.768922
249
33.012047
33.2089
118
false
false
0
0
0
0
0
0
1.554217
false
false
2
10d842f00105802f33c9f1f92289f74390430921
7,868,380,124,244
b595f94aba6588ab42cdf1be8ccfbc41023e7791
/src/object/chapter02/src/main/java/org/eternity/movie/step02/DiscountCondition.java
2ae9590779b1a4b6e3ee0ed8b90596c53ef01e5c
[]
no_license
NickKies/Object
https://github.com/NickKies/Object
8e41eefd8f455dc567f06970c9a5f4bb7ad98ec9
73948678134cccfdc5e066227258b3b56a5680f7
refs/heads/master
2022-09-21T12:23:54.347000
2020-06-04T01:09:31
2020-06-04T01:09:31
259,182,242
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package object.chapter02.src.main.java.org.eternity.movie.step02; public interface DiscountCondition { boolean isSatisfiedBy(Screening screening); }
UTF-8
Java
155
java
DiscountCondition.java
Java
[]
null
[]
package object.chapter02.src.main.java.org.eternity.movie.step02; public interface DiscountCondition { boolean isSatisfiedBy(Screening screening); }
155
0.806452
0.780645
6
24.833334
25.919212
65
false
false
0
0
0
0
0
0
0.333333
false
false
2
8e6bb7733866e602c8dff273eda167056e9f73c2
16,690,242,948,079
495c7f9b43cd66b7a0ed41f08fd6a431d3cc1e79
/MyBatis从入门到精通--刘增辉/Mybatis-Annotation/src/main/java/com/moon/mybatis/mapper/SysRoleMapper2.java
158653fe98f40e598c9a8b2e2bf04013dc37d1ad
[]
no_license
dear-Alice-moon/MyBatis-Demo
https://github.com/dear-Alice-moon/MyBatis-Demo
c09a514601b9b93afbdf42f5d1162fde72a6d54d
8804c31a4a24b235e59286464363ba66067667ab
refs/heads/master
2022-11-18T06:27:31.222000
2021-05-22T08:25:07
2021-05-22T08:25:07
185,786,638
1
0
null
false
2022-11-16T12:25:53
2019-05-09T11:32:51
2021-05-22T08:25:32
2022-11-16T12:25:52
420
1
0
48
Java
false
false
package com.moon.mybatis.mapper; import org.apache.ibatis.annotations.Delete; import org.apache.ibatis.annotations.Insert; import org.apache.ibatis.annotations.Options; import org.apache.ibatis.annotations.Select; import org.apache.ibatis.annotations.SelectKey; import org.apache.ibatis.annotations.Update; import com.moon.mybatis.pojo.SysRole; /** * 基于注解开发, 主要测试'新增'功能. * 注解开发仅用于学习,不推荐在实际项目中运用. * * @author moon 2019/02/14 10:43 */ public interface SysRoleMapper2 { /** * 验证注解删除功能 * * @param id * @return * * @author moon 2019/02/14 16:14 */ @Delete({"DELETE FROM sys_role WHERE id = #{id}"}) Integer deleteRoleById(Long id); /** * 验证注解更新功能 * * @param sysRole * @return * * @author moon 2019/02/14 15:18 */ @Update({"UPDATE sys_role SET role_name = #{roleName}, enabled = #{enabled}, create_by = #{createBy}, create_time = #{createTime, jdbcType=TIMESTAMP}", "WHERE id = #{id}" }) Integer updateRoleById2(SysRole sysRole); /** * 验证注解更新功能 * * @param sysRole * @return * * @author moon 2019/02/14 15:18 */ @Update({"UPDATE sys_role", "SET role_name = #{roleName},", "enabled = #{enabled},", "create_by = #{createBy},", "create_time = #{createTime, jdbcType=TIMESTAMP}", "WHERE id = #{id}" }) Integer updateRoleById(SysRole sysRole); /** * 返回非自增主键 * 这里或许有些问题,当Mysql数据库中,主键不自增,则Eclipse控制台报错! @author moon 2019/02/14 15:16 * * @param sysRole * @return * * @author moon 2019/02/14 11:19 */ @Insert({"INSERT INTO sys_role(role_name, enabled, create_by, create_time)", "VALUES(#{roleName}, #{enabled}, #{createBy},", "#{createTime, jdbcType = TIMESTAMP})"}) @SelectKey(statement = "SELECT LAST_INSERT_ID()", keyProperty ="id", resultType = Long.class, before = false) Integer insertRole4(SysRole sysRole); // 这里,sql语句中无id字段,返回'非自增字段ID'值为:1004L /** * 返回非自增主键 * * @param sysRole * @return * * @author moon 2019/02/14 11:19 */ @Insert({"INSERT INTO sys_role(id, role_name, enabled, create_by, create_time)", "VALUES(#{id}, #{roleName}, #{enabled}, #{createBy},", "#{createTime, jdbcType = TIMESTAMP})"}) @SelectKey(statement = "SELECT LAST_INSERT_ID()", keyProperty ="id", resultType = Long.class, before = false) Integer insertRole3(SysRole sysRole); // 这里,sql语句中是否要添加id字段,返回'非自增字段ID'值为:0, 传递的SysRole中的id值为:1003L . /** * 返回自增主键 * * @param sysRole * @return * * @author moon 2019/02/14 11:04 */ @Insert({"INSERT INTO sys_role(role_name, enabled, create_by, create_time)", "VALUES(#{roleName}, #{enabled}, #{createBy},", "#{createTime, jdbcType=TIMESTAMP})"}) @Options(useGeneratedKeys=true, keyProperty="id") Integer insertRole2(SysRole sysRole); /** * 不需要返回主键 * * @param sysRole * @return * * @author moon 2019/02/14 10:35 */ @Insert({"INSERT INTO sys_role(id, role_name, enabled, create_by, create_time)", "VALUES(#{id}, #{roleName}, #{enabled}, #{createBy}, ", "#{createTime, jdbcType=TIMESTAMP})"}) Integer insertRole(SysRole sysRole); @Select({"SELECT id, role_name roleName, enabled, create_by createBy, create_time createTime", "FROM sys_role", "WHERE id=#{id}"}) SysRole selectById(Long id); }
UTF-8
Java
3,668
java
SysRoleMapper2.java
Java
[ { "context": "能.\n * 注解开发仅用于学习,不推荐在实际项目中运用. \n * \n * @author moon 2019/02/14 10:43 \n */\npublic interface Sys", "end": 427, "score": 0.9587681889533997, "start": 423, "tag": "USERNAME", "value": "moon" }, { "context": " \n\t * \n\t * @param id\n\t * @return\n\t * \n\t * @author moon 2019/02/14 16:14 \n\t */\n\t@Delete({\"DELETE FROM ", "end": 567, "score": 0.9467812776565552, "start": 563, "tag": "USERNAME", "value": "moon" }, { "context": "* \n\t * @param sysRole\n\t * @return\n\t * \n\t * @author moon 2019/02/14 15:18 \n\t */\n\t@Update({\"UPDATE sys_r", "end": 1091, "score": 0.7634822726249695, "start": 1087, "tag": "USERNAME", "value": "moon" }, { "context": "这里或许有些问题,当Mysql数据库中,主键不自增,则Eclipse控制台报错! @author moon 2019/02/14 15:16 \n\t * \n\t * @param sysRole\n\t *", "end": 1455, "score": 0.9582921862602234, "start": 1451, "tag": "USERNAME", "value": "moon" }, { "context": "* \n\t * @param sysRole\n\t * @return\n\t * \n\t * @author moon 2019/02/14 11:19 \n\t */\n\t@Insert({\"INSERT INTO s", "end": 1535, "score": 0.8969088196754456, "start": 1531, "tag": "USERNAME", "value": "moon" }, { "context": "* \n\t * @param sysRole\n\t * @return\n\t * \n\t * @author moon 2019/02/14 11:19 \n\t */\n\t@Insert({\"INSERT INTO s", "end": 2025, "score": 0.8465921878814697, "start": 2021, "tag": "USERNAME", "value": "moon" }, { "context": "* \n\t * @param sysRole\n\t * @return\n\t * \n\t * @author moon 2019/02/14 11:04\n\t */\n\t@Insert({\"INSERT INTO sy", "end": 2551, "score": 0.6837495565414429, "start": 2547, "tag": "USERNAME", "value": "moon" }, { "context": "* \n\t * @param sysRole\n\t * @return\n\t * \n\t * @author moon 2019/02/14 10:35 \n\t */\n\t@Insert({\"INSERT INTO ", "end": 2915, "score": 0.9949648976325989, "start": 2911, "tag": "USERNAME", "value": "moon" } ]
null
[]
package com.moon.mybatis.mapper; import org.apache.ibatis.annotations.Delete; import org.apache.ibatis.annotations.Insert; import org.apache.ibatis.annotations.Options; import org.apache.ibatis.annotations.Select; import org.apache.ibatis.annotations.SelectKey; import org.apache.ibatis.annotations.Update; import com.moon.mybatis.pojo.SysRole; /** * 基于注解开发, 主要测试'新增'功能. * 注解开发仅用于学习,不推荐在实际项目中运用. * * @author moon 2019/02/14 10:43 */ public interface SysRoleMapper2 { /** * 验证注解删除功能 * * @param id * @return * * @author moon 2019/02/14 16:14 */ @Delete({"DELETE FROM sys_role WHERE id = #{id}"}) Integer deleteRoleById(Long id); /** * 验证注解更新功能 * * @param sysRole * @return * * @author moon 2019/02/14 15:18 */ @Update({"UPDATE sys_role SET role_name = #{roleName}, enabled = #{enabled}, create_by = #{createBy}, create_time = #{createTime, jdbcType=TIMESTAMP}", "WHERE id = #{id}" }) Integer updateRoleById2(SysRole sysRole); /** * 验证注解更新功能 * * @param sysRole * @return * * @author moon 2019/02/14 15:18 */ @Update({"UPDATE sys_role", "SET role_name = #{roleName},", "enabled = #{enabled},", "create_by = #{createBy},", "create_time = #{createTime, jdbcType=TIMESTAMP}", "WHERE id = #{id}" }) Integer updateRoleById(SysRole sysRole); /** * 返回非自增主键 * 这里或许有些问题,当Mysql数据库中,主键不自增,则Eclipse控制台报错! @author moon 2019/02/14 15:16 * * @param sysRole * @return * * @author moon 2019/02/14 11:19 */ @Insert({"INSERT INTO sys_role(role_name, enabled, create_by, create_time)", "VALUES(#{roleName}, #{enabled}, #{createBy},", "#{createTime, jdbcType = TIMESTAMP})"}) @SelectKey(statement = "SELECT LAST_INSERT_ID()", keyProperty ="id", resultType = Long.class, before = false) Integer insertRole4(SysRole sysRole); // 这里,sql语句中无id字段,返回'非自增字段ID'值为:1004L /** * 返回非自增主键 * * @param sysRole * @return * * @author moon 2019/02/14 11:19 */ @Insert({"INSERT INTO sys_role(id, role_name, enabled, create_by, create_time)", "VALUES(#{id}, #{roleName}, #{enabled}, #{createBy},", "#{createTime, jdbcType = TIMESTAMP})"}) @SelectKey(statement = "SELECT LAST_INSERT_ID()", keyProperty ="id", resultType = Long.class, before = false) Integer insertRole3(SysRole sysRole); // 这里,sql语句中是否要添加id字段,返回'非自增字段ID'值为:0, 传递的SysRole中的id值为:1003L . /** * 返回自增主键 * * @param sysRole * @return * * @author moon 2019/02/14 11:04 */ @Insert({"INSERT INTO sys_role(role_name, enabled, create_by, create_time)", "VALUES(#{roleName}, #{enabled}, #{createBy},", "#{createTime, jdbcType=TIMESTAMP})"}) @Options(useGeneratedKeys=true, keyProperty="id") Integer insertRole2(SysRole sysRole); /** * 不需要返回主键 * * @param sysRole * @return * * @author moon 2019/02/14 10:35 */ @Insert({"INSERT INTO sys_role(id, role_name, enabled, create_by, create_time)", "VALUES(#{id}, #{roleName}, #{enabled}, #{createBy}, ", "#{createTime, jdbcType=TIMESTAMP})"}) Integer insertRole(SysRole sysRole); @Select({"SELECT id, role_name roleName, enabled, create_by createBy, create_time createTime", "FROM sys_role", "WHERE id=#{id}"}) SysRole selectById(Long id); }
3,668
0.627022
0.590473
136
23.544117
25.478037
153
false
false
0
0
0
0
0
0
1.823529
false
false
2
ee5e4cbe57574543897ad99fe9e081b56c224998
18,236,431,180,448
008ba2c87f73a66c67c9c8293a0e4db5e8e67f35
/src/main/java/in/zhaoj/eventbridge/util/ConsumerWebSocketSessionUtil.java
060ea3cc626304bcde5a6726596ee742f1b5ecde
[ "MIT" ]
permissive
glzjin/eventbridge-server
https://github.com/glzjin/eventbridge-server
b26db3c71fd9e0e25a128777e7a437af9fe102c5
9f83e5265ea2f9306e141781da3f6e9121bd45ba
refs/heads/master
2020-03-26T03:54:47.061000
2018-08-18T18:40:47
2018-08-18T18:40:47
144,476,619
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package in.zhaoj.eventbridge.util; import in.zhaoj.eventbridge.pojo.ConsumerSocketSessionWarehouse; import in.zhaoj.eventbridge.pojo.Event; import in.zhaoj.eventbridge.pojo.Response; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.web.socket.TextMessage; import org.springframework.web.socket.WebSocketSession; import java.io.IOException; /** * @author: jinzhao * @date:2018/8/19 * @description: */ @Component public class ConsumerWebSocketSessionUtil { @Autowired private ConsumerSocketSessionWarehouse consumerSocketSessionWarehouse; private final Logger logger = LoggerFactory.getLogger(ConsumerWebSocketSessionUtil.class); public void sendResponse(WebSocketSession webSocketSession, Response response) { try { webSocketSession.sendMessage(new TextMessage(JSONUtil.encode(response))); } catch (IOException e) { e.printStackTrace(); } } public void sendEvent(WebSocketSession webSocketSession, Event event) { Response response = new Response(Response.CODE_NEW_EVENT); response.setData("event", event); String consumerUUID = consumerSocketSessionWarehouse.getUUIDByWebSocket(webSocketSession); logger.info("推送事件请求:" + consumerUUID + " Event ID: " + event.getEvent_id()); this.sendResponse(webSocketSession, response); logger.info("推送事件请求:" + consumerUUID + " Event ID: " + event.getEvent_id() + " 成功!"); } }
UTF-8
Java
1,624
java
ConsumerWebSocketSessionUtil.java
Java
[ { "context": "ion;\n\nimport java.io.IOException;\n\n/**\n * @author: jinzhao\n * @date:2018/8/19\n * @description:\n */\n@Componen", "end": 513, "score": 0.9996370077133179, "start": 506, "tag": "USERNAME", "value": "jinzhao" } ]
null
[]
package in.zhaoj.eventbridge.util; import in.zhaoj.eventbridge.pojo.ConsumerSocketSessionWarehouse; import in.zhaoj.eventbridge.pojo.Event; import in.zhaoj.eventbridge.pojo.Response; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.web.socket.TextMessage; import org.springframework.web.socket.WebSocketSession; import java.io.IOException; /** * @author: jinzhao * @date:2018/8/19 * @description: */ @Component public class ConsumerWebSocketSessionUtil { @Autowired private ConsumerSocketSessionWarehouse consumerSocketSessionWarehouse; private final Logger logger = LoggerFactory.getLogger(ConsumerWebSocketSessionUtil.class); public void sendResponse(WebSocketSession webSocketSession, Response response) { try { webSocketSession.sendMessage(new TextMessage(JSONUtil.encode(response))); } catch (IOException e) { e.printStackTrace(); } } public void sendEvent(WebSocketSession webSocketSession, Event event) { Response response = new Response(Response.CODE_NEW_EVENT); response.setData("event", event); String consumerUUID = consumerSocketSessionWarehouse.getUUIDByWebSocket(webSocketSession); logger.info("推送事件请求:" + consumerUUID + " Event ID: " + event.getEvent_id()); this.sendResponse(webSocketSession, response); logger.info("推送事件请求:" + consumerUUID + " Event ID: " + event.getEvent_id() + " 成功!"); } }
1,624
0.740903
0.735257
46
33.652172
31.061102
98
false
false
0
0
0
0
0
0
0.543478
false
false
2
0d5d42600011c8d79ffedb108585c09610d5df86
31,086,973,288,601
c05b86eadd9535f9837658c5069256647d2d0a8a
/orm/mybatis/tk-mybatis/src/main/java/pers/Application.java
a4e33c8e967cc3eff74c9ac5659535841298e9ec
[]
no_license
luolanmeet/java-learn
https://github.com/luolanmeet/java-learn
035b24774b2f2a07611d07a08b16b1ee4a114f4c
5f3c95d8470d55e967319840fb7cc7c4a1709ab8
refs/heads/master
2023-08-17T14:03:43.854000
2023-08-15T03:51:04
2023-08-15T03:51:04
165,463,978
9
8
null
false
2022-12-21T15:36:35
2019-01-13T04:03:25
2022-01-07T07:51:04
2022-12-21T15:36:34
9,480
6
6
42
Java
false
false
package pers; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.ConfigurableApplicationContext; import pers.bean.User; import pers.mapper.IUserMapper; import tk.mybatis.mapper.entity.Example; import tk.mybatis.mapper.util.Sqls; import tk.mybatis.spring.annotation.MapperScan; import java.util.List; @MapperScan(basePackages = {"pers.mapper"}) @SpringBootApplication public class Application { public static void main(String[] args) { ConfigurableApplicationContext applicationContext = SpringApplication.run(Application.class, args); IUserMapper userMapper = applicationContext.getBean(IUserMapper.class); // 使用提供的api System.out.println(userMapper.selectByPrimaryKey(1)); // 自定义查询 Sqls sqls = Sqls.custom() .andEqualTo("userId", 1) .andEqualTo("name", "cck"); Example example = Example.builder(User.class).andWhere(sqls).build(); List<User> users = userMapper.selectByExample(example); System.out.println(users); } }
UTF-8
Java
1,161
java
Application.java
Java
[]
null
[]
package pers; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.ConfigurableApplicationContext; import pers.bean.User; import pers.mapper.IUserMapper; import tk.mybatis.mapper.entity.Example; import tk.mybatis.mapper.util.Sqls; import tk.mybatis.spring.annotation.MapperScan; import java.util.List; @MapperScan(basePackages = {"pers.mapper"}) @SpringBootApplication public class Application { public static void main(String[] args) { ConfigurableApplicationContext applicationContext = SpringApplication.run(Application.class, args); IUserMapper userMapper = applicationContext.getBean(IUserMapper.class); // 使用提供的api System.out.println(userMapper.selectByPrimaryKey(1)); // 自定义查询 Sqls sqls = Sqls.custom() .andEqualTo("userId", 1) .andEqualTo("name", "cck"); Example example = Example.builder(User.class).andWhere(sqls).build(); List<User> users = userMapper.selectByExample(example); System.out.println(users); } }
1,161
0.728308
0.726556
34
32.558823
27.203148
107
false
false
0
0
0
0
0
0
0.588235
false
false
2
39f5b00bffa8aeed74be93b2f450e4e6fcfe1f34
12,532,714,612,932
d66210ab3660270b3ff0a34cf2474600eda763d6
/src/main/java/Package_05/selenideUI.java
404827b53c20d2a8e3862a4d45e3503aed94b9a0
[]
no_license
dmitriyaux/Work_MyProject_02_Repo
https://github.com/dmitriyaux/Work_MyProject_02_Repo
1447bb7a0f2012f8f32812522583271b29893796
7fadc7e57cdbfd52b0935de0af700e7d6d716d55
refs/heads/master
2018-12-20T12:48:10.185000
2018-10-15T14:57:20
2018-10-15T14:57:20
114,082,543
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package Package_05; import com.codeborne.selenide.Configuration; //import selenideFNS440LoginPage; import org.testng.annotations.Test; import static com.codeborne.selenide.CollectionCondition.size; import static com.codeborne.selenide.Condition.text; import static com.codeborne.selenide.Selenide.open; public class selenideUI { @Test public void test1(){ // selenideFNS440LoginPage selenideFNS440LoginPage = new selenideFNS440LoginPage(); // selenideFNS440LoginPage.openPage(); Configuration.browser = "ie"; Configuration.startMaximized = true; selenideFNS440LoginPage loginPage = open("http://192.168.3.92:8083/fns-adapter-p440/", selenideFNS440LoginPage.class); selenideFNS440LoginPage resultsPage = loginPage.login( "fns_admin", "fns"); // GoogleSearchPage searchPage = open("/login", GoogleSearchPage.class); // GoogleSearchPage searchPage = open("https://www.google.ru/", GoogleSearchPage.class); // GoogleResultsPage resultsPage = searchPage.search("selenide"); // resultsPage.results().shouldHave(size(10)); // resultsPage.results().get(0).shouldHave(text("Selenide: Concise UI Tests in Java")); } }
UTF-8
Java
1,211
java
selenideUI.java
Java
[ { "context": " selenideFNS440LoginPage loginPage = open(\"http://192.168.3.92:8083/fns-adapter-p440/\", selenideFNS440LoginPage.", "end": 659, "score": 0.9996953010559082, "start": 647, "tag": "IP_ADDRESS", "value": "192.168.3.92" }, { "context": "NS440LoginPage resultsPage = loginPage.login( \"fns_admin\", \"fns\");\n\n// GoogleSearchPage searchPage ", "end": 790, "score": 0.6456562876701355, "start": 785, "tag": "USERNAME", "value": "admin" } ]
null
[]
package Package_05; import com.codeborne.selenide.Configuration; //import selenideFNS440LoginPage; import org.testng.annotations.Test; import static com.codeborne.selenide.CollectionCondition.size; import static com.codeborne.selenide.Condition.text; import static com.codeborne.selenide.Selenide.open; public class selenideUI { @Test public void test1(){ // selenideFNS440LoginPage selenideFNS440LoginPage = new selenideFNS440LoginPage(); // selenideFNS440LoginPage.openPage(); Configuration.browser = "ie"; Configuration.startMaximized = true; selenideFNS440LoginPage loginPage = open("http://192.168.3.92:8083/fns-adapter-p440/", selenideFNS440LoginPage.class); selenideFNS440LoginPage resultsPage = loginPage.login( "fns_admin", "fns"); // GoogleSearchPage searchPage = open("/login", GoogleSearchPage.class); // GoogleSearchPage searchPage = open("https://www.google.ru/", GoogleSearchPage.class); // GoogleResultsPage resultsPage = searchPage.search("selenide"); // resultsPage.results().shouldHave(size(10)); // resultsPage.results().get(0).shouldHave(text("Selenide: Concise UI Tests in Java")); } }
1,211
0.727498
0.689513
33
35.696968
35.379745
126
false
false
0
0
0
0
0
0
0.666667
false
false
2
a326048f78ac474229276e5c4958826231a79c16
15,272,903,740,556
a99cfb81ca9feab34ec674c4c0cfc7454dcf5288
/src/com/wxx/adapter/PaiHangAdapter.java
2169d04cc4c7dda5a51aa0e8de1cde51b6ca9ca5
[]
no_license
wuxinxi/MiaoZhiDao
https://github.com/wuxinxi/MiaoZhiDao
23978e58d9e9ff6b87a5d1affb1c9e7b1cd48b81
d6c5fa4623da2a0499453ae54fbf7420cb9c367c
refs/heads/master
2016-08-08T20:53:11.070000
2016-02-29T05:14:37
2016-02-29T05:14:37
52,754,896
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.wxx.adapter; import java.util.List; import java.util.Map; import com.wxx.main.R; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; public class PaiHangAdapter extends BaseAdapter { private List<Map<String, Object>> list; private Context context; private LayoutInflater inflater; public PaiHangAdapter(Context context, List<Map<String, Object>> list) { // TODO Auto-generated constructor stub this.context = context; this.list = list; inflater = inflater.from(context); } @Override public int getCount() { // TODO Auto-generated method stub return list.size(); } @Override public Object getItem(int position) { // TODO Auto-generated method stub return list.get(position); } @Override public long getItemId(int position) { // TODO Auto-generated method stub return position; } @Override public View getView(int position, View converView, ViewGroup parent) { // TODO Auto-generated method stub ViewHolder holder; if (converView == null) { holder = new ViewHolder(); converView = inflater.inflate(R.layout.items_paihang, null); holder.shunxun = (TextView) converView.findViewById(R.id.shunxu); holder.name = (TextView) converView.findViewById(R.id.account1); holder.count = (TextView) converView.findViewById(R.id.huidashu1); converView.setTag(holder); } else { holder = (ViewHolder) converView.getTag(); } holder.shunxun.setText(list.get(position).get("shunxu").toString()); holder.name.setText(list.get(position).get("account").toString()); holder.count.setText(list.get(position).get("count").toString()); return converView; } class ViewHolder { ImageView first, second, threa; TextView shunxun, name1, name2, name3, name, count1, count2, count3, count; } }
UTF-8
Java
1,944
java
PaiHangAdapter.java
Java
[]
null
[]
package com.wxx.adapter; import java.util.List; import java.util.Map; import com.wxx.main.R; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; public class PaiHangAdapter extends BaseAdapter { private List<Map<String, Object>> list; private Context context; private LayoutInflater inflater; public PaiHangAdapter(Context context, List<Map<String, Object>> list) { // TODO Auto-generated constructor stub this.context = context; this.list = list; inflater = inflater.from(context); } @Override public int getCount() { // TODO Auto-generated method stub return list.size(); } @Override public Object getItem(int position) { // TODO Auto-generated method stub return list.get(position); } @Override public long getItemId(int position) { // TODO Auto-generated method stub return position; } @Override public View getView(int position, View converView, ViewGroup parent) { // TODO Auto-generated method stub ViewHolder holder; if (converView == null) { holder = new ViewHolder(); converView = inflater.inflate(R.layout.items_paihang, null); holder.shunxun = (TextView) converView.findViewById(R.id.shunxu); holder.name = (TextView) converView.findViewById(R.id.account1); holder.count = (TextView) converView.findViewById(R.id.huidashu1); converView.setTag(holder); } else { holder = (ViewHolder) converView.getTag(); } holder.shunxun.setText(list.get(position).get("shunxu").toString()); holder.name.setText(list.get(position).get("account").toString()); holder.count.setText(list.get(position).get("count").toString()); return converView; } class ViewHolder { ImageView first, second, threa; TextView shunxun, name1, name2, name3, name, count1, count2, count3, count; } }
1,944
0.736111
0.731996
74
25.270269
22.026579
73
false
false
0
0
0
0
0
0
1.837838
false
false
2
da6b6b91eeabbd924e4755e5b5802247ab653d2f
29,712,583,790,559
fbd6a4aa5f7b34142a38ecdb5506eceef884e973
/src/interfaces/Pila.java
57b301ff7be86638eabb4fde81b9a9be0f27cb84
[]
no_license
marlonmartinez4/EjerciciosJava
https://github.com/marlonmartinez4/EjerciciosJava
f9dbeb2d002d375fcfcc65b4b750fbaac91da349
258f8badad62969c37f2fa03cb218f02c06a64c1
refs/heads/master
2020-05-07T20:47:07.399000
2019-04-11T21:05:52
2019-04-11T21:05:52
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package interfaces; import javax.swing.JOptionPane; public class Pila { private NodoPila ultimovaloringresado; int tamaño=0; String lista=""; public Pila(){ ultimovaloringresado=null; tamaño=0; } public boolean pilaVacia(){ return ultimovaloringresado==null; } public void insertarNodo(int nodo){ NodoPila nuevo_nodo=new NodoPila(nodo); nuevo_nodo.siguiente=ultimovaloringresado; ultimovaloringresado=nuevo_nodo; tamaño++; } public int eliminarNodo(){ int auxiliar=ultimovaloringresado.informacion; ultimovaloringresado=ultimovaloringresado.siguiente; tamaño--; return auxiliar; } public int mostrarUltimoValorIngresado(){ return ultimovaloringresado.informacion; } public int tamañoPila(){ return tamaño; } public void vaciarPila(){ while(!pilaVacia() ){ eliminarNodo(); } } public void mostrarValores(){ NodoPila recorrido=ultimovaloringresado; while(recorrido !=null){ lista +=recorrido.informacion + "\n"; recorrido=recorrido.siguiente; } JOptionPane.showMessageDialog(null, lista); lista=""; } }
UTF-8
Java
1,293
java
Pila.java
Java
[]
null
[]
package interfaces; import javax.swing.JOptionPane; public class Pila { private NodoPila ultimovaloringresado; int tamaño=0; String lista=""; public Pila(){ ultimovaloringresado=null; tamaño=0; } public boolean pilaVacia(){ return ultimovaloringresado==null; } public void insertarNodo(int nodo){ NodoPila nuevo_nodo=new NodoPila(nodo); nuevo_nodo.siguiente=ultimovaloringresado; ultimovaloringresado=nuevo_nodo; tamaño++; } public int eliminarNodo(){ int auxiliar=ultimovaloringresado.informacion; ultimovaloringresado=ultimovaloringresado.siguiente; tamaño--; return auxiliar; } public int mostrarUltimoValorIngresado(){ return ultimovaloringresado.informacion; } public int tamañoPila(){ return tamaño; } public void vaciarPila(){ while(!pilaVacia() ){ eliminarNodo(); } } public void mostrarValores(){ NodoPila recorrido=ultimovaloringresado; while(recorrido !=null){ lista +=recorrido.informacion + "\n"; recorrido=recorrido.siguiente; } JOptionPane.showMessageDialog(null, lista); lista=""; } }
1,293
0.620047
0.618493
51
24.215687
17.149075
60
false
false
0
0
0
0
0
0
0.490196
false
false
2
b45660d330d7f1282fd1c96e9fda3fdcc204994a
2,336,462,259,994
3bca769ae61e67207cff64202f6a0fd02a8ba7cf
/src/main/java/org/olat/finance/fee/ui/wizard/FCCopySingleCategoryStepController.java
12a7d709172326c85d4f43785a11b955008c6301
[]
no_license
manglatech/myStudy
https://github.com/manglatech/myStudy
0b3bc2febe3b131657f7ea95ab3d975285420e4c
9fa2c02dd17f0cbf4304c694e4e0a78608249c17
refs/heads/master
2020-06-04T07:39:12.336000
2013-02-23T17:58:02
2013-02-23T17:58:02
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.olat.finance.fee.ui.wizard; import java.util.ArrayList; import java.util.List; import org.olat.core.gui.UserRequest; import org.olat.core.gui.components.form.flexible.FormItemContainer; import org.olat.core.gui.components.form.flexible.impl.Form; import org.olat.core.gui.control.Controller; import org.olat.core.gui.control.WindowControl; import org.olat.core.gui.control.generic.wizard.StepFormBasicController; import org.olat.core.gui.control.generic.wizard.StepsEvent; import org.olat.core.gui.control.generic.wizard.StepsRunContext; import org.olat.finance.fee.model.FeeCategory; import org.olat.finance.fee.ui.FeeCategoryFormController; public class FCCopySingleCategoryStepController extends StepFormBasicController { private FeeCategory originalCategory; private FeeCategoryFormController feeFormController; public FCCopySingleCategoryStepController(UserRequest ureq, WindowControl wControl, Form rootForm, StepsRunContext runContext, FeeCategory originalCategory) { super(ureq, wControl, rootForm, runContext, LAYOUT_CUSTOM, "wrapper"); this.originalCategory = originalCategory; feeFormController = new FeeCategoryFormController(ureq, getWindowControl(), originalCategory, mainForm); listenTo(feeFormController); feeFormController.getFeeName().setValue(originalCategory.getName() + " " + translate("fccopywizard.copyform.name.copy")); initForm(ureq); } @Override protected void initForm(FormItemContainer formLayout, Controller listener, UserRequest ureq) { formLayout.add("wrapped", feeFormController.getInitialFormItem()); } @Override protected void doDispose() { // } @Override protected boolean validateFormLogic(UserRequest ureq) { return feeFormController.validateFormLogic(ureq); } @Override protected void formOK(UserRequest ureq) { @SuppressWarnings("unchecked") List<FCCopyFeeCategory> copies = (List<FCCopyFeeCategory>)getFromRunContext("categoryCopy"); if(copies == null) { copies = new ArrayList<FCCopyFeeCategory>(); addToRunContext("categoryCopy", copies); } FCCopyFeeCategory currentCopy = getWithOriginal(copies); if(currentCopy == null) { FCCopyFeeCategory feeCategory = new FCCopyFeeCategory(originalCategory); feeCategory.setName(feeFormController.getFeeName().getValue()); feeCategory.setDescription(feeFormController.getFeeDesc().getValue()); copies.add(feeCategory); } else { currentCopy.setName(feeFormController.getFeeName().getValue()); currentCopy.setDescription(feeFormController.getFeeDesc().getValue()); } fireEvent(ureq, StepsEvent.ACTIVATE_NEXT); } private FCCopyFeeCategory getWithOriginal(List<FCCopyFeeCategory> copies) { for(FCCopyFeeCategory copy:copies) { if(copy.getOriginal().equals(originalCategory)) { return copy; } } return null; } }
UTF-8
Java
2,825
java
FCCopySingleCategoryStepController.java
Java
[]
null
[]
package org.olat.finance.fee.ui.wizard; import java.util.ArrayList; import java.util.List; import org.olat.core.gui.UserRequest; import org.olat.core.gui.components.form.flexible.FormItemContainer; import org.olat.core.gui.components.form.flexible.impl.Form; import org.olat.core.gui.control.Controller; import org.olat.core.gui.control.WindowControl; import org.olat.core.gui.control.generic.wizard.StepFormBasicController; import org.olat.core.gui.control.generic.wizard.StepsEvent; import org.olat.core.gui.control.generic.wizard.StepsRunContext; import org.olat.finance.fee.model.FeeCategory; import org.olat.finance.fee.ui.FeeCategoryFormController; public class FCCopySingleCategoryStepController extends StepFormBasicController { private FeeCategory originalCategory; private FeeCategoryFormController feeFormController; public FCCopySingleCategoryStepController(UserRequest ureq, WindowControl wControl, Form rootForm, StepsRunContext runContext, FeeCategory originalCategory) { super(ureq, wControl, rootForm, runContext, LAYOUT_CUSTOM, "wrapper"); this.originalCategory = originalCategory; feeFormController = new FeeCategoryFormController(ureq, getWindowControl(), originalCategory, mainForm); listenTo(feeFormController); feeFormController.getFeeName().setValue(originalCategory.getName() + " " + translate("fccopywizard.copyform.name.copy")); initForm(ureq); } @Override protected void initForm(FormItemContainer formLayout, Controller listener, UserRequest ureq) { formLayout.add("wrapped", feeFormController.getInitialFormItem()); } @Override protected void doDispose() { // } @Override protected boolean validateFormLogic(UserRequest ureq) { return feeFormController.validateFormLogic(ureq); } @Override protected void formOK(UserRequest ureq) { @SuppressWarnings("unchecked") List<FCCopyFeeCategory> copies = (List<FCCopyFeeCategory>)getFromRunContext("categoryCopy"); if(copies == null) { copies = new ArrayList<FCCopyFeeCategory>(); addToRunContext("categoryCopy", copies); } FCCopyFeeCategory currentCopy = getWithOriginal(copies); if(currentCopy == null) { FCCopyFeeCategory feeCategory = new FCCopyFeeCategory(originalCategory); feeCategory.setName(feeFormController.getFeeName().getValue()); feeCategory.setDescription(feeFormController.getFeeDesc().getValue()); copies.add(feeCategory); } else { currentCopy.setName(feeFormController.getFeeName().getValue()); currentCopy.setDescription(feeFormController.getFeeDesc().getValue()); } fireEvent(ureq, StepsEvent.ACTIVATE_NEXT); } private FCCopyFeeCategory getWithOriginal(List<FCCopyFeeCategory> copies) { for(FCCopyFeeCategory copy:copies) { if(copy.getOriginal().equals(originalCategory)) { return copy; } } return null; } }
2,825
0.787257
0.787257
82
33.451218
32.177158
127
false
false
0
0
0
0
0
0
1.987805
false
false
2
8c3fe5ad72410801fea99806b4255b792f481284
25,812,753,466,399
efa2ac92aea13b38272da7bce1309d9d4c40b476
/Flight Managment Systems/src/com/uog/Airline/AirlineTest.java
1281fbeae1a9aa9fafc5a2250f80b8deca698d3c
[]
no_license
ChFaizan009/OOP-PROJECTS
https://github.com/ChFaizan009/OOP-PROJECTS
95f69f61d890c7934327e760534833d3f7222034
43bea5b4737110c93118a3264790f7be1cb2d61b
refs/heads/master
2023-08-07T03:01:07.870000
2021-09-23T06:53:22
2021-09-23T06:53:22
294,663,010
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.uog.Airline; public class AirlineTest { public static void main(String[] args) { Airline airline1 = new Airline("12", "Pakistan Airline"); airline1.setAIRLINE_ID("2"); airline1.setAIRLINE_NAME("Pakistan Airlines"); System.out.println(airline1); Airline airline2 = new Airline("M2", "Malasia Airlines"); System.out.println("\n"+airline2); System.out.println(airline2.getAIRLINE_ID()); System.out.println(airline2.getAIRLINE_NAME()); } }
UTF-8
Java
611
java
AirlineTest.java
Java
[]
null
[]
package com.uog.Airline; public class AirlineTest { public static void main(String[] args) { Airline airline1 = new Airline("12", "Pakistan Airline"); airline1.setAIRLINE_ID("2"); airline1.setAIRLINE_NAME("Pakistan Airlines"); System.out.println(airline1); Airline airline2 = new Airline("M2", "Malasia Airlines"); System.out.println("\n"+airline2); System.out.println(airline2.getAIRLINE_ID()); System.out.println(airline2.getAIRLINE_NAME()); } }
611
0.553191
0.533552
28
20.821428
21.791306
65
false
false
0
0
0
0
0
0
0.392857
false
false
2
537727a14272cfe57f3fb2176a9ea6ad5f0e3314
910,533,115,814
93173e5a0fda295b9936e5e7b92f4fe022295b78
/src/main/java/behavioral/visitor/oldway/Board.java
eb2b77eead726f213ef39185112f5ef492a6982e
[]
no_license
douniaHas/designPatternsJava
https://github.com/douniaHas/designPatternsJava
6abf208e3d112dae0b856fe78209911ec10ff581
2fcdb44f9a39e87abbf3d3a9d0d31d3958b20393
refs/heads/master
2022-07-02T13:09:20.294000
2020-04-22T16:11:20
2020-04-22T16:11:20
254,364,330
0
1
null
false
2022-06-21T03:16:56
2020-04-09T12:24:30
2020-04-22T16:11:27
2022-06-21T03:16:56
245
0
0
2
Java
false
false
package behavioral.visitor.oldway; public class Board extends Part { @Override long calculateShipping() { return 0; } }
UTF-8
Java
141
java
Board.java
Java
[]
null
[]
package behavioral.visitor.oldway; public class Board extends Part { @Override long calculateShipping() { return 0; } }
141
0.659574
0.652482
8
16.625
13.312941
34
false
false
0
0
0
0
0
0
0.25
false
false
2
485124b84f54b688941b49480fbff9af687efa06
5,231,270,214,825
6aef9dfd3d773c48f0b97c1ae213ff22eb569eb2
/herenciafigura/EjecutaFigura.java
480a1f3ce456f6117537f3c3ded9c12e4db57986
[]
no_license
andresvallejoz1991/poo2020
https://github.com/andresvallejoz1991/poo2020
14564f0f72522c355b357f12aeb87b2d4b3ea783
efff341b702f59b39879e1492a7a3731597a422e
refs/heads/master
2020-12-31T08:17:13.004000
2020-03-06T13:03:14
2020-03-06T13:03:14
238,947,485
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package intropoo.Disenopoo.herenciafigura; import java.util.Scanner; public class EjecutaFigura { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int opcion =0; while (opcion!=5){ System.out.println("-----------------------------"); System.out.println("|| Figuras||"); System.out.println("|1- Triangulo |"); System.out.println("|2- Cuadrado |"); System.out.println("|3- Rectangulo |"); System.out.println("|4- Circulo |"); System.out.println("|5- Salir |"); System.out.println("-----------------------------"); System.out.println("Ingrese la figura que desesa"); opcion = scan.nextInt(); scan.nextLine(); switch (opcion){ case 1: System.out.println("Ingrese nombre figura"); String nombre = scan.nextLine(); System.out.println("Ingrese base del Triangulo"); double base = scan.nextDouble(); System.out.println("Ingrese la altura del Triangulo"); double altura = scan.nextDouble(); Triangulo triangulo = new Triangulo(nombre,base,altura); System.out.println(triangulo.getNombre()); System.out.println("\nEl area del triangulo es:"+triangulo.calcularArea()); break; case 2: System.out.println("Ingrese nombre figura"); nombre = scan.nextLine(); System.out.println("Ingrese lado del Triangulo"); double lado = scan.nextDouble(); Cuadrado cuadrado = new Cuadrado(nombre,lado); System.out.println(cuadrado.getNombre()); System.out.println("\nEl area del cuadrado es:"+cuadrado.calcularArea()); break; case 3: System.out.println("Ingrese nombre figura"); nombre = scan.nextLine(); System.out.println("Ingrese lado del Rectangulo"); lado = scan.nextDouble(); System.out.println("Ingrese la altura del Rectangulo"); altura = scan.nextDouble(); Rectangulo rectangulo = new Rectangulo(nombre, lado, altura); System.out.println(rectangulo.getNombre()); System.out.println("\nEl area del cuadrado es:"+rectangulo.calcularArea()); break; case 4: System.out.println("Ingrese nombre figura"); nombre = scan.nextLine(); System.out.println("Ingrese radio de la figura"); double radio = scan.nextDouble(); Circulo circulo = new Circulo(nombre,radio); System.out.println(circulo.getNombre()); System.out.println("\nEl area del cuadrado es:"+circulo.calcularArea()); break; case 5: System.out.println("Salida del sistema"); break; default: System.out.println("Invalido"); break; } } } }
UTF-8
Java
3,478
java
EjecutaFigura.java
Java
[]
null
[]
package intropoo.Disenopoo.herenciafigura; import java.util.Scanner; public class EjecutaFigura { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int opcion =0; while (opcion!=5){ System.out.println("-----------------------------"); System.out.println("|| Figuras||"); System.out.println("|1- Triangulo |"); System.out.println("|2- Cuadrado |"); System.out.println("|3- Rectangulo |"); System.out.println("|4- Circulo |"); System.out.println("|5- Salir |"); System.out.println("-----------------------------"); System.out.println("Ingrese la figura que desesa"); opcion = scan.nextInt(); scan.nextLine(); switch (opcion){ case 1: System.out.println("Ingrese nombre figura"); String nombre = scan.nextLine(); System.out.println("Ingrese base del Triangulo"); double base = scan.nextDouble(); System.out.println("Ingrese la altura del Triangulo"); double altura = scan.nextDouble(); Triangulo triangulo = new Triangulo(nombre,base,altura); System.out.println(triangulo.getNombre()); System.out.println("\nEl area del triangulo es:"+triangulo.calcularArea()); break; case 2: System.out.println("Ingrese nombre figura"); nombre = scan.nextLine(); System.out.println("Ingrese lado del Triangulo"); double lado = scan.nextDouble(); Cuadrado cuadrado = new Cuadrado(nombre,lado); System.out.println(cuadrado.getNombre()); System.out.println("\nEl area del cuadrado es:"+cuadrado.calcularArea()); break; case 3: System.out.println("Ingrese nombre figura"); nombre = scan.nextLine(); System.out.println("Ingrese lado del Rectangulo"); lado = scan.nextDouble(); System.out.println("Ingrese la altura del Rectangulo"); altura = scan.nextDouble(); Rectangulo rectangulo = new Rectangulo(nombre, lado, altura); System.out.println(rectangulo.getNombre()); System.out.println("\nEl area del cuadrado es:"+rectangulo.calcularArea()); break; case 4: System.out.println("Ingrese nombre figura"); nombre = scan.nextLine(); System.out.println("Ingrese radio de la figura"); double radio = scan.nextDouble(); Circulo circulo = new Circulo(nombre,radio); System.out.println(circulo.getNombre()); System.out.println("\nEl area del cuadrado es:"+circulo.calcularArea()); break; case 5: System.out.println("Salida del sistema"); break; default: System.out.println("Invalido"); break; } } } }
3,478
0.479586
0.476136
77
43.168831
25.489189
95
false
false
0
0
0
0
0
0
0.974026
false
false
2
e4c87c7c98570a7a0561f2f1d551963fcb854f1a
16,088,947,542,503
a4515123a47a3f6e5d24783ec804c47dd6110045
/src/main/java/recursive/MagicIndex.java
2577418f398db06cf96789dec29d377ac30b8b9a
[]
no_license
sjw611/code-interview
https://github.com/sjw611/code-interview
afdf3a51c11d10783f533ea00ff23452d4a1465f
e0567bc633a40cfe88af30b7d907477022ab2793
refs/heads/master
2021-01-01T18:00:05.062000
2018-09-25T20:24:03
2018-09-30T20:29:24
98,219,209
0
0
null
false
2017-09-05T17:41:26
2017-07-24T17:56:07
2017-07-24T18:04:01
2017-09-05T17:41:25
95
0
0
0
Java
null
null
package recursive; import java.util.Objects; public class MagicIndex { private static final int NOT_FOUND = -1; public int find(int[] array) { Objects.requireNonNull(array); int low = 0; int high = array.length - 1; while (true) { if (low > high) { return NOT_FOUND; } int mid = low + ((high - low) >> 1); if (array[mid] == mid) { return mid; } else if (array[mid] > mid) { high = mid - 1; } else { low = mid + 1; } } } }
UTF-8
Java
509
java
MagicIndex.java
Java
[]
null
[]
package recursive; import java.util.Objects; public class MagicIndex { private static final int NOT_FOUND = -1; public int find(int[] array) { Objects.requireNonNull(array); int low = 0; int high = array.length - 1; while (true) { if (low > high) { return NOT_FOUND; } int mid = low + ((high - low) >> 1); if (array[mid] == mid) { return mid; } else if (array[mid] > mid) { high = mid - 1; } else { low = mid + 1; } } } }
509
0.526523
0.514735
30
14.966666
13.075379
41
false
false
0
0
0
0
0
0
2.033333
false
false
2
cbd52a02ceaf1a100ee291b97baeca27bc202351
25,013,889,542,659
6fa458d558029123b65c211b452fc75216525996
/day34_inheritance/Muhasebe.java
ef59d315011dd82f68a5a99e8db6b09094f365c1
[]
no_license
mmesutaksu/winter2021turkish
https://github.com/mmesutaksu/winter2021turkish
f58b09ffccc110c014bf6a0776ae779094dc067c
b8d85b89bbb0715440a37f4f726ab703193a590e
refs/heads/master
2023-04-06T15:45:07.522000
2021-04-17T11:59:41
2021-04-17T11:59:41
354,641,683
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package day34_inheritance; public class Muhasebe extends Personel{ // Muhasebe class'inin personel class'inin child class'i oldugunu // declare etmek icin class ismine extends keyword ile parent class'i yazariz public int saatÜcreti; public String statü; public int maas; public int maasHesapla() { maas=30*8*saatÜcreti; return maas; } }
ISO-8859-3
Java
366
java
Muhasebe.java
Java
[]
null
[]
package day34_inheritance; public class Muhasebe extends Personel{ // Muhasebe class'inin personel class'inin child class'i oldugunu // declare etmek icin class ismine extends keyword ile parent class'i yazariz public int saatÜcreti; public String statü; public int maas; public int maasHesapla() { maas=30*8*saatÜcreti; return maas; } }
366
0.741047
0.727273
18
19.166666
22.056116
78
false
false
0
0
0
0
0
0
1.388889
false
false
2
5cf8ad49239d06f6d049209a59a382ac346ed0b2
24,730,421,734,825
e27965ed683a1001aeb8caba11ee91309541b187
/org/johnnei/ld26/miniharvest/item/ItemCarrot.java
5911aeed5316c00a82976ad3ff3bef043ae15370
[]
no_license
Johnnei/LudumDare26
https://github.com/Johnnei/LudumDare26
0376ed3eff7ed8a3a2a849f3ba8abeaf299a5a9b
9270cf78781f1709698b19484ab352d92f80f983
refs/heads/master
2021-01-20T10:10:51.162000
2013-04-28T15:05:48
2013-04-28T15:05:48
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.johnnei.ld26.miniharvest.item; public class ItemCarrot extends Item { public static final int ID = 7; @Override public int getId() { return ID; } @Override public String getTextureName() { return "carrot"; } @Override public String getName() { return "Carrot"; } }
UTF-8
Java
300
java
ItemCarrot.java
Java
[]
null
[]
package org.johnnei.ld26.miniharvest.item; public class ItemCarrot extends Item { public static final int ID = 7; @Override public int getId() { return ID; } @Override public String getTextureName() { return "carrot"; } @Override public String getName() { return "Carrot"; } }
300
0.686667
0.676667
22
12.636364
13.5363
42
false
false
0
0
0
0
0
0
1
false
false
2
b5fd503953add93af71acffdd9953a46cfb94258
7,593,502,239,340
4c18ef55211126fc5a170ec6ff241968bb6112b8
/src/com/company/Game/PaneGame/MapGame/Map/MapNhaMay.java
7a2376058fc0945f4c2da7668627ad24c4600efd
[]
no_license
DatNguyen15399/Boom
https://github.com/DatNguyen15399/Boom
49f91244243229f042350c32da5af298df6f1ec7
73c23d9679aec2fc9e882e7d14d5974212e2fd2e
refs/heads/master
2021-07-16T01:56:11.269000
2020-09-14T04:32:59
2020-09-14T04:32:59
207,462,497
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.company.Game.PaneGame.MapGame.Map; import com.company.Game.PaneGame.MapGame.InputMap; import com.company.Game.PaneGame.MapGame.Map.MapNhaMayGame.*; import com.company.Game.PaneGame.MapGame.MapGame; import com.company.Library.libarary; import java.util.Random; public class MapNhaMay extends MapGame { public MapNhaMay() { InputMap.setMap("Mapnhamay.txt"); RandomVitri(); buildMap(); } @Override public void buildMap() { listMap.clear(); for (int y = 0; y < libarary.soHang; y += 3) { for (int x = 0; x < libarary.soCot; x += 3) { if (InputMap.Map[y][x] == libarary.Tuong) { listMap.add(new Tuong(x, y)); } else { listMap.add(new NenDichuyen(x, y)); } if (InputMap.Map[y][x] == libarary.Gach) { Random random = new Random(); AddItem_And_Door(x, y); int a = random.nextInt(90); if (a < 30) listMap.add(new Gach(x, y)); else if (a < 60) listMap.add(new Thung1(x, y)); else listMap.add(new Thung2(x, y)); } } } } }
UTF-8
Java
1,331
java
MapNhaMay.java
Java
[]
null
[]
package com.company.Game.PaneGame.MapGame.Map; import com.company.Game.PaneGame.MapGame.InputMap; import com.company.Game.PaneGame.MapGame.Map.MapNhaMayGame.*; import com.company.Game.PaneGame.MapGame.MapGame; import com.company.Library.libarary; import java.util.Random; public class MapNhaMay extends MapGame { public MapNhaMay() { InputMap.setMap("Mapnhamay.txt"); RandomVitri(); buildMap(); } @Override public void buildMap() { listMap.clear(); for (int y = 0; y < libarary.soHang; y += 3) { for (int x = 0; x < libarary.soCot; x += 3) { if (InputMap.Map[y][x] == libarary.Tuong) { listMap.add(new Tuong(x, y)); } else { listMap.add(new NenDichuyen(x, y)); } if (InputMap.Map[y][x] == libarary.Gach) { Random random = new Random(); AddItem_And_Door(x, y); int a = random.nextInt(90); if (a < 30) listMap.add(new Gach(x, y)); else if (a < 60) listMap.add(new Thung1(x, y)); else listMap.add(new Thung2(x, y)); } } } } }
1,331
0.486101
0.477085
41
31.463415
19.737419
61
false
false
0
0
0
0
0
0
0.682927
false
false
2
04e853bdf41166e663f73a6590dd5e002ba9e5ae
17,205,639,038,254
37d283086dbb46541aee2f3491925970146f0b8c
/src/anotherfour/FourTest.java
3b0fae831b55561d20950b2cf45a7fd61c5eafde
[]
no_license
yuanyuan123123/myrepositoryfour
https://github.com/yuanyuan123123/myrepositoryfour
1883ca1a6d97b787fc2a295c0bbf8951597dff7d
7e20bfeb9d1b04c1c0e1fb6382c1865bcc63609f
refs/heads/master
2021-06-24T18:23:28.576000
2021-01-14T13:08:16
2021-01-14T13:13:24
192,078,963
0
0
null
false
2021-01-14T08:15:51
2019-06-15T12:59:53
2021-01-14T08:12:35
2021-01-14T08:15:51
46
0
0
0
Java
false
false
package anotherfour; /** * @program: future-emr-edas-root * @description: * @author: suihaiying * @date: 2019/6/16 15:54 */ public class FourTest { public static void main(String args[]){ System.out.print("这是anotherfour包下的FourTest类的输出语句!"); int a=9; System.out.print(a); System.out.print(" mihao"); } }
UTF-8
Java
375
java
FourTest.java
Java
[ { "context": " future-emr-edas-root\n * @description:\n * @author: suihaiying\n * @date: 2019/6/16 15:54\n */\npublic class FourTe", "end": 99, "score": 0.979912281036377, "start": 89, "tag": "USERNAME", "value": "suihaiying" } ]
null
[]
package anotherfour; /** * @program: future-emr-edas-root * @description: * @author: suihaiying * @date: 2019/6/16 15:54 */ public class FourTest { public static void main(String args[]){ System.out.print("这是anotherfour包下的FourTest类的输出语句!"); int a=9; System.out.print(a); System.out.print(" mihao"); } }
375
0.615385
0.581197
18
18.5
16.634134
60
false
false
0
0
0
0
0
0
0.277778
false
false
2
95a49f9f5d5db93856e93ea671888be42301b66b
1,838,246,057,753
4ea1c43893200c86cc9dbaaa311ae052568e84fa
/src/exAula70/ex03/Aluno.java
8f01644fec57291a5f1429fdbc58c56ed1fd1aa7
[]
no_license
uluizeduardo/exerciciosJava
https://github.com/uluizeduardo/exerciciosJava
b0a97c1c133fa5d948de972cedf0135b0b519972
c1dcaa122ed1cb24f8bdb9c47cd41fbe28229614
refs/heads/main
2023-06-02T19:11:27.614000
2021-06-21T18:56:02
2021-06-21T18:56:02
373,830,547
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package exAula70.ex03; public class Aluno { //Variáveis public String nome; public double n1, n2, n3; //Método para verificar a média do aluno public double mediaDoAluno(){ return n1 + n2 + n3; } //Método para verificar se os pontos é maior que 60 public double pontosFaltando(){ if (mediaDoAluno() < 60){ return 60.0 - mediaDoAluno(); }else{ return 0.0; } } }
UTF-8
Java
463
java
Aluno.java
Java
[]
null
[]
package exAula70.ex03; public class Aluno { //Variáveis public String nome; public double n1, n2, n3; //Método para verificar a média do aluno public double mediaDoAluno(){ return n1 + n2 + n3; } //Método para verificar se os pontos é maior que 60 public double pontosFaltando(){ if (mediaDoAluno() < 60){ return 60.0 - mediaDoAluno(); }else{ return 0.0; } } }
463
0.569869
0.528384
23
18.913044
16.067556
55
false
false
0
0
0
0
0
0
0.347826
false
false
2
d645e56320d5691b4d85316712ad8b28545758a4
11,373,073,437,145
3b6facf13f48345e24d90b70ec401690c8bcdd8a
/src/main/java/com/javabull/ssm/blog/service/ICategoryService.java
43d0ad0a59db806c245c6c48597b3051763a957f
[]
no_license
JavaBull-dev/ssm-blog
https://github.com/JavaBull-dev/ssm-blog
27a16a38de45bee342dff51c71970fc22e8d0062
62f41dee7610231c32c341ef3c4a1931c83c5e00
refs/heads/master
2023-01-20T15:39:01.124000
2021-04-07T09:28:39
2021-04-07T09:28:39
317,801,799
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.javabull.ssm.blog.service; import com.javabull.ssm.blog.bean.Category; import com.javabull.ssm.blog.entity.CategoryParam; import java.util.List; public interface ICategoryService { /** * @return */ List<Category> getAll(); /** * @param categoryId */ void deleteOneCategory(Integer categoryId); /** * @param categoryId * @return */ Category getCategoryById(Integer categoryId); /** * @return */ List<CategoryParam> getAllCategoryCount(); /** * @param category * @return */ int updateOneCategory(Category category); /** * @param categoryName * @return */ boolean exist(String categoryName); /** * @param category * @return */ int saveCategory(Category category); /** * @param categoryId * @return */ boolean hasArticleAssocation(Integer categoryId); }
UTF-8
Java
941
java
ICategoryService.java
Java
[]
null
[]
package com.javabull.ssm.blog.service; import com.javabull.ssm.blog.bean.Category; import com.javabull.ssm.blog.entity.CategoryParam; import java.util.List; public interface ICategoryService { /** * @return */ List<Category> getAll(); /** * @param categoryId */ void deleteOneCategory(Integer categoryId); /** * @param categoryId * @return */ Category getCategoryById(Integer categoryId); /** * @return */ List<CategoryParam> getAllCategoryCount(); /** * @param category * @return */ int updateOneCategory(Category category); /** * @param categoryName * @return */ boolean exist(String categoryName); /** * @param category * @return */ int saveCategory(Category category); /** * @param categoryId * @return */ boolean hasArticleAssocation(Integer categoryId); }
941
0.5983
0.5983
53
16.754717
16.029343
53
false
false
0
0
0
0
0
0
0.226415
false
false
2
57a40dc452ff17b2c6e61757c10315aa5665d2da
11,733,850,710,924
3d5283dc5ae4a781b47bfd595625a58d034429a4
/src/main/java/com/example/demo/untils/DateUtils.java
3625c9638ab255124745a7156e68db8f2fe35678
[]
no_license
ZhangNR/demo
https://github.com/ZhangNR/demo
4f74fb0f2c10aa0b8455c3d1beb1c3f99c30ba17
e2d9aa71d64347f8ea020453f13d29151feafca7
refs/heads/master
2023-07-27T00:35:00.487000
2021-09-07T01:29:23
2021-09-07T01:29:23
175,363,325
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.demo.untils; import cn.hutool.core.date.DateTime; import cn.hutool.core.date.DateUtil; /** * DateUtils * * @author ZhangJP * @date 2020/9/23 */ public class DateUtils { public static void test() { DateTime yesterday = DateUtil.yesterday(); } }
UTF-8
Java
289
java
DateUtils.java
Java
[ { "context": "ore.date.DateUtil;\n\n/**\n * DateUtils\n *\n * @author ZhangJP\n * @date 2020/9/23\n */\npublic class DateUtils {\n\n", "end": 147, "score": 0.8042412400245667, "start": 140, "tag": "USERNAME", "value": "ZhangJP" } ]
null
[]
package com.example.demo.untils; import cn.hutool.core.date.DateTime; import cn.hutool.core.date.DateUtil; /** * DateUtils * * @author ZhangJP * @date 2020/9/23 */ public class DateUtils { public static void test() { DateTime yesterday = DateUtil.yesterday(); } }
289
0.67128
0.647059
18
15.055555
15.657701
50
false
false
0
0
0
0
0
0
0.222222
false
false
2
14b9e5cd4e8946cf5509d510644637c3ebbb2678
32,762,010,603,958
2a2c18588dda6f37f081ed06c7a3a89f4f9e5554
/DesignPatterns/src/main/java/org/meena/StrategyPattern/need_to_remember_strategy/move_strategy/DefensiveStrategy.java
06c3b417ca14c674d36a703ea435314b452a7c5b
[]
no_license
prash-kr-meena/00Design
https://github.com/prash-kr-meena/00Design
3566f594b499546cc25867da11302339b0131333
52a5ee4df090bd545de3b13d384e4b6cf4569ad6
refs/heads/master
2023-03-25T02:40:05.285000
2021-03-23T18:46:05
2021-03-23T18:46:05
338,622,699
4
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.meena.StrategyPattern.need_to_remember_strategy.move_strategy; public class DefensiveStrategy extends MoveStrategy { public DefensiveStrategy(String strategyName) { super(strategyName); } public void move(String name) { System.out.println(name + " Robot is : Moving " + this.strategyName); } }
UTF-8
Java
325
java
DefensiveStrategy.java
Java
[]
null
[]
package org.meena.StrategyPattern.need_to_remember_strategy.move_strategy; public class DefensiveStrategy extends MoveStrategy { public DefensiveStrategy(String strategyName) { super(strategyName); } public void move(String name) { System.out.println(name + " Robot is : Moving " + this.strategyName); } }
325
0.744615
0.744615
12
26.083334
28.188231
74
false
false
0
0
0
0
0
0
0.25
false
false
2
d87a3f2f358092255cf4b37177c42db464248023
10,934,986,745,584
784cb6a64cf42630017809960d39a003a938803d
/src/recursion/MagicIndexSol.java
c200d1d1bf956463e4e3891d27df4d96db511fd7
[]
no_license
earlywusa/coding_practice
https://github.com/earlywusa/coding_practice
5f3cc2b1950fe2aaa0149d18da4563dae0200550
aae99cca7556c67390b9d77d29d9b477882ed765
refs/heads/master
2020-04-06T04:20:54.378000
2017-11-26T23:40:05
2017-11-26T23:40:05
82,970,638
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package recursion; public class MagicIndexSol { public int findMagicIndex(int[] vals){ int magicIndex = -1; System.out.println("start"); System.out.println("binary search result: "+ binarySearch(vals, 0, vals.length-1)); return magicIndex; } public int binarySearch(int[] vals, int start, int end){ System.out.println("checking: start=" + start + " end="+ end); if(start <= end){ int mid = start + (end - start)/2; if(vals[mid] == mid){ System.out.println("mid matches:" + mid); return mid; } if(vals[mid] > mid){ System.out.println("mid val greater then mid index: val=" + vals[mid] + " index=" + mid ); return -1; } return binarySearch(vals, mid + 1, end ); } return -1; } }
UTF-8
Java
737
java
MagicIndexSol.java
Java
[]
null
[]
package recursion; public class MagicIndexSol { public int findMagicIndex(int[] vals){ int magicIndex = -1; System.out.println("start"); System.out.println("binary search result: "+ binarySearch(vals, 0, vals.length-1)); return magicIndex; } public int binarySearch(int[] vals, int start, int end){ System.out.println("checking: start=" + start + " end="+ end); if(start <= end){ int mid = start + (end - start)/2; if(vals[mid] == mid){ System.out.println("mid matches:" + mid); return mid; } if(vals[mid] > mid){ System.out.println("mid val greater then mid index: val=" + vals[mid] + " index=" + mid ); return -1; } return binarySearch(vals, mid + 1, end ); } return -1; } }
737
0.622795
0.613297
28
25.321428
24.843874
94
false
false
0
0
0
0
0
0
2.714286
false
false
2
4503307bea36f56b6deed46491408fdfbec12c69
14,018,773,302,163
e37975c76be7d39665f3486adbbcbd4e8dd5e5e7
/PCI_Project1/src/test/java/BackEnd_Test_Cases/TC_01_loginPage.java
35e39a8d9d471d3e8d19e791a1002cbe11aa4d84
[]
no_license
sumitkoli/Selenium
https://github.com/sumitkoli/Selenium
ebd6c7555f17f0d4230d29085ba5847764733193
6766fcacd8a8000980b40a5bdc57c0460801c959
refs/heads/master
2023-04-24T18:04:10.343000
2021-05-03T10:42:25
2021-05-03T10:42:25
320,668,583
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package BackEnd_Test_Cases; import org.openqa.selenium.support.PageFactory; import org.testng.Assert; import org.testng.annotations.Test; import BackEnd_PageObject.PO_01_loginPage; import Functions.BaseTest; public class TC_01_loginPage extends BaseTest { @Test public void loginValid() throws InterruptedException { PO_01_loginPage po_01_loginPage=PageFactory.initElements(driver, PO_01_loginPage.class); po_01_loginPage.enterUserId("admin@gmail.com"); po_01_loginPage.enterPassword("123456"); po_01_loginPage.clickSubmitButton(); Thread.sleep(3000); String expected =driver.getTitle(); String actual="PCI Admin"; Assert.assertEquals(actual, expected); } @Test public void loginINvalid() throws InterruptedException { PO_01_loginPage po_01_loginPage=PageFactory.initElements(driver, PO_01_loginPage.class); po_01_loginPage.enterUserId(""); po_01_loginPage.enterPassword(""); po_01_loginPage.clickSubmitButton(); Thread.sleep(3000); String expected =driver.getTitle(); String actual="PCI Admin"; Assert.assertNotEquals(actual, expected); } }
UTF-8
Java
1,099
java
TC_01_loginPage.java
Java
[ { "context": "_loginPage.class);\n\t\tpo_01_loginPage.enterUserId(\"admin@gmail.com\");\n\t\tpo_01_loginPage.enterPassword(\"123456\");\n\t\tp", "end": 463, "score": 0.9999076724052429, "start": 448, "tag": "EMAIL", "value": "admin@gmail.com" }, { "context": "min@gmail.com\");\n\t\tpo_01_loginPage.enterPassword(\"123456\");\n\t\tpo_01_loginPage.clickSubmitButton();\n\t\tThrea", "end": 506, "score": 0.9991934299468994, "start": 500, "tag": "PASSWORD", "value": "123456" } ]
null
[]
package BackEnd_Test_Cases; import org.openqa.selenium.support.PageFactory; import org.testng.Assert; import org.testng.annotations.Test; import BackEnd_PageObject.PO_01_loginPage; import Functions.BaseTest; public class TC_01_loginPage extends BaseTest { @Test public void loginValid() throws InterruptedException { PO_01_loginPage po_01_loginPage=PageFactory.initElements(driver, PO_01_loginPage.class); po_01_loginPage.enterUserId("<EMAIL>"); po_01_loginPage.enterPassword("<PASSWORD>"); po_01_loginPage.clickSubmitButton(); Thread.sleep(3000); String expected =driver.getTitle(); String actual="PCI Admin"; Assert.assertEquals(actual, expected); } @Test public void loginINvalid() throws InterruptedException { PO_01_loginPage po_01_loginPage=PageFactory.initElements(driver, PO_01_loginPage.class); po_01_loginPage.enterUserId(""); po_01_loginPage.enterPassword(""); po_01_loginPage.clickSubmitButton(); Thread.sleep(3000); String expected =driver.getTitle(); String actual="PCI Admin"; Assert.assertNotEquals(actual, expected); } }
1,095
0.757962
0.719745
40
26.475
23.512749
90
false
false
0
0
0
0
0
0
1.825
false
false
2
a9d86932190f99c2ffa0e0cb504d86b6d0e8db19
31,464,930,465,709
07bc25d01375fe9c59e848dc4dbe2bc489dc8771
/src/clases/Reserva.java
9562467b5d91dabc8fb2237ca18d0964ec6087c2
[]
no_license
mkhi26/ProyectoHotel
https://github.com/mkhi26/ProyectoHotel
3311dabe4f4be3389275477af04f12271b178e68
843cce014221ba8dd5509e7460bdd5666d20de17
refs/heads/master
2023-01-05T17:16:37.545000
2022-05-02T22:30:50
2022-05-02T22:30:50
287,658,969
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package clases; import java.util.Date; import utilitario.AdminFechas; import java.io.Serializable; import java.util.LinkedList; public class Reserva implements Serializable { private int idReserva; private String nombre, apellido, correo, telefono, numIdentidad; private Habitacion datosHabitacion; private Empleado datosEmpleadoEncargado; private int numHuesped; private Date fechaReserva; private Date fechaIngreso; private Date fechaEgreso; private double precioEstadia; final public double impustos = 0.13; public Reserva() { // TODO Auto-generated constructor stub } public int getIdReserva() { return idReserva; } public void setIdReserva(int idReserva) { this.idReserva = idReserva; } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public String getApellido() { return apellido; } public void setApellido(String apellido) { this.apellido = apellido; } public String getCorreo() { return correo; } public void setCorreo(String correo) { this.correo = correo; } public String getTelefono() { return telefono; } public void setTelefono(String telefono) { this.telefono = telefono; } public String getNumIdentidad() { return numIdentidad; } public void setNumIdentidad(String numIdentidad) { this.numIdentidad = numIdentidad; } public Habitacion getDatosHabitacion() { return datosHabitacion; } public void setDatosHabitacion(Habitacion datosHabitacion) { this.datosHabitacion = datosHabitacion; } public Empleado getDatosEmpleadoEncargado() { return datosEmpleadoEncargado; } public void setDatosEmpleadoEncargado(Empleado datosEmpleadoEncargado) { this.datosEmpleadoEncargado = datosEmpleadoEncargado; } public int getNumHuesped() { return numHuesped; } public void setNumHuesped(int numHuesped) { this.numHuesped = numHuesped; } public Date getFechaReserva() { return fechaReserva; } public void setFechaReserva(Date fechaReserva) { this.fechaReserva = fechaReserva; } public Date getFechaIngreso() { return fechaIngreso; } public void setFechaIngreso(Date fechaIngreso) { this.fechaIngreso = fechaIngreso; } public Date getFechaEgreso() { return fechaEgreso; } public void setFechaEgreso(Date fechaEgreso) { this.fechaEgreso = fechaEgreso; } public double getPrecioEstadia() { return precioEstadia; } public void setPrecioEstadia(double precioEstadia) { this.precioEstadia = precioEstadia; } }
UTF-8
Java
3,004
java
Reserva.java
Java
[]
null
[]
package clases; import java.util.Date; import utilitario.AdminFechas; import java.io.Serializable; import java.util.LinkedList; public class Reserva implements Serializable { private int idReserva; private String nombre, apellido, correo, telefono, numIdentidad; private Habitacion datosHabitacion; private Empleado datosEmpleadoEncargado; private int numHuesped; private Date fechaReserva; private Date fechaIngreso; private Date fechaEgreso; private double precioEstadia; final public double impustos = 0.13; public Reserva() { // TODO Auto-generated constructor stub } public int getIdReserva() { return idReserva; } public void setIdReserva(int idReserva) { this.idReserva = idReserva; } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public String getApellido() { return apellido; } public void setApellido(String apellido) { this.apellido = apellido; } public String getCorreo() { return correo; } public void setCorreo(String correo) { this.correo = correo; } public String getTelefono() { return telefono; } public void setTelefono(String telefono) { this.telefono = telefono; } public String getNumIdentidad() { return numIdentidad; } public void setNumIdentidad(String numIdentidad) { this.numIdentidad = numIdentidad; } public Habitacion getDatosHabitacion() { return datosHabitacion; } public void setDatosHabitacion(Habitacion datosHabitacion) { this.datosHabitacion = datosHabitacion; } public Empleado getDatosEmpleadoEncargado() { return datosEmpleadoEncargado; } public void setDatosEmpleadoEncargado(Empleado datosEmpleadoEncargado) { this.datosEmpleadoEncargado = datosEmpleadoEncargado; } public int getNumHuesped() { return numHuesped; } public void setNumHuesped(int numHuesped) { this.numHuesped = numHuesped; } public Date getFechaReserva() { return fechaReserva; } public void setFechaReserva(Date fechaReserva) { this.fechaReserva = fechaReserva; } public Date getFechaIngreso() { return fechaIngreso; } public void setFechaIngreso(Date fechaIngreso) { this.fechaIngreso = fechaIngreso; } public Date getFechaEgreso() { return fechaEgreso; } public void setFechaEgreso(Date fechaEgreso) { this.fechaEgreso = fechaEgreso; } public double getPrecioEstadia() { return precioEstadia; } public void setPrecioEstadia(double precioEstadia) { this.precioEstadia = precioEstadia; } }
3,004
0.631824
0.630826
132
20.757576
19.429407
76
false
false
0
0
0
0
0
0
0.340909
false
false
2
e8d936a16e04b04e8569299e2539431c0933b311
31,817,117,784,638
a41168fcbfd4d83a33011110878d6456a6096cc4
/Kiosker/src/main/java/dk/itu/kiosker/web/KioskerWebViewClient.java
f3addcf67a04313a7f4884e15f965803d79a151b
[]
no_license
zhaozw/Kiosker
https://github.com/zhaozw/Kiosker
c03c5323f55de3e730ef72cd82e32b1fb51f5957
6dce37036e5eab3512ebc292b743e78bc4b9d8b2
refs/heads/master
2021-01-24T02:23:32.025000
2014-06-24T11:21:21
2014-06-24T11:21:21
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package dk.itu.kiosker.web; import android.content.Context; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import android.util.Log; import android.webkit.WebView; import android.webkit.WebViewClient; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.concurrent.TimeUnit; import dk.itu.kiosker.activities.KioskerActivity; import dk.itu.kiosker.models.Constants; import dk.itu.kiosker.utils.SettingsExtractor; import rx.Observable; import rx.android.schedulers.AndroidSchedulers; import rx.functions.Action1; public class KioskerWebViewClient extends WebViewClient implements SensorEventListener { private final long errorReloadMins; private final KioskerActivity kioskerActivity; private final int lightSensorDelaySpeed; private final WebPage webPage; private final ArrayList<String> lightSensorReceivers; private boolean errorReloaderStarted; private boolean firstPageLoad; private SensorManager sensorManager; private WebView view; public KioskerWebViewClient(LinkedHashMap settings, KioskerActivity kioskerActivity, WebPage webPage) { this.errorReloadMins = SettingsExtractor.getInteger(settings, "errorReloadMins"); this.kioskerActivity = kioskerActivity; this.webPage = webPage; this.lightSensorReceivers = SettingsExtractor.getStringArrayList(settings, "lightSensorReceivers"); this.lightSensorDelaySpeed = SettingsExtractor.getInteger(settings, "lightSensorDelay"); this.sensorManager = (SensorManager) kioskerActivity.getSystemService(Context.SENSOR_SERVICE); // 0 - fastest, 1, 2, 3 - slowest (normal) } // you tell the web client you want to catch when a url is about to load @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { return false; } // here you execute an action when the URL you want is about to load @Override public void onLoadResource(WebView view, String url) { if (!url.startsWith("http")) { Log.d(Constants.TAG, "URL ERROR" + url); } } @Override public void onPageFinished(WebView view, String url) { super.onPageFinished(view, url); if (!firstPageLoad) { Constants.setString(kioskerActivity, url, Constants.KIOSKER_HOME_URL_ID); firstPageLoad = true; } // Only add the light sensor if this web page is one of the receivers. if (lightSensorReceivers.contains(webPage.title)) { int sensorDelay; switch (lightSensorDelaySpeed) { case 0: sensorDelay = SensorManager.SENSOR_DELAY_FASTEST; break; case 1: sensorDelay = SensorManager.SENSOR_DELAY_GAME; break; case 2: sensorDelay = SensorManager.SENSOR_DELAY_UI; break; case 3: sensorDelay = SensorManager.SENSOR_DELAY_NORMAL; break; default: sensorDelay = SensorManager.SENSOR_DELAY_NORMAL; } sensorManager.registerListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT), sensorDelay); } this.view = view; } @Override public void onReceivedError(final WebView view, int errorCode, final String description, String failingUrl) { final int webError = errorCode; if (errorReloadMins > 0 && !errorReloaderStarted) { errorReloaderStarted = true; Observable.timer(errorReloadMins, TimeUnit.MINUTES).observeOn(AndroidSchedulers.mainThread()).subscribe(new Action1<Long>() { @Override public void call(Long aLong) { errorReloaderStarted = false; if (webError == ERROR_HOST_LOOKUP) { Log.d(Constants.TAG, "Refreshing after error web error: " + description); kioskerActivity.refreshDevice(); } else if (Constants.isNetworkAvailable(kioskerActivity)) { Log.d(Constants.TAG, "Reloading after web error: " + description); view.reload(); } } }); } } @Override public void onSensorChanged(SensorEvent event) { if (event.sensor.getType() == Sensor.TYPE_LIGHT) { float lux = event.values[0]; // SI lux units (m/s^2), range 0.0 -> 32768.0 view.loadUrl("javascript:changeBackground()"); } } public void stopSensors() { // If this is a light sensor receiver, then unregister it before a page load if (lightSensorReceivers.contains(webPage.title)) sensorManager.unregisterListener(this); } @Override public void onAccuracyChanged(Sensor sensor, int i) { } }
UTF-8
Java
5,089
java
KioskerWebViewClient.java
Java
[]
null
[]
package dk.itu.kiosker.web; import android.content.Context; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import android.util.Log; import android.webkit.WebView; import android.webkit.WebViewClient; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.concurrent.TimeUnit; import dk.itu.kiosker.activities.KioskerActivity; import dk.itu.kiosker.models.Constants; import dk.itu.kiosker.utils.SettingsExtractor; import rx.Observable; import rx.android.schedulers.AndroidSchedulers; import rx.functions.Action1; public class KioskerWebViewClient extends WebViewClient implements SensorEventListener { private final long errorReloadMins; private final KioskerActivity kioskerActivity; private final int lightSensorDelaySpeed; private final WebPage webPage; private final ArrayList<String> lightSensorReceivers; private boolean errorReloaderStarted; private boolean firstPageLoad; private SensorManager sensorManager; private WebView view; public KioskerWebViewClient(LinkedHashMap settings, KioskerActivity kioskerActivity, WebPage webPage) { this.errorReloadMins = SettingsExtractor.getInteger(settings, "errorReloadMins"); this.kioskerActivity = kioskerActivity; this.webPage = webPage; this.lightSensorReceivers = SettingsExtractor.getStringArrayList(settings, "lightSensorReceivers"); this.lightSensorDelaySpeed = SettingsExtractor.getInteger(settings, "lightSensorDelay"); this.sensorManager = (SensorManager) kioskerActivity.getSystemService(Context.SENSOR_SERVICE); // 0 - fastest, 1, 2, 3 - slowest (normal) } // you tell the web client you want to catch when a url is about to load @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { return false; } // here you execute an action when the URL you want is about to load @Override public void onLoadResource(WebView view, String url) { if (!url.startsWith("http")) { Log.d(Constants.TAG, "URL ERROR" + url); } } @Override public void onPageFinished(WebView view, String url) { super.onPageFinished(view, url); if (!firstPageLoad) { Constants.setString(kioskerActivity, url, Constants.KIOSKER_HOME_URL_ID); firstPageLoad = true; } // Only add the light sensor if this web page is one of the receivers. if (lightSensorReceivers.contains(webPage.title)) { int sensorDelay; switch (lightSensorDelaySpeed) { case 0: sensorDelay = SensorManager.SENSOR_DELAY_FASTEST; break; case 1: sensorDelay = SensorManager.SENSOR_DELAY_GAME; break; case 2: sensorDelay = SensorManager.SENSOR_DELAY_UI; break; case 3: sensorDelay = SensorManager.SENSOR_DELAY_NORMAL; break; default: sensorDelay = SensorManager.SENSOR_DELAY_NORMAL; } sensorManager.registerListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT), sensorDelay); } this.view = view; } @Override public void onReceivedError(final WebView view, int errorCode, final String description, String failingUrl) { final int webError = errorCode; if (errorReloadMins > 0 && !errorReloaderStarted) { errorReloaderStarted = true; Observable.timer(errorReloadMins, TimeUnit.MINUTES).observeOn(AndroidSchedulers.mainThread()).subscribe(new Action1<Long>() { @Override public void call(Long aLong) { errorReloaderStarted = false; if (webError == ERROR_HOST_LOOKUP) { Log.d(Constants.TAG, "Refreshing after error web error: " + description); kioskerActivity.refreshDevice(); } else if (Constants.isNetworkAvailable(kioskerActivity)) { Log.d(Constants.TAG, "Reloading after web error: " + description); view.reload(); } } }); } } @Override public void onSensorChanged(SensorEvent event) { if (event.sensor.getType() == Sensor.TYPE_LIGHT) { float lux = event.values[0]; // SI lux units (m/s^2), range 0.0 -> 32768.0 view.loadUrl("javascript:changeBackground()"); } } public void stopSensors() { // If this is a light sensor receiver, then unregister it before a page load if (lightSensorReceivers.contains(webPage.title)) sensorManager.unregisterListener(this); } @Override public void onAccuracyChanged(Sensor sensor, int i) { } }
5,089
0.641776
0.63765
132
37.553032
30.456953
145
false
false
0
0
0
0
0
0
0.659091
false
false
2
61922756209ca1840df46f6976c79a3eabf35b60
31,207,232,421,735
35ca0d46d714bcb6b775ca933f610ada265eff6e
/app/src/main/java/com/example/hasee/baidutest/newtest/suzhou/model/SceneModel.java
3d98e707e48df1f99c35867fa6144986f4ee5f03
[]
no_license
jihymood/BaiduTest
https://github.com/jihymood/BaiduTest
d0b2630a2a04e9a15e03393758667fb4c889367d
cc911e652d344980194c74c0fb97b95165406d39
refs/heads/master
2020-06-20T04:20:43.126000
2017-10-16T08:07:59
2017-10-16T08:07:59
94,193,972
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.hasee.baidutest.newtest.suzhou.model; /** * * 图层场景 * Created by SUNKY on 16/10/19. */ public class SceneModel { private int state;//选中、未选中 private long addDate;//添加日期 private String name;//场景名称 private String idList;//场景列表 private String remark; private int sceneOrder;//场景顺序 private int isAddToSwitch;//是否添加到切换中 private int _id;//场景的序号 public int getState() { return state; } public void setState(int state) { this.state = state; } public long getAddDate() { return addDate; } public void setAddDate(long addDate) { this.addDate = addDate; } public String getIdList() { return idList; } public void setIdList(String idList) { this.idList = idList; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark; } public int getSceneOrder() { return sceneOrder; } public void setSceneOrder(int sceneOrder) { this.sceneOrder = sceneOrder; } public int getIsAddToSwitch() { return isAddToSwitch; } public void setIsAddToSwitch(int isAddToSwitch) { this.isAddToSwitch = isAddToSwitch; } public int get_id() { return _id; } public void set_id(int _id) { this._id = _id; } }
UTF-8
Java
1,626
java
SceneModel.java
Java
[ { "context": "ewtest.suzhou.model;\n\n/**\n *\n * 图层场景\n * Created by SUNKY on 16/10/19.\n */\npublic class SceneModel {\n\n p", "end": 93, "score": 0.9972884058952332, "start": 88, "tag": "USERNAME", "value": "SUNKY" } ]
null
[]
package com.example.hasee.baidutest.newtest.suzhou.model; /** * * 图层场景 * Created by SUNKY on 16/10/19. */ public class SceneModel { private int state;//选中、未选中 private long addDate;//添加日期 private String name;//场景名称 private String idList;//场景列表 private String remark; private int sceneOrder;//场景顺序 private int isAddToSwitch;//是否添加到切换中 private int _id;//场景的序号 public int getState() { return state; } public void setState(int state) { this.state = state; } public long getAddDate() { return addDate; } public void setAddDate(long addDate) { this.addDate = addDate; } public String getIdList() { return idList; } public void setIdList(String idList) { this.idList = idList; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark; } public int getSceneOrder() { return sceneOrder; } public void setSceneOrder(int sceneOrder) { this.sceneOrder = sceneOrder; } public int getIsAddToSwitch() { return isAddToSwitch; } public void setIsAddToSwitch(int isAddToSwitch) { this.isAddToSwitch = isAddToSwitch; } public int get_id() { return _id; } public void set_id(int _id) { this._id = _id; } }
1,626
0.591085
0.587209
89
16.393259
15.994815
57
false
false
0
0
0
0
0
0
0.280899
false
false
2
8c7443626a39e9926d6f15e7ace1093f17e4f47e
10,557,029,649,087
815be69e2bc3b74c0d826cf21b6c7ffc1b65522d
/server/slcp/front-api/src/main/java/com/zwp/slcp/frontapi/service/failCallBack/ActiveFailCallBack.java
37bba9de2e9f5b6b4b93b6e89661ddcbc24375f0
[]
no_license
simpleag/Student-Learning-Communication-Platform
https://github.com/simpleag/Student-Learning-Communication-Platform
9119ea677c95528e3479f83b949414dcfe3dbbc6
9e5679e3c9b8f54fafb69a33972d8711ce144b6c
refs/heads/master
2020-03-07T07:50:10.377000
2018-05-24T00:55:40
2018-05-24T00:55:40
127,360,006
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.zwp.slcp.frontapi.service.failCallBack; import com.zwp.slcp.apicommon.entity.Active; import com.zwp.slcp.frontapi.service.ActiveService; import org.bson.Document; import org.springframework.stereotype.Component; import java.util.List; /** * Created by ASUS on 2018/4/29. */ @Component public class ActiveFailCallBack implements ActiveService { @Override public void createActive(String collName, Long userId, Long targetId, Integer type, String activeContent) { } @Override public List<Document> listUsersActives(String collName, Long userId, Integer pageSize, Integer pageNumber) { return null; } }
UTF-8
Java
679
java
ActiveFailCallBack.java
Java
[ { "context": "t;\r\n\r\nimport java.util.List;\r\n\r\n/**\r\n * Created by ASUS on 2018/4/29.\r\n */\r\n@Component\r\npublic class Acti", "end": 282, "score": 0.9973344802856445, "start": 278, "tag": "USERNAME", "value": "ASUS" } ]
null
[]
package com.zwp.slcp.frontapi.service.failCallBack; import com.zwp.slcp.apicommon.entity.Active; import com.zwp.slcp.frontapi.service.ActiveService; import org.bson.Document; import org.springframework.stereotype.Component; import java.util.List; /** * Created by ASUS on 2018/4/29. */ @Component public class ActiveFailCallBack implements ActiveService { @Override public void createActive(String collName, Long userId, Long targetId, Integer type, String activeContent) { } @Override public List<Document> listUsersActives(String collName, Long userId, Integer pageSize, Integer pageNumber) { return null; } }
679
0.72754
0.717231
26
24.115385
31.372852
112
false
false
0
0
0
0
0
0
0.538462
false
false
2
c846b31308234f2e7f7396fb129597eada8baeea
5,488,968,273,856
b31410327674647849c341cc6d5745c37b44ea0f
/core-module/src/main/java/dcu/model/info/MarriageIranianSpouseInfo.java
521b488eeb690e9e1e9afdb17f305b4e5b94b363
[]
no_license
rayaPajohesh/IC
https://github.com/rayaPajohesh/IC
76f78a491078d2fa4d71ba6d6dc0af3a2267ebfd
53d66eb6ffc3ef188cd7ec7a81d751406aa2d198
refs/heads/master
2017-05-21T10:09:15.136000
2015-12-07T09:49:34
2015-12-07T09:52:03
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package dcu.model.info; public class MarriageIranianSpouseInfo implements java.io.Serializable { private Long personNin; private long marriageId; private String personName; private String personFname; private String dateOfBirthSun; private String shenasnameNo; private String shenasnameSeri; private String shenasnameSrno; private String shenasnameIssuePlace; private short hozehCode; private String hozehKind; private String sexCode; private String jobCode; private String educationCode; private String religionCode; private Long zipCode; private String addressGeoSerial; private Integer marriageTimes; private String address; public Long getPersonNin() { return personNin; } public void setPersonNin(Long val) { personNin = val; } public long getMarriageId() { return marriageId; } public void setMarriageId(long val) { marriageId = val; } public String getPersonName() { return personName; } public void setPersonName(String val) { this.personName = val; } public String getPersonFname() { return personFname; } public void setPersonFname(String val) { personFname = val; } public String getDateOfBirthSun() { return dateOfBirthSun; } public void setDateOfBirthSun(String val) { dateOfBirthSun = val; } public String getShenasnameNo() { return shenasnameNo; } public void setShenasnameNo(String val) { shenasnameNo = val; } public String getShenasnameSeri() { return shenasnameSeri; } public void setShenasnameSeri(String val) { shenasnameSeri = val; } public String getShenasnameSrno() { return shenasnameSrno; } public void setShenasnameSrno(String val) { shenasnameSrno = val; } public String getShenasnameIssuePlace() { return shenasnameIssuePlace; } public void setShenasnameIssuePlace(String val) { shenasnameIssuePlace = val; } public short getHozehCode() { return hozehCode; } public void setHozehCode(short val) { hozehCode = val; } public String getHozehKind() { return hozehKind; } public void setHozehKind(String val) { hozehKind = val; } public String getSexCode() { return sexCode; } public void setSexCode(String val) { sexCode = val; } public String getJobCode() { return jobCode; } public void setJobCode(String val) { jobCode = val; } public String getEducationCode() { return educationCode; } public void setEducationCode(String val) { educationCode = val; } public String getReligionCode() { return religionCode; } public void setReligionCode(String val) { religionCode = val; } public Long getZipCode() { return zipCode; } public void setZipCode(Long val) { zipCode = val; } public String getAddressGeoSerial() { return addressGeoSerial; } public void setAddressGeoSerial(String val) { addressGeoSerial = val; } public Integer getMarriageTimes() { return marriageTimes; } public void setMarriageTimes(Integer val) { // if(val == null || val == 0) // marriageTimes = null; // else marriageTimes = val; } public String getAddress() { return address; } public void setAddress(String val) { address = val; } }
UTF-8
Java
3,336
java
MarriageIranianSpouseInfo.java
Java
[]
null
[]
package dcu.model.info; public class MarriageIranianSpouseInfo implements java.io.Serializable { private Long personNin; private long marriageId; private String personName; private String personFname; private String dateOfBirthSun; private String shenasnameNo; private String shenasnameSeri; private String shenasnameSrno; private String shenasnameIssuePlace; private short hozehCode; private String hozehKind; private String sexCode; private String jobCode; private String educationCode; private String religionCode; private Long zipCode; private String addressGeoSerial; private Integer marriageTimes; private String address; public Long getPersonNin() { return personNin; } public void setPersonNin(Long val) { personNin = val; } public long getMarriageId() { return marriageId; } public void setMarriageId(long val) { marriageId = val; } public String getPersonName() { return personName; } public void setPersonName(String val) { this.personName = val; } public String getPersonFname() { return personFname; } public void setPersonFname(String val) { personFname = val; } public String getDateOfBirthSun() { return dateOfBirthSun; } public void setDateOfBirthSun(String val) { dateOfBirthSun = val; } public String getShenasnameNo() { return shenasnameNo; } public void setShenasnameNo(String val) { shenasnameNo = val; } public String getShenasnameSeri() { return shenasnameSeri; } public void setShenasnameSeri(String val) { shenasnameSeri = val; } public String getShenasnameSrno() { return shenasnameSrno; } public void setShenasnameSrno(String val) { shenasnameSrno = val; } public String getShenasnameIssuePlace() { return shenasnameIssuePlace; } public void setShenasnameIssuePlace(String val) { shenasnameIssuePlace = val; } public short getHozehCode() { return hozehCode; } public void setHozehCode(short val) { hozehCode = val; } public String getHozehKind() { return hozehKind; } public void setHozehKind(String val) { hozehKind = val; } public String getSexCode() { return sexCode; } public void setSexCode(String val) { sexCode = val; } public String getJobCode() { return jobCode; } public void setJobCode(String val) { jobCode = val; } public String getEducationCode() { return educationCode; } public void setEducationCode(String val) { educationCode = val; } public String getReligionCode() { return religionCode; } public void setReligionCode(String val) { religionCode = val; } public Long getZipCode() { return zipCode; } public void setZipCode(Long val) { zipCode = val; } public String getAddressGeoSerial() { return addressGeoSerial; } public void setAddressGeoSerial(String val) { addressGeoSerial = val; } public Integer getMarriageTimes() { return marriageTimes; } public void setMarriageTimes(Integer val) { // if(val == null || val == 0) // marriageTimes = null; // else marriageTimes = val; } public String getAddress() { return address; } public void setAddress(String val) { address = val; } }
3,336
0.68765
0.68735
178
17.741573
15.943389
72
false
false
0
0
0
0
0
0
0.342697
false
false
2
8b1e73ee91ac795b9fba353eb6cee6a7856bb2f6
9,715,216,082,521
aaa9081ef444ed64dbe9f3ca4ad4ea37de70d8c9
/src/test/java/cn/byhieg/threadtutorialtest/char01test/ExampleInterruptThreadTest.java
2dfb29ece566454d591c05e7e85d33dd7096f4a9
[ "MIT" ]
permissive
0717wangjianing/Project
https://github.com/0717wangjianing/Project
0247414900970fd9dd0e364a797112801d5679d5
59035d584c522bee7fb08f36b14bbb8c1f15fccc
refs/heads/master
2022-12-28T21:16:50.320000
2020-09-27T06:55:30
2020-09-27T06:55:30
256,717,030
0
0
MIT
false
2020-10-14T00:33:31
2020-04-18T09:42:48
2020-09-27T06:55:42
2020-10-14T00:33:30
488
0
0
1
Java
false
false
package cn.byhieg.threadtutorialtest.char01test; import cn.byhieg.threadtutorial.char01.ExampleInterruptThread; import junit.framework.TestCase; /** * Created by byhieg on 16/12/27. * Mail to byhieg@gmail.com */ public class ExampleInterruptThreadTest extends TestCase { public void testRun() throws Exception { ExampleInterruptThread thread = new ExampleInterruptThread(); thread.start(); Thread.sleep(1000); thread.interrupt(); } }
UTF-8
Java
479
java
ExampleInterruptThreadTest.java
Java
[ { "context": "mport junit.framework.TestCase;\n\n/**\n * Created by byhieg on 16/12/27.\n * Mail to byhieg@gmail.com\n */\npubl", "end": 171, "score": 0.9997156858444214, "start": 165, "tag": "USERNAME", "value": "byhieg" }, { "context": "\n\n/**\n * Created by byhieg on 16/12/27.\n * Mail to byhieg@gmail.com\n */\npublic class ExampleInterruptThreadTest exten", "end": 212, "score": 0.9999291896820068, "start": 196, "tag": "EMAIL", "value": "byhieg@gmail.com" } ]
null
[]
package cn.byhieg.threadtutorialtest.char01test; import cn.byhieg.threadtutorial.char01.ExampleInterruptThread; import junit.framework.TestCase; /** * Created by byhieg on 16/12/27. * Mail to <EMAIL> */ public class ExampleInterruptThreadTest extends TestCase { public void testRun() throws Exception { ExampleInterruptThread thread = new ExampleInterruptThread(); thread.start(); Thread.sleep(1000); thread.interrupt(); } }
470
0.726514
0.697286
18
25.666666
22.637236
69
false
false
0
0
0
0
0
0
0.388889
false
false
2
254581fc0f8711ac582c4e83ccdc51c7684f54c4
27,427,661,209,606
64a895809f44a85f03748bc2854307649849f408
/java/l2n/game/skills/skillclasses/PDam.java
03945486dba98e95aa864e2c57f5a07ad2afbf23
[]
no_license
NoobsDevelopers/L2Nextgen
https://github.com/NoobsDevelopers/L2Nextgen
ed764229a4191e7bd69078fc81668ee70f2ba6cf
1c562199f9a428c8e467a4154242190fbb8ef51c
refs/heads/master
2016-03-23T05:31:03.207000
2015-09-02T14:48:52
2015-09-02T14:48:52
41,800,903
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package l2n.game.skills.skillclasses; import l2n.commons.util.StatsSet; import l2n.game.model.L2Effect; import l2n.game.model.L2Skill; import l2n.game.model.actor.L2Character; import l2n.game.network.serverpackets.BeginRotation; import l2n.game.network.serverpackets.StopRotation; import l2n.game.network.serverpackets.SystemMessage; import l2n.game.skills.Env; import l2n.game.skills.Formulas; import l2n.game.skills.Formulas.AttackInfo; import l2n.game.skills.Stats; import l2n.util.Rnd; public class PDam extends L2Skill { private final boolean _onCrit; private final boolean _directHp; private final boolean _blow; private final int _turner; private final String _dispelType; private final int _cancelRate; private final int _negateCount; public PDam(final StatsSet set) { super(set); _onCrit = set.getBool("onCrit", false); _directHp = set.getBool("directHp", false); _blow = set.getBool("blow", false); _turner = set.getInteger("turner", 0); _dispelType = set.getString("dispelType", ""); _cancelRate = set.getInteger("cancelRate", 0); _negateCount = set.getInteger("negateCount", 5); } @Override public void useSkill(final L2Character activeChar, final L2Character... targets) { // Thread.dumpStack(); final boolean ss = activeChar.getChargedSoulShot() && isSSPossible(); if(ss) activeChar.unChargeShots(false); L2Character realTarget; boolean reflected; Env env; for(L2Character target : targets) if(target != null && !target.isDead()) { if(_cancelRate > 0) { env = new Env(); env.character = activeChar; env.target = target; env.skill = this; env.value = _cancelRate; if(Formulas.calcSkillSuccess(env, Stats.CANCEL_RECEPTIVE, Stats.CANCEL_POWER, activeChar.getChargedSpiritShot())) { int counter = 0; if(_dispelType.contains("negative")) for(final L2Effect e : target.getEffectList().getAllEffects()) if(counter < _negateCount && e.getSkill().isOffensive() && e.getSkill().isCancelable()) { e.exit(); counter++; } if(_dispelType.contains("positive")) for(final L2Effect e : target.getEffectList().getAllEffects()) { final L2Skill skill = e.getSkill(); if(counter < _negateCount && !skill.isOffensive() && skill.isCancelable()) { e.exit(); counter++; } } } } if(_turner > 0 && Rnd.chance(_turner) && !target.isInvul()) { target.broadcastPacket(new BeginRotation(target, target.getHeading(), 1, 65535)); target.broadcastPacket(new StopRotation(target, activeChar.getHeading(), 65535)); target.setHeading(activeChar.getHeading()); target.sendPacket(new SystemMessage(SystemMessage.YOU_CAN_FEEL_S1S_EFFECT).addSkillName(_displayId, _displayLevel)); } reflected = target.checkReflectSkill(activeChar, this); realTarget = reflected ? activeChar : target; AttackInfo info = Formulas.calcPhysDam(activeChar, realTarget, this, false, _blow, ss, _onCrit); if(info.lethal_dmg > 0) realTarget.reduceCurrentHp(info.lethal_dmg, activeChar, this, true, true, false, false, false); if(!info.miss || info.damage >= 1) realTarget.reduceCurrentHp(info.damage, activeChar, this, true, true, info.lethal ? false : _directHp, true, false); if(!reflected) Formulas.doCounterAttack(this, activeChar, realTarget, _blow); getEffects(activeChar, target, getActivateRate() > 0, false); } if(isSuicideAttack()) { activeChar.doDie(null); activeChar.onDecay(); } else if(isSSPossible()) activeChar.unChargeShots(isMagic()); } }
UTF-8
Java
3,659
java
PDam.java
Java
[]
null
[]
package l2n.game.skills.skillclasses; import l2n.commons.util.StatsSet; import l2n.game.model.L2Effect; import l2n.game.model.L2Skill; import l2n.game.model.actor.L2Character; import l2n.game.network.serverpackets.BeginRotation; import l2n.game.network.serverpackets.StopRotation; import l2n.game.network.serverpackets.SystemMessage; import l2n.game.skills.Env; import l2n.game.skills.Formulas; import l2n.game.skills.Formulas.AttackInfo; import l2n.game.skills.Stats; import l2n.util.Rnd; public class PDam extends L2Skill { private final boolean _onCrit; private final boolean _directHp; private final boolean _blow; private final int _turner; private final String _dispelType; private final int _cancelRate; private final int _negateCount; public PDam(final StatsSet set) { super(set); _onCrit = set.getBool("onCrit", false); _directHp = set.getBool("directHp", false); _blow = set.getBool("blow", false); _turner = set.getInteger("turner", 0); _dispelType = set.getString("dispelType", ""); _cancelRate = set.getInteger("cancelRate", 0); _negateCount = set.getInteger("negateCount", 5); } @Override public void useSkill(final L2Character activeChar, final L2Character... targets) { // Thread.dumpStack(); final boolean ss = activeChar.getChargedSoulShot() && isSSPossible(); if(ss) activeChar.unChargeShots(false); L2Character realTarget; boolean reflected; Env env; for(L2Character target : targets) if(target != null && !target.isDead()) { if(_cancelRate > 0) { env = new Env(); env.character = activeChar; env.target = target; env.skill = this; env.value = _cancelRate; if(Formulas.calcSkillSuccess(env, Stats.CANCEL_RECEPTIVE, Stats.CANCEL_POWER, activeChar.getChargedSpiritShot())) { int counter = 0; if(_dispelType.contains("negative")) for(final L2Effect e : target.getEffectList().getAllEffects()) if(counter < _negateCount && e.getSkill().isOffensive() && e.getSkill().isCancelable()) { e.exit(); counter++; } if(_dispelType.contains("positive")) for(final L2Effect e : target.getEffectList().getAllEffects()) { final L2Skill skill = e.getSkill(); if(counter < _negateCount && !skill.isOffensive() && skill.isCancelable()) { e.exit(); counter++; } } } } if(_turner > 0 && Rnd.chance(_turner) && !target.isInvul()) { target.broadcastPacket(new BeginRotation(target, target.getHeading(), 1, 65535)); target.broadcastPacket(new StopRotation(target, activeChar.getHeading(), 65535)); target.setHeading(activeChar.getHeading()); target.sendPacket(new SystemMessage(SystemMessage.YOU_CAN_FEEL_S1S_EFFECT).addSkillName(_displayId, _displayLevel)); } reflected = target.checkReflectSkill(activeChar, this); realTarget = reflected ? activeChar : target; AttackInfo info = Formulas.calcPhysDam(activeChar, realTarget, this, false, _blow, ss, _onCrit); if(info.lethal_dmg > 0) realTarget.reduceCurrentHp(info.lethal_dmg, activeChar, this, true, true, false, false, false); if(!info.miss || info.damage >= 1) realTarget.reduceCurrentHp(info.damage, activeChar, this, true, true, info.lethal ? false : _directHp, true, false); if(!reflected) Formulas.doCounterAttack(this, activeChar, realTarget, _blow); getEffects(activeChar, target, getActivateRate() > 0, false); } if(isSuicideAttack()) { activeChar.doDie(null); activeChar.onDecay(); } else if(isSSPossible()) activeChar.unChargeShots(isMagic()); } }
3,659
0.684887
0.672588
117
30.273504
28.404173
121
false
false
0
0
0
0
0
0
3.786325
false
false
2
9e4ee463f0786627ed853dd6a8422483c3b20102
13,829,794,757,533
aa97d233bd5ed372058985a2ebb9c5e1f674c34d
/repository/src/main/java/com/soonfor/repository/ui/activity/knowledge/AddKnowledgeActivity.java
032ca320c226eee1d3fc866783a64968f3480a21
[]
no_license
sf2018dyg/MeasureManger
https://github.com/sf2018dyg/MeasureManger
8e27eef12f2380de6a4fa6f5993fab00024b2e79
d57265ba9ba0a3db715dc657284b68ea8e27cd63
refs/heads/master
2020-04-14T02:09:45.598000
2018-12-30T10:00:29
2018-12-30T10:00:29
163,577,394
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.soonfor.repository.ui.activity.knowledge; import android.Manifest; import android.app.Dialog; import android.content.Intent; import android.content.pm.ActivityInfo; import android.graphics.Bitmap; import android.net.Uri; import android.support.annotation.NonNull; import android.text.Editable; import android.text.TextWatcher; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import com.dingyg.edittextwithclear.EditTextWithClear; import com.dingyg.richeditor.RichEditUtils; import com.dingyg.richeditor.RichTextEditor; import com.dingyg.richeditor.Tools; import com.dingyg.richeditor.utils.ImageUtils; import com.dingyg.richeditor.utils.MyGlideEngine; import com.dingyg.richeditor.utils.SDCardUtil; import com.dingyg.videocompressorr.VideoCompress; import com.github.dfqin.grantor.PermissionListener; import com.github.dfqin.grantor.PermissionsUtil; import com.orhanobut.hawk.Hawk; import com.soonfor.repository.R; import com.soonfor.repository.base.RepBaseActivity; import com.soonfor.repository.model.knowledge.CategoryBean; import com.soonfor.repository.presenter.knowledge.AddKnowledgePresenter; import com.soonfor.repository.tools.ComTools; import com.soonfor.repository.tools.DataTools; import com.soonfor.repository.tools.MyToast; import com.soonfor.repository.tools.Tokens; import com.soonfor.repository.tools.dialog.CustomDialog; import com.soonfor.repository.tools.popupwindow.SelectAddClassifyPopupWindow; import com.soonfor.repository.view.knowledge.IAddKnowledgeView; import com.zhihu.matisse.Matisse; import com.zhihu.matisse.MimeType; import com.zhihu.matisse.internal.entity.CaptureStrategy; import org.json.JSONException; import org.json.JSONObject; import java.io.File; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.List; import cn.jzvd.JZVideoPlayer; /** * 作者:DC-DingYG on 2018-07-31 8:40 * 邮箱:dingyg012655@126.com */ public class AddKnowledgeActivity extends RepBaseActivity<AddKnowledgePresenter> implements IAddKnowledgeView { private AddKnowledgeActivity mActivity; ImageView imgfOpen;//展示二级菜单 TextView tvfClassify; TextView tvfTitile; RelativeLayout rlfTablayout; EditTextWithClear llfEditTitle; EditText etfTilte; RichTextEditor editor;//图文混编器 ImageView imgfCover; ImageView imgfCamera, imgfPhoto, imgfAccessory; RelativeLayout rlfBottom; Button btfSend; private RichEditUtils richEditUtils; //private boolean isRichFocus = false;//光标焦点是否在内容编辑器上 private CategoryBean[] fcbs = new CategoryBean[2];//選中的一、二級菜單 public static final int REQUEST_CODE_CHOOSE = 23;//定义请求码常量 @Override protected int attachLayoutRes() { return R.layout.activity_addknowledge; } @Override protected void finishByBack() { super.finishByBack(); InFinish(); } @Override protected void updateViews(boolean isRefresh) { } private void findViewById() { imgfOpen = this.findViewById(R.id.imgfState); imgfOpen.setOnClickListener(listener); tvfClassify = this.findViewById(R.id.tvfClassify); tvfTitile = this.findViewById(R.id.tvfTitile); rlfTablayout = this.findViewById(R.id.rlfTablayout); rlfTablayout.setOnClickListener(listener); llfEditTitle = this.findViewById(R.id.ewfTitle); editor = this.findViewById(R.id.richEditor); imgfCover = this.findViewById(R.id.imgfCover); rlfBottom = this.findViewById(R.id.rlfBottom); imgfCamera = this.findViewById(R.id.imgfCamera); imgfCamera.setOnClickListener(listener); imgfPhoto = this.findViewById(R.id.imgfPhoto); imgfPhoto.setOnClickListener(listener); btfSend = this.findViewById(R.id.btfSave); btfSend.setOnClickListener(listener); if (RichTextEditor.framePics == null) { RichTextEditor.framePics = new HashMap<>(); } else if (RichTextEditor.framePics.size() > 0) { RichTextEditor.framePics.clear(); } } @Override protected AddKnowledgePresenter initPresenter() { findViewById(); actionName = "上传中..."; presenter = new AddKnowledgePresenter(this); mActivity = AddKnowledgeActivity.this; tvfTitile.setText("添加知识"); etfTilte = llfEditTitle.getEditText(); editor.setHint("内容"); etfTilte.setHint("标题"); etfTilte.requestFocus(); etfTilte.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void afterTextChanged(Editable s) { if (s.toString().trim().equals("")) { btfSend.setEnabled(false); } else if (etfTilte.getText().toString().trim().length() > 0 && fcbs != null && fcbs.length > 1 && fcbs[1] != null && !fcbs[1].getId().equals("")) { btfSend.setEnabled(true); } } }); return presenter; } @Override protected void initViews() { richEditUtils = RichEditUtils.getRichEditUtils(mActivity, editor); presenter.getTabTitles(mActivity, false); } @Override public void setGetCategory(boolean isSuccess, String msg) { if (isSuccess) { } else { showNoDataHint(msg); MyToast.showFailToast(mActivity, msg); } } @Override public void setAddKnowLedge(boolean isSuccess, String msg) { btfSend.setEnabled(true); if (isSuccess) { MyToast.showFailToast(mActivity, "已成功新增知识"); finish(); } else { showNoDataHint(msg); MyToast.showFailToast(mActivity, msg); } } SelectAddClassifyPopupWindow scPopupWindow; private View.OnClickListener listener = new View.OnClickListener() { @Override public void onClick(View v) { int i = v.getId(); if (i == R.id.rlfTablayout || i == R.id.imgfState) { if (DataTools.fTypes == null) { return; } if (scPopupWindow != null) { scPopupWindow.dismiss(); } scPopupWindow = new SelectAddClassifyPopupWindow(mActivity, fcbs, imgfCover, new SelectAddClassifyPopupWindow.refresh() { @Override public void refreshLayout(CategoryBean[] cbs) { fcbs = cbs; if (scPopupWindow != null) { scPopupWindow.dismiss(); } tvfClassify.setText(fcbs[1].getName()); if (!fcbs[1].getId().equals("")) { if (!etfTilte.getText().toString().trim().equals("")) ; btfSend.setEnabled(true); } } }); scPopupWindow.showPopupWindow(rlfTablayout, mActivity); } else if (i == R.id.btfSave) { if (fcbs[1] == null || fcbs[1].getId().equals("")) { MyToast.showToast(mActivity, "请选择要增加的知识类型"); return; } String title = etfTilte.getText().toString().trim(); if (title.equals("")) { MyToast.showToast(mActivity, "请填写标题"); return; } String content = richEditUtils.getEditData(); if (content.length() == 0) { MyToast.showToast(mActivity, "请填写内容"); return; } btfSend.setEnabled(false); presenter.addKonwledge(mActivity, fcbs[1].getId(), title, content, null); } else if (i == R.id.imgfCamera) { PermissionsUtil.requestPermission(mActivity, new PermissionListener() { @Override public void permissionGranted(@NonNull String[] permission) { Tools.closeSoftKeyInput(mActivity);//关闭软键盘 // if (isRichFocus) { // 打开相机 richEditUtils.openCamera(2); // } else { // MyToast.showToast(mActivity, "请先将光标聚焦内容编辑器"); // } } @Override public void permissionDenied(@NonNull String[] permission) { } }, Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE); } else if (i == R.id.imgfPhoto) { PermissionsUtil.requestPermission(mActivity, new PermissionListener() { @Override public void permissionGranted(@NonNull String[] permission) { // 打开系统相册 Tools.closeSoftKeyInput(mActivity);//关闭软键盘 // if (isRichFocus) { // 打开相册 //int count = editor.getChildCount(); ImageUtils.callGallery(mActivity, MimeType.ofAll(), 1, REQUEST_CODE_CHOOSE); // } else { // MyToast.showToast(mActivity, "请先将光标聚焦内容编辑器"); // } } @Override public void permissionDenied(@NonNull String[] permission) { } }, Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE); } else if (i == R.id.imgfAccessory) { } } }; @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode == RESULT_OK) { switch (requestCode) { case RichEditUtils.REQUEST_CODE_CAMERA://拍照 break; case RichEditUtils.REQUEST_CODE_CAMERA2://摄像 showLoadingDialog("视频压缩中..."); //根据Uri获取文件的存放路径 String loca_videopath = SDCardUtil.getFilePathByUri(mActivity, data.getData()); ComprassVideo(loca_videopath); break; case REQUEST_CODE_CHOOSE: List<Uri> mSelected = richEditUtils.getUriList(data); if (mSelected != null && mSelected.get(0) != null) { //根据Uri获取文件的存放路径 String locapath = SDCardUtil.getFilePathByUri(mActivity, mSelected.get(0)); //获取文件格式用于判断是视频还是图片 String fmat = SDCardUtil.getFrmatByUri(locapath); String filepath = null; if (fmat.equals("video")) { showLoadingDialog("正在计算视频大小"); int during = SDCardUtil.getRingDuring(locapath); closeLoadingDialog(); if (during <= 0) { MyToast.showToast(AddKnowledgeActivity.this, "视频无效,请重新选择"); } else if (during > 600 * 1000) { MyToast.showToast(AddKnowledgeActivity.this, "视频过长,请重新选择"); } else { showLoadingDialog("视频压缩中..."); ComprassVideo(locapath); } } else { showLoadingDialog("压缩中..."); filepath = richEditUtils.getCompressImageFile("image", mSelected.get(0));//压缩图片 closeLoadingDialog(); presenter.uploadFile(mActivity, "image", filepath, "图片上传中..."); } } break; } } } //上传图片或视频 @Override public void setUploadFile(String fileType, boolean isSuccess, String localpath, String msg) { try { if (isSuccess) { JSONObject jo = new JSONObject(msg); String domain = Hawk.get(Tokens.SP_UPLOADCNETERPATH, ""); if (!domain.equals("")) { if (fileType.equals("video")) { //视频的网络路径 String videoPath = domain + "/" + ComTools.ToString(jo.getString("url")); //获取第一帧图片后上传 String frameLocalPath = SDCardUtil.saveToSdCard(richEditUtils.getLocalVideoBitmap(localpath)); presenter.uploadFrameAtPic(mActivity, "image", frameLocalPath, videoPath); } else if (fileType.equals("image")) { String imgpath = domain + "/" + ComTools.ToString(jo.getString("url")); Bitmap bitmap = richEditUtils.getScaledBitmap(localpath, editor.getMeasuredWidth()); richEditUtils.insertImagesSync(bitmap, null, imgpath); } } } else { showNoDataHint(msg); MyToast.showFailToast(mActivity, msg); } } catch (Exception e) { e.printStackTrace(); } } //上传第一帧图片 @Override public void setUploadFrameAtPic(boolean isSuccess, String videoPath, String frameLocalPath, String msg) { try { String fameAtPath = null; if (isSuccess) { try { JSONObject jo = new JSONObject(msg); String domain = Hawk.get(Tokens.SP_UPLOADCNETERPATH, ""); if (!domain.equals("")) { fameAtPath = domain + "/" + ComTools.ToString(jo.getString("url")); } } catch (JSONException e) { e.printStackTrace(); } } if (RichTextEditor.framePics == null) { RichTextEditor.framePics = new HashMap<>(); } RichTextEditor.framePics.put(videoPath, fameAtPath); richEditUtils.insertImagesSync(null, frameLocalPath, videoPath); } catch (Exception e) { e.getMessage(); } } @Override public void onBackPressed() { InFinish(); } @Override protected void onPause() { super.onPause(); JZVideoPlayer.releaseAllVideos(); } Dialog quitDialog = null; private void InFinish() { if (editor.getLastIndex() > 1) { quitDialog = CustomDialog.createCancleDialog(mActivity, "添加的内容尚未发布,确定要退出界面吗?", new View.OnClickListener() { @Override public void onClick(View v) { quitDialog.dismiss(); editor.removeAllViews(); presenter.addHotAndAll(); closeLoadingDialog(); finish(); } }); quitDialog.show(); } else { editor.removeAllViews(); presenter.addHotAndAll(); closeLoadingDialog(); finish(); } } @Override protected void onDestroy() { super.onDestroy(); if (RichTextEditor.framePics != null && RichTextEditor.framePics.size() > 0) { RichTextEditor.framePics.clear(); } //清空缓存的图片 new Thread(new Runnable() { @Override public void run() { SDCardUtil.deleteDir(SDCardUtil.APP_NAME, null); } }).start(); //清空缓存的压缩视频 new Thread(new Runnable() { @Override public void run() { SDCardUtil.deleteDir(SDCardUtil.CompressFile, "VID_"); } }); } private void ComprassVideo(String vUrl){ if(SDCardUtil.getFileSizeMB(vUrl) < 5){//压缩的大小是否在5M以下 closeLoadingDialog(); presenter.uploadFile(mActivity, "video", vUrl, "视频上传中..."); }else { final String destPath = SDCardUtil.CompressFile + "VID_" + new SimpleDateFormat("yyyyMMdd_HHmmss", SDCardUtil.getLocale(mActivity)).format(new Date()) + ".mp4"; VideoCompress.compressVideoLow(vUrl, destPath, new VideoCompress.CompressListener() { @Override public void onStart() { } @Override public void onSuccess() { ComprassVideo(destPath); } @Override public void onFail() { closeLoadingDialog(); MyToast.showFailToast(mActivity, "视频压缩失败!"); } @Override public void onProgress(float percent) { } }); } } }
UTF-8
Java
18,021
java
AddKnowledgeActivity.java
Java
[ { "context": "l.List;\n\nimport cn.jzvd.JZVideoPlayer;\n\n/**\n * 作者:DC-DingYG on 2018-07-31 8:40\n * 邮箱:dingyg012655@126.com\n */", "end": 2034, "score": 0.999559760093689, "start": 2025, "tag": "USERNAME", "value": "DC-DingYG" }, { "context": "er;\n\n/**\n * 作者:DC-DingYG on 2018-07-31 8:40\n * 邮箱:dingyg012655@126.com\n */\npublic class AddKnowledgeActivity extends Rep", "end": 2080, "score": 0.9999061822891235, "start": 2060, "tag": "EMAIL", "value": "dingyg012655@126.com" } ]
null
[]
package com.soonfor.repository.ui.activity.knowledge; import android.Manifest; import android.app.Dialog; import android.content.Intent; import android.content.pm.ActivityInfo; import android.graphics.Bitmap; import android.net.Uri; import android.support.annotation.NonNull; import android.text.Editable; import android.text.TextWatcher; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import com.dingyg.edittextwithclear.EditTextWithClear; import com.dingyg.richeditor.RichEditUtils; import com.dingyg.richeditor.RichTextEditor; import com.dingyg.richeditor.Tools; import com.dingyg.richeditor.utils.ImageUtils; import com.dingyg.richeditor.utils.MyGlideEngine; import com.dingyg.richeditor.utils.SDCardUtil; import com.dingyg.videocompressorr.VideoCompress; import com.github.dfqin.grantor.PermissionListener; import com.github.dfqin.grantor.PermissionsUtil; import com.orhanobut.hawk.Hawk; import com.soonfor.repository.R; import com.soonfor.repository.base.RepBaseActivity; import com.soonfor.repository.model.knowledge.CategoryBean; import com.soonfor.repository.presenter.knowledge.AddKnowledgePresenter; import com.soonfor.repository.tools.ComTools; import com.soonfor.repository.tools.DataTools; import com.soonfor.repository.tools.MyToast; import com.soonfor.repository.tools.Tokens; import com.soonfor.repository.tools.dialog.CustomDialog; import com.soonfor.repository.tools.popupwindow.SelectAddClassifyPopupWindow; import com.soonfor.repository.view.knowledge.IAddKnowledgeView; import com.zhihu.matisse.Matisse; import com.zhihu.matisse.MimeType; import com.zhihu.matisse.internal.entity.CaptureStrategy; import org.json.JSONException; import org.json.JSONObject; import java.io.File; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.List; import cn.jzvd.JZVideoPlayer; /** * 作者:DC-DingYG on 2018-07-31 8:40 * 邮箱:<EMAIL> */ public class AddKnowledgeActivity extends RepBaseActivity<AddKnowledgePresenter> implements IAddKnowledgeView { private AddKnowledgeActivity mActivity; ImageView imgfOpen;//展示二级菜单 TextView tvfClassify; TextView tvfTitile; RelativeLayout rlfTablayout; EditTextWithClear llfEditTitle; EditText etfTilte; RichTextEditor editor;//图文混编器 ImageView imgfCover; ImageView imgfCamera, imgfPhoto, imgfAccessory; RelativeLayout rlfBottom; Button btfSend; private RichEditUtils richEditUtils; //private boolean isRichFocus = false;//光标焦点是否在内容编辑器上 private CategoryBean[] fcbs = new CategoryBean[2];//選中的一、二級菜單 public static final int REQUEST_CODE_CHOOSE = 23;//定义请求码常量 @Override protected int attachLayoutRes() { return R.layout.activity_addknowledge; } @Override protected void finishByBack() { super.finishByBack(); InFinish(); } @Override protected void updateViews(boolean isRefresh) { } private void findViewById() { imgfOpen = this.findViewById(R.id.imgfState); imgfOpen.setOnClickListener(listener); tvfClassify = this.findViewById(R.id.tvfClassify); tvfTitile = this.findViewById(R.id.tvfTitile); rlfTablayout = this.findViewById(R.id.rlfTablayout); rlfTablayout.setOnClickListener(listener); llfEditTitle = this.findViewById(R.id.ewfTitle); editor = this.findViewById(R.id.richEditor); imgfCover = this.findViewById(R.id.imgfCover); rlfBottom = this.findViewById(R.id.rlfBottom); imgfCamera = this.findViewById(R.id.imgfCamera); imgfCamera.setOnClickListener(listener); imgfPhoto = this.findViewById(R.id.imgfPhoto); imgfPhoto.setOnClickListener(listener); btfSend = this.findViewById(R.id.btfSave); btfSend.setOnClickListener(listener); if (RichTextEditor.framePics == null) { RichTextEditor.framePics = new HashMap<>(); } else if (RichTextEditor.framePics.size() > 0) { RichTextEditor.framePics.clear(); } } @Override protected AddKnowledgePresenter initPresenter() { findViewById(); actionName = "上传中..."; presenter = new AddKnowledgePresenter(this); mActivity = AddKnowledgeActivity.this; tvfTitile.setText("添加知识"); etfTilte = llfEditTitle.getEditText(); editor.setHint("内容"); etfTilte.setHint("标题"); etfTilte.requestFocus(); etfTilte.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void afterTextChanged(Editable s) { if (s.toString().trim().equals("")) { btfSend.setEnabled(false); } else if (etfTilte.getText().toString().trim().length() > 0 && fcbs != null && fcbs.length > 1 && fcbs[1] != null && !fcbs[1].getId().equals("")) { btfSend.setEnabled(true); } } }); return presenter; } @Override protected void initViews() { richEditUtils = RichEditUtils.getRichEditUtils(mActivity, editor); presenter.getTabTitles(mActivity, false); } @Override public void setGetCategory(boolean isSuccess, String msg) { if (isSuccess) { } else { showNoDataHint(msg); MyToast.showFailToast(mActivity, msg); } } @Override public void setAddKnowLedge(boolean isSuccess, String msg) { btfSend.setEnabled(true); if (isSuccess) { MyToast.showFailToast(mActivity, "已成功新增知识"); finish(); } else { showNoDataHint(msg); MyToast.showFailToast(mActivity, msg); } } SelectAddClassifyPopupWindow scPopupWindow; private View.OnClickListener listener = new View.OnClickListener() { @Override public void onClick(View v) { int i = v.getId(); if (i == R.id.rlfTablayout || i == R.id.imgfState) { if (DataTools.fTypes == null) { return; } if (scPopupWindow != null) { scPopupWindow.dismiss(); } scPopupWindow = new SelectAddClassifyPopupWindow(mActivity, fcbs, imgfCover, new SelectAddClassifyPopupWindow.refresh() { @Override public void refreshLayout(CategoryBean[] cbs) { fcbs = cbs; if (scPopupWindow != null) { scPopupWindow.dismiss(); } tvfClassify.setText(fcbs[1].getName()); if (!fcbs[1].getId().equals("")) { if (!etfTilte.getText().toString().trim().equals("")) ; btfSend.setEnabled(true); } } }); scPopupWindow.showPopupWindow(rlfTablayout, mActivity); } else if (i == R.id.btfSave) { if (fcbs[1] == null || fcbs[1].getId().equals("")) { MyToast.showToast(mActivity, "请选择要增加的知识类型"); return; } String title = etfTilte.getText().toString().trim(); if (title.equals("")) { MyToast.showToast(mActivity, "请填写标题"); return; } String content = richEditUtils.getEditData(); if (content.length() == 0) { MyToast.showToast(mActivity, "请填写内容"); return; } btfSend.setEnabled(false); presenter.addKonwledge(mActivity, fcbs[1].getId(), title, content, null); } else if (i == R.id.imgfCamera) { PermissionsUtil.requestPermission(mActivity, new PermissionListener() { @Override public void permissionGranted(@NonNull String[] permission) { Tools.closeSoftKeyInput(mActivity);//关闭软键盘 // if (isRichFocus) { // 打开相机 richEditUtils.openCamera(2); // } else { // MyToast.showToast(mActivity, "请先将光标聚焦内容编辑器"); // } } @Override public void permissionDenied(@NonNull String[] permission) { } }, Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE); } else if (i == R.id.imgfPhoto) { PermissionsUtil.requestPermission(mActivity, new PermissionListener() { @Override public void permissionGranted(@NonNull String[] permission) { // 打开系统相册 Tools.closeSoftKeyInput(mActivity);//关闭软键盘 // if (isRichFocus) { // 打开相册 //int count = editor.getChildCount(); ImageUtils.callGallery(mActivity, MimeType.ofAll(), 1, REQUEST_CODE_CHOOSE); // } else { // MyToast.showToast(mActivity, "请先将光标聚焦内容编辑器"); // } } @Override public void permissionDenied(@NonNull String[] permission) { } }, Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE); } else if (i == R.id.imgfAccessory) { } } }; @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode == RESULT_OK) { switch (requestCode) { case RichEditUtils.REQUEST_CODE_CAMERA://拍照 break; case RichEditUtils.REQUEST_CODE_CAMERA2://摄像 showLoadingDialog("视频压缩中..."); //根据Uri获取文件的存放路径 String loca_videopath = SDCardUtil.getFilePathByUri(mActivity, data.getData()); ComprassVideo(loca_videopath); break; case REQUEST_CODE_CHOOSE: List<Uri> mSelected = richEditUtils.getUriList(data); if (mSelected != null && mSelected.get(0) != null) { //根据Uri获取文件的存放路径 String locapath = SDCardUtil.getFilePathByUri(mActivity, mSelected.get(0)); //获取文件格式用于判断是视频还是图片 String fmat = SDCardUtil.getFrmatByUri(locapath); String filepath = null; if (fmat.equals("video")) { showLoadingDialog("正在计算视频大小"); int during = SDCardUtil.getRingDuring(locapath); closeLoadingDialog(); if (during <= 0) { MyToast.showToast(AddKnowledgeActivity.this, "视频无效,请重新选择"); } else if (during > 600 * 1000) { MyToast.showToast(AddKnowledgeActivity.this, "视频过长,请重新选择"); } else { showLoadingDialog("视频压缩中..."); ComprassVideo(locapath); } } else { showLoadingDialog("压缩中..."); filepath = richEditUtils.getCompressImageFile("image", mSelected.get(0));//压缩图片 closeLoadingDialog(); presenter.uploadFile(mActivity, "image", filepath, "图片上传中..."); } } break; } } } //上传图片或视频 @Override public void setUploadFile(String fileType, boolean isSuccess, String localpath, String msg) { try { if (isSuccess) { JSONObject jo = new JSONObject(msg); String domain = Hawk.get(Tokens.SP_UPLOADCNETERPATH, ""); if (!domain.equals("")) { if (fileType.equals("video")) { //视频的网络路径 String videoPath = domain + "/" + ComTools.ToString(jo.getString("url")); //获取第一帧图片后上传 String frameLocalPath = SDCardUtil.saveToSdCard(richEditUtils.getLocalVideoBitmap(localpath)); presenter.uploadFrameAtPic(mActivity, "image", frameLocalPath, videoPath); } else if (fileType.equals("image")) { String imgpath = domain + "/" + ComTools.ToString(jo.getString("url")); Bitmap bitmap = richEditUtils.getScaledBitmap(localpath, editor.getMeasuredWidth()); richEditUtils.insertImagesSync(bitmap, null, imgpath); } } } else { showNoDataHint(msg); MyToast.showFailToast(mActivity, msg); } } catch (Exception e) { e.printStackTrace(); } } //上传第一帧图片 @Override public void setUploadFrameAtPic(boolean isSuccess, String videoPath, String frameLocalPath, String msg) { try { String fameAtPath = null; if (isSuccess) { try { JSONObject jo = new JSONObject(msg); String domain = Hawk.get(Tokens.SP_UPLOADCNETERPATH, ""); if (!domain.equals("")) { fameAtPath = domain + "/" + ComTools.ToString(jo.getString("url")); } } catch (JSONException e) { e.printStackTrace(); } } if (RichTextEditor.framePics == null) { RichTextEditor.framePics = new HashMap<>(); } RichTextEditor.framePics.put(videoPath, fameAtPath); richEditUtils.insertImagesSync(null, frameLocalPath, videoPath); } catch (Exception e) { e.getMessage(); } } @Override public void onBackPressed() { InFinish(); } @Override protected void onPause() { super.onPause(); JZVideoPlayer.releaseAllVideos(); } Dialog quitDialog = null; private void InFinish() { if (editor.getLastIndex() > 1) { quitDialog = CustomDialog.createCancleDialog(mActivity, "添加的内容尚未发布,确定要退出界面吗?", new View.OnClickListener() { @Override public void onClick(View v) { quitDialog.dismiss(); editor.removeAllViews(); presenter.addHotAndAll(); closeLoadingDialog(); finish(); } }); quitDialog.show(); } else { editor.removeAllViews(); presenter.addHotAndAll(); closeLoadingDialog(); finish(); } } @Override protected void onDestroy() { super.onDestroy(); if (RichTextEditor.framePics != null && RichTextEditor.framePics.size() > 0) { RichTextEditor.framePics.clear(); } //清空缓存的图片 new Thread(new Runnable() { @Override public void run() { SDCardUtil.deleteDir(SDCardUtil.APP_NAME, null); } }).start(); //清空缓存的压缩视频 new Thread(new Runnable() { @Override public void run() { SDCardUtil.deleteDir(SDCardUtil.CompressFile, "VID_"); } }); } private void ComprassVideo(String vUrl){ if(SDCardUtil.getFileSizeMB(vUrl) < 5){//压缩的大小是否在5M以下 closeLoadingDialog(); presenter.uploadFile(mActivity, "video", vUrl, "视频上传中..."); }else { final String destPath = SDCardUtil.CompressFile + "VID_" + new SimpleDateFormat("yyyyMMdd_HHmmss", SDCardUtil.getLocale(mActivity)).format(new Date()) + ".mp4"; VideoCompress.compressVideoLow(vUrl, destPath, new VideoCompress.CompressListener() { @Override public void onStart() { } @Override public void onSuccess() { ComprassVideo(destPath); } @Override public void onFail() { closeLoadingDialog(); MyToast.showFailToast(mActivity, "视频压缩失败!"); } @Override public void onProgress(float percent) { } }); } } }
18,008
0.552751
0.549704
465
36.404301
27.970722
172
false
false
0
0
0
0
0
0
0.625806
false
false
2
62e377d8ecba3ff3a0d7013e4f3cf83667d2cc61
19,035,295,123,823
fd7ad830bdda9fd2fcc52d733254be1f8ef29efc
/src/main/java/com/shop/trash/PostsController.java
0fb6e73042899e23b885625140c511bda0be20dd
[]
no_license
niramis/shopping-back
https://github.com/niramis/shopping-back
ffd837b93aba49149fd3b670519af5d841fb920b
e5d1025f44e616e7fd86f1e8738050af8c282204
refs/heads/master
2023-06-17T18:09:59.923000
2019-12-01T16:37:32
2019-12-01T16:37:32
224,927,264
0
0
null
false
2023-05-26T22:25:20
2019-11-29T21:59:34
2019-12-01T16:37:50
2023-05-26T22:25:20
31
0
0
1
Java
false
false
//package com.shop.controllers; // //import com.shop.model.Post; //import com.shop.model.Tag; //import com.shop.repository.PostRepository; //import com.shop.repository.TagRepository; //import org.springframework.beans.factory.annotation.Autowired; //import org.springframework.web.bind.annotation.GetMapping; //import org.springframework.web.bind.annotation.PostMapping; //import org.springframework.web.bind.annotation.RequestMapping; //import org.springframework.web.bind.annotation.RestController; // //import java.util.List; // //@RestController //@RequestMapping(path = "posts") //public class PostsController { // @Autowired // private TagRepository tagRepository; // // @Autowired // private PostRepository postRepository; // // @GetMapping(path = "/delete") // public void delete() { // postRepository.deleteAllInBatch(); // tagRepository.deleteAllInBatch(); // } // // @GetMapping(path = "/post") // public List<Post> getAllPosts() { // return postRepository.findAll(); // } // // @GetMapping(path = "tags") // public List<Tag> getAllTags() { // return tagRepository.findAll(); // } // // @PostMapping(path="savetag") // public Tag saveTag(Tag tag){ // return tagRepository.save(tag); // } // // @GetMapping(path = "save") // public void save() { // // Create a Post // Post post = new Post("Hibernate Many to Many Example with Spring Boot", // "Learn how to map a many to many relationship using hibernate", // "Entire Post content with Sample code"); // // // Create two tags // Tag tag1 = new Tag("Spring Boot"); // Tag tag2 = new Tag("Hibernate"); // // // // Add tag references in the post // post.getTags().add(tag1); // post.getTags().add(tag2); // // // Add post reference in the tags // tag1.getPosts().add(post); // tag2.getPosts().add(post); // // postRepository.save(post); // } // //}
UTF-8
Java
2,013
java
PostsController.java
Java
[]
null
[]
//package com.shop.controllers; // //import com.shop.model.Post; //import com.shop.model.Tag; //import com.shop.repository.PostRepository; //import com.shop.repository.TagRepository; //import org.springframework.beans.factory.annotation.Autowired; //import org.springframework.web.bind.annotation.GetMapping; //import org.springframework.web.bind.annotation.PostMapping; //import org.springframework.web.bind.annotation.RequestMapping; //import org.springframework.web.bind.annotation.RestController; // //import java.util.List; // //@RestController //@RequestMapping(path = "posts") //public class PostsController { // @Autowired // private TagRepository tagRepository; // // @Autowired // private PostRepository postRepository; // // @GetMapping(path = "/delete") // public void delete() { // postRepository.deleteAllInBatch(); // tagRepository.deleteAllInBatch(); // } // // @GetMapping(path = "/post") // public List<Post> getAllPosts() { // return postRepository.findAll(); // } // // @GetMapping(path = "tags") // public List<Tag> getAllTags() { // return tagRepository.findAll(); // } // // @PostMapping(path="savetag") // public Tag saveTag(Tag tag){ // return tagRepository.save(tag); // } // // @GetMapping(path = "save") // public void save() { // // Create a Post // Post post = new Post("Hibernate Many to Many Example with Spring Boot", // "Learn how to map a many to many relationship using hibernate", // "Entire Post content with Sample code"); // // // Create two tags // Tag tag1 = new Tag("Spring Boot"); // Tag tag2 = new Tag("Hibernate"); // // // // Add tag references in the post // post.getTags().add(tag1); // post.getTags().add(tag2); // // // Add post reference in the tags // tag1.getPosts().add(post); // tag2.getPosts().add(post); // // postRepository.save(post); // } // //}
2,013
0.626428
0.623448
68
28.602942
20.81723
81
false
false
0
0
0
0
0
0
0.411765
false
false
2
1a0903ccc8abe642b23d7be68081d905c6e16855
17,987,323,092,563
c66461708e8509eb565ea3eaaba645ff87324003
/app/src/main/java/com/bigshark/smartlight/pro/mine/view/adapter/RideListAdapter.java
7f9eb63be36b62f13e381e6f786a33493c06c35f
[]
no_license
answes/SmartLights
https://github.com/answes/SmartLights
e1edc723adb02ee4a232c048cf24f4d5aa53fbea
eb8cb1d87879f59e70d545e3e1e08d1756877c7c
refs/heads/master
2021-01-12T06:53:15.857000
2017-08-31T15:04:18
2017-08-31T15:04:18
76,852,906
3
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.bigshark.smartlight.pro.mine.view.adapter; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.andview.refreshview.recyclerview.BaseRecyclerAdapter; import com.bigshark.smartlight.R; import com.bigshark.smartlight.bean.Ride; import com.bigshark.smartlight.utils.DateFomat; import com.bigshark.smartlight.utils.SupportMultipleScreensUtil; import java.text.DecimalFormat; import java.util.List; /** * Created by luyanhong on 16/9/28. */ public class RideListAdapter extends BaseRecyclerAdapter<RideListAdapter.MyViewHolder> { private List<Ride.Bike> list; private Context context; private OnItemOnClickListenr onItemOnClickListenr; public void setOnItemOnClickListre(OnItemOnClickListenr onItemOnClickListenr){ this.onItemOnClickListenr = onItemOnClickListenr; } public RideListAdapter(Context context, List<Ride.Bike> list){ this.list = list; this.context = context; } @Override public MyViewHolder getViewHolder(View view) { return new MyViewHolder(view,false,onItemOnClickListenr); } @Override public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType, boolean isItem) { MyViewHolder myViewHolder = new MyViewHolder(LayoutInflater.from(context).inflate(R.layout.item_mine_ride_list_layout,parent,false),true,onItemOnClickListenr); return myViewHolder; } @Override public void onBindViewHolder(MyViewHolder holder, final int position, boolean isItem) { final Double cny = Double.parseDouble(list.get(position).getDistance()); DecimalFormat df = new DecimalFormat("0.000"); holder.distance.setText(df.format(cny)); holder.time.setText(DateFomat.convertSecond2DateSS(list.get(position).getCre_tm())); } @Override public int getAdapterItemCount() { return list.size(); } class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener { OnItemOnClickListenr myonItemOnClickListenr; TextView distance; TextView time; public MyViewHolder(View itemView,boolean is,OnItemOnClickListenr myonItemOnClickListenr) { super(itemView); this.myonItemOnClickListenr = myonItemOnClickListenr; SupportMultipleScreensUtil.scale(itemView); if(is){ distance = (TextView) itemView.findViewById(R.id.tv_distance); time = (TextView) itemView.findViewById(R.id.tv_time); } itemView.setOnClickListener(this); } @Override public void onClick(View view) { if(myonItemOnClickListenr != null){ myonItemOnClickListenr.clickItem(view,getPosition()); } } } public interface OnItemOnClickListenr{ void clickItem(View view , int postin); } }
UTF-8
Java
3,038
java
RideListAdapter.java
Java
[ { "context": "lFormat;\nimport java.util.List;\n\n/**\n * Created by luyanhong on 16/9/28.\n */\npublic class RideListAdapter exte", "end": 599, "score": 0.9996341466903687, "start": 590, "tag": "USERNAME", "value": "luyanhong" } ]
null
[]
package com.bigshark.smartlight.pro.mine.view.adapter; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.andview.refreshview.recyclerview.BaseRecyclerAdapter; import com.bigshark.smartlight.R; import com.bigshark.smartlight.bean.Ride; import com.bigshark.smartlight.utils.DateFomat; import com.bigshark.smartlight.utils.SupportMultipleScreensUtil; import java.text.DecimalFormat; import java.util.List; /** * Created by luyanhong on 16/9/28. */ public class RideListAdapter extends BaseRecyclerAdapter<RideListAdapter.MyViewHolder> { private List<Ride.Bike> list; private Context context; private OnItemOnClickListenr onItemOnClickListenr; public void setOnItemOnClickListre(OnItemOnClickListenr onItemOnClickListenr){ this.onItemOnClickListenr = onItemOnClickListenr; } public RideListAdapter(Context context, List<Ride.Bike> list){ this.list = list; this.context = context; } @Override public MyViewHolder getViewHolder(View view) { return new MyViewHolder(view,false,onItemOnClickListenr); } @Override public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType, boolean isItem) { MyViewHolder myViewHolder = new MyViewHolder(LayoutInflater.from(context).inflate(R.layout.item_mine_ride_list_layout,parent,false),true,onItemOnClickListenr); return myViewHolder; } @Override public void onBindViewHolder(MyViewHolder holder, final int position, boolean isItem) { final Double cny = Double.parseDouble(list.get(position).getDistance()); DecimalFormat df = new DecimalFormat("0.000"); holder.distance.setText(df.format(cny)); holder.time.setText(DateFomat.convertSecond2DateSS(list.get(position).getCre_tm())); } @Override public int getAdapterItemCount() { return list.size(); } class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener { OnItemOnClickListenr myonItemOnClickListenr; TextView distance; TextView time; public MyViewHolder(View itemView,boolean is,OnItemOnClickListenr myonItemOnClickListenr) { super(itemView); this.myonItemOnClickListenr = myonItemOnClickListenr; SupportMultipleScreensUtil.scale(itemView); if(is){ distance = (TextView) itemView.findViewById(R.id.tv_distance); time = (TextView) itemView.findViewById(R.id.tv_time); } itemView.setOnClickListener(this); } @Override public void onClick(View view) { if(myonItemOnClickListenr != null){ myonItemOnClickListenr.clickItem(view,getPosition()); } } } public interface OnItemOnClickListenr{ void clickItem(View view , int postin); } }
3,038
0.709019
0.705398
90
32.755554
31.635532
167
false
false
0
0
0
0
0
0
0.6
false
false
2
46a96a6d7ef74712fecbe4dc477d778cdb7ae9d6
32,813,550,199,223
d2798388180b926e131b9b5e5c542de5b5dbd607
/src/by/it/luksha/jd01_13/taskC/patient/Patient.java
fc7f28d25f257dec5b2f552fcd8ae6fbb01138ad
[]
no_license
VasilevichSergey/JD2016
https://github.com/VasilevichSergey/JD2016
14a22a5c31ded3783014b9d89cdddf0eb6ad4398
dfb8e38a6c4022677708dc03d0047d76bc801bfd
refs/heads/master
2020-12-24T20:25:06.458000
2016-10-04T10:35:49
2016-10-04T10:35:49
58,029,314
0
0
null
true
2016-05-04T06:46:27
2016-05-04T06:46:27
2016-05-03T21:33:48
2016-05-03T23:17:47
66
0
0
0
null
null
null
package by.it.luksha.jd01_13.taskC.patient; public class Patient { //имя пациента private String name; //название болезни private String sickness; //состояние пациента здоров/болен - false/true private boolean isSick = false; public Patient(String name) { this.name = name; } public void setSickness(String sickness) { this.sickness = sickness; } public void setSick(boolean sick) { isSick = sick; } public String getSickness() { return sickness; } public boolean isSick() { return isSick; } @Override public String toString() { return this.name; } }
UTF-8
Java
737
java
Patient.java
Java
[]
null
[]
package by.it.luksha.jd01_13.taskC.patient; public class Patient { //имя пациента private String name; //название болезни private String sickness; //состояние пациента здоров/болен - false/true private boolean isSick = false; public Patient(String name) { this.name = name; } public void setSickness(String sickness) { this.sickness = sickness; } public void setSick(boolean sick) { isSick = sick; } public String getSickness() { return sickness; } public boolean isSick() { return isSick; } @Override public String toString() { return this.name; } }
737
0.610542
0.604685
36
17.972221
15.236079
50
false
false
0
0
0
0
0
0
0.277778
false
false
2
046cbf6247ba36afa59798f566cd66905e43ab6a
1,872,605,802,592
8b7d7ba2c7797b9cf0ae3d3b2d41eeea0a368f98
/src/main/java/com/example/ctic/clase2pit2/MainActivity.java
8a3b09e0e723ef05712e01f31caee53694d38e6d
[]
no_license
edgarhuaranga/Clase2PIT2
https://github.com/edgarhuaranga/Clase2PIT2
2dcbcaa5c25874809a79c05ad0f178dc7122425d
258e77d888ae392a741115b0df9609d1404a5429
refs/heads/master
2020-03-15T02:27:07.605000
2018-05-03T01:54:05
2018-05-03T01:54:05
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.ctic.clase2pit2; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; public class MainActivity extends AppCompatActivity { EditText editTextCodigo; Button botonConsultar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); editTextCodigo = findViewById(R.id.edittext_codigo); botonConsultar = findViewById(R.id.boton_consultar); } public void consultaORCE(View view) { String codigoAlumno = editTextCodigo.getText().toString(); Intent intent = new Intent(this, MapsActivity.class); intent.putExtra("codigo", codigoAlumno); startActivity(intent); } }
UTF-8
Java
925
java
MainActivity.java
Java
[]
null
[]
package com.example.ctic.clase2pit2; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; public class MainActivity extends AppCompatActivity { EditText editTextCodigo; Button botonConsultar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); editTextCodigo = findViewById(R.id.edittext_codigo); botonConsultar = findViewById(R.id.boton_consultar); } public void consultaORCE(View view) { String codigoAlumno = editTextCodigo.getText().toString(); Intent intent = new Intent(this, MapsActivity.class); intent.putExtra("codigo", codigoAlumno); startActivity(intent); } }
925
0.708108
0.704865
29
29.896551
21.557213
66
false
false
0
0
0
0
0
0
0.655172
false
false
2
94b408e86708818759062f9a3989aba6208c0e7b
9,105,330,678,658
ffe216bd5f1100880d477059dac5297a1cdb2ff9
/oauthsecure-client/src/main/java/za/co/sindi/oauth/client/response/AbstractResponseHandler.java
17d9da25e590d19a34a36cd2f07ee4126a6e80aa
[ "Apache-2.0" ]
permissive
TheEliteGentleman/oauthsecure
https://github.com/TheEliteGentleman/oauthsecure
37b4b0d9ad0bb6c463491c97867dbc7c56a74cba
69dfc5a8c440a2ccabdb481264a0be1477325b1a
refs/heads/master
2020-04-06T06:57:35.022000
2016-09-02T14:30:04
2016-09-02T14:30:04
62,515,755
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * */ package za.co.sindi.oauth.client.response; import java.util.ArrayList; import java.util.List; import org.apache.log4j.Logger; import za.co.sindi.oauth.client.ResponseHandler; import za.co.sindi.oauth.client.exception.OAuthResponseException; import za.co.sindi.oauth.client.transport.Interceptor; import za.co.sindi.oauth.client.transport.Response; import za.co.sindi.oauth.client.transport.http.HttpResponse; import za.co.sindi.oauth.client.transport.interceptor.InterceptorContext; /** * @author Buhake Sindi * @since 17 February 2012 * */ public abstract class AbstractResponseHandler<T> implements ResponseHandler<T>, InterceptorContext<Response> { protected static final String LINE_SEPARATOR = System.getProperty("line.separator"); protected final Logger logger = Logger.getLogger(this.getClass()); private List<Interceptor<Response>> interceptors = new ArrayList<Interceptor<Response>>(); /* (non-Javadoc) * @see net.oauth.client.InterceptorContext#addResponseInterceptor(net.oauth.transport.interceptor.ResponseInterceptor) */ @Override public void addInterceptor(Interceptor<Response> interceptor) { // TODO Auto-generated method stub if (interceptor != null) { interceptors.add(interceptor); } } /* (non-Javadoc) * @see net.oauth.client.InterceptorContext#removeInterceptor(net.oauth.transport.interceptor.ResponseInterceptor) */ @Override public void removeInterceptor(Interceptor<Response> interceptor) { // TODO Auto-generated method stub if (interceptor != null) { interceptors.remove(interceptor); } } /* (non-Javadoc) * @see net.oauth.client.InterceptorContext#clearInterceptor() */ @Override public void clearInterceptors() { // TODO Auto-generated method stub interceptors.clear(); } /* (non-Javadoc) * @see net.oauth.client.OAuthResponseHandler#handleResponse(net.oauth.transport.Response) */ @Override public T handleResponse(Response response) throws OAuthResponseException { // TODO Auto-generated method stub if (response == null) { throw new OAuthResponseException("Invalid Http response received."); } if (interceptors != null && !interceptors.isEmpty()) { if (logger.isInfoEnabled()) { logger.info("Sending response (of type " + response.getClass().getName() + ") to " + interceptors.size() + " interceptor(s)."); } for (Interceptor<Response> interceptor : interceptors) { interceptor.accept(response); } } if (response instanceof HttpResponse) { return handleHttpResponse((HttpResponse) response); } throw new OAuthResponseException("Invalid response of type " + response.getClass().getName()); } /** * This method should be overridden if the user wants to handle {@link HttpResponse}. * @param response an HTTP response. * @return * @throws OAuthResponseException */ protected abstract T handleHttpResponse(HttpResponse response) throws OAuthResponseException; }
UTF-8
Java
2,944
java
AbstractResponseHandler.java
Java
[ { "context": "rt.interceptor.InterceptorContext;\n\n/**\n * @author Buhake Sindi\n * @since 17 February 2012\n *\n */\npublic abstract", "end": 526, "score": 0.9998644590377808, "start": 514, "tag": "NAME", "value": "Buhake Sindi" } ]
null
[]
/** * */ package za.co.sindi.oauth.client.response; import java.util.ArrayList; import java.util.List; import org.apache.log4j.Logger; import za.co.sindi.oauth.client.ResponseHandler; import za.co.sindi.oauth.client.exception.OAuthResponseException; import za.co.sindi.oauth.client.transport.Interceptor; import za.co.sindi.oauth.client.transport.Response; import za.co.sindi.oauth.client.transport.http.HttpResponse; import za.co.sindi.oauth.client.transport.interceptor.InterceptorContext; /** * @author <NAME> * @since 17 February 2012 * */ public abstract class AbstractResponseHandler<T> implements ResponseHandler<T>, InterceptorContext<Response> { protected static final String LINE_SEPARATOR = System.getProperty("line.separator"); protected final Logger logger = Logger.getLogger(this.getClass()); private List<Interceptor<Response>> interceptors = new ArrayList<Interceptor<Response>>(); /* (non-Javadoc) * @see net.oauth.client.InterceptorContext#addResponseInterceptor(net.oauth.transport.interceptor.ResponseInterceptor) */ @Override public void addInterceptor(Interceptor<Response> interceptor) { // TODO Auto-generated method stub if (interceptor != null) { interceptors.add(interceptor); } } /* (non-Javadoc) * @see net.oauth.client.InterceptorContext#removeInterceptor(net.oauth.transport.interceptor.ResponseInterceptor) */ @Override public void removeInterceptor(Interceptor<Response> interceptor) { // TODO Auto-generated method stub if (interceptor != null) { interceptors.remove(interceptor); } } /* (non-Javadoc) * @see net.oauth.client.InterceptorContext#clearInterceptor() */ @Override public void clearInterceptors() { // TODO Auto-generated method stub interceptors.clear(); } /* (non-Javadoc) * @see net.oauth.client.OAuthResponseHandler#handleResponse(net.oauth.transport.Response) */ @Override public T handleResponse(Response response) throws OAuthResponseException { // TODO Auto-generated method stub if (response == null) { throw new OAuthResponseException("Invalid Http response received."); } if (interceptors != null && !interceptors.isEmpty()) { if (logger.isInfoEnabled()) { logger.info("Sending response (of type " + response.getClass().getName() + ") to " + interceptors.size() + " interceptor(s)."); } for (Interceptor<Response> interceptor : interceptors) { interceptor.accept(response); } } if (response instanceof HttpResponse) { return handleHttpResponse((HttpResponse) response); } throw new OAuthResponseException("Invalid response of type " + response.getClass().getName()); } /** * This method should be overridden if the user wants to handle {@link HttpResponse}. * @param response an HTTP response. * @return * @throws OAuthResponseException */ protected abstract T handleHttpResponse(HttpResponse response) throws OAuthResponseException; }
2,938
0.744905
0.742527
94
30.319149
33.073811
131
false
false
0
0
0
0
0
0
1.404255
false
false
2
f16eba0cb17ac0beb3e36676a9b21e4de5cc7dff
27,590,869,924,433
986476e2628166ec4ed95ea0acdf715f4fe5be57
/Hamburger.java
5a235fc77b940d56596c5d3f80741216cfa74c22
[]
no_license
brq13/BillsBurgers
https://github.com/brq13/BillsBurgers
2f20f7889c6e3dcb918b073b9294faa6e40513b1
4525e77d94a0505f6cd9ce104ddcf3431d03b691
refs/heads/master
2022-09-23T23:25:21.869000
2020-06-07T12:46:57
2020-06-07T12:46:57
270,303,159
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.summer.burgersMasterOOP; public class Hamburger { private String hamburgerName; private BreadType breadType; // Rye Bread, Multigrain Bread, Pita Bread private MeatType meatType; // Poke, Beef, Chicken, Mutton private AdditionsType[] additionsType; // Every addition costs 2$ private double totalHamburgerPrice; public Hamburger(String hamburgerName, BreadType breadType, MeatType meatType, AdditionsType ... additionsType) { this.hamburgerName = hamburgerName; this.breadType = breadType; this.meatType = meatType; this.additionsType = additionsType; } public String getHamburgerName() { return hamburgerName; } public BreadType getBreadType() { return breadType; } public MeatType getMeatType() { return meatType; } public AdditionsType[] getAdditionsType() { return additionsType; } public double getTotalAdditionsPrice() { int totalAdditionsPrice = 0; for(int i = 0; i < additionsType.length; i++) { totalAdditionsPrice+=additionsType[i].getAdditionsTypePrice(); } return totalAdditionsPrice; } public void getTotalAdditionsName() { for(int i = 0; i < additionsType.length; i++) { System.out.println(additionsType[i].getAdditionsTypeName() + " : " + additionsType[i].getAdditionsTypePrice()); } } public void getTotalHamburgerPrice() { totalHamburgerPrice = breadType.getBreadTypePrice() + meatType.getMeatTypePrice() + getTotalAdditionsPrice(); System.out.print(hamburgerName + " consists of:\n" + "BREAD:\n" + breadType.getBreadTypeName() + " : " + breadType.getBreadTypePrice() + "\n" + "MEAT:\n" + meatType.getMeatTypeName() + " : " + meatType.getMeatTypePrice() + "\n" + "ADDITIONS:\n"); getTotalAdditionsName(); System.out.println("\n" + "TOTAL PRICE: " + totalHamburgerPrice + "\n"); } }
UTF-8
Java
2,078
java
Hamburger.java
Java
[]
null
[]
package com.summer.burgersMasterOOP; public class Hamburger { private String hamburgerName; private BreadType breadType; // Rye Bread, Multigrain Bread, Pita Bread private MeatType meatType; // Poke, Beef, Chicken, Mutton private AdditionsType[] additionsType; // Every addition costs 2$ private double totalHamburgerPrice; public Hamburger(String hamburgerName, BreadType breadType, MeatType meatType, AdditionsType ... additionsType) { this.hamburgerName = hamburgerName; this.breadType = breadType; this.meatType = meatType; this.additionsType = additionsType; } public String getHamburgerName() { return hamburgerName; } public BreadType getBreadType() { return breadType; } public MeatType getMeatType() { return meatType; } public AdditionsType[] getAdditionsType() { return additionsType; } public double getTotalAdditionsPrice() { int totalAdditionsPrice = 0; for(int i = 0; i < additionsType.length; i++) { totalAdditionsPrice+=additionsType[i].getAdditionsTypePrice(); } return totalAdditionsPrice; } public void getTotalAdditionsName() { for(int i = 0; i < additionsType.length; i++) { System.out.println(additionsType[i].getAdditionsTypeName() + " : " + additionsType[i].getAdditionsTypePrice()); } } public void getTotalHamburgerPrice() { totalHamburgerPrice = breadType.getBreadTypePrice() + meatType.getMeatTypePrice() + getTotalAdditionsPrice(); System.out.print(hamburgerName + " consists of:\n" + "BREAD:\n" + breadType.getBreadTypeName() + " : " + breadType.getBreadTypePrice() + "\n" + "MEAT:\n" + meatType.getMeatTypeName() + " : " + meatType.getMeatTypePrice() + "\n" + "ADDITIONS:\n"); getTotalAdditionsName(); System.out.println("\n" + "TOTAL PRICE: " + totalHamburgerPrice + "\n"); } }
2,078
0.626083
0.624158
57
34.456139
34.538597
149
false
false
0
0
0
0
0
0
0.596491
false
false
2
c75fa7417bb35042397013e01dcd45d7f354f09c
25,658,134,630,520
54db660973b839a316e8a0889cc6884f7c51095f
/src/Main.java
88d74f156fc01a5fa1b5f52c3f9f5e184e9953b6
[]
no_license
syedrashid47/AdapterPatternExample
https://github.com/syedrashid47/AdapterPatternExample
7fc0627cc7ca3cf2c17754eb325196b53741b937
e4a92e94660c2763777a25d6c744b7f0e844680a
refs/heads/master
2022-12-25T13:35:07.284000
2020-09-29T11:30:18
2020-09-29T11:30:18
299,583,700
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
public class Main { public static void main(String[] args) { LabGradingManager labGradingManager = new LabGradingManager(); labGradingManager.CalculateGrades("Lab", "FA12-BSE-324"); labGradingManager.CalculateGrades("CovidLab", "FA12-BSE-324"); labGradingManager.CalculateGrades("CovidNonLab", "FA12-BSE-324"); labGradingManager.CalculateGrades("Covid Lab without lab", "FA12-BSE-324"); } }
UTF-8
Java
444
java
Main.java
Java
[]
null
[]
public class Main { public static void main(String[] args) { LabGradingManager labGradingManager = new LabGradingManager(); labGradingManager.CalculateGrades("Lab", "FA12-BSE-324"); labGradingManager.CalculateGrades("CovidLab", "FA12-BSE-324"); labGradingManager.CalculateGrades("CovidNonLab", "FA12-BSE-324"); labGradingManager.CalculateGrades("Covid Lab without lab", "FA12-BSE-324"); } }
444
0.691441
0.646396
14
30.714285
33.121914
83
false
false
0
0
0
0
0
0
0.642857
false
false
2
09c6e62722b5bcb938c657d7ae21392259bbe40e
32,719,060,922,841
3186924070aa97e66df4b2a789583ba469059910
/20150622_ex12/src/Linking.java
7cbac014170ceb4d5cb422a4a698af368b00b3dc
[]
no_license
ChadCYB/workspace1.8_2
https://github.com/ChadCYB/workspace1.8_2
52e5a0e7137b3648e8721e2ae342f255a04d96fe
48a83c89a4c8092be97df869208ec2a43b79dd53
refs/heads/master
2021-01-10T18:23:53.410000
2015-06-25T08:31:44
2015-06-25T08:31:44
37,169,143
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* Uses: 鏈結串列類別(失敗作品) * Java JDK: 1.8 */ public class Linking { public int root; public Linking nLink; public Linking(int data, Linking theLink){ root = data; nLink = theLink; } public void setNextLink(Linking theLink){ nLink = theLink; } public void setNextData(int data){ nLink = new Linking(data,null); } public Linking getNextLink(){ return nLink; } public int getCurData(){ return root; } public void addLast(int data, Linking nextLink){ if(nLink == null){ System.out.println("<setNextLink>"); setNextData(data); }else{ // System.out.println("<addLink>"); addLast(data,nLink); } } public void addLink(Linking theLink, Linking nextLink){ if(nLink == null){ System.out.println("<setNextLink>"); setNextLink(theLink); }else{ // System.out.println("<addLink>"); addLink(theLink,nLink); } } }
BIG5
Java
878
java
Linking.java
Java
[]
null
[]
/* Uses: 鏈結串列類別(失敗作品) * Java JDK: 1.8 */ public class Linking { public int root; public Linking nLink; public Linking(int data, Linking theLink){ root = data; nLink = theLink; } public void setNextLink(Linking theLink){ nLink = theLink; } public void setNextData(int data){ nLink = new Linking(data,null); } public Linking getNextLink(){ return nLink; } public int getCurData(){ return root; } public void addLast(int data, Linking nextLink){ if(nLink == null){ System.out.println("<setNextLink>"); setNextData(data); }else{ // System.out.println("<addLink>"); addLast(data,nLink); } } public void addLink(Linking theLink, Linking nextLink){ if(nLink == null){ System.out.println("<setNextLink>"); setNextLink(theLink); }else{ // System.out.println("<addLink>"); addLink(theLink,nLink); } } }
878
0.665501
0.66317
41
19.926828
14.772074
56
false
false
0
0
0
0
0
0
2.146342
false
false
2
e3bc33b1ea9511f9bbeb86761be02914d56eb191
20,469,814,136,278
d78b1c946203c698ebba5cb2fa921972dd74a09d
/cloud-provoder-payment8002/src/main/java/com/wzy/springcloud/alibaba/service/PaymentService.java
621d27b2122b08690bace7c2e0d2c991860947e7
[]
no_license
KongXinYu/spring-cloud-study
https://github.com/KongXinYu/spring-cloud-study
663f8b458fc86c103b69503764060793df1bdb19
7e3cca4d7c7942fa5d6c92841adfa4ec986a9ac8
refs/heads/master
2023-03-24T06:56:31.898000
2021-03-25T05:25:04
2021-03-25T05:25:04
340,855,980
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.wzy.springcloud.alibaba.service; import com.wzy.commons.entity.payment.Payment; /** * @description: * @author: WuZY * @time: 2021/2/2 0002 */ public interface PaymentService { public int create(Payment payment); public Payment getPaymentById(Long id); }
UTF-8
Java
281
java
PaymentService.java
Java
[ { "context": "payment.Payment;\n\n/**\n * @description:\n * @author: WuZY\n * @time: 2021/2/2 0002\n */\npublic interface P", "end": 128, "score": 0.8861669301986694, "start": 127, "tag": "NAME", "value": "W" }, { "context": "yment.Payment;\n\n/**\n * @description:\n * @author: WuZY\n * @time: 2021/2/2 0002\n */\npublic interface Paym", "end": 131, "score": 0.5223006010055542, "start": 128, "tag": "USERNAME", "value": "uZY" } ]
null
[]
package com.wzy.springcloud.alibaba.service; import com.wzy.commons.entity.payment.Payment; /** * @description: * @author: WuZY * @time: 2021/2/2 0002 */ public interface PaymentService { public int create(Payment payment); public Payment getPaymentById(Long id); }
281
0.72242
0.686833
14
19.071428
17.886404
46
false
false
0
0
0
0
0
0
0.285714
false
false
2
c63e7249103705dbdedf42c2d704af5b4adcced7
28,733,331,233,683
0ad66e8b0aba8197dbd33d5f94593a0c16873c6b
/operations/src/main/java/io/retxt/operations/Operation.java
7171f431d5ab03d9f5d443fe8fae72b0ce0ca5e5
[ "MIT" ]
permissive
reTXT/concurrency-java
https://github.com/reTXT/concurrency-java
08ab14a175ce5bf1420118c018582619b311de10
ff6ee9f33bfce62aae5c063f6fb800483d15f395
refs/heads/master
2021-01-10T05:03:47.505000
2017-03-18T22:58:06
2017-03-18T22:58:06
51,101,632
5
4
null
false
2016-02-04T21:57:02
2016-02-04T20:01:21
2016-02-04T20:52:47
2016-02-04T21:57:02
29
0
0
0
Java
null
null
package io.retxt.operations; import java.util.Collection; import java.util.HashSet; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import static com.google.common.base.Preconditions.checkState; import static java.util.Collections.synchronizedCollection; /** * Operation that supports dependencies &amp; execution on an OperationQueue * <p> * Created by kdubb on 1/28/16. */ public abstract class Operation { public interface StateObserver { void operationStateChanged(Operation operation); } private String name; private OperationQueue queue; private Collection<StateObserver> observers = synchronizedCollection(new HashSet<>()); private Collection<Operation> waitingDependencies = synchronizedCollection(new HashSet<>()); private AtomicBoolean cancelled = new AtomicBoolean(false); private AtomicBoolean started = new AtomicBoolean(false); private AtomicBoolean finished = new AtomicBoolean(false); private CountDownLatch completionLatch = new CountDownLatch(1); private Runnable completionBlock; public Operation(String name) { this.name = name; } public String getName() { return name; } public boolean isReady() { return !started.get() && waitingDependencies.isEmpty(); } public boolean isExecuting() { return started.get() && !finished.get(); } public boolean isFinished() { return finished.get(); } public boolean isCancelled() { return cancelled.get(); } public void cancel() { cancelled.set(true); waitingDependencies.clear(); fireStateChanged(); } public void addDependency(Operation dependency) { checkState(queue == null, "Cannot add dependencies after adding the operation to a queue"); checkState(!isExecuting() && !isFinished() && !isCancelled(), "Cannot add dependencies after operation has started"); waitingDependencies.add(dependency); dependency.observers.add(this::dependencyStateChanged); dependencyStateChanged(dependency); } public void removeDependency(Operation dependency) { checkState(queue == null, "Cannot add dependencies after adding the operation to a queue"); checkState(!isExecuting() && !isFinished() && !isCancelled(), "Cannot add dependencies after operation has started"); dependency.observers.remove((StateObserver) this::dependencyStateChanged); waitingDependencies.remove(dependency); dependencyStateChanged(dependency); } public void addStateObserver(StateObserver observer) { observers.add(observer); } public void waitForCompletion() throws InterruptedException { completionLatch.await(); } public boolean waitForCompletion(long timeout, TimeUnit timeUnit) throws InterruptedException { return completionLatch.await(timeout, timeUnit); } public Runnable getCompletionBlock() { return completionBlock; } public void setCompletionBlock(Runnable completionBlock) { this.completionBlock = completionBlock; } protected abstract void run(); protected void execute() { beginExecution(); try { if(!isCancelled()) { run(); } } catch(Throwable e) { Thread thread = Thread.currentThread(); thread.getUncaughtExceptionHandler().uncaughtException(thread, e); } finally { endExecution(); } } void setQueue(OperationQueue queue) { if(this.queue != null) { throw new IllegalStateException("Operation already in queue"); } synchronized(this) { this.queue = queue; observers.add(this.queue::operationStateChanged); } } void unsetQueue() { synchronized(this) { if(isExecuting() || isFinished() || isCancelled()) { throw new IllegalStateException("Operation in invalid state to remove "); } observers.remove((StateObserver) this.queue::operationStateChanged); this.queue = null; } } protected void beginExecution() { started.set(true); fireStateChanged(); } protected void endExecution() { finished.set(true); fireStateChanged(); completionLatch.countDown(); if(completionBlock != null) { completionBlock.run(); } } void fireStateChanged() { for(StateObserver observer : observers) { observer.operationStateChanged(this); } } void dependencyStateChanged(Operation dependency) { if(dependency.isFinished()) { waitingDependencies.remove(dependency); } fireStateChanged(); } }
UTF-8
Java
4,619
java
Operation.java
Java
[ { "context": "xecution on an OperationQueue\n * <p>\n * Created by kdubb on 1/28/16.\n */\npublic abstract class Operation {", "end": 451, "score": 0.999661386013031, "start": 446, "tag": "USERNAME", "value": "kdubb" } ]
null
[]
package io.retxt.operations; import java.util.Collection; import java.util.HashSet; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import static com.google.common.base.Preconditions.checkState; import static java.util.Collections.synchronizedCollection; /** * Operation that supports dependencies &amp; execution on an OperationQueue * <p> * Created by kdubb on 1/28/16. */ public abstract class Operation { public interface StateObserver { void operationStateChanged(Operation operation); } private String name; private OperationQueue queue; private Collection<StateObserver> observers = synchronizedCollection(new HashSet<>()); private Collection<Operation> waitingDependencies = synchronizedCollection(new HashSet<>()); private AtomicBoolean cancelled = new AtomicBoolean(false); private AtomicBoolean started = new AtomicBoolean(false); private AtomicBoolean finished = new AtomicBoolean(false); private CountDownLatch completionLatch = new CountDownLatch(1); private Runnable completionBlock; public Operation(String name) { this.name = name; } public String getName() { return name; } public boolean isReady() { return !started.get() && waitingDependencies.isEmpty(); } public boolean isExecuting() { return started.get() && !finished.get(); } public boolean isFinished() { return finished.get(); } public boolean isCancelled() { return cancelled.get(); } public void cancel() { cancelled.set(true); waitingDependencies.clear(); fireStateChanged(); } public void addDependency(Operation dependency) { checkState(queue == null, "Cannot add dependencies after adding the operation to a queue"); checkState(!isExecuting() && !isFinished() && !isCancelled(), "Cannot add dependencies after operation has started"); waitingDependencies.add(dependency); dependency.observers.add(this::dependencyStateChanged); dependencyStateChanged(dependency); } public void removeDependency(Operation dependency) { checkState(queue == null, "Cannot add dependencies after adding the operation to a queue"); checkState(!isExecuting() && !isFinished() && !isCancelled(), "Cannot add dependencies after operation has started"); dependency.observers.remove((StateObserver) this::dependencyStateChanged); waitingDependencies.remove(dependency); dependencyStateChanged(dependency); } public void addStateObserver(StateObserver observer) { observers.add(observer); } public void waitForCompletion() throws InterruptedException { completionLatch.await(); } public boolean waitForCompletion(long timeout, TimeUnit timeUnit) throws InterruptedException { return completionLatch.await(timeout, timeUnit); } public Runnable getCompletionBlock() { return completionBlock; } public void setCompletionBlock(Runnable completionBlock) { this.completionBlock = completionBlock; } protected abstract void run(); protected void execute() { beginExecution(); try { if(!isCancelled()) { run(); } } catch(Throwable e) { Thread thread = Thread.currentThread(); thread.getUncaughtExceptionHandler().uncaughtException(thread, e); } finally { endExecution(); } } void setQueue(OperationQueue queue) { if(this.queue != null) { throw new IllegalStateException("Operation already in queue"); } synchronized(this) { this.queue = queue; observers.add(this.queue::operationStateChanged); } } void unsetQueue() { synchronized(this) { if(isExecuting() || isFinished() || isCancelled()) { throw new IllegalStateException("Operation in invalid state to remove "); } observers.remove((StateObserver) this.queue::operationStateChanged); this.queue = null; } } protected void beginExecution() { started.set(true); fireStateChanged(); } protected void endExecution() { finished.set(true); fireStateChanged(); completionLatch.countDown(); if(completionBlock != null) { completionBlock.run(); } } void fireStateChanged() { for(StateObserver observer : observers) { observer.operationStateChanged(this); } } void dependencyStateChanged(Operation dependency) { if(dependency.isFinished()) { waitingDependencies.remove(dependency); } fireStateChanged(); } }
4,619
0.697121
0.695822
198
22.328283
24.592606
97
false
false
0
0
0
0
0
0
0.378788
false
false
2
fe688c1173272c0f94af994be2ae43eef46cda15
10,359,461,118,999
3089f5e69412fe87ddd7574e984cf280bdb940e9
/src/main/java/com/nfwork/dbfound/web/i18n/I18NProvide.java
5b2d4f43d7d5fb7192b0df304517e9c675015268
[]
no_license
nfwork/dbfound
https://github.com/nfwork/dbfound
585022b43936a27da32b0a778febb93d0e9bf578
4ca7bffb5c4bc1c0fb04108e3e1c03d985a0310a
refs/heads/master
2023-08-31T09:00:46.942000
2023-08-29T04:36:49
2023-08-29T04:36:49
28,895,244
34
20
null
false
2023-06-15T06:12:03
2015-01-07T02:53:07
2023-06-13T03:13:36
2023-06-15T06:12:01
1,683
31
15
0
Java
false
false
package com.nfwork.dbfound.web.i18n; import javax.servlet.jsp.PageContext; public interface I18NProvide { public String value(String code, PageContext pageContext); }
UTF-8
Java
179
java
I18NProvide.java
Java
[]
null
[]
package com.nfwork.dbfound.web.i18n; import javax.servlet.jsp.PageContext; public interface I18NProvide { public String value(String code, PageContext pageContext); }
179
0.765363
0.743017
8
20.375
21.580879
59
false
false
0
0
0
0
0
0
0.625
false
false
2
a51c54d61867ff2ecfe9a4c64be5d3e69c031ea9
30,167,850,290,187
855665c5c58bd33c9cd880968e48c829fa467e5f
/software/caTissue/modules/core/src/main/java/edu/wustl/catissuecore/util/SpringContextHolder.java
f4778d35ea99e653b7e463ddfaeaa43f79749d08
[]
no_license
jpmccu/caTissue
https://github.com/jpmccu/caTissue
94c990f5d1b03bb376f622fe1b6d3acadc0b5118
85ceaac971ab0eaf15de3bddd451860a1ca1760a
refs/heads/master
2021-10-29T16:19:25.366000
2011-12-20T16:05:24
2011-12-20T16:05:24
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * */ package edu.wustl.catissuecore.util; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import edu.wustl.catissuecore.bizlogic.ccts.RegistrationPersistenceListener; /** * Utility class that helps other classes, which are not managed by Spring (such * as {@link RegistrationPersistenceListener}, to obtain * {@link ApplicationContext} reference. <b>Try not to rely on this class too * much; it's not an example of best design.</b> * * @author Denis G. Krylov * */ public final class SpringContextHolder implements ApplicationContextAware { public static ApplicationContext applicationContext; @Override public void setApplicationContext(ApplicationContext ctx) throws BeansException { applicationContext = ctx; } }
UTF-8
Java
897
java
SpringContextHolder.java
Java
[ { "context": "ot an example of best design.</b>\r\n * \r\n * @author Denis G. Krylov\r\n * \r\n */\r\npublic final class SpringContextHolder", "end": 609, "score": 0.9998809099197388, "start": 594, "tag": "NAME", "value": "Denis G. Krylov" } ]
null
[]
/** * */ package edu.wustl.catissuecore.util; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import edu.wustl.catissuecore.bizlogic.ccts.RegistrationPersistenceListener; /** * Utility class that helps other classes, which are not managed by Spring (such * as {@link RegistrationPersistenceListener}, to obtain * {@link ApplicationContext} reference. <b>Try not to rely on this class too * much; it's not an example of best design.</b> * * @author <NAME> * */ public final class SpringContextHolder implements ApplicationContextAware { public static ApplicationContext applicationContext; @Override public void setApplicationContext(ApplicationContext ctx) throws BeansException { applicationContext = ctx; } }
888
0.756968
0.756968
32
26.03125
28.452246
80
false
false
0
0
0
0
0
0
0.59375
false
false
2
34cffa136d6aaa4f5aa584e0a7e85c92183286ac
23,811,298,689,106
679733a04b82790f73d0dfe6f224ccfaac375110
/BrainFuck Tiny IDE/BF/src/runner/ClientRunner.java
5194f0398ec6c4a04f41e8d8a33d16590712a553
[]
no_license
Aneureka/nju-exp
https://github.com/Aneureka/nju-exp
c690ea8c57960c7e8bf51d81814de2a61c75e3ea
9d5e2000c117cf10c1187e260dc983562d7a5464
refs/heads/master
2018-10-10T04:20:44.736000
2018-07-14T17:10:18
2018-07-14T17:10:18
96,423,095
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package runner; import java.net.MalformedURLException; import java.rmi.Naming; import java.rmi.NotBoundException; import java.rmi.RemoteException; import rmi.RemoteHelper; import service.IOService; import ui.MainFrame; /** * @author GuoHaobin * 用户对接方面,实现了登入,登出,注册功能,用户注册后为其生成以用户名命名的文件夹,供其存储文件,这里预先存储用户名为"admin",密码为"123456"。 * 里面预先存储了"Helloworld","一位数加法","一位数乘法"的测试代码。 * 用户登录后,Account按钮会变成以用户名命名的按钮,用户可以双击以登出,当鼠标移到用户名按钮时会给出气泡提示。 * 操作体验方面,未登录时,用户可以进行新建、运行等操作,但不能进行打开文件,保存文件等操作,因为其没有申请自己的存储空间。 * 实现版本功能,用户可以多次保存不同版本的代码。 * 实现了undo,redo功能,逻辑基本与eclipse(模拟对象)相同,第一次undo需要操作两次,针对这点,第一次点击undo时会给出提示,当用户再次点击时提示消失。 * Yeah! **/ public class ClientRunner { private RemoteHelper remoteHelper; public ClientRunner() { linkToServer(); initGUI(); } private void linkToServer() { try { remoteHelper = RemoteHelper.getInstance(); remoteHelper.setRemote(Naming.lookup("rmi://localhost:8888/DataRemoteObject")); System.out.println("linked"); } catch (MalformedURLException e) { e.printStackTrace(); } catch (RemoteException e) { e.printStackTrace(); } catch (NotBoundException e) { e.printStackTrace(); } } private void initGUI() { MainFrame mainFrame = new MainFrame(); } public static void main(String[] args){ ClientRunner cr = new ClientRunner(); } }
UTF-8
Java
1,876
java
ClientRunner.java
Java
[ { "context": "ce.IOService;\nimport ui.MainFrame;\n\n/**\n * @author GuoHaobin\n * 用户对接方面,实现了登入,登出,注册功能,用户注册后为其生成以用户名命名的文件夹,供其存储文", "end": 246, "score": 0.8513582348823547, "start": 237, "tag": "NAME", "value": "GuoHaobin" }, { "context": "了登入,登出,注册功能,用户注册后为其生成以用户名命名的文件夹,供其存储文件,这里预先存储用户名为\"admin\",密码为\"123456\"。\n * 里面预先存储了\"Helloworld\",\"一位数加法\",\"一位数", "end": 314, "score": 0.9368804097175598, "start": 309, "tag": "USERNAME", "value": "admin" }, { "context": ",用户注册后为其生成以用户名命名的文件夹,供其存储文件,这里预先存储用户名为\"admin\",密码为\"123456\"。\n * 里面预先存储了\"Helloworld\",\"一位数加法\",\"一位数乘法\"的测试代码。\n *", "end": 326, "score": 0.9992555975914001, "start": 320, "tag": "PASSWORD", "value": "123456" } ]
null
[]
package runner; import java.net.MalformedURLException; import java.rmi.Naming; import java.rmi.NotBoundException; import java.rmi.RemoteException; import rmi.RemoteHelper; import service.IOService; import ui.MainFrame; /** * @author GuoHaobin * 用户对接方面,实现了登入,登出,注册功能,用户注册后为其生成以用户名命名的文件夹,供其存储文件,这里预先存储用户名为"admin",密码为"<PASSWORD>"。 * 里面预先存储了"Helloworld","一位数加法","一位数乘法"的测试代码。 * 用户登录后,Account按钮会变成以用户名命名的按钮,用户可以双击以登出,当鼠标移到用户名按钮时会给出气泡提示。 * 操作体验方面,未登录时,用户可以进行新建、运行等操作,但不能进行打开文件,保存文件等操作,因为其没有申请自己的存储空间。 * 实现版本功能,用户可以多次保存不同版本的代码。 * 实现了undo,redo功能,逻辑基本与eclipse(模拟对象)相同,第一次undo需要操作两次,针对这点,第一次点击undo时会给出提示,当用户再次点击时提示消失。 * Yeah! **/ public class ClientRunner { private RemoteHelper remoteHelper; public ClientRunner() { linkToServer(); initGUI(); } private void linkToServer() { try { remoteHelper = RemoteHelper.getInstance(); remoteHelper.setRemote(Naming.lookup("rmi://localhost:8888/DataRemoteObject")); System.out.println("linked"); } catch (MalformedURLException e) { e.printStackTrace(); } catch (RemoteException e) { e.printStackTrace(); } catch (NotBoundException e) { e.printStackTrace(); } } private void initGUI() { MainFrame mainFrame = new MainFrame(); } public static void main(String[] args){ ClientRunner cr = new ClientRunner(); } }
1,880
0.738931
0.731298
56
22.392857
21.867849
87
false
false
0
0
0
0
0
0
1.321429
false
false
2
5bf843c997db5a6f813bbc5eca7b342a3324c917
14,439,680,060,567
0a2c662a78767e27ba7fabb546f630fb28832803
/src/ta/NotaController.java
99b4aa71ffec6e40f172faecf3b361c43cb3f798
[]
no_license
IsvadhaPutri/TugasAkhirPBOIsvadhaPutri
https://github.com/IsvadhaPutri/TugasAkhirPBOIsvadhaPutri
c16ef865f75309fe77a0c20a1421c83eca425e59
cc0ef741765faf27452fb6799a34ded5246986d2
refs/heads/master
2021-08-23T01:59:25.904000
2017-12-02T10:14:21
2017-12-02T10:14:21
112,831,409
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 ta; import com.jfoenix.controls.JFXTextArea; import static com.sun.javafx.animation.TickCalculation.sub; import java.net.URL; import java.util.ResourceBundle; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.Button; import javafx.scene.control.TextArea; import javafx.scene.control.TextField; /** * FXML Controller class * * @author HP */ public class NotaController implements Initializable { @FXML private TextField total; @FXML private JFXTextArea barangyangdibeli; @FXML private Button proses; @FXML private TextField bayar; @FXML private TextField kembalian; String byr, totalll; int sisa; @Override public void initialize(URL url, ResourceBundle rb) { // TODO } @FXML void tekanproses(ActionEvent event) { String byr = bayar.getText(); totalll = total.getText(); sisa = Integer.parseInt(byr) - Integer.parseInt(totalll); kembalian.setText(String.valueOf(sisa)); } void setdata(int jml1, int jml2, int jml3, int jml4, int jml5, int jml6) { barangyangdibeli.setText(String.valueOf("Lightstick = "+jml1+"\n" + "Clock = "+jml2+"\n" + "Jacket = "+jml3+"\n" + "Phone Case = "+jml4+"\n" + "Key Chain = "+jml5+"\n" + "Album = "+jml6)); total.setText(String.valueOf(jml1 + jml2 + jml3 + jml4 + jml5 + jml6)); } }
UTF-8
Java
1,819
java
NotaController.java
Java
[ { "context": ";\r\n\r\n/**\r\n * FXML Controller class\r\n *\r\n * @author HP\r\n */\r\npublic class NotaController implements Init", "end": 625, "score": 0.9933472275733948, "start": 623, "tag": "USERNAME", "value": "HP" } ]
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 ta; import com.jfoenix.controls.JFXTextArea; import static com.sun.javafx.animation.TickCalculation.sub; import java.net.URL; import java.util.ResourceBundle; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.Button; import javafx.scene.control.TextArea; import javafx.scene.control.TextField; /** * FXML Controller class * * @author HP */ public class NotaController implements Initializable { @FXML private TextField total; @FXML private JFXTextArea barangyangdibeli; @FXML private Button proses; @FXML private TextField bayar; @FXML private TextField kembalian; String byr, totalll; int sisa; @Override public void initialize(URL url, ResourceBundle rb) { // TODO } @FXML void tekanproses(ActionEvent event) { String byr = bayar.getText(); totalll = total.getText(); sisa = Integer.parseInt(byr) - Integer.parseInt(totalll); kembalian.setText(String.valueOf(sisa)); } void setdata(int jml1, int jml2, int jml3, int jml4, int jml5, int jml6) { barangyangdibeli.setText(String.valueOf("Lightstick = "+jml1+"\n" + "Clock = "+jml2+"\n" + "Jacket = "+jml3+"\n" + "Phone Case = "+jml4+"\n" + "Key Chain = "+jml5+"\n" + "Album = "+jml6)); total.setText(String.valueOf(jml1 + jml2 + jml3 + jml4 + jml5 + jml6)); } }
1,819
0.605827
0.595932
69
24.362318
21.824711
79
false
false
0
0
0
0
0
0
0.492754
false
false
2
1b6080bf2b82f1a7a9b32d575d3d0662951d72e8
1,769,526,559,191
1a360fc8939a1cc9a848b5de887b08a8593b74ee
/leetCode/Medium/M_Leetcode783.java
b66caaacc360c6aafe5d664277e1dc7df1d804cc
[]
no_license
soumya27/CodingPractice
https://github.com/soumya27/CodingPractice
1cbfc07ca620059e0c579c232c71e59a0d99ab99
d4058b598a4709c72b36d572132beb43496bd4b6
refs/heads/master
2020-06-24T05:59:04.182000
2020-05-12T20:30:55
2020-05-12T20:30:55
198,869,801
0
0
null
false
2020-01-04T06:36:59
2019-07-25T16:53:57
2019-11-07T06:47:06
2020-01-04T06:36:58
72
0
0
0
Java
false
false
//Link:https://leetcode.com/problems/minimum-distance-between-bst-nodes/ package leetCode.Medium; import java.util.ArrayList; import java.util.List; public class M_Leetcode783 { private static class TreeNode { int val ; TreeNode left; TreeNode right; TreeNode(int val){ this.val = val; } } List<Integer> bstArray = new ArrayList<>(); private void createArray (TreeNode root){ if( root == null) return ; createArray(root.left); bstArray.add(root.val); createArray(root.right); } public int minDiffInBST(TreeNode root) { //Inorder --> array ( sorted ) createArray(root); int min = Integer.MAX_VALUE; for(int i = 1 ; i <bstArray.size(); i++){ min = Math.min(min, Math.subtractExact(bstArray.get(i),bstArray.get(i-1))); } return min; } public static void main(String[] args) { TreeNode root = new TreeNode(4); root.left = new TreeNode(2); root.right = new TreeNode(6); root.left.left = new TreeNode(1); root.left.right = new TreeNode(3); System.out.println(new M_Leetcode783().minDiffInBST(root)); } }
UTF-8
Java
1,247
java
M_Leetcode783.java
Java
[]
null
[]
//Link:https://leetcode.com/problems/minimum-distance-between-bst-nodes/ package leetCode.Medium; import java.util.ArrayList; import java.util.List; public class M_Leetcode783 { private static class TreeNode { int val ; TreeNode left; TreeNode right; TreeNode(int val){ this.val = val; } } List<Integer> bstArray = new ArrayList<>(); private void createArray (TreeNode root){ if( root == null) return ; createArray(root.left); bstArray.add(root.val); createArray(root.right); } public int minDiffInBST(TreeNode root) { //Inorder --> array ( sorted ) createArray(root); int min = Integer.MAX_VALUE; for(int i = 1 ; i <bstArray.size(); i++){ min = Math.min(min, Math.subtractExact(bstArray.get(i),bstArray.get(i-1))); } return min; } public static void main(String[] args) { TreeNode root = new TreeNode(4); root.left = new TreeNode(2); root.right = new TreeNode(6); root.left.left = new TreeNode(1); root.left.right = new TreeNode(3); System.out.println(new M_Leetcode783().minDiffInBST(root)); } }
1,247
0.582197
0.571772
48
24.979166
20.425158
87
false
false
0
0
0
0
0
0
0.541667
false
false
2
66f923cc1a7ea282cb1ef323bc4aac47da01c4e7
6,073,083,776,595
21017a76c972c0d1220bba05a9ffeb75fa620403
/Entidades/CAPESEntidades/src/main/java/br/com/sicoob/capes/negocio/entidades/bemantigo/BemImovel.java
84a02d470327edec54c33539b8cdde6532f37841
[]
no_license
pabllo007/cpes
https://github.com/pabllo007/cpes
a1b3b8920c9b591b702156ae36663483cd62a880
f4fc8dce3d487df89ac8f88c41023bc8db91b0c2
refs/heads/master
2022-11-28T02:55:07.675000
2019-10-27T22:17:53
2019-10-27T22:17:53
217,923,554
0
0
null
false
2022-11-24T06:24:02
2019-10-27T22:13:09
2019-10-27T22:19:30
2022-11-24T06:23:59
3,963
0
0
6
Java
false
false
/* * SICOOB * * BemImovel.java(br.com.sicoob.capes.negocio.entidades.bemantigo.BemImovel) */ package br.com.sicoob.capes.negocio.entidades.bemantigo; import javax.persistence.Entity; import javax.persistence.Table; import br.com.sicoob.capes.comum.negocio.annotation.NaoVerificarGestorResponsavel; import br.com.sicoob.capes.negocio.entidades.interfaces.Vigente; /** * The Class BemImovel. */ @Entity(name = "BEMIMOVELANTIGO") @Table(name = "BEMPESSOAIMOVEL", schema = "CLI") @NaoVerificarGestorResponsavel public class BemImovel extends BemImovelBase implements Vigente { /** * */ private static final long serialVersionUID = 1L; }
UTF-8
Java
652
java
BemImovel.java
Java
[]
null
[]
/* * SICOOB * * BemImovel.java(br.com.sicoob.capes.negocio.entidades.bemantigo.BemImovel) */ package br.com.sicoob.capes.negocio.entidades.bemantigo; import javax.persistence.Entity; import javax.persistence.Table; import br.com.sicoob.capes.comum.negocio.annotation.NaoVerificarGestorResponsavel; import br.com.sicoob.capes.negocio.entidades.interfaces.Vigente; /** * The Class BemImovel. */ @Entity(name = "BEMIMOVELANTIGO") @Table(name = "BEMPESSOAIMOVEL", schema = "CLI") @NaoVerificarGestorResponsavel public class BemImovel extends BemImovelBase implements Vigente { /** * */ private static final long serialVersionUID = 1L; }
652
0.768405
0.766871
28
22.321428
26.311396
82
false
false
0
0
0
0
0
0
0.392857
false
false
2
afc0d7f285a8045b120b865e932991a8f4123760
18,391,049,998,631
44e91f60f37ce21a050125237b947dc89f5a7192
/MyDream_SJC_11/app/src/main/java/myway/sbs11/com/myapplication/MainActivity.java
8c46e791304232ec39b14f3a77c37a6e57490696
[]
no_license
luxdolorosa/omentandp
https://github.com/luxdolorosa/omentandp
e1a1746c4d769ab85f1159092d034201183a4f26
c395dd54865de113d441a6a6ff271582e4255180
refs/heads/master
2017-12-20T00:58:43.594000
2017-01-11T17:58:20
2017-01-11T17:58:20
76,620,124
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package myway.sbs11.com.myapplication; import android.app.Activity; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.widget.TextView; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; public class MainActivity extends Activity { TextView textView; // 출력할 textView @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textView = (TextView) findViewById(R.id.textview); // 텍스트뷰 객체 참조 new JsonLoadingTask().execute(); } /** * 원격의 데이터를 가지고 JSON 객체를 생성한 다음에 객체에서 데이터 타입별로 데이터를 읽어서 StringBuffer에 추가한다. */ public String getJsonText() { // 내부적으로 문자열 편집이 가능한 StringBuffer 생성자 StringBuffer sb = new StringBuffer(); try { String line = getStringFromUrl("http://192.168.116.1:8080/userList"); // 원격에서 읽어온 데이터로 JSON 객체 생성 JSONObject object = new JSONObject(line); Log.d("data>>>>", object + ""); // "data" 배열로 구성 되어있으므로 JSON 배열생성 JSONArray Array = new JSONArray(object.getString("data")); for (int i = 0; i < Array.length(); i++) { // bodylist 배열안에 내부 JSON 이므로 JSON 내부 객체 생성 JSONObject insideObject = Array.getJSONObject(i); sb.append("유저넘버 : ").append(insideObject.getString("userSeq")).append("\n"); sb.append("유저이름 : ").append(insideObject.getString("userNm")).append("\n"); sb.append("유저아이디 : ").append(insideObject.getString("userId")).append("\n"); sb.append("유저나이 : ").append(insideObject.getString("userAge")).append("\n"); sb.append("\n"); } // for } catch (JSONException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } return sb.toString(); } // getJsonText // getStringFromUrl : 주어진 URL 페이지를 문자열로 얻는다. public String getStringFromUrl(String url) throws UnsupportedEncodingException { // 입력스트림을 "UTF-8" 를 사용해서 읽은 후, 라인 단위로 데이터를 읽을 수 있는 BufferedReader 를 생성한다. BufferedReader br = new BufferedReader(new InputStreamReader(getInputStreamFromUrl(url), "UTF-8")); // 읽은 데이터를 저장한 StringBuffer 를 생성한다. StringBuffer sb = new StringBuffer(); try { // 라인 단위로 읽은 데이터를 임시 저장한 문자열 변수 line String line = null; // 라인 단위로 데이터를 읽어서 StringBuffer 에 저장한다. while ((line = br.readLine()) != null) { sb.append(line); } } catch (Exception e) { e.printStackTrace(); } return sb.toString(); } // getStringFromUrl // getInputStreamFromUrl : 주어진 URL 에 대한 입력 스트림(InputStream)을 얻는다. public static InputStream getInputStreamFromUrl(String url) { InputStream contentStream = null; try { // HttpClient 를 사용해서 주어진 URL에 대한 입력 스트림을 얻는다. HttpClient httpclient = new DefaultHttpClient(); HttpResponse response = httpclient.execute(new HttpGet(url)); contentStream = response.getEntity().getContent(); } catch (Exception e) { e.printStackTrace(); } return contentStream; } // getInputStreamFromUrl // AsyncTask 를 이용 UI 처리 및 Background 작업 등을 하나의 클래스에서 작업 할 수 있도록 지원해준다. private class JsonLoadingTask extends AsyncTask<String, Void, String> { @Override protected String doInBackground (String...strs){ return getJsonText(); } // doInBackground : 백그라운드 작업을 진행한다. @Override protected void onPostExecute (String result){ textView.setText(result); } // onPostExecute : 백그라운드 작업이 끝난 후 UI 작업을 진행한다. } // JsonLoadingTask } //class end
UTF-8
Java
4,877
java
MainActivity.java
Java
[]
null
[]
package myway.sbs11.com.myapplication; import android.app.Activity; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.widget.TextView; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; public class MainActivity extends Activity { TextView textView; // 출력할 textView @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textView = (TextView) findViewById(R.id.textview); // 텍스트뷰 객체 참조 new JsonLoadingTask().execute(); } /** * 원격의 데이터를 가지고 JSON 객체를 생성한 다음에 객체에서 데이터 타입별로 데이터를 읽어서 StringBuffer에 추가한다. */ public String getJsonText() { // 내부적으로 문자열 편집이 가능한 StringBuffer 생성자 StringBuffer sb = new StringBuffer(); try { String line = getStringFromUrl("http://192.168.116.1:8080/userList"); // 원격에서 읽어온 데이터로 JSON 객체 생성 JSONObject object = new JSONObject(line); Log.d("data>>>>", object + ""); // "data" 배열로 구성 되어있으므로 JSON 배열생성 JSONArray Array = new JSONArray(object.getString("data")); for (int i = 0; i < Array.length(); i++) { // bodylist 배열안에 내부 JSON 이므로 JSON 내부 객체 생성 JSONObject insideObject = Array.getJSONObject(i); sb.append("유저넘버 : ").append(insideObject.getString("userSeq")).append("\n"); sb.append("유저이름 : ").append(insideObject.getString("userNm")).append("\n"); sb.append("유저아이디 : ").append(insideObject.getString("userId")).append("\n"); sb.append("유저나이 : ").append(insideObject.getString("userAge")).append("\n"); sb.append("\n"); } // for } catch (JSONException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } return sb.toString(); } // getJsonText // getStringFromUrl : 주어진 URL 페이지를 문자열로 얻는다. public String getStringFromUrl(String url) throws UnsupportedEncodingException { // 입력스트림을 "UTF-8" 를 사용해서 읽은 후, 라인 단위로 데이터를 읽을 수 있는 BufferedReader 를 생성한다. BufferedReader br = new BufferedReader(new InputStreamReader(getInputStreamFromUrl(url), "UTF-8")); // 읽은 데이터를 저장한 StringBuffer 를 생성한다. StringBuffer sb = new StringBuffer(); try { // 라인 단위로 읽은 데이터를 임시 저장한 문자열 변수 line String line = null; // 라인 단위로 데이터를 읽어서 StringBuffer 에 저장한다. while ((line = br.readLine()) != null) { sb.append(line); } } catch (Exception e) { e.printStackTrace(); } return sb.toString(); } // getStringFromUrl // getInputStreamFromUrl : 주어진 URL 에 대한 입력 스트림(InputStream)을 얻는다. public static InputStream getInputStreamFromUrl(String url) { InputStream contentStream = null; try { // HttpClient 를 사용해서 주어진 URL에 대한 입력 스트림을 얻는다. HttpClient httpclient = new DefaultHttpClient(); HttpResponse response = httpclient.execute(new HttpGet(url)); contentStream = response.getEntity().getContent(); } catch (Exception e) { e.printStackTrace(); } return contentStream; } // getInputStreamFromUrl // AsyncTask 를 이용 UI 처리 및 Background 작업 등을 하나의 클래스에서 작업 할 수 있도록 지원해준다. private class JsonLoadingTask extends AsyncTask<String, Void, String> { @Override protected String doInBackground (String...strs){ return getJsonText(); } // doInBackground : 백그라운드 작업을 진행한다. @Override protected void onPostExecute (String result){ textView.setText(result); } // onPostExecute : 백그라운드 작업이 끝난 후 UI 작업을 진행한다. } // JsonLoadingTask } //class end
4,877
0.622722
0.618225
124
33.072582
26.060158
107
false
false
0
0
0
0
0
0
0.459677
false
false
2
a80df839377b9a3ac6e1f4f9bea2820a9a9a55c8
23,751,169,154,912
8698d2e8aad9108aa965c20da0730e81038b9799
/src/quest4/Aircraft/contain/Wing.java
56ffad9385a80bf28cf984e208f57ab63c7a4b24
[]
no_license
dnaroid/quest4
https://github.com/dnaroid/quest4
24997ad8c26587fcf119783b4a0d2ec81cb51b61
caed9ef44be72b21b7e9ead15e3fbdccb9fd96b3
refs/heads/master
2021-01-10T18:31:50.923000
2016-02-03T14:06:07
2016-02-03T14:06:07
50,999,972
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package quest4.Aircraft.contain; public class Wing { private int id; public Wing(int id){ this.id = id; } @Override public String toString() { return getClass().getName() + "@id:" + id; } @Override public boolean equals(Object a){ if(this == a) return true; if(a == null) return false; if(getClass() != a.getClass()) return false; Wing other = (Wing)a; return (other.id == id); } @Override public int hashCode(){ return id; } }
UTF-8
Java
563
java
Wing.java
Java
[]
null
[]
package quest4.Aircraft.contain; public class Wing { private int id; public Wing(int id){ this.id = id; } @Override public String toString() { return getClass().getName() + "@id:" + id; } @Override public boolean equals(Object a){ if(this == a) return true; if(a == null) return false; if(getClass() != a.getClass()) return false; Wing other = (Wing)a; return (other.id == id); } @Override public int hashCode(){ return id; } }
563
0.51865
0.516874
28
18.964285
14.736937
52
false
false
0
0
0
0
0
0
0.357143
false
false
2
531bd3f46d9813e2a1d4bee9186dba40c53a50bf
23,751,169,153,403
0c8d02c7e636d18be2dec5854f2f1b8fa6db27a0
/src/main/java/com/wangchong/seckill/config/RedisSessionConfig.java
c5a505e1493f9b09c14077777c9c6376d740174c
[]
no_license
wangchong123/seckill
https://github.com/wangchong123/seckill
badb7719bd0cd00d7b5986f2460e3080466cff2c
a31df69c2e037d43c359f2541d630d20a735fe1a
refs/heads/master
2020-03-27T17:41:58.945000
2018-09-07T02:40:15
2018-09-07T02:40:15
146,867,633
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.wangchong.seckill.config; import org.springframework.context.annotation.Configuration; import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession; /** * @Author: wangchong * @Description * @Date : Created in 14:00 2018/9/3 */ @Configuration @EnableRedisHttpSession public class RedisSessionConfig { }
UTF-8
Java
356
java
RedisSessionConfig.java
Java
[ { "context": ".web.http.EnableRedisHttpSession;\n\n/**\n * @Author: wangchong\n * @Description\n * @Date : Created in 14:00 2018/", "end": 223, "score": 0.9992309808731079, "start": 214, "tag": "USERNAME", "value": "wangchong" } ]
null
[]
package com.wangchong.seckill.config; import org.springframework.context.annotation.Configuration; import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession; /** * @Author: wangchong * @Description * @Date : Created in 14:00 2018/9/3 */ @Configuration @EnableRedisHttpSession public class RedisSessionConfig { }
356
0.797753
0.769663
14
24.428572
26.220804
96
false
false
0
0
0
0
0
0
0.214286
false
false
2
2f11bd496321e7266016316b19b1175c4f925c5f
20,263,655,707,554
9a3c4d3ba6b1d80457616284c46a16aff7891cb9
/src/main/java/com/xuchg/mssm/tool/JedisClientSingle.java
eb45d188da26f49eac13fe436e6881dae84fb5d4
[ "Apache-2.0" ]
permissive
Waynee-jiang/xuchg
https://github.com/Waynee-jiang/xuchg
0eb445380f2d9faa25093e2d0698c93f7157b8f5
a04e401cbf8acf4115714db8f1ebb5402f508846
refs/heads/master
2021-08-31T18:01:23.540000
2017-12-22T09:03:08
2017-12-22T09:03:08
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.xuchg.mssm.tool; import org.springframework.context.annotation.Bean; import org.springframework.stereotype.Service; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool; /** * redis 操作service. * 假设将用户的登录信息存储在redis中,初始设置一个失效时间, * 如果在失效时间内用户有请求信息,则刷新失效时间,如果在失 * 效时间内用户未再有任何请求,则视为用户下线,key被自动删除 * @author xuchg1 * */ @Service public class JedisClientSingle implements JedisClient { /** * redis 的key过期时间 */ protected static Integer KEY_ALIVE_SECOND = 60*60; @Bean public JedisPool getJedisPool(){ return new JedisPool("47.94.217.138",6379); } public String get(String key) { Jedis jedis = getJedisPool().getResource(); String string = jedis.get(key); if(string != null){ jedis.expire(key, KEY_ALIVE_SECOND); } jedis.close(); return string; } public String set(String key, String value) { Jedis jedis = getJedisPool().getResource(); String string = jedis.set(key, value); /** * 思路:当存储进redis,设置其key存活时间,而当get key的时候再刷新其存活时间 */ if(string.toLowerCase().equals("ok")){ jedis.expire(key, KEY_ALIVE_SECOND); } jedis.close(); return string; } public String hget(String hkey, String key) { System.out.println("jedisPool "+getJedisPool()); Jedis jedis = getJedisPool().getResource(); System.out.println("jedis "+jedis); String string = jedis.hget(hkey, key); jedis.close(); return string; } public long hset(String hkey, String key, String value) { Jedis jedis = getJedisPool().getResource(); Long result = jedis.hset(hkey, key, value); jedis.close(); return result; } public long incr(String key) { Jedis jedis = getJedisPool().getResource(); Long result = jedis.incr(key); jedis.close(); return result; } public long expire(String key, int second) { Jedis jedis = getJedisPool().getResource(); Long result = jedis.expire(key, second); jedis.close(); return result; } public long ttl(String key) { Jedis jedis = getJedisPool().getResource(); Long result = jedis.ttl(key); jedis.close(); return result; } public long del(String key) { Jedis jedis = getJedisPool().getResource(); Long result = jedis.del(key); jedis.close(); return result; } public long hdel(String hkey, String key) { Jedis jedis = getJedisPool().getResource(); Long result = jedis.hdel(hkey,key); jedis.close(); return result; } public String set(byte[] key, byte[] value) { Jedis jedis = getJedisPool().getResource(); String string = jedis.set(key, value); if(string.toLowerCase().equals("ok")){ jedis.expire(key, KEY_ALIVE_SECOND); } jedis.close(); return string; } public byte[] get(byte[] key) { Jedis jedis = getJedisPool().getResource(); byte[] value = jedis.get(key); if(value.length>0){ jedis.expire(key, KEY_ALIVE_SECOND); } jedis.close(); return value; } public long del(byte[] key) { Jedis jedis = getJedisPool().getResource(); Long result = jedis.del(key); jedis.close(); return result; } }
UTF-8
Java
3,666
java
JedisClientSingle.java
Java
[ { "context": ",如果在失\n * 效时间内用户未再有任何请求,则视为用户下线,key被自动删除\n * @author xuchg1\n *\n */\n@Service\npublic class JedisClientSingle im", "end": 344, "score": 0.9995288848876953, "start": 338, "tag": "USERNAME", "value": "xuchg1" }, { "context": "ool getJedisPool(){\n return new JedisPool(\"47.94.217.138\",6379);\n }\n public String get(String key) {", "end": 588, "score": 0.9997473955154419, "start": 575, "tag": "IP_ADDRESS", "value": "47.94.217.138" } ]
null
[]
package com.xuchg.mssm.tool; import org.springframework.context.annotation.Bean; import org.springframework.stereotype.Service; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool; /** * redis 操作service. * 假设将用户的登录信息存储在redis中,初始设置一个失效时间, * 如果在失效时间内用户有请求信息,则刷新失效时间,如果在失 * 效时间内用户未再有任何请求,则视为用户下线,key被自动删除 * @author xuchg1 * */ @Service public class JedisClientSingle implements JedisClient { /** * redis 的key过期时间 */ protected static Integer KEY_ALIVE_SECOND = 60*60; @Bean public JedisPool getJedisPool(){ return new JedisPool("172.16.31.10",6379); } public String get(String key) { Jedis jedis = getJedisPool().getResource(); String string = jedis.get(key); if(string != null){ jedis.expire(key, KEY_ALIVE_SECOND); } jedis.close(); return string; } public String set(String key, String value) { Jedis jedis = getJedisPool().getResource(); String string = jedis.set(key, value); /** * 思路:当存储进redis,设置其key存活时间,而当get key的时候再刷新其存活时间 */ if(string.toLowerCase().equals("ok")){ jedis.expire(key, KEY_ALIVE_SECOND); } jedis.close(); return string; } public String hget(String hkey, String key) { System.out.println("jedisPool "+getJedisPool()); Jedis jedis = getJedisPool().getResource(); System.out.println("jedis "+jedis); String string = jedis.hget(hkey, key); jedis.close(); return string; } public long hset(String hkey, String key, String value) { Jedis jedis = getJedisPool().getResource(); Long result = jedis.hset(hkey, key, value); jedis.close(); return result; } public long incr(String key) { Jedis jedis = getJedisPool().getResource(); Long result = jedis.incr(key); jedis.close(); return result; } public long expire(String key, int second) { Jedis jedis = getJedisPool().getResource(); Long result = jedis.expire(key, second); jedis.close(); return result; } public long ttl(String key) { Jedis jedis = getJedisPool().getResource(); Long result = jedis.ttl(key); jedis.close(); return result; } public long del(String key) { Jedis jedis = getJedisPool().getResource(); Long result = jedis.del(key); jedis.close(); return result; } public long hdel(String hkey, String key) { Jedis jedis = getJedisPool().getResource(); Long result = jedis.hdel(hkey,key); jedis.close(); return result; } public String set(byte[] key, byte[] value) { Jedis jedis = getJedisPool().getResource(); String string = jedis.set(key, value); if(string.toLowerCase().equals("ok")){ jedis.expire(key, KEY_ALIVE_SECOND); } jedis.close(); return string; } public byte[] get(byte[] key) { Jedis jedis = getJedisPool().getResource(); byte[] value = jedis.get(key); if(value.length>0){ jedis.expire(key, KEY_ALIVE_SECOND); } jedis.close(); return value; } public long del(byte[] key) { Jedis jedis = getJedisPool().getResource(); Long result = jedis.del(key); jedis.close(); return result; } }
3,665
0.596154
0.590326
126
26.238094
18.595284
61
false
false
0
0
0
0
0
0
0.777778
false
false
2
c6e31295068a217f568d71dcff930584cdfcf4e0
20,684,562,518,093
fb0aef42a0013a5c08ae0374ab23483903d31c84
/epc-web-client/src/main/java/com/epc/web/client/remoteApi/terdering/project/ProjectHystrix.java
d9113eceeb92e17dea992c4148eb241877cc47bf
[]
no_license
techqiao/easily-purchase
https://github.com/techqiao/easily-purchase
7a132ed3ee3e7af96d0ce0cbaac887065eaea2fa
71259df0f5ae2014c1be6a8823e09d6602c3687a
refs/heads/master
2021-09-25T02:37:51.584000
2018-10-17T07:16:22
2018-10-17T07:16:22
153,409,297
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.epc.web.client.remoteApi.terdering.project; import com.epc.common.Result; import com.epc.web.facade.terdering.project.FacadeTProjectBasicInfoService; import com.epc.web.facade.terdering.project.handle.*; import com.epc.web.facade.terdering.project.query.LoginInfo; import com.epc.web.facade.terdering.project.query.QueryProjectInfoDTO; import com.epc.web.facade.terdering.project.vo.ProjectDetailInfoVO; import com.epc.web.facade.terdering.project.vo.SelectProjectListVO; import com.epc.web.facade.terdering.project.vo.SelectProjectPurchaserListVO; import java.util.List; import java.util.Map; /** * <p>Description : easily-purchase * <p>Date : 2018-09-18 14:15 * <p>@Author : wjq */ public class ProjectHystrix implements FacadeTProjectBasicInfoService { @Override public Result<Boolean> handleProjectBasicInfo(HandleProjectBasicInfo handleProjectBasicInfo) { return Result.hystrixError(); } @Override public Result<ProjectDetailInfoVO> getProjectDetailInfo(Long projectId) { return Result.hystrixError(); } @Override public Result<Map<String, Object>> getProjectList(QueryProjectInfoDTO queryProjectInfoDTO) { return Result.hystrixError(); } @Override public Result<Boolean> createProjectByAdmin(HandleCreateProjectByAdmin handleCreateProjectByAdmin) { return Result.hystrixError(); } @Override public Result<Boolean> updateProjectAdmin(HandleUpdateProjectAdmin handleUpdateProjectAdmin) { return Result.hystrixError(); } @Override public Result<List<SelectProjectListVO>> selectProjectList(LoginInfo loginInfo) { return Result.hystrixError(); } }
UTF-8
Java
1,696
java
ProjectHystrix.java
Java
[ { "context": "hase\n * <p>Date : 2018-09-18 14:15\n * <p>@Author : wjq\n */\npublic class ProjectHystrix implements Facade", "end": 698, "score": 0.9996370673179626, "start": 695, "tag": "USERNAME", "value": "wjq" } ]
null
[]
package com.epc.web.client.remoteApi.terdering.project; import com.epc.common.Result; import com.epc.web.facade.terdering.project.FacadeTProjectBasicInfoService; import com.epc.web.facade.terdering.project.handle.*; import com.epc.web.facade.terdering.project.query.LoginInfo; import com.epc.web.facade.terdering.project.query.QueryProjectInfoDTO; import com.epc.web.facade.terdering.project.vo.ProjectDetailInfoVO; import com.epc.web.facade.terdering.project.vo.SelectProjectListVO; import com.epc.web.facade.terdering.project.vo.SelectProjectPurchaserListVO; import java.util.List; import java.util.Map; /** * <p>Description : easily-purchase * <p>Date : 2018-09-18 14:15 * <p>@Author : wjq */ public class ProjectHystrix implements FacadeTProjectBasicInfoService { @Override public Result<Boolean> handleProjectBasicInfo(HandleProjectBasicInfo handleProjectBasicInfo) { return Result.hystrixError(); } @Override public Result<ProjectDetailInfoVO> getProjectDetailInfo(Long projectId) { return Result.hystrixError(); } @Override public Result<Map<String, Object>> getProjectList(QueryProjectInfoDTO queryProjectInfoDTO) { return Result.hystrixError(); } @Override public Result<Boolean> createProjectByAdmin(HandleCreateProjectByAdmin handleCreateProjectByAdmin) { return Result.hystrixError(); } @Override public Result<Boolean> updateProjectAdmin(HandleUpdateProjectAdmin handleUpdateProjectAdmin) { return Result.hystrixError(); } @Override public Result<List<SelectProjectListVO>> selectProjectList(LoginInfo loginInfo) { return Result.hystrixError(); } }
1,696
0.763561
0.756486
52
31.615385
32.154167
104
false
false
0
0
0
0
0
0
0.346154
false
false
2
78129da1a0263e895da69776d3c601234854e75f
21,569,325,791,594
1f0251b47318cc1836b4b6536409c4f4548ecd37
/src/main/java/ee/ttu/shop/order/Order.java
b7539e17d5b56ed3fbe0f4c96e6649832964c177
[]
no_license
bedmansz/server-side
https://github.com/bedmansz/server-side
09b693d14602b818992aac6c86f0d18eb0ac6205
1976601c1fa9b42f6a74fa3ca32c71a4558dbe80
refs/heads/master
2017-12-07T11:05:33.578000
2017-01-20T16:21:31
2017-01-20T16:21:31
79,574,838
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ee.ttu.shop.order; import java.io.Serializable; import java.math.BigDecimal; import java.sql.Timestamp; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import ee.ttu.shop.user.User; public class Order implements Serializable{ /** * */ private static final long serialVersionUID = -8281287513065091365L; public static int OrderItemLimit = 3; private int id; private Timestamp creationDate; private String first_name; private String last_name; private String phone; private String email; private String address; private User user; private Order_status order_status; private List<OrderItem> orderItems = new ArrayList<>(); //private String order_status_name="Unpaid"; public Order(){ order_status = new Order_status(); order_status.setId(1); order_status.setName("Unpaid"); } public Timestamp getCreationDate() { return creationDate; } public void setCreationDate(Timestamp creationDate) { this.creationDate = creationDate; } public String getFirst_name() { return first_name; } public void setFirst_name(String first_name) { this.first_name = first_name; } public String getLast_name() { return last_name; } public void setLast_name(String last_name) { this.last_name = last_name; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } /* public boolean isIs_client() { return is_client; } public void setIs_client(boolean is_client) { this.is_client = is_client; } public boolean isIs_employee() { return is_employee; } public void setIs_employee(boolean is_employee) { this.is_employee = is_employee; } */ public User getUser() { return user; } public void setUser(User user) { this.user = user; } public Order_status getOrder_status() { return order_status; } public void setOrder_status(Order_status order_status) { this.order_status = order_status; } public List<OrderItem> getOrderItems() { return orderItems; } public void setOrderItems(List<OrderItem> orderItems) { this.orderItems = orderItems; } /*public String getOrder_status_name() { return order_status_name; } public void setOrder_status_name(String order_status_name) { this.order_status_name = order_status_name; }*/ public int getId() { return id; } public void setId(int id) { this.id = id; } }
UTF-8
Java
2,644
java
Order.java
Java
[]
null
[]
package ee.ttu.shop.order; import java.io.Serializable; import java.math.BigDecimal; import java.sql.Timestamp; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import ee.ttu.shop.user.User; public class Order implements Serializable{ /** * */ private static final long serialVersionUID = -8281287513065091365L; public static int OrderItemLimit = 3; private int id; private Timestamp creationDate; private String first_name; private String last_name; private String phone; private String email; private String address; private User user; private Order_status order_status; private List<OrderItem> orderItems = new ArrayList<>(); //private String order_status_name="Unpaid"; public Order(){ order_status = new Order_status(); order_status.setId(1); order_status.setName("Unpaid"); } public Timestamp getCreationDate() { return creationDate; } public void setCreationDate(Timestamp creationDate) { this.creationDate = creationDate; } public String getFirst_name() { return first_name; } public void setFirst_name(String first_name) { this.first_name = first_name; } public String getLast_name() { return last_name; } public void setLast_name(String last_name) { this.last_name = last_name; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } /* public boolean isIs_client() { return is_client; } public void setIs_client(boolean is_client) { this.is_client = is_client; } public boolean isIs_employee() { return is_employee; } public void setIs_employee(boolean is_employee) { this.is_employee = is_employee; } */ public User getUser() { return user; } public void setUser(User user) { this.user = user; } public Order_status getOrder_status() { return order_status; } public void setOrder_status(Order_status order_status) { this.order_status = order_status; } public List<OrderItem> getOrderItems() { return orderItems; } public void setOrderItems(List<OrderItem> orderItems) { this.orderItems = orderItems; } /*public String getOrder_status_name() { return order_status_name; } public void setOrder_status_name(String order_status_name) { this.order_status_name = order_status_name; }*/ public int getId() { return id; } public void setId(int id) { this.id = id; } }
2,644
0.712935
0.704992
128
19.65625
16.941277
68
false
false
0
0
0
0
0
0
1.484375
false
false
2
9bb0f6cfebee0c156e7996d2e752ba17a7ee9e5e
2,534,030,711,575
f1578c5fb657c59c8f80993887991612e930d84d
/BroadcastReceiver28MDemo/app/src/main/java/com/adityadua/broadcastreceiver28mdemo/MainActivity.java
6981f0eb37073c6a94e7e60bc7050557c2f328ff
[]
no_license
aditya-dua/28thMay
https://github.com/aditya-dua/28thMay
cd1c9807c97eee1eb2b3656030aa7fe2801d3fa3
d3511a62f87edc42609544b8b20d29085dd5b4ff
refs/heads/master
2020-03-19T07:32:41.101000
2018-06-26T04:53:31
2018-06-26T04:53:31
136,122,796
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.adityadua.broadcastreceiver28mdemo; import android.content.DialogInterface; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.Toast; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } @Override public void onBackPressed() { openAlert(); //super.onBackPressed(); } private void openAlert(){ AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(MainActivity.this); alertDialogBuilder.setTitle("Exit App"); alertDialogBuilder.setMessage("Are you sure you want to exit !"); alertDialogBuilder.setIcon(R.mipmap.ic_launcher); alertDialogBuilder.setPositiveButton("Yes , Exit App", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { Toast.makeText(MainActivity.this, "Exiting....", Toast.LENGTH_SHORT).show(); finish(); } }); alertDialogBuilder.setNegativeButton("No, I will use the App", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { Toast.makeText(MainActivity.this, "You may have presses back button by mistake , please continuw with your app", Toast.LENGTH_SHORT).show(); dialogInterface.cancel(); } }); AlertDialog alertDialog = alertDialogBuilder.create(); alertDialog.show(); } }
UTF-8
Java
1,758
java
MainActivity.java
Java
[ { "context": "package com.adityadua.broadcastreceiver28mdemo;\n\nimport android.content", "end": 21, "score": 0.655636191368103, "start": 12, "tag": "USERNAME", "value": "adityadua" } ]
null
[]
package com.adityadua.broadcastreceiver28mdemo; import android.content.DialogInterface; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.Toast; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } @Override public void onBackPressed() { openAlert(); //super.onBackPressed(); } private void openAlert(){ AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(MainActivity.this); alertDialogBuilder.setTitle("Exit App"); alertDialogBuilder.setMessage("Are you sure you want to exit !"); alertDialogBuilder.setIcon(R.mipmap.ic_launcher); alertDialogBuilder.setPositiveButton("Yes , Exit App", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { Toast.makeText(MainActivity.this, "Exiting....", Toast.LENGTH_SHORT).show(); finish(); } }); alertDialogBuilder.setNegativeButton("No, I will use the App", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { Toast.makeText(MainActivity.this, "You may have presses back button by mistake , please continuw with your app", Toast.LENGTH_SHORT).show(); dialogInterface.cancel(); } }); AlertDialog alertDialog = alertDialogBuilder.create(); alertDialog.show(); } }
1,758
0.668942
0.666667
53
32.169811
34.141071
156
false
false
0
0
0
0
0
0
0.622642
false
false
2
99948e107ebba6cdb8a7ae2be477434fe4ce5afa
24,601,572,687,582
cc1aa6da60313ef285679e8c586af0feab524120
/src/main/java/org/denisferreira/cleanarchitecture/designpatterns/decorator/ConcreteDecoratorB.java
c195aa656ecea5607c3aa67c5006ccd4352fde5a
[]
no_license
DenisFerreira/CleanArchitecture
https://github.com/DenisFerreira/CleanArchitecture
9db6d4379bb278315de380de38e0b504307c06d5
3aed407e651a3ef4609d6fdba714907bb834e5dd
refs/heads/main
2023-06-16T02:52:59.176000
2021-07-15T22:10:50
2021-07-15T22:10:50
382,491,936
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.denisferreira.cleanarchitecture.designpatterns.decorator; public class ConcreteDecoratorB extends BaseDecorator{ ConcreteDecoratorB(Component component) { super(component); } @Override public void execute() { System.out.print("ConcreteDecoratorB;"); super.execute(); } }
UTF-8
Java
329
java
ConcreteDecoratorB.java
Java
[]
null
[]
package org.denisferreira.cleanarchitecture.designpatterns.decorator; public class ConcreteDecoratorB extends BaseDecorator{ ConcreteDecoratorB(Component component) { super(component); } @Override public void execute() { System.out.print("ConcreteDecoratorB;"); super.execute(); } }
329
0.702128
0.702128
13
24.307692
22.31724
69
false
false
0
0
0
0
0
0
0.384615
false
false
2
852745d41848896065dad3f34c4e4e78abd14d71
7,241,314,887,230
6a925fd88d1c6b29b7249f6bb9e88be87c5f098a
/app/src/main/java/com/example/jcstange/bletemplate/Adapters/ScanActivity_Adapter.java
c7ff4dea2e5cc49df5c6b23abe8f789c31a5ee02
[]
no_license
emanuelliborio/AndroidBLETemplate
https://github.com/emanuelliborio/AndroidBLETemplate
8af2ce894001bd2f3e2654e6905a449f645aeb9f
a614a752b66837447488026a1133f814e87963a6
refs/heads/master
2020-03-27T22:25:43.370000
2017-06-20T09:14:24
2017-06-20T09:14:24
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.jcstange.bletemplate.Adapters; /** * Created by jcstange on 18/05/2017. */ import android.content.Context; import android.os.ParcelUuid; import android.support.annotation.NonNull; import android.util.SparseArray; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.LinearLayout; import android.widget.TextView; import com.example.jcstange.bletemplate.MainActivity; import com.example.jcstange.bletemplate.R; import com.example.jcstange.bletemplate.Utils.Converters; import java.util.ArrayList; import java.util.List; import java.util.Map; public class ScanActivity_Adapter extends ArrayAdapter<MainActivity.DeviceInfo> { private final Context context; private final List<MainActivity.DeviceInfo> devicesInfo; public ScanActivity_Adapter(Context context, List<MainActivity.DeviceInfo> devicesInfo) { super(context , 0); this.context = context; this.devicesInfo = devicesInfo; } static class ViewHolder { public TextView device_name; public TextView device_address; public TextView device_rssi; public LinearLayout deviceAdapter; public LinearLayout info; public LinearLayout flag_layout; public LinearLayout manuf_layout; public LinearLayout tx_layout; public TextView flag; public TextView manuf; public TextView tx; public TextView deltaT; public TextView scan_record; public Button configDevice; public int position; } @NonNull @Override public View getView(int position, View convertView, @NonNull ViewGroup parent) { LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); final ViewHolder viewHolder = new ViewHolder(); if (convertView==null){ convertView = inflater.inflate(R.layout.scanscreen_device_adapter, parent,false); } viewHolder.device_name = (TextView) convertView.findViewById(R.id.device_name); viewHolder.device_address = (TextView) convertView.findViewById(R.id.device_address); viewHolder.device_rssi = (TextView) convertView.findViewById(R.id.device_rssi); viewHolder.deviceAdapter = (LinearLayout) convertView.findViewById(R.id.device_adapter); viewHolder.info = (LinearLayout) convertView.findViewById(R.id.info); viewHolder.flag = (TextView) convertView.findViewById(R.id.flag); viewHolder.manuf = (TextView) convertView.findViewById(R.id.manuf); viewHolder.tx = (TextView) convertView.findViewById(R.id.tx); viewHolder.deltaT = (TextView) convertView.findViewById(R.id.device_delta); viewHolder.scan_record = (TextView) convertView.findViewById(R.id.scanRecord); viewHolder.position = position; viewHolder.configDevice = (Button) convertView.findViewById(R.id.config_device); viewHolder.flag_layout = (LinearLayout) convertView.findViewById(R.id.flag_layout); viewHolder.manuf_layout = (LinearLayout) convertView.findViewById(R.id.manuf_layout); viewHolder.tx_layout = (LinearLayout) convertView.findViewById(R.id.tx_layout); String deviceName = devicesInfo.get(position).device_name!=null ? devicesInfo.get(position).device_name : "Unknown"; String deviceAdress = devicesInfo.get(position).device_address; String deviceRssi = ""+devicesInfo.get(position).rssi+ " dBm "; String advFlag = devicesInfo.get(position).flag; List<ParcelUuid> serUuid = devicesInfo.get(position).uuid; SparseArray manuf_data = devicesInfo.get(position).manuf; Map<ParcelUuid, byte[]> serviceData = devicesInfo.get(position).service_data; int txPower = devicesInfo.get(position).tx; long timeStamp = devicesInfo.get(position).deltaT; final int pos = position; viewHolder.configDevice.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //meshScannerFragment.configDevice(pos); } }); viewHolder.device_name.setText(deviceName); viewHolder.device_address.setText(deviceAdress); viewHolder.device_rssi.setText(deviceRssi); ArrayList<byte[]> MD = new ArrayList<>(); MD = asList(manuf_data); if (!MD.isEmpty()) { StringBuilder message = new StringBuilder(); for (byte[] tmp : MD){ message.append(Converters.getHexValue(tmp) + "\n"); } viewHolder.manuf.setText(message); } else viewHolder.manuf_layout.setVisibility(View.GONE); if (advFlag != null ) viewHolder.flag.setText("" + advFlag); else viewHolder.flag_layout.setVisibility(View.GONE); viewHolder.deltaT.setText("" + timeStamp + " ms"); viewHolder.scan_record.setText(Converters.getHexValue(devicesInfo.get(position).scanRecord)); if (txPower > (-100)) viewHolder.tx.setText("" + txPower); else viewHolder.tx_layout.setVisibility(View.GONE); return convertView; } public static <C> ArrayList<C> asList(SparseArray<C> sparseArray) { if (sparseArray == null) return null; ArrayList arrayList = new ArrayList<C>(sparseArray.size()); for (int i = 0; i < sparseArray.size(); i++) arrayList.add(sparseArray.valueAt(i)); return arrayList; } }
UTF-8
Java
5,603
java
ScanActivity_Adapter.java
Java
[ { "context": ".jcstange.bletemplate.Adapters;\n\n/**\n * Created by jcstange on 18/05/2017.\n */\n\nimport android.content.Contex", "end": 78, "score": 0.9996792674064636, "start": 70, "tag": "USERNAME", "value": "jcstange" } ]
null
[]
package com.example.jcstange.bletemplate.Adapters; /** * Created by jcstange on 18/05/2017. */ import android.content.Context; import android.os.ParcelUuid; import android.support.annotation.NonNull; import android.util.SparseArray; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.LinearLayout; import android.widget.TextView; import com.example.jcstange.bletemplate.MainActivity; import com.example.jcstange.bletemplate.R; import com.example.jcstange.bletemplate.Utils.Converters; import java.util.ArrayList; import java.util.List; import java.util.Map; public class ScanActivity_Adapter extends ArrayAdapter<MainActivity.DeviceInfo> { private final Context context; private final List<MainActivity.DeviceInfo> devicesInfo; public ScanActivity_Adapter(Context context, List<MainActivity.DeviceInfo> devicesInfo) { super(context , 0); this.context = context; this.devicesInfo = devicesInfo; } static class ViewHolder { public TextView device_name; public TextView device_address; public TextView device_rssi; public LinearLayout deviceAdapter; public LinearLayout info; public LinearLayout flag_layout; public LinearLayout manuf_layout; public LinearLayout tx_layout; public TextView flag; public TextView manuf; public TextView tx; public TextView deltaT; public TextView scan_record; public Button configDevice; public int position; } @NonNull @Override public View getView(int position, View convertView, @NonNull ViewGroup parent) { LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); final ViewHolder viewHolder = new ViewHolder(); if (convertView==null){ convertView = inflater.inflate(R.layout.scanscreen_device_adapter, parent,false); } viewHolder.device_name = (TextView) convertView.findViewById(R.id.device_name); viewHolder.device_address = (TextView) convertView.findViewById(R.id.device_address); viewHolder.device_rssi = (TextView) convertView.findViewById(R.id.device_rssi); viewHolder.deviceAdapter = (LinearLayout) convertView.findViewById(R.id.device_adapter); viewHolder.info = (LinearLayout) convertView.findViewById(R.id.info); viewHolder.flag = (TextView) convertView.findViewById(R.id.flag); viewHolder.manuf = (TextView) convertView.findViewById(R.id.manuf); viewHolder.tx = (TextView) convertView.findViewById(R.id.tx); viewHolder.deltaT = (TextView) convertView.findViewById(R.id.device_delta); viewHolder.scan_record = (TextView) convertView.findViewById(R.id.scanRecord); viewHolder.position = position; viewHolder.configDevice = (Button) convertView.findViewById(R.id.config_device); viewHolder.flag_layout = (LinearLayout) convertView.findViewById(R.id.flag_layout); viewHolder.manuf_layout = (LinearLayout) convertView.findViewById(R.id.manuf_layout); viewHolder.tx_layout = (LinearLayout) convertView.findViewById(R.id.tx_layout); String deviceName = devicesInfo.get(position).device_name!=null ? devicesInfo.get(position).device_name : "Unknown"; String deviceAdress = devicesInfo.get(position).device_address; String deviceRssi = ""+devicesInfo.get(position).rssi+ " dBm "; String advFlag = devicesInfo.get(position).flag; List<ParcelUuid> serUuid = devicesInfo.get(position).uuid; SparseArray manuf_data = devicesInfo.get(position).manuf; Map<ParcelUuid, byte[]> serviceData = devicesInfo.get(position).service_data; int txPower = devicesInfo.get(position).tx; long timeStamp = devicesInfo.get(position).deltaT; final int pos = position; viewHolder.configDevice.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //meshScannerFragment.configDevice(pos); } }); viewHolder.device_name.setText(deviceName); viewHolder.device_address.setText(deviceAdress); viewHolder.device_rssi.setText(deviceRssi); ArrayList<byte[]> MD = new ArrayList<>(); MD = asList(manuf_data); if (!MD.isEmpty()) { StringBuilder message = new StringBuilder(); for (byte[] tmp : MD){ message.append(Converters.getHexValue(tmp) + "\n"); } viewHolder.manuf.setText(message); } else viewHolder.manuf_layout.setVisibility(View.GONE); if (advFlag != null ) viewHolder.flag.setText("" + advFlag); else viewHolder.flag_layout.setVisibility(View.GONE); viewHolder.deltaT.setText("" + timeStamp + " ms"); viewHolder.scan_record.setText(Converters.getHexValue(devicesInfo.get(position).scanRecord)); if (txPower > (-100)) viewHolder.tx.setText("" + txPower); else viewHolder.tx_layout.setVisibility(View.GONE); return convertView; } public static <C> ArrayList<C> asList(SparseArray<C> sparseArray) { if (sparseArray == null) return null; ArrayList arrayList = new ArrayList<C>(sparseArray.size()); for (int i = 0; i < sparseArray.size(); i++) arrayList.add(sparseArray.valueAt(i)); return arrayList; } }
5,603
0.685169
0.682848
136
40.198528
29.837259
124
false
false
0
0
0
0
0
0
0.713235
false
false
2
a637a64a91a7064f118a77ca61f9690ced2bfb4f
7,241,314,887,815
8c71a154a5a06909c1b4858aa54d5884019a8f43
/challenge-client/app/src/main/java/hr/foi/challenge/challengeclient/adapters/ProjectListAdapter.java
03797995441225fd29997def7f97088efa9a7941
[]
no_license
davinci2015/Challenge
https://github.com/davinci2015/Challenge
6fb8d11d995e8e5b1775f86974b880dbd6f7bc81
e11b1c04de98389ab51c5759eba96a0497b7b4fe
refs/heads/master
2021-01-10T12:50:59.745000
2015-10-12T09:00:30
2015-10-12T09:00:30
42,992,370
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package hr.foi.challenge.challengeclient.adapters; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.TextView; import java.util.List; import butterknife.Bind; import butterknife.ButterKnife; import hr.foi.challenge.challengeclient.R; import hr.foi.challenge.challengeclient.models.Project; /** * Created by Tomislav Turek on 23.09.15.. */ public class ProjectListAdapter extends ArrayAdapter<Project> { public ProjectListAdapter(Context context, List<Project> objects) { super(context, R.layout.list_item_project, objects); } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder; if(convertView == null) { convertView = LayoutInflater.from(getContext()).inflate(R.layout.list_item_project, parent, false); holder = new ViewHolder(convertView); } else { holder = (ViewHolder) convertView.getTag(); } Project project = getItem(position); holder.projectTitle.setText(project.getName()); holder.projectDesc.setText(project.getDescription()); return convertView; } static class ViewHolder { @Bind(R.id.project_title) TextView projectTitle; @Bind(R.id.project_desc) TextView projectDesc; public ViewHolder(View view) { ButterKnife.bind(this, view); view.setTag(this); } } }
UTF-8
Java
1,569
java
ProjectListAdapter.java
Java
[ { "context": "challengeclient.models.Project;\n\n/**\n * Created by Tomislav Turek on 23.09.15..\n */\npublic class ProjectListAdapter", "end": 459, "score": 0.9998916983604431, "start": 445, "tag": "NAME", "value": "Tomislav Turek" } ]
null
[]
package hr.foi.challenge.challengeclient.adapters; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.TextView; import java.util.List; import butterknife.Bind; import butterknife.ButterKnife; import hr.foi.challenge.challengeclient.R; import hr.foi.challenge.challengeclient.models.Project; /** * Created by <NAME> on 23.09.15.. */ public class ProjectListAdapter extends ArrayAdapter<Project> { public ProjectListAdapter(Context context, List<Project> objects) { super(context, R.layout.list_item_project, objects); } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder; if(convertView == null) { convertView = LayoutInflater.from(getContext()).inflate(R.layout.list_item_project, parent, false); holder = new ViewHolder(convertView); } else { holder = (ViewHolder) convertView.getTag(); } Project project = getItem(position); holder.projectTitle.setText(project.getName()); holder.projectDesc.setText(project.getDescription()); return convertView; } static class ViewHolder { @Bind(R.id.project_title) TextView projectTitle; @Bind(R.id.project_desc) TextView projectDesc; public ViewHolder(View view) { ButterKnife.bind(this, view); view.setTag(this); } } }
1,561
0.683875
0.680051
55
27.527273
24.065708
111
false
false
0
0
0
0
0
0
0.6
false
false
2
d7e0e45d2f403388bfbb012086007b56c444c177
16,157,667,013,674
b33554ba4622ce55ebf5a3bad619d338ab01712d
/android/src/main/java/top/huic/tencent_im_plugin/message/entity/SoundMessageEntity.java
3283ff4a3726c96e021d9bcfaeefeb79c48acf31
[ "Apache-2.0" ]
permissive
JiangJuHong/FlutterTencentImPlugin
https://github.com/JiangJuHong/FlutterTencentImPlugin
6e4b01ca28816bbee73aa8f89b4fd68e8daa4331
84a314326778a38de7203193b69577ee03d8b76a
refs/heads/master
2023-06-29T15:56:22.327000
2023-06-12T07:05:32
2023-06-12T07:05:32
224,773,756
228
63
Apache-2.0
false
2021-03-25T09:07:42
2019-11-29T03:58:07
2021-03-25T09:06:52
2021-03-25T09:07:41
23,283
146
44
0
Dart
false
false
package top.huic.tencent_im_plugin.message.entity; import com.tencent.imsdk.v2.V2TIMSoundElem; import top.huic.tencent_im_plugin.enums.MessageNodeType; /** * 语音消息实体 * * @author 蒋具宏 */ public class SoundMessageEntity extends AbstractMessageEntity { /** * 语音ID */ private String uuid; /** * 路径 */ private String path; /** * 时长 */ private Integer duration; /** * 数据大小 */ private Integer dataSize; public SoundMessageEntity() { super(MessageNodeType.Sound); } public SoundMessageEntity(V2TIMSoundElem elem) { super(MessageNodeType.Sound); this.setPath(elem.getPath()); this.setDuration(elem.getDuration()); this.setDataSize(elem.getDataSize()); this.setUuid(elem.getUUID()); } public String getPath() { return path; } public void setPath(String path) { this.path = path; } public Integer getDuration() { return duration; } public void setDuration(Integer duration) { this.duration = duration; } public Integer getDataSize() { return dataSize; } public void setDataSize(Integer dataSize) { this.dataSize = dataSize; } public String getUuid() { return uuid; } public void setUuid(String uuid) { this.uuid = uuid; } }
UTF-8
Java
1,433
java
SoundMessageEntity.java
Java
[ { "context": "ums.MessageNodeType;\n\n/**\n * 语音消息实体\n *\n * @author 蒋具宏\n */\npublic class SoundMessageEntity extends Abstr", "end": 186, "score": 0.9997909665107727, "start": 183, "tag": "NAME", "value": "蒋具宏" } ]
null
[]
package top.huic.tencent_im_plugin.message.entity; import com.tencent.imsdk.v2.V2TIMSoundElem; import top.huic.tencent_im_plugin.enums.MessageNodeType; /** * 语音消息实体 * * @author 蒋具宏 */ public class SoundMessageEntity extends AbstractMessageEntity { /** * 语音ID */ private String uuid; /** * 路径 */ private String path; /** * 时长 */ private Integer duration; /** * 数据大小 */ private Integer dataSize; public SoundMessageEntity() { super(MessageNodeType.Sound); } public SoundMessageEntity(V2TIMSoundElem elem) { super(MessageNodeType.Sound); this.setPath(elem.getPath()); this.setDuration(elem.getDuration()); this.setDataSize(elem.getDataSize()); this.setUuid(elem.getUUID()); } public String getPath() { return path; } public void setPath(String path) { this.path = path; } public Integer getDuration() { return duration; } public void setDuration(Integer duration) { this.duration = duration; } public Integer getDataSize() { return dataSize; } public void setDataSize(Integer dataSize) { this.dataSize = dataSize; } public String getUuid() { return uuid; } public void setUuid(String uuid) { this.uuid = uuid; } }
1,433
0.597133
0.594982
77
17.129869
17.297512
63
false
false
0
0
0
0
0
0
0.272727
false
false
2
b4e8b1122a5ca5f2d1bf20b9c9360eed797b0572
9,259,949,531,476
f89e139e41e7a0100892c93b66536adcc43d3dff
/src/main/java/com/carlos/gestorfinancas/services/ItemInvestimentoService.java
920c5d9b170c2b4b66999f7dbceb284b63c74eb5
[]
no_license
carlosdaniiel07/gestor-financas-api
https://github.com/carlosdaniiel07/gestor-financas-api
ca3cd7b0cdbe955958af5f62a0a4d56212e1da58
16d5402483c0bd35f482fdf0fe537aa0b668aa6e
refs/heads/master
2022-07-24T10:22:01.173000
2022-04-06T03:41:16
2022-04-06T03:41:16
195,544,920
1
0
null
false
2022-07-15T21:06:55
2019-07-06T13:53:41
2022-04-26T02:59:10
2022-07-15T21:06:54
521
1
0
1
Java
false
false
package com.carlos.gestorfinancas.services; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.carlos.gestorfinancas.entities.ItemInvestimento; import com.carlos.gestorfinancas.entities.enums.TipoItemInvestimento; import com.carlos.gestorfinancas.repositories.ItemInvestimentoRepository; @Service public class ItemInvestimentoService { @Autowired private ItemInvestimentoRepository repository; public ItemInvestimento insere(ItemInvestimento item) { if (item.getTipo() == TipoItemInvestimento.APLICACAO || item.getTipo() == TipoItemInvestimento.REINVESTIMENTO) { item.setIof(0); item.setIr(0); item.setOutrasTaxas(0); item.setRendimento(0); } else { // Nenhuma tratativa específica é feita quando o item é um 'RESGATE } return repository.save(item); } }
UTF-8
Java
888
java
ItemInvestimentoService.java
Java
[]
null
[]
package com.carlos.gestorfinancas.services; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.carlos.gestorfinancas.entities.ItemInvestimento; import com.carlos.gestorfinancas.entities.enums.TipoItemInvestimento; import com.carlos.gestorfinancas.repositories.ItemInvestimentoRepository; @Service public class ItemInvestimentoService { @Autowired private ItemInvestimentoRepository repository; public ItemInvestimento insere(ItemInvestimento item) { if (item.getTipo() == TipoItemInvestimento.APLICACAO || item.getTipo() == TipoItemInvestimento.REINVESTIMENTO) { item.setIof(0); item.setIr(0); item.setOutrasTaxas(0); item.setRendimento(0); } else { // Nenhuma tratativa específica é feita quando o item é um 'RESGATE } return repository.save(item); } }
888
0.771751
0.767232
27
30.777779
29.606472
114
false
false
0
0
0
0
0
0
1.592593
false
false
2
37f6d226b68ab0b239e4a6a88614670f8d04ff4a
27,797,028,364,025
db36a773fc66f49437db58fc6886dfa7ebf5d7bc
/annis-service/src/main/java/annis/ql/parser/AnnisParser.java
855decdf804ca8d5c7609e4a99a26a828ba3a7ea
[ "Apache-2.0", "LicenseRef-scancode-public-domain" ]
permissive
thomaskrause/ANNIS
https://github.com/thomaskrause/ANNIS
6300f4f2623bc146abdeed18d37913fc0f6ed900
c63560cd067d698609ddc62b085c651261a3dd79
refs/heads/master
2020-04-05T22:40:57.781000
2013-07-31T12:01:26
2013-07-31T12:01:26
5,452,472
0
0
Apache-2.0
true
2018-08-10T00:17:14
2012-08-17T13:20:45
2014-06-24T10:45:38
2018-08-10T00:15:43
155,665
0
0
1
Java
false
null
/* * Copyright 2009-2011 Collaborative Research Centre SFB 632 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package annis.ql.parser; import annis.exceptions.AnnisQLSyntaxException; import java.io.IOException; import java.io.PrintWriter; import java.io.PushbackReader; import java.io.StringReader; import java.io.StringWriter; import java.util.ArrayList; import java.util.List; import annis.ql.analysis.DepthFirstAdapter; import annis.ql.lexer.Lexer; import annis.ql.lexer.LexerException; import annis.ql.node.Start; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class AnnisParser { private static final Logger log = LoggerFactory.getLogger(AnnisParser.class); // extra class to allow stubbing in tests public static class InternalParser { public Start parse(String input) throws ParserException, LexerException, IOException { return new Parser(new Lexer(new PushbackReader(new StringReader(input), 3000))).parse(); } } private InternalParser internalParser; // holds a list of post-processors private List<DepthFirstAdapter> postProcessors; /** * Creates a parser for AnnisQL statements. */ public AnnisParser() { postProcessors = new ArrayList<DepthFirstAdapter>(); postProcessors.add(new NodeSearchNormalizer()); postProcessors.add(new QueryValidator()); internalParser = new InternalParser(); } public Start parse(String annisQuery) { try { log.debug("parsing ANNIS query: " + annisQuery); // build and post-process syntax tree Start start = getInternalParser().parse(annisQuery); for(DepthFirstAdapter postProcessor : getPostProcessors()) { log.debug("applying post processor to syntax tree: " + postProcessor.getClass().getSimpleName()); start.apply(postProcessor); } log.debug("syntax tree is:\n" + dumpTree(start)); return start; } catch(ParserException e) { log.warn("an exception occured on the query: " + annisQuery, e); throw new AnnisQLSyntaxException(e.getLocalizedMessage()); } catch(LexerException e) { log.warn("an exception occured on the query: " + annisQuery, e); throw new AnnisQLSyntaxException(e.getLocalizedMessage()); } catch(IOException e) { log.warn("an exception occured on the query: " + annisQuery, e); throw new AnnisQLSyntaxException(e.getLocalizedMessage()); } } public String dumpTree(String annisQuery) { return dumpTree(parse(annisQuery)); } public static String dumpTree(Start start) { try { StringWriter result = new StringWriter(); start.apply(new TreeDumper(new PrintWriter(result))); return result.toString(); } catch(RuntimeException e) { String errorMessage = "could not serialize syntax tree"; log.warn(errorMessage, e); return errorMessage; } } ///// Getter / Setter public List<DepthFirstAdapter> getPostProcessors() { return postProcessors; } public void setPostProcessors(List<DepthFirstAdapter> postProcessors) { this.postProcessors = postProcessors; } protected void setInternalParser(InternalParser parser) { this.internalParser = parser; } protected InternalParser getInternalParser() { return internalParser; } }
UTF-8
Java
3,858
java
AnnisParser.java
Java
[]
null
[]
/* * Copyright 2009-2011 Collaborative Research Centre SFB 632 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package annis.ql.parser; import annis.exceptions.AnnisQLSyntaxException; import java.io.IOException; import java.io.PrintWriter; import java.io.PushbackReader; import java.io.StringReader; import java.io.StringWriter; import java.util.ArrayList; import java.util.List; import annis.ql.analysis.DepthFirstAdapter; import annis.ql.lexer.Lexer; import annis.ql.lexer.LexerException; import annis.ql.node.Start; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class AnnisParser { private static final Logger log = LoggerFactory.getLogger(AnnisParser.class); // extra class to allow stubbing in tests public static class InternalParser { public Start parse(String input) throws ParserException, LexerException, IOException { return new Parser(new Lexer(new PushbackReader(new StringReader(input), 3000))).parse(); } } private InternalParser internalParser; // holds a list of post-processors private List<DepthFirstAdapter> postProcessors; /** * Creates a parser for AnnisQL statements. */ public AnnisParser() { postProcessors = new ArrayList<DepthFirstAdapter>(); postProcessors.add(new NodeSearchNormalizer()); postProcessors.add(new QueryValidator()); internalParser = new InternalParser(); } public Start parse(String annisQuery) { try { log.debug("parsing ANNIS query: " + annisQuery); // build and post-process syntax tree Start start = getInternalParser().parse(annisQuery); for(DepthFirstAdapter postProcessor : getPostProcessors()) { log.debug("applying post processor to syntax tree: " + postProcessor.getClass().getSimpleName()); start.apply(postProcessor); } log.debug("syntax tree is:\n" + dumpTree(start)); return start; } catch(ParserException e) { log.warn("an exception occured on the query: " + annisQuery, e); throw new AnnisQLSyntaxException(e.getLocalizedMessage()); } catch(LexerException e) { log.warn("an exception occured on the query: " + annisQuery, e); throw new AnnisQLSyntaxException(e.getLocalizedMessage()); } catch(IOException e) { log.warn("an exception occured on the query: " + annisQuery, e); throw new AnnisQLSyntaxException(e.getLocalizedMessage()); } } public String dumpTree(String annisQuery) { return dumpTree(parse(annisQuery)); } public static String dumpTree(Start start) { try { StringWriter result = new StringWriter(); start.apply(new TreeDumper(new PrintWriter(result))); return result.toString(); } catch(RuntimeException e) { String errorMessage = "could not serialize syntax tree"; log.warn(errorMessage, e); return errorMessage; } } ///// Getter / Setter public List<DepthFirstAdapter> getPostProcessors() { return postProcessors; } public void setPostProcessors(List<DepthFirstAdapter> postProcessors) { this.postProcessors = postProcessors; } protected void setInternalParser(InternalParser parser) { this.internalParser = parser; } protected InternalParser getInternalParser() { return internalParser; } }
3,858
0.708917
0.703473
143
25.979021
25.730303
105
false
false
0
0
0
0
0
0
0.405594
false
false
2
ca2e6059362768350823c2b9fcbf83faa9f68f39
27,797,028,366,674
060eb0c4e669b093dbb9d5c578ad058b7d6307c8
/android/app/src/main/java/com/munger/stereocamera/ip/SocketCtrlCtrl.java
33f5e63966d31dcff7fe70b5b7e73bdb332cd9da
[]
no_license
fPonias/stereoCamera
https://github.com/fPonias/stereoCamera
ed0f4c7cca3c9e1fa2ef94ca764f98c6909186e9
3c8d1a8b9fe887e90e7dd7a2ecb417727ba67daa
refs/heads/master
2023-03-02T20:37:22.846000
2023-03-01T19:28:28
2023-03-01T19:28:28
122,685,593
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.munger.stereocamera.ip; import com.munger.stereocamera.ip.command.CommCtrl; public interface SocketCtrlCtrl { boolean getIsSetup(); SocketCtrl getSlave(); SocketCtrl getMaster(); Boolean isMaster(); }
UTF-8
Java
219
java
SocketCtrlCtrl.java
Java
[]
null
[]
package com.munger.stereocamera.ip; import com.munger.stereocamera.ip.command.CommCtrl; public interface SocketCtrlCtrl { boolean getIsSetup(); SocketCtrl getSlave(); SocketCtrl getMaster(); Boolean isMaster(); }
219
0.785388
0.785388
11
18.90909
16.081919
51
false
false
0
0
0
0
0
0
0.909091
false
false
2
9107f60cfb1bedd23d1880e5173c9e72dc046acd
14,731,737,847,433
b1ac476acb850c3bee35808c80d558717083579b
/Exercises/Fourth Homework/ClassworkExerciseEight.java
b6763fa94213c63bcf60f36156e208976a3df5e8
[]
no_license
NikolovJunior/Tasks
https://github.com/NikolovJunior/Tasks
35d2e7f2be3b17d832d8a94dd0f952f6ef0f82a2
3566892b7c793e457adcaf3ed6b99f09fdd10269
refs/heads/master
2020-05-29T08:50:32.826000
2018-12-02T15:51:05
2018-12-02T15:51:05
69,283,916
0
0
null
false
2018-11-25T19:07:52
2016-09-26T19:11:50
2018-11-25T18:51:56
2018-11-25T19:03:08
2,042
0
0
1
Java
false
null
public class ClassworkExerciseEight { /* * Напишете програма, която за матрица от булеви стойности, проверява дали * се съдържа елемент със стойност true над втория диагонал. */ public static void main(String[] args) { boolean[][] array = { { true, false, false }, { false, true, false }, { false, false, true } }; System.out.println("The elements below the diagonal are: "); int count = 0; for (int row = 0; row < array.length; row++) { for (int col = 0; col < array[row].length - row - 1; col++) { if (col < array.length - row - 1) { if (array[row][col] == true) { System.out.print("Contains true."); break; } else { count++; } } } } if (count == 3) { System.out.println("Does not contains true."); } } }
WINDOWS-1251
Java
904
java
ClassworkExerciseEight.java
Java
[]
null
[]
public class ClassworkExerciseEight { /* * Напишете програма, която за матрица от булеви стойности, проверява дали * се съдържа елемент със стойност true над втория диагонал. */ public static void main(String[] args) { boolean[][] array = { { true, false, false }, { false, true, false }, { false, false, true } }; System.out.println("The elements below the diagonal are: "); int count = 0; for (int row = 0; row < array.length; row++) { for (int col = 0; col < array[row].length - row - 1; col++) { if (col < array.length - row - 1) { if (array[row][col] == true) { System.out.print("Contains true."); break; } else { count++; } } } } if (count == 3) { System.out.println("Does not contains true."); } } }
904
0.57625
0.56875
32
24
21.712612
75
false
false
0
0
0
0
0
0
3.34375
false
false
2
9050f3741437c9322460e6f4baacd8f481ecc6c6
18,786,186,974,284
646a5898f6a9cad553c77ab4fb9938c97f8f7fbe
/src/main/java/com/viaflow/manager/api/service/CurriculumBaseService.java
2153a204e0913ddf652195ca7ae0f36c9e9d6b9a
[]
no_license
jpaulo0866/projectManagerAPI
https://github.com/jpaulo0866/projectManagerAPI
a39f77c847769395df8cfdc4289812a1959550e0
9aaa6aa9a5c1c85c129f459d1f54ebfa0a5c3547
refs/heads/master
2020-05-09T15:14:14.140000
2019-04-13T21:06:38
2019-04-13T21:06:38
181,225,730
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.viaflow.manager.api.service; import java.util.List; import org.springframework.stereotype.Service; import com.viaflow.manager.api.entity.curriculum.CurriculumBase; @Service public interface CurriculumBaseService extends BaseService<CurriculumBase>{ List<CurriculumBase> findAllBy(String text); }
UTF-8
Java
323
java
CurriculumBaseService.java
Java
[]
null
[]
package com.viaflow.manager.api.service; import java.util.List; import org.springframework.stereotype.Service; import com.viaflow.manager.api.entity.curriculum.CurriculumBase; @Service public interface CurriculumBaseService extends BaseService<CurriculumBase>{ List<CurriculumBase> findAllBy(String text); }
323
0.80805
0.80805
12
25.083334
26.553274
75
false
false
0
0
0
0
0
0
0.5
false
false
2
b16e82975239c43e2d761843109f84875782c2b1
29,789,893,187,045
90f725b114ff893bb16ecf94fbf5a592c1752d2d
/src/test/java/com/ykun/commons/utils/mapper/Destination.java
4febb2d7f0235242973278b640b3cce0e6f43ac8
[ "Apache-2.0" ]
permissive
decadenceqi/commons
https://github.com/decadenceqi/commons
4ecb249b4382a425d39668f681756d388c75185e
7f7e6d7d841ce02f5b2749df9f8247df1671ef61
refs/heads/master
2021-01-13T05:02:31.616000
2019-10-21T03:33:07
2019-10-21T03:33:07
81,193,762
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * Commons-Utils * Copyright (c) 2017. * * Licensed under the Apache License, Version 2.0 (the "License") */ package com.ykun.commons.utils.mapper; /** * @author Ykun 于 2017-03-29 14:27 */ public class Destination { private String name; private int age; private int pk; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public int getPk() { return pk; } public void setPk(int pk) { this.pk = pk; } @Override public String toString() { return "Destination{" + "name='" + name + '\'' + ", age=" + age + ", pk=" + pk + '}'; } }
UTF-8
Java
870
java
Destination.java
Java
[ { "context": "age com.ykun.commons.utils.mapper;\n\n/**\n * @author Ykun 于 2017-03-29 14:27\n */\npublic class Destination {", "end": 176, "score": 0.9765121936798096, "start": 172, "tag": "NAME", "value": "Ykun" } ]
null
[]
/* * Commons-Utils * Copyright (c) 2017. * * Licensed under the Apache License, Version 2.0 (the "License") */ package com.ykun.commons.utils.mapper; /** * @author Ykun 于 2017-03-29 14:27 */ public class Destination { private String name; private int age; private int pk; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public int getPk() { return pk; } public void setPk(int pk) { this.pk = pk; } @Override public String toString() { return "Destination{" + "name='" + name + '\'' + ", age=" + age + ", pk=" + pk + '}'; } }
870
0.495392
0.474654
53
15.377358
14.683101
65
false
false
0
0
0
0
0
0
0.264151
false
false
2
85c39cef6cf90dde603c5a5de57e3ea94209381c
21,930,103,060,386
4d57bf24ca0a314296d8b1037d1f4b32b82a58a4
/malls/src/main/java/com/kgc/controller/CategoryController.java
1abc1b0412703b8e986dc2109f384514d11acec3
[]
no_license
hanchaofa/malls
https://github.com/hanchaofa/malls
255dbd664eabcebec80a201138d4a42c901202a3
4379fd91a7cb1852a0d95c4aaf337621ca37448c
refs/heads/master
2023-08-24T00:15:00.849000
2021-10-30T07:49:49
2021-10-30T07:49:49
417,437,162
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.kgc.controller; import com.alibaba.fastjson.JSON; import com.kgc.mapper.CategoryMapper; import com.kgc.pojo.Category; import com.kgc.pojo.Product; import com.kgc.pojo.Productimage; import com.kgc.service.CategoryService; import com.kgc.service.ProductService; import com.kgc.service.ProductimageService; import com.kgc.service.impl.CategoryServiceImpl; import com.kgc.service.impl.ProductServiceImpl; import com.kgc.service.impl.ProductimageServiceImpl; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import javax.annotation.Resource; import java.util.HashMap; import java.util.List; import java.util.Map; @Controller @RequestMapping("/Category") public class CategoryController { @Resource CategoryServiceImpl categoryService; @Resource ProductServiceImpl productService; @Resource ProductimageServiceImpl productimageService; @RequestMapping("/getCategory") public String getCateoryAll(Model model){ List<Category> list = categoryService.getCateoryList(); List<Product> promotion = productService.getPromotion(); for(int i=0;i<list.size();i++){ List<Product> products = productService.getPageByCate(list.get(i).getCategoryId()); for(int j=0;j<products.size();j++){ List<Productimage> pImage = productimageService.getPImage(products.get(j).getProductId()); products.get(j).setSingleProductImageList(pImage); } list.get(i).setProductList(products); } model.addAttribute("categoryList",list); model.addAttribute("specialProductList",promotion); return "/page/fore/homePage"; } @GetMapping(value = "/nav/{toggle}",produces = {"application/json;charset=utf-8"}) @ResponseBody public String getNav(@PathVariable("toggle")Integer tog){ List<Category> list = categoryService.getCateoryList(); Map<String,Object> map=new HashMap<>(); Category category=new Category(); for(int i=0;i<list.size();i++){ if(list.get(i).getCategoryId()==tog){ list.get(i).setProductList(productService.getAllProduct(null,tog)); category=list.get(i); } } map.put("category",category); map.put("success",true); return JSON.toJSONString(map); } }
UTF-8
Java
2,616
java
CategoryController.java
Java
[]
null
[]
package com.kgc.controller; import com.alibaba.fastjson.JSON; import com.kgc.mapper.CategoryMapper; import com.kgc.pojo.Category; import com.kgc.pojo.Product; import com.kgc.pojo.Productimage; import com.kgc.service.CategoryService; import com.kgc.service.ProductService; import com.kgc.service.ProductimageService; import com.kgc.service.impl.CategoryServiceImpl; import com.kgc.service.impl.ProductServiceImpl; import com.kgc.service.impl.ProductimageServiceImpl; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import javax.annotation.Resource; import java.util.HashMap; import java.util.List; import java.util.Map; @Controller @RequestMapping("/Category") public class CategoryController { @Resource CategoryServiceImpl categoryService; @Resource ProductServiceImpl productService; @Resource ProductimageServiceImpl productimageService; @RequestMapping("/getCategory") public String getCateoryAll(Model model){ List<Category> list = categoryService.getCateoryList(); List<Product> promotion = productService.getPromotion(); for(int i=0;i<list.size();i++){ List<Product> products = productService.getPageByCate(list.get(i).getCategoryId()); for(int j=0;j<products.size();j++){ List<Productimage> pImage = productimageService.getPImage(products.get(j).getProductId()); products.get(j).setSingleProductImageList(pImage); } list.get(i).setProductList(products); } model.addAttribute("categoryList",list); model.addAttribute("specialProductList",promotion); return "/page/fore/homePage"; } @GetMapping(value = "/nav/{toggle}",produces = {"application/json;charset=utf-8"}) @ResponseBody public String getNav(@PathVariable("toggle")Integer tog){ List<Category> list = categoryService.getCateoryList(); Map<String,Object> map=new HashMap<>(); Category category=new Category(); for(int i=0;i<list.size();i++){ if(list.get(i).getCategoryId()==tog){ list.get(i).setProductList(productService.getAllProduct(null,tog)); category=list.get(i); } } map.put("category",category); map.put("success",true); return JSON.toJSONString(map); } }
2,616
0.709862
0.708333
67
38.044777
22.54179
105
false
false
0
0
0
0
0
0
0.835821
false
false
2
33a5f34048e8a3ec6fa2d3fb098046bb9c71742c
17,935,783,463,119
33d48671619881ecad4831f4fcd8ff53423519be
/src/main/java/com/mail/test/service/EmailServiceImpl.java
9fd3b55b6d9864b56590a316378288321439e965
[]
no_license
anushanthR/spring-boot-email-demo
https://github.com/anushanthR/spring-boot-email-demo
1267eba07ee5d23287056f9f3cfab96ea0d35ae4
c67a3d073fc799f4ae6c5a43b31d8dd777596b86
refs/heads/master
2020-04-06T14:42:11.162000
2018-11-18T14:35:30
2018-11-18T14:35:30
157,551,298
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.mail.test.service; import java.io.File; import javax.mail.internet.MimeMessage; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.io.FileSystemResource; import org.springframework.mail.SimpleMailMessage; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.mail.javamail.MimeMessageHelper; import org.springframework.stereotype.Service; import com.mail.test.dto.EmailDto; @Service public class EmailServiceImpl implements EmailService { @Autowired public JavaMailSender emailSender; @Override public String sendSimpleMessage(EmailDto emailDto) { SimpleMailMessage message = new SimpleMailMessage(); message.setTo(emailDto.getEmail()); message.setSubject(emailDto.getSubject()); message.setText(emailDto.getMessage()); emailSender.send(message); return "email sent successfully"; } @Override public String sendMessageWithAttachment(EmailDto emailDto) { MimeMessage message = emailSender.createMimeMessage(); try { MimeMessageHelper helper = new MimeMessageHelper(message, true); helper.setTo(emailDto.getEmail()); helper.setSubject(emailDto.getSubject()); helper.setText(emailDto.getMessage()); FileSystemResource file = new FileSystemResource(new File(emailDto.getPath())); helper.addAttachment(emailDto.getFileName(), file); } catch (Exception e) { e.printStackTrace(); return "Error while sending mail .."; } emailSender.send(message); return "Mail Sent Success!"; } }
UTF-8
Java
1,621
java
EmailServiceImpl.java
Java
[]
null
[]
package com.mail.test.service; import java.io.File; import javax.mail.internet.MimeMessage; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.io.FileSystemResource; import org.springframework.mail.SimpleMailMessage; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.mail.javamail.MimeMessageHelper; import org.springframework.stereotype.Service; import com.mail.test.dto.EmailDto; @Service public class EmailServiceImpl implements EmailService { @Autowired public JavaMailSender emailSender; @Override public String sendSimpleMessage(EmailDto emailDto) { SimpleMailMessage message = new SimpleMailMessage(); message.setTo(emailDto.getEmail()); message.setSubject(emailDto.getSubject()); message.setText(emailDto.getMessage()); emailSender.send(message); return "email sent successfully"; } @Override public String sendMessageWithAttachment(EmailDto emailDto) { MimeMessage message = emailSender.createMimeMessage(); try { MimeMessageHelper helper = new MimeMessageHelper(message, true); helper.setTo(emailDto.getEmail()); helper.setSubject(emailDto.getSubject()); helper.setText(emailDto.getMessage()); FileSystemResource file = new FileSystemResource(new File(emailDto.getPath())); helper.addAttachment(emailDto.getFileName(), file); } catch (Exception e) { e.printStackTrace(); return "Error while sending mail .."; } emailSender.send(message); return "Mail Sent Success!"; } }
1,621
0.737816
0.737816
53
29.584906
22.540056
69
false
false
0
0
0
0
0
0
1.226415
false
false
2
5636b9885cb057fcd8a5a1085a02608d8620b912
2,147,483,655,357
e7ea37736c9cdcd8afed5152f2ccb233dd382047
/gulimall-member/src/main/java/com/atguigu/gulimall/member/dao/IntegrationChangeHistoryDao.java
b1f9660739df1d7ae4b284791de179999b72bef1
[]
no_license
zhaoxiaohua111/gulimall
https://github.com/zhaoxiaohua111/gulimall
39b3d456abfda0820ea5869e04bb23e0e3d3efb4
e2ebff92791360376a411721a1442ae716cc08b9
refs/heads/main
2023-03-24T09:59:26.662000
2021-03-20T15:51:18
2021-03-20T15:51:18
349,326,286
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.atguigu.gulimall.member.dao; import com.atguigu.gulimall.member.entity.IntegrationChangeHistoryEntity; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import org.apache.ibatis.annotations.Mapper; /** * 积分变化历史记录 * * @author zx * @email 2674671187@qq.com * @date 2021-03-19 21:43:06 */ @Mapper public interface IntegrationChangeHistoryDao extends BaseMapper<IntegrationChangeHistoryEntity> { }
UTF-8
Java
439
java
IntegrationChangeHistoryDao.java
Java
[ { "context": "nnotations.Mapper;\n\n/**\n * 积分变化历史记录\n * \n * @author zx\n * @email 2674671187@qq.com\n * @date 2021-03-19 2", "end": 251, "score": 0.9986376166343689, "start": 249, "tag": "USERNAME", "value": "zx" }, { "context": "per;\n\n/**\n * 积分变化历史记录\n * \n * @author zx\n * @email 2674671187@qq.com\n * @date 2021-03-19 21:43:06\n */\n@Mapper\npublic i", "end": 279, "score": 0.9998415112495422, "start": 262, "tag": "EMAIL", "value": "2674671187@qq.com" } ]
null
[]
package com.atguigu.gulimall.member.dao; import com.atguigu.gulimall.member.entity.IntegrationChangeHistoryEntity; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import org.apache.ibatis.annotations.Mapper; /** * 积分变化历史记录 * * @author zx * @email <EMAIL> * @date 2021-03-19 21:43:06 */ @Mapper public interface IntegrationChangeHistoryDao extends BaseMapper<IntegrationChangeHistoryEntity> { }
429
0.791962
0.735225
17
23.882353
28.163143
97
false
false
0
0
0
0
0
0
0.294118
false
false
2
daa0c41524d99f0018817cb391426fd86b78757e
5,531,917,914,880
9de5b3a08a7cf3de959edf16006f5d49b8816a31
/tests/SudokuVerifierParametrizedTest.java
e2a1fc6fc6df2907b9459d9374c5c6890c04ea74
[]
no_license
nmarkuks18/SudokuVerifier
https://github.com/nmarkuks18/SudokuVerifier
c11e0ba253d2ffb0c29844081ee7311eaed75aac
fb6c97cde9c0e39cc47693c76208ed50c003eee0
refs/heads/master
2020-03-30T06:53:10.666000
2018-10-01T20:40:46
2018-10-01T20:40:46
150,896,883
0
0
null
true
2018-09-29T19:35:05
2018-09-29T19:35:04
2017-09-25T00:40:21
2018-09-29T19:14:56
101
0
0
0
null
false
null
import static org.junit.Assert.*; import org.junit.Test; public class SudokuVerifierParametrizedTest { //valid=417369825632158947958724316825437169791586432346912758289643571573291684164875293 String valid="417369825632158947958724316825437169791586432346912758289643571573291684164875293"; String invalid="123456789912345678891234567789123456678912345567891234456789123345678912234567891"; String LenghtError="12345678991234567889123456778912345667891234556789123445678912334567891223456789144"; String FormError="-17369825632158947958724316825437169791586432346912758289643571573291684164875293"; String RowError="417369825632158947958724316825437169791586432346912758289643571573291684164875299"; String ColumnError="417369825632158947958724316825437169791586432346912758289643571573291684564875293"; String SubgridError="447369825632158947958724316825437169791586432346912758289643571573291684164875993"; @Test (expected=IllegalArgumentException.class) public void TestSudokuVerifier_LenghtElseThan81ThrowsException() { SudokuVerifier sudoku = new SudokuVerifier(); sudoku.checkLenght(LenghtError); } @Test public void TestSudokuVerifier_NegativeDigitReturnsNeg1() { SudokuVerifier sudoku = new SudokuVerifier(); assertEquals("Fail",-1,sudoku.checkDigits(FormError)); } @Test public void TestSudokuVerifier_RowErrorReturnsNeg3() { SudokuVerifier sudoku = new SudokuVerifier(); assertEquals("Fail",-3,sudoku.checkRows(RowError)); } @Test public void TestSudokuVerifier_CorrectRowReturns0() { SudokuVerifier sudoku = new SudokuVerifier(); assertEquals("Fail",0,sudoku.checkRows(valid)); } @Test public void TestSudokuVerifier_ColumnErrorReturnsNeg4() { SudokuVerifier sudoku = new SudokuVerifier(); assertEquals("Fail",-4,sudoku.checkColumns(ColumnError)); } @Test public void TestSudokuVerifier_CorrectColumnReturns0() { SudokuVerifier sudoku = new SudokuVerifier(); assertEquals("Fail",0,sudoku.checkColumns(valid)); } @Test public void TestSudokuVerifier_SubgridErrorReturnsNeg2() { SudokuVerifier sudoku = new SudokuVerifier(); assertEquals("Fail",-2,sudoku.checkSubgrids(SubgridError)); } @Test public void TestSudokuVerifier_CorrectSubgridReturns0() { SudokuVerifier sudoku = new SudokuVerifier(); assertEquals("Fail",0,sudoku.checkSubgrids(valid)); } @Test public void TestSudokuVerifier_CorrectSolutionReturnsZero() { SudokuVerifier sudoku = new SudokuVerifier(); assertEquals("Fail",0,sudoku.verify(valid)); } @Test public void TestSudokuVerifier_IncorrectSolutionReturnsNegative() {//apparently -2 in given incorrect string SudokuVerifier sudoku = new SudokuVerifier(); assertEquals("Fail",-2,sudoku.verify(invalid)); } }
UTF-8
Java
2,739
java
SudokuVerifierParametrizedTest.java
Java
[]
null
[]
import static org.junit.Assert.*; import org.junit.Test; public class SudokuVerifierParametrizedTest { //valid=417369825632158947958724316825437169791586432346912758289643571573291684164875293 String valid="417369825632158947958724316825437169791586432346912758289643571573291684164875293"; String invalid="123456789912345678891234567789123456678912345567891234456789123345678912234567891"; String LenghtError="12345678991234567889123456778912345667891234556789123445678912334567891223456789144"; String FormError="-17369825632158947958724316825437169791586432346912758289643571573291684164875293"; String RowError="417369825632158947958724316825437169791586432346912758289643571573291684164875299"; String ColumnError="417369825632158947958724316825437169791586432346912758289643571573291684564875293"; String SubgridError="447369825632158947958724316825437169791586432346912758289643571573291684164875993"; @Test (expected=IllegalArgumentException.class) public void TestSudokuVerifier_LenghtElseThan81ThrowsException() { SudokuVerifier sudoku = new SudokuVerifier(); sudoku.checkLenght(LenghtError); } @Test public void TestSudokuVerifier_NegativeDigitReturnsNeg1() { SudokuVerifier sudoku = new SudokuVerifier(); assertEquals("Fail",-1,sudoku.checkDigits(FormError)); } @Test public void TestSudokuVerifier_RowErrorReturnsNeg3() { SudokuVerifier sudoku = new SudokuVerifier(); assertEquals("Fail",-3,sudoku.checkRows(RowError)); } @Test public void TestSudokuVerifier_CorrectRowReturns0() { SudokuVerifier sudoku = new SudokuVerifier(); assertEquals("Fail",0,sudoku.checkRows(valid)); } @Test public void TestSudokuVerifier_ColumnErrorReturnsNeg4() { SudokuVerifier sudoku = new SudokuVerifier(); assertEquals("Fail",-4,sudoku.checkColumns(ColumnError)); } @Test public void TestSudokuVerifier_CorrectColumnReturns0() { SudokuVerifier sudoku = new SudokuVerifier(); assertEquals("Fail",0,sudoku.checkColumns(valid)); } @Test public void TestSudokuVerifier_SubgridErrorReturnsNeg2() { SudokuVerifier sudoku = new SudokuVerifier(); assertEquals("Fail",-2,sudoku.checkSubgrids(SubgridError)); } @Test public void TestSudokuVerifier_CorrectSubgridReturns0() { SudokuVerifier sudoku = new SudokuVerifier(); assertEquals("Fail",0,sudoku.checkSubgrids(valid)); } @Test public void TestSudokuVerifier_CorrectSolutionReturnsZero() { SudokuVerifier sudoku = new SudokuVerifier(); assertEquals("Fail",0,sudoku.verify(valid)); } @Test public void TestSudokuVerifier_IncorrectSolutionReturnsNegative() {//apparently -2 in given incorrect string SudokuVerifier sudoku = new SudokuVerifier(); assertEquals("Fail",-2,sudoku.verify(invalid)); } }
2,739
0.815991
0.572107
69
38.695652
33.683224
109
false
false
0
0
0
0
90
0.240234
2.101449
false
false
2
d070fca17e34dba22d4170211cd0ee8e8e9a6512
2,448,131,376,161
5ad1bfa493ffb59efc010857e97d6d4498803c27
/src/main/java/lk/wasity_institute/asset/hall/dao/HallDao.java
1ae4a9c92ac84bb62aa4944f5556d46b29eeba85
[]
no_license
LalithK90/publicLibrary
https://github.com/LalithK90/publicLibrary
80e99943a5512a28df9547bc2f9a7ab15551584e
4a34368a8f059dc7c11d6a75d601cc3d61134b6f
refs/heads/master
2021-05-17T17:03:53.409000
2021-05-07T17:32:01
2021-05-07T17:32:01
250,885,938
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package lk.wasity_institute.asset.hall.dao; import lk.wasity_institute.asset.hall.entity.Hall; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; @Repository public interface HallDao extends JpaRepository< Hall, Integer> { }
UTF-8
Java
292
java
HallDao.java
Java
[]
null
[]
package lk.wasity_institute.asset.hall.dao; import lk.wasity_institute.asset.hall.entity.Hall; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; @Repository public interface HallDao extends JpaRepository< Hall, Integer> { }
292
0.818493
0.818493
13
21.461538
25.871325
64
false
false
0
0
0
0
0
0
0.384615
false
false
2
0807e11a37421d1b36e5c607e3d9dc3abca15380
4,492,535,810,045
0b2c838fe8ec4dc6a5d45191e535fac405ecd71c
/com/massivecraft/massivecore/util/extractor/ExtractorLogic.java
41034415e705a644bb9b93a66bd97a2af9d6b793
[]
no_license
rexbut/test
https://github.com/rexbut/test
69565bc666dbc7196a2a7d6dbc1512027932c7b3
a63451a6e55d8f473c63a1648c98bc2f334453ba
refs/heads/master
2016-03-25T10:24:53.473000
2016-02-18T00:10:07
2016-02-18T00:10:07
51,964,912
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.massivecraft.massivecore.util.extractor; import com.massivecraft.massivecore.mixin.Mixin; import com.massivecraft.massivecore.ps.PS; import com.massivecraft.massivecore.util.IdUtil; import com.massivecraft.massivecore.util.MUtil; import org.bukkit.Location; import org.bukkit.World; import org.bukkit.block.Block; import org.bukkit.command.CommandSender; import org.bukkit.entity.Entity; import org.bukkit.entity.Player; import org.bukkit.entity.Vehicle; import org.bukkit.event.block.BlockBreakEvent; import org.bukkit.event.block.BlockDamageEvent; import org.bukkit.event.block.BlockIgniteEvent; import org.bukkit.event.block.BlockPlaceEvent; import org.bukkit.event.block.SignChangeEvent; import org.bukkit.event.enchantment.EnchantItemEvent; import org.bukkit.event.enchantment.PrepareItemEnchantEvent; import org.bukkit.event.entity.EntityEvent; import org.bukkit.event.hanging.HangingBreakByEntityEvent; import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.event.inventory.InventoryCloseEvent; import org.bukkit.event.inventory.InventoryOpenEvent; import org.bukkit.event.player.PlayerEvent; import org.bukkit.event.vehicle.VehicleDamageEvent; import org.bukkit.event.vehicle.VehicleDestroyEvent; import org.bukkit.event.vehicle.VehicleEnterEvent; import org.bukkit.event.vehicle.VehicleEvent; import org.bukkit.event.vehicle.VehicleExitEvent; public class ExtractorLogic { public static CommandSender sender(String o) { return IdUtil.getSender(o); } public static CommandSender sender(PlayerEvent o) { return o.getPlayer(); } public static CommandSender sender(BlockBreakEvent o) { return o.getPlayer(); } public static CommandSender sender(BlockDamageEvent o) { return o.getPlayer(); } public static CommandSender sender(BlockIgniteEvent o) { return o.getPlayer(); } public static CommandSender sender(BlockPlaceEvent o) { return o.getPlayer(); } public static CommandSender sender(SignChangeEvent o) { return o.getPlayer(); } public static CommandSender sender(EnchantItemEvent o) { return o.getEnchanter(); } public static CommandSender sender(PrepareItemEnchantEvent o) { return o.getEnchanter(); } public static CommandSender sender(Entity o) { if ((o instanceof CommandSender)) { return o; } return null; } public static CommandSender sender(EntityEvent o) { return sender(o.getEntity()); } public static CommandSender sender(InventoryClickEvent o) { return sender(o.getWhoClicked()); } public static CommandSender sender(InventoryCloseEvent o) { return sender(o.getPlayer()); } public static CommandSender sender(InventoryOpenEvent o) { return sender(o.getPlayer()); } public static CommandSender sender(HangingBreakByEntityEvent o) { return sender(o.getRemover()); } public static CommandSender sender(VehicleDamageEvent o) { return sender(o.getAttacker()); } public static CommandSender sender(VehicleDestroyEvent o) { return sender(o.getAttacker()); } public static CommandSender sender(VehicleEnterEvent o) { return sender(o.getEntered()); } public static CommandSender sender(VehicleExitEvent o) { return sender(o.getExited()); } public static CommandSender sender(VehicleEvent o) { return sender(o.getVehicle().getPassenger()); } public static CommandSender senderFromObject(Object o) { if (o == null) { return null; } if ((o instanceof CommandSender)) { return (CommandSender)o; } if ((o instanceof String)) { return sender((String)o); } if ((o instanceof PlayerEvent)) { return sender((PlayerEvent)o); } if ((o instanceof BlockBreakEvent)) { return sender((BlockBreakEvent)o); } if ((o instanceof BlockDamageEvent)) { return sender((BlockDamageEvent)o); } if ((o instanceof BlockIgniteEvent)) { return sender((BlockIgniteEvent)o); } if ((o instanceof BlockPlaceEvent)) { return sender((BlockPlaceEvent)o); } if ((o instanceof SignChangeEvent)) { return sender((SignChangeEvent)o); } if ((o instanceof EnchantItemEvent)) { return sender((EnchantItemEvent)o); } if ((o instanceof PrepareItemEnchantEvent)) { return sender((PrepareItemEnchantEvent)o); } if ((o instanceof Entity)) { return sender((Entity)o); } if ((o instanceof EntityEvent)) { return sender((EntityEvent)o); } if ((o instanceof InventoryClickEvent)) { return sender((InventoryClickEvent)o); } if ((o instanceof InventoryCloseEvent)) { return sender((InventoryCloseEvent)o); } if ((o instanceof InventoryOpenEvent)) { return sender((InventoryOpenEvent)o); } if ((o instanceof HangingBreakByEntityEvent)) { return sender((HangingBreakByEntityEvent)o); } if ((o instanceof VehicleDamageEvent)) { return sender((VehicleDamageEvent)o); } if ((o instanceof VehicleDestroyEvent)) { return sender((VehicleDestroyEvent)o); } if ((o instanceof VehicleEnterEvent)) { return sender((VehicleEnterEvent)o); } if ((o instanceof VehicleExitEvent)) { return sender((VehicleExitEvent)o); } if ((o instanceof VehicleEvent)) { return sender((VehicleEvent)o); } return null; } public static Player playerFromObject(Object o) { CommandSender sender = senderFromObject(o); if ((sender instanceof Player)) { return (Player)sender; } return null; } public static String senderIdFromObject(Object o) { if (o == null) { return null; } String id = IdUtil.getId(o); if (id != null) { return id; } CommandSender sender = senderFromObject(o); if (sender == null) { return null; } return IdUtil.getId(sender); } public static String senderNameFromObject(Object o) { if (o == null) { return null; } String name = IdUtil.getName(o); if (name != null) { return name; } CommandSender sender = senderFromObject(o); if (sender == null) { return null; } return IdUtil.getName(sender); } public static String playerNameFromObject(Object o) { String senderId = senderNameFromObject(o); return senderId; } public static World world(Block o) { return o.getWorld(); } public static World world(Location o) { return o.getWorld(); } public static World world(Entity o) { return o.getWorld(); } public static World world(PlayerEvent o) { return world(o.getPlayer()); } public static World world(PS o) { try { return o.asBukkitWorld(true); } catch (Exception e) {} return null; } public static World worldFromObject(Object o) { if ((o instanceof World)) { return (World)o; } if ((o instanceof Block)) { return world((Block)o); } if ((o instanceof Location)) { return world((Location)o); } if ((o instanceof Entity)) { return world((Entity)o); } if ((o instanceof PlayerEvent)) { return world((PlayerEvent)o); } if ((o instanceof PS)) { return world((PS)o); } return null; } public static String worldNameFromObject(Object o) { if ((o instanceof String)) { String string = (String)o; if (MUtil.isUuid(string)) { String ret = worldNameViaPsMixin(string); if (ret != null) { return ret; } } return string; } if ((o instanceof PS)) { return ((PS)o).getWorld(); } World world = worldFromObject(o); if (world != null) { return world.getName(); } String ret = worldNameViaPsMixin(o); if (ret != null) { return ret; } return null; } public static String worldNameViaPsMixin(Object senderObject) { if (senderObject == null) { return null; } PS ps = Mixin.getSenderPs(senderObject); if (ps == null) { return null; } return ps.getWorld(); } }
UTF-8
Java
8,244
java
ExtractorLogic.java
Java
[]
null
[]
package com.massivecraft.massivecore.util.extractor; import com.massivecraft.massivecore.mixin.Mixin; import com.massivecraft.massivecore.ps.PS; import com.massivecraft.massivecore.util.IdUtil; import com.massivecraft.massivecore.util.MUtil; import org.bukkit.Location; import org.bukkit.World; import org.bukkit.block.Block; import org.bukkit.command.CommandSender; import org.bukkit.entity.Entity; import org.bukkit.entity.Player; import org.bukkit.entity.Vehicle; import org.bukkit.event.block.BlockBreakEvent; import org.bukkit.event.block.BlockDamageEvent; import org.bukkit.event.block.BlockIgniteEvent; import org.bukkit.event.block.BlockPlaceEvent; import org.bukkit.event.block.SignChangeEvent; import org.bukkit.event.enchantment.EnchantItemEvent; import org.bukkit.event.enchantment.PrepareItemEnchantEvent; import org.bukkit.event.entity.EntityEvent; import org.bukkit.event.hanging.HangingBreakByEntityEvent; import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.event.inventory.InventoryCloseEvent; import org.bukkit.event.inventory.InventoryOpenEvent; import org.bukkit.event.player.PlayerEvent; import org.bukkit.event.vehicle.VehicleDamageEvent; import org.bukkit.event.vehicle.VehicleDestroyEvent; import org.bukkit.event.vehicle.VehicleEnterEvent; import org.bukkit.event.vehicle.VehicleEvent; import org.bukkit.event.vehicle.VehicleExitEvent; public class ExtractorLogic { public static CommandSender sender(String o) { return IdUtil.getSender(o); } public static CommandSender sender(PlayerEvent o) { return o.getPlayer(); } public static CommandSender sender(BlockBreakEvent o) { return o.getPlayer(); } public static CommandSender sender(BlockDamageEvent o) { return o.getPlayer(); } public static CommandSender sender(BlockIgniteEvent o) { return o.getPlayer(); } public static CommandSender sender(BlockPlaceEvent o) { return o.getPlayer(); } public static CommandSender sender(SignChangeEvent o) { return o.getPlayer(); } public static CommandSender sender(EnchantItemEvent o) { return o.getEnchanter(); } public static CommandSender sender(PrepareItemEnchantEvent o) { return o.getEnchanter(); } public static CommandSender sender(Entity o) { if ((o instanceof CommandSender)) { return o; } return null; } public static CommandSender sender(EntityEvent o) { return sender(o.getEntity()); } public static CommandSender sender(InventoryClickEvent o) { return sender(o.getWhoClicked()); } public static CommandSender sender(InventoryCloseEvent o) { return sender(o.getPlayer()); } public static CommandSender sender(InventoryOpenEvent o) { return sender(o.getPlayer()); } public static CommandSender sender(HangingBreakByEntityEvent o) { return sender(o.getRemover()); } public static CommandSender sender(VehicleDamageEvent o) { return sender(o.getAttacker()); } public static CommandSender sender(VehicleDestroyEvent o) { return sender(o.getAttacker()); } public static CommandSender sender(VehicleEnterEvent o) { return sender(o.getEntered()); } public static CommandSender sender(VehicleExitEvent o) { return sender(o.getExited()); } public static CommandSender sender(VehicleEvent o) { return sender(o.getVehicle().getPassenger()); } public static CommandSender senderFromObject(Object o) { if (o == null) { return null; } if ((o instanceof CommandSender)) { return (CommandSender)o; } if ((o instanceof String)) { return sender((String)o); } if ((o instanceof PlayerEvent)) { return sender((PlayerEvent)o); } if ((o instanceof BlockBreakEvent)) { return sender((BlockBreakEvent)o); } if ((o instanceof BlockDamageEvent)) { return sender((BlockDamageEvent)o); } if ((o instanceof BlockIgniteEvent)) { return sender((BlockIgniteEvent)o); } if ((o instanceof BlockPlaceEvent)) { return sender((BlockPlaceEvent)o); } if ((o instanceof SignChangeEvent)) { return sender((SignChangeEvent)o); } if ((o instanceof EnchantItemEvent)) { return sender((EnchantItemEvent)o); } if ((o instanceof PrepareItemEnchantEvent)) { return sender((PrepareItemEnchantEvent)o); } if ((o instanceof Entity)) { return sender((Entity)o); } if ((o instanceof EntityEvent)) { return sender((EntityEvent)o); } if ((o instanceof InventoryClickEvent)) { return sender((InventoryClickEvent)o); } if ((o instanceof InventoryCloseEvent)) { return sender((InventoryCloseEvent)o); } if ((o instanceof InventoryOpenEvent)) { return sender((InventoryOpenEvent)o); } if ((o instanceof HangingBreakByEntityEvent)) { return sender((HangingBreakByEntityEvent)o); } if ((o instanceof VehicleDamageEvent)) { return sender((VehicleDamageEvent)o); } if ((o instanceof VehicleDestroyEvent)) { return sender((VehicleDestroyEvent)o); } if ((o instanceof VehicleEnterEvent)) { return sender((VehicleEnterEvent)o); } if ((o instanceof VehicleExitEvent)) { return sender((VehicleExitEvent)o); } if ((o instanceof VehicleEvent)) { return sender((VehicleEvent)o); } return null; } public static Player playerFromObject(Object o) { CommandSender sender = senderFromObject(o); if ((sender instanceof Player)) { return (Player)sender; } return null; } public static String senderIdFromObject(Object o) { if (o == null) { return null; } String id = IdUtil.getId(o); if (id != null) { return id; } CommandSender sender = senderFromObject(o); if (sender == null) { return null; } return IdUtil.getId(sender); } public static String senderNameFromObject(Object o) { if (o == null) { return null; } String name = IdUtil.getName(o); if (name != null) { return name; } CommandSender sender = senderFromObject(o); if (sender == null) { return null; } return IdUtil.getName(sender); } public static String playerNameFromObject(Object o) { String senderId = senderNameFromObject(o); return senderId; } public static World world(Block o) { return o.getWorld(); } public static World world(Location o) { return o.getWorld(); } public static World world(Entity o) { return o.getWorld(); } public static World world(PlayerEvent o) { return world(o.getPlayer()); } public static World world(PS o) { try { return o.asBukkitWorld(true); } catch (Exception e) {} return null; } public static World worldFromObject(Object o) { if ((o instanceof World)) { return (World)o; } if ((o instanceof Block)) { return world((Block)o); } if ((o instanceof Location)) { return world((Location)o); } if ((o instanceof Entity)) { return world((Entity)o); } if ((o instanceof PlayerEvent)) { return world((PlayerEvent)o); } if ((o instanceof PS)) { return world((PS)o); } return null; } public static String worldNameFromObject(Object o) { if ((o instanceof String)) { String string = (String)o; if (MUtil.isUuid(string)) { String ret = worldNameViaPsMixin(string); if (ret != null) { return ret; } } return string; } if ((o instanceof PS)) { return ((PS)o).getWorld(); } World world = worldFromObject(o); if (world != null) { return world.getName(); } String ret = worldNameViaPsMixin(o); if (ret != null) { return ret; } return null; } public static String worldNameViaPsMixin(Object senderObject) { if (senderObject == null) { return null; } PS ps = Mixin.getSenderPs(senderObject); if (ps == null) { return null; } return ps.getWorld(); } }
8,244
0.660844
0.660844
349
22.621777
19.221233
65
false
false
0
0
0
0
0
0
0.338109
false
false
2
a31d3d6d59c2577196417af2b3a1f3764af79054
26,731,876,465,064
122ead092007cf1cdc19f651bffab3140dbd5639
/modules/common/src/main/java/org/battleplugins/api/common/event/gen/EventGenerator.java
acda467e6684c999ed9572fe0c46dbb41a1fe1ea
[]
no_license
BattlePlugins/BattleMcAPI
https://github.com/BattlePlugins/BattleMcAPI
f4030e99041577bbd17e3e405db2d5a7c5f8ef07
7e5854542b6b9dd02290c644cb020c43caaac725
refs/heads/master
2023-05-30T02:56:06.239000
2021-05-30T23:06:14
2021-05-30T23:06:14
37,286,264
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.battleplugins.api.common.event.gen; import com.google.common.base.CaseFormat; import com.google.common.collect.ForwardingMap; import com.google.common.primitives.Primitives; import org.battleplugins.api.common.util.MethodHandleUtil; import org.battleplugins.api.event.Event; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.function.Function; import java.util.stream.Collectors; /** * Represents a class capable of generating the * event "classes" from interfaces. */ public class EventGenerator { private static final Map<Class<? extends Event>, EventGenerator> EVENT_CACHE = new ForwardingEventMap<>(new ConcurrentHashMap<>(), EventGenerator::new); private Class<? extends Event> eventClass; private List<Method> methods; private Map<String, Class<?>> returnTypes; private EventGenerator(Class<? extends Event> eventClass) { this.eventClass = eventClass; this.methods = Collections.unmodifiableList(Arrays.stream( eventClass.getMethods()) .filter(method -> !method.isDefault()) .collect(Collectors.toList()) ); this.returnTypes = Collections.unmodifiableMap(this.methods.stream() .collect(Collectors.toMap(Method::getName, Method::getReturnType))); } /** * Generates a new {@link Event} instance with the * given parameters * * @param parameters the parameters * @return a new event with the given parameters */ public Event newInstance(Map<String, Object> parameters) { for (Map.Entry<String, Class<?>> returnTypeEntry : returnTypes.entrySet()) { String variable = returnTypeEntry.getKey(); if (returnTypeEntry.getKey().startsWith("is")) { variable = returnTypeEntry.getKey().substring("is".length()); } if (returnTypeEntry.getKey().startsWith("get")) { variable = returnTypeEntry.getKey().substring("get".length()); } if (returnTypeEntry.getKey().startsWith("set")) { variable = returnTypeEntry.getKey().substring("set".length()); } Object parameter = parameters.get(CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_CAMEL, variable)); if (parameter == null) { throw new IllegalArgumentException("Could not find parameter with method " + returnTypeEntry.getKey() + " and variable name " + variable + "!"); } // We need to wrap here since maps auto box if (!Primitives.wrap(returnTypeEntry.getValue()).isInstance(parameter) && !returnTypeEntry.getValue().equals(Void.TYPE)) { throw new IllegalArgumentException("Parameter " + variable + " (" + parameter.getClass() + ") cannot be assigned to " + returnTypeEntry.getValue()); } } EventInvocationHandler eventInvocationHandler = new EventInvocationHandler(parameters); return (Event) Proxy.newProxyInstance(EventGenerator.class.getClassLoader(), new Class[]{this.eventClass}, eventInvocationHandler); } public static EventGenerator generate(Class<? extends Event> event) { return EVENT_CACHE.get(event); } private class EventInvocationHandler implements InvocationHandler { private Map<String, Object> parameters = new HashMap<>(); public EventInvocationHandler(Map<String, Object> parameters) { parameters.forEach((str, obj) -> this.parameters.put(str.toLowerCase(), obj)); } @Override public Object invoke(Object obj, Method method, Object[] args) throws Throwable { if (method.getName().equals("toString")) { return "Event(" + "proxy=" + obj.getClass().getName() + "@" + Integer.toHexString(obj.hashCode()) + ", " + "class=" + EventGenerator.this.eventClass.getName() + ", " + "fields=" + this.parameters.values() + ")"; } if (method.getName().equals("equals")) { return obj == args[0]; } if (method.getName().equals("hashCode")) { return System.identityHashCode(obj); } if (method.isDefault()) { try { return MethodHandleUtil.getMethodHandle(method) .bindTo(obj) .invokeWithArguments(args); } catch (Throwable ex) { ex.printStackTrace(); } return null; } if (method.getName().startsWith("is")) { String variable = method.getName().substring("is".length()); return this.parameters.get(variable.toLowerCase()); } if (method.getName().startsWith("get")) { String variable = method.getName().substring("get".length()); return this.parameters.get(variable.toLowerCase()); } if (method.getName().startsWith("set")) { String variable = method.getName().substring("set".length()); return this.parameters.put(variable.toLowerCase(), args[0]); } int methodIndex = EventGenerator.this.methods.indexOf(method); if (methodIndex == -1) { throw new UnsupportedOperationException("Method " + method + " is not supported!"); } return new ArrayList<>(parameters.values()).get(methodIndex); } } private static class ForwardingEventMap<K, V> extends ForwardingMap<K, V> implements Map<K, V> { private Map<K, V> backingMap; private Function<K, V> function; private ForwardingEventMap(Map<K, V> backingMap, Function<K, V> function) { this.backingMap = backingMap; this.function = function; } @Override protected Map<K, V> delegate() { return this.backingMap; } @Override public V get(Object key) { V value = this.backingMap.get(key); if (value != null) { return value; } return this.backingMap.computeIfAbsent((K) key, this.function); } } }
UTF-8
Java
6,601
java
EventGenerator.java
Java
[]
null
[]
package org.battleplugins.api.common.event.gen; import com.google.common.base.CaseFormat; import com.google.common.collect.ForwardingMap; import com.google.common.primitives.Primitives; import org.battleplugins.api.common.util.MethodHandleUtil; import org.battleplugins.api.event.Event; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.function.Function; import java.util.stream.Collectors; /** * Represents a class capable of generating the * event "classes" from interfaces. */ public class EventGenerator { private static final Map<Class<? extends Event>, EventGenerator> EVENT_CACHE = new ForwardingEventMap<>(new ConcurrentHashMap<>(), EventGenerator::new); private Class<? extends Event> eventClass; private List<Method> methods; private Map<String, Class<?>> returnTypes; private EventGenerator(Class<? extends Event> eventClass) { this.eventClass = eventClass; this.methods = Collections.unmodifiableList(Arrays.stream( eventClass.getMethods()) .filter(method -> !method.isDefault()) .collect(Collectors.toList()) ); this.returnTypes = Collections.unmodifiableMap(this.methods.stream() .collect(Collectors.toMap(Method::getName, Method::getReturnType))); } /** * Generates a new {@link Event} instance with the * given parameters * * @param parameters the parameters * @return a new event with the given parameters */ public Event newInstance(Map<String, Object> parameters) { for (Map.Entry<String, Class<?>> returnTypeEntry : returnTypes.entrySet()) { String variable = returnTypeEntry.getKey(); if (returnTypeEntry.getKey().startsWith("is")) { variable = returnTypeEntry.getKey().substring("is".length()); } if (returnTypeEntry.getKey().startsWith("get")) { variable = returnTypeEntry.getKey().substring("get".length()); } if (returnTypeEntry.getKey().startsWith("set")) { variable = returnTypeEntry.getKey().substring("set".length()); } Object parameter = parameters.get(CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_CAMEL, variable)); if (parameter == null) { throw new IllegalArgumentException("Could not find parameter with method " + returnTypeEntry.getKey() + " and variable name " + variable + "!"); } // We need to wrap here since maps auto box if (!Primitives.wrap(returnTypeEntry.getValue()).isInstance(parameter) && !returnTypeEntry.getValue().equals(Void.TYPE)) { throw new IllegalArgumentException("Parameter " + variable + " (" + parameter.getClass() + ") cannot be assigned to " + returnTypeEntry.getValue()); } } EventInvocationHandler eventInvocationHandler = new EventInvocationHandler(parameters); return (Event) Proxy.newProxyInstance(EventGenerator.class.getClassLoader(), new Class[]{this.eventClass}, eventInvocationHandler); } public static EventGenerator generate(Class<? extends Event> event) { return EVENT_CACHE.get(event); } private class EventInvocationHandler implements InvocationHandler { private Map<String, Object> parameters = new HashMap<>(); public EventInvocationHandler(Map<String, Object> parameters) { parameters.forEach((str, obj) -> this.parameters.put(str.toLowerCase(), obj)); } @Override public Object invoke(Object obj, Method method, Object[] args) throws Throwable { if (method.getName().equals("toString")) { return "Event(" + "proxy=" + obj.getClass().getName() + "@" + Integer.toHexString(obj.hashCode()) + ", " + "class=" + EventGenerator.this.eventClass.getName() + ", " + "fields=" + this.parameters.values() + ")"; } if (method.getName().equals("equals")) { return obj == args[0]; } if (method.getName().equals("hashCode")) { return System.identityHashCode(obj); } if (method.isDefault()) { try { return MethodHandleUtil.getMethodHandle(method) .bindTo(obj) .invokeWithArguments(args); } catch (Throwable ex) { ex.printStackTrace(); } return null; } if (method.getName().startsWith("is")) { String variable = method.getName().substring("is".length()); return this.parameters.get(variable.toLowerCase()); } if (method.getName().startsWith("get")) { String variable = method.getName().substring("get".length()); return this.parameters.get(variable.toLowerCase()); } if (method.getName().startsWith("set")) { String variable = method.getName().substring("set".length()); return this.parameters.put(variable.toLowerCase(), args[0]); } int methodIndex = EventGenerator.this.methods.indexOf(method); if (methodIndex == -1) { throw new UnsupportedOperationException("Method " + method + " is not supported!"); } return new ArrayList<>(parameters.values()).get(methodIndex); } } private static class ForwardingEventMap<K, V> extends ForwardingMap<K, V> implements Map<K, V> { private Map<K, V> backingMap; private Function<K, V> function; private ForwardingEventMap(Map<K, V> backingMap, Function<K, V> function) { this.backingMap = backingMap; this.function = function; } @Override protected Map<K, V> delegate() { return this.backingMap; } @Override public V get(Object key) { V value = this.backingMap.get(key); if (value != null) { return value; } return this.backingMap.computeIfAbsent((K) key, this.function); } } }
6,601
0.601879
0.601424
171
37.602341
34.666748
164
false
false
0
0
0
0
0
0
0.51462
false
false
2
016b1a40bcd92b18d62c6648470a247e013a854f
14,233,521,641,195
09e153412d1e7f796402b24d47b96675df787c79
/src/main/java/fr/encheresnobyl/encherestroc/bll/BusinessException.java
40b93a95547b94c3ed31e57a696f43d4b8cd004f
[]
no_license
Mikael-LB/Encheres-Troc-Shared
https://github.com/Mikael-LB/Encheres-Troc-Shared
093a84c430dabd7c6b62737dd68c0cb0ad22be12
58ca9d73047c8b5f02a157793d21d8d893f9b9ef
refs/heads/main
2023-04-29T12:35:53.068000
2021-05-21T12:04:11
2021-05-21T12:04:11
367,374,326
0
0
null
false
2021-05-21T12:04:12
2021-05-14T13:40:33
2021-05-20T22:19:09
2021-05-21T12:04:11
710
0
0
0
Java
false
false
/** * */ package fr.encheresnobyl.encherestroc.bll; import java.util.ArrayList; import java.util.List; /** * @author mlebris2021 * */ public class BusinessException extends Exception { /** * */ private static final long serialVersionUID = 1L; private List<Integer> lstErrorCodes; /** * Constructor * @param lstErrorCodes */ public BusinessException() { this.lstErrorCodes = new ArrayList<>(); } /** * Getter * @return the lstErrorCodes : List<Integer> */ public List<Integer> getLstErrorCodes() { return lstErrorCodes; } /** * Method to add an error code to the list * @param errorCode */ public void addError(int errorCode) { this.lstErrorCodes.add(errorCode); } /** * Method to knox if the list of errors is empty or not * @return true if there is at one or more error code */ public boolean hasError() { return !this.lstErrorCodes.isEmpty(); } }
UTF-8
Java
924
java
BusinessException.java
Java
[ { "context": ".ArrayList;\nimport java.util.List;\n\n/**\n * @author mlebris2021\n *\n */\npublic class BusinessException extends Exc", "end": 134, "score": 0.9995781183242798, "start": 123, "tag": "USERNAME", "value": "mlebris2021" } ]
null
[]
/** * */ package fr.encheresnobyl.encherestroc.bll; import java.util.ArrayList; import java.util.List; /** * @author mlebris2021 * */ public class BusinessException extends Exception { /** * */ private static final long serialVersionUID = 1L; private List<Integer> lstErrorCodes; /** * Constructor * @param lstErrorCodes */ public BusinessException() { this.lstErrorCodes = new ArrayList<>(); } /** * Getter * @return the lstErrorCodes : List<Integer> */ public List<Integer> getLstErrorCodes() { return lstErrorCodes; } /** * Method to add an error code to the list * @param errorCode */ public void addError(int errorCode) { this.lstErrorCodes.add(errorCode); } /** * Method to knox if the list of errors is empty or not * @return true if there is at one or more error code */ public boolean hasError() { return !this.lstErrorCodes.isEmpty(); } }
924
0.667749
0.662338
56
15.5
17.734148
56
false
false
0
0
0
0
0
0
0.928571
false
false
2
4a8e4c023967e752a4553e8e2b19c05057630dc5
15,573,551,449,071
e352dd43f2e31e09864f2006f3cf9294a3c7ac63
/src/materials/Coin.java
76a32a66e0e73afee893728dbe9070211c123de3
[]
no_license
634-1-Printemps-2020/patterns-tp2-payam-HEG
https://github.com/634-1-Printemps-2020/patterns-tp2-payam-HEG
26c0195dcf7a2730be9e20638bfb5763f66795d6
07757adfe3bc0e85783c60605dc025d6b6bd48dd
refs/heads/master
2021-01-14T21:56:16.510000
2020-03-02T09:07:52
2020-03-02T09:07:52
242,771,904
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package materials; import java.util.Random; public class Coin { private CoinState coinState; /** * Change l'état de la pièce. * 50% de probabilité d'obtenir HEADS, 50% de probabilité d'obtenir TAILS */ public void throwCoin() { // TODO : Votre code ici Random rand = new Random(); int pileOuFace = rand.nextInt(2); if(pileOuFace == 0){ coinState = CoinState.HEADS; } else { coinState = CoinState.TAILS; } } public CoinState getState() { return coinState; } @Override public String toString() { return "Coin{" + "coinState=" + coinState + '}'; } }
UTF-8
Java
628
java
Coin.java
Java
[]
null
[]
package materials; import java.util.Random; public class Coin { private CoinState coinState; /** * Change l'état de la pièce. * 50% de probabilité d'obtenir HEADS, 50% de probabilité d'obtenir TAILS */ public void throwCoin() { // TODO : Votre code ici Random rand = new Random(); int pileOuFace = rand.nextInt(2); if(pileOuFace == 0){ coinState = CoinState.HEADS; } else { coinState = CoinState.TAILS; } } public CoinState getState() { return coinState; } @Override public String toString() { return "Coin{" + "coinState=" + coinState + '}'; } }
628
0.621795
0.612179
32
18.5
17.485708
75
false
false
0
0
0
0
0
0
0.3125
false
false
2
3686dcaac205b7f0e2acafa0cb293602909b9494
3,667,902,100,081
9d1870a895c63f540937f04a6285dd25ada5e52a
/chromecast-app-reverse-engineering/src/from-jd-gui/apz.java
bae5937068271bc6093d44365e9bea5ea8920dfb
[]
no_license
Churritosjesus/Chromecast-Reverse-Engineering
https://github.com/Churritosjesus/Chromecast-Reverse-Engineering
572aa97eb1fd65380ca0549b4166393505328ed4
29fae511060a820f2500a4e6e038dfdb591f4402
refs/heads/master
2023-06-04T10:27:15.869000
2015-10-27T10:43:11
2015-10-27T10:43:11
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
final class apz implements Runnable { apz(apu paramapu) {} public final void run() { if (!apu.d(this.a).i) { apu.c(this.a); apu.e(this.a); } } } /* Location: C:\DEV\android\dex2jar-2.1-SNAPSHOT\classes-dex2jar.jar!\apz.class * Java compiler version: 6 (50.0) * JD-Core Version: 0.7.1 */
UTF-8
Java
347
java
apz.java
Java
[]
null
[]
final class apz implements Runnable { apz(apu paramapu) {} public final void run() { if (!apu.d(this.a).i) { apu.c(this.a); apu.e(this.a); } } } /* Location: C:\DEV\android\dex2jar-2.1-SNAPSHOT\classes-dex2jar.jar!\apz.class * Java compiler version: 6 (50.0) * JD-Core Version: 0.7.1 */
347
0.556196
0.524496
20
16.4
20.597088
92
false
false
0
0
0
0
0
0
0.1
false
false
2
77641349e46f2cf464fff969e093938ed9c01a6d
9,363,028,735,072
f5ff13f66e33d1a38700ffe17b164180889a8c37
/src/com/prakat/InsightPredict/CI_IPD_TS07_07.java
4d0bc39bee56576deffc1ed386119c011c1a15ae
[]
no_license
abhik003/MyRep
https://github.com/abhik003/MyRep
22d684e5909d15ff1236f26d7542434f1de66452
2bcd0384ce281abd8395cadced19d197c7db4776
refs/heads/master
2017-12-22T04:39:39.414000
2014-10-07T03:44:59
2014-10-07T03:44:59
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * Project : Catayst Insight * Module Name: Insight predict * Script : CI_IPD_TS07_07 * Author : Aravind * Date : May.21.2014 * Description: To update project settings */ package com.prakat.InsightPredict; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Set; import java.util.concurrent.TimeUnit; import org.apache.commons.lang.StringUtils; import org.openqa.selenium.By; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.Keys; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.interactions.Actions; import org.openqa.selenium.remote.DesiredCapabilities; import org.openqa.selenium.remote.RemoteWebDriver; import org.testng.Assert; import org.testng.SkipException; import org.testng.annotations.BeforeTest; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import com.prakat.baseclass.BaseClass; import com.prakat.helpers.BusinessUtil; import com.prakat.helpers.ButtonHelper; import com.prakat.helpers.CheckBoxHelper; import com.prakat.helpers.ComboBoxHelper; import com.prakat.helpers.LabelHelper; import com.prakat.helpers.LinkHelper; import com.prakat.helpers.TextboxHelper; import com.prakat.helpers.Validation; //import com.prakat.helpers.TextboxHelper; import com.prakat.helpers.Xls_Reader; public class CI_IPD_TS07_07 extends InsightPredict { @Test (dataProvider = "getData") public static void CI_IPD_TS07_07(String ProjectName,String PASS,String FAIL,String Docs,String GroupBy,String OrderBy) throws Exception { try{ String title=BaseClass.driver.getTitle(); if(title.equalsIgnoreCase("Login - Catalyst Insight")){ BaseClass.driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); BusinessUtil.login(""); BusinessUtil.BuildInfo(); ButtonHelper.WaitForLoadMaskToComplete("WBtn_Right_Panel_id", 10); } LinkHelper.findElementWithTimeoutWait(By.id(BaseClass.OR.getProperty("WBtn_InsightPredict")), 5); LinkHelper.clickLinkById("WBtn_InsightPredict", "Free form search"); ButtonHelper.WaitForLoadMaskToComplete("WBtn_Right_Panel_id", 10); Thread.sleep(2000); int count1 = BaseClass.driver.findElements(By.xpath("//*[@id='predictAccordion']/h4/span[1]")).size(); int r1; for(r1=1; r1<= count1; r1++){ WebElement projects = BaseClass.driver.findElement(By.xpath("//*[@id='predictAccordion']/h4["+r1+"]/span[2]")); String Pname=projects.getText(); if(StringUtils.equalsIgnoreCase( Pname, ProjectName)){ WebElement Dashboard=BaseClass.driver.findElement(By.xpath("//*[@id='div_menuHolder']/div/div["+r1+"]/div[1]/a")); Dashboard.click(); break; } } Thread.sleep(8000); ButtonHelper.WaitForLoadMaskToComplete("WBtn_Right_Panel_id", 10); ButtonHelper.WaitForLoadMaskToComplete("WBtn_Right_Panel_id", 10); Actions builder = new Actions(BaseClass.driver); WebElement tagElement = BaseClass.driver.findElement(By.xpath("//*[@id='phaseHolder']/div[1]/div[1]")); builder.moveToElement(tagElement).build().perform(); Thread.sleep(1000); WebElement xyz=BaseClass.driver.findElement(By.id(BaseClass.OR.getProperty("WBtn_ManualEdit"))); xyz.click(); Thread.sleep(15000); ButtonHelper.clickById("WBtn_SelfAssignment", "Self assign"); Thread.sleep(5000); TextboxHelper.TextBoxClearByID("WCmBx_Maxdocs"); TextboxHelper.typeText("WCmBx_Maxdocs", Docs); if(BaseClass.driver.findElement(By.id("sel_MaxDocuments")).isDisplayed()) { BaseClass.logging("PASS:Buttons present"); } else { BaseClass.logging("FAIL:Buttons are not present"); } ComboBoxHelper.selectComboBoxItemByValue("WCmbx_GroupBy", GroupBy); ComboBoxHelper.selectComboBoxItemByValue("WCmb_OrderBy", OrderBy); ButtonHelper.clickById("WBtn_savechanges", "save"); ButtonHelper.WaitForLoadMaskToComplete("WBtn_Right_Panel_id", 10); Thread.sleep(3000); WebElement abcd=BaseClass.driver.findElement(By.xpath("//*[@id='insightDocumentBody']/div[5]/div[1]/button/span[1]")); JavascriptExecutor executor1 = (JavascriptExecutor)BaseClass.driver; executor1.executeScript("arguments[0].click();", abcd); Thread.sleep(1000); Actions manual1 = new Actions(BaseClass.driver); WebElement tagElement1 = BaseClass.driver.findElement(By.xpath("//*[@id='phaseHolder']/div[1]/div[1]")); builder.moveToElement(tagElement1).build().perform(); Thread.sleep(1000); WebElement manual2=BaseClass.driver.findElement(By.id(BaseClass.OR.getProperty("WBtn_ManualEdit"))); manual2.click(); Thread.sleep(15000); ButtonHelper.clickById("WBtn_SelfAssignment", "Self assign"); Thread.sleep(3000); // String testcount=LabelHelper.getTextForLabelbyID("WCmBx_Maxdocs"); String test=BaseClass.driver.findElement(By.id("sel_MaxDocuments")).getText(); if(test=="250") { BaseClass.logging("PASS:Changes saved successfully for manual stage"); } else { BaseClass.logging("FAIL:Changes not saved for manual stage"); } WebElement close2=BaseClass.driver.findElement(By.xpath("//*[@id='insightDocumentBody']/div[5]/div[1]/button/span[1]")); JavascriptExecutor executor2 = (JavascriptExecutor)BaseClass.driver; executor2.executeScript("arguments[0].click();", close2); Thread.sleep(1000);//close of manual Actions random = new Actions(BaseClass.driver); WebElement tagElement3 = BaseClass.driver.findElement(By.xpath("//*[@id='phaseHolder']/div[2]/div[1]")); random.moveToElement(tagElement3).build().perform(); Thread.sleep(1000); WebElement random1=BaseClass.driver.findElement(By.id(BaseClass.OR.getProperty("WBtn_ManualEdit"))); random1.click(); Thread.sleep(15000); ButtonHelper.clickById("WBtn_SelfAssignment", "Self assign"); Thread.sleep(3000); TextboxHelper.TextBoxClearByID("WCmBx_Maxdocs"); TextboxHelper.typeText("WCmBx_Maxdocs", Docs); ComboBoxHelper.selectComboBoxItemByValue("WCmbx_GroupBy", GroupBy); ComboBoxHelper.selectComboBoxItemByValue("WCmb_OrderBy", OrderBy); ButtonHelper.clickById("WBtn_savechanges", "save"); ButtonHelper.WaitForLoadMaskToComplete("WBtn_Right_Panel_id", 10); Thread.sleep(3000); WebElement randomclose=BaseClass.driver.findElement(By.xpath("//*[@id='insightDocumentBody']/div[5]/div[1]/button/span[1]")); JavascriptExecutor executor4 = (JavascriptExecutor)BaseClass.driver; executor4.executeScript("arguments[0].click();", randomclose); Thread.sleep(1000); Actions random2 = new Actions(BaseClass.driver); WebElement tagElement4 = BaseClass.driver.findElement(By.xpath("//*[@id='phaseHolder']/div[2]/div[1]")); random2.moveToElement(tagElement4).build().perform(); Thread.sleep(1000); WebElement randomedit=BaseClass.driver.findElement(By.id(BaseClass.OR.getProperty("WBtn_ManualEdit"))); randomedit.click(); Thread.sleep(15000); ButtonHelper.clickById("WBtn_SelfAssignment", "Self assign"); Thread.sleep(3000); String testcount1=LabelHelper.getTextForLabelbyID("WCmBx_Maxdocs"); if(testcount1=="250") { BaseClass.logging("PASS:Changes saved successfully for random stage"); } else { BaseClass.logging("FAIL:Changes not saved for random stage"); } WebElement randomclose1=BaseClass.driver.findElement(By.xpath("//*[@id='insightDocumentBody']/div[5]/div[1]/button/span[1]")); JavascriptExecutor executor5 = (JavascriptExecutor)BaseClass.driver; executor5.executeScript("arguments[0].click();", randomclose1); Thread.sleep(1000);//close of random Actions automated = new Actions(BaseClass.driver); WebElement tagElement5 = BaseClass.driver.findElement(By.xpath("//*[@id='phaseHolder']/div[3]/div[1]")); automated.moveToElement(tagElement5).build().perform(); Thread.sleep(1000); WebElement automatededit=BaseClass.driver.findElement(By.id(BaseClass.OR.getProperty("WBtn_ManualEdit"))); automatededit.click(); Thread.sleep(15000); ButtonHelper.clickById("WBtn_SelfAssignment", "Self assign"); Thread.sleep(3000); TextboxHelper.TextBoxClearByID("WCmBx_Maxdocs"); TextboxHelper.typeText("WCmBx_Maxdocs", Docs); ComboBoxHelper.selectComboBoxItemByValue("WCmbx_GroupBy", GroupBy); ComboBoxHelper.selectComboBoxItemByValue("WCmb_OrderBy", OrderBy); ButtonHelper.clickById("WBtn_savechanges", "save"); ButtonHelper.WaitForLoadMaskToComplete("WBtn_Right_Panel_id", 10); Thread.sleep(3000); WebElement automatedclose1=BaseClass.driver.findElement(By.xpath("//*[@id='insightDocumentBody']/div[5]/div[1]/button/span[1]")); JavascriptExecutor executor6 = (JavascriptExecutor)BaseClass.driver; executor6.executeScript("arguments[0].click();", automatedclose1); Thread.sleep(1000); Actions auto2 = new Actions(BaseClass.driver); WebElement tagElement6 = BaseClass.driver.findElement(By.xpath("//*[@id='phaseHolder']/div[3]/div[1]")); auto2.moveToElement(tagElement6).build().perform(); Thread.sleep(1000); WebElement autoedit=BaseClass.driver.findElement(By.id(BaseClass.OR.getProperty("WBtn_ManualEdit"))); autoedit.click(); Thread.sleep(15000); ButtonHelper.clickById("WBtn_SelfAssignment", "Self assign"); Thread.sleep(3000); String testcount3=LabelHelper.getTextForLabelbyID("WCmBx_Maxdocs"); if(testcount3=="250") { BaseClass.logging("PASS:Changes saved successfully for random stage"); } else { BaseClass.logging("FAIL:Changes not saved for random stage"); } WebElement autoclose1=BaseClass.driver.findElement(By.xpath("//*[@id='insightDocumentBody']/div[5]/div[1]/button/span[1]")); JavascriptExecutor executor7 = (JavascriptExecutor)BaseClass.driver; executor7.executeScript("arguments[0].click();", autoclose1); Thread.sleep(1000);//close of automated Actions QC = new Actions(BaseClass.driver); WebElement tagElement8 = BaseClass.driver.findElement(By.xpath("//*[@id='phaseHolder']/div[4]/div[1]")); QC.moveToElement(tagElement8).build().perform(); Thread.sleep(1000); WebElement QCedit=BaseClass.driver.findElement(By.id(BaseClass.OR.getProperty("WBtn_ManualEdit"))); QCedit.click(); Thread.sleep(15000); ButtonHelper.clickById("WBtn_SelfAssignment", "Self assign"); Thread.sleep(3000); TextboxHelper.TextBoxClearByID("WCmBx_Maxdocs"); TextboxHelper.typeText("WCmBx_Maxdocs", Docs); ComboBoxHelper.selectComboBoxItemByValue("WCmbx_GroupBy", GroupBy); ComboBoxHelper.selectComboBoxItemByValue("WCmb_OrderBy", OrderBy); ButtonHelper.clickById("WBtn_savechanges", "save"); ButtonHelper.WaitForLoadMaskToComplete("WBtn_Right_Panel_id", 10); Thread.sleep(3000); WebElement qcclose1=BaseClass.driver.findElement(By.xpath("//*[@id='insightDocumentBody']/div[5]/div[1]/button/span[1]")); JavascriptExecutor executor9 = (JavascriptExecutor)BaseClass.driver; executor9.executeScript("arguments[0].click();", qcclose1); Thread.sleep(1000); Actions qc2 = new Actions(BaseClass.driver); WebElement tagElement10 = BaseClass.driver.findElement(By.xpath("//*[@id='phaseHolder']/div[4]/div[1]")); qc2.moveToElement(tagElement10).build().perform(); Thread.sleep(1000); WebElement qcedit=BaseClass.driver.findElement(By.id(BaseClass.OR.getProperty("WBtn_ManualEdit"))); qcedit.click(); Thread.sleep(15000); ButtonHelper.clickById("WBtn_SelfAssignment", "Self assign"); Thread.sleep(3000); String testcount4=LabelHelper.getTextForLabelbyID("WCmBx_Maxdocs"); if(testcount3=="250") { BaseClass.logging("PASS:Changes saved successfully for random stage"); } else { BaseClass.logging("FAIL:Changes not saved for random stage"); } WebElement qcclose2=BaseClass.driver.findElement(By.xpath("//*[@id='insightDocumentBody']/div[5]/div[1]/button/span[1]")); JavascriptExecutor executor11 = (JavascriptExecutor)BaseClass.driver; executor11.executeScript("arguments[0].click();", qcclose2); Thread.sleep(1000);//close of qc Actions systematic = new Actions(BaseClass.driver); WebElement tagElement12 = BaseClass.driver.findElement(By.xpath("//*[@id='phaseHolder']/div[5]/div[1]")); systematic.moveToElement(tagElement12).build().perform(); Thread.sleep(1000); WebElement systematicedit=BaseClass.driver.findElement(By.id(BaseClass.OR.getProperty("WBtn_ManualEdit"))); systematicedit.click(); Thread.sleep(15000); ButtonHelper.clickById("WBtn_SelfAssignment", "Self assign"); Thread.sleep(3000); TextboxHelper.TextBoxClearByID("WCmBx_Maxdocs"); TextboxHelper.typeText("WCmBx_Maxdocs", Docs); ComboBoxHelper.selectComboBoxItemByValue("WCmbx_GroupBy", GroupBy); ComboBoxHelper.selectComboBoxItemByValue("WCmb_OrderBy", OrderBy); ButtonHelper.clickById("WBtn_savechanges", "save"); ButtonHelper.WaitForLoadMaskToComplete("WBtn_Right_Panel_id", 10); Thread.sleep(3000); WebElement systematicclose1=BaseClass.driver.findElement(By.xpath("//*[@id='insightDocumentBody']/div[5]/div[1]/button/span[1]")); JavascriptExecutor executor13 = (JavascriptExecutor)BaseClass.driver; executor13.executeScript("arguments[0].click();", systematicclose1); Thread.sleep(1000); Actions systematic2 = new Actions(BaseClass.driver); WebElement tagElement14 = BaseClass.driver.findElement(By.xpath("//*[@id='phaseHolder']/div[5]/div[1]")); systematic2.moveToElement(tagElement14).build().perform(); Thread.sleep(1000); WebElement systematicedit2=BaseClass.driver.findElement(By.id(BaseClass.OR.getProperty("WBtn_ManualEdit"))); systematicedit2.click(); Thread.sleep(15000); ButtonHelper.clickById("WBtn_SelfAssignment", "Self assign"); Thread.sleep(3000); String testcount5=LabelHelper.getTextForLabelbyID("WCmBx_Maxdocs"); if(testcount3=="250") { BaseClass.logging("PASS:Changes saved successfully for random stage"); } else { BaseClass.logging("FAIL:Changes not saved for random stage"); } WebElement systematicclose2=BaseClass.driver.findElement(By.xpath("//*[@id='insightDocumentBody']/div[5]/div[1]/button/span[1]")); JavascriptExecutor executor15 = (JavascriptExecutor)BaseClass.driver; executor15.executeScript("arguments[0].click();", systematicclose2); Thread.sleep(1000);//close of qc } finally{ } } @DataProvider public Object[][] getData() { return Xls_Reader.getData("CI_IPD_TS07_07"); } }
UTF-8
Java
14,455
java
CI_IPD_TS07_07.java
Java
[ { "context": "ict\n * Script : CI_IPD_TS07_07\n * Author : Aravind\n * Date : May.21.2014\n * Description: To up", "end": 122, "score": 0.9997416138648987, "start": 115, "tag": "NAME", "value": "Aravind" } ]
null
[]
/* * Project : Catayst Insight * Module Name: Insight predict * Script : CI_IPD_TS07_07 * Author : Aravind * Date : May.21.2014 * Description: To update project settings */ package com.prakat.InsightPredict; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Set; import java.util.concurrent.TimeUnit; import org.apache.commons.lang.StringUtils; import org.openqa.selenium.By; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.Keys; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.interactions.Actions; import org.openqa.selenium.remote.DesiredCapabilities; import org.openqa.selenium.remote.RemoteWebDriver; import org.testng.Assert; import org.testng.SkipException; import org.testng.annotations.BeforeTest; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import com.prakat.baseclass.BaseClass; import com.prakat.helpers.BusinessUtil; import com.prakat.helpers.ButtonHelper; import com.prakat.helpers.CheckBoxHelper; import com.prakat.helpers.ComboBoxHelper; import com.prakat.helpers.LabelHelper; import com.prakat.helpers.LinkHelper; import com.prakat.helpers.TextboxHelper; import com.prakat.helpers.Validation; //import com.prakat.helpers.TextboxHelper; import com.prakat.helpers.Xls_Reader; public class CI_IPD_TS07_07 extends InsightPredict { @Test (dataProvider = "getData") public static void CI_IPD_TS07_07(String ProjectName,String PASS,String FAIL,String Docs,String GroupBy,String OrderBy) throws Exception { try{ String title=BaseClass.driver.getTitle(); if(title.equalsIgnoreCase("Login - Catalyst Insight")){ BaseClass.driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); BusinessUtil.login(""); BusinessUtil.BuildInfo(); ButtonHelper.WaitForLoadMaskToComplete("WBtn_Right_Panel_id", 10); } LinkHelper.findElementWithTimeoutWait(By.id(BaseClass.OR.getProperty("WBtn_InsightPredict")), 5); LinkHelper.clickLinkById("WBtn_InsightPredict", "Free form search"); ButtonHelper.WaitForLoadMaskToComplete("WBtn_Right_Panel_id", 10); Thread.sleep(2000); int count1 = BaseClass.driver.findElements(By.xpath("//*[@id='predictAccordion']/h4/span[1]")).size(); int r1; for(r1=1; r1<= count1; r1++){ WebElement projects = BaseClass.driver.findElement(By.xpath("//*[@id='predictAccordion']/h4["+r1+"]/span[2]")); String Pname=projects.getText(); if(StringUtils.equalsIgnoreCase( Pname, ProjectName)){ WebElement Dashboard=BaseClass.driver.findElement(By.xpath("//*[@id='div_menuHolder']/div/div["+r1+"]/div[1]/a")); Dashboard.click(); break; } } Thread.sleep(8000); ButtonHelper.WaitForLoadMaskToComplete("WBtn_Right_Panel_id", 10); ButtonHelper.WaitForLoadMaskToComplete("WBtn_Right_Panel_id", 10); Actions builder = new Actions(BaseClass.driver); WebElement tagElement = BaseClass.driver.findElement(By.xpath("//*[@id='phaseHolder']/div[1]/div[1]")); builder.moveToElement(tagElement).build().perform(); Thread.sleep(1000); WebElement xyz=BaseClass.driver.findElement(By.id(BaseClass.OR.getProperty("WBtn_ManualEdit"))); xyz.click(); Thread.sleep(15000); ButtonHelper.clickById("WBtn_SelfAssignment", "Self assign"); Thread.sleep(5000); TextboxHelper.TextBoxClearByID("WCmBx_Maxdocs"); TextboxHelper.typeText("WCmBx_Maxdocs", Docs); if(BaseClass.driver.findElement(By.id("sel_MaxDocuments")).isDisplayed()) { BaseClass.logging("PASS:Buttons present"); } else { BaseClass.logging("FAIL:Buttons are not present"); } ComboBoxHelper.selectComboBoxItemByValue("WCmbx_GroupBy", GroupBy); ComboBoxHelper.selectComboBoxItemByValue("WCmb_OrderBy", OrderBy); ButtonHelper.clickById("WBtn_savechanges", "save"); ButtonHelper.WaitForLoadMaskToComplete("WBtn_Right_Panel_id", 10); Thread.sleep(3000); WebElement abcd=BaseClass.driver.findElement(By.xpath("//*[@id='insightDocumentBody']/div[5]/div[1]/button/span[1]")); JavascriptExecutor executor1 = (JavascriptExecutor)BaseClass.driver; executor1.executeScript("arguments[0].click();", abcd); Thread.sleep(1000); Actions manual1 = new Actions(BaseClass.driver); WebElement tagElement1 = BaseClass.driver.findElement(By.xpath("//*[@id='phaseHolder']/div[1]/div[1]")); builder.moveToElement(tagElement1).build().perform(); Thread.sleep(1000); WebElement manual2=BaseClass.driver.findElement(By.id(BaseClass.OR.getProperty("WBtn_ManualEdit"))); manual2.click(); Thread.sleep(15000); ButtonHelper.clickById("WBtn_SelfAssignment", "Self assign"); Thread.sleep(3000); // String testcount=LabelHelper.getTextForLabelbyID("WCmBx_Maxdocs"); String test=BaseClass.driver.findElement(By.id("sel_MaxDocuments")).getText(); if(test=="250") { BaseClass.logging("PASS:Changes saved successfully for manual stage"); } else { BaseClass.logging("FAIL:Changes not saved for manual stage"); } WebElement close2=BaseClass.driver.findElement(By.xpath("//*[@id='insightDocumentBody']/div[5]/div[1]/button/span[1]")); JavascriptExecutor executor2 = (JavascriptExecutor)BaseClass.driver; executor2.executeScript("arguments[0].click();", close2); Thread.sleep(1000);//close of manual Actions random = new Actions(BaseClass.driver); WebElement tagElement3 = BaseClass.driver.findElement(By.xpath("//*[@id='phaseHolder']/div[2]/div[1]")); random.moveToElement(tagElement3).build().perform(); Thread.sleep(1000); WebElement random1=BaseClass.driver.findElement(By.id(BaseClass.OR.getProperty("WBtn_ManualEdit"))); random1.click(); Thread.sleep(15000); ButtonHelper.clickById("WBtn_SelfAssignment", "Self assign"); Thread.sleep(3000); TextboxHelper.TextBoxClearByID("WCmBx_Maxdocs"); TextboxHelper.typeText("WCmBx_Maxdocs", Docs); ComboBoxHelper.selectComboBoxItemByValue("WCmbx_GroupBy", GroupBy); ComboBoxHelper.selectComboBoxItemByValue("WCmb_OrderBy", OrderBy); ButtonHelper.clickById("WBtn_savechanges", "save"); ButtonHelper.WaitForLoadMaskToComplete("WBtn_Right_Panel_id", 10); Thread.sleep(3000); WebElement randomclose=BaseClass.driver.findElement(By.xpath("//*[@id='insightDocumentBody']/div[5]/div[1]/button/span[1]")); JavascriptExecutor executor4 = (JavascriptExecutor)BaseClass.driver; executor4.executeScript("arguments[0].click();", randomclose); Thread.sleep(1000); Actions random2 = new Actions(BaseClass.driver); WebElement tagElement4 = BaseClass.driver.findElement(By.xpath("//*[@id='phaseHolder']/div[2]/div[1]")); random2.moveToElement(tagElement4).build().perform(); Thread.sleep(1000); WebElement randomedit=BaseClass.driver.findElement(By.id(BaseClass.OR.getProperty("WBtn_ManualEdit"))); randomedit.click(); Thread.sleep(15000); ButtonHelper.clickById("WBtn_SelfAssignment", "Self assign"); Thread.sleep(3000); String testcount1=LabelHelper.getTextForLabelbyID("WCmBx_Maxdocs"); if(testcount1=="250") { BaseClass.logging("PASS:Changes saved successfully for random stage"); } else { BaseClass.logging("FAIL:Changes not saved for random stage"); } WebElement randomclose1=BaseClass.driver.findElement(By.xpath("//*[@id='insightDocumentBody']/div[5]/div[1]/button/span[1]")); JavascriptExecutor executor5 = (JavascriptExecutor)BaseClass.driver; executor5.executeScript("arguments[0].click();", randomclose1); Thread.sleep(1000);//close of random Actions automated = new Actions(BaseClass.driver); WebElement tagElement5 = BaseClass.driver.findElement(By.xpath("//*[@id='phaseHolder']/div[3]/div[1]")); automated.moveToElement(tagElement5).build().perform(); Thread.sleep(1000); WebElement automatededit=BaseClass.driver.findElement(By.id(BaseClass.OR.getProperty("WBtn_ManualEdit"))); automatededit.click(); Thread.sleep(15000); ButtonHelper.clickById("WBtn_SelfAssignment", "Self assign"); Thread.sleep(3000); TextboxHelper.TextBoxClearByID("WCmBx_Maxdocs"); TextboxHelper.typeText("WCmBx_Maxdocs", Docs); ComboBoxHelper.selectComboBoxItemByValue("WCmbx_GroupBy", GroupBy); ComboBoxHelper.selectComboBoxItemByValue("WCmb_OrderBy", OrderBy); ButtonHelper.clickById("WBtn_savechanges", "save"); ButtonHelper.WaitForLoadMaskToComplete("WBtn_Right_Panel_id", 10); Thread.sleep(3000); WebElement automatedclose1=BaseClass.driver.findElement(By.xpath("//*[@id='insightDocumentBody']/div[5]/div[1]/button/span[1]")); JavascriptExecutor executor6 = (JavascriptExecutor)BaseClass.driver; executor6.executeScript("arguments[0].click();", automatedclose1); Thread.sleep(1000); Actions auto2 = new Actions(BaseClass.driver); WebElement tagElement6 = BaseClass.driver.findElement(By.xpath("//*[@id='phaseHolder']/div[3]/div[1]")); auto2.moveToElement(tagElement6).build().perform(); Thread.sleep(1000); WebElement autoedit=BaseClass.driver.findElement(By.id(BaseClass.OR.getProperty("WBtn_ManualEdit"))); autoedit.click(); Thread.sleep(15000); ButtonHelper.clickById("WBtn_SelfAssignment", "Self assign"); Thread.sleep(3000); String testcount3=LabelHelper.getTextForLabelbyID("WCmBx_Maxdocs"); if(testcount3=="250") { BaseClass.logging("PASS:Changes saved successfully for random stage"); } else { BaseClass.logging("FAIL:Changes not saved for random stage"); } WebElement autoclose1=BaseClass.driver.findElement(By.xpath("//*[@id='insightDocumentBody']/div[5]/div[1]/button/span[1]")); JavascriptExecutor executor7 = (JavascriptExecutor)BaseClass.driver; executor7.executeScript("arguments[0].click();", autoclose1); Thread.sleep(1000);//close of automated Actions QC = new Actions(BaseClass.driver); WebElement tagElement8 = BaseClass.driver.findElement(By.xpath("//*[@id='phaseHolder']/div[4]/div[1]")); QC.moveToElement(tagElement8).build().perform(); Thread.sleep(1000); WebElement QCedit=BaseClass.driver.findElement(By.id(BaseClass.OR.getProperty("WBtn_ManualEdit"))); QCedit.click(); Thread.sleep(15000); ButtonHelper.clickById("WBtn_SelfAssignment", "Self assign"); Thread.sleep(3000); TextboxHelper.TextBoxClearByID("WCmBx_Maxdocs"); TextboxHelper.typeText("WCmBx_Maxdocs", Docs); ComboBoxHelper.selectComboBoxItemByValue("WCmbx_GroupBy", GroupBy); ComboBoxHelper.selectComboBoxItemByValue("WCmb_OrderBy", OrderBy); ButtonHelper.clickById("WBtn_savechanges", "save"); ButtonHelper.WaitForLoadMaskToComplete("WBtn_Right_Panel_id", 10); Thread.sleep(3000); WebElement qcclose1=BaseClass.driver.findElement(By.xpath("//*[@id='insightDocumentBody']/div[5]/div[1]/button/span[1]")); JavascriptExecutor executor9 = (JavascriptExecutor)BaseClass.driver; executor9.executeScript("arguments[0].click();", qcclose1); Thread.sleep(1000); Actions qc2 = new Actions(BaseClass.driver); WebElement tagElement10 = BaseClass.driver.findElement(By.xpath("//*[@id='phaseHolder']/div[4]/div[1]")); qc2.moveToElement(tagElement10).build().perform(); Thread.sleep(1000); WebElement qcedit=BaseClass.driver.findElement(By.id(BaseClass.OR.getProperty("WBtn_ManualEdit"))); qcedit.click(); Thread.sleep(15000); ButtonHelper.clickById("WBtn_SelfAssignment", "Self assign"); Thread.sleep(3000); String testcount4=LabelHelper.getTextForLabelbyID("WCmBx_Maxdocs"); if(testcount3=="250") { BaseClass.logging("PASS:Changes saved successfully for random stage"); } else { BaseClass.logging("FAIL:Changes not saved for random stage"); } WebElement qcclose2=BaseClass.driver.findElement(By.xpath("//*[@id='insightDocumentBody']/div[5]/div[1]/button/span[1]")); JavascriptExecutor executor11 = (JavascriptExecutor)BaseClass.driver; executor11.executeScript("arguments[0].click();", qcclose2); Thread.sleep(1000);//close of qc Actions systematic = new Actions(BaseClass.driver); WebElement tagElement12 = BaseClass.driver.findElement(By.xpath("//*[@id='phaseHolder']/div[5]/div[1]")); systematic.moveToElement(tagElement12).build().perform(); Thread.sleep(1000); WebElement systematicedit=BaseClass.driver.findElement(By.id(BaseClass.OR.getProperty("WBtn_ManualEdit"))); systematicedit.click(); Thread.sleep(15000); ButtonHelper.clickById("WBtn_SelfAssignment", "Self assign"); Thread.sleep(3000); TextboxHelper.TextBoxClearByID("WCmBx_Maxdocs"); TextboxHelper.typeText("WCmBx_Maxdocs", Docs); ComboBoxHelper.selectComboBoxItemByValue("WCmbx_GroupBy", GroupBy); ComboBoxHelper.selectComboBoxItemByValue("WCmb_OrderBy", OrderBy); ButtonHelper.clickById("WBtn_savechanges", "save"); ButtonHelper.WaitForLoadMaskToComplete("WBtn_Right_Panel_id", 10); Thread.sleep(3000); WebElement systematicclose1=BaseClass.driver.findElement(By.xpath("//*[@id='insightDocumentBody']/div[5]/div[1]/button/span[1]")); JavascriptExecutor executor13 = (JavascriptExecutor)BaseClass.driver; executor13.executeScript("arguments[0].click();", systematicclose1); Thread.sleep(1000); Actions systematic2 = new Actions(BaseClass.driver); WebElement tagElement14 = BaseClass.driver.findElement(By.xpath("//*[@id='phaseHolder']/div[5]/div[1]")); systematic2.moveToElement(tagElement14).build().perform(); Thread.sleep(1000); WebElement systematicedit2=BaseClass.driver.findElement(By.id(BaseClass.OR.getProperty("WBtn_ManualEdit"))); systematicedit2.click(); Thread.sleep(15000); ButtonHelper.clickById("WBtn_SelfAssignment", "Self assign"); Thread.sleep(3000); String testcount5=LabelHelper.getTextForLabelbyID("WCmBx_Maxdocs"); if(testcount3=="250") { BaseClass.logging("PASS:Changes saved successfully for random stage"); } else { BaseClass.logging("FAIL:Changes not saved for random stage"); } WebElement systematicclose2=BaseClass.driver.findElement(By.xpath("//*[@id='insightDocumentBody']/div[5]/div[1]/button/span[1]")); JavascriptExecutor executor15 = (JavascriptExecutor)BaseClass.driver; executor15.executeScript("arguments[0].click();", systematicclose2); Thread.sleep(1000);//close of qc } finally{ } } @DataProvider public Object[][] getData() { return Xls_Reader.getData("CI_IPD_TS07_07"); } }
14,455
0.740574
0.711588
311
45.472668
33.288734
139
false
false
0
0
0
0
0
0
3.4791
false
false
2
519fd833ac485a631c062184627e1c619dffce5d
2,851,858,350,654
6c1021d80a301c0d3831e1ea873daddacc01c588
/core/src/main/java/com/jdcloud/sdk/service/JdcloudRequest.java
e0a09e63437ed13750eabb9d4db9a39bf7e20228
[ "Apache-2.0" ]
permissive
lidaobing/jdcloud-sdk-java
https://github.com/lidaobing/jdcloud-sdk-java
0f4b80abdd0d7245e917f23cb1305db08cc796c5
f872c3945ee5af3baa4e4bd048934b220f3db219
refs/heads/master
2020-03-12T00:02:49.294000
2018-04-20T08:09:44
2018-04-20T08:09:44
130,339,365
0
0
Apache-2.0
true
2020-01-09T08:07:40
2018-04-20T09:17:45
2018-04-20T09:17:48
2020-01-09T08:07:38
341
0
0
29
Java
false
false
package com.jdcloud.sdk.service; /** * 抽象出来的Request */ public class JdcloudRequest { private transient String regionId; private transient String version; public String getRegionId() { return regionId; } public void setRegionId(String regionId) { this.regionId = regionId; } public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } }
UTF-8
Java
481
java
JdcloudRequest.java
Java
[]
null
[]
package com.jdcloud.sdk.service; /** * 抽象出来的Request */ public class JdcloudRequest { private transient String regionId; private transient String version; public String getRegionId() { return regionId; } public void setRegionId(String regionId) { this.regionId = regionId; } public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } }
481
0.639066
0.639066
27
16.444445
16.148233
46
false
false
0
0
0
0
0
0
0.259259
false
false
2
d6dad9d165a958bde7686ea9a642998d86f2cbf1
15,152,644,635,002
965b7ad0216d0dfbbfa425a7089f186b45258fd4
/app/src/main/java/com/yiqiji/money/modules/common/view/sortlistview/PinyinComparator.java
69bebde3a004f6ea224e21da3bb0a0a31302a5a4
[]
no_license
295286769/yiqijinew
https://github.com/295286769/yiqijinew
e95400f053291c54a0fa54b6a17796686564a6b7
797293141e6632b82ff1bbe3e4dba378fccfd37a
refs/heads/master
2020-09-30T18:52:42.805000
2019-12-11T11:43:36
2019-12-11T11:43:36
227,350,950
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.yiqiji.money.modules.common.view.sortlistview; import java.util.Comparator; import com.yiqiji.money.modules.common.entity.Card; /** * * @author xiaanming * */ public class PinyinComparator implements Comparator<Card.Data> { public int compare(Card.Data o1, Card.Data o2) { if (o1.getLetters().equals("@") || o2.getLetters().equals("#")) { return -1; } else if (o1.getLetters().equals("#") || o2.getLetters().equals("@")) { return 1; } else { return o1.getLetters().compareTo(o2.getLetters()); } } }
UTF-8
Java
541
java
PinyinComparator.java
Java
[ { "context": "ey.modules.common.entity.Card;\n\n/**\n * \n * @author xiaanming\n * \n */\npublic class PinyinComparator implements ", "end": 171, "score": 0.9995470643043518, "start": 162, "tag": "USERNAME", "value": "xiaanming" } ]
null
[]
package com.yiqiji.money.modules.common.view.sortlistview; import java.util.Comparator; import com.yiqiji.money.modules.common.entity.Card; /** * * @author xiaanming * */ public class PinyinComparator implements Comparator<Card.Data> { public int compare(Card.Data o1, Card.Data o2) { if (o1.getLetters().equals("@") || o2.getLetters().equals("#")) { return -1; } else if (o1.getLetters().equals("#") || o2.getLetters().equals("@")) { return 1; } else { return o1.getLetters().compareTo(o2.getLetters()); } } }
541
0.665434
0.64695
24
21.541666
25.61409
74
false
false
0
0
0
0
0
0
1.25
false
false
2
b001c91fdcbf7f3b1a778f8d4000b415757efd58
15,152,644,634,270
1d928c3f90d4a0a9a3919a804597aa0a4aab19a3
/java/neo4j/2018/4/RWLockCompatibility.java
d93bb492ff678b04effd12c3fb0298d171728cdf
[]
no_license
rosoareslv/SED99
https://github.com/rosoareslv/SED99
d8b2ff5811e7f0ffc59be066a5a0349a92cbb845
a062c118f12b93172e31e8ca115ce3f871b64461
refs/heads/main
2023-02-22T21:59:02.703000
2021-01-28T19:40:51
2021-01-28T19:40:51
306,497,459
1
1
null
false
2020-11-24T20:56:18
2020-10-23T01:18:07
2020-11-24T20:46:14
2020-11-24T20:56:17
744,608
0
0
0
null
false
false
/* * Copyright (c) 2002-2018 "Neo Technology," * Network Engine for Objects in Lund AB [http://neotechnology.com] * * This file is part of Neo4j. * * Neo4j is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.neo4j.kernel.impl.locking; import org.junit.Ignore; import org.junit.Test; import java.io.File; import java.util.Random; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Future; import org.neo4j.kernel.DeadlockDetectedException; import static java.lang.System.currentTimeMillis; import static java.util.concurrent.TimeUnit.SECONDS; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.neo4j.kernel.impl.locking.ResourceTypes.NODE; /** * This is the test suite that tested the original (from 2007) lock manager. * It has been ported to test {@link org.neo4j.kernel.impl.locking.Locks} * to ensure implementors of that API don't fall in any of the traps this test suite sets for them. */ @Ignore( "Not a test. This is a compatibility suite, run from LockingCompatibilityTestSuite." ) public class RWLockCompatibility extends LockingCompatibilityTestSuite.Compatibility { public RWLockCompatibility( LockingCompatibilityTestSuite suite ) { super( suite ); } @Test public void testSingleThread() { try { clientA.releaseExclusive( NODE, 1L ); fail( "Invalid release should throw exception" ); } catch ( Exception e ) { // good } try { clientA.releaseShared( NODE, 1L ); fail( "Invalid release should throw exception" ); } catch ( Exception e ) { // good } clientA.acquireShared( LockTracer.NONE, NODE, 1L ); try { clientA.releaseExclusive( NODE, 1L ); fail( "Invalid release should throw exception" ); } catch ( Exception e ) { // good } clientA.releaseShared( NODE, 1L ); clientA.acquireExclusive( LockTracer.NONE, NODE, 1L ); try { clientA.releaseShared( NODE, 1L ); fail( "Invalid release should throw exception" ); } catch ( Exception e ) { // good } clientA.releaseExclusive( NODE, 1L ); clientA.acquireShared( LockTracer.NONE, NODE, 1L ); clientA.acquireExclusive( LockTracer.NONE, NODE, 1L ); clientA.releaseExclusive( NODE, 1L ); clientA.releaseShared( NODE, 1L ); clientA.acquireExclusive( LockTracer.NONE, NODE, 1L ); clientA.acquireShared( LockTracer.NONE, NODE, 1L ); clientA.releaseShared( NODE, 1L ); clientA.releaseExclusive( NODE, 1L ); for ( int i = 0; i < 10; i++ ) { if ( (i % 2) == 0 ) { clientA.acquireExclusive( LockTracer.NONE, NODE, 1L ); } else { clientA.acquireShared( LockTracer.NONE, NODE, 1L ); } } for ( int i = 9; i >= 0; i-- ) { if ( (i % 2) == 0 ) { clientA.releaseExclusive( NODE, 1L ); } else { clientA.releaseShared( NODE, 1L ); } } } @Test public void testMultipleThreads() throws Exception { LockWorker t1 = new LockWorker( "T1", locks ); LockWorker t2 = new LockWorker( "T2", locks ); LockWorker t3 = new LockWorker( "T3", locks ); LockWorker t4 = new LockWorker( "T4", locks ); long r1 = 1L; try { t1.getReadLock( r1, true ); t2.getReadLock( r1, true ); t3.getReadLock( r1, true ); Future<Void> t4Wait = t4.getWriteLock( r1, false ); t3.releaseReadLock( r1 ); t2.releaseReadLock( r1 ); assertTrue( !t4Wait.isDone() ); t1.releaseReadLock( r1 ); // now we can wait for write lock since it can be acquired // get write lock t4.awaitFuture( t4Wait ); t4.getReadLock( r1, true ); t4.getReadLock( r1, true ); // put readlock in queue Future<Void> t1Wait = t1.getReadLock( r1, false ); t4.getReadLock( r1, true ); t4.releaseReadLock( r1 ); t4.getWriteLock( r1, true ); t4.releaseWriteLock( r1 ); assertTrue( !t1Wait.isDone() ); t4.releaseWriteLock( r1 ); // get read lock t1.awaitFuture( t1Wait ); t4.releaseReadLock( r1 ); // t4 now has 1 readlock and t1 one readlock // let t1 drop readlock and t4 get write lock t4Wait = t4.getWriteLock( r1, false ); t1.releaseReadLock( r1 ); t4.awaitFuture( t4Wait ); t4.releaseReadLock( r1 ); t4.releaseWriteLock( r1 ); t4.getWriteLock( r1, true ); t1Wait = t1.getReadLock( r1, false ); Future<Void> t2Wait = t2.getReadLock( r1, false ); Future<Void> t3Wait = t3.getReadLock( r1, false ); t4.getReadLock( r1, true ); t4.releaseWriteLock( r1 ); t1.awaitFuture( t1Wait ); t2.awaitFuture( t2Wait ); t3.awaitFuture( t3Wait ); t1Wait = t1.getWriteLock( r1, false ); t2.releaseReadLock( r1 ); t4.releaseReadLock( r1 ); t3.releaseReadLock( r1 ); t1.awaitFuture( t1Wait ); t1.releaseWriteLock( r1 ); t2.getReadLock( r1, true ); t1.releaseReadLock( r1 ); t2.getWriteLock( r1, true ); t2.releaseWriteLock( r1 ); t2.releaseReadLock( r1 ); } catch ( Exception e ) { LockWorkFailureDump dumper = new LockWorkFailureDump( testDir.file( getClass().getSimpleName() ) ); File file = dumper.dumpState( locks, t1, t2, t3, t4 ); throw new RuntimeException( "Failed, forensics information dumped to " + file.getAbsolutePath(), e ); } finally { t1.close(); t2.close(); t3.close(); t4.close(); } } public class StressThread extends Thread { private final Random rand = new Random( currentTimeMillis() ); private final Object READ = new Object(); private final Object WRITE = new Object(); private final String name; private final int numberOfIterations; private final int depthCount; private final float readWriteRatio; private final CountDownLatch startSignal; private final Locks.Client client; private final long nodeId; private Exception error; StressThread( String name, int numberOfIterations, int depthCount, float readWriteRatio, long nodeId, CountDownLatch startSignal ) { super(); this.nodeId = nodeId; this.client = locks.newClient(); this.name = name; this.numberOfIterations = numberOfIterations; this.depthCount = depthCount; this.readWriteRatio = readWriteRatio; this.startSignal = startSignal; } @Override public void run() { try { startSignal.await(); java.util.Stack<Object> lockStack = new java.util.Stack<>(); for ( int i = 0; i < numberOfIterations; i++ ) { try { int depth = depthCount; do { float f = rand.nextFloat(); if ( f < readWriteRatio ) { client.acquireShared( LockTracer.NONE, NODE, nodeId ); lockStack.push( READ ); } else { client.acquireExclusive( LockTracer.NONE, NODE, nodeId ); lockStack.push( WRITE ); } } while ( --depth > 0 ); while ( !lockStack.isEmpty() ) { if ( lockStack.pop() == READ ) { client.releaseShared( NODE, nodeId ); } else { client.releaseExclusive( NODE, nodeId ); } } } catch ( DeadlockDetectedException ignored ) { } finally { while ( !lockStack.isEmpty() ) { if ( lockStack.pop() == READ ) { client.releaseShared( NODE, nodeId ); } else { client.releaseExclusive( NODE, nodeId ); } } } } } catch ( Exception e ) { error = e; } } @Override public String toString() { return this.name; } } @Test public void testStressMultipleThreads() throws Exception { long r1 = 1L; StressThread[] stressThreads = new StressThread[100]; CountDownLatch startSignal = new CountDownLatch( 1 ); for ( int i = 0; i < 100; i++ ) { stressThreads[i] = new StressThread( "Thread" + i, 100, 9, 0.50f, r1, startSignal ); } for ( int i = 0; i < 100; i++ ) { stressThreads[i].start(); } startSignal.countDown(); long end = currentTimeMillis() + SECONDS.toMillis( 2000 ); boolean anyAlive; while ( (anyAlive = anyAliveAndAllWell( stressThreads )) && currentTimeMillis() < end ) { sleepALittle(); } for ( StressThread stressThread : stressThreads ) { if ( stressThread.error != null ) { throw stressThread.error; } else if ( stressThread.isAlive() ) { for ( StackTraceElement stackTraceElement : stressThread.getStackTrace() ) { System.out.println( stackTraceElement ); } } } if ( anyAlive ) { throw new RuntimeException( "Expected all threads to complete." ); } } private void sleepALittle() { try { Thread.sleep( 100 ); } catch ( InterruptedException e ) { Thread.interrupted(); } } private boolean anyAliveAndAllWell( StressThread[] stressThreads ) { for ( StressThread stressThread : stressThreads ) { if ( stressThread.error != null ) { return false; } if ( stressThread.isAlive() ) { return true; } } return false; } }
UTF-8
Java
12,382
java
RWLockCompatibility.java
Java
[]
null
[]
/* * Copyright (c) 2002-2018 "Neo Technology," * Network Engine for Objects in Lund AB [http://neotechnology.com] * * This file is part of Neo4j. * * Neo4j is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.neo4j.kernel.impl.locking; import org.junit.Ignore; import org.junit.Test; import java.io.File; import java.util.Random; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Future; import org.neo4j.kernel.DeadlockDetectedException; import static java.lang.System.currentTimeMillis; import static java.util.concurrent.TimeUnit.SECONDS; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.neo4j.kernel.impl.locking.ResourceTypes.NODE; /** * This is the test suite that tested the original (from 2007) lock manager. * It has been ported to test {@link org.neo4j.kernel.impl.locking.Locks} * to ensure implementors of that API don't fall in any of the traps this test suite sets for them. */ @Ignore( "Not a test. This is a compatibility suite, run from LockingCompatibilityTestSuite." ) public class RWLockCompatibility extends LockingCompatibilityTestSuite.Compatibility { public RWLockCompatibility( LockingCompatibilityTestSuite suite ) { super( suite ); } @Test public void testSingleThread() { try { clientA.releaseExclusive( NODE, 1L ); fail( "Invalid release should throw exception" ); } catch ( Exception e ) { // good } try { clientA.releaseShared( NODE, 1L ); fail( "Invalid release should throw exception" ); } catch ( Exception e ) { // good } clientA.acquireShared( LockTracer.NONE, NODE, 1L ); try { clientA.releaseExclusive( NODE, 1L ); fail( "Invalid release should throw exception" ); } catch ( Exception e ) { // good } clientA.releaseShared( NODE, 1L ); clientA.acquireExclusive( LockTracer.NONE, NODE, 1L ); try { clientA.releaseShared( NODE, 1L ); fail( "Invalid release should throw exception" ); } catch ( Exception e ) { // good } clientA.releaseExclusive( NODE, 1L ); clientA.acquireShared( LockTracer.NONE, NODE, 1L ); clientA.acquireExclusive( LockTracer.NONE, NODE, 1L ); clientA.releaseExclusive( NODE, 1L ); clientA.releaseShared( NODE, 1L ); clientA.acquireExclusive( LockTracer.NONE, NODE, 1L ); clientA.acquireShared( LockTracer.NONE, NODE, 1L ); clientA.releaseShared( NODE, 1L ); clientA.releaseExclusive( NODE, 1L ); for ( int i = 0; i < 10; i++ ) { if ( (i % 2) == 0 ) { clientA.acquireExclusive( LockTracer.NONE, NODE, 1L ); } else { clientA.acquireShared( LockTracer.NONE, NODE, 1L ); } } for ( int i = 9; i >= 0; i-- ) { if ( (i % 2) == 0 ) { clientA.releaseExclusive( NODE, 1L ); } else { clientA.releaseShared( NODE, 1L ); } } } @Test public void testMultipleThreads() throws Exception { LockWorker t1 = new LockWorker( "T1", locks ); LockWorker t2 = new LockWorker( "T2", locks ); LockWorker t3 = new LockWorker( "T3", locks ); LockWorker t4 = new LockWorker( "T4", locks ); long r1 = 1L; try { t1.getReadLock( r1, true ); t2.getReadLock( r1, true ); t3.getReadLock( r1, true ); Future<Void> t4Wait = t4.getWriteLock( r1, false ); t3.releaseReadLock( r1 ); t2.releaseReadLock( r1 ); assertTrue( !t4Wait.isDone() ); t1.releaseReadLock( r1 ); // now we can wait for write lock since it can be acquired // get write lock t4.awaitFuture( t4Wait ); t4.getReadLock( r1, true ); t4.getReadLock( r1, true ); // put readlock in queue Future<Void> t1Wait = t1.getReadLock( r1, false ); t4.getReadLock( r1, true ); t4.releaseReadLock( r1 ); t4.getWriteLock( r1, true ); t4.releaseWriteLock( r1 ); assertTrue( !t1Wait.isDone() ); t4.releaseWriteLock( r1 ); // get read lock t1.awaitFuture( t1Wait ); t4.releaseReadLock( r1 ); // t4 now has 1 readlock and t1 one readlock // let t1 drop readlock and t4 get write lock t4Wait = t4.getWriteLock( r1, false ); t1.releaseReadLock( r1 ); t4.awaitFuture( t4Wait ); t4.releaseReadLock( r1 ); t4.releaseWriteLock( r1 ); t4.getWriteLock( r1, true ); t1Wait = t1.getReadLock( r1, false ); Future<Void> t2Wait = t2.getReadLock( r1, false ); Future<Void> t3Wait = t3.getReadLock( r1, false ); t4.getReadLock( r1, true ); t4.releaseWriteLock( r1 ); t1.awaitFuture( t1Wait ); t2.awaitFuture( t2Wait ); t3.awaitFuture( t3Wait ); t1Wait = t1.getWriteLock( r1, false ); t2.releaseReadLock( r1 ); t4.releaseReadLock( r1 ); t3.releaseReadLock( r1 ); t1.awaitFuture( t1Wait ); t1.releaseWriteLock( r1 ); t2.getReadLock( r1, true ); t1.releaseReadLock( r1 ); t2.getWriteLock( r1, true ); t2.releaseWriteLock( r1 ); t2.releaseReadLock( r1 ); } catch ( Exception e ) { LockWorkFailureDump dumper = new LockWorkFailureDump( testDir.file( getClass().getSimpleName() ) ); File file = dumper.dumpState( locks, t1, t2, t3, t4 ); throw new RuntimeException( "Failed, forensics information dumped to " + file.getAbsolutePath(), e ); } finally { t1.close(); t2.close(); t3.close(); t4.close(); } } public class StressThread extends Thread { private final Random rand = new Random( currentTimeMillis() ); private final Object READ = new Object(); private final Object WRITE = new Object(); private final String name; private final int numberOfIterations; private final int depthCount; private final float readWriteRatio; private final CountDownLatch startSignal; private final Locks.Client client; private final long nodeId; private Exception error; StressThread( String name, int numberOfIterations, int depthCount, float readWriteRatio, long nodeId, CountDownLatch startSignal ) { super(); this.nodeId = nodeId; this.client = locks.newClient(); this.name = name; this.numberOfIterations = numberOfIterations; this.depthCount = depthCount; this.readWriteRatio = readWriteRatio; this.startSignal = startSignal; } @Override public void run() { try { startSignal.await(); java.util.Stack<Object> lockStack = new java.util.Stack<>(); for ( int i = 0; i < numberOfIterations; i++ ) { try { int depth = depthCount; do { float f = rand.nextFloat(); if ( f < readWriteRatio ) { client.acquireShared( LockTracer.NONE, NODE, nodeId ); lockStack.push( READ ); } else { client.acquireExclusive( LockTracer.NONE, NODE, nodeId ); lockStack.push( WRITE ); } } while ( --depth > 0 ); while ( !lockStack.isEmpty() ) { if ( lockStack.pop() == READ ) { client.releaseShared( NODE, nodeId ); } else { client.releaseExclusive( NODE, nodeId ); } } } catch ( DeadlockDetectedException ignored ) { } finally { while ( !lockStack.isEmpty() ) { if ( lockStack.pop() == READ ) { client.releaseShared( NODE, nodeId ); } else { client.releaseExclusive( NODE, nodeId ); } } } } } catch ( Exception e ) { error = e; } } @Override public String toString() { return this.name; } } @Test public void testStressMultipleThreads() throws Exception { long r1 = 1L; StressThread[] stressThreads = new StressThread[100]; CountDownLatch startSignal = new CountDownLatch( 1 ); for ( int i = 0; i < 100; i++ ) { stressThreads[i] = new StressThread( "Thread" + i, 100, 9, 0.50f, r1, startSignal ); } for ( int i = 0; i < 100; i++ ) { stressThreads[i].start(); } startSignal.countDown(); long end = currentTimeMillis() + SECONDS.toMillis( 2000 ); boolean anyAlive; while ( (anyAlive = anyAliveAndAllWell( stressThreads )) && currentTimeMillis() < end ) { sleepALittle(); } for ( StressThread stressThread : stressThreads ) { if ( stressThread.error != null ) { throw stressThread.error; } else if ( stressThread.isAlive() ) { for ( StackTraceElement stackTraceElement : stressThread.getStackTrace() ) { System.out.println( stackTraceElement ); } } } if ( anyAlive ) { throw new RuntimeException( "Expected all threads to complete." ); } } private void sleepALittle() { try { Thread.sleep( 100 ); } catch ( InterruptedException e ) { Thread.interrupted(); } } private boolean anyAliveAndAllWell( StressThread[] stressThreads ) { for ( StressThread stressThread : stressThreads ) { if ( stressThread.error != null ) { return false; } if ( stressThread.isAlive() ) { return true; } } return false; } }
12,382
0.496446
0.480536
383
31.328981
23.377174
113
false
false
0
0
0
0
0
0
0.618799
false
false
2
17cad659118e7827c654beebecf3b547ff3e2362
15,152,644,631,429
d31504f95d4c66bcc166e51facaf4fc482a4478f
/src/mainEngine/contexts/guielements/Button.java
6faf18b986c686c0576da3f018ebd0e056134cb9
[]
no_license
team4015/4015_Robotics_Simulator
https://github.com/team4015/4015_Robotics_Simulator
de90adb6ece408f71c0732caff2be02d51cbc1af
fed52d64ae3b5ca231c344aaaa664acf92332975
refs/heads/master
2020-05-14T03:11:42.106000
2019-04-16T13:28:32
2019-04-16T13:28:32
181,693,254
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package mainEngine.contexts.guielements; import mainEngine.callbacks.DrawCallback2D; import mainEngine.callbacks.mouse.MouseClickCB; import mainEngine.graphicBuffers.ElementBufferObject; import mainEngine.graphicBuffers.VertexArrayObject; import mainEngine.logging.Logger; import org.lwjgl.BufferUtils; import java.awt.*; import java.awt.image.BufferedImage; import java.nio.ByteBuffer; import static org.lwjgl.opengl.GL11.*; import static org.lwjgl.opengl.GL12.GL_CLAMP_TO_EDGE; import static org.lwjgl.opengl.GL13.GL_TEXTURE0; import static org.lwjgl.opengl.GL13.glActiveTexture; import static org.lwjgl.opengl.GL15.GL_DYNAMIC_DRAW; import static org.lwjgl.opengl.GL15.GL_STATIC_DRAW; public class Button extends element implements DrawCallback2D{ Image buttonImage; BufferedImage buttonTexture; int textureID; VertexArrayObject vao; ElementBufferObject ibo; String buttonText; MouseClickCB cbFunction; Graphics2D g2d; float [] textureCoords; float [] vertices; boolean once = true; public Button(float xOffset, float yOffset, int width, int height, String buttonText, MouseClickCB cbFunction) { super(xOffset, yOffset, width, height,false); this.buttonText = buttonText; buttonImage = GuiTextureStore.getInstance().getButtonBySize(width,height); buttonTexture = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB); vao = new VertexArrayObject(); ibo = new ElementBufferObject(); g2d = buttonTexture.createGraphics(); g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,RenderingHints.VALUE_TEXT_ANTIALIAS_ON); initTextures(); this.cbFunction = cbFunction; } private void initTextures(){ textureID = glGenTextures(); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D,textureID); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glBindTexture(GL_TEXTURE_2D,0); textureCoords = new float[8]; textureCoords[0] = 0.0f; textureCoords[1] = 0.0f; textureCoords[2] = 0.0f; textureCoords[3] = 1.0f; textureCoords[4] = 1.0f; textureCoords[5] = 0.0f; textureCoords[6] = 1.0f; textureCoords[7] = 1.0f; vao.setData(1,textureCoords,true,GL_STATIC_DRAW); ibo.setData(new int[]{0,1,2,2,1,3}); } private void initVertices(){ vertices = new float [8]; float x = super.xOffset; float y = super.yOffset; vertices[0] = x; vertices[1] = y +super.height; vertices[2] =x; vertices[3] = y; vertices[4] = x+super.width; vertices[5] = y+super.height; vertices[6] = x+super.width; vertices[7] = y; vao.setData(0,vertices,true,GL_DYNAMIC_DRAW); } @Override public void update2D() { } @Override public void draw2D() { draw(g2d); hasMouseHover(); hasMouseClick(); initVertices(); uploadTexture(); drawTexture(); } private void drawTexture(){ vao.bind(); ibo.bind(); glBindTexture(GL_TEXTURE_2D,textureID); Logger.getInstance().clearErrors(); glDrawElements(GL_TRIANGLES,6,GL_UNSIGNED_INT,0L); Logger.getInstance().getErrors(); VertexArrayObject.unbind(); ElementBufferObject.unbind(); glBindTexture(GL_TEXTURE_2D,0); } private void uploadTexture(){ int [] pixels = new int [width*height]; ByteBuffer texBuf = BufferUtils.createByteBuffer(width*height * 4); buttonTexture.getRGB(0,0,width,height,pixels,0,width); for(int i =0 ; i<height; i++){ for(int j=0 ; j<width; j++){ int pixel = pixels[i * width + j]; texBuf.put((byte) ((pixel >> 16) & 0xFF)); // Red component texBuf.put((byte) ((pixel >> 8) & 0xFF)); // Green component texBuf.put((byte) (pixel & 0xFF)); // Blue component // texBuf.put((byte) ((pixel >> 24) & 0xFF)); } } texBuf.flip(); glBindTexture(GL_TEXTURE_2D,textureID); if(!once) { glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, width, height, GL_RGB, GL_UNSIGNED_BYTE, texBuf); }else { glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, texBuf); once = false; } glBindTexture(GL_TEXTURE_2D,0); } @Override public void draw(Graphics2D g) { g.drawImage(buttonImage,0,0,null); drawText(g2d,buttonText,"Times New Roman",20,10,30,Color.WHITE); } @Override public void onMouseClick() { cbFunction.onClick(); } @Override public void onMouseHover() { g2d.setPaint(Color.RED); g2d.drawRect(0,0,width-1,height-1); //System.out.println("Clicked"); } }
UTF-8
Java
5,240
java
Button.java
Java
[]
null
[]
package mainEngine.contexts.guielements; import mainEngine.callbacks.DrawCallback2D; import mainEngine.callbacks.mouse.MouseClickCB; import mainEngine.graphicBuffers.ElementBufferObject; import mainEngine.graphicBuffers.VertexArrayObject; import mainEngine.logging.Logger; import org.lwjgl.BufferUtils; import java.awt.*; import java.awt.image.BufferedImage; import java.nio.ByteBuffer; import static org.lwjgl.opengl.GL11.*; import static org.lwjgl.opengl.GL12.GL_CLAMP_TO_EDGE; import static org.lwjgl.opengl.GL13.GL_TEXTURE0; import static org.lwjgl.opengl.GL13.glActiveTexture; import static org.lwjgl.opengl.GL15.GL_DYNAMIC_DRAW; import static org.lwjgl.opengl.GL15.GL_STATIC_DRAW; public class Button extends element implements DrawCallback2D{ Image buttonImage; BufferedImage buttonTexture; int textureID; VertexArrayObject vao; ElementBufferObject ibo; String buttonText; MouseClickCB cbFunction; Graphics2D g2d; float [] textureCoords; float [] vertices; boolean once = true; public Button(float xOffset, float yOffset, int width, int height, String buttonText, MouseClickCB cbFunction) { super(xOffset, yOffset, width, height,false); this.buttonText = buttonText; buttonImage = GuiTextureStore.getInstance().getButtonBySize(width,height); buttonTexture = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB); vao = new VertexArrayObject(); ibo = new ElementBufferObject(); g2d = buttonTexture.createGraphics(); g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,RenderingHints.VALUE_TEXT_ANTIALIAS_ON); initTextures(); this.cbFunction = cbFunction; } private void initTextures(){ textureID = glGenTextures(); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D,textureID); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glBindTexture(GL_TEXTURE_2D,0); textureCoords = new float[8]; textureCoords[0] = 0.0f; textureCoords[1] = 0.0f; textureCoords[2] = 0.0f; textureCoords[3] = 1.0f; textureCoords[4] = 1.0f; textureCoords[5] = 0.0f; textureCoords[6] = 1.0f; textureCoords[7] = 1.0f; vao.setData(1,textureCoords,true,GL_STATIC_DRAW); ibo.setData(new int[]{0,1,2,2,1,3}); } private void initVertices(){ vertices = new float [8]; float x = super.xOffset; float y = super.yOffset; vertices[0] = x; vertices[1] = y +super.height; vertices[2] =x; vertices[3] = y; vertices[4] = x+super.width; vertices[5] = y+super.height; vertices[6] = x+super.width; vertices[7] = y; vao.setData(0,vertices,true,GL_DYNAMIC_DRAW); } @Override public void update2D() { } @Override public void draw2D() { draw(g2d); hasMouseHover(); hasMouseClick(); initVertices(); uploadTexture(); drawTexture(); } private void drawTexture(){ vao.bind(); ibo.bind(); glBindTexture(GL_TEXTURE_2D,textureID); Logger.getInstance().clearErrors(); glDrawElements(GL_TRIANGLES,6,GL_UNSIGNED_INT,0L); Logger.getInstance().getErrors(); VertexArrayObject.unbind(); ElementBufferObject.unbind(); glBindTexture(GL_TEXTURE_2D,0); } private void uploadTexture(){ int [] pixels = new int [width*height]; ByteBuffer texBuf = BufferUtils.createByteBuffer(width*height * 4); buttonTexture.getRGB(0,0,width,height,pixels,0,width); for(int i =0 ; i<height; i++){ for(int j=0 ; j<width; j++){ int pixel = pixels[i * width + j]; texBuf.put((byte) ((pixel >> 16) & 0xFF)); // Red component texBuf.put((byte) ((pixel >> 8) & 0xFF)); // Green component texBuf.put((byte) (pixel & 0xFF)); // Blue component // texBuf.put((byte) ((pixel >> 24) & 0xFF)); } } texBuf.flip(); glBindTexture(GL_TEXTURE_2D,textureID); if(!once) { glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, width, height, GL_RGB, GL_UNSIGNED_BYTE, texBuf); }else { glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, texBuf); once = false; } glBindTexture(GL_TEXTURE_2D,0); } @Override public void draw(Graphics2D g) { g.drawImage(buttonImage,0,0,null); drawText(g2d,buttonText,"Times New Roman",20,10,30,Color.WHITE); } @Override public void onMouseClick() { cbFunction.onClick(); } @Override public void onMouseHover() { g2d.setPaint(Color.RED); g2d.drawRect(0,0,width-1,height-1); //System.out.println("Clicked"); } }
5,240
0.621183
0.598282
186
27.172043
24.958513
116
false
false
0
0
0
0
0
0
0.978495
false
false
2
2eae289885bf47e0845738b1fe35fc8ac17393fc
23,708,219,536,035
e56238aa50078fc2dddfe360360c49b0afec4f83
/src/main/java/com/hoostec/hfz/service/HfzUserTaskRecordService.java
c16de6de8b8c1c83b8308d0cca65fdd763141598
[]
no_license
13327955131/hafuzhu
https://github.com/13327955131/hafuzhu
3a7e2c3e8e36291a9d0dddba17b5d90b2c34fe1e
764c6622ceca04eb977202a5386a3e5136eb424f
refs/heads/master
2023-04-14T08:53:41.746000
2021-03-26T07:15:12
2021-03-26T07:15:12
351,643,085
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.hoostec.hfz.service; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import com.hoostec.hfz.dao.HfzUserTaskRecordMapper; import com.hoostec.hfz.entity.HfzFeedback; import com.hoostec.hfz.entity.HfzUserTaskRecord; import java.util.List; import java.util.concurrent.TimeUnit; import com.hoostec.hfz.utils.PageUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.ValueOperations; import org.springframework.stereotype.Service;; @Service public class HfzUserTaskRecordService { @Autowired private HfzUserTaskRecordMapper hfzUserTaskRecord; @Autowired private RedisTemplate redisTemplate; /** * 任务数求和 * * @return **/ public int selectNumber(HfzUserTaskRecord obj) { int ret = hfzUserTaskRecord.selectNumber(obj); return ret; } /** * 任务数量 * * @return **/ public int selectCount(HfzUserTaskRecord obj) { int ret = hfzUserTaskRecord.selectCount(obj); return ret; } /** * 任务数量 * * @return **/ public int selectCountIndex(HfzUserTaskRecord obj) { int ret; String key=""; if(obj.getType()==1&&obj.getDegree()==null&&obj.getDayTime()==null){ key="taskVideoAllRedis"; }else if(obj.getType()==1 && obj.getDegree()!=null && null==obj.getDayTime()){ key="taskVideoDownloadAllRedis"; }else if(obj.getType()==2&&obj.getDegree()==null&&obj.getDayTime()==null){ key="taskBrowseAllRedis"; }else if(obj.getType()==2&&obj.getDegree()!=null&&obj.getDayTime()==null){ key="taskBrowseDownloadAllRedis"; }else if(obj.getType()==1&&obj.getDegree()==null&&obj.getDayTime()!=null){ key="taskVideoThsRedis"; }else if(obj.getType()==1&&obj.getDegree()!=null&&obj.getDayTime()!=null){ key="taskVideoDownloadThsRedis"; }else if(obj.getType()==2&&obj.getDegree()==null&&obj.getDayTime()!=null){ key="taskBrowseThsRedis"; }else if(obj.getType()==2&&obj.getDegree()!=null&&obj.getDayTime()!=null){ key="taskBrowseDownloadThsRedis"; } ValueOperations<String, Integer> operations = redisTemplate.opsForValue(); boolean hasKey = redisTemplate.hasKey(key); if (hasKey) { // 读取缓存 ret = operations.get(key); return ret; } else { ret = hfzUserTaskRecord.selectCount(obj); // 写入缓存 operations.set(key, ret, 10, TimeUnit.MINUTES); return ret; } // int ret = hfzUserTaskRecord.selectCount(obj); } /** * 插入接口 * * @return **/ public int insert(HfzUserTaskRecord obj) { int ret = hfzUserTaskRecord.insert(obj); return ret; } /** * 修改 * * @return **/ public int update(HfzUserTaskRecord obj) { int ret = hfzUserTaskRecord.update(obj); return ret; } /** * 查询全部 * * @return **/ public List<HfzUserTaskRecord> selectAll(HfzUserTaskRecord obj) { List<HfzUserTaskRecord> ret = hfzUserTaskRecord.selectAll(obj); return ret; } /** * 删除全部del_status=-1 * * @return **/ public int deleteAll(String[] ids) { int ret = hfzUserTaskRecord.deleteAll(ids); return ret; } /** * 批量查询 * * @param obj * @return */ public PageInfo<HfzUserTaskRecord> selectAll(HfzUserTaskRecord obj, PageUtil page) { PageHelper.startPage(page.getCurrentPage(), page.getPageSize()); List<HfzUserTaskRecord> list = hfzUserTaskRecord.selectAllUserTask(obj); PageInfo<HfzUserTaskRecord> appsPageInfo = new PageInfo<>(list); return appsPageInfo; } }
UTF-8
Java
4,031
java
HfzUserTaskRecordService.java
Java
[ { "context": "==null&&obj.getDayTime()==null){\n key=\"taskVideoAllRedis\";\n }else if(obj.getType()==1 && obj.getDeg", "end": 1393, "score": 0.7772847414016724, "start": 1376, "tag": "KEY", "value": "taskVideoAllRedis" }, { "context": "null && null==obj.getDayTime()){\n key=\"taskVideoDownloadAllRedis\";\n\n }else if(obj.getType()==2&&obj.getDegr", "end": 1525, "score": 0.8093353509902954, "start": 1500, "tag": "KEY", "value": "taskVideoDownloadAllRedis" }, { "context": "==null&&obj.getDayTime()==null){\n key=\"taskBrowseAllRedis\";\n }else if(obj.getType()==2&&obj.getDegre", "end": 1647, "score": 0.9217740297317505, "start": 1629, "tag": "KEY", "value": "taskBrowseAllRedis" }, { "context": "!=null&&obj.getDayTime()==null){\n key=\"taskBrowseDownloadAllRedis\";\n\n }else if(obj.getType()==1&&obj.getDegr", "end": 1776, "score": 0.7249337434768677, "start": 1750, "tag": "KEY", "value": "taskBrowseDownloadAllRedis" }, { "context": "==null&&obj.getDayTime()!=null){\n key=\"taskVideoThsRedis\";\n }else if(obj.getType()==1&&obj.getDegr", "end": 1897, "score": 0.9915434122085571, "start": 1880, "tag": "KEY", "value": "taskVideoThsRedis" }, { "context": "!=null&&obj.getDayTime()!=null){\n key=\"taskVideoDownloadThsRedis\";\n\n }else if(obj.getType()==2&&obj.getDegr", "end": 2026, "score": 0.9872611165046692, "start": 2001, "tag": "KEY", "value": "taskVideoDownloadThsRedis" }, { "context": "==null&&obj.getDayTime()!=null){\n key=\"taskBrowseThsRedis\";\n }else if(obj.getType()==2&&obj.getDegre", "end": 2148, "score": 0.9644396901130676, "start": 2130, "tag": "KEY", "value": "taskBrowseThsRedis" }, { "context": "!=null&&obj.getDayTime()!=null){\n key=\"taskBrowseDownloadThsRedis\";\n }\n\n ValueOperations<String, Inte", "end": 2277, "score": 0.9818646907806396, "start": 2251, "tag": "KEY", "value": "taskBrowseDownloadThsRedis" } ]
null
[]
package com.hoostec.hfz.service; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import com.hoostec.hfz.dao.HfzUserTaskRecordMapper; import com.hoostec.hfz.entity.HfzFeedback; import com.hoostec.hfz.entity.HfzUserTaskRecord; import java.util.List; import java.util.concurrent.TimeUnit; import com.hoostec.hfz.utils.PageUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.ValueOperations; import org.springframework.stereotype.Service;; @Service public class HfzUserTaskRecordService { @Autowired private HfzUserTaskRecordMapper hfzUserTaskRecord; @Autowired private RedisTemplate redisTemplate; /** * 任务数求和 * * @return **/ public int selectNumber(HfzUserTaskRecord obj) { int ret = hfzUserTaskRecord.selectNumber(obj); return ret; } /** * 任务数量 * * @return **/ public int selectCount(HfzUserTaskRecord obj) { int ret = hfzUserTaskRecord.selectCount(obj); return ret; } /** * 任务数量 * * @return **/ public int selectCountIndex(HfzUserTaskRecord obj) { int ret; String key=""; if(obj.getType()==1&&obj.getDegree()==null&&obj.getDayTime()==null){ key="taskVideoAllRedis"; }else if(obj.getType()==1 && obj.getDegree()!=null && null==obj.getDayTime()){ key="taskVideoDownloadAllRedis"; }else if(obj.getType()==2&&obj.getDegree()==null&&obj.getDayTime()==null){ key="taskBrowseAllRedis"; }else if(obj.getType()==2&&obj.getDegree()!=null&&obj.getDayTime()==null){ key="taskBrowseDownloadAllRedis"; }else if(obj.getType()==1&&obj.getDegree()==null&&obj.getDayTime()!=null){ key="taskVideoThsRedis"; }else if(obj.getType()==1&&obj.getDegree()!=null&&obj.getDayTime()!=null){ key="taskVideoDownloadThsRedis"; }else if(obj.getType()==2&&obj.getDegree()==null&&obj.getDayTime()!=null){ key="taskBrowseThsRedis"; }else if(obj.getType()==2&&obj.getDegree()!=null&&obj.getDayTime()!=null){ key="taskBrowseDownloadThsRedis"; } ValueOperations<String, Integer> operations = redisTemplate.opsForValue(); boolean hasKey = redisTemplate.hasKey(key); if (hasKey) { // 读取缓存 ret = operations.get(key); return ret; } else { ret = hfzUserTaskRecord.selectCount(obj); // 写入缓存 operations.set(key, ret, 10, TimeUnit.MINUTES); return ret; } // int ret = hfzUserTaskRecord.selectCount(obj); } /** * 插入接口 * * @return **/ public int insert(HfzUserTaskRecord obj) { int ret = hfzUserTaskRecord.insert(obj); return ret; } /** * 修改 * * @return **/ public int update(HfzUserTaskRecord obj) { int ret = hfzUserTaskRecord.update(obj); return ret; } /** * 查询全部 * * @return **/ public List<HfzUserTaskRecord> selectAll(HfzUserTaskRecord obj) { List<HfzUserTaskRecord> ret = hfzUserTaskRecord.selectAll(obj); return ret; } /** * 删除全部del_status=-1 * * @return **/ public int deleteAll(String[] ids) { int ret = hfzUserTaskRecord.deleteAll(ids); return ret; } /** * 批量查询 * * @param obj * @return */ public PageInfo<HfzUserTaskRecord> selectAll(HfzUserTaskRecord obj, PageUtil page) { PageHelper.startPage(page.getCurrentPage(), page.getPageSize()); List<HfzUserTaskRecord> list = hfzUserTaskRecord.selectAllUserTask(obj); PageInfo<HfzUserTaskRecord> appsPageInfo = new PageInfo<>(list); return appsPageInfo; } }
4,031
0.61194
0.609158
138
27.652174
25.158815
88
false
false
0
0
0
0
0
0
0.405797
false
false
2
aea173b4bc559f79c5d819436c9bfebafb957ce8
23,708,219,538,382
dc8306edeebb06363093372ef34361a640d47963
/nested_class/member_inner.java
3a661833bcb45030b5e2e2ea6e75f6ae29d67bc7
[]
no_license
Apurvak2098/synchronisation_tables
https://github.com/Apurvak2098/synchronisation_tables
029a34c9db6b58774cde87c9a0450b4892092e81
59ed4680e6f4e5ef7ac294d628faa6734b46d5e9
refs/heads/main
2023-05-09T21:40:16.278000
2021-06-10T07:53:38
2021-06-10T07:53:38
375,428,286
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package Nestedclass; class A{ void set() { } static class B{ void get() { System.out.println("in get"); } } } public class nestedclass { public static void main(String[] args) { A.B obj =new A.B();//{new A().new B()-member inner class} obj.get(); }}
UTF-8
Java
273
java
member_inner.java
Java
[]
null
[]
package Nestedclass; class A{ void set() { } static class B{ void get() { System.out.println("in get"); } } } public class nestedclass { public static void main(String[] args) { A.B obj =new A.B();//{new A().new B()-member inner class} obj.get(); }}
273
0.59707
0.59707
20
12.65
15.678887
59
false
false
0
0
0
0
0
0
1.1
false
false
2
21a18588ba658eee09a19bfc4cb13b74f9bac08b
24,532,853,243,153
9fb7d7ab108e403d9dadc576b0b02a1de6ce1ab9
/resolver/src/main/java/munch/data/resolver/tag/TagMapper.java
79f86245ee6144f59b8268bd078f9f7b7ce57096
[]
no_license
johndpope/munch-data
https://github.com/johndpope/munch-data
806c355b1f7e0f0205e96fd87bf903b26e2f28c6
15bcf36a069e90b3bbebe84937cab4c36f3e00dd
refs/heads/master
2023-03-17T23:03:33.371000
2019-03-28T08:30:18
2019-03-28T08:30:18
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package munch.data.resolver.tag; import com.google.common.collect.ImmutableSet; import com.google.common.io.Resources; import munch.data.client.TagClient; import munch.data.place.Place; import munch.data.tag.Tag; import org.apache.commons.lang3.StringUtils; import javax.inject.Inject; import java.io.IOException; import java.net.URL; import java.nio.charset.Charset; import java.util.*; import java.util.function.BiFunction; import java.util.stream.Collectors; /** * Created by: Fuxing * Date: 1/10/18 * Time: 3:26 PM * Project: munch-data */ @SuppressWarnings("UnstableApiUsage") public class TagMapper { private Map<String, Set<Tag>> tagsMap = new HashMap<>(); private Set<String> postfixes; private Set<String> prefixes; private Set<String> blacklist; private Set<String> divider; @Inject public TagMapper(TagClient tagClient) { postfixes = openResource("tag-postfix.txt"); prefixes = openResource("tag-prefix.txt"); blacklist = openResource("tag-blacklist.txt"); divider = openResource("tag-divider.txt"); tagClient.iterator().forEachRemaining(tag -> { // Put Names tag.getNames().forEach(s -> { tagsMap.computeIfAbsent(s.toLowerCase(), s1 -> new HashSet<>()).add(tag); }); // Put Remapping tag.getPlace().getRemapping().forEach(s -> { tagsMap.computeIfAbsent(s.toLowerCase(), s1 -> new HashSet<>()).add(tag); }); }); } public Set<Tag> get(String name) { name = StringUtils.stripAccents(name); name = StringUtils.lowerCase(name); name = StringUtils.normalizeSpace(name); if (StringUtils.isBlank(name)) return Set.of(); Set<Tag> tags = tagsMap.get(name); if (tags != null) return tags; // Keep track all the versions Set<String> versions = getVersions(name); Map<String, Set<Tag>> mapped = new HashMap<>(); versions.forEach(s -> { Set<Tag> set = tagsMap.get(s); if (set == null) return; mapped.put(s, set); }); if (mapped.isEmpty()) return Set.of(); // Get the longest version reduced Tag, to ensure reliability of tag return mapped.entrySet().stream() .min((o1, o2) -> Integer.compare(o2.getKey().length(), o1.getKey().length())) .map(Map.Entry::getValue) .orElse(Set.of()); } /** * @param text to reduce into * @return multiple versions of the tag */ private Set<String> getVersions(String text) { Set<String> versions = new HashSet<>(); versions.add(text); // Replace all Dividers mapReduce(divider, versions, (s, tag) -> tag.replace(s, " ")); // Trim Prefix mapReduce(prefixes, versions, (s, tag) -> StringUtils.removeStart(tag, s)); // Trim Postfix mapReduce(postfixes, versions, (s, tag) -> StringUtils.removeEnd(tag, s)); // Remove all blacklisted versions.removeAll(blacklist); return versions; } private Set<String> mapReduce(Set<String> set, Set<String> versions, BiFunction<String, String, String> map) { Set<String> reduced = new HashSet<>(); set.forEach(s -> { versions.forEach(tag -> { tag = map.apply(s, tag); tag = tag.trim(); if (StringUtils.isBlank(tag)) return; reduced.add(StringUtils.normalizeSpace(tag)); }); }); return reduced; } /** * Convert Collections of Tag into list of Place.Tag * - Distinct & Ordered as input */ public List<Place.Tag> mapDistinct(Collection<Tag> tags) { return tags.stream() .map(TagMapper::parse) .distinct() .collect(Collectors.toList()); } /** * @param tag converted to Place.Tag * @return Place.Tag */ private static Place.Tag parse(Tag tag) { Place.Tag placeTag = new Place.Tag(); placeTag.setTagId(tag.getTagId()); placeTag.setName(tag.getName()); placeTag.setType(tag.getType()); return placeTag; } private static Set<String> openResource(String resource) { URL url = Resources.getResource(resource); Set<String> tags = new HashSet<>(); try { Resources.readLines(url, Charset.defaultCharset()).forEach(s -> { if (StringUtils.isBlank(s)) return; tags.add(s.toLowerCase()); }); } catch (IOException e) { throw new RuntimeException(e); } return ImmutableSet.copyOf(tags); } }
UTF-8
Java
4,770
java
TagMapper.java
Java
[ { "context": "t java.util.stream.Collectors;\n\n/**\n * Created by: Fuxing\n * Date: 1/10/18\n * Time: 3:26 PM\n * Project: mun", "end": 490, "score": 0.9977385997772217, "start": 484, "tag": "USERNAME", "value": "Fuxing" } ]
null
[]
package munch.data.resolver.tag; import com.google.common.collect.ImmutableSet; import com.google.common.io.Resources; import munch.data.client.TagClient; import munch.data.place.Place; import munch.data.tag.Tag; import org.apache.commons.lang3.StringUtils; import javax.inject.Inject; import java.io.IOException; import java.net.URL; import java.nio.charset.Charset; import java.util.*; import java.util.function.BiFunction; import java.util.stream.Collectors; /** * Created by: Fuxing * Date: 1/10/18 * Time: 3:26 PM * Project: munch-data */ @SuppressWarnings("UnstableApiUsage") public class TagMapper { private Map<String, Set<Tag>> tagsMap = new HashMap<>(); private Set<String> postfixes; private Set<String> prefixes; private Set<String> blacklist; private Set<String> divider; @Inject public TagMapper(TagClient tagClient) { postfixes = openResource("tag-postfix.txt"); prefixes = openResource("tag-prefix.txt"); blacklist = openResource("tag-blacklist.txt"); divider = openResource("tag-divider.txt"); tagClient.iterator().forEachRemaining(tag -> { // Put Names tag.getNames().forEach(s -> { tagsMap.computeIfAbsent(s.toLowerCase(), s1 -> new HashSet<>()).add(tag); }); // Put Remapping tag.getPlace().getRemapping().forEach(s -> { tagsMap.computeIfAbsent(s.toLowerCase(), s1 -> new HashSet<>()).add(tag); }); }); } public Set<Tag> get(String name) { name = StringUtils.stripAccents(name); name = StringUtils.lowerCase(name); name = StringUtils.normalizeSpace(name); if (StringUtils.isBlank(name)) return Set.of(); Set<Tag> tags = tagsMap.get(name); if (tags != null) return tags; // Keep track all the versions Set<String> versions = getVersions(name); Map<String, Set<Tag>> mapped = new HashMap<>(); versions.forEach(s -> { Set<Tag> set = tagsMap.get(s); if (set == null) return; mapped.put(s, set); }); if (mapped.isEmpty()) return Set.of(); // Get the longest version reduced Tag, to ensure reliability of tag return mapped.entrySet().stream() .min((o1, o2) -> Integer.compare(o2.getKey().length(), o1.getKey().length())) .map(Map.Entry::getValue) .orElse(Set.of()); } /** * @param text to reduce into * @return multiple versions of the tag */ private Set<String> getVersions(String text) { Set<String> versions = new HashSet<>(); versions.add(text); // Replace all Dividers mapReduce(divider, versions, (s, tag) -> tag.replace(s, " ")); // Trim Prefix mapReduce(prefixes, versions, (s, tag) -> StringUtils.removeStart(tag, s)); // Trim Postfix mapReduce(postfixes, versions, (s, tag) -> StringUtils.removeEnd(tag, s)); // Remove all blacklisted versions.removeAll(blacklist); return versions; } private Set<String> mapReduce(Set<String> set, Set<String> versions, BiFunction<String, String, String> map) { Set<String> reduced = new HashSet<>(); set.forEach(s -> { versions.forEach(tag -> { tag = map.apply(s, tag); tag = tag.trim(); if (StringUtils.isBlank(tag)) return; reduced.add(StringUtils.normalizeSpace(tag)); }); }); return reduced; } /** * Convert Collections of Tag into list of Place.Tag * - Distinct & Ordered as input */ public List<Place.Tag> mapDistinct(Collection<Tag> tags) { return tags.stream() .map(TagMapper::parse) .distinct() .collect(Collectors.toList()); } /** * @param tag converted to Place.Tag * @return Place.Tag */ private static Place.Tag parse(Tag tag) { Place.Tag placeTag = new Place.Tag(); placeTag.setTagId(tag.getTagId()); placeTag.setName(tag.getName()); placeTag.setType(tag.getType()); return placeTag; } private static Set<String> openResource(String resource) { URL url = Resources.getResource(resource); Set<String> tags = new HashSet<>(); try { Resources.readLines(url, Charset.defaultCharset()).forEach(s -> { if (StringUtils.isBlank(s)) return; tags.add(s.toLowerCase()); }); } catch (IOException e) { throw new RuntimeException(e); } return ImmutableSet.copyOf(tags); } }
4,770
0.584696
0.581551
157
29.382166
23.188658
114
false
false
0
0
0
0
0
0
0.611465
false
false
2
f3e375f5fe29077c2dcbb3a2cf5c321a528b55ef
23,502,061,087,244
ead99de3d0c25580b4d633ec74c9761475c335da
/swampmachine-core/src/main/java/net/kiberion/swampmachine/events/ChangeStateEvent.java
3d2f35b955df60eefab9c36b6b9ffc5db1c53a6a
[ "Apache-2.0" ]
permissive
kibertoad/swampmachine
https://github.com/kibertoad/swampmachine
9840704fd907d8e0c2ed57c9deeca9960c02aead
b17b4121f4fffccb862c798b188c4e19e61ed4c1
refs/heads/master
2021-01-17T03:19:41.162000
2018-06-12T11:10:30
2018-06-12T11:10:30
41,201,298
5
2
null
false
2016-12-12T21:28:58
2015-08-22T09:56:19
2016-12-12T18:28:09
2016-12-12T21:28:58
1,253
1
1
3
Java
null
null
package net.kiberion.swampmachine.events; import org.springframework.context.ApplicationEvent; import lombok.Getter; import net.kiberion.swampmachine.annotations.ConstructableEntity; @ConstructableEntity(id = "changeState", constructorProperties = {"source", "stateId"}) public class ChangeStateEvent extends ApplicationEvent{ /** * */ private static final long serialVersionUID = 1377301404419621755L; @Getter private final String stateCode; public ChangeStateEvent(Object source, String stateId) { super(source); this.stateCode = stateId; } @Override public String toString() { return "Change to state: "+stateCode; } }
UTF-8
Java
709
java
ChangeStateEvent.java
Java
[]
null
[]
package net.kiberion.swampmachine.events; import org.springframework.context.ApplicationEvent; import lombok.Getter; import net.kiberion.swampmachine.annotations.ConstructableEntity; @ConstructableEntity(id = "changeState", constructorProperties = {"source", "stateId"}) public class ChangeStateEvent extends ApplicationEvent{ /** * */ private static final long serialVersionUID = 1377301404419621755L; @Getter private final String stateCode; public ChangeStateEvent(Object source, String stateId) { super(source); this.stateCode = stateId; } @Override public String toString() { return "Change to state: "+stateCode; } }
709
0.706629
0.679831
29
23.448277
25.218475
87
false
false
0
0
0
0
0
0
0.413793
false
false
2
fa4109249aebd7ce6bf4aafa752f9d8203bb7e3a
25,443,386,311,454
68fbbb8284b990fd3bb6cee173e2e737c2a6c1a5
/vertigo-dynamo-api/src/main/java/io/vertigo/dynamo/search/model/SearchQuery.java
9c53e78123e041fa2dc39206124754287b4967b5
[ "Apache-2.0" ]
permissive
evernat/vertigo
https://github.com/evernat/vertigo
cca5222e12d59e21cc13e2daa7ab1bb728e18275
962d7b8d41a6c9f740312a92e643b046b4b22696
refs/heads/master
2021-01-17T15:56:17.625000
2019-11-12T15:56:53
2019-11-12T15:56:53
82,934,842
0
0
null
true
2017-02-23T14:24:49
2017-02-23T14:24:49
2017-02-07T10:57:26
2017-02-22T22:30:09
13,866
0
0
0
null
null
null
/** * vertigo - simple java starter * * Copyright (C) 2013-2019, Vertigo.io, KleeGroup, direction.technique@kleegroup.com (http://www.kleegroup.com) * KleeGroup, Centre d'affaire la Boursidiere - BP 159 - 92357 Le Plessis Robinson Cedex - France * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.vertigo.dynamo.search.model; import java.io.Serializable; import java.util.Optional; import io.vertigo.core.definition.DefinitionReference; import io.vertigo.dynamo.collections.ListFilter; import io.vertigo.dynamo.collections.metamodel.FacetDefinition; import io.vertigo.dynamo.collections.model.FacetedQuery; import io.vertigo.dynamo.domain.metamodel.DtField; import io.vertigo.lang.Assertion; /** * Critères de recherche. * @author npiedeloup */ public final class SearchQuery implements Serializable { private static final long serialVersionUID = -3215786603726103410L; private final ListFilter queryListFilter; private final Optional<ListFilter> securityListFilter; //Informations optionnelles pour booster la pertinence des documents plus récent (null si inutilisé) private final String boostedDocumentDateFieldName; private final Integer numDaysOfBoostRefDocument; private final Integer mostRecentBoost; private final Optional<FacetedQuery> facetedQuery; private final DefinitionReference<FacetDefinition> clusteringFacetDefinitionRef; /** * Constructor. * @param facetedQuery facetedQueryDefinition * @param queryListFilter Filtre principal correspondant aux critères de la recherche * @param securityListFilter Filtre de sécurité * @param clusteringFacetDefinition Facet utilisée pour cluster des resultats (null si non utilisé) * @param boostedDocumentDateField Nom du champ portant la date du document (null si non utilisé) * @param numDaysOfBoostRefDocument Age des documents servant de référence pour le boost des plus récents par rapport à eux (null si non utilisé) * @param mostRecentBoost Boost relatif maximum entre les plus récents et ceux ayant l'age de référence (doit être > 1) (null si non utilisé) */ SearchQuery( final Optional<FacetedQuery> facetedQuery, final ListFilter queryListFilter, final Optional<ListFilter> securityListFilter, final FacetDefinition clusteringFacetDefinition, final DtField boostedDocumentDateField, final Integer numDaysOfBoostRefDocument, final Integer mostRecentBoost) { Assertion.checkNotNull(facetedQuery); Assertion.checkNotNull(queryListFilter); Assertion.checkNotNull(securityListFilter); Assertion.when(boostedDocumentDateField != null) .check(() -> numDaysOfBoostRefDocument != null && mostRecentBoost != null, "Lorsque le boost des documents récents est activé, numDaysOfBoostRefDocument et mostRecentBoost sont obligatoires."); Assertion.when(boostedDocumentDateField == null) .check(() -> numDaysOfBoostRefDocument == null && mostRecentBoost == null, "Lorsque le boost des documents récents est désactivé, numDaysOfBoostRefDocument et mostRecentBoost doivent être null."); Assertion.when(numDaysOfBoostRefDocument != null) .check(() -> numDaysOfBoostRefDocument.longValue() > 1, "numDaysOfBoostRefDocument et mostRecentBoost doivent être strictement supérieur à 1."); Assertion.when(mostRecentBoost != null) .check(() -> mostRecentBoost.longValue() > 1, "numDaysOfBoostRefDocument et mostRecentBoost doivent être strictement supérieur à 1."); //----- this.facetedQuery = facetedQuery; this.queryListFilter = queryListFilter; this.securityListFilter = securityListFilter; boostedDocumentDateFieldName = boostedDocumentDateField != null ? boostedDocumentDateField.getName() : null; this.numDaysOfBoostRefDocument = numDaysOfBoostRefDocument; this.mostRecentBoost = mostRecentBoost; clusteringFacetDefinitionRef = clusteringFacetDefinition != null ? new DefinitionReference<>(clusteringFacetDefinition) : null; } /** * Static method factory for SearchQueryBuilder * @param listFilter ListFilter * @return SearchQueryBuilder */ public static SearchQueryBuilder builder(final ListFilter listFilter) { return new SearchQueryBuilder(listFilter); } /** * Facets informations. * @return facetedQuery. */ public Optional<FacetedQuery> getFacetedQuery() { return facetedQuery; } /** * Filtre principal correspondant aux critères de la recherche. * @return Valeur du filtre */ public ListFilter getListFilter() { return queryListFilter; } /** * Filtre correspondant aux critères de sécurité. * @return Valeur du filtre */ public Optional<ListFilter> getSecurityListFilter() { return securityListFilter; } /** * Indique que la recherche propose un clustering des documents par une facette. * Le nombre de document par valeur des facette est limité * @return si le clustering est activé */ public boolean isClusteringFacet() { return clusteringFacetDefinitionRef != null; } /** * @return Facette utilisé pour le clustering */ public FacetDefinition getClusteringFacetDefinition() { Assertion.checkArgument(isClusteringFacet(), "Le clustering des documents par facette n'est pas activé sur cette recherche"); //----- return clusteringFacetDefinitionRef.get(); } /** * Indique que la recherche boost les documents les plus récents. * C'est une formule de type 1/x qui est utilisée. * La formule de boost est 1 / ((documentAgeDay/NumDaysOfBoostRefDocument) + (1/(MostRecentBoost-1))) * @return si le boost est activé */ public boolean isBoostMostRecent() { return boostedDocumentDateFieldName != null; } /** * Si le booste des documents recents est activé. * @return Nom du champ portant la date du document */ public String getBoostedDocumentDateField() { Assertion.checkArgument(isBoostMostRecent(), "Le boost des documents les plus récent n'est pas activé sur cette recherche"); //----- return boostedDocumentDateFieldName; } /** * Si le booste des documents recents est activé. * @return Age des documents servant de référence pour le boost des plus récents par rapport à eux */ public int getNumDaysOfBoostRefDocument() { Assertion.checkArgument(isBoostMostRecent(), "Le boost des documents les plus récent, n'est pas activé sur cette recherche"); //----- return numDaysOfBoostRefDocument; } /** * Si le booste des documents recents est activé. * @return Boost relatif maximum entre les plus récents et ceux ayant l'age de référence (doit être > 1). */ public int getMostRecentBoost() { Assertion.checkArgument(isBoostMostRecent(), "Le boost des documents les plus récent, n'est pas activé sur cette recherche"); //----- return mostRecentBoost; } }
UTF-8
Java
7,226
java
SearchQuery.java
Java
[ { "context": " * Copyright (C) 2013-2019, Vertigo.io, KleeGroup, direction.technique@kleegroup.com (http://www.kleegroup.com)\n * KleeGroup, Centre d", "end": 124, "score": 0.9999266862869263, "start": 91, "tag": "EMAIL", "value": "direction.technique@kleegroup.com" }, { "context": "entre d'affaire la Boursidiere - BP 159 - 92357 Le Plessis Robinson Cedex - France\n *\n * Licensed under the Apache Li", "end": 234, "score": 0.9921474456787109, "start": 218, "tag": "NAME", "value": "Plessis Robinson" }, { "context": "sertion;\n\n/**\n * Critères de recherche.\n * @author npiedeloup\n */\npublic final class SearchQuery implements Ser", "end": 1268, "score": 0.9996210932731628, "start": 1258, "tag": "USERNAME", "value": "npiedeloup" } ]
null
[]
/** * vertigo - simple java starter * * Copyright (C) 2013-2019, Vertigo.io, KleeGroup, <EMAIL> (http://www.kleegroup.com) * KleeGroup, Centre d'affaire la Boursidiere - BP 159 - 92357 Le <NAME> Cedex - France * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.vertigo.dynamo.search.model; import java.io.Serializable; import java.util.Optional; import io.vertigo.core.definition.DefinitionReference; import io.vertigo.dynamo.collections.ListFilter; import io.vertigo.dynamo.collections.metamodel.FacetDefinition; import io.vertigo.dynamo.collections.model.FacetedQuery; import io.vertigo.dynamo.domain.metamodel.DtField; import io.vertigo.lang.Assertion; /** * Critères de recherche. * @author npiedeloup */ public final class SearchQuery implements Serializable { private static final long serialVersionUID = -3215786603726103410L; private final ListFilter queryListFilter; private final Optional<ListFilter> securityListFilter; //Informations optionnelles pour booster la pertinence des documents plus récent (null si inutilisé) private final String boostedDocumentDateFieldName; private final Integer numDaysOfBoostRefDocument; private final Integer mostRecentBoost; private final Optional<FacetedQuery> facetedQuery; private final DefinitionReference<FacetDefinition> clusteringFacetDefinitionRef; /** * Constructor. * @param facetedQuery facetedQueryDefinition * @param queryListFilter Filtre principal correspondant aux critères de la recherche * @param securityListFilter Filtre de sécurité * @param clusteringFacetDefinition Facet utilisée pour cluster des resultats (null si non utilisé) * @param boostedDocumentDateField Nom du champ portant la date du document (null si non utilisé) * @param numDaysOfBoostRefDocument Age des documents servant de référence pour le boost des plus récents par rapport à eux (null si non utilisé) * @param mostRecentBoost Boost relatif maximum entre les plus récents et ceux ayant l'age de référence (doit être > 1) (null si non utilisé) */ SearchQuery( final Optional<FacetedQuery> facetedQuery, final ListFilter queryListFilter, final Optional<ListFilter> securityListFilter, final FacetDefinition clusteringFacetDefinition, final DtField boostedDocumentDateField, final Integer numDaysOfBoostRefDocument, final Integer mostRecentBoost) { Assertion.checkNotNull(facetedQuery); Assertion.checkNotNull(queryListFilter); Assertion.checkNotNull(securityListFilter); Assertion.when(boostedDocumentDateField != null) .check(() -> numDaysOfBoostRefDocument != null && mostRecentBoost != null, "Lorsque le boost des documents récents est activé, numDaysOfBoostRefDocument et mostRecentBoost sont obligatoires."); Assertion.when(boostedDocumentDateField == null) .check(() -> numDaysOfBoostRefDocument == null && mostRecentBoost == null, "Lorsque le boost des documents récents est désactivé, numDaysOfBoostRefDocument et mostRecentBoost doivent être null."); Assertion.when(numDaysOfBoostRefDocument != null) .check(() -> numDaysOfBoostRefDocument.longValue() > 1, "numDaysOfBoostRefDocument et mostRecentBoost doivent être strictement supérieur à 1."); Assertion.when(mostRecentBoost != null) .check(() -> mostRecentBoost.longValue() > 1, "numDaysOfBoostRefDocument et mostRecentBoost doivent être strictement supérieur à 1."); //----- this.facetedQuery = facetedQuery; this.queryListFilter = queryListFilter; this.securityListFilter = securityListFilter; boostedDocumentDateFieldName = boostedDocumentDateField != null ? boostedDocumentDateField.getName() : null; this.numDaysOfBoostRefDocument = numDaysOfBoostRefDocument; this.mostRecentBoost = mostRecentBoost; clusteringFacetDefinitionRef = clusteringFacetDefinition != null ? new DefinitionReference<>(clusteringFacetDefinition) : null; } /** * Static method factory for SearchQueryBuilder * @param listFilter ListFilter * @return SearchQueryBuilder */ public static SearchQueryBuilder builder(final ListFilter listFilter) { return new SearchQueryBuilder(listFilter); } /** * Facets informations. * @return facetedQuery. */ public Optional<FacetedQuery> getFacetedQuery() { return facetedQuery; } /** * Filtre principal correspondant aux critères de la recherche. * @return Valeur du filtre */ public ListFilter getListFilter() { return queryListFilter; } /** * Filtre correspondant aux critères de sécurité. * @return Valeur du filtre */ public Optional<ListFilter> getSecurityListFilter() { return securityListFilter; } /** * Indique que la recherche propose un clustering des documents par une facette. * Le nombre de document par valeur des facette est limité * @return si le clustering est activé */ public boolean isClusteringFacet() { return clusteringFacetDefinitionRef != null; } /** * @return Facette utilisé pour le clustering */ public FacetDefinition getClusteringFacetDefinition() { Assertion.checkArgument(isClusteringFacet(), "Le clustering des documents par facette n'est pas activé sur cette recherche"); //----- return clusteringFacetDefinitionRef.get(); } /** * Indique que la recherche boost les documents les plus récents. * C'est une formule de type 1/x qui est utilisée. * La formule de boost est 1 / ((documentAgeDay/NumDaysOfBoostRefDocument) + (1/(MostRecentBoost-1))) * @return si le boost est activé */ public boolean isBoostMostRecent() { return boostedDocumentDateFieldName != null; } /** * Si le booste des documents recents est activé. * @return Nom du champ portant la date du document */ public String getBoostedDocumentDateField() { Assertion.checkArgument(isBoostMostRecent(), "Le boost des documents les plus récent n'est pas activé sur cette recherche"); //----- return boostedDocumentDateFieldName; } /** * Si le booste des documents recents est activé. * @return Age des documents servant de référence pour le boost des plus récents par rapport à eux */ public int getNumDaysOfBoostRefDocument() { Assertion.checkArgument(isBoostMostRecent(), "Le boost des documents les plus récent, n'est pas activé sur cette recherche"); //----- return numDaysOfBoostRefDocument; } /** * Si le booste des documents recents est activé. * @return Boost relatif maximum entre les plus récents et ceux ayant l'age de référence (doit être > 1). */ public int getMostRecentBoost() { Assertion.checkArgument(isBoostMostRecent(), "Le boost des documents les plus récent, n'est pas activé sur cette recherche"); //----- return mostRecentBoost; } }
7,190
0.769499
0.762662
178
39.264046
39.591637
200
false
false
0
0
0
0
0
0
1.455056
false
false
2
7c4107bdd946a25878aa75ae3e2c1899b70cb393
1,812,476,253,181
2857788bf4efd5b2bfb331cf0f4bd6cb86e09952
/src/main/java/com/nagp/createuserpojo/CreateUser.java
15324eef629061164833d5a89c75e6db611288aa
[]
no_license
sanjeet7271/FaqRestAssured
https://github.com/sanjeet7271/FaqRestAssured
01e1fea430e5e42aefdbf3fef1db4cff85de0ff7
fe6f81ee5355f05747776778fab6d0a1dc49796e
refs/heads/master
2023-03-25T12:11:39.168000
2021-03-16T00:05:50
2021-03-16T00:05:50
348,049,377
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.nagp.createuserpojo; public class CreateUser { CreateUserBody user; public CreateUser(CreateUserBody user) { this.user=user; } public CreateUserBody getUser() { return user; } public void setUser(CreateUserBody user) { this.user = user; } }
UTF-8
Java
276
java
CreateUser.java
Java
[]
null
[]
package com.nagp.createuserpojo; public class CreateUser { CreateUserBody user; public CreateUser(CreateUserBody user) { this.user=user; } public CreateUserBody getUser() { return user; } public void setUser(CreateUserBody user) { this.user = user; } }
276
0.713768
0.713768
19
13.526316
14.805292
43
false
false
0
0
0
0
0
0
1.157895
false
false
2
85434ed8bc98d871dbcd9a09a612a2a275fdfc00
10,445,360,480,277
04fd2fdec5e26b3c4818a9dec430ba092a69e931
/dinah/src/main/java/org/fuwjin/dinah/signature/ArgCountSignature.java
8c492c6f927599e59bcaeb8f46add1829929b2ba
[]
no_license
fuwjax/fuwjin
https://github.com/fuwjax/fuwjin
b8f8bfc43c6dba77e62469b764dbcc4b9d79e48a
762fbc5bf95818d08c2e115bf6b5d6e902342d69
refs/heads/master
2016-08-07T04:16:34.102000
2015-10-25T02:55:18
2015-10-25T02:55:18
34,927,307
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/******************************************************************************* * Copyright (c) 2011 Michael Doberenz. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Michael Doberenz - initial API and implementation ******************************************************************************/ package org.fuwjin.dinah.signature; import org.fuwjin.dinah.FunctionSignature; import org.fuwjin.dinah.SignatureConstraint; /** * Abstraction over a Function's name and argument types. */ public class ArgCountSignature extends ConstraintDecorator { private final int count; /** * Creates a new instance. * @param name the function name * @param argCount the number of arguments */ public ArgCountSignature(final SignatureConstraint constraint, final int argCount) { super(constraint); count = argCount; } @Override public boolean matches(final FunctionSignature signature) { return super.matches(signature) && signature.supportsArgs(count); } @Override public String toString() { final StringBuilder builder = new StringBuilder(); builder.append(name()); String delim = "("; if(count == 0) { builder.append(delim); } else { for(int i = 0; i < count; i++) { builder.append(delim).append("?"); delim = ", "; } } return builder.append(')').toString(); } }
UTF-8
Java
1,643
java
ArgCountSignature.java
Java
[ { "context": "****************************\n * Copyright (c) 2011 Michael Doberenz.\n * All rights reserved. This program and the acc", "end": 119, "score": 0.9998539090156555, "start": 103, "tag": "NAME", "value": "Michael Doberenz" }, { "context": "org/legal/epl-v10.html\n * \n * Contributors:\n * Michael Doberenz - initial API and implementation\n ***************", "end": 411, "score": 0.9998469948768616, "start": 395, "tag": "NAME", "value": "Michael Doberenz" } ]
null
[]
/******************************************************************************* * Copyright (c) 2011 <NAME>. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * <NAME> - initial API and implementation ******************************************************************************/ package org.fuwjin.dinah.signature; import org.fuwjin.dinah.FunctionSignature; import org.fuwjin.dinah.SignatureConstraint; /** * Abstraction over a Function's name and argument types. */ public class ArgCountSignature extends ConstraintDecorator { private final int count; /** * Creates a new instance. * @param name the function name * @param argCount the number of arguments */ public ArgCountSignature(final SignatureConstraint constraint, final int argCount) { super(constraint); count = argCount; } @Override public boolean matches(final FunctionSignature signature) { return super.matches(signature) && signature.supportsArgs(count); } @Override public String toString() { final StringBuilder builder = new StringBuilder(); builder.append(name()); String delim = "("; if(count == 0) { builder.append(delim); } else { for(int i = 0; i < count; i++) { builder.append(delim).append("?"); delim = ", "; } } return builder.append(')').toString(); } }
1,623
0.60073
0.594644
52
30.596153
24.924702
87
false
false
0
0
0
0
0
0
0.365385
false
false
4
103f941cdf1f6c30e558ddc67d0a2cd8f98d6b93
31,026,843,759,585
c8ec380449ae032251fe6c05919823722f41f61d
/app/src/main/java/com/nsw/a6vfilm/fragment/CategoryFragment.java
d0260c7e6f747efc6abfec23450efe61dccd027a
[]
no_license
n272367953/6vfilm
https://github.com/n272367953/6vfilm
acadfc280ab914b0a5ea21a84f2b52cea82fe8e3
1c1ba3182a4423723a8ad5318895713265e052b9
refs/heads/master
2021-01-21T04:53:58.654000
2016-06-08T11:41:15
2016-06-08T11:41:15
54,894,229
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.nsw.a6vfilm.fragment; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.RadioButton; import android.widget.RadioGroup; import com.nsw.a6vfilm.R; /** * Created by niushuowen on 2016/5/9. */ public class CategoryFragment extends Fragment implements RadioGroup.OnCheckedChangeListener { private RadioGroup tabs; private RadioButton tab_cate; private RadioButton tab_coun; private ViewPager viewPager; private View pagerByCate; private View pagerByCountry; @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_category, container, false); tabs = (RadioGroup) view.findViewById(R.id.id_tabs); tab_coun = (RadioButton) view.findViewById(R.id.id_tab_2); tab_cate = (RadioButton) view.findViewById(R.id.id_tab_1); viewPager = (ViewPager) view.findViewById(R.id.id_tab_pager); CategroyPagerAdapter adapter = new CategroyPagerAdapter(); viewPager.setAdapter(adapter); viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() { @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { } @Override public void onPageSelected(int position) { if (0 == position) { tabs.check(R.id.id_tab_1); } else { tabs.check(R.id.id_tab_2); } } @Override public void onPageScrollStateChanged(int state) { } }); tabs.setOnCheckedChangeListener(this); clickByCountry(); return view; } @Override public void onCheckedChanged(RadioGroup group, int checkedId) { switch (checkedId) { case R.id.id_tab_1: clickByCountry(); break; case R.id.id_tab_2: clickByCategory(); break; } } /** * 点击按类别 */ private void clickByCategory() { tabs.check(R.id.id_tab_2); viewPager.setCurrentItem(1); } /** * 点击按国家 */ private void clickByCountry() { tabs.check(R.id.id_tab_1); viewPager.setCurrentItem(0); } public class CategroyPagerAdapter extends PagerAdapter { @Override public int getCount() { return 2; } @Override public boolean isViewFromObject(View view, Object object) { return view == object; } @Override public Object instantiateItem(ViewGroup container, int position) { View view; if (position == 0) { view = View.inflate(getActivity(), R.layout.by_country_view, null); } else { view = View.inflate(getActivity(), R.layout.by_category_view, null); } container.addView(view); return view; } @Override public void destroyItem(ViewGroup container, int position, Object object) { // super.destroyItem(container, position, object); } } }
UTF-8
Java
3,570
java
CategoryFragment.java
Java
[ { "context": "oup;\n\nimport com.nsw.a6vfilm.R;\n\n/**\n * Created by niushuowen on 2016/5/9.\n */\npublic class CategoryFragment ex", "end": 450, "score": 0.9996469616889954, "start": 440, "tag": "USERNAME", "value": "niushuowen" } ]
null
[]
package com.nsw.a6vfilm.fragment; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.RadioButton; import android.widget.RadioGroup; import com.nsw.a6vfilm.R; /** * Created by niushuowen on 2016/5/9. */ public class CategoryFragment extends Fragment implements RadioGroup.OnCheckedChangeListener { private RadioGroup tabs; private RadioButton tab_cate; private RadioButton tab_coun; private ViewPager viewPager; private View pagerByCate; private View pagerByCountry; @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_category, container, false); tabs = (RadioGroup) view.findViewById(R.id.id_tabs); tab_coun = (RadioButton) view.findViewById(R.id.id_tab_2); tab_cate = (RadioButton) view.findViewById(R.id.id_tab_1); viewPager = (ViewPager) view.findViewById(R.id.id_tab_pager); CategroyPagerAdapter adapter = new CategroyPagerAdapter(); viewPager.setAdapter(adapter); viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() { @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { } @Override public void onPageSelected(int position) { if (0 == position) { tabs.check(R.id.id_tab_1); } else { tabs.check(R.id.id_tab_2); } } @Override public void onPageScrollStateChanged(int state) { } }); tabs.setOnCheckedChangeListener(this); clickByCountry(); return view; } @Override public void onCheckedChanged(RadioGroup group, int checkedId) { switch (checkedId) { case R.id.id_tab_1: clickByCountry(); break; case R.id.id_tab_2: clickByCategory(); break; } } /** * 点击按类别 */ private void clickByCategory() { tabs.check(R.id.id_tab_2); viewPager.setCurrentItem(1); } /** * 点击按国家 */ private void clickByCountry() { tabs.check(R.id.id_tab_1); viewPager.setCurrentItem(0); } public class CategroyPagerAdapter extends PagerAdapter { @Override public int getCount() { return 2; } @Override public boolean isViewFromObject(View view, Object object) { return view == object; } @Override public Object instantiateItem(ViewGroup container, int position) { View view; if (position == 0) { view = View.inflate(getActivity(), R.layout.by_country_view, null); } else { view = View.inflate(getActivity(), R.layout.by_category_view, null); } container.addView(view); return view; } @Override public void destroyItem(ViewGroup container, int position, Object object) { // super.destroyItem(container, position, object); } } }
3,570
0.605634
0.598873
125
27.408001
25.526487
123
false
false
0
0
0
0
0
0
0.512
false
false
4
fad7c202f3a9e6d5fe1995e85e4f98c3003cd82b
35,459,249,998,310
fa91450deb625cda070e82d5c31770be5ca1dec6
/Diff-Raw-Data/2/2_7df0488f80a986101fd2a28d1791fab12c351294/KiezatlasPlugin/2_7df0488f80a986101fd2a28d1791fab12c351294_KiezatlasPlugin_t.java
a8d0668f9ad747e23b56d43afacea56c440e0e81
[]
no_license
zhongxingyu/Seer
https://github.com/zhongxingyu/Seer
48e7e5197624d7afa94d23f849f8ea2075bcaec0
c11a3109fdfca9be337e509ecb2c085b60076213
refs/heads/master
2023-07-06T12:48:55.516000
2023-06-22T07:55:56
2023-06-22T07:55:56
259,613,157
6
2
null
false
2023-06-22T07:55:57
2020-04-28T11:07:49
2023-06-21T00:53:27
2023-06-22T07:55:57
2,849,868
2
2
0
null
false
false
package de.deepamehta.plugins.kiezatlas; import de.deepamehta.plugins.geomaps.model.Geomap; import de.deepamehta.plugins.geomaps.model.GeomapTopic; import de.deepamehta.plugins.geomaps.service.GeomapsService; import de.deepamehta.plugins.facets.service.FacetsService; import de.deepamehta.core.Association; import de.deepamehta.core.AssociationDefinition; import de.deepamehta.core.RelatedTopic; import de.deepamehta.core.ResultSet; import de.deepamehta.core.Topic; import de.deepamehta.core.model.AssociationModel; import de.deepamehta.core.model.AssociationRoleModel; import de.deepamehta.core.model.CompositeValue; import de.deepamehta.core.model.TopicModel; import de.deepamehta.core.model.TopicRoleModel; import de.deepamehta.core.service.ClientState; import de.deepamehta.core.service.Directives; import de.deepamehta.core.service.Plugin; import de.deepamehta.core.service.PluginService; import javax.ws.rs.GET; import javax.ws.rs.PUT; import javax.ws.rs.POST; import javax.ws.rs.DELETE; import javax.ws.rs.HeaderParam; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.Consumes; import javax.ws.rs.WebApplicationException; import java.io.InputStream; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.logging.Logger; @Path("/") @Consumes("application/json") @Produces("application/json") public class KiezatlasPlugin extends Plugin { // Website-Geomap association private static final String WEBSITE_GEOMAP = "dm4.core.association"; private static final String ROLE_TYPE_WEBSITE = "dm4.core.default"; private static final String ROLE_TYPE_GEOMAP = "dm4.core.default"; // Website-Facet Types association private static final String WEBSITE_FACET_TYPES = "dm4.core.association"; // private static final String ROLE_TYPE_WEBSITE = "dm4.core.default"; private static final String ROLE_TYPE_FACET_TYPE = "dm4.core.default"; // ---------------------------------------------------------------------------------------------- Instance Variables private GeomapsService geomapsService; private FacetsService facetsService; private Logger logger = Logger.getLogger(getClass().getName()); // -------------------------------------------------------------------------------------------------- Public Methods // ********************** // *** Plugin Service *** // ********************** @GET @Path("/{url}") @Produces("text/html") public InputStream launchWebclient() { // Note: the template parameters are evaluated at client-side try { return dms.getPlugin("de.deepamehta.webclient").getResourceAsStream("web/index.html"); } catch (Exception e) { throw new WebApplicationException(e); } } @GET @Path("/geomap/{geomap_id}") public Topic getWebsite(@PathParam("geomap_id") long geomapId) { try { return dms.getTopic(geomapId, false, null).getRelatedTopic(WEBSITE_GEOMAP, ROLE_TYPE_WEBSITE, ROLE_TYPE_GEOMAP, "dm4.kiezatlas.website", false, false, null); } catch (Exception e) { throw new WebApplicationException(new RuntimeException("Finding the geomap's website topic failed " + "(geomapId=" + geomapId + ")", e)); } } @GET @Path("/{website_id}/facets") public ResultSet<RelatedTopic> getFacetTypes(@PathParam("website_id") long websiteId) { try { return dms.getTopic(websiteId, false, null).getRelatedTopics(WEBSITE_FACET_TYPES, ROLE_TYPE_WEBSITE, ROLE_TYPE_FACET_TYPE, "dm4.core.topic_type", false, false, 0, null); } catch (Exception e) { throw new WebApplicationException(new RuntimeException("Finding the website's facet types failed " + "(websiteId=" + websiteId + ")", e)); } } @GET @Path("/geomap/{geomap_id}/objects") public Set<Topic> getGeoObjects(@PathParam("geomap_id") long geomapId, @HeaderParam("Cookie") ClientState clientState) { try { return fetchGeoObjects(geomapId, clientState); } catch (Exception e) { throw new WebApplicationException(new RuntimeException("Fetching the geomap's geo objects failed " + "(geomapId=" + geomapId + ")", e)); } } // ************************************************** // *** Core Hooks (called from DeepaMehta 4 Core) *** // ************************************************** @Override public void serviceArrived(PluginService service) { logger.info("########## Service arrived: " + service); if (service instanceof GeomapsService) { geomapsService = (GeomapsService) service; } else if (service instanceof FacetsService) { facetsService = (FacetsService) service; } } @Override public void serviceGone(PluginService service) { logger.info("########## Service gone: " + service); if (service == geomapsService) { geomapsService = null; } else if (service == facetsService) { facetsService = null; } } // --- @Override public void postFetchTopicHook(Topic topic, ClientState clientState, Directives directives) { if (topic.getTypeUri().equals("dm4.kiezatlas.geo_object")) { ResultSet<RelatedTopic> facetTypes = getFacetTypes(clientState); if (facetTypes == null) { return; } // for (Topic facetType : facetTypes) { String facetTypeUri = facetType.getUri(); Topic facet = facetsService.getFacet(topic, facetTypeUri); // Note: facet is null in 2 cases: // 1) The geo object has just been created (no update yet) // 2) The geo object has been created inside a non-geomap and then being revealed inside a geomap. if (facet != null) { logger.info("### Enriching geo object " + topic.getId() + " with its \"" + facetTypeUri + "\" facet (" + facet + ")"); topic.getCompositeValue().put(facet.getTypeUri(), facet.getModel()); } else { logger.info("### Enriching geo object " + topic.getId() + " with its \"" + facetTypeUri + "\" facet ABORTED -- no such facet in DB"); } } } } @Override public void postUpdateHook(Topic topic, TopicModel newModel, TopicModel oldModel, ClientState clientState, Directives directives) { if (topic.getTypeUri().equals("dm4.kiezatlas.geo_object")) { ResultSet<RelatedTopic> facetTypes = getFacetTypes(clientState); if (facetTypes == null) { return; } // for (Topic facetType : facetTypes) { String facetTypeUri = facetType.getUri(); String assocDefUri = getAssocDef(facetTypeUri).getUri(); TopicModel facet = newModel.getCompositeValue().getTopic(assocDefUri); logger.info("### Storing facet of type \"" + facetTypeUri + "\" for geo object " + topic.getId() + " (facet=" + facet + ")"); facetsService.setFacet(topic, facetTypeUri, facet, clientState, directives); } } } // ------------------------------------------------------------------------------------------------- Private Methods /** * Finds the geo object facet types for the selected topicmap. */ private ResultSet<RelatedTopic> getFacetTypes(ClientState clientState) { long topicmapId = clientState.getLong("dm4_topicmap_id"); // if (!isGeomap(topicmapId)) { logger.info("### Finding geo object facet types for topicmap " + topicmapId + " ABORTED -- not a geomap"); return null; } // Topic website = getWebsite(topicmapId); if (website == null) { logger.info("### Finding geo object facet types for geomap " + topicmapId + " ABORTED -- not part of a " + "Kiezatlas website"); return null; } // logger.info("### Finding geo object facet types for geomap " + topicmapId); return getFacetTypes(website.getId()); } private Set<Topic> fetchGeoObjects(long geomapId, ClientState clientState) { Set<Topic> geoObjects = new HashSet(); ResultSet<RelatedTopic> geomapTopics = geomapsService.getGeomapTopics(geomapId); for (RelatedTopic topic : geomapTopics) { Topic geoTopic = geomapsService.getGeoTopic(topic.getId(), clientState); geoObjects.add(geoTopic); // ### TODO: optimization. Include only name and address in returned geo objects. // ### For the moment the entire objects are returned, including composite values and facets. } return geoObjects; } // --- private boolean isGeomap(long topicmapId) { Topic topicmap = dms.getTopic(topicmapId, true, null); String rendererUri = topicmap.getCompositeValue().getString("dm4.topicmaps.canvas_renderer_uri"); return rendererUri.equals("dm4.geomaps.geomap_renderer"); } // ### FIXME: there is a copy in FacetsPlugin.java private AssociationDefinition getAssocDef(String facetTypeUri) { // Note: a facet type has exactly *one* association definition return dms.getTopicType(facetTypeUri, null).getAssocDefs().values().iterator().next(); } }
UTF-8
Java
10,128
java
2_7df0488f80a986101fd2a28d1791fab12c351294_KiezatlasPlugin_t.java
Java
[]
null
[]
package de.deepamehta.plugins.kiezatlas; import de.deepamehta.plugins.geomaps.model.Geomap; import de.deepamehta.plugins.geomaps.model.GeomapTopic; import de.deepamehta.plugins.geomaps.service.GeomapsService; import de.deepamehta.plugins.facets.service.FacetsService; import de.deepamehta.core.Association; import de.deepamehta.core.AssociationDefinition; import de.deepamehta.core.RelatedTopic; import de.deepamehta.core.ResultSet; import de.deepamehta.core.Topic; import de.deepamehta.core.model.AssociationModel; import de.deepamehta.core.model.AssociationRoleModel; import de.deepamehta.core.model.CompositeValue; import de.deepamehta.core.model.TopicModel; import de.deepamehta.core.model.TopicRoleModel; import de.deepamehta.core.service.ClientState; import de.deepamehta.core.service.Directives; import de.deepamehta.core.service.Plugin; import de.deepamehta.core.service.PluginService; import javax.ws.rs.GET; import javax.ws.rs.PUT; import javax.ws.rs.POST; import javax.ws.rs.DELETE; import javax.ws.rs.HeaderParam; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.Consumes; import javax.ws.rs.WebApplicationException; import java.io.InputStream; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.logging.Logger; @Path("/") @Consumes("application/json") @Produces("application/json") public class KiezatlasPlugin extends Plugin { // Website-Geomap association private static final String WEBSITE_GEOMAP = "dm4.core.association"; private static final String ROLE_TYPE_WEBSITE = "dm4.core.default"; private static final String ROLE_TYPE_GEOMAP = "dm4.core.default"; // Website-Facet Types association private static final String WEBSITE_FACET_TYPES = "dm4.core.association"; // private static final String ROLE_TYPE_WEBSITE = "dm4.core.default"; private static final String ROLE_TYPE_FACET_TYPE = "dm4.core.default"; // ---------------------------------------------------------------------------------------------- Instance Variables private GeomapsService geomapsService; private FacetsService facetsService; private Logger logger = Logger.getLogger(getClass().getName()); // -------------------------------------------------------------------------------------------------- Public Methods // ********************** // *** Plugin Service *** // ********************** @GET @Path("/{url}") @Produces("text/html") public InputStream launchWebclient() { // Note: the template parameters are evaluated at client-side try { return dms.getPlugin("de.deepamehta.webclient").getResourceAsStream("web/index.html"); } catch (Exception e) { throw new WebApplicationException(e); } } @GET @Path("/geomap/{geomap_id}") public Topic getWebsite(@PathParam("geomap_id") long geomapId) { try { return dms.getTopic(geomapId, false, null).getRelatedTopic(WEBSITE_GEOMAP, ROLE_TYPE_WEBSITE, ROLE_TYPE_GEOMAP, "dm4.kiezatlas.website", false, false, null); } catch (Exception e) { throw new WebApplicationException(new RuntimeException("Finding the geomap's website topic failed " + "(geomapId=" + geomapId + ")", e)); } } @GET @Path("/{website_id}/facets") public ResultSet<RelatedTopic> getFacetTypes(@PathParam("website_id") long websiteId) { try { return dms.getTopic(websiteId, false, null).getRelatedTopics(WEBSITE_FACET_TYPES, ROLE_TYPE_WEBSITE, ROLE_TYPE_FACET_TYPE, "dm4.core.topic_type", false, false, 0, null); } catch (Exception e) { throw new WebApplicationException(new RuntimeException("Finding the website's facet types failed " + "(websiteId=" + websiteId + ")", e)); } } @GET @Path("/geomap/{geomap_id}/objects") public Set<Topic> getGeoObjects(@PathParam("geomap_id") long geomapId, @HeaderParam("Cookie") ClientState clientState) { try { return fetchGeoObjects(geomapId, clientState); } catch (Exception e) { throw new WebApplicationException(new RuntimeException("Fetching the geomap's geo objects failed " + "(geomapId=" + geomapId + ")", e)); } } // ************************************************** // *** Core Hooks (called from DeepaMehta 4 Core) *** // ************************************************** @Override public void serviceArrived(PluginService service) { logger.info("########## Service arrived: " + service); if (service instanceof GeomapsService) { geomapsService = (GeomapsService) service; } else if (service instanceof FacetsService) { facetsService = (FacetsService) service; } } @Override public void serviceGone(PluginService service) { logger.info("########## Service gone: " + service); if (service == geomapsService) { geomapsService = null; } else if (service == facetsService) { facetsService = null; } } // --- @Override public void postFetchTopicHook(Topic topic, ClientState clientState, Directives directives) { if (topic.getTypeUri().equals("dm4.kiezatlas.geo_object")) { ResultSet<RelatedTopic> facetTypes = getFacetTypes(clientState); if (facetTypes == null) { return; } // for (Topic facetType : facetTypes) { String facetTypeUri = facetType.getUri(); Topic facet = facetsService.getFacet(topic, facetTypeUri); // Note: facet is null in 2 cases: // 1) The geo object has just been created (no update yet) // 2) The geo object has been created inside a non-geomap and then being revealed inside a geomap. if (facet != null) { logger.info("### Enriching geo object " + topic.getId() + " with its \"" + facetTypeUri + "\" facet (" + facet + ")"); topic.getCompositeValue().put(facet.getTypeUri(), facet.getModel()); } else { logger.info("### Enriching geo object " + topic.getId() + " with its \"" + facetTypeUri + "\" facet ABORTED -- no such facet in DB"); } } } } @Override public void postUpdateHook(Topic topic, TopicModel newModel, TopicModel oldModel, ClientState clientState, Directives directives) { if (topic.getTypeUri().equals("dm4.kiezatlas.geo_object")) { ResultSet<RelatedTopic> facetTypes = getFacetTypes(clientState); if (facetTypes == null) { return; } // for (Topic facetType : facetTypes) { String facetTypeUri = facetType.getUri(); String assocDefUri = getAssocDef(facetTypeUri).getUri(); TopicModel facet = newModel.getCompositeValue().getTopic(assocDefUri); logger.info("### Storing facet of type \"" + facetTypeUri + "\" for geo object " + topic.getId() + " (facet=" + facet + ")"); facetsService.setFacet(topic, facetTypeUri, facet, clientState, directives); } } } // ------------------------------------------------------------------------------------------------- Private Methods /** * Finds the geo object facet types for the selected topicmap. */ private ResultSet<RelatedTopic> getFacetTypes(ClientState clientState) { long topicmapId = clientState.getLong("dm4_topicmap_id"); // if (!isGeomap(topicmapId)) { logger.info("### Finding geo object facet types for topicmap " + topicmapId + " ABORTED -- not a geomap"); return null; } // Topic website = getWebsite(topicmapId); if (website == null) { logger.info("### Finding geo object facet types for geomap " + topicmapId + " ABORTED -- not part of a " + "Kiezatlas website"); return null; } // logger.info("### Finding geo object facet types for geomap " + topicmapId); return getFacetTypes(website.getId()); } private Set<Topic> fetchGeoObjects(long geomapId, ClientState clientState) { Set<Topic> geoObjects = new HashSet(); ResultSet<RelatedTopic> geomapTopics = geomapsService.getGeomapTopics(geomapId); for (RelatedTopic topic : geomapTopics) { Topic geoTopic = geomapsService.getGeoTopic(topic.getId(), clientState); geoObjects.add(geoTopic); // ### TODO: optimization. Include only name and address in returned geo objects. // ### For the moment the entire objects are returned, including composite values and facets. } return geoObjects; } // --- private boolean isGeomap(long topicmapId) { Topic topicmap = dms.getTopic(topicmapId, true, null); String rendererUri = topicmap.getCompositeValue().getString("dm4.topicmaps.canvas_renderer_uri"); return rendererUri.equals("dm4.geomaps.geomap_renderer"); } // ### FIXME: there is a copy in FacetsPlugin.java private AssociationDefinition getAssocDef(String facetTypeUri) { // Note: a facet type has exactly *one* association definition return dms.getTopicType(facetTypeUri, null).getAssocDefs().values().iterator().next(); } }
10,128
0.583136
0.581359
251
39.346615
33.371674
121
false
false
0
0
0
0
0
0
0.517928
false
false
4
86f04764afc464ed0c7dec8bb9994a30ad5f695e
10,024,453,671,323
8dbf896883341bd3e393d3e25eaac0bd32f3ef99
/DepanNodeUI/prod/src/com/google/devtools/depan/nodes/filters/persistence/NodeKindResources.java
3e3c13681f1a1b13ef8c666aea87e695c7b1e265
[ "Apache-2.0" ]
permissive
pnambic/depan
https://github.com/pnambic/depan
e213a02ffa776749e42d9164a8d1bcee8f91e8a4
086971525e419fd264b634b93c1cabe5e3c12f43
refs/heads/master
2022-05-01T06:14:06.421000
2019-09-20T18:05:00
2019-09-20T18:05:00
124,971,168
0
1
null
true
2018-03-13T00:59:24
2018-03-13T00:59:24
2018-03-04T10:48:37
2018-02-17T19:06:17
3,411
0
0
0
null
false
null
/* * Copyright 2016 The Depan Project Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.devtools.depan.nodes.filters.persistence; import com.google.devtools.depan.resources.ResourceContainer; import com.google.devtools.depan.resources.analysis.AnalysisResources; /** * @author <a href="leeca@pnambic.com">Lee Carver</a> */ public class NodeKindResources { /** Name of resource tree container for node-kind resources. */ public static final String NODES = "nodes"; public static final String BASE_NAME = null; /** Expected extensions for node-kind resources. */ public static final String EXTENSION = "nkxml"; private NodeKindResources() { // Prevent instantiation. } public static void installResources(ResourceContainer root) { root.addChild(NODES); } /** * Kludgy bit of Singleton mis-use to simplify access to a very * commonly referenced resource. Other solutions are welcome. */ public static ResourceContainer getContainer() { return AnalysisResources.getRoot().getChild(NODES); } }
UTF-8
Java
1,586
java
NodeKindResources.java
Java
[ { "context": "lysis.AnalysisResources;\n\n/**\n * @author <a href=\"leeca@pnambic.com\">Lee Carver</a>\n */\npublic class NodeKindResource", "end": 847, "score": 0.9999301433563232, "start": 830, "tag": "EMAIL", "value": "leeca@pnambic.com" }, { "context": "rces;\n\n/**\n * @author <a href=\"leeca@pnambic.com\">Lee Carver</a>\n */\npublic class NodeKindResources {\n\n /** N", "end": 859, "score": 0.999862551689148, "start": 849, "tag": "NAME", "value": "Lee Carver" } ]
null
[]
/* * Copyright 2016 The Depan Project Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.devtools.depan.nodes.filters.persistence; import com.google.devtools.depan.resources.ResourceContainer; import com.google.devtools.depan.resources.analysis.AnalysisResources; /** * @author <a href="<EMAIL>"><NAME></a> */ public class NodeKindResources { /** Name of resource tree container for node-kind resources. */ public static final String NODES = "nodes"; public static final String BASE_NAME = null; /** Expected extensions for node-kind resources. */ public static final String EXTENSION = "nkxml"; private NodeKindResources() { // Prevent instantiation. } public static void installResources(ResourceContainer root) { root.addChild(NODES); } /** * Kludgy bit of Singleton mis-use to simplify access to a very * commonly referenced resource. Other solutions are welcome. */ public static ResourceContainer getContainer() { return AnalysisResources.getRoot().getChild(NODES); } }
1,572
0.737705
0.732661
50
30.719999
27.858242
75
false
false
0
0
0
0
0
0
0.26
false
false
4
e56151dbbeaa7d80c3b23ec166ac9a725a19c64c
23,519,240,961,446
e3e348f7732cf0a45b73628a51c54d7777690d0a
/src/main/java/shift/sextiarysector/recipe/RecipesFurnaceCraft.java
dd6957b7f4c7dcc6be6ec51d3572d0c68bf6e1f5
[]
no_license
shift02/SextiarySector2
https://github.com/shift02/SextiarySector2
cf89a03527cebd8a605c787e6d547f4ede5a8bde
79a78d3008f573a52de87bcf9f828c121b8038ce
refs/heads/master
2021-12-12T21:18:21.553000
2017-09-05T14:47:11
2017-09-05T14:47:11
25,522,254
10
16
null
false
2016-06-04T00:56:52
2014-10-21T12:56:47
2016-03-25T20:13:18
2016-06-04T00:56:52
2,402
5
10
4
Java
null
null
package shift.sextiarysector.recipe; import java.util.HashMap; import java.util.Map; import net.minecraft.init.Blocks; import net.minecraft.init.Items; import net.minecraft.item.ItemStack; import net.minecraft.item.crafting.FurnaceRecipes; import net.minecraftforge.oredict.ShapedOreRecipe; import net.minecraftforge.oredict.ShapelessOreRecipe; import shift.sextiarysector.SSBlocks; import shift.sextiarysector.SSItems; public class RecipesFurnaceCraft { public static void addRecipes(FurnaceCraftingManager p_77608_1_) { //飲み物 //p_77608_1_.addRecipe(new ShapelessOreRecipe(new ItemStack(SSItems.drinkingWaterBottle, 1), // new Object[] { // new ItemStack(Items.potionitem), // })); //スライム p_77608_1_.addRecipe(new ShapelessOreRecipe(new ItemStack(Items.slime_ball, 1), new Object[] { SSItems.dustWaterLily, "condimentSugar", "fluidWater", })); p_77608_1_.addRecipe(new ShapelessOreRecipe(new ItemStack(Items.slime_ball, 1), new Object[] { "dyeGreen", "fluidSap", })); //石鹸 p_77608_1_.addRecipe(new ShapelessOreRecipe(new ItemStack(SSItems.soap, 1), new Object[] { "dustAsh", SSItems.animalOil, SSItems.animalOil })); /* p_77608_1_.addRecipe(new ShapelessOreRecipe(new ItemStack(Items.slime_ball, 2), new Object[] { "condimentSugar", "condimentSugar", "condimentSalt", "fluidSap", })); p_77608_1_.addRecipe(new ShapelessOreRecipe(new ItemStack(Items.slime_ball, 2), new Object[] { "algaLaver", "algaLaver", "condimentSalt", "fluidWater", })); */ //p_77608_1_.addRecipe(new ShapelessOreRecipe(new ItemStack(SSItems.drinkingWaterBottle, 2), // new Object[] { // SSItems.emptyBottle, // SSItems.emptyBottle, // SSItems.waterBottle, // })); p_77608_1_.addRecipe(new ShapelessOreRecipe(new ItemStack(SSItems.chocolate, 1), new Object[] { "condimentSugar", "condimentSugar", "condimentSugar", "condimentCocoa", })); p_77608_1_.addRecipe(new ShapelessOreRecipe(new ItemStack(SSItems.redGel, 2), new Object[] { "dustRedstone", "slimeball" })); p_77608_1_.addRecipe(new ShapelessOreRecipe(new ItemStack(SSItems.blueGel, 2), new Object[] { "dustBluestone", "slimeball" })); p_77608_1_.addRecipe(new ShapelessOreRecipe(new ItemStack(SSItems.yellowGel, 2), new Object[] { "dustYellowstone", "slimeball" })); p_77608_1_.addRecipe(new ShapelessOreRecipe(new ItemStack(SSItems.steelIngot, 1), new Object[] { "dustCoal", "dustIron" })); p_77608_1_.addRecipe(new ShapelessOreRecipe(new ItemStack(SSItems.brassIngot, 2), new Object[] { "dustCopper", "dustCopper", "dustZinc" })); p_77608_1_.addRecipe(new ShapelessOreRecipe(new ItemStack(SSItems.ninjaIngot, 1), new Object[] { "dustMithril", "dustDiamond" })); //瓦 p_77608_1_.addRecipe(new ShapelessOreRecipe(new ItemStack(SSItems.kawara, 1), new Object[] { Items.clay_ball, SSItems.glaze })); /* p_77608_1_.addRecipe(new ShapedOreRecipe(new ItemStack(SSItems.unit, 1), new Object[] { "xxx", "xyx", "xxx", Character.valueOf('y'), SSItems.blueGel, Character.valueOf('x'), "cobblestone", })); */ //p_77608_1_.addRecipe(new ShapedOreRecipe(new ItemStack(SSBlocks.machineFrame, 1), // new Object[] { "xxx", "xyx", "xxx", // Character.valueOf('y'), "gelBluestone", // Character.valueOf('x'), "cobblestone", // })); // p_77608_1_.addRecipe(new ShapedOreRecipe(new ItemStack(SSItems.emptyBottle, 8), // new Object[] { // "x", "x", // 'x', "paneGlassColorless", // })); p_77608_1_.addRecipe(new ShapedOreRecipe(new ItemStack(SSItems.orichalcumGem, 1), new Object[] { "xyb", "aza", "byx", 'x', "ingotBrass", 'y', "ingotSilver", 'z', "craftingMagic", 'a', "ingotMithril", 'b', "ingotGold" })); //Hammer //p_77608_1_.addRecipe(new ShapedOreRecipe(new ItemStack(SSItems.ironSpanner, 1), // new Object[] { "xxx", " y ", " y ", // Character.valueOf('x'), "ingotIron", // Character.valueOf('y'), "stickWood", // })); //鉄のリング p_77608_1_.addRecipe(new ShapedOreRecipe(new ItemStack(SSItems.ironRing, 1), new Object[] { " x ", "x x", " x ", Character.valueOf('x'), "ingotIron", })); //クリーパーリング //p_77608_1_.addRecipe(new ShapelessOreRecipe(new ItemStack(SSItems.creeperRing, 1), // new Object[] { // "ringIron", // SSItems.objectReactor, // BlockMonitor.getMonitor(MonitorType.creeper) // })); //MPRing p_77608_1_.addRecipe(new ShapelessOreRecipe(new ItemStack(SSItems.mpRing, 1), new Object[] { "ringIron", SSItems.magicDust, "dustGold" })); //XPRing p_77608_1_.addRecipe(new ShapelessOreRecipe(new ItemStack(SSItems.xpRing, 1), new Object[] { "ringIron", SSItems.magicDust, new ItemStack(Items.dye, 1, 4) })); //液体カマド p_77608_1_.addRecipe(new ShapedOreRecipe(new ItemStack(SSBlocks.fluidFurnace, 1), new Object[] { "xxx", "xyx", "xxx", Character.valueOf('x'), "cobblestone", Character.valueOf('y'), Blocks.glass_pane, })); //魔法カマド p_77608_1_.addRecipe(new ShapedOreRecipe(new ItemStack(SSBlocks.magicFurnace, 1), new Object[] { "xxx", "xyx", "xxx", Character.valueOf('x'), "cobblestone", Character.valueOf('y'), SSItems.magicDust, })); //フリーザー p_77608_1_.addRecipe(new ShapelessOreRecipe(new ItemStack(SSBlocks.freezer, 1), new Object[] { SSItems.objectReactor, Blocks.ice, Blocks.furnace, })); //乾燥機 p_77608_1_.addRecipe(new ShapedOreRecipe(new ItemStack(SSBlocks.foodSmokers, 1), new Object[] { "xxx", "xyx", "xxx", Character.valueOf('x'), "ingotSteel", Character.valueOf('y'), Blocks.glass_pane, })); //time p_77608_1_.addRecipe(new ShapedOreRecipe(new ItemStack(SSBlocks.chunkLoader, 1), new Object[] { "xyx", "yzy", "xyx", Character.valueOf('x'), "ingotIron", Character.valueOf('y'), Blocks.obsidian, Character.valueOf('z'), Items.clock, })); //パイプ p_77608_1_.addRecipe(new ShapedOreRecipe(new ItemStack(SSBlocks.copperPipe, 4), new Object[] { "x", "x", "x", 'x', "ingotCopper", })); //料理 p_77608_1_.addRecipe(new ShapelessOreRecipe(new ItemStack(SSItems.curryRice, 1), new Object[] { "containerWoodBowl", "condimentCurryPowder", "cookingRice", "cropPotato", "cropCarrot" })); //スープ p_77608_1_.addRecipe(new ShapelessOreRecipe(new ItemStack(SSItems.carrotSoup, 1), new Object[] { "containerWoodBowl", "fluidWater", "cropCarrot" })); p_77608_1_.addRecipe(new ShapelessOreRecipe(new ItemStack(SSItems.cornSoup, 1), new Object[] { "containerWoodBowl", "fluidWater", "cropCorn" })); p_77608_1_.addRecipe(new ShapelessOreRecipe(new ItemStack(SSItems.eggSoup, 1), new Object[] { "containerWoodBowl", "fluidWater", "eggChicken" })); p_77608_1_.addRecipe(new ShapelessOreRecipe(new ItemStack(SSItems.onionSoup, 1), new Object[] { "containerWoodBowl", "fluidWater", "cropOnion" })); p_77608_1_.addRecipe(new ShapelessOreRecipe(new ItemStack(SSItems.tomatoSoup, 1), new Object[] { "containerWoodBowl", "fluidWater", "cropTomato" })); //輸送系 p_77608_1_.addRecipe(new ShapedOreRecipe(new ItemStack(SSBlocks.poweredBuoy, 4), new Object[] { "xyx", "yzy", "xyx", Character.valueOf('x'), "ingotIron", Character.valueOf('y'), SSItems.dustWaterLily, Character.valueOf('z'), Items.redstone, })); p_77608_1_.addRecipe(new ShapedOreRecipe(new ItemStack(SSBlocks.boardingBuoy, 4), new Object[] { "xyx", "yzy", "xyx", Character.valueOf('x'), "ingotGold", Character.valueOf('y'), SSItems.dustWaterLily, Character.valueOf('z'), Items.redstone, })); p_77608_1_.addRecipe(new ShapedOreRecipe(new ItemStack(SSBlocks.detectorBuoy, 4), new Object[] { "xyx", "yzy", "xyx", Character.valueOf('z'), "ingotIron", Character.valueOf('x'), SSItems.dustWaterLily, Character.valueOf('y'), Items.redstone, })); } public static void addVanillaRecipes() { for (Map.Entry<ItemStack, ItemStack> e : ((HashMap<ItemStack, ItemStack>) FurnaceRecipes.smelting().getSmeltingList()).entrySet()) { try { if (e.getValue().getItem().hasContainerItem(e.getValue().copy()) && e.getKey().getItem().hasContainerItem(e.getKey().copy())) { if (checkItem(e.getValue().getItem().getContainerItem(e.getValue().copy()), e.getKey().getItem().getContainerItem(e.getKey().copy()))) continue; } FurnaceCraftingManager.getInstance().addShapelessRecipe(e.getValue(), new Object[] { e.getKey() }); } catch (NullPointerException nullE) { } } } private static boolean checkItem(ItemStack p_151397_1_, ItemStack p_151397_2_) { return p_151397_2_.getItem() == p_151397_1_.getItem() && (p_151397_2_.getItemDamage() == 32767 || p_151397_2_.getItemDamage() == p_151397_1_.getItemDamage()); } }
UTF-8
Java
12,507
java
RecipesFurnaceCraft.java
Java
[]
null
[]
package shift.sextiarysector.recipe; import java.util.HashMap; import java.util.Map; import net.minecraft.init.Blocks; import net.minecraft.init.Items; import net.minecraft.item.ItemStack; import net.minecraft.item.crafting.FurnaceRecipes; import net.minecraftforge.oredict.ShapedOreRecipe; import net.minecraftforge.oredict.ShapelessOreRecipe; import shift.sextiarysector.SSBlocks; import shift.sextiarysector.SSItems; public class RecipesFurnaceCraft { public static void addRecipes(FurnaceCraftingManager p_77608_1_) { //飲み物 //p_77608_1_.addRecipe(new ShapelessOreRecipe(new ItemStack(SSItems.drinkingWaterBottle, 1), // new Object[] { // new ItemStack(Items.potionitem), // })); //スライム p_77608_1_.addRecipe(new ShapelessOreRecipe(new ItemStack(Items.slime_ball, 1), new Object[] { SSItems.dustWaterLily, "condimentSugar", "fluidWater", })); p_77608_1_.addRecipe(new ShapelessOreRecipe(new ItemStack(Items.slime_ball, 1), new Object[] { "dyeGreen", "fluidSap", })); //石鹸 p_77608_1_.addRecipe(new ShapelessOreRecipe(new ItemStack(SSItems.soap, 1), new Object[] { "dustAsh", SSItems.animalOil, SSItems.animalOil })); /* p_77608_1_.addRecipe(new ShapelessOreRecipe(new ItemStack(Items.slime_ball, 2), new Object[] { "condimentSugar", "condimentSugar", "condimentSalt", "fluidSap", })); p_77608_1_.addRecipe(new ShapelessOreRecipe(new ItemStack(Items.slime_ball, 2), new Object[] { "algaLaver", "algaLaver", "condimentSalt", "fluidWater", })); */ //p_77608_1_.addRecipe(new ShapelessOreRecipe(new ItemStack(SSItems.drinkingWaterBottle, 2), // new Object[] { // SSItems.emptyBottle, // SSItems.emptyBottle, // SSItems.waterBottle, // })); p_77608_1_.addRecipe(new ShapelessOreRecipe(new ItemStack(SSItems.chocolate, 1), new Object[] { "condimentSugar", "condimentSugar", "condimentSugar", "condimentCocoa", })); p_77608_1_.addRecipe(new ShapelessOreRecipe(new ItemStack(SSItems.redGel, 2), new Object[] { "dustRedstone", "slimeball" })); p_77608_1_.addRecipe(new ShapelessOreRecipe(new ItemStack(SSItems.blueGel, 2), new Object[] { "dustBluestone", "slimeball" })); p_77608_1_.addRecipe(new ShapelessOreRecipe(new ItemStack(SSItems.yellowGel, 2), new Object[] { "dustYellowstone", "slimeball" })); p_77608_1_.addRecipe(new ShapelessOreRecipe(new ItemStack(SSItems.steelIngot, 1), new Object[] { "dustCoal", "dustIron" })); p_77608_1_.addRecipe(new ShapelessOreRecipe(new ItemStack(SSItems.brassIngot, 2), new Object[] { "dustCopper", "dustCopper", "dustZinc" })); p_77608_1_.addRecipe(new ShapelessOreRecipe(new ItemStack(SSItems.ninjaIngot, 1), new Object[] { "dustMithril", "dustDiamond" })); //瓦 p_77608_1_.addRecipe(new ShapelessOreRecipe(new ItemStack(SSItems.kawara, 1), new Object[] { Items.clay_ball, SSItems.glaze })); /* p_77608_1_.addRecipe(new ShapedOreRecipe(new ItemStack(SSItems.unit, 1), new Object[] { "xxx", "xyx", "xxx", Character.valueOf('y'), SSItems.blueGel, Character.valueOf('x'), "cobblestone", })); */ //p_77608_1_.addRecipe(new ShapedOreRecipe(new ItemStack(SSBlocks.machineFrame, 1), // new Object[] { "xxx", "xyx", "xxx", // Character.valueOf('y'), "gelBluestone", // Character.valueOf('x'), "cobblestone", // })); // p_77608_1_.addRecipe(new ShapedOreRecipe(new ItemStack(SSItems.emptyBottle, 8), // new Object[] { // "x", "x", // 'x', "paneGlassColorless", // })); p_77608_1_.addRecipe(new ShapedOreRecipe(new ItemStack(SSItems.orichalcumGem, 1), new Object[] { "xyb", "aza", "byx", 'x', "ingotBrass", 'y', "ingotSilver", 'z', "craftingMagic", 'a', "ingotMithril", 'b', "ingotGold" })); //Hammer //p_77608_1_.addRecipe(new ShapedOreRecipe(new ItemStack(SSItems.ironSpanner, 1), // new Object[] { "xxx", " y ", " y ", // Character.valueOf('x'), "ingotIron", // Character.valueOf('y'), "stickWood", // })); //鉄のリング p_77608_1_.addRecipe(new ShapedOreRecipe(new ItemStack(SSItems.ironRing, 1), new Object[] { " x ", "x x", " x ", Character.valueOf('x'), "ingotIron", })); //クリーパーリング //p_77608_1_.addRecipe(new ShapelessOreRecipe(new ItemStack(SSItems.creeperRing, 1), // new Object[] { // "ringIron", // SSItems.objectReactor, // BlockMonitor.getMonitor(MonitorType.creeper) // })); //MPRing p_77608_1_.addRecipe(new ShapelessOreRecipe(new ItemStack(SSItems.mpRing, 1), new Object[] { "ringIron", SSItems.magicDust, "dustGold" })); //XPRing p_77608_1_.addRecipe(new ShapelessOreRecipe(new ItemStack(SSItems.xpRing, 1), new Object[] { "ringIron", SSItems.magicDust, new ItemStack(Items.dye, 1, 4) })); //液体カマド p_77608_1_.addRecipe(new ShapedOreRecipe(new ItemStack(SSBlocks.fluidFurnace, 1), new Object[] { "xxx", "xyx", "xxx", Character.valueOf('x'), "cobblestone", Character.valueOf('y'), Blocks.glass_pane, })); //魔法カマド p_77608_1_.addRecipe(new ShapedOreRecipe(new ItemStack(SSBlocks.magicFurnace, 1), new Object[] { "xxx", "xyx", "xxx", Character.valueOf('x'), "cobblestone", Character.valueOf('y'), SSItems.magicDust, })); //フリーザー p_77608_1_.addRecipe(new ShapelessOreRecipe(new ItemStack(SSBlocks.freezer, 1), new Object[] { SSItems.objectReactor, Blocks.ice, Blocks.furnace, })); //乾燥機 p_77608_1_.addRecipe(new ShapedOreRecipe(new ItemStack(SSBlocks.foodSmokers, 1), new Object[] { "xxx", "xyx", "xxx", Character.valueOf('x'), "ingotSteel", Character.valueOf('y'), Blocks.glass_pane, })); //time p_77608_1_.addRecipe(new ShapedOreRecipe(new ItemStack(SSBlocks.chunkLoader, 1), new Object[] { "xyx", "yzy", "xyx", Character.valueOf('x'), "ingotIron", Character.valueOf('y'), Blocks.obsidian, Character.valueOf('z'), Items.clock, })); //パイプ p_77608_1_.addRecipe(new ShapedOreRecipe(new ItemStack(SSBlocks.copperPipe, 4), new Object[] { "x", "x", "x", 'x', "ingotCopper", })); //料理 p_77608_1_.addRecipe(new ShapelessOreRecipe(new ItemStack(SSItems.curryRice, 1), new Object[] { "containerWoodBowl", "condimentCurryPowder", "cookingRice", "cropPotato", "cropCarrot" })); //スープ p_77608_1_.addRecipe(new ShapelessOreRecipe(new ItemStack(SSItems.carrotSoup, 1), new Object[] { "containerWoodBowl", "fluidWater", "cropCarrot" })); p_77608_1_.addRecipe(new ShapelessOreRecipe(new ItemStack(SSItems.cornSoup, 1), new Object[] { "containerWoodBowl", "fluidWater", "cropCorn" })); p_77608_1_.addRecipe(new ShapelessOreRecipe(new ItemStack(SSItems.eggSoup, 1), new Object[] { "containerWoodBowl", "fluidWater", "eggChicken" })); p_77608_1_.addRecipe(new ShapelessOreRecipe(new ItemStack(SSItems.onionSoup, 1), new Object[] { "containerWoodBowl", "fluidWater", "cropOnion" })); p_77608_1_.addRecipe(new ShapelessOreRecipe(new ItemStack(SSItems.tomatoSoup, 1), new Object[] { "containerWoodBowl", "fluidWater", "cropTomato" })); //輸送系 p_77608_1_.addRecipe(new ShapedOreRecipe(new ItemStack(SSBlocks.poweredBuoy, 4), new Object[] { "xyx", "yzy", "xyx", Character.valueOf('x'), "ingotIron", Character.valueOf('y'), SSItems.dustWaterLily, Character.valueOf('z'), Items.redstone, })); p_77608_1_.addRecipe(new ShapedOreRecipe(new ItemStack(SSBlocks.boardingBuoy, 4), new Object[] { "xyx", "yzy", "xyx", Character.valueOf('x'), "ingotGold", Character.valueOf('y'), SSItems.dustWaterLily, Character.valueOf('z'), Items.redstone, })); p_77608_1_.addRecipe(new ShapedOreRecipe(new ItemStack(SSBlocks.detectorBuoy, 4), new Object[] { "xyx", "yzy", "xyx", Character.valueOf('z'), "ingotIron", Character.valueOf('x'), SSItems.dustWaterLily, Character.valueOf('y'), Items.redstone, })); } public static void addVanillaRecipes() { for (Map.Entry<ItemStack, ItemStack> e : ((HashMap<ItemStack, ItemStack>) FurnaceRecipes.smelting().getSmeltingList()).entrySet()) { try { if (e.getValue().getItem().hasContainerItem(e.getValue().copy()) && e.getKey().getItem().hasContainerItem(e.getKey().copy())) { if (checkItem(e.getValue().getItem().getContainerItem(e.getValue().copy()), e.getKey().getItem().getContainerItem(e.getKey().copy()))) continue; } FurnaceCraftingManager.getInstance().addShapelessRecipe(e.getValue(), new Object[] { e.getKey() }); } catch (NullPointerException nullE) { } } } private static boolean checkItem(ItemStack p_151397_1_, ItemStack p_151397_2_) { return p_151397_2_.getItem() == p_151397_1_.getItem() && (p_151397_2_.getItemDamage() == 32767 || p_151397_2_.getItemDamage() == p_151397_1_.getItemDamage()); } }
12,507
0.474482
0.447472
330
36.58485
29.91291
166
false
false
0
0
0
0
0
0
1.163636
false
false
4
899e69dda327cf531142cd03bdc191dc890dd4a6
32,384,053,437,201
d3a3bc2c07d46ab86a4aeef3c73dcdea19ebe25b
/eapli.ExpenseManager/src/Model/ExpenseRecord.java
eecb817332e24322966b5657cf40d914aac2fda8
[]
no_license
mcneves/EAPLI_PL_2DG
https://github.com/mcneves/EAPLI_PL_2DG
8acae5c0435ef9579b28b99f391b447b62e7cc76
2368acb2c00fbb1ce2ed8311f2a1f1447ea2a0ec
refs/heads/master
2021-01-22T11:47:15.445000
2013-05-24T16:06:15
2013-05-24T16:06:15
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Model; import Persistence.Inmemory.ExpenseRepository; import eapli.util.DateTime; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; /** * * @author i110459 */ public class ExpenseRecord { private List<Expense> allExpenses; public ExpenseRecord(List<Expense> all) { allExpenses = all; } public List<Expense> getMonthlyExpensesList(String month) { BigDecimal total = new BigDecimal(0); String[] aux = month.split("-"); int[] auxM = new int[2]; List<Expense> despesas = allExpenses; List<Expense> despmes = new ArrayList<>(); for (int i = 0; i < despesas.size(); i++) { auxM[0] = despesas.get(i).getMonth()+1; auxM[1] = despesas.get(i).getYear()+1900; if ((Integer.parseInt(aux[0])) == auxM[0] && (Integer.parseInt(aux[1])) == auxM[1]) { Expense e=despesas.get(i); despmes.add(e); } } return despmes; } public List<Expense> getFMonthlyExpensesList(ExpenseType T, String month) { String[] aux = month.split("-"); int[] auxM = new int[2]; List<Expense> despesas = allExpenses; List<Expense> despmes = new ArrayList<>(); for (int i = 0; i < despesas.size(); i++) { auxM[0] = despesas.get(i).getMonth()+1; auxM[1] = despesas.get(i).getYear()+1900; if ((Integer.parseInt(aux[0])) == auxM[0] && (Integer.parseInt(aux[1])) == auxM[1] && despesas.get(i).getExpenseType().getdescription().matches(T.getdescription())) { Expense e=despesas.get(i); despmes.add(e); } } return despmes; } public BigDecimal getMonthlyExpenses(String month) { BigDecimal total = new BigDecimal(0); List<Expense> monthExpenses = new ArrayList<>(); for (int i = 0; i < allExpenses.size(); i++) { if (allExpenses.get(i).getMonth()+1 == Integer.parseInt(month)) { monthExpenses.add(allExpenses.get(i)); } } for (int i = 0; i < monthExpenses.size(); i++) { total = new BigDecimal(total.doubleValue() + monthExpenses.get(i).getAmount().doubleValue()); } return total; } public BigDecimal getWeeklyExpenses(int n) { List<Expense> weekExpenses = new ArrayList<>(); BigDecimal total = new BigDecimal(0); for (int i = 0; i < allExpenses.size(); i++) { Calendar c = Calendar.getInstance(); c.setTime(allExpenses.get(i).getDateOcurred()); if (c.get(Calendar.WEEK_OF_YEAR) == n) { weekExpenses.add(allExpenses.get(i)); } } for (int i = 0; i < weekExpenses.size(); i++) { total = new BigDecimal(total.doubleValue() + weekExpenses.get(i).getAmount().doubleValue()); } return total; } public float calculateExpensesBalance() { float balance = 0; for (int i = 0; i < allExpenses.size(); i++) { balance = balance + allExpenses.get(i).getAmount().floatValue(); } System.out.println("DEBUG - Balance: " + balance); return balance; } }
UTF-8
Java
3,531
java
ExpenseRecord.java
Java
[ { "context": "te;\r\nimport java.util.List;\r\n\r\n/**\r\n *\r\n * @author i110459\r\n */\r\npublic class ExpenseRecord {\r\n\r\n private L", "end": 363, "score": 0.9628664255142212, "start": 356, "tag": "USERNAME", "value": "i110459" } ]
null
[]
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Model; import Persistence.Inmemory.ExpenseRepository; import eapli.util.DateTime; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; /** * * @author i110459 */ public class ExpenseRecord { private List<Expense> allExpenses; public ExpenseRecord(List<Expense> all) { allExpenses = all; } public List<Expense> getMonthlyExpensesList(String month) { BigDecimal total = new BigDecimal(0); String[] aux = month.split("-"); int[] auxM = new int[2]; List<Expense> despesas = allExpenses; List<Expense> despmes = new ArrayList<>(); for (int i = 0; i < despesas.size(); i++) { auxM[0] = despesas.get(i).getMonth()+1; auxM[1] = despesas.get(i).getYear()+1900; if ((Integer.parseInt(aux[0])) == auxM[0] && (Integer.parseInt(aux[1])) == auxM[1]) { Expense e=despesas.get(i); despmes.add(e); } } return despmes; } public List<Expense> getFMonthlyExpensesList(ExpenseType T, String month) { String[] aux = month.split("-"); int[] auxM = new int[2]; List<Expense> despesas = allExpenses; List<Expense> despmes = new ArrayList<>(); for (int i = 0; i < despesas.size(); i++) { auxM[0] = despesas.get(i).getMonth()+1; auxM[1] = despesas.get(i).getYear()+1900; if ((Integer.parseInt(aux[0])) == auxM[0] && (Integer.parseInt(aux[1])) == auxM[1] && despesas.get(i).getExpenseType().getdescription().matches(T.getdescription())) { Expense e=despesas.get(i); despmes.add(e); } } return despmes; } public BigDecimal getMonthlyExpenses(String month) { BigDecimal total = new BigDecimal(0); List<Expense> monthExpenses = new ArrayList<>(); for (int i = 0; i < allExpenses.size(); i++) { if (allExpenses.get(i).getMonth()+1 == Integer.parseInt(month)) { monthExpenses.add(allExpenses.get(i)); } } for (int i = 0; i < monthExpenses.size(); i++) { total = new BigDecimal(total.doubleValue() + monthExpenses.get(i).getAmount().doubleValue()); } return total; } public BigDecimal getWeeklyExpenses(int n) { List<Expense> weekExpenses = new ArrayList<>(); BigDecimal total = new BigDecimal(0); for (int i = 0; i < allExpenses.size(); i++) { Calendar c = Calendar.getInstance(); c.setTime(allExpenses.get(i).getDateOcurred()); if (c.get(Calendar.WEEK_OF_YEAR) == n) { weekExpenses.add(allExpenses.get(i)); } } for (int i = 0; i < weekExpenses.size(); i++) { total = new BigDecimal(total.doubleValue() + weekExpenses.get(i).getAmount().doubleValue()); } return total; } public float calculateExpensesBalance() { float balance = 0; for (int i = 0; i < allExpenses.size(); i++) { balance = balance + allExpenses.get(i).getAmount().floatValue(); } System.out.println("DEBUG - Balance: " + balance); return balance; } }
3,531
0.54857
0.536675
102
32.617645
28.813478
178
false
false
0
0
0
0
0
0
0.607843
false
false
4
6b7ddbb1f95946ea6837285ebeb52fe2689821e9
6,021,544,172,825
53c797550d72ee589db19d309714d466068390c7
/mystory-sas/mystory-sas-intf/src/main/java/com/boneix/elasticsearch/repository/UserRepository.java
cc3bae0aeca37cbdec7b4a855af3a6a6aa8362b4
[]
no_license
kaitezhan/Demos
https://github.com/kaitezhan/Demos
d3f777f4c07c56ab66370822ec89856ea1893e11
4760a3c7a82d75a0092be92713e8e47e42cd5eb9
refs/heads/master
2020-03-28T05:39:53.191000
2018-09-06T07:11:01
2018-09-06T07:11:01
147,789,679
1
0
null
true
2018-09-07T07:47:53
2018-09-07T07:47:53
2018-09-06T07:11:24
2018-09-06T07:11:23
3,328
0
0
0
null
false
null
package com.boneix.elasticsearch.repository; import com.boneix.elasticsearch.document.UserDocument; import org.springframework.data.elasticsearch.repository.ElasticsearchRepository; /** * Created by zhangrong5 on 2016/9/21. */ public interface UserRepository extends ElasticsearchRepository<UserDocument,Integer> { UserDocument findByUserId(int userId); }
UTF-8
Java
365
java
UserRepository.java
Java
[ { "context": "itory.ElasticsearchRepository;\n\n\n/**\n * Created by zhangrong5 on 2016/9/21.\n */\npublic interface UserRepository", "end": 213, "score": 0.9996713399887085, "start": 203, "tag": "USERNAME", "value": "zhangrong5" } ]
null
[]
package com.boneix.elasticsearch.repository; import com.boneix.elasticsearch.document.UserDocument; import org.springframework.data.elasticsearch.repository.ElasticsearchRepository; /** * Created by zhangrong5 on 2016/9/21. */ public interface UserRepository extends ElasticsearchRepository<UserDocument,Integer> { UserDocument findByUserId(int userId); }
365
0.821918
0.8
12
29.416666
31.391237
87
false
false
0
0
0
0
0
0
0.416667
false
false
4
48a4d24cf6eee5ef355285a03184bc0f2a7973b9
8,306,466,791,187
69debdf0e42ba363581fa9a69830796941b83edc
/workspace/VjezbeW3D1/src/Mujo.java
d13d2e5135f1fc787ffdd4913fd0980b18fe5634
[]
no_license
GordanMasic/bitCampMiniMac
https://github.com/GordanMasic/bitCampMiniMac
fa13533f70a9bc25a43e7b1229e30888ede3c5a1
378414b1eb4dac312341390761fbc9ee14d950ab
refs/heads/master
2020-06-06T09:51:12.029000
2015-08-03T15:19:00
2015-08-03T15:19:00
37,205,105
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.util.Scanner; public class Mujo { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Input number of containers: "); int n = input.nextInt(); System.out.print("Input capacity: "); int k = input.nextInt(); int counter = 0; input.close(); int reducedN = n; while (reducedN > k){ reducedN = n; while (reducedN % 2 == 0){ reducedN /= 2; }if (reducedN > k){ n++; counter++; } } System.out.println(counter); } }
UTF-8
Java
526
java
Mujo.java
Java
[]
null
[]
import java.util.Scanner; public class Mujo { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Input number of containers: "); int n = input.nextInt(); System.out.print("Input capacity: "); int k = input.nextInt(); int counter = 0; input.close(); int reducedN = n; while (reducedN > k){ reducedN = n; while (reducedN % 2 == 0){ reducedN /= 2; }if (reducedN > k){ n++; counter++; } } System.out.println(counter); } }
526
0.596958
0.589354
30
16.533333
14.440067
51
false
false
0
0
0
0
0
0
2.233333
false
false
4
65196464b45e35e44db11348917e9d87ddf5797c
1,279,900,302,996
98fb5148d987cb57c0c57fec752cf7466507580d
/src/main/java/org/kemri/wellcome/dhisreport/api/impl/DHIS2ReportingServiceImpl.java
067776902ed394c7bdf396d804c87f8af72b60f0
[]
no_license
Keniajin/kemri-wellcome-dhisreport
https://github.com/Keniajin/kemri-wellcome-dhisreport
964d7e752290e7b7050955eb5b020068de8606af
acd6b458ecb4ac50a6d1d7189fcd8e22a2f146b5
refs/heads/master
2021-01-15T23:12:20.877000
2013-05-06T07:01:12
2013-05-06T07:01:12
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * Copyright 2012 Society for Health Information Systems Programmes, India (HISP India) * * This file is part of DHIS2 Reporting module. * * DHIS2 Reporting module is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * DHIS2 Reporting module is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with DHIS2 Reporting module. If not, see <http://www.gnu.org/licenses/>. * **/ package org.kemri.wellcome.dhisreport.api.impl; import java.io.InputStream; import java.io.OutputStream; import java.util.Collection; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import javax.xml.bind.Unmarshaller; import org.apache.log4j.Logger; import org.hisp.dhis.dxf2.importsummary.ImportSummary; import org.kemri.wellcome.dhisreport.api.DHIS2ReportingException; import org.kemri.wellcome.dhisreport.api.DHIS2ReportingService; import org.kemri.wellcome.dhisreport.api.db.DHIS2ReportingDAO; import org.kemri.wellcome.dhisreport.api.db.DhisServerDAO; import org.kemri.wellcome.dhisreport.api.dxf2.DataValue; import org.kemri.wellcome.dhisreport.api.dxf2.DataValueSet; import org.kemri.wellcome.dhisreport.api.model.*; import org.kemri.wellcome.dhisreport.api.utils.Period; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Propagation; /** * It is a default implementation of {@link DHIS2ReportingService}. */ @Service("service") @Transactional(propagation=Propagation.REQUIRED, rollbackFor=Exception.class) public class DHIS2ReportingServiceImpl implements DHIS2ReportingService { protected final Logger log = Logger.getLogger(DHIS2ReportingServiceImpl.class); @Autowired private DHIS2ReportingDAO dao; @Autowired private DhisServerDAO serverDAO; @Override public ReportDefinition fetchReportTemplates() throws DHIS2ReportingException { return serverDAO.getDhisServer().fetchReportTemplates(); } @Override public ImportSummary postDataValueSet( DataValueSet dvset ) { try { return serverDAO.getDhisServer().postReport( dvset ); } catch (DHIS2ReportingException e) { log.error(e.getMessage()); e.printStackTrace(); return null; } } @Override public DataElement getDataElement( Integer id ) { return dao.getDataElement( id ); } @Override public DataElement getDataElementByUid( String uid ) { return dao.getDataElementByUid( uid ); } @Override public DataElement saveDataElement( DataElement de ) { return dao.saveDataElement( de ); } @Override public void purgeDataElement( DataElement de ) { dao.deleteDataElement( de ); } @Override public Disaggregation getDisaggregation( Integer id ) { return dao.getDisaggregation( id ); } @Override public Disaggregation saveDisaggregation( Disaggregation disagg ) { return dao.saveDisaggregation( disagg ); } @Override public ReportDefinition getReportDefinition( Integer id ) { return dao.getReportDefinition( id ); } public ReportDefinition getReportDefinitionByUId( String uid ) { return dao.getReportDefinitionByUid( uid ); } @Override public ReportDefinition saveReportDefinition( ReportDefinition reportDefinition ) { return dao.saveReportDefinition( reportDefinition ); } @Override public Collection<DataElement> getAllDataElements() { return dao.getAllDataElements(); } @Override public void purgeDisaggregation( Disaggregation disagg ) { dao.deleteDisaggregation( disagg ); } @Override public Collection<Disaggregation> getAllDisaggregations() { return dao.getAllDisaggregations(); } @Override public void purgeReportDefinition( ReportDefinition rd ) { dao.deleteReportDefinition( rd ); } @Override public Collection<ReportDefinition> getAllReportDefinitions() { return dao.getAllReportDefinitions(); } @Override public String evaluateDataValueTemplate( DataValueTemplate dv, Period period, Location location ) throws DHIS2ReportingException { return dao.evaluateDataValueTemplate( dv, period, location ); } /** * Create a datavalueset report TODO: handle the sql query exceptions which are bound to happen * * @param reportDefinition * @param period * @param location * @return */ @Override public DataValueSet evaluateReportDefinition( ReportDefinition reportDefinition, Period period, Location location ) { Collection<DataValueTemplate> templates = reportDefinition.getDataValueTemplates(); DataValueSet dataValueSet = new DataValueSet(); dataValueSet.setDataElementIdScheme( "code" ); dataValueSet.setOrgUnitIdScheme( "code" ); dataValueSet.setPeriod( period.getAsIsoString() ); // dataValueSet.setOrgUnit( "OU_" + location.getId() ); /* Removed because will set directly from the controller */ dataValueSet.setDataSet( reportDefinition.getCode() ); Collection<DataValue> dataValues = dataValueSet.getDataValues(); for ( DataValueTemplate dvt : templates ) { DataValue dataValue = new DataValue(); dataValue.setDataElement( dvt.getDataelement().getCode() ); dataValue.setCategoryOptionCombo( dvt.getDisaggregation().getCode() ); try { String value = dao.evaluateDataValueTemplate( dvt, period, location ); if ( value != null ) { dataValue.setValue( value ); dataValues.add( dataValue ); } } catch ( DHIS2ReportingException ex ) { // TODO: percolate this through to UI log.warn( ex.getMessage() ); } } return dataValueSet; } @Override public void saveReportTemplates( ReportTemplates rt ) { throw new UnsupportedOperationException( "Not supported yet." ); } @Override public void unMarshallandSaveReportTemplates( InputStream is ) { JAXBContext jaxbContext=null; Unmarshaller jaxbUnmarshaller=null; ReportTemplates reportTemplates=null; try { jaxbContext = JAXBContext.newInstance( ReportTemplates.class ); jaxbUnmarshaller = jaxbContext.createUnmarshaller(); reportTemplates = (ReportTemplates) jaxbUnmarshaller.unmarshal( is ); if(reportTemplates==null) log.error("\n reportTemplates : null"); } catch (JAXBException e) { log.error(e.getMessage()); e.printStackTrace(); } for ( DataElement de : reportTemplates.getDataElements() ){ saveDataElement( de ); } for ( Disaggregation disagg : reportTemplates.getDisaggregations() ){ saveDisaggregation( disagg ); } for ( ReportDefinition rd : reportTemplates.getReportDefinitions() ) { ReportDefinition reportDefination = saveReportDefinition( rd ); for ( DataValueTemplate dvt : rd.getDataValueTemplates() ) { dvt.setReportDefinition( reportDefination ); saveDataValueTemplate(dvt); } } } @Override public ReportTemplates getReportTemplates() { ReportTemplates rt = new ReportTemplates(); rt.setDataElements( getAllDataElements() ); rt.setDisaggregations( getAllDisaggregations() ); rt.setReportDefinitions( getAllReportDefinitions() ); return rt; } @Override public void marshallReportTemplates( OutputStream os, ReportTemplates rt ) throws Exception { JAXBContext jaxbContext = JAXBContext.newInstance( ReportTemplates.class ); Marshaller marshaller = jaxbContext.createMarshaller(); marshaller.marshal( rt, os ); } @Override public DataValueTemplate getDataValueTemplate( Integer id ) { return dao.getDataValueTemplate( id ); } @Override public void saveDataValueTemplate( DataValueTemplate dvt ) { dao.saveDataValueTemplate( dvt ); } @Override public Location getLocationByOU_Code( String OU_Code ) { return dao.getLocationByOU_Code( OU_Code ); } @Override public String getUsername() { return SecurityContextHolder.getContext().getAuthentication().getName(); } @Override public void purgeDataValueTemplate(DataValueTemplate dvt) { dao.deleteDataValueTemplate(dvt); } @Override public void purgeLocation(Location ln) { dao.deleteLocation(ln); } @Override public Location saveLocation(Location ln) { return dao.saveLocation( ln ); } @Override public Location getLocation(Integer id) { return dao.getLocation( id ); } @Override public Collection<Location> getAllLocations() { return dao.getAllLocations(); } }
UTF-8
Java
9,759
java
DHIS2ReportingServiceImpl.java
Java
[]
null
[]
/** * Copyright 2012 Society for Health Information Systems Programmes, India (HISP India) * * This file is part of DHIS2 Reporting module. * * DHIS2 Reporting module is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * DHIS2 Reporting module is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with DHIS2 Reporting module. If not, see <http://www.gnu.org/licenses/>. * **/ package org.kemri.wellcome.dhisreport.api.impl; import java.io.InputStream; import java.io.OutputStream; import java.util.Collection; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import javax.xml.bind.Unmarshaller; import org.apache.log4j.Logger; import org.hisp.dhis.dxf2.importsummary.ImportSummary; import org.kemri.wellcome.dhisreport.api.DHIS2ReportingException; import org.kemri.wellcome.dhisreport.api.DHIS2ReportingService; import org.kemri.wellcome.dhisreport.api.db.DHIS2ReportingDAO; import org.kemri.wellcome.dhisreport.api.db.DhisServerDAO; import org.kemri.wellcome.dhisreport.api.dxf2.DataValue; import org.kemri.wellcome.dhisreport.api.dxf2.DataValueSet; import org.kemri.wellcome.dhisreport.api.model.*; import org.kemri.wellcome.dhisreport.api.utils.Period; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Propagation; /** * It is a default implementation of {@link DHIS2ReportingService}. */ @Service("service") @Transactional(propagation=Propagation.REQUIRED, rollbackFor=Exception.class) public class DHIS2ReportingServiceImpl implements DHIS2ReportingService { protected final Logger log = Logger.getLogger(DHIS2ReportingServiceImpl.class); @Autowired private DHIS2ReportingDAO dao; @Autowired private DhisServerDAO serverDAO; @Override public ReportDefinition fetchReportTemplates() throws DHIS2ReportingException { return serverDAO.getDhisServer().fetchReportTemplates(); } @Override public ImportSummary postDataValueSet( DataValueSet dvset ) { try { return serverDAO.getDhisServer().postReport( dvset ); } catch (DHIS2ReportingException e) { log.error(e.getMessage()); e.printStackTrace(); return null; } } @Override public DataElement getDataElement( Integer id ) { return dao.getDataElement( id ); } @Override public DataElement getDataElementByUid( String uid ) { return dao.getDataElementByUid( uid ); } @Override public DataElement saveDataElement( DataElement de ) { return dao.saveDataElement( de ); } @Override public void purgeDataElement( DataElement de ) { dao.deleteDataElement( de ); } @Override public Disaggregation getDisaggregation( Integer id ) { return dao.getDisaggregation( id ); } @Override public Disaggregation saveDisaggregation( Disaggregation disagg ) { return dao.saveDisaggregation( disagg ); } @Override public ReportDefinition getReportDefinition( Integer id ) { return dao.getReportDefinition( id ); } public ReportDefinition getReportDefinitionByUId( String uid ) { return dao.getReportDefinitionByUid( uid ); } @Override public ReportDefinition saveReportDefinition( ReportDefinition reportDefinition ) { return dao.saveReportDefinition( reportDefinition ); } @Override public Collection<DataElement> getAllDataElements() { return dao.getAllDataElements(); } @Override public void purgeDisaggregation( Disaggregation disagg ) { dao.deleteDisaggregation( disagg ); } @Override public Collection<Disaggregation> getAllDisaggregations() { return dao.getAllDisaggregations(); } @Override public void purgeReportDefinition( ReportDefinition rd ) { dao.deleteReportDefinition( rd ); } @Override public Collection<ReportDefinition> getAllReportDefinitions() { return dao.getAllReportDefinitions(); } @Override public String evaluateDataValueTemplate( DataValueTemplate dv, Period period, Location location ) throws DHIS2ReportingException { return dao.evaluateDataValueTemplate( dv, period, location ); } /** * Create a datavalueset report TODO: handle the sql query exceptions which are bound to happen * * @param reportDefinition * @param period * @param location * @return */ @Override public DataValueSet evaluateReportDefinition( ReportDefinition reportDefinition, Period period, Location location ) { Collection<DataValueTemplate> templates = reportDefinition.getDataValueTemplates(); DataValueSet dataValueSet = new DataValueSet(); dataValueSet.setDataElementIdScheme( "code" ); dataValueSet.setOrgUnitIdScheme( "code" ); dataValueSet.setPeriod( period.getAsIsoString() ); // dataValueSet.setOrgUnit( "OU_" + location.getId() ); /* Removed because will set directly from the controller */ dataValueSet.setDataSet( reportDefinition.getCode() ); Collection<DataValue> dataValues = dataValueSet.getDataValues(); for ( DataValueTemplate dvt : templates ) { DataValue dataValue = new DataValue(); dataValue.setDataElement( dvt.getDataelement().getCode() ); dataValue.setCategoryOptionCombo( dvt.getDisaggregation().getCode() ); try { String value = dao.evaluateDataValueTemplate( dvt, period, location ); if ( value != null ) { dataValue.setValue( value ); dataValues.add( dataValue ); } } catch ( DHIS2ReportingException ex ) { // TODO: percolate this through to UI log.warn( ex.getMessage() ); } } return dataValueSet; } @Override public void saveReportTemplates( ReportTemplates rt ) { throw new UnsupportedOperationException( "Not supported yet." ); } @Override public void unMarshallandSaveReportTemplates( InputStream is ) { JAXBContext jaxbContext=null; Unmarshaller jaxbUnmarshaller=null; ReportTemplates reportTemplates=null; try { jaxbContext = JAXBContext.newInstance( ReportTemplates.class ); jaxbUnmarshaller = jaxbContext.createUnmarshaller(); reportTemplates = (ReportTemplates) jaxbUnmarshaller.unmarshal( is ); if(reportTemplates==null) log.error("\n reportTemplates : null"); } catch (JAXBException e) { log.error(e.getMessage()); e.printStackTrace(); } for ( DataElement de : reportTemplates.getDataElements() ){ saveDataElement( de ); } for ( Disaggregation disagg : reportTemplates.getDisaggregations() ){ saveDisaggregation( disagg ); } for ( ReportDefinition rd : reportTemplates.getReportDefinitions() ) { ReportDefinition reportDefination = saveReportDefinition( rd ); for ( DataValueTemplate dvt : rd.getDataValueTemplates() ) { dvt.setReportDefinition( reportDefination ); saveDataValueTemplate(dvt); } } } @Override public ReportTemplates getReportTemplates() { ReportTemplates rt = new ReportTemplates(); rt.setDataElements( getAllDataElements() ); rt.setDisaggregations( getAllDisaggregations() ); rt.setReportDefinitions( getAllReportDefinitions() ); return rt; } @Override public void marshallReportTemplates( OutputStream os, ReportTemplates rt ) throws Exception { JAXBContext jaxbContext = JAXBContext.newInstance( ReportTemplates.class ); Marshaller marshaller = jaxbContext.createMarshaller(); marshaller.marshal( rt, os ); } @Override public DataValueTemplate getDataValueTemplate( Integer id ) { return dao.getDataValueTemplate( id ); } @Override public void saveDataValueTemplate( DataValueTemplate dvt ) { dao.saveDataValueTemplate( dvt ); } @Override public Location getLocationByOU_Code( String OU_Code ) { return dao.getLocationByOU_Code( OU_Code ); } @Override public String getUsername() { return SecurityContextHolder.getContext().getAuthentication().getName(); } @Override public void purgeDataValueTemplate(DataValueTemplate dvt) { dao.deleteDataValueTemplate(dvt); } @Override public void purgeLocation(Location ln) { dao.deleteLocation(ln); } @Override public Location saveLocation(Location ln) { return dao.saveLocation( ln ); } @Override public Location getLocation(Integer id) { return dao.getLocation( id ); } @Override public Collection<Location> getAllLocations() { return dao.getAllLocations(); } }
9,759
0.685316
0.682754
328
28.753048
27.464445
123
false
false
0
0
0
0
0
0
0.585366
false
false
4
714d911871d2847dcdb1b5fb79a65bb4ecb8dbf4
34,239,479,300,618
f4bb1d1fa846285873d6fb1271a729ad16898d62
/src/main/java/jp/kaiz/atsassistmod/ATSAssistCore.java
37ddc0063494ea923e8e06863f3ccb3f3796085e
[ "MIT" ]
permissive
Kai-Z-JP/ATSAssistModSimple
https://github.com/Kai-Z-JP/ATSAssistModSimple
63c5f92dfb250e2a914d2c7fc3fad13ded16e470
f9141d3b6c1f7c25ac8a4e20c40067ef8b3a5f96
refs/heads/master
2023-04-17T06:26:33.386000
2021-04-30T22:52:18
2021-04-30T22:52:18
269,197,972
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package jp.kaiz.atsassistmod; import cpw.mods.fml.common.Mod; import cpw.mods.fml.common.Mod.EventHandler; import cpw.mods.fml.common.event.FMLInitializationEvent; import cpw.mods.fml.common.event.FMLPreInitializationEvent; import cpw.mods.fml.common.network.NetworkRegistry; import cpw.mods.fml.common.network.simpleimpl.SimpleNetworkWrapper; @Mod(modid = ATSAssistCore.MODID, version = ATSAssistCore.VERSION, name = ATSAssistCore.MODID) public class ATSAssistCore { //変更するとブロック消える public static final String MODID = "ATSAssistMod"; public static final String VERSION = "Simple3.0"; @Mod.Instance(MODID) public static ATSAssistCore INSTANCE; public static final SimpleNetworkWrapper NETWORK_WRAPPER = NetworkRegistry.INSTANCE.newSimpleChannel(MODID); //preInit init postInitの順 @EventHandler public void init(FMLInitializationEvent event) { new ATSAssistNetwork().init(); } @EventHandler public void preInit(FMLPreInitializationEvent event) { System.out.println("[ATSAssist]Loading..."); } }
UTF-8
Java
1,094
java
ATSAssistCore.java
Java
[]
null
[]
package jp.kaiz.atsassistmod; import cpw.mods.fml.common.Mod; import cpw.mods.fml.common.Mod.EventHandler; import cpw.mods.fml.common.event.FMLInitializationEvent; import cpw.mods.fml.common.event.FMLPreInitializationEvent; import cpw.mods.fml.common.network.NetworkRegistry; import cpw.mods.fml.common.network.simpleimpl.SimpleNetworkWrapper; @Mod(modid = ATSAssistCore.MODID, version = ATSAssistCore.VERSION, name = ATSAssistCore.MODID) public class ATSAssistCore { //変更するとブロック消える public static final String MODID = "ATSAssistMod"; public static final String VERSION = "Simple3.0"; @Mod.Instance(MODID) public static ATSAssistCore INSTANCE; public static final SimpleNetworkWrapper NETWORK_WRAPPER = NetworkRegistry.INSTANCE.newSimpleChannel(MODID); //preInit init postInitの順 @EventHandler public void init(FMLInitializationEvent event) { new ATSAssistNetwork().init(); } @EventHandler public void preInit(FMLPreInitializationEvent event) { System.out.println("[ATSAssist]Loading..."); } }
1,094
0.761726
0.75985
32
32.34375
28.572943
112
false
false
0
0
0
0
0
0
0.46875
false
false
4
10528c11dda412ff6ccadf6c6c9e5d9381275fda
35,665,408,430,962
e4c65810a23ee1aa528524ee83252ceafcfc276e
/Practica1_DT_FP/src/ec/edu/ups/modelo/Categoria.java
6954317108933b6f8be44d30a8ed5a3a049b08fe
[]
no_license
PelaezFrancisco/Pr-ctica-de-laboratorio-01-Servlets-JSP-y-JDBC
https://github.com/PelaezFrancisco/Pr-ctica-de-laboratorio-01-Servlets-JSP-y-JDBC
59ce3bdc8d505e1807dd714e051e92f745969d9b
edd53f9847dec21c791c720fa0c383a72b2b8dbe
refs/heads/main
2023-01-31T09:57:08.052000
2020-12-15T16:06:12
2020-12-15T16:06:12
315,437,186
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ec.edu.ups.modelo; import java.io.Serializable; public class Categoria implements Serializable { private static final long serialVersionUID = 1L; private int categoriaId; private String categoriaNombre; private String categoriaDescripcion; public Categoria() { // TODO Auto-generated constructor stub } public Categoria(int categoriaId, String categoriaNombre, String categoriaDescripcion ) { this.categoriaId=categoriaId; this.categoriaNombre= categoriaNombre; this.categoriaDescripcion= categoriaDescripcion; // TODO Auto-generated constructor stub } public int getCategoriaId() { return categoriaId; } public void setCategoriaId(int categoriaId) { this.categoriaId = categoriaId; } public String getCategoriaNombre() { return categoriaNombre; } public void setCategoriaNombre(String categoriaNombre) { this.categoriaNombre = categoriaNombre; } public String getCategoriaDescripcion() { return categoriaDescripcion; } public void setCategoriaDescripcion(String categoriaDescripcion) { this.categoriaDescripcion = categoriaDescripcion; } }
UTF-8
Java
1,109
java
Categoria.java
Java
[]
null
[]
package ec.edu.ups.modelo; import java.io.Serializable; public class Categoria implements Serializable { private static final long serialVersionUID = 1L; private int categoriaId; private String categoriaNombre; private String categoriaDescripcion; public Categoria() { // TODO Auto-generated constructor stub } public Categoria(int categoriaId, String categoriaNombre, String categoriaDescripcion ) { this.categoriaId=categoriaId; this.categoriaNombre= categoriaNombre; this.categoriaDescripcion= categoriaDescripcion; // TODO Auto-generated constructor stub } public int getCategoriaId() { return categoriaId; } public void setCategoriaId(int categoriaId) { this.categoriaId = categoriaId; } public String getCategoriaNombre() { return categoriaNombre; } public void setCategoriaNombre(String categoriaNombre) { this.categoriaNombre = categoriaNombre; } public String getCategoriaDescripcion() { return categoriaDescripcion; } public void setCategoriaDescripcion(String categoriaDescripcion) { this.categoriaDescripcion = categoriaDescripcion; } }
1,109
0.784491
0.783589
43
24.744186
22.145494
90
false
false
0
0
0
0
0
0
1.55814
false
false
4
5c704810c6ecb43aa7620af93e1e45f280745740
35,665,408,432,331
25ae3a5160249c248b3972ef3918b8fa0742eb7c
/HealthCareAppointmentApplication/src/main/java/com/healthCare/dao/IDiagnosticCenterRepository.java
7b0f0b4f8db5a0975fd62322f678fee10cb70ff6
[]
no_license
nomaanhusain/Sprint-Group-6
https://github.com/nomaanhusain/Sprint-Group-6
c1706a66be2b60a15b0653f5c2fa6f8ddf3d4197
c1e980621b96e9e75e989caa7a860289c11dd019
refs/heads/master
2023-04-01T02:19:22.380000
2021-04-12T04:07:30
2021-04-12T04:07:30
344,164,230
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.healthCare.dao; import java.util.List; import java.util.Optional; import java.util.Set; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import com.healthCare.exception.CenterNotFoundException; import com.healthCare.model.DiagnosticCenter; import com.healthCare.model.DiagnosticTest; @Repository public class IDiagnosticCenterRepository { @Autowired private DiagnosticCenterDAO diagCenterDao; @Autowired private DiagnosticTestDAO diagTestDao; public List<DiagnosticCenter> getAllDiagnosticCenter() { List<DiagnosticCenter> centerList = diagCenterDao.findAll(); return centerList; } public DiagnosticCenter addDiagnosticCenter(DiagnosticCenter diagnosticCenter) { DiagnosticCenter diag = diagCenterDao.save(diagnosticCenter); return diag; } public DiagnosticCenter getDiagnosticCenterById(int diagnosticCenterId) { Optional<DiagnosticCenter> optional=diagCenterDao.findById(diagnosticCenterId); DiagnosticCenter diag=optional.orElseThrow(()->new CenterNotFoundException("Center Not Exists")); return diag; } public DiagnosticCenter updateDiagnosticCenter(DiagnosticCenter diagnosticCenter) { DiagnosticCenter updateCenter = diagCenterDao.save(diagnosticCenter); return updateCenter; } public DiagnosticTest viewTestDetails(int diagnosticCenterId, String testName) { Optional<DiagnosticCenter> option=diagCenterDao.findById(diagnosticCenterId); DiagnosticCenter dc=option.get(); Set<DiagnosticTest> set=dc.getTests(); for(DiagnosticTest test:set) { if(test.getTestName().equals(testName)) { return test; } } return null; } public DiagnosticTest addTest(int diagnosticcenterId, int testId) { Optional<DiagnosticCenter> optionalDc=diagCenterDao.findById(diagnosticcenterId); Optional<DiagnosticTest> optionalDt=diagTestDao.findById(testId); DiagnosticCenter dc=optionalDc.get(); DiagnosticTest dt=optionalDt.get(); Set<DiagnosticTest> set=dc.getTests(); set.add(dt); dc.setTests(set); diagCenterDao.save(dc); return dt; } public DiagnosticCenter getDiagnosticCenter(String centername) { Optional<DiagnosticCenter> optional=diagCenterDao.findByName(centername); DiagnosticCenter centerName=optional.orElseThrow(()->new CenterNotFoundException("Center Not Exists")); return centerName; } public DiagnosticCenter removeDiagnosticCenter(int id) { Optional<DiagnosticCenter> op=diagCenterDao.findById(id); DiagnosticCenter dc= (DiagnosticCenter) op.orElseThrow(()-> new CenterNotFoundException("Center Does Not Exists")); diagCenterDao.delete(dc); return dc; } }
UTF-8
Java
2,659
java
IDiagnosticCenterRepository.java
Java
[]
null
[]
package com.healthCare.dao; import java.util.List; import java.util.Optional; import java.util.Set; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import com.healthCare.exception.CenterNotFoundException; import com.healthCare.model.DiagnosticCenter; import com.healthCare.model.DiagnosticTest; @Repository public class IDiagnosticCenterRepository { @Autowired private DiagnosticCenterDAO diagCenterDao; @Autowired private DiagnosticTestDAO diagTestDao; public List<DiagnosticCenter> getAllDiagnosticCenter() { List<DiagnosticCenter> centerList = diagCenterDao.findAll(); return centerList; } public DiagnosticCenter addDiagnosticCenter(DiagnosticCenter diagnosticCenter) { DiagnosticCenter diag = diagCenterDao.save(diagnosticCenter); return diag; } public DiagnosticCenter getDiagnosticCenterById(int diagnosticCenterId) { Optional<DiagnosticCenter> optional=diagCenterDao.findById(diagnosticCenterId); DiagnosticCenter diag=optional.orElseThrow(()->new CenterNotFoundException("Center Not Exists")); return diag; } public DiagnosticCenter updateDiagnosticCenter(DiagnosticCenter diagnosticCenter) { DiagnosticCenter updateCenter = diagCenterDao.save(diagnosticCenter); return updateCenter; } public DiagnosticTest viewTestDetails(int diagnosticCenterId, String testName) { Optional<DiagnosticCenter> option=diagCenterDao.findById(diagnosticCenterId); DiagnosticCenter dc=option.get(); Set<DiagnosticTest> set=dc.getTests(); for(DiagnosticTest test:set) { if(test.getTestName().equals(testName)) { return test; } } return null; } public DiagnosticTest addTest(int diagnosticcenterId, int testId) { Optional<DiagnosticCenter> optionalDc=diagCenterDao.findById(diagnosticcenterId); Optional<DiagnosticTest> optionalDt=diagTestDao.findById(testId); DiagnosticCenter dc=optionalDc.get(); DiagnosticTest dt=optionalDt.get(); Set<DiagnosticTest> set=dc.getTests(); set.add(dt); dc.setTests(set); diagCenterDao.save(dc); return dt; } public DiagnosticCenter getDiagnosticCenter(String centername) { Optional<DiagnosticCenter> optional=diagCenterDao.findByName(centername); DiagnosticCenter centerName=optional.orElseThrow(()->new CenterNotFoundException("Center Not Exists")); return centerName; } public DiagnosticCenter removeDiagnosticCenter(int id) { Optional<DiagnosticCenter> op=diagCenterDao.findById(id); DiagnosticCenter dc= (DiagnosticCenter) op.orElseThrow(()-> new CenterNotFoundException("Center Does Not Exists")); diagCenterDao.delete(dc); return dc; } }
2,659
0.796916
0.796916
88
29.045454
30.74045
117
false
false
0
0
0
0
0
0
1.534091
false
false
4
1c40b9263c05b4c24a5ff9dd0e6e2975d77d89c7
10,565,619,605,656
6a43ac677da700af25462bf8043ed358e9285065
/src/Clases/Tecnico.java
b2adfbc1f57cfc1922bcdee36ca290c4234946d3
[]
no_license
Anthony333220/proyectoFinal
https://github.com/Anthony333220/proyectoFinal
bab051598b2d7bb593b7a47516e035c954ee2060
df788b1f7f5f8c9f4a9517ae8806a1345110c9a9
refs/heads/master
2022-04-22T01:04:54.651000
2020-04-27T20:33:02
2020-04-27T20:33:02
257,476,823
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package Clases; import java.util.Date; /** * * @author Anthony */ public class Tecnico { private int cedula; private String nombre; private Date fechaNacimiento; private int telefono; private String correoElectronico; private double salario; public Tecnico(int cedula, String nombre, Date fechaNacimiento, int telefono, String correoElectronico, double salario) { this.cedula = cedula; this.nombre = nombre; this.fechaNacimiento = fechaNacimiento; this.telefono = telefono; this.correoElectronico = correoElectronico; this.salario = salario; } public Tecnico(int cedula, String nombre) { this.cedula = cedula; this.nombre = nombre; } public Tecnico(int cedula) { this.cedula = cedula; } public Tecnico() { this.cedula = 0; this.nombre = null; this.fechaNacimiento = null; this.telefono = 0; this.correoElectronico = null; this.salario = 0; } public int getCedula() { return cedula; } public void setCedula(int cedula) { this.cedula = cedula; } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public Date getFechaNacimiento() { return fechaNacimiento; } public void setFechaNacimiento(Date fechaNacimiento) { this.fechaNacimiento = fechaNacimiento; } public int getTelefono() { return telefono; } public void setTelefono(int telefono) { this.telefono = telefono; } public String getCorreoElectrónico() { return correoElectronico; } public void setCorreoElectrónico(String correoElectrónico) { this.correoElectronico = correoElectrónico; } public double getSalario() { return salario; } public void setSalario(double salario) { this.salario = salario; } public double calcularDeducciones(double salario){ return (double) ((salario * 0.055) + (salario * 0.0384) + (salario * 0.01) + (salario * 0.033)); } public double calcularRenta(double salario){ double renta; if (salario > 817000 && salario <= 1226000) { renta = (salario - 817001) * 0.10; return (double)(renta + calcularDeducciones(salario)); } else if (salario > 1226000) { renta = (salario - 1226001) * 0.15 + 40899.9; return (double) (renta + calcularDeducciones(salario)); } else { return (double) (calcularDeducciones(salario)); } } public double calcularSalario(){ double neto = this.calcularRenta(salario); return (double) (salario - neto) ; } @Override public String toString() { return "<Tecnico>" + "<Cedula>" + cedula + "</Cedula>" + "<Nombre>" + nombre + "</Nombre>" + "</Tecnico>"; } }
UTF-8
Java
3,009
java
Tecnico.java
Java
[ { "context": "Clases;\n\nimport java.util.Date;\n\n/**\n *\n * @author Anthony\n */\npublic class Tecnico {\n\n private int cedul", "end": 66, "score": 0.9997572898864746, "start": 59, "tag": "NAME", "value": "Anthony" } ]
null
[]
package Clases; import java.util.Date; /** * * @author Anthony */ public class Tecnico { private int cedula; private String nombre; private Date fechaNacimiento; private int telefono; private String correoElectronico; private double salario; public Tecnico(int cedula, String nombre, Date fechaNacimiento, int telefono, String correoElectronico, double salario) { this.cedula = cedula; this.nombre = nombre; this.fechaNacimiento = fechaNacimiento; this.telefono = telefono; this.correoElectronico = correoElectronico; this.salario = salario; } public Tecnico(int cedula, String nombre) { this.cedula = cedula; this.nombre = nombre; } public Tecnico(int cedula) { this.cedula = cedula; } public Tecnico() { this.cedula = 0; this.nombre = null; this.fechaNacimiento = null; this.telefono = 0; this.correoElectronico = null; this.salario = 0; } public int getCedula() { return cedula; } public void setCedula(int cedula) { this.cedula = cedula; } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public Date getFechaNacimiento() { return fechaNacimiento; } public void setFechaNacimiento(Date fechaNacimiento) { this.fechaNacimiento = fechaNacimiento; } public int getTelefono() { return telefono; } public void setTelefono(int telefono) { this.telefono = telefono; } public String getCorreoElectrónico() { return correoElectronico; } public void setCorreoElectrónico(String correoElectrónico) { this.correoElectronico = correoElectrónico; } public double getSalario() { return salario; } public void setSalario(double salario) { this.salario = salario; } public double calcularDeducciones(double salario){ return (double) ((salario * 0.055) + (salario * 0.0384) + (salario * 0.01) + (salario * 0.033)); } public double calcularRenta(double salario){ double renta; if (salario > 817000 && salario <= 1226000) { renta = (salario - 817001) * 0.10; return (double)(renta + calcularDeducciones(salario)); } else if (salario > 1226000) { renta = (salario - 1226001) * 0.15 + 40899.9; return (double) (renta + calcularDeducciones(salario)); } else { return (double) (calcularDeducciones(salario)); } } public double calcularSalario(){ double neto = this.calcularRenta(salario); return (double) (salario - neto) ; } @Override public String toString() { return "<Tecnico>" + "<Cedula>" + cedula + "</Cedula>" + "<Nombre>" + nombre + "</Nombre>" + "</Tecnico>"; } }
3,009
0.596672
0.575374
121
23.834711
23.481079
125
false
false
0
0
0
0
0
0
0.421488
false
false
4
346fecae878cb36b534edb43a9da2e4274e2ed1f
9,869,834,872,724
999575a3329394a239342974f145700271388c49
/src/main/java/com/pociot/hcb/auth/controller/UserController.java
1815ce6a8418e3c09548be7438249f28510eb3d6
[]
no_license
pociot/hcb-auth-service
https://github.com/pociot/hcb-auth-service
90701df898d32d1ac00697038904600d65e9bdf6
5338849890dab245bf0f0ca821970045473d9df2
refs/heads/master
2021-06-22T00:19:31.303000
2019-09-05T17:34:32
2019-09-05T17:34:32
150,875,939
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.pociot.hcb.auth.controller; import com.pociot.hcb.auth.domain.User; import com.pociot.hcb.auth.service.UserService; import java.security.Principal; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/users") public class UserController { private final UserService userService; public UserController(UserService userService) { this.userService = userService; } @RequestMapping(value = "/current", method = RequestMethod.GET) public Principal getUser(Principal principal) { return principal; } @RequestMapping(method = RequestMethod.POST) public void createUser(User user) { userService.create(user); } }
UTF-8
Java
820
java
UserController.java
Java
[]
null
[]
package com.pociot.hcb.auth.controller; import com.pociot.hcb.auth.domain.User; import com.pociot.hcb.auth.service.UserService; import java.security.Principal; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/users") public class UserController { private final UserService userService; public UserController(UserService userService) { this.userService = userService; } @RequestMapping(value = "/current", method = RequestMethod.GET) public Principal getUser(Principal principal) { return principal; } @RequestMapping(method = RequestMethod.POST) public void createUser(User user) { userService.create(user); } }
820
0.786585
0.786585
28
28.285715
22.084023
65
false
false
0
0
0
0
0
0
0.428571
false
false
4
467a0b58eb77415fc600c1d82f4af9e9063dfaec
34,033,320,866,763
39481e25321a8b67222cbd97904bfb24be033681
/KMeans/KMeansCombiner.java
8bd7256e19a1a023d2a041218e6e5e838ff1763a
[ "MIT" ]
permissive
DavideTPR/Hadoop_KMeans
https://github.com/DavideTPR/Hadoop_KMeans
7bc9406735666e99012dee89d89a30858c4216fc
86fe1cabcb10b53067e2415f82fd9ea2be7e6c5c
refs/heads/master
2020-04-12T15:55:59.249000
2019-03-28T21:28:15
2019-03-28T21:28:15
162,596,942
1
0
null
false
2019-03-27T15:59:56
2018-12-20T15:22:50
2019-03-27T15:50:38
2019-03-27T15:59:56
3,678
0
0
0
Java
false
null
package KMeans; import java.io.IOException; import java.util.*; import java.util.Iterator; import java.util.ArrayList; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Reducer; import org.apache.hadoop.conf.*; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.SequenceFile; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.io.DoubleWritable; import org.apache.hadoop.fs.FSDataOutputStream; /** * Combiner class used to get partial sum of data passed from Mapper. It counts number of instances belonging to * analyzed key. * The output will be passed to Reducer process * * @author Davide Tarasconi */ public class KMeansCombiner extends Reducer<IntWritable, Element, IntWritable, Element> { public void reduce(IntWritable key, Iterable<Element> values, Context context) throws IOException, InterruptedException { int iKey = key.get(); Configuration conf = context.getConfiguration(); int size = conf.getInt("numParams", 3); double count = 0; ArrayList<DoubleWritable> value = new ArrayList<DoubleWritable>(); for(int i = 0 ; i < size; i++){ value.add(new DoubleWritable(0)); } for(Element c : values) { //Partial sum of parameters of every elements belonging to same centroid for(int i = 0; i < size; i++){ value.get(i).set(value.get(i).get() + c.getParam().get(i).get()); } //increment number of instances of that centroid count++; } //Create element and set number of instances and parameters Element valueSum = new Element(value, count); //pass value to Reducer context.write(key, valueSum); } }
UTF-8
Java
1,692
java
KMeansCombiner.java
Java
[ { "context": "t will be passed to Reducer process\n * \n * @author Davide Tarasconi\n */\n\npublic class KMeansCombiner extends Reducer<", "end": 698, "score": 0.9998841881752014, "start": 682, "tag": "NAME", "value": "Davide Tarasconi" } ]
null
[]
package KMeans; import java.io.IOException; import java.util.*; import java.util.Iterator; import java.util.ArrayList; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Reducer; import org.apache.hadoop.conf.*; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.SequenceFile; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.io.DoubleWritable; import org.apache.hadoop.fs.FSDataOutputStream; /** * Combiner class used to get partial sum of data passed from Mapper. It counts number of instances belonging to * analyzed key. * The output will be passed to Reducer process * * @author <NAME> */ public class KMeansCombiner extends Reducer<IntWritable, Element, IntWritable, Element> { public void reduce(IntWritable key, Iterable<Element> values, Context context) throws IOException, InterruptedException { int iKey = key.get(); Configuration conf = context.getConfiguration(); int size = conf.getInt("numParams", 3); double count = 0; ArrayList<DoubleWritable> value = new ArrayList<DoubleWritable>(); for(int i = 0 ; i < size; i++){ value.add(new DoubleWritable(0)); } for(Element c : values) { //Partial sum of parameters of every elements belonging to same centroid for(int i = 0; i < size; i++){ value.get(i).set(value.get(i).get() + c.getParam().get(i).get()); } //increment number of instances of that centroid count++; } //Create element and set number of instances and parameters Element valueSum = new Element(value, count); //pass value to Reducer context.write(key, valueSum); } }
1,682
0.717494
0.714539
62
26.290323
27.936787
122
false
false
0
0
0
0
0
0
1.419355
false
false
4